_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
010ac73c3b4c7c15e14921033335ec8ea8d3ed0ad3c80ae9783d7648e9d721a8
Clozure/ccl
x86-error-signal.lisp
;;; Copyright 2005 - 2009 Clozure Associates ;;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; -2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (in-package "CCL") #+x8664-target (defun xp-argument-count (xp) (ldb (byte (- 16 x8664::fixnumshift) 0) (encoded-gpr-lisp xp x8664::nargs.q))) #+x8632-target (defun xp-argument-count (xp) (encoded-gpr-lisp xp target::nargs)) #+x8664-target (defun xp-argument-list (xp) (let ((nargs (xp-argument-count xp)) (arg-x (encoded-gpr-lisp xp x8664::arg_x)) (arg-y (encoded-gpr-lisp xp x8664::arg_y)) (arg-z (encoded-gpr-lisp xp x8664::arg_z))) (cond ((eql nargs 0) nil) ((eql nargs 1) (list arg-z)) ((eql nargs 2) (list arg-y arg-z)) (t (let ((args (list arg-x arg-y arg-z))) (if (eql nargs 3) args (let ((sp (%inc-ptr (encoded-gpr-macptr xp x8664::rsp) (+ x8664::node-size x8664::xcf.size)))) (dotimes (i (- nargs 3)) (push (%get-object sp (* i x8664::node-size)) args)) args))))))) #+x8632-target (defun xp-argument-list (xp) (let ((nargs (xp-argument-count xp)) (arg-y (encoded-gpr-lisp xp x8632::arg_y)) (arg-z (encoded-gpr-lisp xp x8632::arg_z))) (cond ((eql nargs 0) nil) ((eql nargs 1) (list arg-z)) (t (let ((args (list arg-y arg-z))) (if (eql nargs 2) args (let ((sp (%inc-ptr (encoded-gpr-macptr xp x8632::ebp) (+ x8632::node-size x8632::xcf.size)))) (dotimes (i (- nargs 2)) (push (%get-object sp (* i x8632::node-size)) args)) args))))))) Making this be continuable is hard , because of the xcf on the ;;; stack and the way that the kernel saves/restores rsp and rbp ;;; before calling out. If we get around those problems, then ;;; we have to also deal with the fact that the return address ;;; is on the stack. Easiest to make the kernel deal with that, ;;; and just set %fn to the function that returns the values ;;; returned by the (newly defined) function and %arg_z to ;;; that list of values. (defun handle-udf-call (xp frame-ptr) (let* ((args (xp-argument-list xp)) (values (multiple-value-list (%kernel-restart-internal $xudfcall (list (maybe-setf-name (encoded-gpr-lisp xp target::fname)) args) frame-ptr))) (f #'(lambda (values) (apply #'values values)))) (setf (encoded-gpr-lisp xp target::arg_z) values (encoded-gpr-lisp xp target::fn) f))) #+x8664-target (defcallback %xerr-disp (:address xp :address xcf :int) (with-error-reentry-detection (let* ((frame-ptr (macptr->fixnum xcf)) (fn (%get-object xcf x8664::xcf.nominal-function)) (op0 (%get-xcf-byte xcf 0)) (op1 (%get-xcf-byte xcf 1)) (op2 (%get-xcf-byte xcf 2))) (declare (type (unsigned-byte 8) op0 op1 op2)) (let* ((skip 2)) (if (and (= op0 #xcd) (>= op1 #x70)) (cond ((< op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setq *error-reentry-count* 0) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) (%slot-unbound-trap (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) frame-ptr))) ((= op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setf (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (%kernel-restart-internal $xvunbnd (list (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr))) ((< op1 #xa0) (setq skip (%check-anchored-uuo xcf 2)) ;; #x9x, x>0 - register X is a symbol. It's unbound, but we do n't have enough info to offer USE - VALUE , STORE - VALUE , or CONTINUE restarts . (%error (make-condition 'unbound-variable :name (encoded-gpr-lisp xp (ldb (byte 4 0) op1))) () frame-ptr)) ((< op1 #xb0) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xfunbnd (list (encoded-gpr-lisp xp (ldb (byte 4 0) op1))) frame-ptr)) ((< op1 #xc0) (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal #.(car (rassoc 'type-error *kernel-simple-error-classes*)) (list (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) (logandc2 op2 arch::error-type-error)) frame-ptr)) ((= op1 #xc0) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-few-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc1) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-many-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc2) (setq skip (%check-anchored-uuo xcf 2)) (let* ((flags (xp-flags-register xp)) (nargs (xp-argument-count xp)) (carry-bit (logbitp x86::x86-carry-flag-bit flags))) (if carry-bit (%error 'too-few-arguments (list :nargs nargs :fn fn) frame-ptr) (%error 'too-many-arguments (list :nargs nargs :fn fn) frame-ptr)))) ((= op1 #xc3) ;array rank (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal $XNDIMS (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc6) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp x8664::temp0) :expected-type '(or symbol function) :format-control "~S is not of type ~S, and can't be FUNCALLed or APPLYed") nil frame-ptr)) ((= op1 #xc7) (handle-udf-call xp frame-ptr) (setq skip 0)) ((or (= op1 #xc8) (= op1 #xcb)) (setq skip (%check-anchored-uuo xcf 3)) (%error (%rsc-string $xarroob) (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc9) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xnotfun (list (encoded-gpr-lisp xp x8664::temp0)) frame-ptr)) ;; #xca = uuo-error-debug-trap ((= op1 #xcc) ;; external entry point or foreign variable (setq skip (%check-anchored-uuo xcf 3)) (let* ((eep-or-fv (encoded-gpr-lisp xp (ldb (byte 4 4) op2)))) (etypecase eep-or-fv (external-entry-point (resolve-eep eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (eep.address eep-or-fv))) (foreign-variable (resolve-foreign-variable eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (fv.addr eep-or-fv)))))) ((< op1 #xe0) (setq skip (%check-anchored-uuo xcf 3)) (if (= op2 x8664::subtag-catch-frame) (%error (make-condition 'cant-throw-error :tag (encoded-gpr-lisp xp (ldb (byte 4 0) op1))) nil frame-ptr) (let* ((typename (cond ((= op2 x8664::tag-fixnum) 'fixnum) ((= op2 x8664::tag-single-float) 'single-float) ((= op2 x8664::subtag-character) 'character) ((= op2 x8664::fulltag-cons) 'cons) ((= op2 x8664::tag-misc) 'uvector) ((= op2 x8664::fulltag-symbol) 'symbol) ((= op2 x8664::fulltag-function) 'function) (t (let* ((class (logand op2 x8664::fulltagmask)) (high4 (ash op2 (- x8664::ntagbits)))) (cond ((= class x8664::fulltag-nodeheader-0) (svref *nodeheader-0-types* high4)) ((= class x8664::fulltag-nodeheader-1) (svref *nodeheader-1-types* high4)) ((= class x8664::fulltag-immheader-0) (svref *immheader-0-types* high4)) ((= class x8664::fulltag-immheader-1) (svref *immheader-1-types* high4)) ((= class x8664::fulltag-immheader-2) (svref *immheader-2-types* high4)) (t (list 'bogus op2)))))))) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) :expected-type typename) nil frame-ptr)))) ((< op1 #xf0) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) :expected-type 'list) nil frame-ptr)) (t (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) :expected-type 'fixnum) nil frame-ptr))) (%error "Unknown trap: #x~x~%xp=~s" (list (list op0 op1 op2) xp) frame-ptr)) skip)))) ;;; lots of duplicated code here #+x8632-target (defcallback %xerr-disp (:address xp :address xcf :int) (with-error-reentry-detection (let* ((frame-ptr (macptr->fixnum xcf)) (fn (%get-object xcf x8632::xcf.nominal-function)) (op0 (%get-xcf-byte xcf 0)) (op1 (%get-xcf-byte xcf 1)) (op2 (%get-xcf-byte xcf 2))) (declare (type (unsigned-byte 8) op0 op1 op2)) (let* ((skip 2)) (if (and (= op0 #xcd) (>= op1 #x70)) (cond ((< op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setq *error-reentry-count* 0) (setf (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) (%slot-unbound-trap (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) frame-ptr))) ((= op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setf (encoded-gpr-lisp xp (ldb (byte 3 0) op2)) (%kernel-restart-internal $xvunbnd (list (encoded-gpr-lisp xp (ldb (byte 3 0) op2))) frame-ptr))) ((< op1 #xa0) (setq skip (%check-anchored-uuo xcf 2)) ;; #x9x, x>- - register X is a symbol. It's unbound, but we do n't have enough info to offer USE - VALUE , STORE - VALUE , or CONTINUE restart (%error (make-condition 'unbound-variable :name (encoded-gpr-lisp xp (ldb (byte 3 0) op1))) () frame-ptr)) ((< op1 #xb0) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xfunbnd (list (encoded-gpr-lisp xp (ldb (byte 3 0) op1))) frame-ptr)) ((< op1 #xc0) (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal #.(car (rassoc 'type-error *kernel-simple-error-classes*)) (list (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) (logandc2 op2 arch::error-type-error)) frame-ptr)) ((= op1 #xc0) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-few-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc1) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-many-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc2) (setq skip (%check-anchored-uuo xcf 2)) (let* ((flags (xp-flags-register xp)) (nargs (xp-argument-count xp)) (carry-bit (logbitp x86::x86-carry-flag-bit flags))) (if carry-bit (%error 'too-few-arguments (list :nargs nargs :fn fn) frame-ptr) (%error 'too-many-arguments (list :nargs nargs :fn fn) frame-ptr)))) ((= op1 #xc3) ;array rank (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal $XNDIMS (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc6) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp x8632::temp0) :expected-type '(or symbol function) :format-control "~S is not of type ~S, and can't be FUNCALLed or APPLYed") nil frame-ptr)) ((= op1 #xc7) (handle-udf-call xp frame-ptr) (setq skip 0)) ((or (= op1 #xc8) (= op1 #xcb)) (setq skip (%check-anchored-uuo xcf 3)) (%error (%rsc-string $xarroob) (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc9) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xnotfun (list (encoded-gpr-lisp xp x8632::temp0)) frame-ptr)) ;; #xca = uuo-error-debug-trap ((= op1 #xcc) ;; external entry point or foreign variable (setq skip (%check-anchored-uuo xcf 3)) (let* ((eep-or-fv (encoded-gpr-lisp xp (ldb (byte 4 4) op2)))) (etypecase eep-or-fv (external-entry-point (resolve-eep eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (eep.address eep-or-fv))) (foreign-variable (resolve-foreign-variable eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (fv.addr eep-or-fv)))))) ((< op1 #xe0) (setq skip (%check-anchored-uuo xcf 3)) (if (= op2 x8632::subtag-catch-frame) (%error (make-condition 'cant-throw-error :tag (encoded-gpr-lisp xp (ldb (byte 3 0) op1))) nil frame-ptr) (let* ((typename (cond ((= op2 x8632::tag-fixnum) 'fixnum) ((= op2 x8632::subtag-character) 'character) ((= op2 x8632::fulltag-cons) 'cons) ((= op2 x8632::tag-misc) 'uvector) (t (let* ((class (logand op2 x8632::fulltagmask)) (high5 (ash op2 (- x8632::ntagbits)))) (cond ((= class x8632::fulltag-nodeheader) (svref *nodeheader-types* high5)) ((= class x8632::fulltag-immheader) (svref *immheader-types* high5)) (t (list 'bogus op2)))))))) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) :expected-type typename) nil frame-ptr)))) ((< op1 #xf0) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) :expected-type 'list) nil frame-ptr)) (t (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) :expected-type 'fixnum) nil frame-ptr))) (%error "Unknown trap: #x~x~%xp=~s" (list (list op0 op1 op2) xp) frame-ptr)) skip))))
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/level-1/x86-error-signal.lisp
lisp
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. stack and the way that the kernel saves/restores rsp and rbp before calling out. If we get around those problems, then we have to also deal with the fact that the return address is on the stack. Easiest to make the kernel deal with that, and just set %fn to the function that returns the values returned by the (newly defined) function and %arg_z to that list of values. #x9x, x>0 - register X is a symbol. It's unbound, array rank #xca = uuo-error-debug-trap external entry point or foreign variable lots of duplicated code here #x9x, x>- - register X is a symbol. It's unbound, array rank #xca = uuo-error-debug-trap external entry point or foreign variable
Copyright 2005 - 2009 Clozure Associates distributed under the License is distributed on an " AS IS " BASIS , (in-package "CCL") #+x8664-target (defun xp-argument-count (xp) (ldb (byte (- 16 x8664::fixnumshift) 0) (encoded-gpr-lisp xp x8664::nargs.q))) #+x8632-target (defun xp-argument-count (xp) (encoded-gpr-lisp xp target::nargs)) #+x8664-target (defun xp-argument-list (xp) (let ((nargs (xp-argument-count xp)) (arg-x (encoded-gpr-lisp xp x8664::arg_x)) (arg-y (encoded-gpr-lisp xp x8664::arg_y)) (arg-z (encoded-gpr-lisp xp x8664::arg_z))) (cond ((eql nargs 0) nil) ((eql nargs 1) (list arg-z)) ((eql nargs 2) (list arg-y arg-z)) (t (let ((args (list arg-x arg-y arg-z))) (if (eql nargs 3) args (let ((sp (%inc-ptr (encoded-gpr-macptr xp x8664::rsp) (+ x8664::node-size x8664::xcf.size)))) (dotimes (i (- nargs 3)) (push (%get-object sp (* i x8664::node-size)) args)) args))))))) #+x8632-target (defun xp-argument-list (xp) (let ((nargs (xp-argument-count xp)) (arg-y (encoded-gpr-lisp xp x8632::arg_y)) (arg-z (encoded-gpr-lisp xp x8632::arg_z))) (cond ((eql nargs 0) nil) ((eql nargs 1) (list arg-z)) (t (let ((args (list arg-y arg-z))) (if (eql nargs 2) args (let ((sp (%inc-ptr (encoded-gpr-macptr xp x8632::ebp) (+ x8632::node-size x8632::xcf.size)))) (dotimes (i (- nargs 2)) (push (%get-object sp (* i x8632::node-size)) args)) args))))))) Making this be continuable is hard , because of the xcf on the (defun handle-udf-call (xp frame-ptr) (let* ((args (xp-argument-list xp)) (values (multiple-value-list (%kernel-restart-internal $xudfcall (list (maybe-setf-name (encoded-gpr-lisp xp target::fname)) args) frame-ptr))) (f #'(lambda (values) (apply #'values values)))) (setf (encoded-gpr-lisp xp target::arg_z) values (encoded-gpr-lisp xp target::fn) f))) #+x8664-target (defcallback %xerr-disp (:address xp :address xcf :int) (with-error-reentry-detection (let* ((frame-ptr (macptr->fixnum xcf)) (fn (%get-object xcf x8664::xcf.nominal-function)) (op0 (%get-xcf-byte xcf 0)) (op1 (%get-xcf-byte xcf 1)) (op2 (%get-xcf-byte xcf 2))) (declare (type (unsigned-byte 8) op0 op1 op2)) (let* ((skip 2)) (if (and (= op0 #xcd) (>= op1 #x70)) (cond ((< op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setq *error-reentry-count* 0) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) (%slot-unbound-trap (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) frame-ptr))) ((= op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setf (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (%kernel-restart-internal $xvunbnd (list (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr))) ((< op1 #xa0) (setq skip (%check-anchored-uuo xcf 2)) but we do n't have enough info to offer USE - VALUE , STORE - VALUE , or CONTINUE restarts . (%error (make-condition 'unbound-variable :name (encoded-gpr-lisp xp (ldb (byte 4 0) op1))) () frame-ptr)) ((< op1 #xb0) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xfunbnd (list (encoded-gpr-lisp xp (ldb (byte 4 0) op1))) frame-ptr)) ((< op1 #xc0) (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal #.(car (rassoc 'type-error *kernel-simple-error-classes*)) (list (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) (logandc2 op2 arch::error-type-error)) frame-ptr)) ((= op1 #xc0) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-few-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc1) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-many-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc2) (setq skip (%check-anchored-uuo xcf 2)) (let* ((flags (xp-flags-register xp)) (nargs (xp-argument-count xp)) (carry-bit (logbitp x86::x86-carry-flag-bit flags))) (if carry-bit (%error 'too-few-arguments (list :nargs nargs :fn fn) frame-ptr) (%error 'too-many-arguments (list :nargs nargs :fn fn) frame-ptr)))) (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal $XNDIMS (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc6) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp x8664::temp0) :expected-type '(or symbol function) :format-control "~S is not of type ~S, and can't be FUNCALLed or APPLYed") nil frame-ptr)) ((= op1 #xc7) (handle-udf-call xp frame-ptr) (setq skip 0)) ((or (= op1 #xc8) (= op1 #xcb)) (setq skip (%check-anchored-uuo xcf 3)) (%error (%rsc-string $xarroob) (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc9) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xnotfun (list (encoded-gpr-lisp xp x8664::temp0)) frame-ptr)) ((= op1 #xcc) (setq skip (%check-anchored-uuo xcf 3)) (let* ((eep-or-fv (encoded-gpr-lisp xp (ldb (byte 4 4) op2)))) (etypecase eep-or-fv (external-entry-point (resolve-eep eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (eep.address eep-or-fv))) (foreign-variable (resolve-foreign-variable eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (fv.addr eep-or-fv)))))) ((< op1 #xe0) (setq skip (%check-anchored-uuo xcf 3)) (if (= op2 x8664::subtag-catch-frame) (%error (make-condition 'cant-throw-error :tag (encoded-gpr-lisp xp (ldb (byte 4 0) op1))) nil frame-ptr) (let* ((typename (cond ((= op2 x8664::tag-fixnum) 'fixnum) ((= op2 x8664::tag-single-float) 'single-float) ((= op2 x8664::subtag-character) 'character) ((= op2 x8664::fulltag-cons) 'cons) ((= op2 x8664::tag-misc) 'uvector) ((= op2 x8664::fulltag-symbol) 'symbol) ((= op2 x8664::fulltag-function) 'function) (t (let* ((class (logand op2 x8664::fulltagmask)) (high4 (ash op2 (- x8664::ntagbits)))) (cond ((= class x8664::fulltag-nodeheader-0) (svref *nodeheader-0-types* high4)) ((= class x8664::fulltag-nodeheader-1) (svref *nodeheader-1-types* high4)) ((= class x8664::fulltag-immheader-0) (svref *immheader-0-types* high4)) ((= class x8664::fulltag-immheader-1) (svref *immheader-1-types* high4)) ((= class x8664::fulltag-immheader-2) (svref *immheader-2-types* high4)) (t (list 'bogus op2)))))))) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) :expected-type typename) nil frame-ptr)))) ((< op1 #xf0) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) :expected-type 'list) nil frame-ptr)) (t (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 4 0) op1)) :expected-type 'fixnum) nil frame-ptr))) (%error "Unknown trap: #x~x~%xp=~s" (list (list op0 op1 op2) xp) frame-ptr)) skip)))) #+x8632-target (defcallback %xerr-disp (:address xp :address xcf :int) (with-error-reentry-detection (let* ((frame-ptr (macptr->fixnum xcf)) (fn (%get-object xcf x8632::xcf.nominal-function)) (op0 (%get-xcf-byte xcf 0)) (op1 (%get-xcf-byte xcf 1)) (op2 (%get-xcf-byte xcf 2))) (declare (type (unsigned-byte 8) op0 op1 op2)) (let* ((skip 2)) (if (and (= op0 #xcd) (>= op1 #x70)) (cond ((< op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setq *error-reentry-count* 0) (setf (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) (%slot-unbound-trap (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) frame-ptr))) ((= op1 #x90) (setq skip (%check-anchored-uuo xcf 3)) (setf (encoded-gpr-lisp xp (ldb (byte 3 0) op2)) (%kernel-restart-internal $xvunbnd (list (encoded-gpr-lisp xp (ldb (byte 3 0) op2))) frame-ptr))) ((< op1 #xa0) (setq skip (%check-anchored-uuo xcf 2)) but we do n't have enough info to offer USE - VALUE , STORE - VALUE , or CONTINUE restart (%error (make-condition 'unbound-variable :name (encoded-gpr-lisp xp (ldb (byte 3 0) op1))) () frame-ptr)) ((< op1 #xb0) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xfunbnd (list (encoded-gpr-lisp xp (ldb (byte 3 0) op1))) frame-ptr)) ((< op1 #xc0) (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal #.(car (rassoc 'type-error *kernel-simple-error-classes*)) (list (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) (logandc2 op2 arch::error-type-error)) frame-ptr)) ((= op1 #xc0) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-few-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc1) (setq skip (%check-anchored-uuo xcf 2)) (%error 'too-many-arguments (list :nargs (xp-argument-count xp) :fn fn) frame-ptr)) ((= op1 #xc2) (setq skip (%check-anchored-uuo xcf 2)) (let* ((flags (xp-flags-register xp)) (nargs (xp-argument-count xp)) (carry-bit (logbitp x86::x86-carry-flag-bit flags))) (if carry-bit (%error 'too-few-arguments (list :nargs nargs :fn fn) frame-ptr) (%error 'too-many-arguments (list :nargs nargs :fn fn) frame-ptr)))) (setq skip (%check-anchored-uuo xcf 3)) (%err-disp-internal $XNDIMS (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc6) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp x8632::temp0) :expected-type '(or symbol function) :format-control "~S is not of type ~S, and can't be FUNCALLed or APPLYed") nil frame-ptr)) ((= op1 #xc7) (handle-udf-call xp frame-ptr) (setq skip 0)) ((or (= op1 #xc8) (= op1 #xcb)) (setq skip (%check-anchored-uuo xcf 3)) (%error (%rsc-string $xarroob) (list (encoded-gpr-lisp xp (ldb (byte 4 4) op2)) (encoded-gpr-lisp xp (ldb (byte 4 0) op2))) frame-ptr)) ((= op1 #xc9) (setq skip (%check-anchored-uuo xcf 2)) (%err-disp-internal $xnotfun (list (encoded-gpr-lisp xp x8632::temp0)) frame-ptr)) ((= op1 #xcc) (setq skip (%check-anchored-uuo xcf 3)) (let* ((eep-or-fv (encoded-gpr-lisp xp (ldb (byte 4 4) op2)))) (etypecase eep-or-fv (external-entry-point (resolve-eep eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (eep.address eep-or-fv))) (foreign-variable (resolve-foreign-variable eep-or-fv) (setf (encoded-gpr-lisp xp (ldb (byte 4 0) op2)) (fv.addr eep-or-fv)))))) ((< op1 #xe0) (setq skip (%check-anchored-uuo xcf 3)) (if (= op2 x8632::subtag-catch-frame) (%error (make-condition 'cant-throw-error :tag (encoded-gpr-lisp xp (ldb (byte 3 0) op1))) nil frame-ptr) (let* ((typename (cond ((= op2 x8632::tag-fixnum) 'fixnum) ((= op2 x8632::subtag-character) 'character) ((= op2 x8632::fulltag-cons) 'cons) ((= op2 x8632::tag-misc) 'uvector) (t (let* ((class (logand op2 x8632::fulltagmask)) (high5 (ash op2 (- x8632::ntagbits)))) (cond ((= class x8632::fulltag-nodeheader) (svref *nodeheader-types* high5)) ((= class x8632::fulltag-immheader) (svref *immheader-types* high5)) (t (list 'bogus op2)))))))) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) :expected-type typename) nil frame-ptr)))) ((< op1 #xf0) (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) :expected-type 'list) nil frame-ptr)) (t (setq skip (%check-anchored-uuo xcf 2)) (%error (make-condition 'type-error :datum (encoded-gpr-lisp xp (ldb (byte 3 0) op1)) :expected-type 'fixnum) nil frame-ptr))) (%error "Unknown trap: #x~x~%xp=~s" (list (list op0 op1 op2) xp) frame-ptr)) skip))))
851b6cd87e11298dd12685e34ec3bbcf8cfb37f2667c6c902e81f07bab5dd249
hbr/albatross
list.mli
* A thin wrapper around [ . List ] which avoids throwing exceptions and with some additional monadic functions . with some additional monadic functions. *) open Module_types * { 1 List Monad } (** A list of values of type ['a]. *) type 'a t = 'a list (** [return a] makes a singleton list with the element [a]. *) val return: 'a -> 'a t (** [l >>= f] applies the function [f] to all elements of the list [l] and concatenates all lists. *) val (>>=): 'a t -> ('a -> 'b t) -> 'b t * [ f > = > g ] composes the two monadic functions [ f ] and [ g ] . val (>=>): ('a -> 'b t) -> ('b -> 'c t) -> ('a -> 'c t) (** [flst <*> lst] is equivalent to [flst >>= fun f -> map f lst] i.e. it maps all functions contained in [flst] over the list [lst] and then concatenates the results. *) val (<*>): ('a -> 'b) t -> 'a t -> 'b t * [ join ] is the same as { ! : concat } . val join: 'a list list -> 'a list (** {1 Modified list functions}*) (** [find p l] finds an element [e] in the list [l] which satisfies [p e]. *) val find: ('a -> bool) ->'a t -> 'a option val split_head_tail: 'a t -> 'a * 'a t (** Split the list in its head and tail parts. Requires that the list is not empty. *) val head_strict: 'a t -> 'a (** Get the head of the list. Requires that the list is not empty. *) val tail_strict: 'a t -> 'a t (** Get the tail of the list. Requires that the list is not empty. *) val nth_strict: int -> 'a t -> 'a (** [ith_strict n list] returns the [n]th element of the list. Precondition: [list] has at least [n + 1] elements. *) val nth: int -> 'a t -> 'a option (** [ith_strict n list] returns the [n]th element of the list if the list is long enough. Otherwise [None] is returned. *) * { 1 List functions from } (** [append a b] prepends the lists [a] in front of the list [b]. Synonym [a @ b]. *) val append: 'a list -> 'a list -> 'a list (** [concat ll] concatenates all lists contained in the list of lists [ll]. *) val concat: 'a list list -> 'a list (** Transform a list of pairs into a pair of lists. *) val split: ('a * 'b) list -> 'a list * 'b list (** [rev a] reverses the list [a]. *) val rev: 'a list -> 'a list (** [rev_append a b] prepends the lists [rev a] in front of the list [b]. *) val rev_append: 'a list -> 'a list -> 'a list val length: 'a t -> int val filter: ('a -> bool) -> 'a t -> 'a t val fold_left: ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a val fold_right: ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b val iter: ('a -> unit) -> 'a list -> unit val map : ('a -> 'b) -> 'a list -> 'b list val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list val rev_map : ('a -> 'b) -> 'a list -> 'b list val for_all : ('a -> bool) -> 'a list -> bool val exists : ('a -> bool) -> 'a list -> bool * { 1 Additional list functions } (** [map_and_filter f list] maps the list with [f] and removes the element for which [f e = None].*) val map_and_filter: ('a -> 'b option) -> 'a list -> 'b list val split_at: ('a -> bool) -> 'a t -> 'a t * 'a t * [ split_at p lst ] scans the list until it finds the first element satisfying [ p ] and returns the prefix and the remainder starting at the encountered element . satisfying [p] and returns the prefix and the remainder starting at the encountered element. *) val transpose: 'a list list -> 'a list list * [ transpose list_of_rows ] returns the list of columns . Preconditions : - The list of rows must not be empty . - All rows in the list of rows must not be empty and have the same length . Example : { [ transpose [   [ 1 ; 2 ; 3 ] ; [ 4 ; 5 ; 6 ]   ] = [ [ 1 ; 4 ] ; [ 2 ; 5 ] ; [ 3 ; 6 ] ] ] } [transpose list_of_rows] returns the list of columns. Preconditions: - The list of rows must not be empty. - All rows in the list of rows must not be empty and have the same length. Example: {[ transpose [ [1; 2; 3]; [4; 5; 6] ] = [ [1; 4]; [2; 5]; [3; 6] ] ]} *) * { 1 Monadic list functions } (** Monadic list functions *) module Monadic (M: MONAD): sig (** [fold_left f lst start] leftfolds the function [f] over the list [lst] starting with the value [start]. Continuation of the fold is determined by the bind operator [>>=] of the monad [M]. E.g. if the monad [M] is [Option] the folding stops as soon as [f e acc] returns the value [None]. {[ fold_left f [a b c ...] s = M.(f a s >>= fun acc -> f b acc >>= fun acc -> f c acc >>= fun acc -> ...) ]} *) val fold_left: ('a -> 'b -> 'b M.t) -> 'a t -> 'b -> 'b M.t (** The same as [fold_left] just right folding. {[ fold_right f [... x y z] s = fold_left f (rev [... x y z]) s = M.(f z s >>= fun acc -> f y acc >>= fun acc -> f x acc >>= fun acc -> ...) ]}*) val fold_right: ('a -> 'b -> 'b M.t) -> 'a t -> 'b -> 'b M.t * The same as [ fold_left ] except that the folding function receives the position of the first argument in the list as an additional argument . position of the first argument in the list as an additional argument. *) val foldi_left: (int -> 'a -> 'b -> 'b M.t) -> 'a t -> 'b -> 'b M.t end
null
https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/fmlib/basic/list.mli
ocaml
* A list of values of type ['a]. * [return a] makes a singleton list with the element [a]. * [l >>= f] applies the function [f] to all elements of the list [l] and concatenates all lists. * [flst <*> lst] is equivalent to [flst >>= fun f -> map f lst] i.e. it maps all functions contained in [flst] over the list [lst] and then concatenates the results. * {1 Modified list functions} * [find p l] finds an element [e] in the list [l] which satisfies [p e]. * Split the list in its head and tail parts. Requires that the list is not empty. * Get the head of the list. Requires that the list is not empty. * Get the tail of the list. Requires that the list is not empty. * [ith_strict n list] returns the [n]th element of the list. Precondition: [list] has at least [n + 1] elements. * [ith_strict n list] returns the [n]th element of the list if the list is long enough. Otherwise [None] is returned. * [append a b] prepends the lists [a] in front of the list [b]. Synonym [a @ b]. * [concat ll] concatenates all lists contained in the list of lists [ll]. * Transform a list of pairs into a pair of lists. * [rev a] reverses the list [a]. * [rev_append a b] prepends the lists [rev a] in front of the list [b]. * [map_and_filter f list] maps the list with [f] and removes the element for which [f e = None]. * Monadic list functions * [fold_left f lst start] leftfolds the function [f] over the list [lst] starting with the value [start]. Continuation of the fold is determined by the bind operator [>>=] of the monad [M]. E.g. if the monad [M] is [Option] the folding stops as soon as [f e acc] returns the value [None]. {[ fold_left f [a b c ...] s = M.(f a s >>= fun acc -> f b acc >>= fun acc -> f c acc >>= fun acc -> ...) ]} * The same as [fold_left] just right folding. {[ fold_right f [... x y z] s = fold_left f (rev [... x y z]) s = M.(f z s >>= fun acc -> f y acc >>= fun acc -> f x acc >>= fun acc -> ...) ]}
* A thin wrapper around [ . List ] which avoids throwing exceptions and with some additional monadic functions . with some additional monadic functions. *) open Module_types * { 1 List Monad } type 'a t = 'a list val return: 'a -> 'a t val (>>=): 'a t -> ('a -> 'b t) -> 'b t * [ f > = > g ] composes the two monadic functions [ f ] and [ g ] . val (>=>): ('a -> 'b t) -> ('b -> 'c t) -> ('a -> 'c t) val (<*>): ('a -> 'b) t -> 'a t -> 'b t * [ join ] is the same as { ! : concat } . val join: 'a list list -> 'a list val find: ('a -> bool) ->'a t -> 'a option val split_head_tail: 'a t -> 'a * 'a t val head_strict: 'a t -> 'a val tail_strict: 'a t -> 'a t val nth_strict: int -> 'a t -> 'a val nth: int -> 'a t -> 'a option * { 1 List functions from } val append: 'a list -> 'a list -> 'a list val concat: 'a list list -> 'a list val split: ('a * 'b) list -> 'a list * 'b list val rev: 'a list -> 'a list val rev_append: 'a list -> 'a list -> 'a list val length: 'a t -> int val filter: ('a -> bool) -> 'a t -> 'a t val fold_left: ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a val fold_right: ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b val iter: ('a -> unit) -> 'a list -> unit val map : ('a -> 'b) -> 'a list -> 'b list val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list val rev_map : ('a -> 'b) -> 'a list -> 'b list val for_all : ('a -> bool) -> 'a list -> bool val exists : ('a -> bool) -> 'a list -> bool * { 1 Additional list functions } val map_and_filter: ('a -> 'b option) -> 'a list -> 'b list val split_at: ('a -> bool) -> 'a t -> 'a t * 'a t * [ split_at p lst ] scans the list until it finds the first element satisfying [ p ] and returns the prefix and the remainder starting at the encountered element . satisfying [p] and returns the prefix and the remainder starting at the encountered element. *) val transpose: 'a list list -> 'a list list * [ transpose list_of_rows ] returns the list of columns . Preconditions : - The list of rows must not be empty . - All rows in the list of rows must not be empty and have the same length . Example : { [ transpose [   [ 1 ; 2 ; 3 ] ; [ 4 ; 5 ; 6 ]   ] = [ [ 1 ; 4 ] ; [ 2 ; 5 ] ; [ 3 ; 6 ] ] ] } [transpose list_of_rows] returns the list of columns. Preconditions: - The list of rows must not be empty. - All rows in the list of rows must not be empty and have the same length. Example: {[ transpose [ [1; 2; 3]; [4; 5; 6] ] = [ [1; 4]; [2; 5]; [3; 6] ] ]} *) * { 1 Monadic list functions } module Monadic (M: MONAD): sig val fold_left: ('a -> 'b -> 'b M.t) -> 'a t -> 'b -> 'b M.t val fold_right: ('a -> 'b -> 'b M.t) -> 'a t -> 'b -> 'b M.t * The same as [ fold_left ] except that the folding function receives the position of the first argument in the list as an additional argument . position of the first argument in the list as an additional argument. *) val foldi_left: (int -> 'a -> 'b -> 'b M.t) -> 'a t -> 'b -> 'b M.t end
165b16b5a912b40f40c8781330632d8077c83bb112e4878fb31894bd057ffb65
facebook/flow
lintSettings.ml
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Lints open Severity let ( >>= ) = Base.Result.( >>= ) type 'a t = { (* The default value associated with a lint if the lint kind isn't found in the map *) default_value: 'a; Values for that have been explicitly set The Loc.t is for settings defined in comments , and is used to find unused lint * suppressions . The Loc.t is set to None for settings coming from the flowconfig or . * suppressions. The Loc.t is set to None for settings coming from the flowconfig or --lints.*) explicit_values: ('a * Loc.t option) LintMap.t; } type warning = int * string type error = int * string let default_explicit_values = LintMap.singleton Lints.UntypedTypeImport (Severity.Err, None) let ignored_by_all = [Lints.ImplicitInexactObject; Lints.AmbiguousObjectType; Lints.UninitializedInstanceProperty] let config_default kind = LintMap.find_opt kind default_explicit_values |> Base.Option.value ~default:(Severity.Off, None) let of_default default_value = let explicit_values = LintMap.of_function ignored_by_all config_default in { default_value; explicit_values } let set_value key value settings = let new_map = LintMap.add key value settings.explicit_values in { settings with explicit_values = new_map } let set_all entries settings = List.fold_left (fun settings (key, value) -> set_value key value settings) settings entries let get_default settings = settings.default_value let get_value lint_kind settings = LintMap.find_opt lint_kind settings.explicit_values |> Base.Option.value_map ~f:fst ~default:settings.default_value let get_loc lint_kind settings = LintMap.find_opt lint_kind settings.explicit_values |> Base.Option.value_map ~f:snd ~default:None let is_explicit lint_kind settings = LintMap.mem lint_kind settings.explicit_values (* Iterate over all lint kinds with an explicit value *) let iter f settings = LintMap.iter f settings.explicit_values Fold over all lint kinds with an explicit value let fold f settings acc = LintMap.fold f settings.explicit_values acc (* Map over all lint kinds with an explicit value *) let map f settings = let new_explicit = LintMap.map f settings.explicit_values in { settings with explicit_values = new_explicit } (* SEVERITY-SPECIFIC FUNCTIONS *) let empty_severities = { default_value = Off; explicit_values = LintMap.empty } let default_severities = { empty_severities with explicit_values = default_explicit_values } let is_enabled lint_kind settings = match get_value lint_kind settings with | Err | Warn -> true | Off -> false type parse_result = | AllSetting of severity t | EntryList of lint_kind list * (severity * Loc.t option) Takes a base LintSettings and a list of labeled lines and returns the corresponding * severity LintSettings.t from applying the new lines on top of the base settings if * successful . Otherwise , returns an error message along with the label of the * line it failed on . * severity LintSettings.t from applying the new lines on top of the base settings if * successful. Otherwise, returns an error message along with the label of the * line it failed on. *) let of_lines base_settings = let parse_value label value = match severity_of_string value with | Some severity -> Ok severity | None -> Error (label, "Invalid setting encountered. Valid settings are error, warn, and off.") in let eq_regex = Str.regexp "=" in let all_regex = Str.regexp "all" in let parse_line (loc, (label, line)) = match Str.split_delim eq_regex line with | [left; right] -> let left = left |> String.trim in let right = right |> String.trim in parse_value label right >>= fun value -> begin match left with | "all" -> Ok (AllSetting (of_default value)) | _ -> begin match kinds_of_string left with | Some kinds -> Ok (EntryList (kinds, (value, Some loc))) | None -> Error (label, Printf.sprintf "Invalid lint rule \"%s\" encountered." left) end end | _ -> Error (label, "Malformed lint rule. Properly formed rules contain a single '=' character.") in let add_value keys value settings = let (new_settings, all_redundant) = List.fold_left (fun (settings, all_redundant) key -> let v = get_value key settings in let all_redundant = all_redundant && v = fst value && v <> fst (config_default key) in let settings = set_value key value settings in (settings, all_redundant)) (settings, true) keys in if all_redundant then Error "Redundant argument. This argument doesn't change any lint settings." else Ok new_settings in let rec loop (acc : Severity.severity t) (warnings : warning list) = function | [] -> Ok (acc, Base.List.rev warnings) | line :: lines -> (match parse_line line with | Ok (EntryList (keys, value)) -> (match add_value keys value acc with | Ok acc -> loop acc warnings lines | Error msg -> let warning = (line |> snd |> fst, msg) in loop acc (warning :: warnings) lines) | Ok (AllSetting value) -> if acc == base_settings then loop value warnings lines else Error ( line |> snd |> fst, "\"all\" is only allowed as the first setting. Settings are order-sensitive." ) | Error line_err -> loop acc (line_err :: warnings) lines) in let loc_of_line line = Loc.( let start = { line; column = 0 } in let _end = { line = line + 1; column = 0 } in { source = None; start; _end } ) in fun lint_lines -> let locate_fun ((label, _) as item) = (loc_of_line label, item) in (* Artificially locate the lines to detect unused lines *) let located_lines = Base.List.map ~f:locate_fun lint_lines in loop base_settings [] located_lines >>= fun (settings, warnings) -> let used_locs = fold (fun _kind (_enabled, loc) acc -> Base.Option.value_map loc ~f:(fun loc -> Loc_collections.LocSet.add loc acc) ~default:acc) settings Loc_collections.LocSet.empty in let used_locs = Base.List.fold ~f:(fun acc (line, _warning) -> Loc_collections.LocSet.add (loc_of_line line) acc) ~init:used_locs warnings in let first_unused = List.fold_left (fun acc (art_loc, (label, line)) -> match acc with | Some _ -> acc | None -> if Loc_collections.LocSet.mem art_loc used_locs || Str.string_match all_regex (String.trim line) 0 then None else Some label) None located_lines in let warnings = match first_unused with | Some label -> let warning = ( label, "Redundant argument. " ^ "The values set by this argument are completely overwritten." ) in warning :: warnings | None -> warnings in (* Remove the artificial locations before returning the result *) let settings = map (fun (enabled, _loc) -> (enabled, None)) settings in Ok (settings, warnings) let to_string settings = let acc = Buffer.create 20 in Buffer.add_string acc (Printf.sprintf "all=%s" (settings |> get_default |> string_of_severity)); iter (fun kind (severity, _) -> Buffer.add_string acc (Printf.sprintf ", %s=%s" (string_of_kind kind) (string_of_severity severity))) settings; Buffer.contents acc type lint_parse_error = | Invalid_setting | Malformed_argument | Naked_comment | Nonexistent_rule | Overwritten_argument | Redundant_argument
null
https://raw.githubusercontent.com/facebook/flow/51c84b797c57d0807a5b6dbbb4a10733913e9ec3/src/common/lints/lintSettings.ml
ocaml
The default value associated with a lint if the lint kind isn't found in the map Iterate over all lint kinds with an explicit value Map over all lint kinds with an explicit value SEVERITY-SPECIFIC FUNCTIONS Artificially locate the lines to detect unused lines Remove the artificial locations before returning the result
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Lints open Severity let ( >>= ) = Base.Result.( >>= ) type 'a t = { default_value: 'a; Values for that have been explicitly set The Loc.t is for settings defined in comments , and is used to find unused lint * suppressions . The Loc.t is set to None for settings coming from the flowconfig or . * suppressions. The Loc.t is set to None for settings coming from the flowconfig or --lints.*) explicit_values: ('a * Loc.t option) LintMap.t; } type warning = int * string type error = int * string let default_explicit_values = LintMap.singleton Lints.UntypedTypeImport (Severity.Err, None) let ignored_by_all = [Lints.ImplicitInexactObject; Lints.AmbiguousObjectType; Lints.UninitializedInstanceProperty] let config_default kind = LintMap.find_opt kind default_explicit_values |> Base.Option.value ~default:(Severity.Off, None) let of_default default_value = let explicit_values = LintMap.of_function ignored_by_all config_default in { default_value; explicit_values } let set_value key value settings = let new_map = LintMap.add key value settings.explicit_values in { settings with explicit_values = new_map } let set_all entries settings = List.fold_left (fun settings (key, value) -> set_value key value settings) settings entries let get_default settings = settings.default_value let get_value lint_kind settings = LintMap.find_opt lint_kind settings.explicit_values |> Base.Option.value_map ~f:fst ~default:settings.default_value let get_loc lint_kind settings = LintMap.find_opt lint_kind settings.explicit_values |> Base.Option.value_map ~f:snd ~default:None let is_explicit lint_kind settings = LintMap.mem lint_kind settings.explicit_values let iter f settings = LintMap.iter f settings.explicit_values Fold over all lint kinds with an explicit value let fold f settings acc = LintMap.fold f settings.explicit_values acc let map f settings = let new_explicit = LintMap.map f settings.explicit_values in { settings with explicit_values = new_explicit } let empty_severities = { default_value = Off; explicit_values = LintMap.empty } let default_severities = { empty_severities with explicit_values = default_explicit_values } let is_enabled lint_kind settings = match get_value lint_kind settings with | Err | Warn -> true | Off -> false type parse_result = | AllSetting of severity t | EntryList of lint_kind list * (severity * Loc.t option) Takes a base LintSettings and a list of labeled lines and returns the corresponding * severity LintSettings.t from applying the new lines on top of the base settings if * successful . Otherwise , returns an error message along with the label of the * line it failed on . * severity LintSettings.t from applying the new lines on top of the base settings if * successful. Otherwise, returns an error message along with the label of the * line it failed on. *) let of_lines base_settings = let parse_value label value = match severity_of_string value with | Some severity -> Ok severity | None -> Error (label, "Invalid setting encountered. Valid settings are error, warn, and off.") in let eq_regex = Str.regexp "=" in let all_regex = Str.regexp "all" in let parse_line (loc, (label, line)) = match Str.split_delim eq_regex line with | [left; right] -> let left = left |> String.trim in let right = right |> String.trim in parse_value label right >>= fun value -> begin match left with | "all" -> Ok (AllSetting (of_default value)) | _ -> begin match kinds_of_string left with | Some kinds -> Ok (EntryList (kinds, (value, Some loc))) | None -> Error (label, Printf.sprintf "Invalid lint rule \"%s\" encountered." left) end end | _ -> Error (label, "Malformed lint rule. Properly formed rules contain a single '=' character.") in let add_value keys value settings = let (new_settings, all_redundant) = List.fold_left (fun (settings, all_redundant) key -> let v = get_value key settings in let all_redundant = all_redundant && v = fst value && v <> fst (config_default key) in let settings = set_value key value settings in (settings, all_redundant)) (settings, true) keys in if all_redundant then Error "Redundant argument. This argument doesn't change any lint settings." else Ok new_settings in let rec loop (acc : Severity.severity t) (warnings : warning list) = function | [] -> Ok (acc, Base.List.rev warnings) | line :: lines -> (match parse_line line with | Ok (EntryList (keys, value)) -> (match add_value keys value acc with | Ok acc -> loop acc warnings lines | Error msg -> let warning = (line |> snd |> fst, msg) in loop acc (warning :: warnings) lines) | Ok (AllSetting value) -> if acc == base_settings then loop value warnings lines else Error ( line |> snd |> fst, "\"all\" is only allowed as the first setting. Settings are order-sensitive." ) | Error line_err -> loop acc (line_err :: warnings) lines) in let loc_of_line line = Loc.( let start = { line; column = 0 } in let _end = { line = line + 1; column = 0 } in { source = None; start; _end } ) in fun lint_lines -> let locate_fun ((label, _) as item) = (loc_of_line label, item) in let located_lines = Base.List.map ~f:locate_fun lint_lines in loop base_settings [] located_lines >>= fun (settings, warnings) -> let used_locs = fold (fun _kind (_enabled, loc) acc -> Base.Option.value_map loc ~f:(fun loc -> Loc_collections.LocSet.add loc acc) ~default:acc) settings Loc_collections.LocSet.empty in let used_locs = Base.List.fold ~f:(fun acc (line, _warning) -> Loc_collections.LocSet.add (loc_of_line line) acc) ~init:used_locs warnings in let first_unused = List.fold_left (fun acc (art_loc, (label, line)) -> match acc with | Some _ -> acc | None -> if Loc_collections.LocSet.mem art_loc used_locs || Str.string_match all_regex (String.trim line) 0 then None else Some label) None located_lines in let warnings = match first_unused with | Some label -> let warning = ( label, "Redundant argument. " ^ "The values set by this argument are completely overwritten." ) in warning :: warnings | None -> warnings in let settings = map (fun (enabled, _loc) -> (enabled, None)) settings in Ok (settings, warnings) let to_string settings = let acc = Buffer.create 20 in Buffer.add_string acc (Printf.sprintf "all=%s" (settings |> get_default |> string_of_severity)); iter (fun kind (severity, _) -> Buffer.add_string acc (Printf.sprintf ", %s=%s" (string_of_kind kind) (string_of_severity severity))) settings; Buffer.contents acc type lint_parse_error = | Invalid_setting | Malformed_argument | Naked_comment | Nonexistent_rule | Overwritten_argument | Redundant_argument
f7931fc6b0c8bcff39f1997e15e3fe2fb83c4e30fbda8118cc02f2d141ab8997
2600hz/kazoo
kazoo_endpoint_maintenance.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kazoo_endpoint_maintenance). -export([flush/0]). -include("kazoo_endpoint.hrl"). -spec flush() -> 'ok'. flush() -> kz_cache:flush_local(?CACHE_NAME).
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_endpoint/src/kazoo_endpoint_maintenance.erl
erlang
----------------------------------------------------------------------------- @doc @end -----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(kazoo_endpoint_maintenance). -export([flush/0]). -include("kazoo_endpoint.hrl"). -spec flush() -> 'ok'. flush() -> kz_cache:flush_local(?CACHE_NAME).
a3fae72dc11d420e81c6fa6964f4adf7d1e76756cd8d0f4c468e3eb4c4d8d907
GaloisInc/cryptol
Unlit.hs
-- | Module : Cryptol . . Copyright : ( c ) 2013 - 2016 Galois , Inc. -- License : BSD3 -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Convert a literate source file into an ordinary source file. {-# LANGUAGE OverloadedStrings, Safe, PatternGuards #-} module Cryptol.Parser.Unlit ( unLit, PreProc(..), guessPreProc, knownExts ) where import Data.Text(Text) import qualified Data.Text as Text import Data.Char(isSpace) import System.FilePath(takeExtension) import Cryptol.Utils.Panic data PreProc = None | Markdown | LaTeX | RST knownExts :: [String] knownExts = [ "cry" , "tex" , "markdown" , "md" , "rst" ] guessPreProc :: FilePath -> PreProc guessPreProc file = case takeExtension file of ".tex" -> LaTeX ".markdown" -> Markdown ".md" -> Markdown ".rst" -> RST _ -> None unLit :: PreProc -> Text -> Text unLit None = id unLit proc = Text.unlines . concatMap toCryptol . preProc proc . Text.lines preProc :: PreProc -> [Text] -> [Block] preProc p = case p of None -> return . Code Markdown -> markdown LaTeX -> latex RST -> rst data Block = Code [Text] | Comment [Text] toCryptol :: Block -> [Text] toCryptol (Code xs) = xs toCryptol (Comment ls) = case ls of [] -> [] [l] -> [ "/* " `Text.append` l `Text.append` " */" ] l1 : rest -> let (more, l) = splitLast rest in "/* " `Text.append` l1 : more ++ [ l `Text.append` " */" ] where splitLast [] = panic "Cryptol.Parser.Unlit.toCryptol" [ "splitLast []" ] splitLast [x] = ([], x) splitLast (x : xs) = let (ys,y) = splitLast xs in (x:ys,y) mk :: ([Text] -> Block) -> [Text] -> [Block] mk _ [] = [] mk c ls = [ c (reverse ls) ] -- | The preprocessor for `markdown` markdown :: [Text] -> [Block] markdown = blanks [] where comment current [] = mk Comment current comment current (l : ls) | Just op <- isOpenFence l = mk Comment (l : current) ++ fenced op [] ls | isBlank l = blanks (l : current) ls | otherwise = comment (l : current) ls blanks current [] = mk Comment current blanks current (l : ls) | Just op <- isOpenFence l = mk Comment (l : current) ++ fenced op [] ls | isCodeLine l = mk Comment current ++ code [l] ls | isBlank l = blanks (l : current) ls | otherwise = comment (l : current) ls code current [] = mk Code current code current (l : ls) | isCodeLine l = code (l : current) ls | otherwise = mk Code current ++ comment [] (l : ls) fenced op current [] = mk op current -- XXX should this be an error? fenced op current (l : ls) | isCloseFence l = mk op current ++ comment [l] ls | otherwise = fenced op (l : current) ls isOpenFence l | "```" `Text.isPrefixOf` l' = Just $ case Text.dropWhile isSpace (Text.drop 3 l') of l'' | "cryptol" `Text.isPrefixOf` l'' -> Code | isBlank l'' -> Code | otherwise -> Comment | otherwise = Nothing where l' = Text.dropWhile isSpace l isCloseFence l = "```" `Text.isPrefixOf` Text.dropWhile isSpace l isBlank l = Text.all isSpace l isCodeLine l = "\t" `Text.isPrefixOf` l || " " `Text.isPrefixOf` l -- | The preprocessor for `latex` latex :: [Text] -> [Block] latex = comment [] where comment current [] = mk Comment current comment current (l : ls) | isBeginCode l = mk Comment (l : current) ++ code [] ls | otherwise = comment (l : current) ls code current [] = mk Code current code current (l : ls) | isEndCode l = mk Code current ++ comment [l] ls | otherwise = code (l : current) ls isBeginCode l = "\\begin{code}" `Text.isPrefixOf` l isEndCode l = "\\end{code}" `Text.isPrefixOf` l rst :: [Text] -> [Block] rst = comment [] where isBeginCode l = case filter (not . Text.null) (Text.split isSpace l) of ["..", dir, "cryptol"] -> dir == "code-block::" || dir == "sourcecode::" _ -> False isEmpty = Text.all isSpace isCode l = case Text.uncons l of Just (c, _) -> isSpace c Nothing -> True comment acc ls = case ls of [] -> mk Comment acc l : ls1 | isBeginCode l -> codeOptions (l : acc) ls1 | otherwise -> comment (l : acc) ls1 codeOptions acc ls = case ls of [] -> mk Comment acc l : ls1 | isEmpty l -> mk Comment (l : acc) ++ code [] ls1 | otherwise -> codeOptions (l : acc) ls1 code acc ls = case ls of [] -> mk Code acc l : ls1 | isCode l -> code (l : acc) ls1 | otherwise -> mk Code acc ++ comment [] ls
null
https://raw.githubusercontent.com/GaloisInc/cryptol/fd05e16022acd13e4659f0c65194e2480cc088a3/src/Cryptol/Parser/Unlit.hs
haskell
| License : BSD3 Maintainer : Stability : provisional Portability : portable Convert a literate source file into an ordinary source file. # LANGUAGE OverloadedStrings, Safe, PatternGuards # | The preprocessor for `markdown` XXX should this be an error? | The preprocessor for `latex`
Module : Cryptol . . Copyright : ( c ) 2013 - 2016 Galois , Inc. module Cryptol.Parser.Unlit ( unLit, PreProc(..), guessPreProc, knownExts ) where import Data.Text(Text) import qualified Data.Text as Text import Data.Char(isSpace) import System.FilePath(takeExtension) import Cryptol.Utils.Panic data PreProc = None | Markdown | LaTeX | RST knownExts :: [String] knownExts = [ "cry" , "tex" , "markdown" , "md" , "rst" ] guessPreProc :: FilePath -> PreProc guessPreProc file = case takeExtension file of ".tex" -> LaTeX ".markdown" -> Markdown ".md" -> Markdown ".rst" -> RST _ -> None unLit :: PreProc -> Text -> Text unLit None = id unLit proc = Text.unlines . concatMap toCryptol . preProc proc . Text.lines preProc :: PreProc -> [Text] -> [Block] preProc p = case p of None -> return . Code Markdown -> markdown LaTeX -> latex RST -> rst data Block = Code [Text] | Comment [Text] toCryptol :: Block -> [Text] toCryptol (Code xs) = xs toCryptol (Comment ls) = case ls of [] -> [] [l] -> [ "/* " `Text.append` l `Text.append` " */" ] l1 : rest -> let (more, l) = splitLast rest in "/* " `Text.append` l1 : more ++ [ l `Text.append` " */" ] where splitLast [] = panic "Cryptol.Parser.Unlit.toCryptol" [ "splitLast []" ] splitLast [x] = ([], x) splitLast (x : xs) = let (ys,y) = splitLast xs in (x:ys,y) mk :: ([Text] -> Block) -> [Text] -> [Block] mk _ [] = [] mk c ls = [ c (reverse ls) ] markdown :: [Text] -> [Block] markdown = blanks [] where comment current [] = mk Comment current comment current (l : ls) | Just op <- isOpenFence l = mk Comment (l : current) ++ fenced op [] ls | isBlank l = blanks (l : current) ls | otherwise = comment (l : current) ls blanks current [] = mk Comment current blanks current (l : ls) | Just op <- isOpenFence l = mk Comment (l : current) ++ fenced op [] ls | isCodeLine l = mk Comment current ++ code [l] ls | isBlank l = blanks (l : current) ls | otherwise = comment (l : current) ls code current [] = mk Code current code current (l : ls) | isCodeLine l = code (l : current) ls | otherwise = mk Code current ++ comment [] (l : ls) fenced op current (l : ls) | isCloseFence l = mk op current ++ comment [l] ls | otherwise = fenced op (l : current) ls isOpenFence l | "```" `Text.isPrefixOf` l' = Just $ case Text.dropWhile isSpace (Text.drop 3 l') of l'' | "cryptol" `Text.isPrefixOf` l'' -> Code | isBlank l'' -> Code | otherwise -> Comment | otherwise = Nothing where l' = Text.dropWhile isSpace l isCloseFence l = "```" `Text.isPrefixOf` Text.dropWhile isSpace l isBlank l = Text.all isSpace l isCodeLine l = "\t" `Text.isPrefixOf` l || " " `Text.isPrefixOf` l latex :: [Text] -> [Block] latex = comment [] where comment current [] = mk Comment current comment current (l : ls) | isBeginCode l = mk Comment (l : current) ++ code [] ls | otherwise = comment (l : current) ls code current [] = mk Code current code current (l : ls) | isEndCode l = mk Code current ++ comment [l] ls | otherwise = code (l : current) ls isBeginCode l = "\\begin{code}" `Text.isPrefixOf` l isEndCode l = "\\end{code}" `Text.isPrefixOf` l rst :: [Text] -> [Block] rst = comment [] where isBeginCode l = case filter (not . Text.null) (Text.split isSpace l) of ["..", dir, "cryptol"] -> dir == "code-block::" || dir == "sourcecode::" _ -> False isEmpty = Text.all isSpace isCode l = case Text.uncons l of Just (c, _) -> isSpace c Nothing -> True comment acc ls = case ls of [] -> mk Comment acc l : ls1 | isBeginCode l -> codeOptions (l : acc) ls1 | otherwise -> comment (l : acc) ls1 codeOptions acc ls = case ls of [] -> mk Comment acc l : ls1 | isEmpty l -> mk Comment (l : acc) ++ code [] ls1 | otherwise -> codeOptions (l : acc) ls1 code acc ls = case ls of [] -> mk Code acc l : ls1 | isCode l -> code (l : acc) ls1 | otherwise -> mk Code acc ++ comment [] ls
9c82ccfd3baa064520a6218b1c49a89674d6d739b01fb40372b4ad0a240f33af
jtdaugherty/vty
Debug.hs
Copyright 2009 - 2010 module Graphics.Vty.Debug ( MockWindow(..) , regionForWindow , allSpansHaveWidth , spanOpsAffectedColumns , spanOpsAffectedRows ) where import Graphics.Vty.Attributes import Graphics.Vty.Image (DisplayRegion) import Graphics.Vty.Span import qualified Data.Vector as Vector rowOpsAffectedColumns :: DisplayOps -> [Int] rowOpsAffectedColumns ops = Vector.toList $ Vector.map spanOpsAffectedColumns ops allSpansHaveWidth :: DisplayOps -> Int -> Bool allSpansHaveWidth ops expected = all (== expected) $ Vector.toList $ Vector.map spanOpsAffectedColumns ops spanOpsAffectedRows :: DisplayOps -> Int spanOpsAffectedRows ops = toEnum $ length (filter (not . null . Vector.toList) (Vector.toList ops)) type SpanConstructLog = [SpanConstructEvent] data SpanConstructEvent = SpanSetAttr Attr isSetAttr :: Attr -> SpanConstructEvent -> Bool isSetAttr expectedAttr (SpanSetAttr inAttr) | inAttr == expectedAttr = True isSetAttr _attr _event = False data MockWindow = MockWindow Int Int deriving (Show, Eq) regionForWindow :: MockWindow -> DisplayRegion regionForWindow (MockWindow w h) = (w,h)
null
https://raw.githubusercontent.com/jtdaugherty/vty/2f8c92b8af5cd82d0746d6cf90bb32f97e564fd2/src/Graphics/Vty/Debug.hs
haskell
Copyright 2009 - 2010 module Graphics.Vty.Debug ( MockWindow(..) , regionForWindow , allSpansHaveWidth , spanOpsAffectedColumns , spanOpsAffectedRows ) where import Graphics.Vty.Attributes import Graphics.Vty.Image (DisplayRegion) import Graphics.Vty.Span import qualified Data.Vector as Vector rowOpsAffectedColumns :: DisplayOps -> [Int] rowOpsAffectedColumns ops = Vector.toList $ Vector.map spanOpsAffectedColumns ops allSpansHaveWidth :: DisplayOps -> Int -> Bool allSpansHaveWidth ops expected = all (== expected) $ Vector.toList $ Vector.map spanOpsAffectedColumns ops spanOpsAffectedRows :: DisplayOps -> Int spanOpsAffectedRows ops = toEnum $ length (filter (not . null . Vector.toList) (Vector.toList ops)) type SpanConstructLog = [SpanConstructEvent] data SpanConstructEvent = SpanSetAttr Attr isSetAttr :: Attr -> SpanConstructEvent -> Bool isSetAttr expectedAttr (SpanSetAttr inAttr) | inAttr == expectedAttr = True isSetAttr _attr _event = False data MockWindow = MockWindow Int Int deriving (Show, Eq) regionForWindow :: MockWindow -> DisplayRegion regionForWindow (MockWindow w h) = (w,h)
4a9fdb2e6f6ada804d5a8fbb29d0809ebd4281664a031c080409eb2bb72f39c8
samaaron/arnold
grumbles.clj
(ns arnold.grumbles (:use [overtone.live])) Inspired by an example in an early chapter of the SuperCollider book (definst grumble [speed 6 freq-mul 1] (let [snd (mix (map #(* (sin-osc (* % freq-mul 100)) (max 0 (+ (lf-noise1:kr speed) (line:kr 1 -1 30 :action FREE)))) [1 (/ 2 3) (/ 3 2) 2]))] (pan2 snd (sin-osc:kr 50)))) (grumble :freq-mul 1) (ctl grumble :speed 3000) (volume (/ 127 127))
null
https://raw.githubusercontent.com/samaaron/arnold/e8daa3ba14dc0d654740750d6cf02ef42cd0fc2e/src/arnold/grumbles.clj
clojure
(ns arnold.grumbles (:use [overtone.live])) Inspired by an example in an early chapter of the SuperCollider book (definst grumble [speed 6 freq-mul 1] (let [snd (mix (map #(* (sin-osc (* % freq-mul 100)) (max 0 (+ (lf-noise1:kr speed) (line:kr 1 -1 30 :action FREE)))) [1 (/ 2 3) (/ 3 2) 2]))] (pan2 snd (sin-osc:kr 50)))) (grumble :freq-mul 1) (ctl grumble :speed 3000) (volume (/ 127 127))
2df8c473bd8d4b38eb1c6d66f18bdeb20296613f7784ab07674023d68b84cfd3
rowangithub/DOrder
mtype.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : mtype.mli 6196 2004 - 04 - 09 13:32:28Z xleroy $ (* Operations on module types *) open Types val scrape: Env.t -> module_type -> module_type (* Expand toplevel module type abbreviations till hitting a "hard" module type (signature, functor, or abstract module type ident. *) val freshen: module_type -> module_type (* Return an alpha-equivalent copy of the given module type where bound identifiers are fresh. *) val strengthen: Env.t -> module_type -> Path.t -> module_type (* Strengthen abstract type components relative to the given path. *) val nondep_supertype: Env.t -> Ident.t -> module_type -> module_type (* Return the smallest supertype of the given type in which the given ident does not appear. Raise [Not_found] if no such type exists. *) val no_code_needed: Env.t -> module_type -> bool val no_code_needed_sig: Env.t -> signature -> bool (* Determine whether a module needs no implementation code, i.e. consists only of type definitions. *) val enrich_modtype: Env.t -> Path.t -> module_type -> module_type val enrich_typedecl: Env.t -> Path.t -> type_declaration -> type_declaration val type_paths: Env.t -> Path.t -> module_type -> Path.t list
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/typing/mtype.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Operations on module types Expand toplevel module type abbreviations till hitting a "hard" module type (signature, functor, or abstract module type ident. Return an alpha-equivalent copy of the given module type where bound identifiers are fresh. Strengthen abstract type components relative to the given path. Return the smallest supertype of the given type in which the given ident does not appear. Raise [Not_found] if no such type exists. Determine whether a module needs no implementation code, i.e. consists only of type definitions.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : mtype.mli 6196 2004 - 04 - 09 13:32:28Z xleroy $ open Types val scrape: Env.t -> module_type -> module_type val freshen: module_type -> module_type val strengthen: Env.t -> module_type -> Path.t -> module_type val nondep_supertype: Env.t -> Ident.t -> module_type -> module_type val no_code_needed: Env.t -> module_type -> bool val no_code_needed_sig: Env.t -> signature -> bool val enrich_modtype: Env.t -> Path.t -> module_type -> module_type val enrich_typedecl: Env.t -> Path.t -> type_declaration -> type_declaration val type_paths: Env.t -> Path.t -> module_type -> Path.t list
be9502714e559bd7b77ab080081dfa5f25de2806ba78ae8c1e9a235d9e5538a7
brendanhay/gogol
Types.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . Translate . Types Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Gogol.Translate.Types ( -- * Configuration translateService, * OAuth CloudPlatform'FullControl, CloudTranslation'FullControl, -- * Types -- ** Xgafv Xgafv (..), * * BatchDocumentInputConfig BatchDocumentInputConfig (..), newBatchDocumentInputConfig, -- ** BatchDocumentOutputConfig BatchDocumentOutputConfig (..), newBatchDocumentOutputConfig, -- ** BatchTranslateDocumentRequest BatchTranslateDocumentRequest (..), newBatchTranslateDocumentRequest, -- ** BatchTranslateDocumentRequest_FormatConversions BatchTranslateDocumentRequest_FormatConversions (..), newBatchTranslateDocumentRequest_FormatConversions, -- ** BatchTranslateDocumentRequest_Glossaries BatchTranslateDocumentRequest_Glossaries (..), newBatchTranslateDocumentRequest_Glossaries, * * BatchTranslateDocumentRequest_Models (..), newBatchTranslateDocumentRequest_Models, -- ** BatchTranslateTextRequest BatchTranslateTextRequest (..), newBatchTranslateTextRequest, -- ** BatchTranslateTextRequest_Glossaries BatchTranslateTextRequest_Glossaries (..), newBatchTranslateTextRequest_Glossaries, -- ** BatchTranslateTextRequest_Labels BatchTranslateTextRequest_Labels (..), newBatchTranslateTextRequest_Labels, * * BatchTranslateTextRequest_Models BatchTranslateTextRequest_Models (..), newBatchTranslateTextRequest_Models, -- ** CancelOperationRequest CancelOperationRequest (..), newCancelOperationRequest, -- ** DetectLanguageRequest DetectLanguageRequest (..), newDetectLanguageRequest, -- ** DetectLanguageRequest_Labels DetectLanguageRequest_Labels (..), newDetectLanguageRequest_Labels, -- ** DetectLanguageResponse DetectLanguageResponse (..), newDetectLanguageResponse, -- ** DetectedLanguage DetectedLanguage (..), newDetectedLanguage, -- ** DocumentInputConfig DocumentInputConfig (..), newDocumentInputConfig, -- ** DocumentOutputConfig DocumentOutputConfig (..), newDocumentOutputConfig, -- ** DocumentTranslation DocumentTranslation (..), newDocumentTranslation, -- ** Empty Empty (..), newEmpty, -- ** GcsDestination GcsDestination (..), newGcsDestination, * * GcsSource (..), newGcsSource, -- ** Glossary Glossary (..), newGlossary, -- ** GlossaryInputConfig GlossaryInputConfig (..), newGlossaryInputConfig, -- ** InputConfig InputConfig (..), newInputConfig, -- ** LanguageCodePair LanguageCodePair (..), newLanguageCodePair, -- ** LanguageCodesSet LanguageCodesSet (..), newLanguageCodesSet, -- ** ListGlossariesResponse ListGlossariesResponse (..), newListGlossariesResponse, * * ListLocationsResponse ListLocationsResponse (..), newListLocationsResponse, -- ** ListOperationsResponse ListOperationsResponse (..), newListOperationsResponse, -- ** Location Location (..), newLocation, -- ** Location_Labels Location_Labels (..), newLocation_Labels, -- ** Location_Metadata Location_Metadata (..), newLocation_Metadata, -- ** Operation Operation (..), newOperation, -- ** Operation_Metadata Operation_Metadata (..), newOperation_Metadata, -- ** Operation_Response Operation_Response (..), newOperation_Response, -- ** OutputConfig OutputConfig (..), newOutputConfig, -- ** Status Status (..), newStatus, -- ** Status_DetailsItem Status_DetailsItem (..), newStatus_DetailsItem, -- ** SupportedLanguage SupportedLanguage (..), newSupportedLanguage, * * SupportedLanguages SupportedLanguages (..), newSupportedLanguages, * * TranslateDocumentRequest TranslateDocumentRequest (..), newTranslateDocumentRequest, * * TranslateDocumentRequest_Labels TranslateDocumentRequest_Labels (..), newTranslateDocumentRequest_Labels, * * TranslateDocumentResponse (..), newTranslateDocumentResponse, -- ** TranslateTextGlossaryConfig TranslateTextGlossaryConfig (..), newTranslateTextGlossaryConfig, -- ** TranslateTextRequest TranslateTextRequest (..), newTranslateTextRequest, -- ** TranslateTextRequest_Labels TranslateTextRequest_Labels (..), newTranslateTextRequest_Labels, -- ** TranslateTextResponse TranslateTextResponse (..), newTranslateTextResponse, -- ** Translation Translation (..), newTranslation, -- ** WaitOperationRequest WaitOperationRequest (..), newWaitOperationRequest, ) where import qualified Gogol.Prelude as Core import Gogol.Translate.Internal.Product import Gogol.Translate.Internal.Sum -- | Default request referring to version @v3@ of the Cloud Translation API. This contains the host and root path used as a starting point for constructing service requests. translateService :: Core.ServiceConfig translateService = Core.defaultService (Core.ServiceId "translate:v3") "translation.googleapis.com" | See , edit , configure , and delete your Google Cloud data and see the email address for your Google Account . type CloudPlatform'FullControl = "-platform" | Translate text from one language to another using Google Translate type CloudTranslation'FullControl = "-translation"
null
https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-translate/gen/Gogol/Translate/Types.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated * Configuration * Types ** Xgafv ** BatchDocumentOutputConfig ** BatchTranslateDocumentRequest ** BatchTranslateDocumentRequest_FormatConversions ** BatchTranslateDocumentRequest_Glossaries ** BatchTranslateTextRequest ** BatchTranslateTextRequest_Glossaries ** BatchTranslateTextRequest_Labels ** CancelOperationRequest ** DetectLanguageRequest ** DetectLanguageRequest_Labels ** DetectLanguageResponse ** DetectedLanguage ** DocumentInputConfig ** DocumentOutputConfig ** DocumentTranslation ** Empty ** GcsDestination ** Glossary ** GlossaryInputConfig ** InputConfig ** LanguageCodePair ** LanguageCodesSet ** ListGlossariesResponse ** ListOperationsResponse ** Location ** Location_Labels ** Location_Metadata ** Operation ** Operation_Metadata ** Operation_Response ** OutputConfig ** Status ** Status_DetailsItem ** SupportedLanguage ** TranslateTextGlossaryConfig ** TranslateTextRequest ** TranslateTextRequest_Labels ** TranslateTextResponse ** Translation ** WaitOperationRequest | Default request referring to version @v3@ of the Cloud Translation API. This contains the host and root path used as a starting point for constructing service requests.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . Translate . Types Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Gogol.Translate.Types translateService, * OAuth CloudPlatform'FullControl, CloudTranslation'FullControl, Xgafv (..), * * BatchDocumentInputConfig BatchDocumentInputConfig (..), newBatchDocumentInputConfig, BatchDocumentOutputConfig (..), newBatchDocumentOutputConfig, BatchTranslateDocumentRequest (..), newBatchTranslateDocumentRequest, BatchTranslateDocumentRequest_FormatConversions (..), newBatchTranslateDocumentRequest_FormatConversions, BatchTranslateDocumentRequest_Glossaries (..), newBatchTranslateDocumentRequest_Glossaries, * * BatchTranslateDocumentRequest_Models (..), newBatchTranslateDocumentRequest_Models, BatchTranslateTextRequest (..), newBatchTranslateTextRequest, BatchTranslateTextRequest_Glossaries (..), newBatchTranslateTextRequest_Glossaries, BatchTranslateTextRequest_Labels (..), newBatchTranslateTextRequest_Labels, * * BatchTranslateTextRequest_Models BatchTranslateTextRequest_Models (..), newBatchTranslateTextRequest_Models, CancelOperationRequest (..), newCancelOperationRequest, DetectLanguageRequest (..), newDetectLanguageRequest, DetectLanguageRequest_Labels (..), newDetectLanguageRequest_Labels, DetectLanguageResponse (..), newDetectLanguageResponse, DetectedLanguage (..), newDetectedLanguage, DocumentInputConfig (..), newDocumentInputConfig, DocumentOutputConfig (..), newDocumentOutputConfig, DocumentTranslation (..), newDocumentTranslation, Empty (..), newEmpty, GcsDestination (..), newGcsDestination, * * GcsSource (..), newGcsSource, Glossary (..), newGlossary, GlossaryInputConfig (..), newGlossaryInputConfig, InputConfig (..), newInputConfig, LanguageCodePair (..), newLanguageCodePair, LanguageCodesSet (..), newLanguageCodesSet, ListGlossariesResponse (..), newListGlossariesResponse, * * ListLocationsResponse ListLocationsResponse (..), newListLocationsResponse, ListOperationsResponse (..), newListOperationsResponse, Location (..), newLocation, Location_Labels (..), newLocation_Labels, Location_Metadata (..), newLocation_Metadata, Operation (..), newOperation, Operation_Metadata (..), newOperation_Metadata, Operation_Response (..), newOperation_Response, OutputConfig (..), newOutputConfig, Status (..), newStatus, Status_DetailsItem (..), newStatus_DetailsItem, SupportedLanguage (..), newSupportedLanguage, * * SupportedLanguages SupportedLanguages (..), newSupportedLanguages, * * TranslateDocumentRequest TranslateDocumentRequest (..), newTranslateDocumentRequest, * * TranslateDocumentRequest_Labels TranslateDocumentRequest_Labels (..), newTranslateDocumentRequest_Labels, * * TranslateDocumentResponse (..), newTranslateDocumentResponse, TranslateTextGlossaryConfig (..), newTranslateTextGlossaryConfig, TranslateTextRequest (..), newTranslateTextRequest, TranslateTextRequest_Labels (..), newTranslateTextRequest_Labels, TranslateTextResponse (..), newTranslateTextResponse, Translation (..), newTranslation, WaitOperationRequest (..), newWaitOperationRequest, ) where import qualified Gogol.Prelude as Core import Gogol.Translate.Internal.Product import Gogol.Translate.Internal.Sum translateService :: Core.ServiceConfig translateService = Core.defaultService (Core.ServiceId "translate:v3") "translation.googleapis.com" | See , edit , configure , and delete your Google Cloud data and see the email address for your Google Account . type CloudPlatform'FullControl = "-platform" | Translate text from one language to another using Google Translate type CloudTranslation'FullControl = "-translation"
550378a5ab81106d83330035ddf20783099f9a88de39132bbaa3ab593e60aeee
fp-works/2019-winter-Haskell-school
Exercise02Spec.hs
module CIS194.Homework05.Exercise02Spec where import CIS194.Homework05.Exercise02 import Test.Tasty.Hspec spec_evalStr :: Spec spec_evalStr = it "evaluates the value correctly" $ do evalStr "(2+3)*4" `shouldBe` Just 20 evalStr "2+3*4" `shouldBe` Just 14 evalStr "2+3*" `shouldBe` Nothing evalStr "" `shouldBe` Nothing evalStr " " `shouldBe` Nothing
null
https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week5/daniel-deng/test/Exercise02Spec.hs
haskell
module CIS194.Homework05.Exercise02Spec where import CIS194.Homework05.Exercise02 import Test.Tasty.Hspec spec_evalStr :: Spec spec_evalStr = it "evaluates the value correctly" $ do evalStr "(2+3)*4" `shouldBe` Just 20 evalStr "2+3*4" `shouldBe` Just 14 evalStr "2+3*" `shouldBe` Nothing evalStr "" `shouldBe` Nothing evalStr " " `shouldBe` Nothing
781e108fe8a9080bea34b5200cbb3df6a11d481adb8a65ddb6f957499affd22a
OCamlPro/directories
directories.mli
module Base_dirs () : sig val home_dir : string option val cache_dir : string option val config_dir : string option val data_dir : string option val data_local_dir : string option val preference_dir : string option val runtime_dir : string option val state_dir : string option val executable_dir : string option end module User_dirs () : sig val home_dir : string option val audio_dir : string option val desktop_dir : string option val document_dir : string option val download_dir : string option val font_dir : string option val picture_dir : string option val public_dir : string option val template_dir : string option val video_dir : string option end module Project_dirs (App_id : sig val qualifier : string val organization : string val application : string end) : sig val cache_dir : string option val config_dir : string option val data_dir : string option val data_local_dir : string option val preference_dir : string option val runtime_dir : string option val state_dir : string option end
null
https://raw.githubusercontent.com/OCamlPro/directories/1cf7211f918fa909e5f77c0dfbb059c74071e99b/src/directories.mli
ocaml
module Base_dirs () : sig val home_dir : string option val cache_dir : string option val config_dir : string option val data_dir : string option val data_local_dir : string option val preference_dir : string option val runtime_dir : string option val state_dir : string option val executable_dir : string option end module User_dirs () : sig val home_dir : string option val audio_dir : string option val desktop_dir : string option val document_dir : string option val download_dir : string option val font_dir : string option val picture_dir : string option val public_dir : string option val template_dir : string option val video_dir : string option end module Project_dirs (App_id : sig val qualifier : string val organization : string val application : string end) : sig val cache_dir : string option val config_dir : string option val data_dir : string option val data_local_dir : string option val preference_dir : string option val runtime_dir : string option val state_dir : string option end
577dbb0b7fdf1c1e5721aa454b40c897362e50e20fc91376f78790fc097a34a3
denisidoro/rosebud
core.clj
(ns fundo.logic.core (:require [clj-time.format :as time.format] [quark.beta.math.point :as point] [quark.beta.time :as time])) (def ^:private formatter (time.format/formatter "yyyyMMdd")) (defn ^:private fundo-entry->point [{:keys [c d p q]}] (point/new (time/date-str->millis (str d) formatter) c)) (defn as-bucket [cnpj body] {:bucket/id (keyword "fundo" (str cnpj)) :bucket/path [:fundo cnpj] :history/gross (map fundo-entry->point body)})
null
https://raw.githubusercontent.com/denisidoro/rosebud/90385528d9a75a0e17803df487a4f6cfb87e981c/server/src/fundo/logic/core.clj
clojure
(ns fundo.logic.core (:require [clj-time.format :as time.format] [quark.beta.math.point :as point] [quark.beta.time :as time])) (def ^:private formatter (time.format/formatter "yyyyMMdd")) (defn ^:private fundo-entry->point [{:keys [c d p q]}] (point/new (time/date-str->millis (str d) formatter) c)) (defn as-bucket [cnpj body] {:bucket/id (keyword "fundo" (str cnpj)) :bucket/path [:fundo cnpj] :history/gross (map fundo-entry->point body)})
10792c6d1604ad5439b5c83e7516a895d2c7ed4cbcce7872347f44495c0f56f4
dalaing/little-languages
Value.hs
module Components.Term.Nat.Eval.Value ( nv , valueInput ) where import Data.Foldable (asum) import Control.Lens (preview, review) import Control.Monad.Reader (ReaderT(..)) import Common.Recursion (Step(..)) import Common.Term.Eval.Value (ValueInput(..)) import Components.Term.Nat.Data valueTmZero :: WithNatTerm ty tm => tm -> Maybe tm valueTmZero = fmap (review _TmZero) . preview _TmZero valueTmSucc :: WithNatTerm ty tm => tm -> Maybe tm valueTmSucc tm = do n <- preview _TmSucc tm -- this is the strict version n' <- nv n return $ review _TmSucc n' nv :: WithNatTerm ty tm => tm -> Maybe tm nv tm = asum . map ($ tm) $ [ valueTmZero , valueTmSucc ] valueInput :: WithNatTerm ty tm => ValueInput tm valueInput = ValueInput [SBase $ ReaderT nv]
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/multityped/nb-modular/src/Components/Term/Nat/Eval/Value.hs
haskell
this is the strict version
module Components.Term.Nat.Eval.Value ( nv , valueInput ) where import Data.Foldable (asum) import Control.Lens (preview, review) import Control.Monad.Reader (ReaderT(..)) import Common.Recursion (Step(..)) import Common.Term.Eval.Value (ValueInput(..)) import Components.Term.Nat.Data valueTmZero :: WithNatTerm ty tm => tm -> Maybe tm valueTmZero = fmap (review _TmZero) . preview _TmZero valueTmSucc :: WithNatTerm ty tm => tm -> Maybe tm valueTmSucc tm = do n <- preview _TmSucc tm n' <- nv n return $ review _TmSucc n' nv :: WithNatTerm ty tm => tm -> Maybe tm nv tm = asum . map ($ tm) $ [ valueTmZero , valueTmSucc ] valueInput :: WithNatTerm ty tm => ValueInput tm valueInput = ValueInput [SBase $ ReaderT nv]
52fced23b09c95c9ed64194b2572afdbca1ef5fec235745c05dcb7e001c1cc16
practicalli/clojure-through-code
01_basics.clj
namespaces are similar to packages in Java , in that they are a grouping of data and behaviour namespaces allow you to structure your Clojure code into logical groupings namesaces help you use functions defined in one namespace in a different namespace ;; using the (use) function in clojure. (ns clojure-through-code.01-basics (:require [clojure.string])) ;; (:require 'clojure.repl) ;; (:require [clojure.repl] :refer :all) ;;;;;;;;;;;;;;;;;;;;;;; Clojure Syntax Clojure uses a prefix notation and ( ) [ ] : { } # @ ! special characters ;; no need for lots of ; , and other silly things... All behaviour in Clojure is defined in a List , with the first elemtent being a function ;; and the remaining elements being arguments to that function. ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; What is my environment Clojure has built in symbols , which start and end with * ;; Symbols can be evaluated outside of a list structure, ;; functions (the behaviour of your application) and their ;; arguments are contained within a list structure () ;; The full clojure version can be used to check you are running a particular version , major or minor of Clojure core *clojure-version* The version info for Clojure core , as a map containing : major : minor ;; :incremental and :qualifier keys. Feature releases may increment ;; :minor and/or :major, bugfix releases will increment :incremental. Possible values of : qualifier include " GA " , " SNAPSHOT " , " RC - x " " BETA - x " The directory where the Clojure compiler will create the .class files for the current project ;; This directory must be in the classpath for 'compile' to work. *compile-path* ;; The path of the file being evaluated, as a String. In the REPL the value is not defined. *file* ;; A clojure.lang.Namespace object representing the current namespace *ns* ;; most recent repl values *1 *2 *3 ;;;;;;;;;;;;;;;;;;;;;;;;; Using Java Interoperability java.lang is part of the Clojure runtime environment , so when ever you run a REPL you can call any methods without having to import them or include any dependencies From java.lang . System getProperty ( ) as documented at : ;; (System/getProperty "java.version") (System/getProperty "java.vm.name") Java properties can be obtained by calling from java.lang . As System.getProperty is called as a function ;; in clojure it needs to be wrapped in a list structure. Make the result prettier using the Clojure str function (str "Current Java version: " (System/getProperty "java.version")) ;; We can also get the version of the project (System/getProperty "clojure-through-code.version") Chaining a few Clojure functions together , to read from the Leiningen project file ;; Getting the version number of the project Information can be read from the Clojure project.clj file using the slurp function (slurp "project.clj") = > " ( defproject clojure - through - code \"20.1.5 - SNAPSHOT\"\n : description \"Learning Clojure by evaluating code on the fly\"\n : url \"\"\n : license { : name \"Eclipse Public License\"\n : url \" / legal / epl - v10.html\"}\n : dependencies [ [ org.clojure/clojure \"1.6.0\"]])\n\n " ;; The value returned by slurp is a bit messy, so we can tidy it up with read-string (read-string (slurp "project.clj")) = > ( defproject clojure - through - code " 20.1.5 - SNAPSHOT " : description " Learning Clojure by evaluating code on the fly " : url " " : license { : name " Eclipse Public License " , : url " -v10.html " } : dependencies [ [ org.clojure/clojure " 1.6.0 " ] ] ) ;; rather than have all the information from the file, we just want to get the project version ;; Using the nth function we can select which element we actually want (nth (read-string (slurp "project.clj")) 2) = > " 20.1.5 - SNAPSHOT " ;; The above code is classic Lisp, you read it from the inside out, so in this case you ;; start with (slurp ...) and what it returns is used as the argument to read-string... ;; Get the contents of the project.clj file using `slurp` ;; Read the text of that file using read-string Select just the third string using nth 2 ( using an index starting at 0 ) ;; You can format the code differently, but in this case its not much easier to read (nth (read-string (slurp "project.clj")) 2) ;; the same behaviour as above can be written using the threading macro ;; which can make code easier to read by reading sequentially down the list of functions. (-> "./project.clj" slurp read-string (nth 2)) ;; Using the threading macro, the result of every function is passed onto the next function ;; in the list. This can be seen very clearly usng ,,, to denote where the value is passed ;; to the next function (-> "./project.clj" slurp ,,, read-string ,,, (nth ,,, 2)) ;; Remember, commas in clojure are ignored ;; To make this really simple lets create a contrived example of the threading macro. ;; Here we use the str function to join strings together. Each individual string call joins its own strings together , then passes them as a single string as the first argument to the next function (-> (str "This" " " "is" " ") (str "the" " " "treading" " " "macro" " ") (str "in" " " "action.")) ;; Using the ->> threading macro, the result of a function is passed as the last parameter ;; of the next function call. So in another simple series of str function calls, ;; our text comes out backwards. (->> (str "This" " ") (str "is" " ") (str "backwards" " ")) ;; Threading macro is very useful for passing a collection through a number of functions, ;; each function manipulating that collection in a specific way before passing it on to the next. (-> [2 5 4 1 3 6] (reverse) (rest) (sort) (last)) ;; add all project information to a map (->> "project.clj" slurp read-string (drop 2) (cons :version) (apply hash-map) (def project)) ;; Threading macros and println statements If you use a print or println function in a threading macro , then part of the value will be lost , as those functions return a value of nil . (-> "message" (str " " "in a bottle") println (str ", The Police")) ;; => ", The Police" The initial part of the message before the println funciton is called has been dropped because println returned nil . Therefore nil was the value passed as the first argument to tne next function , rather than " message in a bottle " . ;; Using the doto function with println we can pass the value on as the return value and pass the value to be printed in the console. (doto "message in a bottle" println) ;; => "message in a bottle" ;; So putting this doto function in our threading macro now works (-> "Message" (str " " "in a bottle") (doto println) (str " - " "The Police")) ;; => "Message in a bottle - The Police" ;; defining functions (def fred "I am free") (def five 5) (def five 6) (def five [1 2 3 4 5 6 7 8]) five (reduce + five) (reduce + [1 2 3 4 5 6 7 8]) = > 36 ;; defn is a macro that builds on def (defn my-function [] (str "I wish I was fred")) ;; defining a function with def (def my-function (fn [args] (str "behaviour"))) ;; anonymous function (fn [args] (str "behaviour")) ;; anonymous function syntax sugar ;; An anonymous function is defined with the #() syntax where % is a placeholder for the arguments. (#(* % %) 6) ;; square a number (fn [num] (* num num)) add three ( fn [ num ] ( + num 3 ) ) add 3 arguments ( fn [ arg1 arg2 arg3 ] ( + arg1 arg2 arg3 4 5 ) ) ;; ;;;;;;;;;;;;;;;;;;;;;;; ;; Working with strings You could use the Java - like function ` println ` to output strings . (println "Hello, whats different with me? What value do I return") However , something different happens when you evaluate this expression . This is refered to as a side - effect because when you call this function it returns nil . The actual text is output to the REPL or console . In Clojure , you are more likely to use the ` str ` function when working with strings . (str "Hello, I am returned as a value of this expression") ;; join strings together with the function str (str "Hello" ", " "HackTheTower UK") using println in LightTable shows the results in console window , as its a side affect ;; using srt you see the results of the evaluation inline with the code, ; as the result of a definition or an expression. ;; Avoid code that creates side-effects where possible to keep your software less complex. ;; using the fast feedback of the REPL usually works beter than println statements in debuging ;;;;;;;;;;;;;;;;;;;;;;;; Simple math to show you the basic structure of Clojure ; Math is straightforward (+ 3 (/ 4 2) (* 3 5)) (+ 1 1 2489 459 2.7) (-> (+ 12 144 20 (* 3 (Math/sqrt 4))) (/ 7) (+ (* 5 11)) (= (+ 0.0 (* 9 9)))) (Math/sqrt 4) = > 1 = > 2 (/ 1 2) (type (/ 22 7.0)) (/ 5000 20000) (type (Integer. "2")) The above is the same as the Java statement Integer myInt = new Integer("2 " ) (/ (* 22/7 3) 3) ;; Ratios delay the need to drop into decimal numbers. Once you create a decimal number then everything it touches had a greater potential to becoming a decimal Clojure uses Prefix notation , so math operations on many arguments is easy . (+ 1 2 3 4 5) (+ 1 2 (* 3 4) (- 5 6 -7)) (+) (*) (* 2) (+ 4) Variadic functions (+ 1 2 3) (< 1 2 3) (< 1 3 8 4) ( remaining 22 7 ) (inc 3) (dec 4) (min 1 2 3 5 8 13) (max 1 2 3 5 8 13) (apply + [1 2 3]) (reduce + [1 2 3]) (apply / [1 2 3]) (/ 53) (map + [1 2 3.0] [4.0 5 6]) (repeat 4 9) ; Equality is = (= 1 1) ; => true (= 2 1) ; => false ;; Equality is very useful when your data structures are immutable ; You need not for logic, too (not true) ; => false (identical? "foo" "bar") (identical? "foo" "foo") (= "foo" "bar") (= "foo" "foo") (identical? :foo :bar) (identical? :foo :foo) ;; Keywords exist as identifiers and for very fast comparisons (def my-map {:foo "a"}) (= "a" (:foo my-map)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Truethy experiments ;; some truthiness with math functions - looking at types (+) (class (+)) (*) (true? +) (false? +) (true? *) (false? *) (true? 1) (true? -1) (true? true) (true? (not false)) (- 2) ; (class (/)) ;; wrong number of arguments error (= 4 (inc 2)) ;; => false ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Conditionals ;; if something is true, do this, else do that (if false "hello" (do (+ 3 4) (str "goodbye"))) (if false "one" "two") (if nil "uh" "oh") (if false "Hello word" "Goodbye crule world") ;; cond - if condition true, do this, :otherwise do that (cond (zero? (- (* 4 2) 8)) (= 4 (inc 2)) (= 4 (/ 8 2)) (= "Hello World" (str "Hello " "World")) :otherwise "None of the above.") (cond (= 7 (inc 2)) "(inc 2) is not 7, so this condition is false" (= 16 (* 8 2)) "This is the first correct condition so its associated expression is returned" (zero? (- (* 8 8) 64)) "This is true but not returned as a previous condition is true" :otherwise "None of the above are true") ;; when true do the following (when (> 8 2) "Higher") ;; Predicates - take a value and return a boolean result (true | false) (true? true) (true? (not true)) (true? false) (true? (not false)) (true? nil) ; Types ;;;;;;;;;;;;; Clojure uses Java 's object types for booleans , strings and numbers . ; Use `class` to inspect them. (class 1) Integer literals are java.lang . Long by default (class 1.1) ; Float literals are java.lang.Double (class "") ; Strings always double-quoted, and are java.lang.String (class false) ; Booleans are java.lang.Boolean (class nil) ; The "null" value is called nil (class (list 1 2 3 4)) (class true) (class ()) (class (list 1 2 34 5)) (class (str 2 3 4 5)) (class (+ 22/7)) (class 5) (class "fish") (type [1 2 3]) (type {:a 1 :b 2}) (type (take 3 (range 10))) (take 10 (range)) (type (Integer. "8080")) (type "This is a string") (type '(1 2 3 4)) (type 1) (type "I am a string") (type :i-am-a-keyword) (type 22/7) (type 'def) (type 'defn) (type '(1 2 3 4)) (type [1 2 3 4]) (type {:a 1 :b 2}) (type #{1 2 3 4}) ;; Ratios To help maintain the precision of numbers , Clojure has a type called Ratio ;; So when you are dividing numbers you can keep the as a fraction using whole numbers ;; rather than constrain the result to a approximate (/ 2) A classic example is dividing 22 by 7 which is approximately the value of Pi (/ 22 7) (class (/ 22 7)) If you want to force Clojure to evaluate this then you can specify one of the ;; numbers with a decimal point (class (/ 22 7.0)) (/ 14 4) 7/2 (* (/ 22 7) 7) (type 7.0) ;; Is something a thing (instance? String "hello") (instance? Double 3.14) (instance? Number 3.14) (instance? java.util.Date #inst "2015-01-01") ;; Lets try and break clojure with Math ;; (/ 22 0) ArithmeticException Divide by zero clojure.lang.Numbers.divide ( Numbers.java:156 ) java.lang . * packages are included in all Clojure projects , so you can call the ;; Java Math functions easily (Math/sqrt 4) (Math/sqrt 13) (Math/PI) (.toUpperCase "bla") ;;(new yourObjectName) ;; (. youObjectName) Lets have some maths fun and see how Clojure deals with this (Math/sqrt -1) So Clojure , well Java really as its the Java Math class methods , deals with interesting ;; mathematical concepts like the square-root of minus one. So what does NaN mean . Well by consulting Stack Overflow , a NaN is produced if a floating point operation would produce an undefinable result . Other examples include dividing 0.0 by 0.0 is arithmetically undefined . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Clojure projects Install Leiningen build tool from leingingen.org Create a new project with new project - name Run the repl using repl ;; Look at the project configuration file project.clj The project is defined as Clojure code using defproject macro , keywords , maps & vectors ;; In the source code src/project-name/core.clj is some sample code in a specific namespace Namespaces are similar to packages in Java ;; A namespace is a way to organise your clojure code (data structure and function definitions) ;; The namespace represents the underlying directory and filename which contain specific data structure and function definitions (namespace 'clojure-through-code.01-basics/my-map) (name 'clojure-through-code.01-basics/my-map) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Documentation in Clojure & LightTable Clojure functions have Documentation - in LightTable you can right - click on a function name and select " show docs " ;; documentation is shown inline ;; Lets look at the documentation for map (class []) (map? [1 2 3 4]) ;;;;;;;;;;;;;;;;;;;;;;;; LightTable Settings The configuration in LightTable uses a Clojure syntax ;; which is easy enough to understand even if you dont know ;; clojure. Essentially the configurations are a datastructure , a map with Clojure keywords to make it ;; simple to pull out the relevant settings ;; Set up keyboard shortcuts or look at the default shortcuts ;; Settings: User keymap ;; Settings: Default keymap General configuration settings for LightTable - eg , , themes , editor settings ;; Settings: User behaviors ;; (doto) ;; Chain functions together ;; -> ;;; cool stuff ;; user> (as-> 0 n) 0 ;; user> (as-> 0 n (inc n) (inc n)) 2 user > ( def x [ [ 1 2 3 ] [ 4 5 6 ] ] ) ;; #'user/x ;; user> x ;; [[1 2 3] [4 5 6]] ;; user> (ffirst x) 1 user > ( first x ) ;; [1 2 3] ;; user> (assoc nil :a) ArityException Wrong number of args ( 2 ) passed to : core / assoc clojure.lang . AFn.throwArity ( AFn.java:429 ) user > ( assoc nil : a 1 ) { : a 1 } user > ( filter identity @)RuntimeException Unmatched delimiter : ) clojure.lang . Util.runtimeException ( Util.java:221 ) ;; user> (filter identity '(1 2 3 nil)) ;; (1 2 3) ;; user> (identity nil) ;; nil ;; user> (true? nil) ;; false Paredit ;; Alt-up - get rid of parent (def a "I have a name") ;; (def :a "What about keywords") ;; => keywords cannot be used as names, as keywords point to themselves (class :a) (get {"a" "ay"} "a") (get-in {"a" {"aa" "You found me"}} ["a" "aa"]) (let [reason "sick"] (cond (= reason "sick") "I ache all over and am seeing green elephant-shaped spots" (= reason "train") "That darn Southern Rail on strike again" (= reason "pet") "My pet ate my homework")) (let [greeting :fr] (case greeting :fr "bonjour monde clojure" :en "hello clojure world" :it "ciao mondo clojure" :es "hola mundo clojure")) (let [language :fr message (case language :fr "bonjour monde clojure" :en "hello clojure world" :it "ciao mondo clojure" :es "hola mundo clojure") upper-case? true] (if upper-case? (clojure.string/upper-case message) message)) (let [reason "sick"] (cond (= reason "sick") "I ache all over and am seeing green elephant-shaped spots" (= reason "train") "That darn Southern Rail on strike again" (= reason "pet") "My pet ate my homework")) (def my-details ["John" "Stevenson" "37" "Clojure" "London" "North Yorkshire" 12]) (first my-details) (second my-details) (rest my-details) (nth ["John" "Stevenson" "37" "Clojure" "London" "North Yorkshire" 12] 2) (nth my-details 0) (first my-details) (first "John") (str (nth "John" 0)) ["string" ["fish" "rabit"]] {:key ["value1" "value2"]} {:bicycle ["wheels" "frame" "handlbars"]} {:meal ["starter" "main course" "desert"]} {:meal ["starter" ["soup" "bread rolls"] "main course" ["fish" "chips" "mushy peas"] "desert" ["cheese" "wine"]]} {:meal {"starter" ["soup" "bread rolls"] "main course" ["fish" "chips" "mushy peas"] "desert" ["cheese" "wine"]}} {:meal {:starter ["soup" "bread rolls"] :main-course ["fish" "chips" "mushy peas"] :desert ["cheese" "wine"]}} {:meal {:ingredience [] :recipe []}}
null
https://raw.githubusercontent.com/practicalli/clojure-through-code/e65842363c328fb251c88a0c6a377ed2a42d152a/src/clojure_through_code/01_basics.clj
clojure
using the (use) function in clojure. (:require 'clojure.repl) (:require [clojure.repl] :refer :all) no need for lots of ; , and other silly things... and the remaining elements being arguments to that function. What is my environment Symbols can be evaluated outside of a list structure, functions (the behaviour of your application) and their arguments are contained within a list structure () The full clojure version :incremental and :qualifier keys. Feature releases may increment :minor and/or :major, bugfix releases will increment :incremental. This directory must be in the classpath for 'compile' to work. The path of the file being evaluated, as a String. In the REPL the value is not defined. A clojure.lang.Namespace object representing the current namespace most recent repl values in clojure it needs to be wrapped in a list structure. We can also get the version of the project Getting the version number of the project The value returned by slurp is a bit messy, so we can tidy it up with read-string rather than have all the information from the file, we just want to get the project version Using the nth function we can select which element we actually want The above code is classic Lisp, you read it from the inside out, so in this case you start with (slurp ...) and what it returns is used as the argument to read-string... Get the contents of the project.clj file using `slurp` Read the text of that file using read-string You can format the code differently, but in this case its not much easier to read the same behaviour as above can be written using the threading macro which can make code easier to read by reading sequentially down the list of functions. Using the threading macro, the result of every function is passed onto the next function in the list. This can be seen very clearly usng ,,, to denote where the value is passed to the next function Remember, commas in clojure are ignored To make this really simple lets create a contrived example of the threading macro. Here we use the str function to join strings together. Each individual string call Using the ->> threading macro, the result of a function is passed as the last parameter of the next function call. So in another simple series of str function calls, our text comes out backwards. Threading macro is very useful for passing a collection through a number of functions, each function manipulating that collection in a specific way before passing it on to the next. add all project information to a map Threading macros and println statements => ", The Police" Using the doto function with println we can pass the value on as the return value and pass the value to be printed in the console. => "message in a bottle" So putting this doto function in our threading macro now works => "Message in a bottle - The Police" defining functions defn is a macro that builds on def defining a function with def anonymous function anonymous function syntax sugar An anonymous function is defined with the #() syntax where % is a placeholder for the arguments. square a number (fn [num] (* num num)) Working with strings join strings together with the function str using srt you see the results of the evaluation inline with the code, as the result of a definition or an expression. Avoid code that creates side-effects where possible to keep your software less complex. using the fast feedback of the REPL usually works beter than println statements in debuging Math is straightforward Ratios delay the need to drop into decimal numbers. Once you create a decimal number then everything it touches had a greater potential to becoming a decimal Equality is = => true => false Equality is very useful when your data structures are immutable You need not for logic, too => false Keywords exist as identifiers and for very fast comparisons some truthiness with math functions - looking at types (class (/)) ;; wrong number of arguments error => false Conditionals if something is true, do this, else do that cond - if condition true, do this, :otherwise do that when true do the following Predicates - take a value and return a boolean result (true | false) Types Use `class` to inspect them. Float literals are java.lang.Double Strings always double-quoted, and are java.lang.String Booleans are java.lang.Boolean The "null" value is called nil Ratios So when you are dividing numbers you can keep the as a fraction using whole numbers rather than constrain the result to a approximate numbers with a decimal point Is something a thing Lets try and break clojure with Math (/ 22 0) Java Math functions easily (new yourObjectName) (. youObjectName) mathematical concepts like the square-root of minus one. Look at the project configuration file project.clj In the source code src/project-name/core.clj is some sample code in a specific namespace A namespace is a way to organise your clojure code (data structure and function definitions) The namespace represents the underlying directory and filename which contain specific data structure and function definitions Documentation in Clojure & LightTable documentation is shown inline Lets look at the documentation for map which is easy enough to understand even if you dont know clojure. Essentially the configurations are a simple to pull out the relevant settings Set up keyboard shortcuts or look at the default shortcuts Settings: User keymap Settings: Default keymap Settings: User behaviors (doto) ;; Chain functions together -> cool stuff user> (as-> 0 n) user> (as-> 0 n (inc n) (inc n)) #'user/x user> x [[1 2 3] [4 5 6]] user> (ffirst x) [1 2 3] user> (assoc nil :a) user> (filter identity '(1 2 3 nil)) (1 2 3) user> (identity nil) nil user> (true? nil) false Alt-up - get rid of parent (def :a "What about keywords") => keywords cannot be used as names, as keywords point to themselves
namespaces are similar to packages in Java , in that they are a grouping of data and behaviour namespaces allow you to structure your Clojure code into logical groupings namesaces help you use functions defined in one namespace in a different namespace (ns clojure-through-code.01-basics (:require [clojure.string])) Clojure Syntax Clojure uses a prefix notation and ( ) [ ] : { } # @ ! special characters All behaviour in Clojure is defined in a List , with the first elemtent being a function Clojure has built in symbols , which start and end with * can be used to check you are running a particular version , major or minor of Clojure core *clojure-version* The version info for Clojure core , as a map containing : major : minor Possible values of : qualifier include " GA " , " SNAPSHOT " , " RC - x " " BETA - x " The directory where the Clojure compiler will create the .class files for the current project *compile-path* *file* *ns* *1 *2 *3 Using Java Interoperability java.lang is part of the Clojure runtime environment , so when ever you run a REPL you can call any methods without having to import them or include any dependencies From java.lang . System getProperty ( ) as documented at : (System/getProperty "java.version") (System/getProperty "java.vm.name") Java properties can be obtained by calling from java.lang . As System.getProperty is called as a function Make the result prettier using the Clojure str function (str "Current Java version: " (System/getProperty "java.version")) (System/getProperty "clojure-through-code.version") Chaining a few Clojure functions together , to read from the Leiningen project file Information can be read from the Clojure project.clj file using the slurp function (slurp "project.clj") = > " ( defproject clojure - through - code \"20.1.5 - SNAPSHOT\"\n : description \"Learning Clojure by evaluating code on the fly\"\n : url \"\"\n : license { : name \"Eclipse Public License\"\n : url \" / legal / epl - v10.html\"}\n : dependencies [ [ org.clojure/clojure \"1.6.0\"]])\n\n " (read-string (slurp "project.clj")) = > ( defproject clojure - through - code " 20.1.5 - SNAPSHOT " : description " Learning Clojure by evaluating code on the fly " : url " " : license { : name " Eclipse Public License " , : url " -v10.html " } : dependencies [ [ org.clojure/clojure " 1.6.0 " ] ] ) (nth (read-string (slurp "project.clj")) 2) = > " 20.1.5 - SNAPSHOT " Select just the third string using nth 2 ( using an index starting at 0 ) (nth (read-string (slurp "project.clj")) 2) (-> "./project.clj" slurp read-string (nth 2)) (-> "./project.clj" slurp ,,, read-string ,,, (nth ,,, 2)) joins its own strings together , then passes them as a single string as the first argument to the next function (-> (str "This" " " "is" " ") (str "the" " " "treading" " " "macro" " ") (str "in" " " "action.")) (->> (str "This" " ") (str "is" " ") (str "backwards" " ")) (-> [2 5 4 1 3 6] (reverse) (rest) (sort) (last)) (->> "project.clj" slurp read-string (drop 2) (cons :version) (apply hash-map) (def project)) If you use a print or println function in a threading macro , then part of the value will be lost , as those functions return a value of nil . (-> "message" (str " " "in a bottle") println (str ", The Police")) The initial part of the message before the println funciton is called has been dropped because println returned nil . Therefore nil was the value passed as the first argument to tne next function , rather than " message in a bottle " . (doto "message in a bottle" println) (-> "Message" (str " " "in a bottle") (doto println) (str " - " "The Police")) (def fred "I am free") (def five 5) (def five 6) (def five [1 2 3 4 5 6 7 8]) five (reduce + five) (reduce + [1 2 3 4 5 6 7 8]) = > 36 (defn my-function [] (str "I wish I was fred")) (def my-function (fn [args] (str "behaviour"))) (fn [args] (str "behaviour")) add three ( fn [ num ] ( + num 3 ) ) add 3 arguments ( fn [ arg1 arg2 arg3 ] ( + arg1 arg2 arg3 4 5 ) ) You could use the Java - like function ` println ` to output strings . (println "Hello, whats different with me? What value do I return") However , something different happens when you evaluate this expression . This is refered to as a side - effect because when you call this function it returns nil . The actual text is output to the REPL or console . In Clojure , you are more likely to use the ` str ` function when working with strings . (str "Hello, I am returned as a value of this expression") (str "Hello" ", " "HackTheTower UK") using println in LightTable shows the results in console window , as its a side affect Simple math to show you the basic structure of Clojure (+ 3 (/ 4 2) (* 3 5)) (+ 1 1 2489 459 2.7) (-> (+ 12 144 20 (* 3 (Math/sqrt 4))) (/ 7) (+ (* 5 11)) (= (+ 0.0 (* 9 9)))) (Math/sqrt 4) = > 1 = > 2 (/ 1 2) (type (/ 22 7.0)) (/ 5000 20000) (type (Integer. "2")) The above is the same as the Java statement Integer myInt = new Integer("2 " ) (/ (* 22/7 3) 3) Clojure uses Prefix notation , so math operations on many arguments is easy . (+ 1 2 3 4 5) (+ 1 2 (* 3 4) (- 5 6 -7)) (+) (*) (* 2) (+ 4) Variadic functions (+ 1 2 3) (< 1 2 3) (< 1 3 8 4) ( remaining 22 7 ) (inc 3) (dec 4) (min 1 2 3 5 8 13) (max 1 2 3 5 8 13) (apply + [1 2 3]) (reduce + [1 2 3]) (apply / [1 2 3]) (/ 53) (map + [1 2 3.0] [4.0 5 6]) (repeat 4 9) (identical? "foo" "bar") (identical? "foo" "foo") (= "foo" "bar") (= "foo" "foo") (identical? :foo :bar) (identical? :foo :foo) (def my-map {:foo "a"}) (= "a" (:foo my-map)) Truethy experiments (+) (class (+)) (*) (true? +) (false? +) (true? *) (false? *) (true? 1) (true? -1) (true? true) (true? (not false)) (- 2) (= 4 (inc 2)) (if false "hello" (do (+ 3 4) (str "goodbye"))) (if false "one" "two") (if nil "uh" "oh") (if false "Hello word" "Goodbye crule world") (cond (zero? (- (* 4 2) 8)) (= 4 (inc 2)) (= 4 (/ 8 2)) (= "Hello World" (str "Hello " "World")) :otherwise "None of the above.") (cond (= 7 (inc 2)) "(inc 2) is not 7, so this condition is false" (= 16 (* 8 2)) "This is the first correct condition so its associated expression is returned" (zero? (- (* 8 8) 64)) "This is true but not returned as a previous condition is true" :otherwise "None of the above are true") (when (> 8 2) "Higher") (true? true) (true? (not true)) (true? false) (true? (not false)) (true? nil) Clojure uses Java 's object types for booleans , strings and numbers . (class 1) Integer literals are java.lang . Long by default (class "") (class (list 1 2 3 4)) (class true) (class ()) (class (list 1 2 34 5)) (class (str 2 3 4 5)) (class (+ 22/7)) (class 5) (class "fish") (type [1 2 3]) (type {:a 1 :b 2}) (type (take 3 (range 10))) (take 10 (range)) (type (Integer. "8080")) (type "This is a string") (type '(1 2 3 4)) (type 1) (type "I am a string") (type :i-am-a-keyword) (type 22/7) (type 'def) (type 'defn) (type '(1 2 3 4)) (type [1 2 3 4]) (type {:a 1 :b 2}) (type #{1 2 3 4}) To help maintain the precision of numbers , Clojure has a type called Ratio (/ 2) A classic example is dividing 22 by 7 which is approximately the value of Pi (/ 22 7) (class (/ 22 7)) If you want to force Clojure to evaluate this then you can specify one of the (class (/ 22 7.0)) (/ 14 4) 7/2 (* (/ 22 7) 7) (type 7.0) (instance? String "hello") (instance? Double 3.14) (instance? Number 3.14) (instance? java.util.Date #inst "2015-01-01") ArithmeticException Divide by zero clojure.lang.Numbers.divide ( Numbers.java:156 ) java.lang . * packages are included in all Clojure projects , so you can call the (Math/sqrt 4) (Math/sqrt 13) (Math/PI) (.toUpperCase "bla") Lets have some maths fun and see how Clojure deals with this (Math/sqrt -1) So Clojure , well Java really as its the Java Math class methods , deals with interesting So what does NaN mean . Well by consulting Stack Overflow , a NaN is produced if a floating point operation would produce an undefinable result . Other examples include dividing 0.0 by 0.0 is arithmetically undefined . Clojure projects Install Leiningen build tool from leingingen.org Create a new project with new project - name Run the repl using repl The project is defined as Clojure code using defproject macro , keywords , maps & vectors Namespaces are similar to packages in Java (namespace 'clojure-through-code.01-basics/my-map) (name 'clojure-through-code.01-basics/my-map) Clojure functions have Documentation - in LightTable you can right - click on a function name and select " show docs " (class []) (map? [1 2 3 4]) LightTable Settings The configuration in LightTable uses a Clojure syntax datastructure , a map with Clojure keywords to make it General configuration settings for LightTable - eg , , themes , editor settings 0 2 user > ( def x [ [ 1 2 3 ] [ 4 5 6 ] ] ) 1 user > ( first x ) ArityException Wrong number of args ( 2 ) passed to : core / assoc clojure.lang . AFn.throwArity ( AFn.java:429 ) user > ( assoc nil : a 1 ) { : a 1 } user > ( filter identity @)RuntimeException Unmatched delimiter : ) clojure.lang . Util.runtimeException ( Util.java:221 ) Paredit (def a "I have a name") (class :a) (get {"a" "ay"} "a") (get-in {"a" {"aa" "You found me"}} ["a" "aa"]) (let [reason "sick"] (cond (= reason "sick") "I ache all over and am seeing green elephant-shaped spots" (= reason "train") "That darn Southern Rail on strike again" (= reason "pet") "My pet ate my homework")) (let [greeting :fr] (case greeting :fr "bonjour monde clojure" :en "hello clojure world" :it "ciao mondo clojure" :es "hola mundo clojure")) (let [language :fr message (case language :fr "bonjour monde clojure" :en "hello clojure world" :it "ciao mondo clojure" :es "hola mundo clojure") upper-case? true] (if upper-case? (clojure.string/upper-case message) message)) (let [reason "sick"] (cond (= reason "sick") "I ache all over and am seeing green elephant-shaped spots" (= reason "train") "That darn Southern Rail on strike again" (= reason "pet") "My pet ate my homework")) (def my-details ["John" "Stevenson" "37" "Clojure" "London" "North Yorkshire" 12]) (first my-details) (second my-details) (rest my-details) (nth ["John" "Stevenson" "37" "Clojure" "London" "North Yorkshire" 12] 2) (nth my-details 0) (first my-details) (first "John") (str (nth "John" 0)) ["string" ["fish" "rabit"]] {:key ["value1" "value2"]} {:bicycle ["wheels" "frame" "handlbars"]} {:meal ["starter" "main course" "desert"]} {:meal ["starter" ["soup" "bread rolls"] "main course" ["fish" "chips" "mushy peas"] "desert" ["cheese" "wine"]]} {:meal {"starter" ["soup" "bread rolls"] "main course" ["fish" "chips" "mushy peas"] "desert" ["cheese" "wine"]}} {:meal {:starter ["soup" "bread rolls"] :main-course ["fish" "chips" "mushy peas"] :desert ["cheese" "wine"]}} {:meal {:ingredience [] :recipe []}}
e22cf5a4671acc80357915fac90aaf4f7d35a40f74aabbecf80fc95a09451d7c
txyyss/Project-Euler
Euler138.hs
-- Special isosceles triangles module Euler138 where -- Detailed analysis can be found in -- -euler-138-special-isosceles-triangles/ result138 = sum $ map (abs . snd) $ tail $ take 13 $ iterate helper (0,1) where helper (x,y) = (- 9 * x - 4 * y - 4, - 20 * x - 9 * y - 8)
null
https://raw.githubusercontent.com/txyyss/Project-Euler/d2f41dad429013868445c1c9c1c270b951550ee9/Euler138.hs
haskell
Special isosceles triangles Detailed analysis can be found in -euler-138-special-isosceles-triangles/
module Euler138 where result138 = sum $ map (abs . snd) $ tail $ take 13 $ iterate helper (0,1) where helper (x,y) = (- 9 * x - 4 * y - 4, - 20 * x - 9 * y - 8)
e5a57475aa4138879435ee54983d0b819f6cf916590e35dd785c4b98ddf43cd4
mtakuya/gauche-yahoo-jp
news-topicslog.scm
#!/usr/bin/env gosh (use yahoo-jp) (define appid "YOUR-APPID") (define yahoo-obj (make-yahoo-jp appid)) (define res (yahoo:news-topicslog yahoo-obj '((category "computer") (startdate "20100301") (results "5")))) (for-each (lambda (lst) (display (topicslog-topicname lst)) (newline) (display (topicslog-url lst)) (newline)) res)
null
https://raw.githubusercontent.com/mtakuya/gauche-yahoo-jp/3abdbf3b10d3db1923329e41b3a8d8cff5796413/example/news-topicslog.scm
scheme
#!/usr/bin/env gosh (use yahoo-jp) (define appid "YOUR-APPID") (define yahoo-obj (make-yahoo-jp appid)) (define res (yahoo:news-topicslog yahoo-obj '((category "computer") (startdate "20100301") (results "5")))) (for-each (lambda (lst) (display (topicslog-topicname lst)) (newline) (display (topicslog-url lst)) (newline)) res)
f03273f6b0091444699a9ccb96f5b133ab01a6d3fbe5c10210ecf73761a2bf61
NorfairKing/sydtest
Webdriver.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE NumericUnderscores # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # -- Because of webdriver using dangerous constructors # OPTIONS_GHC -fno - warn - incomplete - record - updates # -- For the undefined trick # OPTIONS_GHC -fno - warn - unused - pattern - binds # module Test.Syd.Webdriver ( -- * Defining webdriver tests WebdriverSpec, webdriverSpec, WebdriverTestM (..), runWebdriverTestM, WebdriverTestEnv (..), webdriverTestEnvSetupFunc, -- * Writing webdriver tests openPath, setWindowSize, -- * Running a selenium server SeleniumServerHandle (..), seleniumServerSetupFunc, ) where import Control.Monad.Base import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Aeson as JSON import GHC.Stack import Network.HTTP.Client as HTTP import Network.Socket import Network.Socket.Free import Network.Socket.Wait as Port import Network.URI import Path import Path.IO import System.Exit import System.Process.Typed import Test.Syd import Test.Syd.Path import Test.Syd.Process.Typed import Test.Syd.Wai import Test.WebDriver as WD hiding (setWindowSize) import Test.WebDriver.Class (WebDriver (..)) import qualified Test.WebDriver.Commands.Internal as WD import qualified Test.WebDriver.JSON as WD import Test.WebDriver.Session (WDSessionState (..)) -- | Type synonym for webdriver tests type WebdriverSpec app = TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app) -- | A monad for webdriver tests. This instantiates the ' WebDriver ' class , as well as the ' IsTest ' class . newtype WebdriverTestM app a = WebdriverTestM { unWebdriverTestM :: ReaderT (WebdriverTestEnv app) WD a } deriving ( Functor, Applicative, Monad, MonadIO, MonadReader (WebdriverTestEnv app), We do n't want ' MonadBaseControl IO ' or ' MonadBase IO ' , but we have to because webdriver uses them . MonadBaseControl IO, MonadBase IO ) data WebdriverTestEnv app = WebdriverTestEnv { -- | The base url of the app we test, so that we can test external sites just like local ones. webdriverTestEnvURI :: !URI, -- | The webdriver configuration webdriverTestEnvConfig :: !WDConfig, -- | The app that we'll test. -- You can put any piece of data here . In the case of yesod tests , we 'll put an @App@ here . webdriverTestEnvApp :: !app } instance WDSessionState (WebdriverTestM app) where getSession = WebdriverTestM getSession putSession = WebdriverTestM . putSession instance WebDriver (WebdriverTestM app) where doCommand m p a = WebdriverTestM $ doCommand m p a instance IsTest (WebdriverTestM app ()) where type Arg1 (WebdriverTestM app ()) = () type Arg2 (WebdriverTestM app ()) = WebdriverTestEnv app runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc) instance IsTest (WebdriverTestM app (GoldenTest a)) where type Arg1 (WebdriverTestM app (GoldenTest a)) = () type Arg2 (WebdriverTestM app (GoldenTest a)) = WebdriverTestEnv app runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc) -- | Run a webdriver test. runWebdriverTestM :: WebdriverTestEnv app -> WebdriverTestM app a -> IO a runWebdriverTestM env (WebdriverTestM func) = WD.runSession (webdriverTestEnvConfig env) $ WD.finallyClose $ do setImplicitWait 10_000 setScriptTimeout 10_000 setPageLoadTimeout 10_000 runReaderT func env | Open a page on the URI in the ' WebdriverTestEnv ' . openPath :: String -> WebdriverTestM app () openPath p = do uri <- asks webdriverTestEnvURI let url = show uri <> p openPage url -- We have to override this because it returns something. -- So we remove the 'noReturn'. setWindowSize :: (HasCallStack, WebDriver wd) => | ( Width , ) (Word, Word) -> wd () setWindowSize (w, h) = WD.ignoreReturn $ WD.doWinCommand methodPost currentWindow "/size" $ object ["width" .= w, "height" .= h] webdriverSpec :: (HTTP.Manager -> SetupFunc (URI, app)) -> WebdriverSpec app -> Spec webdriverSpec appSetupFunc = managerSpec . modifyMaxSuccess (`div` 50) . setupAroundWith' (\man () -> appSetupFunc man) . setupAroundAll seleniumServerSetupFunc . webdriverTestEnvSpec webdriverTestEnvSpec :: TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app) -> TestDef '[SeleniumServerHandle, HTTP.Manager] (URI, app) webdriverTestEnvSpec = setupAroundWith' go2 . setupAroundWith' go1 where go1 :: SeleniumServerHandle -> (SeleniumServerHandle -> SetupFunc (WebdriverTestEnv app)) -> SetupFunc (WebdriverTestEnv app) go1 ssh func = func ssh go2 :: HTTP.Manager -> (URI, app) -> SetupFunc (SeleniumServerHandle -> SetupFunc (WebdriverTestEnv app)) go2 man (uri, app) = pure $ \ssh -> webdriverTestEnvSetupFunc ssh man uri app -- | Set up a 'WebdriverTestEnv' for your app by readying a webdriver session webdriverTestEnvSetupFunc :: SeleniumServerHandle -> HTTP.Manager -> URI -> app -> SetupFunc (WebdriverTestEnv app) webdriverTestEnvSetupFunc SeleniumServerHandle {..} manager uri app = do chromeExecutable <- liftIO $ do chromeFile <- parseRelFile "chromium" mExecutable <- findExecutable chromeFile case mExecutable of Nothing -> die "No chromium found on PATH." Just executable -> pure executable let browser = chrome { chromeOptions = [ -- We don't set the --user-data-dir because it makes the -- chromedriver timeout for unknown reasons. -- "--user-data-dir=" "--headless", -- Bypass OS security model to run on nix as well "--no-sandbox", -- No need for a GPU in headless mode? "--disable-gpu", -- Overcome limited resource problem "--disable-dev-shm-usage", Normalise setup for screenshots "--use-gl=angle", "--use-angle=swiftshader", "--window-size=1920,1080", -- So that screenshots tests don't start failing when something new is added at the bottom of the page that isn't even on the screen "--hide-scrollbars" ], chromeBinary = Just $ fromAbsFile chromeExecutable } let caps = WD.defaultCaps { browser = browser } let webdriverTestEnvConfig = WD.defaultConfig { wdPort = (fromIntegral :: PortNumber -> Int) seleniumServerHandlePort, wdHTTPManager = Just manager, wdCapabilities = caps } let webdriverTestEnvURI = uri webdriverTestEnvApp = app pure WebdriverTestEnv {..} data SeleniumServerHandle = SeleniumServerHandle { seleniumServerHandlePort :: PortNumber } -- | Run, and clean up, a selenium server seleniumServerSetupFunc :: SetupFunc SeleniumServerHandle seleniumServerSetupFunc = do tempDir <- tempDirSetupFunc "selenium-server" portInt <- liftIO getFreePort let processConfig = setStdout nullStream $ setStderr nullStream $ setWorkingDir (fromAbsDir tempDir) $ proc "selenium-server" [ "-port", show portInt ] _ <- typedProcessSetupFunc processConfig liftIO $ Port.wait "127.0.0.1" portInt let seleniumServerHandlePort = fromIntegral portInt pure SeleniumServerHandle {..}
null
https://raw.githubusercontent.com/NorfairKing/sydtest/74fc91867dca88c0d22faae1a0bfcd027d74e4b8/sydtest-webdriver/src/Test/Syd/Webdriver.hs
haskell
# LANGUAGE OverloadedStrings # Because of webdriver using dangerous constructors For the undefined trick * Defining webdriver tests * Writing webdriver tests * Running a selenium server | Type synonym for webdriver tests | A monad for webdriver tests. | The base url of the app we test, so that we can test external sites just like local ones. | The webdriver configuration | The app that we'll test. | Run a webdriver test. We have to override this because it returns something. So we remove the 'noReturn'. | Set up a 'WebdriverTestEnv' for your app by readying a webdriver session We don't set the --user-data-dir because it makes the chromedriver timeout for unknown reasons. "--user-data-dir=" Bypass OS security model to run on nix as well No need for a GPU in headless mode? Overcome limited resource problem So that screenshots tests don't start failing when something new is added at the bottom of the page that isn't even on the screen | Run, and clean up, a selenium server
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE NumericUnderscores # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - incomplete - record - updates # # OPTIONS_GHC -fno - warn - unused - pattern - binds # module Test.Syd.Webdriver WebdriverSpec, webdriverSpec, WebdriverTestM (..), runWebdriverTestM, WebdriverTestEnv (..), webdriverTestEnvSetupFunc, openPath, setWindowSize, SeleniumServerHandle (..), seleniumServerSetupFunc, ) where import Control.Monad.Base import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Aeson as JSON import GHC.Stack import Network.HTTP.Client as HTTP import Network.Socket import Network.Socket.Free import Network.Socket.Wait as Port import Network.URI import Path import Path.IO import System.Exit import System.Process.Typed import Test.Syd import Test.Syd.Path import Test.Syd.Process.Typed import Test.Syd.Wai import Test.WebDriver as WD hiding (setWindowSize) import Test.WebDriver.Class (WebDriver (..)) import qualified Test.WebDriver.Commands.Internal as WD import qualified Test.WebDriver.JSON as WD import Test.WebDriver.Session (WDSessionState (..)) type WebdriverSpec app = TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app) This instantiates the ' WebDriver ' class , as well as the ' IsTest ' class . newtype WebdriverTestM app a = WebdriverTestM { unWebdriverTestM :: ReaderT (WebdriverTestEnv app) WD a } deriving ( Functor, Applicative, Monad, MonadIO, MonadReader (WebdriverTestEnv app), We do n't want ' MonadBaseControl IO ' or ' MonadBase IO ' , but we have to because webdriver uses them . MonadBaseControl IO, MonadBase IO ) data WebdriverTestEnv app = WebdriverTestEnv webdriverTestEnvURI :: !URI, webdriverTestEnvConfig :: !WDConfig, You can put any piece of data here . In the case of yesod tests , we 'll put an @App@ here . webdriverTestEnvApp :: !app } instance WDSessionState (WebdriverTestM app) where getSession = WebdriverTestM getSession putSession = WebdriverTestM . putSession instance WebDriver (WebdriverTestM app) where doCommand m p a = WebdriverTestM $ doCommand m p a instance IsTest (WebdriverTestM app ()) where type Arg1 (WebdriverTestM app ()) = () type Arg2 (WebdriverTestM app ()) = WebdriverTestEnv app runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc) instance IsTest (WebdriverTestM app (GoldenTest a)) where type Arg1 (WebdriverTestM app (GoldenTest a)) = () type Arg2 (WebdriverTestM app (GoldenTest a)) = WebdriverTestEnv app runTest wdTestFunc = runTest (\() wdte -> runWebdriverTestM wdte wdTestFunc) runWebdriverTestM :: WebdriverTestEnv app -> WebdriverTestM app a -> IO a runWebdriverTestM env (WebdriverTestM func) = WD.runSession (webdriverTestEnvConfig env) $ WD.finallyClose $ do setImplicitWait 10_000 setScriptTimeout 10_000 setPageLoadTimeout 10_000 runReaderT func env | Open a page on the URI in the ' WebdriverTestEnv ' . openPath :: String -> WebdriverTestM app () openPath p = do uri <- asks webdriverTestEnvURI let url = show uri <> p openPage url setWindowSize :: (HasCallStack, WebDriver wd) => | ( Width , ) (Word, Word) -> wd () setWindowSize (w, h) = WD.ignoreReturn $ WD.doWinCommand methodPost currentWindow "/size" $ object ["width" .= w, "height" .= h] webdriverSpec :: (HTTP.Manager -> SetupFunc (URI, app)) -> WebdriverSpec app -> Spec webdriverSpec appSetupFunc = managerSpec . modifyMaxSuccess (`div` 50) . setupAroundWith' (\man () -> appSetupFunc man) . setupAroundAll seleniumServerSetupFunc . webdriverTestEnvSpec webdriverTestEnvSpec :: TestDef '[SeleniumServerHandle, HTTP.Manager] (WebdriverTestEnv app) -> TestDef '[SeleniumServerHandle, HTTP.Manager] (URI, app) webdriverTestEnvSpec = setupAroundWith' go2 . setupAroundWith' go1 where go1 :: SeleniumServerHandle -> (SeleniumServerHandle -> SetupFunc (WebdriverTestEnv app)) -> SetupFunc (WebdriverTestEnv app) go1 ssh func = func ssh go2 :: HTTP.Manager -> (URI, app) -> SetupFunc (SeleniumServerHandle -> SetupFunc (WebdriverTestEnv app)) go2 man (uri, app) = pure $ \ssh -> webdriverTestEnvSetupFunc ssh man uri app webdriverTestEnvSetupFunc :: SeleniumServerHandle -> HTTP.Manager -> URI -> app -> SetupFunc (WebdriverTestEnv app) webdriverTestEnvSetupFunc SeleniumServerHandle {..} manager uri app = do chromeExecutable <- liftIO $ do chromeFile <- parseRelFile "chromium" mExecutable <- findExecutable chromeFile case mExecutable of Nothing -> die "No chromium found on PATH." Just executable -> pure executable let browser = chrome { chromeOptions = "--headless", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", Normalise setup for screenshots "--use-gl=angle", "--use-angle=swiftshader", "--window-size=1920,1080", "--hide-scrollbars" ], chromeBinary = Just $ fromAbsFile chromeExecutable } let caps = WD.defaultCaps { browser = browser } let webdriverTestEnvConfig = WD.defaultConfig { wdPort = (fromIntegral :: PortNumber -> Int) seleniumServerHandlePort, wdHTTPManager = Just manager, wdCapabilities = caps } let webdriverTestEnvURI = uri webdriverTestEnvApp = app pure WebdriverTestEnv {..} data SeleniumServerHandle = SeleniumServerHandle { seleniumServerHandlePort :: PortNumber } seleniumServerSetupFunc :: SetupFunc SeleniumServerHandle seleniumServerSetupFunc = do tempDir <- tempDirSetupFunc "selenium-server" portInt <- liftIO getFreePort let processConfig = setStdout nullStream $ setStderr nullStream $ setWorkingDir (fromAbsDir tempDir) $ proc "selenium-server" [ "-port", show portInt ] _ <- typedProcessSetupFunc processConfig liftIO $ Port.wait "127.0.0.1" portInt let seleniumServerHandlePort = fromIntegral portInt pure SeleniumServerHandle {..}
89453334e21bd8c4bd95bfdd858b3527260186ad52994c5d73ef486aad1abc58
Opetushallitus/ataru
liitepyynto_information_request_handlers.cljs
(ns ataru.virkailija.application.attachments.liitepyynto-information-request-handlers (:require [ataru.application-common.fx :refer [http]] [cljs-time.core :as c] [cljs-time.format :as f] [re-frame.core :as re-frame])) (def iso-formatter (f/formatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZ")) (def date-formatter (f/formatter "yyyy-MM-dd")) (def time-formatter (f/formatter "HH:mm")) (def datetime-formatter (f/formatter "yyyy-MM-dd HH:mm")) (defn- get-deadline-visibility-state [db application-key liitepyynto-key] (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :visibility-state] :hidden)) (defn- set-deadline-visibility-state [db application-key liitepyynto-key state] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :visibility-state] state)) (defn- set-deadline-date [db application-key liitepyynto-key value] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :date] value)) (defn- set-deadline-time [db application-key liitepyynto-key value] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :time] value)) (defn- get-deadline-last-modified [db application-key liitepyynto-key] (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified] nil)) (defn- set-deadline-last-modified [db application-key liitepyynto-key last-modified] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified] last-modified)) (defn- set-deadline [db application-key liitepyynto-key date-string time-string last-modified] (-> db (set-deadline-date application-key liitepyynto-key date-string) (set-deadline-time application-key liitepyynto-key time-string) (set-deadline-last-modified application-key liitepyynto-key last-modified))) (re-frame/reg-event-db :liitepyynto-information-request/set-deadline-visibility-state (fn [db [_ application-key liitepyynto-key state]] (set-deadline-visibility-state db application-key liitepyynto-key state))) (re-frame/reg-event-fx :liitepyynto-information-request/hide-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (let [current-state (get-deadline-visibility-state db application-key liitepyynto-key)] (when (or (= :visible current-state) (= :appearing current-state)) {:db (set-deadline-visibility-state db application-key liitepyynto-key :disappearing) :dispatch-later [{:ms 200 :dispatch [:liitepyynto-information-request/set-deadline-visibility-state application-key liitepyynto-key :hidden]}]})))) (re-frame/reg-event-fx :liitepyynto-information-request/show-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (let [current-state (get-deadline-visibility-state db application-key liitepyynto-key)] (when (or (= :hidden current-state) (= :disappearing current-state)) {:db (set-deadline-visibility-state db application-key liitepyynto-key :appearing) :dispatch-later [{:ms 200 :dispatch [:liitepyynto-information-request/set-deadline-visibility-state application-key liitepyynto-key :visible]}]})))) (re-frame/reg-event-fx :liitepyynto-information-request/set-deadline-toggle (fn [{db :db} [_ application-key liitepyynto-key on?]] {:dispatch [(cond on? :liitepyynto-information-request/show-deadline (some? (get-deadline-last-modified db application-key liitepyynto-key)) :liitepyynto-information-request/delete-deadline :else :liitepyynto-information-request/hide-deadline) application-key liitepyynto-key]})) (re-frame/reg-event-db :liitepyynto-information-request/set-deadline-date (fn [db [_ application-key liitepyynto-key value]] (set-deadline-date db application-key liitepyynto-key value))) (re-frame/reg-event-db :liitepyynto-information-request/set-deadline-time (fn [db [_ application-key liitepyynto-key value]] (set-deadline-time db application-key liitepyynto-key value))) (re-frame/reg-event-db :liitepyynto-information-request/hide-deadline-error (fn [db [_ application-key liitepyynto-key]] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :error?] false))) (re-frame/reg-event-fx :liitepyynto-information-request/show-deadline-error (fn [{db :db} [_ application-key liitepyynto-key]] {:db (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :error?] true) :dispatch-later [{:ms 5000 :dispatch [:liitepyynto-information-request/hide-deadline-error application-key liitepyynto-key]}]})) (defn- parse-deadline [deadline] (let [datetime (->> deadline (f/parse iso-formatter) c/to-default-time-zone)] [(f/unparse date-formatter datetime) (f/unparse time-formatter datetime)])) (re-frame/reg-event-fx :liitepyynto-information-request/set-deadlines (fn [{db :db} [_ application-key response]] (let [last-modified (get-in response [:headers "last-modified"])] {:db (reduce (fn [db deadline] (let [liitepyynto-key (keyword (:field-id deadline)) [date-string time-string] (parse-deadline (:deadline deadline))] (set-deadline db application-key liitepyynto-key date-string time-string last-modified))) db (:body response)) :dispatch-n (map (fn [deadline] [:liitepyynto-information-request/show-deadline application-key (keyword (:field-id deadline))]) (:body response))}))) (re-frame/reg-event-fx :liitepyynto-information-request/set-deadline (fn [{db :db} [_ application-key liitepyynto-key response]] (let [last-modified (get-in response [:headers "last-modified"]) [date-string time-string] (parse-deadline (get-in response [:body :deadline]))] {:db (set-deadline db application-key liitepyynto-key date-string time-string last-modified) :dispatch [:liitepyynto-information-request/show-deadline application-key liitepyynto-key]}))) (re-frame/reg-event-fx :liitepyynto-information-request/unset-deadline (fn [{db :db} [_ application-key liitepyynto-key _]] {:db (set-deadline db application-key liitepyynto-key "" "" nil) :dispatch [:liitepyynto-information-request/hide-deadline application-key liitepyynto-key]})) (re-frame/reg-event-db :liitepyynto-information-request/ignore-error (fn [db _] db)) (re-frame/reg-event-fx :liitepyynto-information-request/re-fetch-and-show-error (fn [_ [_ application-key liitepyynto-key _]] {:liitepyynto-information-request/get-deadline {:application-key application-key :liitepyynto-key liitepyynto-key} :dispatch [:liitepyynto-information-request/show-deadline-error application-key liitepyynto-key]})) (re-frame/reg-event-fx :liitepyynto-information-request/get-deadlines (fn [_ [_ application-key]] {:liitepyynto-information-request/get-deadlines {:application-key application-key}})) (re-frame/reg-event-fx :liitepyynto-information-request/debounced-save-deadline (fn [_ [_ application-key liitepyynto-key]] {:dispatch-debounced {:timeout 500 :id [:liitepyynto-information-request/save-deadline application-key liitepyynto-key] :dispatch [:liitepyynto-information-request/save-deadline application-key liitepyynto-key]}})) (re-frame/reg-event-fx :liitepyynto-information-request/save-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (let [date (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :date]) time (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :time]) last-modified (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified])] (when-let [datetime (try (->> (str date " " time) (f/parse-local datetime-formatter) c/to-utc-time-zone) (catch js/Error e nil))] {:liitepyynto-information-request/save-deadline {:application-key application-key :liitepyynto-key liitepyynto-key :deadline datetime :last-modified last-modified}})))) (re-frame/reg-event-fx :liitepyynto-information-request/delete-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (when-let [last-modified (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified])] {:liitepyynto-information-request/delete-deadline {:application-key application-key :liitepyynto-key liitepyynto-key :last-modified last-modified}}))) (re-frame/reg-fx :liitepyynto-information-request/get-deadlines (fn [{:keys [application-key]}] (http (aget js/config "virkailija-caller-id") {:method :get :url (str "/lomake-editori/api/applications/" application-key "/field-deadline") :handler [:liitepyynto-information-request/set-deadlines application-key] :error-handler [:liitepyynto-information-request/ignore-error]}))) (re-frame/reg-fx :liitepyynto-information-request/get-deadline (fn [{:keys [application-key liitepyynto-key]}] (http (aget js/config "virkailija-caller-id") {:method :get :url (str "/lomake-editori/api/applications/" application-key "/field-deadline/" (name liitepyynto-key)) :handler [:liitepyynto-information-request/set-deadline application-key liitepyynto-key] :error-handler [:liitepyynto-information-request/unset-deadline application-key liitepyynto-key]}))) (re-frame/reg-fx :liitepyynto-information-request/save-deadline (fn [{:keys [application-key liitepyynto-key deadline last-modified]}] (http (aget js/config "virkailija-caller-id") {:method :put :url (str "/lomake-editori/api/applications/" application-key "/field-deadline/" (name liitepyynto-key)) :post-data {:deadline (f/unparse iso-formatter deadline)} :headers (if (some? last-modified) {"If-Unmodified-Since" last-modified} {"If-None-Match" "*"}) :handler [:liitepyynto-information-request/set-deadline application-key liitepyynto-key] :error-handler [:liitepyynto-information-request/re-fetch-and-show-error application-key liitepyynto-key]}))) (re-frame/reg-fx :liitepyynto-information-request/delete-deadline (fn [{:keys [application-key liitepyynto-key last-modified]}] (http (aget js/config "virkailija-caller-id") {:method :delete :url (str "/lomake-editori/api/applications/" application-key "/field-deadline/" (name liitepyynto-key)) :headers {"If-Unmodified-Since" last-modified} :handler [:liitepyynto-information-request/unset-deadline application-key liitepyynto-key] :error-handler [:liitepyynto-information-request/re-fetch-and-show-error application-key liitepyynto-key]})))
null
https://raw.githubusercontent.com/Opetushallitus/ataru/2d8ef1d3f972621e301a3818567d4e11219d2e82/src/cljs/ataru/virkailija/application/attachments/liitepyynto_information_request_handlers.cljs
clojure
(ns ataru.virkailija.application.attachments.liitepyynto-information-request-handlers (:require [ataru.application-common.fx :refer [http]] [cljs-time.core :as c] [cljs-time.format :as f] [re-frame.core :as re-frame])) (def iso-formatter (f/formatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZ")) (def date-formatter (f/formatter "yyyy-MM-dd")) (def time-formatter (f/formatter "HH:mm")) (def datetime-formatter (f/formatter "yyyy-MM-dd HH:mm")) (defn- get-deadline-visibility-state [db application-key liitepyynto-key] (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :visibility-state] :hidden)) (defn- set-deadline-visibility-state [db application-key liitepyynto-key state] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :visibility-state] state)) (defn- set-deadline-date [db application-key liitepyynto-key value] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :date] value)) (defn- set-deadline-time [db application-key liitepyynto-key value] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :time] value)) (defn- get-deadline-last-modified [db application-key liitepyynto-key] (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified] nil)) (defn- set-deadline-last-modified [db application-key liitepyynto-key last-modified] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified] last-modified)) (defn- set-deadline [db application-key liitepyynto-key date-string time-string last-modified] (-> db (set-deadline-date application-key liitepyynto-key date-string) (set-deadline-time application-key liitepyynto-key time-string) (set-deadline-last-modified application-key liitepyynto-key last-modified))) (re-frame/reg-event-db :liitepyynto-information-request/set-deadline-visibility-state (fn [db [_ application-key liitepyynto-key state]] (set-deadline-visibility-state db application-key liitepyynto-key state))) (re-frame/reg-event-fx :liitepyynto-information-request/hide-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (let [current-state (get-deadline-visibility-state db application-key liitepyynto-key)] (when (or (= :visible current-state) (= :appearing current-state)) {:db (set-deadline-visibility-state db application-key liitepyynto-key :disappearing) :dispatch-later [{:ms 200 :dispatch [:liitepyynto-information-request/set-deadline-visibility-state application-key liitepyynto-key :hidden]}]})))) (re-frame/reg-event-fx :liitepyynto-information-request/show-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (let [current-state (get-deadline-visibility-state db application-key liitepyynto-key)] (when (or (= :hidden current-state) (= :disappearing current-state)) {:db (set-deadline-visibility-state db application-key liitepyynto-key :appearing) :dispatch-later [{:ms 200 :dispatch [:liitepyynto-information-request/set-deadline-visibility-state application-key liitepyynto-key :visible]}]})))) (re-frame/reg-event-fx :liitepyynto-information-request/set-deadline-toggle (fn [{db :db} [_ application-key liitepyynto-key on?]] {:dispatch [(cond on? :liitepyynto-information-request/show-deadline (some? (get-deadline-last-modified db application-key liitepyynto-key)) :liitepyynto-information-request/delete-deadline :else :liitepyynto-information-request/hide-deadline) application-key liitepyynto-key]})) (re-frame/reg-event-db :liitepyynto-information-request/set-deadline-date (fn [db [_ application-key liitepyynto-key value]] (set-deadline-date db application-key liitepyynto-key value))) (re-frame/reg-event-db :liitepyynto-information-request/set-deadline-time (fn [db [_ application-key liitepyynto-key value]] (set-deadline-time db application-key liitepyynto-key value))) (re-frame/reg-event-db :liitepyynto-information-request/hide-deadline-error (fn [db [_ application-key liitepyynto-key]] (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :error?] false))) (re-frame/reg-event-fx :liitepyynto-information-request/show-deadline-error (fn [{db :db} [_ application-key liitepyynto-key]] {:db (assoc-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :error?] true) :dispatch-later [{:ms 5000 :dispatch [:liitepyynto-information-request/hide-deadline-error application-key liitepyynto-key]}]})) (defn- parse-deadline [deadline] (let [datetime (->> deadline (f/parse iso-formatter) c/to-default-time-zone)] [(f/unparse date-formatter datetime) (f/unparse time-formatter datetime)])) (re-frame/reg-event-fx :liitepyynto-information-request/set-deadlines (fn [{db :db} [_ application-key response]] (let [last-modified (get-in response [:headers "last-modified"])] {:db (reduce (fn [db deadline] (let [liitepyynto-key (keyword (:field-id deadline)) [date-string time-string] (parse-deadline (:deadline deadline))] (set-deadline db application-key liitepyynto-key date-string time-string last-modified))) db (:body response)) :dispatch-n (map (fn [deadline] [:liitepyynto-information-request/show-deadline application-key (keyword (:field-id deadline))]) (:body response))}))) (re-frame/reg-event-fx :liitepyynto-information-request/set-deadline (fn [{db :db} [_ application-key liitepyynto-key response]] (let [last-modified (get-in response [:headers "last-modified"]) [date-string time-string] (parse-deadline (get-in response [:body :deadline]))] {:db (set-deadline db application-key liitepyynto-key date-string time-string last-modified) :dispatch [:liitepyynto-information-request/show-deadline application-key liitepyynto-key]}))) (re-frame/reg-event-fx :liitepyynto-information-request/unset-deadline (fn [{db :db} [_ application-key liitepyynto-key _]] {:db (set-deadline db application-key liitepyynto-key "" "" nil) :dispatch [:liitepyynto-information-request/hide-deadline application-key liitepyynto-key]})) (re-frame/reg-event-db :liitepyynto-information-request/ignore-error (fn [db _] db)) (re-frame/reg-event-fx :liitepyynto-information-request/re-fetch-and-show-error (fn [_ [_ application-key liitepyynto-key _]] {:liitepyynto-information-request/get-deadline {:application-key application-key :liitepyynto-key liitepyynto-key} :dispatch [:liitepyynto-information-request/show-deadline-error application-key liitepyynto-key]})) (re-frame/reg-event-fx :liitepyynto-information-request/get-deadlines (fn [_ [_ application-key]] {:liitepyynto-information-request/get-deadlines {:application-key application-key}})) (re-frame/reg-event-fx :liitepyynto-information-request/debounced-save-deadline (fn [_ [_ application-key liitepyynto-key]] {:dispatch-debounced {:timeout 500 :id [:liitepyynto-information-request/save-deadline application-key liitepyynto-key] :dispatch [:liitepyynto-information-request/save-deadline application-key liitepyynto-key]}})) (re-frame/reg-event-fx :liitepyynto-information-request/save-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (let [date (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :date]) time (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :time]) last-modified (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified])] (when-let [datetime (try (->> (str date " " time) (f/parse-local datetime-formatter) c/to-utc-time-zone) (catch js/Error e nil))] {:liitepyynto-information-request/save-deadline {:application-key application-key :liitepyynto-key liitepyynto-key :deadline datetime :last-modified last-modified}})))) (re-frame/reg-event-fx :liitepyynto-information-request/delete-deadline (fn [{db :db} [_ application-key liitepyynto-key]] (when-let [last-modified (get-in db [:liitepyynto-information-request application-key liitepyynto-key :deadline :last-modified])] {:liitepyynto-information-request/delete-deadline {:application-key application-key :liitepyynto-key liitepyynto-key :last-modified last-modified}}))) (re-frame/reg-fx :liitepyynto-information-request/get-deadlines (fn [{:keys [application-key]}] (http (aget js/config "virkailija-caller-id") {:method :get :url (str "/lomake-editori/api/applications/" application-key "/field-deadline") :handler [:liitepyynto-information-request/set-deadlines application-key] :error-handler [:liitepyynto-information-request/ignore-error]}))) (re-frame/reg-fx :liitepyynto-information-request/get-deadline (fn [{:keys [application-key liitepyynto-key]}] (http (aget js/config "virkailija-caller-id") {:method :get :url (str "/lomake-editori/api/applications/" application-key "/field-deadline/" (name liitepyynto-key)) :handler [:liitepyynto-information-request/set-deadline application-key liitepyynto-key] :error-handler [:liitepyynto-information-request/unset-deadline application-key liitepyynto-key]}))) (re-frame/reg-fx :liitepyynto-information-request/save-deadline (fn [{:keys [application-key liitepyynto-key deadline last-modified]}] (http (aget js/config "virkailija-caller-id") {:method :put :url (str "/lomake-editori/api/applications/" application-key "/field-deadline/" (name liitepyynto-key)) :post-data {:deadline (f/unparse iso-formatter deadline)} :headers (if (some? last-modified) {"If-Unmodified-Since" last-modified} {"If-None-Match" "*"}) :handler [:liitepyynto-information-request/set-deadline application-key liitepyynto-key] :error-handler [:liitepyynto-information-request/re-fetch-and-show-error application-key liitepyynto-key]}))) (re-frame/reg-fx :liitepyynto-information-request/delete-deadline (fn [{:keys [application-key liitepyynto-key last-modified]}] (http (aget js/config "virkailija-caller-id") {:method :delete :url (str "/lomake-editori/api/applications/" application-key "/field-deadline/" (name liitepyynto-key)) :headers {"If-Unmodified-Since" last-modified} :handler [:liitepyynto-information-request/unset-deadline application-key liitepyynto-key] :error-handler [:liitepyynto-information-request/re-fetch-and-show-error application-key liitepyynto-key]})))
c1cefb528d6ba4ec1fe505700e5a06b7dca0e734457b072ef8d52d0e483a6c90
jdreaver/eventful
Projection.hs
# LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module Eventful.TH.Projection ( mkProjection ) where import Data.Char (toLower) import Language.Haskell.TH import SumTypes.TH import Eventful.Projection -- | Creates a 'Projection' for a given type and a list of events. The user of -- this function also needs to provide event handlers for each event. For -- example: -- -- @ data EventA = EventA data EventB = EventB -- data = -- myStateDefault : : myStateDefault = 0 -- mkProjection '' ' myStateDefault [ '' EventA , '' EventB ] -- handleEventA : : - > EventA - > handleEventA ( x ) EventA = ( x + 1 ) -- : : - > EventB - > ( x ) EventB = ( x - 1 ) -- @ -- -- This will produce the following: -- -- @ data MyStateEvent = MyStateEventA ! EventA | MyStateEventB ! -- handleMyStateEvent : : - > MyStateEvent - > handleMyStateEvent state ( MyStateEventA event ) = handleEventA state event handleMyStateEvent state ( event ) = handleEventB state event -- -- type MyStateProjection = Projection MyState MyStateEvent -- -- myStateProjection :: MyStateProjection myStateProjection = Projection myStateDefault handleMyStateEvent -- @ mkProjection :: Name -> Name -> [Name] -> Q [Dec] mkProjection stateName stateDefault events = do -- Make event sum type let eventTypeName = nameBase stateName ++ "Event" sumTypeDecls <- constructSumType eventTypeName defaultSumTypeOptions events -- Make function to handle events from sum type to handlers. let handleFuncName = mkName $ "handle" ++ eventTypeName handleFuncType <- [t| $(conT stateName) -> $(conT $ mkName eventTypeName) -> $(conT stateName) |] handleFuncBodies <- mapM (handleFuncBody stateName) events let handleTypeDecls = [ SigD handleFuncName handleFuncType , FunD handleFuncName handleFuncBodies ] -- Make the projection type projectionType <- [t| Projection $(conT stateName) $(conT $ mkName eventTypeName) |] let projectionTypeName = mkName $ nameBase stateName ++ "Projection" projectionTypeDecl = TySynD projectionTypeName [] projectionType -- Make the projection projectionFuncExpr <- [e| Projection $(varE stateDefault) $(varE handleFuncName) |] let projectionFuncName = mkName $ firstCharToLower (nameBase stateName) ++ "Projection" projectionFuncClause = Clause [] (NormalB projectionFuncExpr) [] projectionDecls = [ SigD projectionFuncName (ConT projectionTypeName) , FunD projectionFuncName [projectionFuncClause] ] return $ sumTypeDecls ++ handleTypeDecls ++ [projectionTypeDecl] ++ projectionDecls handleFuncBody :: Name -> Name -> Q Clause handleFuncBody stateName event = do let statePattern = VarP (mkName "state") eventPattern = ConP (mkName $ nameBase stateName ++ nameBase event) [VarP (mkName "event")] handleFuncName = mkName $ "handle" ++ nameBase event constructor <- [e| $(varE handleFuncName) $(varE $ mkName "state") $(varE $ mkName "event") |] return $ Clause [statePattern, eventPattern] (NormalB constructor) [] firstCharToLower :: String -> String firstCharToLower [] = [] firstCharToLower (x:xs) = toLower x : xs
null
https://raw.githubusercontent.com/jdreaver/eventful/3f0c604e5bb2dcf5bacf0a2e01edf6a5e9c5e22e/eventful-core/src/Eventful/TH/Projection.hs
haskell
| Creates a 'Projection' for a given type and a list of events. The user of this function also needs to provide event handlers for each event. For example: @ @ This will produce the following: @ type MyStateProjection = Projection MyState MyStateEvent myStateProjection :: MyStateProjection @ Make event sum type Make function to handle events from sum type to handlers. Make the projection type Make the projection
# LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module Eventful.TH.Projection ( mkProjection ) where import Data.Char (toLower) import Language.Haskell.TH import SumTypes.TH import Eventful.Projection data EventA = EventA data EventB = EventB data = myStateDefault : : myStateDefault = 0 mkProjection '' ' myStateDefault [ '' EventA , '' EventB ] handleEventA : : - > EventA - > handleEventA ( x ) EventA = ( x + 1 ) : : - > EventB - > ( x ) EventB = ( x - 1 ) data MyStateEvent = MyStateEventA ! EventA | MyStateEventB ! handleMyStateEvent : : - > MyStateEvent - > handleMyStateEvent state ( MyStateEventA event ) = handleEventA state event handleMyStateEvent state ( event ) = handleEventB state event myStateProjection = Projection myStateDefault handleMyStateEvent mkProjection :: Name -> Name -> [Name] -> Q [Dec] mkProjection stateName stateDefault events = do let eventTypeName = nameBase stateName ++ "Event" sumTypeDecls <- constructSumType eventTypeName defaultSumTypeOptions events let handleFuncName = mkName $ "handle" ++ eventTypeName handleFuncType <- [t| $(conT stateName) -> $(conT $ mkName eventTypeName) -> $(conT stateName) |] handleFuncBodies <- mapM (handleFuncBody stateName) events let handleTypeDecls = [ SigD handleFuncName handleFuncType , FunD handleFuncName handleFuncBodies ] projectionType <- [t| Projection $(conT stateName) $(conT $ mkName eventTypeName) |] let projectionTypeName = mkName $ nameBase stateName ++ "Projection" projectionTypeDecl = TySynD projectionTypeName [] projectionType projectionFuncExpr <- [e| Projection $(varE stateDefault) $(varE handleFuncName) |] let projectionFuncName = mkName $ firstCharToLower (nameBase stateName) ++ "Projection" projectionFuncClause = Clause [] (NormalB projectionFuncExpr) [] projectionDecls = [ SigD projectionFuncName (ConT projectionTypeName) , FunD projectionFuncName [projectionFuncClause] ] return $ sumTypeDecls ++ handleTypeDecls ++ [projectionTypeDecl] ++ projectionDecls handleFuncBody :: Name -> Name -> Q Clause handleFuncBody stateName event = do let statePattern = VarP (mkName "state") eventPattern = ConP (mkName $ nameBase stateName ++ nameBase event) [VarP (mkName "event")] handleFuncName = mkName $ "handle" ++ nameBase event constructor <- [e| $(varE handleFuncName) $(varE $ mkName "state") $(varE $ mkName "event") |] return $ Clause [statePattern, eventPattern] (NormalB constructor) [] firstCharToLower :: String -> String firstCharToLower [] = [] firstCharToLower (x:xs) = toLower x : xs
ebb84146d112379eeeaa8d25872bf27e97292451e8a8e8191d804829943e5017
LambdaScientist/CLaSH-by-example
TestSimpleDFlop.hs
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveAnyClass #-} module ClocksAndRegisters.TestSimpleDFlop where import CLaSH.Prelude import SAFE.TestingTools import SAFE.CommonClash import ClocksAndRegisters.Models.SimpleDFlop import Text.PrettyPrint.HughesPJClass import GHC.Generics (Generic) import Control.DeepSeq configurationList :: [Config] configurationList = [configOne, configTwo, configThree, configFour] where startSt = St 0 inputOne = signal $ PIn 0 0 configOne = Config inputOne startSt inputTwo = signal $ PIn 0 1 configTwo = Config inputTwo startSt inputThree = signal $ PIn 1 0 configThree = Config inputThree startSt startStOther = St 1 inputFour = signal $ PIn 1 1 configFour = Config inputFour startStOther ---TESTING data Config = Config { input :: Signal PIn , startSt :: St } instance NFData Config where rnf a = seq a () instance Pretty Config where pPrint Config{..} = text "Config:" $ + $ text " input = " < + > pPrint input $+$ text "startSt =" <+> pPrint startSt instance Transition Config where runOneTest = runOneTest' setupTest :: Config -> Signal St setupTest (Config pin st) = topEntity' st pin setupAndRun :: [[TestResult]] setupAndRun = runConfigList' False 5 setupTest configurationList ppSetupAndRun :: Doc ppSetupAndRun = pPrint setupAndRun ppSetupAndRun2 :: String ppSetupAndRun2 = show setupAndRun
null
https://raw.githubusercontent.com/LambdaScientist/CLaSH-by-example/e783cd2f2408e67baf7f36c10398c27036a78ef3/ConvertedClashExamples/src/ClocksAndRegisters/TestSimpleDFlop.hs
haskell
# LANGUAGE DeriveAnyClass # -TESTING
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE DeriveGeneric # module ClocksAndRegisters.TestSimpleDFlop where import CLaSH.Prelude import SAFE.TestingTools import SAFE.CommonClash import ClocksAndRegisters.Models.SimpleDFlop import Text.PrettyPrint.HughesPJClass import GHC.Generics (Generic) import Control.DeepSeq configurationList :: [Config] configurationList = [configOne, configTwo, configThree, configFour] where startSt = St 0 inputOne = signal $ PIn 0 0 configOne = Config inputOne startSt inputTwo = signal $ PIn 0 1 configTwo = Config inputTwo startSt inputThree = signal $ PIn 1 0 configThree = Config inputThree startSt startStOther = St 1 inputFour = signal $ PIn 1 1 configFour = Config inputFour startStOther data Config = Config { input :: Signal PIn , startSt :: St } instance NFData Config where rnf a = seq a () instance Pretty Config where pPrint Config{..} = text "Config:" $ + $ text " input = " < + > pPrint input $+$ text "startSt =" <+> pPrint startSt instance Transition Config where runOneTest = runOneTest' setupTest :: Config -> Signal St setupTest (Config pin st) = topEntity' st pin setupAndRun :: [[TestResult]] setupAndRun = runConfigList' False 5 setupTest configurationList ppSetupAndRun :: Doc ppSetupAndRun = pPrint setupAndRun ppSetupAndRun2 :: String ppSetupAndRun2 = show setupAndRun
64c42355d3225bc220b20aeffe4f876828f612b4ba19d6045bf6e1eba14d4acc
opennars/Narjure
set_functions.clj
(ns nal.deriver.set-functions (:require [clojure.set :as set])) ;todo performance (defn difference "Set difference precondition operation application code" [[op & set1] [_ & set2]] (into [op] (sort-by hash (set/difference (set set1) (set set2))))) (defn union [[op & set1] [_ & set2]] "Set union precondition operation application code" (into [op] (sort-by hash (set/union (set set1) (set set2))))) (defn intersection [[op & set1] [_ & set2]] "Set intersection precondition operation application code" (into [op] (sort-by hash (set/intersection (set set1) (set set2))))) (def f-map {:difference difference :union union :intersection intersection}) (defn not-empty-diff? [[_ & set1] [_ & set2]] (not-empty (set/difference (set set1) (set set2)))) (defn not-empty-inter? [[_ & set1] [_ & set2]] (not-empty (set/intersection (set set1) (set set2))))
null
https://raw.githubusercontent.com/opennars/Narjure/cd5a72e6777fc47271d721fef8362aa2dad664ca/src/nal/deriver/set_functions.clj
clojure
todo performance
(ns nal.deriver.set-functions (:require [clojure.set :as set])) (defn difference "Set difference precondition operation application code" [[op & set1] [_ & set2]] (into [op] (sort-by hash (set/difference (set set1) (set set2))))) (defn union [[op & set1] [_ & set2]] "Set union precondition operation application code" (into [op] (sort-by hash (set/union (set set1) (set set2))))) (defn intersection [[op & set1] [_ & set2]] "Set intersection precondition operation application code" (into [op] (sort-by hash (set/intersection (set set1) (set set2))))) (def f-map {:difference difference :union union :intersection intersection}) (defn not-empty-diff? [[_ & set1] [_ & set2]] (not-empty (set/difference (set set1) (set set2)))) (defn not-empty-inter? [[_ & set1] [_ & set2]] (not-empty (set/intersection (set set1) (set set2))))
d052b6dd73994ee19910d5503ab04cead2005197323ce4a24e719bb117097ece
UBTECH-Walker/WalkerSimulationFor2020WAIC
HeadPanCommand.lisp
; Auto-generated. Do not edit! (cl:in-package ubt_core_msgs-msg) ;//! \htmlinclude HeadPanCommand.msg.html (cl:defclass <HeadPanCommand> (roslisp-msg-protocol:ros-message) ((target :reader target :initarg :target :type cl:float :initform 0.0) (speed_ratio :reader speed_ratio :initarg :speed_ratio :type cl:float :initform 0.0) (enable_pan_request :reader enable_pan_request :initarg :enable_pan_request :type cl:fixnum :initform 0)) ) (cl:defclass HeadPanCommand (<HeadPanCommand>) ()) (cl:defmethod cl:initialize-instance :after ((m <HeadPanCommand>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'HeadPanCommand) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name ubt_core_msgs-msg:<HeadPanCommand> is deprecated: use ubt_core_msgs-msg:HeadPanCommand instead."))) (cl:ensure-generic-function 'target-val :lambda-list '(m)) (cl:defmethod target-val ((m <HeadPanCommand>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ubt_core_msgs-msg:target-val is deprecated. Use ubt_core_msgs-msg:target instead.") (target m)) (cl:ensure-generic-function 'speed_ratio-val :lambda-list '(m)) (cl:defmethod speed_ratio-val ((m <HeadPanCommand>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ubt_core_msgs-msg:speed_ratio-val is deprecated. Use ubt_core_msgs-msg:speed_ratio instead.") (speed_ratio m)) (cl:ensure-generic-function 'enable_pan_request-val :lambda-list '(m)) (cl:defmethod enable_pan_request-val ((m <HeadPanCommand>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ubt_core_msgs-msg:enable_pan_request-val is deprecated. Use ubt_core_msgs-msg:enable_pan_request instead.") (enable_pan_request m)) (cl:defmethod roslisp-msg-protocol:symbol-codes ((msg-type (cl:eql '<HeadPanCommand>))) "Constants for message type '<HeadPanCommand>" '((:MAX_SPEED_RATIO . 1.0) (:MIN_SPEED_RATIO . 0.0) (:REQUEST_PAN_DISABLE . 0) (:REQUEST_PAN_ENABLE . 1) (:REQUEST_PAN_VOID . 2)) ) (cl:defmethod roslisp-msg-protocol:symbol-codes ((msg-type (cl:eql 'HeadPanCommand))) "Constants for message type 'HeadPanCommand" '((:MAX_SPEED_RATIO . 1.0) (:MIN_SPEED_RATIO . 0.0) (:REQUEST_PAN_DISABLE . 0) (:REQUEST_PAN_ENABLE . 1) (:REQUEST_PAN_VOID . 2)) ) (cl:defmethod roslisp-msg-protocol:serialize ((msg <HeadPanCommand>) ostream) "Serializes a message object of type '<HeadPanCommand>" (cl:let ((bits (roslisp-utils:encode-single-float-bits (cl:slot-value msg 'target)))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)) (cl:let ((bits (roslisp-utils:encode-single-float-bits (cl:slot-value msg 'speed_ratio)))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)) (cl:write-byte (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'enable_pan_request)) ostream) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <HeadPanCommand>) istream) "Deserializes a message object of type '<HeadPanCommand>" (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'target) (roslisp-utils:decode-single-float-bits bits))) (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'speed_ratio) (roslisp-utils:decode-single-float-bits bits))) (cl:setf (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'enable_pan_request)) (cl:read-byte istream)) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<HeadPanCommand>))) "Returns string type for a message object of type '<HeadPanCommand>" "ubt_core_msgs/HeadPanCommand") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'HeadPanCommand))) "Returns string type for a message object of type 'HeadPanCommand" "ubt_core_msgs/HeadPanCommand") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<HeadPanCommand>))) "Returns md5sum for a message object of type '<HeadPanCommand>" "23b8a3f4b7ee9de7099d029e57660a8c") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'HeadPanCommand))) "Returns md5sum for a message object of type 'HeadPanCommand" "23b8a3f4b7ee9de7099d029e57660a8c") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<HeadPanCommand>))) "Returns full string definition for message of type '<HeadPanCommand>" (cl:format cl:nil "float32 target # radians for target, 0 str~%float32 speed_ratio # Percentage of max speed [0-1]~%#~% float32 MAX_SPEED_RATIO = 1.0~% float32 MIN_SPEED_RATIO = 0.0~%#~%uint8 enable_pan_request # override automatic pan enable/disable~%# enable_pan_request is tristate: 0 = disable pan; 1 = enable pan; 2 = don't change pan~% uint8 REQUEST_PAN_DISABLE = 0~% uint8 REQUEST_PAN_ENABLE = 1~% uint8 REQUEST_PAN_VOID = 2~%#~%~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'HeadPanCommand))) "Returns full string definition for message of type 'HeadPanCommand" (cl:format cl:nil "float32 target # radians for target, 0 str~%float32 speed_ratio # Percentage of max speed [0-1]~%#~% float32 MAX_SPEED_RATIO = 1.0~% float32 MIN_SPEED_RATIO = 0.0~%#~%uint8 enable_pan_request # override automatic pan enable/disable~%# enable_pan_request is tristate: 0 = disable pan; 1 = enable pan; 2 = don't change pan~% uint8 REQUEST_PAN_DISABLE = 0~% uint8 REQUEST_PAN_ENABLE = 1~% uint8 REQUEST_PAN_VOID = 2~%#~%~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <HeadPanCommand>)) (cl:+ 0 4 4 1 )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <HeadPanCommand>)) "Converts a ROS message object to a list" (cl:list 'HeadPanCommand (cl:cons ':target (target msg)) (cl:cons ':speed_ratio (speed_ratio msg)) (cl:cons ':enable_pan_request (enable_pan_request msg)) ))
null
https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_18.04_v1.2_20200616/walker_install/share/common-lisp/ros/ubt_core_msgs/msg/HeadPanCommand.lisp
lisp
Auto-generated. Do not edit! //! \htmlinclude HeadPanCommand.msg.html
(cl:in-package ubt_core_msgs-msg) (cl:defclass <HeadPanCommand> (roslisp-msg-protocol:ros-message) ((target :reader target :initarg :target :type cl:float :initform 0.0) (speed_ratio :reader speed_ratio :initarg :speed_ratio :type cl:float :initform 0.0) (enable_pan_request :reader enable_pan_request :initarg :enable_pan_request :type cl:fixnum :initform 0)) ) (cl:defclass HeadPanCommand (<HeadPanCommand>) ()) (cl:defmethod cl:initialize-instance :after ((m <HeadPanCommand>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'HeadPanCommand) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name ubt_core_msgs-msg:<HeadPanCommand> is deprecated: use ubt_core_msgs-msg:HeadPanCommand instead."))) (cl:ensure-generic-function 'target-val :lambda-list '(m)) (cl:defmethod target-val ((m <HeadPanCommand>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ubt_core_msgs-msg:target-val is deprecated. Use ubt_core_msgs-msg:target instead.") (target m)) (cl:ensure-generic-function 'speed_ratio-val :lambda-list '(m)) (cl:defmethod speed_ratio-val ((m <HeadPanCommand>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ubt_core_msgs-msg:speed_ratio-val is deprecated. Use ubt_core_msgs-msg:speed_ratio instead.") (speed_ratio m)) (cl:ensure-generic-function 'enable_pan_request-val :lambda-list '(m)) (cl:defmethod enable_pan_request-val ((m <HeadPanCommand>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ubt_core_msgs-msg:enable_pan_request-val is deprecated. Use ubt_core_msgs-msg:enable_pan_request instead.") (enable_pan_request m)) (cl:defmethod roslisp-msg-protocol:symbol-codes ((msg-type (cl:eql '<HeadPanCommand>))) "Constants for message type '<HeadPanCommand>" '((:MAX_SPEED_RATIO . 1.0) (:MIN_SPEED_RATIO . 0.0) (:REQUEST_PAN_DISABLE . 0) (:REQUEST_PAN_ENABLE . 1) (:REQUEST_PAN_VOID . 2)) ) (cl:defmethod roslisp-msg-protocol:symbol-codes ((msg-type (cl:eql 'HeadPanCommand))) "Constants for message type 'HeadPanCommand" '((:MAX_SPEED_RATIO . 1.0) (:MIN_SPEED_RATIO . 0.0) (:REQUEST_PAN_DISABLE . 0) (:REQUEST_PAN_ENABLE . 1) (:REQUEST_PAN_VOID . 2)) ) (cl:defmethod roslisp-msg-protocol:serialize ((msg <HeadPanCommand>) ostream) "Serializes a message object of type '<HeadPanCommand>" (cl:let ((bits (roslisp-utils:encode-single-float-bits (cl:slot-value msg 'target)))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)) (cl:let ((bits (roslisp-utils:encode-single-float-bits (cl:slot-value msg 'speed_ratio)))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)) (cl:write-byte (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'enable_pan_request)) ostream) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <HeadPanCommand>) istream) "Deserializes a message object of type '<HeadPanCommand>" (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'target) (roslisp-utils:decode-single-float-bits bits))) (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'speed_ratio) (roslisp-utils:decode-single-float-bits bits))) (cl:setf (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'enable_pan_request)) (cl:read-byte istream)) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<HeadPanCommand>))) "Returns string type for a message object of type '<HeadPanCommand>" "ubt_core_msgs/HeadPanCommand") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'HeadPanCommand))) "Returns string type for a message object of type 'HeadPanCommand" "ubt_core_msgs/HeadPanCommand") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<HeadPanCommand>))) "Returns md5sum for a message object of type '<HeadPanCommand>" "23b8a3f4b7ee9de7099d029e57660a8c") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'HeadPanCommand))) "Returns md5sum for a message object of type 'HeadPanCommand" "23b8a3f4b7ee9de7099d029e57660a8c") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<HeadPanCommand>))) "Returns full string definition for message of type '<HeadPanCommand>" (cl:format cl:nil "float32 target # radians for target, 0 str~%float32 speed_ratio # Percentage of max speed [0-1]~%#~% float32 MAX_SPEED_RATIO = 1.0~% float32 MIN_SPEED_RATIO = 0.0~%#~%uint8 enable_pan_request # override automatic pan enable/disable~%# enable_pan_request is tristate: 0 = disable pan; 1 = enable pan; 2 = don't change pan~% uint8 REQUEST_PAN_DISABLE = 0~% uint8 REQUEST_PAN_ENABLE = 1~% uint8 REQUEST_PAN_VOID = 2~%#~%~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'HeadPanCommand))) "Returns full string definition for message of type 'HeadPanCommand" (cl:format cl:nil "float32 target # radians for target, 0 str~%float32 speed_ratio # Percentage of max speed [0-1]~%#~% float32 MAX_SPEED_RATIO = 1.0~% float32 MIN_SPEED_RATIO = 0.0~%#~%uint8 enable_pan_request # override automatic pan enable/disable~%# enable_pan_request is tristate: 0 = disable pan; 1 = enable pan; 2 = don't change pan~% uint8 REQUEST_PAN_DISABLE = 0~% uint8 REQUEST_PAN_ENABLE = 1~% uint8 REQUEST_PAN_VOID = 2~%#~%~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <HeadPanCommand>)) (cl:+ 0 4 4 1 )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <HeadPanCommand>)) "Converts a ROS message object to a list" (cl:list 'HeadPanCommand (cl:cons ':target (target msg)) (cl:cons ':speed_ratio (speed_ratio msg)) (cl:cons ':enable_pan_request (enable_pan_request msg)) ))
41dbca589f225c6e4c7105fb3b59988735eaf2595da132b6836a91fae4f19143
practicalli/four-clojure
project.clj
(defproject four-clojure "0.1.0-SNAPSHOT" :description "Discussions on the solutions to the 4Clojure.com challenges" :url "-clojure" :license {:name "Creative Commons Attribution Share-Alike 4.0 International" :url ""} :dependencies [[org.clojure/clojure "1.9.0"]])
null
https://raw.githubusercontent.com/practicalli/four-clojure/9812b63769a06f9b0bfd63e5ffce380b67e5468b/project.clj
clojure
(defproject four-clojure "0.1.0-SNAPSHOT" :description "Discussions on the solutions to the 4Clojure.com challenges" :url "-clojure" :license {:name "Creative Commons Attribution Share-Alike 4.0 International" :url ""} :dependencies [[org.clojure/clojure "1.9.0"]])
f74ce5df45a8c123f57723208f7be51af6933fb710798bd741baf87038cf96df
pink-gorilla/webly
files.clj
(ns modular.webserver.handler.files (:require ; [taoensso.timbre :refer [debug info warn error]] [bidi.bidi :as bidi :refer [url-decode]] [clojure.java.io :as io] [ring.util.response :refer [file-response resource-response]] [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.not-modified :refer [wrap-not-modified]])) (defrecord FilesMaybe [options] bidi/Matched (resolve-handler [this m] (let [reminder (url-decode (:remainder m)) filename (str (:dir options) reminder)] ;(warn "file-maybe: " filename) (when (.exists (io/file filename)) ;(warn "file found: " filename) (assoc (dissoc m :remainder) :handler (-> (fn [req] (file-response reminder {:root (:dir options)})) (wrap-content-type options) (wrap-not-modified)))))) (unresolve-handler [this m] (when (= this (:handler m)) ""))) ; copied from bidi. ; but bidi forgot to wrap not modified ; (defrecord ResourcesMaybe [options] bidi/Matched (resolve-handler [this m] (let [path (url-decode (:remainder m))] (when (not-empty path) (when-let [res (io/resource (str (:prefix options) path))] ;(warn "res: " path) (assoc (dissoc m :remainder) :handler (-> (fn [req] (resource-response (str (:prefix options) path))) (wrap-content-type options) (wrap-not-modified) ; awb99 hack )))))) (unresolve-handler [this m] (when (= this (:handler m)) "")))
null
https://raw.githubusercontent.com/pink-gorilla/webly/d449a506e6101afc16d384300cdebb7425e3a7f3/webserver/src/modular/webserver/handler/files.clj
clojure
[taoensso.timbre :refer [debug info warn error]] (warn "file-maybe: " filename) (warn "file found: " filename) copied from bidi. but bidi forgot to wrap not modified (warn "res: " path) awb99 hack
(ns modular.webserver.handler.files (:require [bidi.bidi :as bidi :refer [url-decode]] [clojure.java.io :as io] [ring.util.response :refer [file-response resource-response]] [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.not-modified :refer [wrap-not-modified]])) (defrecord FilesMaybe [options] bidi/Matched (resolve-handler [this m] (let [reminder (url-decode (:remainder m)) filename (str (:dir options) reminder)] (when (.exists (io/file filename)) (assoc (dissoc m :remainder) :handler (-> (fn [req] (file-response reminder {:root (:dir options)})) (wrap-content-type options) (wrap-not-modified)))))) (unresolve-handler [this m] (when (= this (:handler m)) ""))) (defrecord ResourcesMaybe [options] bidi/Matched (resolve-handler [this m] (let [path (url-decode (:remainder m))] (when (not-empty path) (when-let [res (io/resource (str (:prefix options) path))] (assoc (dissoc m :remainder) :handler (-> (fn [req] (resource-response (str (:prefix options) path))) (wrap-content-type options) )))))) (unresolve-handler [this m] (when (= this (:handler m)) "")))
0697f52c89f243a8197fc93491ef5a72824312739425cf50eaa5dee08b40c0a4
yogthos/reagent-dnd
core.cljs
(ns react-dnd-test.core (:require [reagent.core :as r] [reagent-dnd.core :as dnd]) (:require-macros [reagent.ratom :refer [reaction]])) (defonce state (r/atom {:knight-position [0 0]})) (defn knight-at? [position] (reaction (= (:knight-position @state) position))) (defn can-move-knight? [position] (reaction (let [[kx ky] (:knight-position @state) [tx ty] position dx (Math/abs (- kx tx)) dy (Math/abs (- ky ty))] (or (and (= dx 2) (= dy 1)) (and (= dy 2) (= dx 1)))))) (defn knight-span [drag-state] [:span {:style {:cursor :move :opacity (if (:dragging? @drag-state) 0.5 1)}} "♘"]) (defn knight [] (let [drag-state (r/atom {})] [dnd/drag-source :type :knight :state drag-state :child [knight-span drag-state]])) (defn square [& {:keys [black? piece drag-state]}] [:div {:style {:position :relative :width "32px" :height "32px" :background (if black? :white :black) :color (if black? :black :white) :font-size "32px"}} piece (when (:is-over? @drag-state) [:div {:style {:width "32px" :height "32px" :position :absolute :z-index "1" :opacity "0.5" :background-color :red}}]) (when (:can-drop? @drag-state) [:div {:style {:width "32px" :height "32px" :position :absolute :z-index "2" :opacity "0.5" :background-color :green}}])]) (defn move-knight-to [position] (swap! state assoc :knight-position position)) (defn board-square [& {:keys [position]}] (let [drag-state (r/atom {}) [x y] position black? (odd? (+ x y))] [:div {:style {:height "12.5%" :width "12.5%"}} [:div {:style {:position :relative :width "32px" :height "32px"}} [dnd/drop-target :types [:knight] :state drag-state :drop #(move-knight-to position) :can-drop? (fn [] @(can-move-knight? position)) :child [square :drag-state drag-state :black? black? :piece (when @(knight-at? position) [knight])]]]])) (defn position [i] [(quot i 8) (rem i 8)]) (defn board [] [:div {:style {:width "256px" :height "256px" :display :flex :flex-wrap :wrap}} (for [i (range 64) :let [p (position i)]] ^{:key (str "square-" i)} [board-square :position p])]) (def context (dnd/with-drag-drop-context dnd/html5-backend board)) (defn home [] [context])
null
https://raw.githubusercontent.com/yogthos/reagent-dnd/9830e240b5f2e372c40a633432d0593288ec6682/env/dev/cljs/react_dnd_test/core.cljs
clojure
(ns react-dnd-test.core (:require [reagent.core :as r] [reagent-dnd.core :as dnd]) (:require-macros [reagent.ratom :refer [reaction]])) (defonce state (r/atom {:knight-position [0 0]})) (defn knight-at? [position] (reaction (= (:knight-position @state) position))) (defn can-move-knight? [position] (reaction (let [[kx ky] (:knight-position @state) [tx ty] position dx (Math/abs (- kx tx)) dy (Math/abs (- ky ty))] (or (and (= dx 2) (= dy 1)) (and (= dy 2) (= dx 1)))))) (defn knight-span [drag-state] [:span {:style {:cursor :move :opacity (if (:dragging? @drag-state) 0.5 1)}} "♘"]) (defn knight [] (let [drag-state (r/atom {})] [dnd/drag-source :type :knight :state drag-state :child [knight-span drag-state]])) (defn square [& {:keys [black? piece drag-state]}] [:div {:style {:position :relative :width "32px" :height "32px" :background (if black? :white :black) :color (if black? :black :white) :font-size "32px"}} piece (when (:is-over? @drag-state) [:div {:style {:width "32px" :height "32px" :position :absolute :z-index "1" :opacity "0.5" :background-color :red}}]) (when (:can-drop? @drag-state) [:div {:style {:width "32px" :height "32px" :position :absolute :z-index "2" :opacity "0.5" :background-color :green}}])]) (defn move-knight-to [position] (swap! state assoc :knight-position position)) (defn board-square [& {:keys [position]}] (let [drag-state (r/atom {}) [x y] position black? (odd? (+ x y))] [:div {:style {:height "12.5%" :width "12.5%"}} [:div {:style {:position :relative :width "32px" :height "32px"}} [dnd/drop-target :types [:knight] :state drag-state :drop #(move-knight-to position) :can-drop? (fn [] @(can-move-knight? position)) :child [square :drag-state drag-state :black? black? :piece (when @(knight-at? position) [knight])]]]])) (defn position [i] [(quot i 8) (rem i 8)]) (defn board [] [:div {:style {:width "256px" :height "256px" :display :flex :flex-wrap :wrap}} (for [i (range 64) :let [p (position i)]] ^{:key (str "square-" i)} [board-square :position p])]) (def context (dnd/with-drag-drop-context dnd/html5-backend board)) (defn home [] [context])
14408538c1293144f87f071f2349b7ffa5538dfe1f43a6daefa4550ff075ce96
bmeurer/ocamljit2
testsieve.ml
let sieve primes= Event.sync (Event.send primes 0); Event.sync (Event.send primes 1); Event.sync (Event.send primes 2); let integers = Event.new_channel () in let rec enumerate n= Event.sync (Event.send integers n); enumerate (n + 2) and filter inpout = let n = Event.sync (Event.receive inpout) On prepare le terrain pour l'appel recursif and output = Event.new_channel () in Celui qui etait en tete du crible est premier Event.sync (Event.send primes n); Thread.create filter output; On elimine de la sortie ceux qui sont des multiples de n while true do let m = Event.sync (Event.receive inpout) in print_int n ; print_string " : " ; print_int m ; print_newline ( ) ; if (m mod n) = 0 then () else ((Event.sync (Event.send output m));()) done in Thread.create filter integers; Thread.create enumerate 3 let premiers = Event.new_channel () let main _ = Thread.create sieve premiers; while true do for i = 1 to 100 do let n = Event.sync (Event.receive premiers) in print_int n; print_newline() done; exit 0 done let _ = try main () with _ -> exit 0;;
null
https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/testsuite/tests/lib-threads/testsieve.ml
ocaml
let sieve primes= Event.sync (Event.send primes 0); Event.sync (Event.send primes 1); Event.sync (Event.send primes 2); let integers = Event.new_channel () in let rec enumerate n= Event.sync (Event.send integers n); enumerate (n + 2) and filter inpout = let n = Event.sync (Event.receive inpout) On prepare le terrain pour l'appel recursif and output = Event.new_channel () in Celui qui etait en tete du crible est premier Event.sync (Event.send primes n); Thread.create filter output; On elimine de la sortie ceux qui sont des multiples de n while true do let m = Event.sync (Event.receive inpout) in print_int n ; print_string " : " ; print_int m ; print_newline ( ) ; if (m mod n) = 0 then () else ((Event.sync (Event.send output m));()) done in Thread.create filter integers; Thread.create enumerate 3 let premiers = Event.new_channel () let main _ = Thread.create sieve premiers; while true do for i = 1 to 100 do let n = Event.sync (Event.receive premiers) in print_int n; print_newline() done; exit 0 done let _ = try main () with _ -> exit 0;;
d40d557adfb64acef47f285c7dca9be9b2abf7e95abc64e356a1ddb22b5e58a9
deadtrickster/cl-events
package.lisp
(in-package :cl-user) (defpackage :cl-events.test (:use :cl :alexandria :iterate :prove :cl-events)) (in-package :cl-events.test)
null
https://raw.githubusercontent.com/deadtrickster/cl-events/2fdec2dbdef8ba2144139b27a7350d4cedc011a1/t/package.lisp
lisp
(in-package :cl-user) (defpackage :cl-events.test (:use :cl :alexandria :iterate :prove :cl-events)) (in-package :cl-events.test)
c866510a9c91716451948ac03822116e799f5ac33af07914e2828934c75e91fc
expipiplus1/vulkan
VK_KHR_portability_enumeration.hs
{-# language CPP #-} -- | = Name -- VK_KHR_portability_enumeration - instance extension -- = = VK_KHR_portability_enumeration -- -- [__Name String__] -- @VK_KHR_portability_enumeration@ -- -- [__Extension Type__] -- Instance extension -- -- [__Registered Extension Number__] 395 -- -- [__Revision__] 1 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.0 -- -- [__Contact__] -- - < -Docs/issues/new?body=[VK_KHR_portability_enumeration ] @charles - lunarg%0A*Here describe the issue or question you have about the VK_KHR_portability_enumeration extension * > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2021 - 06 - 02 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - Interacts with @VK_KHR_portability_subset@ -- -- [__Contributors__] -- - , LunarG -- - , LunarG -- -- == Description -- -- This extension allows applications to control whether devices that expose the extension are included in the -- results of physical device enumeration. Since devices which support the @VK_KHR_portability_subset@ extension are not fully conformant Vulkan implementations , the Vulkan loader does not report those devices unless -- the application explicitly asks for them. This prevents applications -- which may not be aware of non-conformant devices from accidentally using -- them, as any device which supports the @VK_KHR_portability_subset@ -- extension mandates that the extension must be enabled if that device is -- used. -- -- This extension is implemented in the loader. -- -- == New Enum Constants -- -- - 'KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME' -- -- - 'KHR_PORTABILITY_ENUMERATION_SPEC_VERSION' -- -- - Extending ' Vulkan . Core10.Enums . InstanceCreateFlagBits . InstanceCreateFlagBits ' : -- - ' Vulkan . Core10.Enums . InstanceCreateFlagBits . INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR ' -- -- == Version History -- - Revision 1 , 2021 - 06 - 02 ( ) -- -- - Initial version -- -- == See Also -- -- No cross-references are available -- -- == Document Notes -- -- For more information, see the -- <-extensions/html/vkspec.html#VK_KHR_portability_enumeration Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_portability_enumeration ( KHR_PORTABILITY_ENUMERATION_SPEC_VERSION , pattern KHR_PORTABILITY_ENUMERATION_SPEC_VERSION , KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME , pattern KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME ) where import Data.String (IsString) type KHR_PORTABILITY_ENUMERATION_SPEC_VERSION = 1 No documentation found for TopLevel " VK_KHR_PORTABILITY_ENUMERATION_SPEC_VERSION " pattern KHR_PORTABILITY_ENUMERATION_SPEC_VERSION :: forall a . Integral a => a pattern KHR_PORTABILITY_ENUMERATION_SPEC_VERSION = 1 type KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME = "VK_KHR_portability_enumeration" No documentation found for TopLevel " VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME " pattern KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME = "VK_KHR_portability_enumeration"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_KHR_portability_enumeration.hs
haskell
# language CPP # | = Name [__Name String__] @VK_KHR_portability_enumeration@ [__Extension Type__] Instance extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] [__Contact__] == Other Extension Metadata [__Last Modified Date__] [__IP Status__] No known IP claims. [__Interactions and External Dependencies__] - Interacts with @VK_KHR_portability_subset@ [__Contributors__] == Description This extension allows applications to control whether devices that results of physical device enumeration. Since devices which support the the application explicitly asks for them. This prevents applications which may not be aware of non-conformant devices from accidentally using them, as any device which supports the @VK_KHR_portability_subset@ extension mandates that the extension must be enabled if that device is used. This extension is implemented in the loader. == New Enum Constants - 'KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME' - 'KHR_PORTABILITY_ENUMERATION_SPEC_VERSION' - Extending == Version History - Initial version == See Also No cross-references are available == Document Notes For more information, see the <-extensions/html/vkspec.html#VK_KHR_portability_enumeration Vulkan Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly.
VK_KHR_portability_enumeration - instance extension = = VK_KHR_portability_enumeration 395 1 - Requires support for Vulkan 1.0 - < -Docs/issues/new?body=[VK_KHR_portability_enumeration ] @charles - lunarg%0A*Here describe the issue or question you have about the VK_KHR_portability_enumeration extension * > 2021 - 06 - 02 - , LunarG - , LunarG expose the extension are included in the @VK_KHR_portability_subset@ extension are not fully conformant Vulkan implementations , the Vulkan loader does not report those devices unless ' Vulkan . Core10.Enums . InstanceCreateFlagBits . InstanceCreateFlagBits ' : - ' Vulkan . Core10.Enums . InstanceCreateFlagBits . INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR ' - Revision 1 , 2021 - 06 - 02 ( ) module Vulkan.Extensions.VK_KHR_portability_enumeration ( KHR_PORTABILITY_ENUMERATION_SPEC_VERSION , pattern KHR_PORTABILITY_ENUMERATION_SPEC_VERSION , KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME , pattern KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME ) where import Data.String (IsString) type KHR_PORTABILITY_ENUMERATION_SPEC_VERSION = 1 No documentation found for TopLevel " VK_KHR_PORTABILITY_ENUMERATION_SPEC_VERSION " pattern KHR_PORTABILITY_ENUMERATION_SPEC_VERSION :: forall a . Integral a => a pattern KHR_PORTABILITY_ENUMERATION_SPEC_VERSION = 1 type KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME = "VK_KHR_portability_enumeration" No documentation found for TopLevel " VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME " pattern KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME = "VK_KHR_portability_enumeration"
a203c2ec4aa546de3204280a973690656702dd8e001fc340656ffb3a6bdecb3d
lambdamikel/DLMAPS
load-race.lisp
;;;-*- Mode: Lisp; Package: COMMON-LISP-USER -*- ;;; This is the RACE Loader for ACL / LINUX Version (in-package :cl-user) (let ((excl::*redefinition-warnings* nil)) (let ((*enable-package-locked-errors* nil)) (defun excl::check-for-duplicate-definitions-in-file (fspec type when &optional icsp) (declare (ignore fspec type when icsp))))) (let* ((load-pathname (concatenate 'string (directory-namestring (translate-logical-pathname *load-pathname*)))) (example-directory (format nil "~Aexamples/**/*.*" load-pathname)) (race-directory (format nil "~A**/*.*" load-pathname))) (setf (logical-pathname-translations "race") `(("**;*.*" ,race-directory) ("examples;**;*.*" ,example-directory)))) (defun load-race () (load "race:race-1-1-0.fasl" :verbose t)) (load-race)
null
https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/prover/dl-benchmark-suite/race-1-1/race-1-1-acl5-linux/load-race.lisp
lisp
-*- Mode: Lisp; Package: COMMON-LISP-USER -*- This is the RACE Loader for ACL / LINUX Version
(in-package :cl-user) (let ((excl::*redefinition-warnings* nil)) (let ((*enable-package-locked-errors* nil)) (defun excl::check-for-duplicate-definitions-in-file (fspec type when &optional icsp) (declare (ignore fspec type when icsp))))) (let* ((load-pathname (concatenate 'string (directory-namestring (translate-logical-pathname *load-pathname*)))) (example-directory (format nil "~Aexamples/**/*.*" load-pathname)) (race-directory (format nil "~A**/*.*" load-pathname))) (setf (logical-pathname-translations "race") `(("**;*.*" ,race-directory) ("examples;**;*.*" ,example-directory)))) (defun load-race () (load "race:race-1-1-0.fasl" :verbose t)) (load-race)
ffacef1defb29aff8b9a6007a0c644198aa10c09c0134a905629098b12300715
puppetlabs/trapperkeeper
bootstrap_test.clj
(ns puppetlabs.trapperkeeper.bootstrap-test (:import (java.io StringReader)) (:require [clojure.test :refer :all] [clojure.java.io :refer [file] :as io] [slingshot.slingshot :refer [try+]] [puppetlabs.kitchensink.core :refer [without-ns]] [puppetlabs.kitchensink.classpath :refer [with-additional-classpath-entries]] [puppetlabs.trapperkeeper.services :refer [service-map]] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.bootstrap :refer :all] [puppetlabs.trapperkeeper.logging :refer [reset-logging]] [puppetlabs.trapperkeeper.testutils.logging :refer [with-test-logging]] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [bootstrap-with-empty-config parse-and-bootstrap]] [puppetlabs.trapperkeeper.examples.bootstrapping.test-services :refer [test-fn test-fn-two test-fn-three hello-world]] [schema.test :as schema-test] [me.raynes.fs :as fs] [clojure.string :as string])) (use-fixtures :once schema-test/validate-schemas Without this , " test " and : only invocations may fail . (fn [f] (reset-logging) (f))) (deftest bootstrapping (testing "Valid bootstrap configurations" (let [bootstrap-config "./dev-resources/bootstrapping/cli/bootstrap.cfg" app (parse-and-bootstrap bootstrap-config)] (testing "Can load a service based on a valid bootstrap config string" (let [test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (= (test-fn test-svc) :cli)) (is (= (hello-world hello-world-svc) "hello world")))) (with-additional-classpath-entries ["./dev-resources/bootstrapping/classpath"] (testing "Looks for bootstrap config on classpath (dev-resources)" (with-test-logging (let [app (bootstrap-with-empty-config) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? #"Loading bootstrap config from classpath: 'file:/.*dev-resources/bootstrapping/classpath/bootstrap.cfg'" :debug)) (is (= (test-fn test-svc) :classpath)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "Gives precedence to bootstrap config in cwd" (let [cwd-config (io/file (System/getProperty "user.dir") "bootstrap.cfg") test-config (io/file "./dev-resources/bootstrapping/cwd/bootstrap.cfg")] ;; This test used to set the user.dir property to the dev-resources dir above, however in Java 11 it is illegal to set user.dir at runtime . (is (not (.exists cwd-config)) "A bootstrap config file exists in the cwd, cannot reliably test cwd bootstrap loading!") (try (io/copy test-config cwd-config) (with-test-logging (let [app (bootstrap-with-empty-config) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? #"Loading bootstrap config from current working directory: '.*/bootstrap.cfg'" :debug)) (is (= (test-fn test-svc) :cwd)) (is (= (hello-world hello-world-svc) "hello world")))) (finally (io/delete-file cwd-config))))) (testing "Gives precedence to bootstrap config specified as CLI arg" (with-test-logging (let [bootstrap-path "./dev-resources/bootstrapping/cli/bootstrap.cfg" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s" bootstrap-path) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (hello-world hello-world-svc) "hello world"))))))) (testing "Invalid bootstrap configurations" (testing "Bootstrap config path specified on CLI does not exist" (let [cfg-path "./dev-resources/bootstrapping/cli/non-existent-bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist: '.*non-existent-bootstrap.cfg'" (bootstrap-with-empty-config ["--bootstrap-config" cfg-path]))))) (testing "No bootstrap config found" (is (thrown-with-msg? IllegalStateException #"Unable to find bootstrap.cfg file via --bootstrap-config command line argument, current working directory, or on classpath" (bootstrap-with-empty-config))) (let [got-expected-exception (atom false)] (try+ (bootstrap-with-empty-config ["--bootstrap-config" nil]) (catch map? m (is (contains? m :kind)) (is (= :cli-error (without-ns (:kind m)))) (is (= :puppetlabs.kitchensink.core/cli-error (:kind m))) (is (contains? m :msg)) (is (re-find #"Missing required argument for.*--bootstrap-config" (m :msg))) (reset! got-expected-exception true))) (is (true? @got-expected-exception)))) (testing "Bad line in bootstrap config file" (let [bootstrap-config "./dev-resources/bootstrapping/cli/invalid_entry_bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException #"(?is)Invalid line in bootstrap.*This is not a legit line" (parse-and-bootstrap bootstrap-config))))) (testing "Invalid service graph" (let [bootstrap-config "./dev-resources/bootstrapping/cli/invalid_service_graph_bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException #"Invalid service definition;" (parse-and-bootstrap bootstrap-config))))))) (testing "comments allowed in bootstrap config file" (let [bootstrap-config "./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg" service-maps (->> bootstrap-config parse-bootstrap-config! (map service-map))] (is (= (count service-maps) 2)) (is (contains? (first service-maps) :HelloWorldService)) (is (contains? (second service-maps) :TestService))))) (deftest empty-bootstrap (testing "Empty bootstrap causes error" (testing "single bootstrap file" (let [bootstrap-config "./dev-resources/bootstrapping/cli/empty_bootstrap.cfg"] (is (thrown-with-msg? Exception (re-pattern (str "No entries found in any supplied bootstrap file\\(s\\):\n" "./dev-resources/bootstrapping/cli/empty_bootstrap.cfg")) (parse-bootstrap-config! bootstrap-config))))) (testing "multiple bootstrap files" (let [bootstraps ["./dev-resources/bootstrapping/cli/split_bootstraps/empty/empty1.cfg" "./dev-resources/bootstrapping/cli/split_bootstraps/empty/empty2.cfg"]] (is (thrown-with-msg? Exception (re-pattern (str "No entries found in any supplied bootstrap file\\(s\\):\n" (string/join "\n" bootstraps))) (parse-bootstrap-configs! bootstraps))))))) (deftest multiple-bootstrap-files (testing "Multiple bootstrap files can be specified directly on the command line" (with-test-logging (let [bootstrap-one "./dev-resources/bootstrapping/cli/split_bootstraps/one/bootstrap_one.cfg" bootstrap-two "./dev-resources/bootstrapping/cli/split_bootstraps/two/bootstrap_two.cfg" bootstrap-path (format "%s,%s" bootstrap-one bootstrap-two) app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s\n%s" bootstrap-one bootstrap-two) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "A path containing multiple .cfg files can be specified on the command line" (with-test-logging (let [bootstrap-path "./dev-resources/bootstrapping/cli/split_bootstraps/both/" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? ; We can't know what order it will find the files on disk, so just look for a partial match with the path we gave TK . (re-pattern (format "Loading bootstrap configs:\n%s" (fs/absolute bootstrap-path))) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "A path containing both a file and a folder can be specified on the command line" (with-test-logging (let [bootstrap-one-dir "./dev-resources/bootstrapping/cli/split_bootstraps/one/" bootstrap-one "./dev-resources/bootstrapping/cli/split_bootstraps/one/bootstrap_one.cfg" bootstrap-two "./dev-resources/bootstrapping/cli/split_bootstraps/two/bootstrap_two.cfg" bootstrap-path (format "%s,%s" bootstrap-one-dir bootstrap-two) app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s\n%s" (fs/absolute bootstrap-one) bootstrap-two) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world")))))) (deftest bootstrap-path-with-spaces (testing "Ensure that a bootstrap config can be loaded with a path that contains spaces" (with-test-logging (let [bootstrap-path "./dev-resources/bootstrapping/cli/path with spaces/bootstrap.cfg" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s" bootstrap-path) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "Multiple bootstrap files can be specified with spaces in the names" (with-test-logging (let [bootstrap-one "./dev-resources/bootstrapping/cli/split_bootstraps/spaces/bootstrap with spaces one.cfg" bootstrap-two "./dev-resources/bootstrapping/cli/split_bootstraps/spaces/bootstrap with spaces two.cfg" bootstrap-path (format "%s,%s" bootstrap-one bootstrap-two) app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s\n%s" bootstrap-one bootstrap-two) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world")))))) (deftest duplicate-service-entries (testing "duplicate bootstrap entries are allowed" (let [bootstrap-path "./dev-resources/bootstrapping/cli/duplicate_entries.cfg" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) hello-world-svc (get-service app :HelloWorldService)] (is (= (hello-world hello-world-svc) "hello world"))))) (deftest duplicate-service-definitions (testing "Duplicate service definitions causes error with filename and line numbers" (let [bootstraps ["./dev-resources/bootstrapping/cli/duplicate_services/duplicates.cfg"]] (is (thrown-with-msg? IllegalArgumentException (re-pattern (str "Duplicate implementations found for service protocol ':TestService':\n" ".*/duplicates.cfg:2\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service\n" ".*/duplicates.cfg:3\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/foo-test-service\n" "Duplicate implementations.*\n" ".*/duplicates.cfg:5\n" ".*test-service-two\n" ".*/duplicates.cfg:6\n" ".*test-service-two-duplicate")) (parse-bootstrap-configs! bootstraps)))) (testing "Duplicate service definitions between two files throws error" (let [bootstraps ["./dev-resources/bootstrapping/cli/duplicate_services/split_one.cfg" "./dev-resources/bootstrapping/cli/duplicate_services/split_two.cfg"]] (is (thrown-with-msg? IllegalArgumentException (re-pattern (str "Duplicate implementations found for service protocol ':TestService':\n" ".*/split_one.cfg:2\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/foo-test-service\n" ".*/split_two.cfg:2\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service\n" "Duplicate implementations.*\n" ".*/split_one.cfg:4\n" ".*test-service-two-duplicate\n" ".*/split_two.cfg:4\n" ".*test-service-two")) (parse-bootstrap-configs! bootstraps))))))) (deftest config-file-in-jar (testing "Bootstrapping via a config file contained in a .jar as command line option" (let [jar (file "./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar") bootstrap-url (str "jar:file:///" (.getAbsolutePath jar) "!/bootstrap.cfg")] ;; just test that this bootstrap config file can be read successfully ;; (ie, this does not throw an exception) (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-url])))) (deftest config-from-classpath-test (testing "can locate bootstrap file on the classpath" (let [bootstrap-file "./dev-resources/bootstrapping/classpath/bootstrap.cfg" bootstrap-uri (str "file:" (.getCanonicalPath (file bootstrap-file)))] (with-additional-classpath-entries ["./dev-resources/bootstrapping/classpath/"] (let [found-bootstraps (config-from-classpath)] (is (= 1 (count found-bootstraps))) (is (= bootstrap-uri (first found-bootstraps))))))) (testing "can locate bootstrap file contained in a .jar on the classpath" (let [jar "./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar" jar-uri (str "file:" (.getAbsolutePath (file jar))) expected-resource-uri (format "jar:%s!/bootstrap.cfg" jar-uri)] (with-additional-classpath-entries ["./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar"] (let [found-bootstraps (config-from-classpath)] (is (= 1 (count found-bootstraps))) (is (= expected-resource-uri (first found-bootstraps)))))))) (deftest parse-bootstrap-config-test (testing "Missing service namespace logs warning" (with-test-logging (let [bootstrap-config "./dev-resources/bootstrapping/cli/fake_namespace_bootstrap.cfg"] (parse-bootstrap-config! bootstrap-config) (is (logged? (str "Unable to load service 'non-existent-service/test-service' from " "./dev-resources/bootstrapping/cli/fake_namespace_bootstrap.cfg:3") :warn))))) (testing "Missing service definition logs warning" (with-test-logging (let [bootstrap-config "./dev-resources/bootstrapping/cli/missing_definition_bootstrap.cfg"] (parse-bootstrap-config! bootstrap-config) (is (logged? (str "Unable to load service " "'puppetlabs.trapperkeeper.examples.bootstrapping.test-services/non-existent-service' " "from ./dev-resources/bootstrapping/cli/missing_definition_bootstrap.cfg:3") :warn))))) (testing "errors are thrown with line number and file" ; Load a bootstrap with a bad service graph to generate an error (let [bootstrap "./dev-resources/bootstrapping/cli/invalid_service_graph_bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException (re-pattern (str "Problem loading service " "'puppetlabs.trapperkeeper.examples.bootstrapping.test-services/invalid-service-graph-service' " "from ./dev-resources/bootstrapping/cli/invalid_service_graph_bootstrap.cfg:1:\n" "Invalid service definition")) (parse-bootstrap-config! bootstrap)))))) (deftest get-annotated-bootstrap-entries-test (testing "file with comments" (let [bootstraps ["./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg"]] (let [entries (get-annotated-bootstrap-entries bootstraps)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 2} {:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/foo-test-service" :line-number 5}] entries))))) (testing "multiple bootstrap files" (let [bootstraps ["./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_one.cfg" "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_two.cfg"]] (let [entries (get-annotated-bootstrap-entries bootstraps)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_one.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service" :line-number 1} {:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_one.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 2} {:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_two.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/test-service-two" :line-number 1} {:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_two.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/test-service-three" :line-number 2}] entries)))))) (deftest find-duplicates-test (testing "correct duplicates found" (let [items [{:important-key :one :other-key 2} {:important-key :one :other-key 3} {:important-key :two :other-key 4} {:important-key :three :other-key 5}]] ; List of key value pairs (is (= {:one [{:important-key :one :other-key 2} {:important-key :one :other-key 3}]} (find-duplicates items :important-key)))))) (deftest check-duplicate-service-implementations!-test (testing "no duplicate service implementations does not throw error" (let [configs ["./dev-resources/bootstrapping/cli/bootstrap.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs) resolved-services (resolve-services! bootstrap-entries)] (check-duplicate-service-implementations! resolved-services bootstrap-entries))) (testing "duplicate service implementations throws error" (let [configs ["./dev-resources/bootstrapping/cli/duplicate_services/duplicates.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs) resolved-services (resolve-services! bootstrap-entries)] (is (thrown-with-msg? IllegalArgumentException #"Duplicate implementations found for service protocol ':TestService'" (check-duplicate-service-implementations! resolved-services bootstrap-entries)))))) (deftest remove-duplicate-entries-test (testing "single bootstrap with all duplicates" (testing "only the first duplicate found is kept" (let [configs ["./dev-resources/bootstrapping/cli/duplicate_entries.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/duplicate_entries.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 1}] (remove-duplicate-entries bootstrap-entries)))))) (testing "two copies of the same set of services" (let [configs ["./dev-resources/bootstrapping/cli/bootstrap.cfg" "./dev-resources/bootstrapping/cli/bootstrap.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service" :line-number 1} {:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 2}] (remove-duplicate-entries bootstrap-entries)))))) (deftest read-config-test (testing "basic config" (let [config "./dev-resources/bootstrapping/cli/bootstrap.cfg"] (is (= ["puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service"] (read-config config))))) (testing "jar uri" (let [jar "./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar" config (str "jar:file:///" (.getAbsolutePath (file jar)) "!/bootstrap.cfg")] ; The bootstrap in the jar contains an empty line at the end (is (= ["puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" ""] (read-config config))))) (testing "malformed uri is wrapped in our exception" (let [config "\n"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist" (read-config config))))) (testing "Non-absolute uri is wrapped in our exception" TODO This path is currently interpreted as a URI because TK checks if it 's a file , and if not , attemps to load as a URI (let [config "./not-a-file"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist" (println (read-config config)))))) (testing "Non-existent file in URI is wrapped in our exception" (let [config "file-a-file"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist" (read-config config))))))
null
https://raw.githubusercontent.com/puppetlabs/trapperkeeper/3e5e7e286287d75e7fdf7eb1dabb2fa534091329/test/puppetlabs/trapperkeeper/bootstrap_test.clj
clojure
This test used to set the user.dir property to the dev-resources dir above, We can't know what order it will find the files on disk, so just just test that this bootstrap config file can be read successfully (ie, this does not throw an exception) Load a bootstrap with a bad service graph to generate an error List of key value pairs The bootstrap in the jar contains an empty line at the end
(ns puppetlabs.trapperkeeper.bootstrap-test (:import (java.io StringReader)) (:require [clojure.test :refer :all] [clojure.java.io :refer [file] :as io] [slingshot.slingshot :refer [try+]] [puppetlabs.kitchensink.core :refer [without-ns]] [puppetlabs.kitchensink.classpath :refer [with-additional-classpath-entries]] [puppetlabs.trapperkeeper.services :refer [service-map]] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.bootstrap :refer :all] [puppetlabs.trapperkeeper.logging :refer [reset-logging]] [puppetlabs.trapperkeeper.testutils.logging :refer [with-test-logging]] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [bootstrap-with-empty-config parse-and-bootstrap]] [puppetlabs.trapperkeeper.examples.bootstrapping.test-services :refer [test-fn test-fn-two test-fn-three hello-world]] [schema.test :as schema-test] [me.raynes.fs :as fs] [clojure.string :as string])) (use-fixtures :once schema-test/validate-schemas Without this , " test " and : only invocations may fail . (fn [f] (reset-logging) (f))) (deftest bootstrapping (testing "Valid bootstrap configurations" (let [bootstrap-config "./dev-resources/bootstrapping/cli/bootstrap.cfg" app (parse-and-bootstrap bootstrap-config)] (testing "Can load a service based on a valid bootstrap config string" (let [test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (= (test-fn test-svc) :cli)) (is (= (hello-world hello-world-svc) "hello world")))) (with-additional-classpath-entries ["./dev-resources/bootstrapping/classpath"] (testing "Looks for bootstrap config on classpath (dev-resources)" (with-test-logging (let [app (bootstrap-with-empty-config) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? #"Loading bootstrap config from classpath: 'file:/.*dev-resources/bootstrapping/classpath/bootstrap.cfg'" :debug)) (is (= (test-fn test-svc) :classpath)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "Gives precedence to bootstrap config in cwd" (let [cwd-config (io/file (System/getProperty "user.dir") "bootstrap.cfg") test-config (io/file "./dev-resources/bootstrapping/cwd/bootstrap.cfg")] however in Java 11 it is illegal to set user.dir at runtime . (is (not (.exists cwd-config)) "A bootstrap config file exists in the cwd, cannot reliably test cwd bootstrap loading!") (try (io/copy test-config cwd-config) (with-test-logging (let [app (bootstrap-with-empty-config) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? #"Loading bootstrap config from current working directory: '.*/bootstrap.cfg'" :debug)) (is (= (test-fn test-svc) :cwd)) (is (= (hello-world hello-world-svc) "hello world")))) (finally (io/delete-file cwd-config))))) (testing "Gives precedence to bootstrap config specified as CLI arg" (with-test-logging (let [bootstrap-path "./dev-resources/bootstrapping/cli/bootstrap.cfg" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s" bootstrap-path) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (hello-world hello-world-svc) "hello world"))))))) (testing "Invalid bootstrap configurations" (testing "Bootstrap config path specified on CLI does not exist" (let [cfg-path "./dev-resources/bootstrapping/cli/non-existent-bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist: '.*non-existent-bootstrap.cfg'" (bootstrap-with-empty-config ["--bootstrap-config" cfg-path]))))) (testing "No bootstrap config found" (is (thrown-with-msg? IllegalStateException #"Unable to find bootstrap.cfg file via --bootstrap-config command line argument, current working directory, or on classpath" (bootstrap-with-empty-config))) (let [got-expected-exception (atom false)] (try+ (bootstrap-with-empty-config ["--bootstrap-config" nil]) (catch map? m (is (contains? m :kind)) (is (= :cli-error (without-ns (:kind m)))) (is (= :puppetlabs.kitchensink.core/cli-error (:kind m))) (is (contains? m :msg)) (is (re-find #"Missing required argument for.*--bootstrap-config" (m :msg))) (reset! got-expected-exception true))) (is (true? @got-expected-exception)))) (testing "Bad line in bootstrap config file" (let [bootstrap-config "./dev-resources/bootstrapping/cli/invalid_entry_bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException #"(?is)Invalid line in bootstrap.*This is not a legit line" (parse-and-bootstrap bootstrap-config))))) (testing "Invalid service graph" (let [bootstrap-config "./dev-resources/bootstrapping/cli/invalid_service_graph_bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException #"Invalid service definition;" (parse-and-bootstrap bootstrap-config))))))) (testing "comments allowed in bootstrap config file" (let [bootstrap-config "./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg" service-maps (->> bootstrap-config parse-bootstrap-config! (map service-map))] (is (= (count service-maps) 2)) (is (contains? (first service-maps) :HelloWorldService)) (is (contains? (second service-maps) :TestService))))) (deftest empty-bootstrap (testing "Empty bootstrap causes error" (testing "single bootstrap file" (let [bootstrap-config "./dev-resources/bootstrapping/cli/empty_bootstrap.cfg"] (is (thrown-with-msg? Exception (re-pattern (str "No entries found in any supplied bootstrap file\\(s\\):\n" "./dev-resources/bootstrapping/cli/empty_bootstrap.cfg")) (parse-bootstrap-config! bootstrap-config))))) (testing "multiple bootstrap files" (let [bootstraps ["./dev-resources/bootstrapping/cli/split_bootstraps/empty/empty1.cfg" "./dev-resources/bootstrapping/cli/split_bootstraps/empty/empty2.cfg"]] (is (thrown-with-msg? Exception (re-pattern (str "No entries found in any supplied bootstrap file\\(s\\):\n" (string/join "\n" bootstraps))) (parse-bootstrap-configs! bootstraps))))))) (deftest multiple-bootstrap-files (testing "Multiple bootstrap files can be specified directly on the command line" (with-test-logging (let [bootstrap-one "./dev-resources/bootstrapping/cli/split_bootstraps/one/bootstrap_one.cfg" bootstrap-two "./dev-resources/bootstrapping/cli/split_bootstraps/two/bootstrap_two.cfg" bootstrap-path (format "%s,%s" bootstrap-one bootstrap-two) app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s\n%s" bootstrap-one bootstrap-two) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "A path containing multiple .cfg files can be specified on the command line" (with-test-logging (let [bootstrap-path "./dev-resources/bootstrapping/cli/split_bootstraps/both/" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? look for a partial match with the path we gave TK . (re-pattern (format "Loading bootstrap configs:\n%s" (fs/absolute bootstrap-path))) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "A path containing both a file and a folder can be specified on the command line" (with-test-logging (let [bootstrap-one-dir "./dev-resources/bootstrapping/cli/split_bootstraps/one/" bootstrap-one "./dev-resources/bootstrapping/cli/split_bootstraps/one/bootstrap_one.cfg" bootstrap-two "./dev-resources/bootstrapping/cli/split_bootstraps/two/bootstrap_two.cfg" bootstrap-path (format "%s,%s" bootstrap-one-dir bootstrap-two) app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s\n%s" (fs/absolute bootstrap-one) bootstrap-two) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world")))))) (deftest bootstrap-path-with-spaces (testing "Ensure that a bootstrap config can be loaded with a path that contains spaces" (with-test-logging (let [bootstrap-path "./dev-resources/bootstrapping/cli/path with spaces/bootstrap.cfg" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s" bootstrap-path) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (hello-world hello-world-svc) "hello world"))))) (testing "Multiple bootstrap files can be specified with spaces in the names" (with-test-logging (let [bootstrap-one "./dev-resources/bootstrapping/cli/split_bootstraps/spaces/bootstrap with spaces one.cfg" bootstrap-two "./dev-resources/bootstrapping/cli/split_bootstraps/spaces/bootstrap with spaces two.cfg" bootstrap-path (format "%s,%s" bootstrap-one bootstrap-two) app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) test-svc (get-service app :TestService) test-svc-two (get-service app :TestServiceTwo) test-svc-three (get-service app :TestServiceThree) hello-world-svc (get-service app :HelloWorldService)] (is (logged? (format "Loading bootstrap configs:\n%s\n%s" bootstrap-one bootstrap-two) :debug)) (is (= (test-fn test-svc) :cli)) (is (= (test-fn-two test-svc-two) :two)) (is (= (test-fn-three test-svc-three) :three)) (is (= (hello-world hello-world-svc) "hello world")))))) (deftest duplicate-service-entries (testing "duplicate bootstrap entries are allowed" (let [bootstrap-path "./dev-resources/bootstrapping/cli/duplicate_entries.cfg" app (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-path]) hello-world-svc (get-service app :HelloWorldService)] (is (= (hello-world hello-world-svc) "hello world"))))) (deftest duplicate-service-definitions (testing "Duplicate service definitions causes error with filename and line numbers" (let [bootstraps ["./dev-resources/bootstrapping/cli/duplicate_services/duplicates.cfg"]] (is (thrown-with-msg? IllegalArgumentException (re-pattern (str "Duplicate implementations found for service protocol ':TestService':\n" ".*/duplicates.cfg:2\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service\n" ".*/duplicates.cfg:3\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/foo-test-service\n" "Duplicate implementations.*\n" ".*/duplicates.cfg:5\n" ".*test-service-two\n" ".*/duplicates.cfg:6\n" ".*test-service-two-duplicate")) (parse-bootstrap-configs! bootstraps)))) (testing "Duplicate service definitions between two files throws error" (let [bootstraps ["./dev-resources/bootstrapping/cli/duplicate_services/split_one.cfg" "./dev-resources/bootstrapping/cli/duplicate_services/split_two.cfg"]] (is (thrown-with-msg? IllegalArgumentException (re-pattern (str "Duplicate implementations found for service protocol ':TestService':\n" ".*/split_one.cfg:2\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/foo-test-service\n" ".*/split_two.cfg:2\n" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service\n" "Duplicate implementations.*\n" ".*/split_one.cfg:4\n" ".*test-service-two-duplicate\n" ".*/split_two.cfg:4\n" ".*test-service-two")) (parse-bootstrap-configs! bootstraps))))))) (deftest config-file-in-jar (testing "Bootstrapping via a config file contained in a .jar as command line option" (let [jar (file "./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar") bootstrap-url (str "jar:file:///" (.getAbsolutePath jar) "!/bootstrap.cfg")] (bootstrap-with-empty-config ["--bootstrap-config" bootstrap-url])))) (deftest config-from-classpath-test (testing "can locate bootstrap file on the classpath" (let [bootstrap-file "./dev-resources/bootstrapping/classpath/bootstrap.cfg" bootstrap-uri (str "file:" (.getCanonicalPath (file bootstrap-file)))] (with-additional-classpath-entries ["./dev-resources/bootstrapping/classpath/"] (let [found-bootstraps (config-from-classpath)] (is (= 1 (count found-bootstraps))) (is (= bootstrap-uri (first found-bootstraps))))))) (testing "can locate bootstrap file contained in a .jar on the classpath" (let [jar "./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar" jar-uri (str "file:" (.getAbsolutePath (file jar))) expected-resource-uri (format "jar:%s!/bootstrap.cfg" jar-uri)] (with-additional-classpath-entries ["./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar"] (let [found-bootstraps (config-from-classpath)] (is (= 1 (count found-bootstraps))) (is (= expected-resource-uri (first found-bootstraps)))))))) (deftest parse-bootstrap-config-test (testing "Missing service namespace logs warning" (with-test-logging (let [bootstrap-config "./dev-resources/bootstrapping/cli/fake_namespace_bootstrap.cfg"] (parse-bootstrap-config! bootstrap-config) (is (logged? (str "Unable to load service 'non-existent-service/test-service' from " "./dev-resources/bootstrapping/cli/fake_namespace_bootstrap.cfg:3") :warn))))) (testing "Missing service definition logs warning" (with-test-logging (let [bootstrap-config "./dev-resources/bootstrapping/cli/missing_definition_bootstrap.cfg"] (parse-bootstrap-config! bootstrap-config) (is (logged? (str "Unable to load service " "'puppetlabs.trapperkeeper.examples.bootstrapping.test-services/non-existent-service' " "from ./dev-resources/bootstrapping/cli/missing_definition_bootstrap.cfg:3") :warn))))) (testing "errors are thrown with line number and file" (let [bootstrap "./dev-resources/bootstrapping/cli/invalid_service_graph_bootstrap.cfg"] (is (thrown-with-msg? IllegalArgumentException (re-pattern (str "Problem loading service " "'puppetlabs.trapperkeeper.examples.bootstrapping.test-services/invalid-service-graph-service' " "from ./dev-resources/bootstrapping/cli/invalid_service_graph_bootstrap.cfg:1:\n" "Invalid service definition")) (parse-bootstrap-config! bootstrap)))))) (deftest get-annotated-bootstrap-entries-test (testing "file with comments" (let [bootstraps ["./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg"]] (let [entries (get-annotated-bootstrap-entries bootstraps)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 2} {:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap_with_comments.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/foo-test-service" :line-number 5}] entries))))) (testing "multiple bootstrap files" (let [bootstraps ["./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_one.cfg" "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_two.cfg"]] (let [entries (get-annotated-bootstrap-entries bootstraps)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_one.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service" :line-number 1} {:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_one.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 2} {:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_two.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/test-service-two" :line-number 1} {:bootstrap-file "./dev-resources/bootstrapping/cli/split_bootstraps/both/bootstrap_two.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/test-service-three" :line-number 2}] entries)))))) (deftest find-duplicates-test (testing "correct duplicates found" (let [items [{:important-key :one :other-key 2} {:important-key :one :other-key 3} {:important-key :two :other-key 4} {:important-key :three :other-key 5}]] (is (= {:one [{:important-key :one :other-key 2} {:important-key :one :other-key 3}]} (find-duplicates items :important-key)))))) (deftest check-duplicate-service-implementations!-test (testing "no duplicate service implementations does not throw error" (let [configs ["./dev-resources/bootstrapping/cli/bootstrap.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs) resolved-services (resolve-services! bootstrap-entries)] (check-duplicate-service-implementations! resolved-services bootstrap-entries))) (testing "duplicate service implementations throws error" (let [configs ["./dev-resources/bootstrapping/cli/duplicate_services/duplicates.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs) resolved-services (resolve-services! bootstrap-entries)] (is (thrown-with-msg? IllegalArgumentException #"Duplicate implementations found for service protocol ':TestService'" (check-duplicate-service-implementations! resolved-services bootstrap-entries)))))) (deftest remove-duplicate-entries-test (testing "single bootstrap with all duplicates" (testing "only the first duplicate found is kept" (let [configs ["./dev-resources/bootstrapping/cli/duplicate_entries.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/duplicate_entries.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 1}] (remove-duplicate-entries bootstrap-entries)))))) (testing "two copies of the same set of services" (let [configs ["./dev-resources/bootstrapping/cli/bootstrap.cfg" "./dev-resources/bootstrapping/cli/bootstrap.cfg"] bootstrap-entries (get-annotated-bootstrap-entries configs)] (is (= [{:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service" :line-number 1} {:bootstrap-file "./dev-resources/bootstrapping/cli/bootstrap.cfg" :entry "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" :line-number 2}] (remove-duplicate-entries bootstrap-entries)))))) (deftest read-config-test (testing "basic config" (let [config "./dev-resources/bootstrapping/cli/bootstrap.cfg"] (is (= ["puppetlabs.trapperkeeper.examples.bootstrapping.test-services/cli-test-service" "puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service"] (read-config config))))) (testing "jar uri" (let [jar "./dev-resources/bootstrapping/jar/this-jar-contains-a-bootstrap-config-file.jar" config (str "jar:file:///" (.getAbsolutePath (file jar)) "!/bootstrap.cfg")] (is (= ["puppetlabs.trapperkeeper.examples.bootstrapping.test-services/hello-world-service" ""] (read-config config))))) (testing "malformed uri is wrapped in our exception" (let [config "\n"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist" (read-config config))))) (testing "Non-absolute uri is wrapped in our exception" TODO This path is currently interpreted as a URI because TK checks if it 's a file , and if not , attemps to load as a URI (let [config "./not-a-file"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist" (println (read-config config)))))) (testing "Non-existent file in URI is wrapped in our exception" (let [config "file-a-file"] (is (thrown-with-msg? IllegalArgumentException #"Specified bootstrap config file does not exist" (read-config config))))))
490f67b805d092f8eb8539f8461d6c8cd750cb4137767e800d85c76254088e24
fpco/ide-backend
SrcDist.hs
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.SrcDist Copyright : 2004 -- -- Maintainer : -- Portability : portable -- -- This handles the @sdist@ command. The module exports an 'sdist' action but -- also some of the phases that make it up so that other tools can use just the -- bits they need. In particular the preparation of the tree of files to go -- into the source tarball is separated from actually building the source -- tarball. -- The ' createArchive ' action uses the external @tar@ program and assumes that it accepts the @-z@ flag . Neither of these assumptions are valid on Windows . -- The 'sdist' action now also does some distribution QA checks. Copyright ( c ) 2003 - 2004 , 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 nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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 . 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 Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} -- NOTE: FIX: we don't have a great way of testing this module, since -- we can't easily look inside a tarball once its created. module Distribution.Simple.SrcDist ( -- * The top level action sdist, -- ** Parts of 'sdist' printPackageProblems, prepareTree, createArchive, -- ** Snaphots prepareSnapshotTree, snapshotPackage, snapshotVersion, dateToSnapshotNumber, ) where import Distribution.PackageDescription ( PackageDescription(..), BuildInfo(..), Executable(..), Library(..) , TestSuite(..), TestSuiteInterface(..), Benchmark(..) , BenchmarkInterface(..) ) import Distribution.PackageDescription.Check ( PackageCheck(..), checkConfiguredPackage, checkPackageFiles ) import Distribution.Package ( PackageIdentifier(pkgVersion), Package(..), packageVersion ) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.Version ( Version(versionBranch) ) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose, withUTF8FileContents, writeUTF8File , installOrdinaryFile, installOrdinaryFiles, setFileExecutable , findFile, findFileWithExtension, matchFileGlob , withTempDirectory, defaultPackageDesc , die, warn, notice, setupMessage ) import Distribution.Simple.Setup (SDistFlags(..), fromFlag, flagToMaybe) import Distribution.Simple.PreProcess (PPSuffixHandler, ppSuffixes, preprocessComponent) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), withComponentsLBI ) import Distribution.Simple.BuildPaths ( autogenModuleName ) import Distribution.Simple.Program ( defaultProgramConfiguration, requireProgram, rawSystemProgram, tarProgram ) import Distribution.Text ( display ) import Control.Monad(when, unless) import Data.Char (toLower) import Data.List (partition, isPrefixOf) import Data.Maybe (isNothing, catMaybes) import System.Time (getClockTime, toCalendarTime, CalendarTime(..)) import System.Directory ( doesFileExist, Permissions(executable), getPermissions ) import Distribution.Verbosity (Verbosity) import System.FilePath ( (</>), (<.>), takeDirectory, dropExtension, isAbsolute ) -- |Create a source distribution. sdist :: PackageDescription -- ^information from the tarball -> Maybe LocalBuildInfo -- ^Information from configure -> SDistFlags -- ^verbosity & snapshot -> (FilePath -> FilePath) -- ^build prefix (temp dir) -> [PPSuffixHandler] -- ^ extra preprocessors (includes suffixes) -> IO () sdist pkg mb_lbi flags mkTmpDir pps = do -- do some QA printPackageProblems verbosity pkg when (isNothing mb_lbi) $ warn verbosity "Cannot run preprocessors. Run 'configure' command first." date <- toCalendarTime =<< getClockTime let pkg' | snapshot = snapshotPackage date pkg | otherwise = pkg case flagToMaybe (sDistDirectory flags) of Just targetDir -> do generateSourceDir targetDir pkg' notice verbosity $ "Source directory created: " ++ targetDir Nothing -> do createDirectoryIfMissingVerbose verbosity True tmpTargetDir withTempDirectory verbosity tmpTargetDir "sdist." $ \tmpDir -> do let targetDir = tmpDir </> tarBallName pkg' generateSourceDir targetDir pkg' targzFile <- createArchive verbosity pkg' mb_lbi tmpDir targetPref notice verbosity $ "Source tarball created: " ++ targzFile where generateSourceDir targetDir pkg' = do setupMessage verbosity "Building source dist for" (packageId pkg') prepareTree verbosity pkg' mb_lbi distPref targetDir pps when snapshot $ overwriteSnapshotPackageDesc verbosity pkg' targetDir verbosity = fromFlag (sDistVerbosity flags) snapshot = fromFlag (sDistSnapshot flags) distPref = fromFlag $ sDistDistPref flags targetPref = distPref tmpTargetDir = mkTmpDir distPref |Prepare a directory tree of source files . prepareTree :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file -> Maybe LocalBuildInfo ^dist -> FilePath -- ^source tree to populate ^extra preprocessors ( includes suffixes ) -> IO () prepareTree verbosity pkg_descr0 mb_lbi distPref targetDir pps = do createDirectoryIfMissingVerbose verbosity True targetDir -- maybe move the library files into place withLib $ \Library { exposedModules = modules, libBuildInfo = libBi } -> prepareDir verbosity pkg_descr distPref targetDir pps modules libBi -- move the executables into place withExe $ \Executable { modulePath = mainPath, buildInfo = exeBi } -> do prepareDir verbosity pkg_descr distPref targetDir pps [] exeBi srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs exeBi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs exeBi) mainPath Just pp -> return pp copyFileTo verbosity targetDir srcMainFile -- move the test suites into place withTest $ \t -> do let bi = testBuildInfo t prep = prepareDir verbosity pkg_descr distPref targetDir pps case testInterface t of TestSuiteExeV10 _ mainPath -> do prep [] bi srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs bi) mainPath Just pp -> return pp copyFileTo verbosity targetDir srcMainFile TestSuiteLibV09 _ m -> do prep [m] bi TestSuiteUnsupported tp -> die $ "Unsupported test suite type: " ++ show tp -- move the benchmarks into place withBenchmark $ \bm -> do let bi = benchmarkBuildInfo bm prep = prepareDir verbosity pkg_descr distPref targetDir pps case benchmarkInterface bm of BenchmarkExeV10 _ mainPath -> do prep [] bi srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs bi) mainPath Just pp -> return pp copyFileTo verbosity targetDir srcMainFile BenchmarkUnsupported tp -> die $ "Unsupported benchmark type: " ++ show tp flip mapM_ (dataFiles pkg_descr) $ \ filename -> do files <- matchFileGlob (dataDir pkg_descr </> filename) let dir = takeDirectory (dataDir pkg_descr </> filename) createDirectoryIfMissingVerbose verbosity True (targetDir </> dir) sequence_ [ installOrdinaryFile verbosity file (targetDir </> file) | file <- files ] when (not (null (licenseFile pkg_descr))) $ copyFileTo verbosity targetDir (licenseFile pkg_descr) flip mapM_ (extraSrcFiles pkg_descr) $ \ fpath -> do files <- matchFileGlob fpath sequence_ [ do copyFileTo verbosity targetDir file -- preserve executable bit on extra-src-files like ./configure perms <- getPermissions file when (executable perms) --only checks user x bit (setFileExecutable (targetDir </> file)) | file <- files ] -- copy the install-include files withLib $ \ l -> do let lbi = libBuildInfo l relincdirs = "." : filter (not.isAbsolute) (includeDirs lbi) incs <- mapM (findInc relincdirs) (installIncludes lbi) flip mapM_ incs $ \(_,fpath) -> copyFileTo verbosity targetDir fpath -- if the package was configured then we can run platform independent -- pre-processors and include those generated files case mb_lbi of Just lbi | not (null pps) -> do let lbi' = lbi{ buildDir = targetDir </> buildDir lbi } withComponentsLBI pkg_descr lbi' $ \c _ -> preprocessComponent pkg_descr c lbi' True verbosity pps _ -> return () -- setup isn't listed in the description file. hsExists <- doesFileExist "Setup.hs" lhsExists <- doesFileExist "Setup.lhs" if hsExists then copyFileTo verbosity targetDir "Setup.hs" else if lhsExists then copyFileTo verbosity targetDir "Setup.lhs" else writeUTF8File (targetDir </> "Setup.hs") $ unlines [ "import Distribution.Simple", "main = defaultMain"] -- the description file itself descFile <- defaultPackageDesc verbosity installOrdinaryFile verbosity descFile (targetDir </> descFile) where pkg_descr = mapAllBuildInfo filterAutogenModule pkg_descr0 filterAutogenModule bi = bi { otherModules = filter (/=autogenModule) (otherModules bi) } autogenModule = autogenModuleName pkg_descr0 findInc [] f = die ("can't find include file " ++ f) findInc (d:ds) f = do let path = (d </> f) b <- doesFileExist path if b then return (f,path) else findInc ds f We have to deal with all libs and executables , so we have local -- versions of these functions that ignore the 'buildable' attribute: withLib action = maybe (return ()) action (library pkg_descr) withExe action = mapM_ action (executables pkg_descr) withTest action = mapM_ action (testSuites pkg_descr) withBenchmark action = mapM_ action (benchmarks pkg_descr) -- | Prepare a directory tree of source files for a snapshot version. -- It is expected that the appropriate snapshot version has already been set in the package description , eg using ' snapshotPackage ' or ' snapshotVersion ' . -- prepareSnapshotTree :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file -> Maybe LocalBuildInfo ^dist -> FilePath -- ^source tree to populate ^extra preprocessors ( includes suffixes ) -> IO () prepareSnapshotTree verbosity pkg mb_lbi distPref targetDir pps = do prepareTree verbosity pkg mb_lbi distPref targetDir pps overwriteSnapshotPackageDesc verbosity pkg targetDir overwriteSnapshotPackageDesc :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file -> FilePath -- ^source tree -> IO () overwriteSnapshotPackageDesc verbosity pkg targetDir = do -- We could just writePackageDescription targetDescFile pkg_descr, -- but that would lose comments and formatting. descFile <- defaultPackageDesc verbosity withUTF8FileContents descFile $ writeUTF8File (targetDir </> descFile) . unlines . map (replaceVersion (packageVersion pkg)) . lines where replaceVersion :: Version -> String -> String replaceVersion version line | "version:" `isPrefixOf` map toLower line = "version: " ++ display version | otherwise = line | Modifies a ' PackageDescription ' by appending a snapshot number -- corresponding to the given date. -- snapshotPackage :: CalendarTime -> PackageDescription -> PackageDescription snapshotPackage date pkg = pkg { package = pkgid { pkgVersion = snapshotVersion date (pkgVersion pkgid) } } where pkgid = packageId pkg -- | Modifies a 'Version' by appending a snapshot number corresponding -- to the given date. -- snapshotVersion :: CalendarTime -> Version -> Version snapshotVersion date version = version { versionBranch = versionBranch version ++ [dateToSnapshotNumber date] } -- | Given a date produce a corresponding integer representation. -- For example given a date @18/03/2008@ produce the number @20080318@. -- dateToSnapshotNumber :: CalendarTime -> Int dateToSnapshotNumber date = year * 10000 + month * 100 + day where year = ctYear date month = fromEnum (ctMonth date) + 1 day = ctDay date -- |Create an archive from a tree of source files, and clean up the tree. createArchive :: Verbosity -- ^verbosity ^info from cabal file -> Maybe LocalBuildInfo -- ^info from configure -> FilePath -- ^source tree to archive -> FilePath -- ^name of archive to create -> IO FilePath createArchive verbosity pkg_descr mb_lbi tmpDir targetPref = do let tarBallFilePath = targetPref </> tarBallName pkg_descr <.> "tar.gz" (tarProg, _) <- requireProgram verbosity tarProgram (maybe defaultProgramConfiguration withPrograms mb_lbi) -- Hmm: I could well be skating on thinner ice here by using the -C option (=> GNU tar-specific?) -- [The prev. solution used pipes and sub-command sequences to set up the paths correctly, -- which is problematic in a Windows setting.] rawSystemProgram verbosity tarProg ["-C", tmpDir, "-czf", tarBallFilePath, tarBallName pkg_descr] return tarBallFilePath -- |Move the sources into place based on buildInfo prepareDir :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file ^dist -> FilePath -- ^TargetPrefix -> [PPSuffixHandler] -- ^ extra preprocessors (includes suffixes) -> [ModuleName] -- ^Exposed modules -> BuildInfo -> IO () prepareDir verbosity _pkg _distPref inPref pps modules bi = do let searchDirs = hsSourceDirs bi sources <- sequence [ let file = ModuleName.toFilePath module_ in findFileWithExtension suffixes searchDirs file >>= maybe (notFound module_) return | module_ <- modules ++ otherModules bi ] bootFiles <- sequence [ let file = ModuleName.toFilePath module_ fileExts = ["hs-boot", "lhs-boot"] in findFileWithExtension fileExts (hsSourceDirs bi) file | module_ <- modules ++ otherModules bi ] let allSources = sources ++ catMaybes bootFiles ++ cSources bi installOrdinaryFiles verbosity inPref (zip (repeat []) allSources) where suffixes = ppSuffixes pps ++ ["hs", "lhs"] notFound m = die $ "Error: Could not find module: " ++ display m ++ " with any suffix: " ++ show suffixes copyFileTo :: Verbosity -> FilePath -> FilePath -> IO () copyFileTo verbosity dir file = do let targetFile = dir </> file createDirectoryIfMissingVerbose verbosity True (takeDirectory targetFile) installOrdinaryFile verbosity file targetFile printPackageProblems :: Verbosity -> PackageDescription -> IO () printPackageProblems verbosity pkg_descr = do ioChecks <- checkPackageFiles pkg_descr "." let pureChecks = checkConfiguredPackage pkg_descr isDistError (PackageDistSuspicious _) = False isDistError _ = True (errors, warnings) = partition isDistError (pureChecks ++ ioChecks) unless (null errors) $ notice verbosity $ "Distribution quality errors:\n" ++ unlines (map explanation errors) unless (null warnings) $ notice verbosity $ "Distribution quality warnings:\n" ++ unlines (map explanation warnings) unless (null errors) $ notice verbosity "Note: the public hackage server would reject this package." ------------------------------------------------------------ -- | The name of the tarball without extension -- tarBallName :: PackageDescription -> String tarBallName = display . packageId mapAllBuildInfo :: (BuildInfo -> BuildInfo) -> (PackageDescription -> PackageDescription) mapAllBuildInfo f pkg = pkg { library = fmap mapLibBi (library pkg), executables = fmap mapExeBi (executables pkg), testSuites = fmap mapTestBi (testSuites pkg), benchmarks = fmap mapBenchBi (benchmarks pkg) } where mapLibBi lib = lib { libBuildInfo = f (libBuildInfo lib) } mapExeBi exe = exe { buildInfo = f (buildInfo exe) } mapTestBi t = t { testBuildInfo = f (testBuildInfo t) } mapBenchBi bm = bm { benchmarkBuildInfo = f (benchmarkBuildInfo bm) }
null
https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.14.0/Distribution/Simple/SrcDist.hs
haskell
--------------------------------------------------------------------------- | Module : Distribution.Simple.SrcDist Maintainer : Portability : portable This handles the @sdist@ command. The module exports an 'sdist' action but also some of the phases that make it up so that other tools can use just the bits they need. In particular the preparation of the tree of files to go into the source tarball is separated from actually building the source tarball. The 'sdist' action now also does some distribution QA checks. NOTE: FIX: we don't have a great way of testing this module, since we can't easily look inside a tarball once its created. * The top level action ** Parts of 'sdist' ** Snaphots |Create a source distribution. ^information from the tarball ^Information from configure ^verbosity & snapshot ^build prefix (temp dir) ^ extra preprocessors (includes suffixes) do some QA ^verbosity ^info from the cabal file ^source tree to populate maybe move the library files into place move the executables into place move the test suites into place move the benchmarks into place preserve executable bit on extra-src-files like ./configure only checks user x bit copy the install-include files if the package was configured then we can run platform independent pre-processors and include those generated files setup isn't listed in the description file. the description file itself versions of these functions that ignore the 'buildable' attribute: | Prepare a directory tree of source files for a snapshot version. It is expected that the appropriate snapshot version has already been set ^verbosity ^info from the cabal file ^source tree to populate ^verbosity ^info from the cabal file ^source tree We could just writePackageDescription targetDescFile pkg_descr, but that would lose comments and formatting. corresponding to the given date. | Modifies a 'Version' by appending a snapshot number corresponding to the given date. | Given a date produce a corresponding integer representation. For example given a date @18/03/2008@ produce the number @20080318@. |Create an archive from a tree of source files, and clean up the tree. ^verbosity ^info from configure ^source tree to archive ^name of archive to create Hmm: I could well be skating on thinner ice here by using the -C option (=> GNU tar-specific?) [The prev. solution used pipes and sub-command sequences to set up the paths correctly, which is problematic in a Windows setting.] |Move the sources into place based on buildInfo ^verbosity ^info from the cabal file ^TargetPrefix ^ extra preprocessors (includes suffixes) ^Exposed modules ---------------------------------------------------------- | The name of the tarball without extension
Copyright : 2004 The ' createArchive ' action uses the external @tar@ program and assumes that it accepts the @-z@ flag . Neither of these assumptions are valid on Windows . Copyright ( c ) 2003 - 2004 , 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 nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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 . 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 Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Simple.SrcDist ( sdist, printPackageProblems, prepareTree, createArchive, prepareSnapshotTree, snapshotPackage, snapshotVersion, dateToSnapshotNumber, ) where import Distribution.PackageDescription ( PackageDescription(..), BuildInfo(..), Executable(..), Library(..) , TestSuite(..), TestSuiteInterface(..), Benchmark(..) , BenchmarkInterface(..) ) import Distribution.PackageDescription.Check ( PackageCheck(..), checkConfiguredPackage, checkPackageFiles ) import Distribution.Package ( PackageIdentifier(pkgVersion), Package(..), packageVersion ) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.Version ( Version(versionBranch) ) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose, withUTF8FileContents, writeUTF8File , installOrdinaryFile, installOrdinaryFiles, setFileExecutable , findFile, findFileWithExtension, matchFileGlob , withTempDirectory, defaultPackageDesc , die, warn, notice, setupMessage ) import Distribution.Simple.Setup (SDistFlags(..), fromFlag, flagToMaybe) import Distribution.Simple.PreProcess (PPSuffixHandler, ppSuffixes, preprocessComponent) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), withComponentsLBI ) import Distribution.Simple.BuildPaths ( autogenModuleName ) import Distribution.Simple.Program ( defaultProgramConfiguration, requireProgram, rawSystemProgram, tarProgram ) import Distribution.Text ( display ) import Control.Monad(when, unless) import Data.Char (toLower) import Data.List (partition, isPrefixOf) import Data.Maybe (isNothing, catMaybes) import System.Time (getClockTime, toCalendarTime, CalendarTime(..)) import System.Directory ( doesFileExist, Permissions(executable), getPermissions ) import Distribution.Verbosity (Verbosity) import System.FilePath ( (</>), (<.>), takeDirectory, dropExtension, isAbsolute ) -> IO () sdist pkg mb_lbi flags mkTmpDir pps = do printPackageProblems verbosity pkg when (isNothing mb_lbi) $ warn verbosity "Cannot run preprocessors. Run 'configure' command first." date <- toCalendarTime =<< getClockTime let pkg' | snapshot = snapshotPackage date pkg | otherwise = pkg case flagToMaybe (sDistDirectory flags) of Just targetDir -> do generateSourceDir targetDir pkg' notice verbosity $ "Source directory created: " ++ targetDir Nothing -> do createDirectoryIfMissingVerbose verbosity True tmpTargetDir withTempDirectory verbosity tmpTargetDir "sdist." $ \tmpDir -> do let targetDir = tmpDir </> tarBallName pkg' generateSourceDir targetDir pkg' targzFile <- createArchive verbosity pkg' mb_lbi tmpDir targetPref notice verbosity $ "Source tarball created: " ++ targzFile where generateSourceDir targetDir pkg' = do setupMessage verbosity "Building source dist for" (packageId pkg') prepareTree verbosity pkg' mb_lbi distPref targetDir pps when snapshot $ overwriteSnapshotPackageDesc verbosity pkg' targetDir verbosity = fromFlag (sDistVerbosity flags) snapshot = fromFlag (sDistSnapshot flags) distPref = fromFlag $ sDistDistPref flags targetPref = distPref tmpTargetDir = mkTmpDir distPref |Prepare a directory tree of source files . -> Maybe LocalBuildInfo ^dist ^extra preprocessors ( includes suffixes ) -> IO () prepareTree verbosity pkg_descr0 mb_lbi distPref targetDir pps = do createDirectoryIfMissingVerbose verbosity True targetDir withLib $ \Library { exposedModules = modules, libBuildInfo = libBi } -> prepareDir verbosity pkg_descr distPref targetDir pps modules libBi withExe $ \Executable { modulePath = mainPath, buildInfo = exeBi } -> do prepareDir verbosity pkg_descr distPref targetDir pps [] exeBi srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs exeBi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs exeBi) mainPath Just pp -> return pp copyFileTo verbosity targetDir srcMainFile withTest $ \t -> do let bi = testBuildInfo t prep = prepareDir verbosity pkg_descr distPref targetDir pps case testInterface t of TestSuiteExeV10 _ mainPath -> do prep [] bi srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs bi) mainPath Just pp -> return pp copyFileTo verbosity targetDir srcMainFile TestSuiteLibV09 _ m -> do prep [m] bi TestSuiteUnsupported tp -> die $ "Unsupported test suite type: " ++ show tp withBenchmark $ \bm -> do let bi = benchmarkBuildInfo bm prep = prepareDir verbosity pkg_descr distPref targetDir pps case benchmarkInterface bm of BenchmarkExeV10 _ mainPath -> do prep [] bi srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs bi) mainPath Just pp -> return pp copyFileTo verbosity targetDir srcMainFile BenchmarkUnsupported tp -> die $ "Unsupported benchmark type: " ++ show tp flip mapM_ (dataFiles pkg_descr) $ \ filename -> do files <- matchFileGlob (dataDir pkg_descr </> filename) let dir = takeDirectory (dataDir pkg_descr </> filename) createDirectoryIfMissingVerbose verbosity True (targetDir </> dir) sequence_ [ installOrdinaryFile verbosity file (targetDir </> file) | file <- files ] when (not (null (licenseFile pkg_descr))) $ copyFileTo verbosity targetDir (licenseFile pkg_descr) flip mapM_ (extraSrcFiles pkg_descr) $ \ fpath -> do files <- matchFileGlob fpath sequence_ [ do copyFileTo verbosity targetDir file perms <- getPermissions file (setFileExecutable (targetDir </> file)) | file <- files ] withLib $ \ l -> do let lbi = libBuildInfo l relincdirs = "." : filter (not.isAbsolute) (includeDirs lbi) incs <- mapM (findInc relincdirs) (installIncludes lbi) flip mapM_ incs $ \(_,fpath) -> copyFileTo verbosity targetDir fpath case mb_lbi of Just lbi | not (null pps) -> do let lbi' = lbi{ buildDir = targetDir </> buildDir lbi } withComponentsLBI pkg_descr lbi' $ \c _ -> preprocessComponent pkg_descr c lbi' True verbosity pps _ -> return () hsExists <- doesFileExist "Setup.hs" lhsExists <- doesFileExist "Setup.lhs" if hsExists then copyFileTo verbosity targetDir "Setup.hs" else if lhsExists then copyFileTo verbosity targetDir "Setup.lhs" else writeUTF8File (targetDir </> "Setup.hs") $ unlines [ "import Distribution.Simple", "main = defaultMain"] descFile <- defaultPackageDesc verbosity installOrdinaryFile verbosity descFile (targetDir </> descFile) where pkg_descr = mapAllBuildInfo filterAutogenModule pkg_descr0 filterAutogenModule bi = bi { otherModules = filter (/=autogenModule) (otherModules bi) } autogenModule = autogenModuleName pkg_descr0 findInc [] f = die ("can't find include file " ++ f) findInc (d:ds) f = do let path = (d </> f) b <- doesFileExist path if b then return (f,path) else findInc ds f We have to deal with all libs and executables , so we have local withLib action = maybe (return ()) action (library pkg_descr) withExe action = mapM_ action (executables pkg_descr) withTest action = mapM_ action (testSuites pkg_descr) withBenchmark action = mapM_ action (benchmarks pkg_descr) in the package description , eg using ' snapshotPackage ' or ' snapshotVersion ' . -> Maybe LocalBuildInfo ^dist ^extra preprocessors ( includes suffixes ) -> IO () prepareSnapshotTree verbosity pkg mb_lbi distPref targetDir pps = do prepareTree verbosity pkg mb_lbi distPref targetDir pps overwriteSnapshotPackageDesc verbosity pkg targetDir -> IO () overwriteSnapshotPackageDesc verbosity pkg targetDir = do descFile <- defaultPackageDesc verbosity withUTF8FileContents descFile $ writeUTF8File (targetDir </> descFile) . unlines . map (replaceVersion (packageVersion pkg)) . lines where replaceVersion :: Version -> String -> String replaceVersion version line | "version:" `isPrefixOf` map toLower line = "version: " ++ display version | otherwise = line | Modifies a ' PackageDescription ' by appending a snapshot number snapshotPackage :: CalendarTime -> PackageDescription -> PackageDescription snapshotPackage date pkg = pkg { package = pkgid { pkgVersion = snapshotVersion date (pkgVersion pkgid) } } where pkgid = packageId pkg snapshotVersion :: CalendarTime -> Version -> Version snapshotVersion date version = version { versionBranch = versionBranch version ++ [dateToSnapshotNumber date] } dateToSnapshotNumber :: CalendarTime -> Int dateToSnapshotNumber date = year * 10000 + month * 100 + day where year = ctYear date month = fromEnum (ctMonth date) + 1 day = ctDay date ^info from cabal file -> IO FilePath createArchive verbosity pkg_descr mb_lbi tmpDir targetPref = do let tarBallFilePath = targetPref </> tarBallName pkg_descr <.> "tar.gz" (tarProg, _) <- requireProgram verbosity tarProgram (maybe defaultProgramConfiguration withPrograms mb_lbi) rawSystemProgram verbosity tarProg ["-C", tmpDir, "-czf", tarBallFilePath, tarBallName pkg_descr] return tarBallFilePath ^dist -> BuildInfo -> IO () prepareDir verbosity _pkg _distPref inPref pps modules bi = do let searchDirs = hsSourceDirs bi sources <- sequence [ let file = ModuleName.toFilePath module_ in findFileWithExtension suffixes searchDirs file >>= maybe (notFound module_) return | module_ <- modules ++ otherModules bi ] bootFiles <- sequence [ let file = ModuleName.toFilePath module_ fileExts = ["hs-boot", "lhs-boot"] in findFileWithExtension fileExts (hsSourceDirs bi) file | module_ <- modules ++ otherModules bi ] let allSources = sources ++ catMaybes bootFiles ++ cSources bi installOrdinaryFiles verbosity inPref (zip (repeat []) allSources) where suffixes = ppSuffixes pps ++ ["hs", "lhs"] notFound m = die $ "Error: Could not find module: " ++ display m ++ " with any suffix: " ++ show suffixes copyFileTo :: Verbosity -> FilePath -> FilePath -> IO () copyFileTo verbosity dir file = do let targetFile = dir </> file createDirectoryIfMissingVerbose verbosity True (takeDirectory targetFile) installOrdinaryFile verbosity file targetFile printPackageProblems :: Verbosity -> PackageDescription -> IO () printPackageProblems verbosity pkg_descr = do ioChecks <- checkPackageFiles pkg_descr "." let pureChecks = checkConfiguredPackage pkg_descr isDistError (PackageDistSuspicious _) = False isDistError _ = True (errors, warnings) = partition isDistError (pureChecks ++ ioChecks) unless (null errors) $ notice verbosity $ "Distribution quality errors:\n" ++ unlines (map explanation errors) unless (null warnings) $ notice verbosity $ "Distribution quality warnings:\n" ++ unlines (map explanation warnings) unless (null errors) $ notice verbosity "Note: the public hackage server would reject this package." tarBallName :: PackageDescription -> String tarBallName = display . packageId mapAllBuildInfo :: (BuildInfo -> BuildInfo) -> (PackageDescription -> PackageDescription) mapAllBuildInfo f pkg = pkg { library = fmap mapLibBi (library pkg), executables = fmap mapExeBi (executables pkg), testSuites = fmap mapTestBi (testSuites pkg), benchmarks = fmap mapBenchBi (benchmarks pkg) } where mapLibBi lib = lib { libBuildInfo = f (libBuildInfo lib) } mapExeBi exe = exe { buildInfo = f (buildInfo exe) } mapTestBi t = t { testBuildInfo = f (testBuildInfo t) } mapBenchBi bm = bm { benchmarkBuildInfo = f (benchmarkBuildInfo bm) }
92636a746e28884bc5e8c59990a56453cad6533344f7748789a5156355218480
crategus/cl-cffi-gtk
gtk.assistant.lisp
;;; ---------------------------------------------------------------------------- ;;; gtk.assistant.lisp ;;; ;;; The documentation of this file is taken from the GTK 3 Reference Manual Version 3.24 and modified to document the Lisp binding to the GTK library . ;;; See <>. The API documentation of the Lisp binding is available from < -cffi-gtk/ > . ;;; Copyright ( C ) 2009 - 2011 Copyright ( C ) 2011 - 2021 ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU Lesser General Public License for Lisp as published by the Free Software Foundation , either version 3 of the ;;; License, or (at your option) any later version and with a preamble to the GNU Lesser General Public License that clarifies the terms for use ;;; with Lisp programs and is referred as the LLGPL. ;;; ;;; 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 and the preamble to the Gnu Lesser ;;; General Public License. If not, see </> ;;; and <>. ;;; ---------------------------------------------------------------------------- ;;; GtkAssistant ;;; ;;; A widget used to guide users through multi-step operations ;;; ;;; Types and Values ;;; ;;; GtkAssistant GtkAssistantPageType ;;; ;;; Functions ;;; ;;; gtk_assistant_new ;;; gtk_assistant_get_current_page ;;; gtk_assistant_set_current_page ;;; gtk_assistant_get_n_pages ;;; gtk_assistant_get_nth_page ;;; gtk_assistant_prepend_page ;;; gtk_assistant_append_page ;;; gtk_assistant_insert_page ;;; gtk_assistant_remove_page ;;; ;;; GtkAssistantPageFunc ;;; gtk_assistant_set_forward_page_func ;;; ;;; gtk_assistant_set_page_type gtk_assistant_get_page_type gtk_assistant_set_page_title ;;; gtk_assistant_get_page_title ;;; gtk_assistant_set_page_header_image deprecated ;;; gtk_assistant_get_page_header_image deprecated ;;; gtk_assistant_set_page_side_image deprecated ;;; gtk_assistant_get_page_side_image deprecated ;;; gtk_assistant_set_page_complete ;;; gtk_assistant_get_page_complete ;;; gtk_assistant_set_page_has_padding ;;; gtk_assistant_get_page_has_padding ;;; gtk_assistant_add_action_widget ;;; gtk_assistant_remove_action_widget ;;; gtk_assistant_update_buttons_state ;;; gtk_assistant_commit ;;; gtk_assistant_next_page ;;; gtk_assistant_previous_page ;;; ;;; Properties ;;; ;;; gint use-header-bar Read / Write / Construct Only ;;; ;;; Child Properties ;;; gboolean complete Read / Write ;;; gboolean has-padding Read / Write ;;; GdkPixbuf* header-image Read / Write GtkAssistantPageType page - type Read / Write GdkPixbuf * sidebar - image Read / Write ;;; gchar* title Read / Write ;;; ;;; Style Properties ;;; ;;; gint content-padding Read ;;; gint header-padding Read ;;; ;;; Signals ;;; ;;; void apply Run Last ;;; void cancel Run Last ;;; void close Run Last ;;; void escape Action ;;; void prepare Run Last ;;; ;;; Object Hierarchy ;;; ;;; GObject ;;; ╰── GInitiallyUnowned ╰ ─ ─ ╰ ─ ─ GtkContainer ╰ ─ ─ ╰ ─ ─ GtkWindow ;;; ╰── GtkAssistant ;;; ;;; Implemented Interfaces ;;; GtkAssistant implements AtkImplementorIface and GtkBuildable . ;;; ---------------------------------------------------------------------------- (in-package :gtk) ;;; ---------------------------------------------------------------------------- enum GtkAssistantPageType ;;; ---------------------------------------------------------------------------- (define-g-enum "GtkAssistantPageType" gtk-assistant-page-type (:export t :type-initializer "gtk_assistant_page_type_get_type") (:content 0) (:intro 1) (:confirm 2) (:summary 3) (:progress 4) (:custom 5)) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-page-type atdoc:*symbol-name-alias*) "GEnum" (gethash 'gtk-assistant-page-type atdoc:*external-symbols*) "@version{*2021-12-3} @begin{short} An enumeration for determining the page role inside the @class{gtk-assistant} widget. It is used to handle buttons sensitivity and visibility. @end{short} Note that an assistant needs to end its page flow with a page of @code{:confirm}, @code{:summary} or @code{:progress} type to be correct. The Cancel button will only be shown if the page is not \"committed\". See the @fun{gtk-assistant-commit} function for details. @begin{pre} (define-g-enum \"GtkAssistantPageType\" gtk-assistant-page-type (:export t :type-initializer \"gtk_assistant_page_type_get_type\") (:content 0) (:intro 1) (:confirm 2) (:summary 3) (:progress 4) (:custom 5)) @end{pre} @begin[code]{table} @entry[:content]{The page has regular contents. Both the Back and Forward buttons will be shown.} @entry[:intro]{The page contains an introduction to the assistant task. Only the Forward button will be shown if there is a next page.} @entry[:confirm]{The page lets the user confirm or deny the changes. The Back and Apply buttons will be shown.} @entry[:summary]{The page informs the user of the changes done. Only the Close button will be shown.} @entry[:progress]{Used for tasks that take a long time to complete, blocks the assistant until the page is marked as complete. Only the Back button will be shown.} @entry[:custom]{Used for when other page types are not appropriate. No buttons will be shown, and the application must add its own buttons through the @fun{gtk-assistant-add-action-widget} function.} @end{table} @see-class{gtk-assistant} @see-function{gtk-assistant-commit} @see-function{gtk-assistant-add-action-widget}") ;;; ---------------------------------------------------------------------------- struct GtkAssistant ;;; ---------------------------------------------------------------------------- (define-g-object-class "GtkAssistant" gtk-assistant (:superclass gtk-window :export t :interfaces ("AtkImplementorIface" "GtkBuildable") :type-initializer "gtk_assistant_get_type") ((use-header-bar gtk-assistant-use-header-bar "use-header-bar" "gint" t t))) #+cl-cffi-gtk-documentation (setf (documentation 'gtk-assistant 'type) "@version{*2021-11-2} @begin{short} A @sym{gtk-assistant} widget is used to represent a generally complex operation splitted in several steps, guiding the user through its pages and controlling the page flow to collect the necessary data. @end{short} @image[assistant]{} The design of the @sym{gtk-assistant} widget is that it controls what buttons to show and to make sensitive, based on what it knows about the page sequence and the type of each page, in addition to state information like the page completion and committed status. If you have a case that does not quite fit in an assistants way of handling buttons, you can use the @code{:custom} page type of the @symbol{gtk-assistant-page-type} enumeration and handle buttons yourself. @begin[GtkAssistant as GtkBuildable]{dictionary} The @sym{gtk-assistant} implementation of the @class{gtk-buildable} interface exposes the action area as internal children with the name @code{\"action_area\"}. To add pages to an assistant in a @class{gtk-builder} object, simply add it as a @code{<child>} to the @sym{gtk-assistant} widget and set its child properties as necessary. @end{dictionary} @begin[CSS nodes]{dictionary} The @sym{gtk-assistant} implementation has a single CSS node with the name @code{assistant}. @end{dictionary} @begin[Child Property Details]{dictionary} @begin[code]{table} @begin[complete]{entry} The @code{complete} child property of type @code{:boolean} (Read / Write) @br{} Setting to @em{true} marks a page as complete, i.e. all the required fields are filled out. GTK uses this information to control the sensitivity of the navigation buttons. @br{} Default value: @em{false} @br{} @end{entry} @begin[has-padding]{entry} The @code{has-padding} child property of type @code{:boolean} (Read / Write) @br{} Whether the assistant adds padding around the page. Since 3.18 @br{} Default value: @em{true} @end{entry} @begin[header-image]{entry} The @code{header-image} child property of type @class{gdk-pixbuf} (Read / Write) @br{} The image used to be displayed in the page header. @br{} @em{Warning:} The @code{header-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, a header is no longer shown. Add your header decoration to the page content instead. @end{entry} @begin[page-type]{entry} The @code{page-type} child property of type @symbol{gtk-assistant-page-type} (Read / Write) @br{} The type of the assistant page. @br{} Default value: @code{:content} @end{entry} @begin[sidebar-image]{entry} The @code{sidebar-image} child property of type @class{gdk-pixbuf} (Read / Write) @br{} The image used to be displayed in the sidebar. @br{} @em{Warning:} The @code{sidebar-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, the sidebar image is no longer shown. @end{entry} @begin[title]{entry} The @code{title} child property of type @code{:string} (Read / Write) @br{} The title of the page. @br{} Default value: @code{nil} @end{entry} @end{table} @end{dictionary} @begin[Style Property Details]{dictionary} @begin[code]{table} @begin[content-padding]{entry} The @code{content-padding} style property of type @code{:int} (Read) @br{} Number of pixels around the content pages. @br{} @em{Warning:} The @code{content-padding} style property has been deprecated since version 3.20 and should not be used in newly written code. This style property is ignored. @br{} Allowed values: >= 0 @br{} Default value: 1 @end{entry} @begin[header-padding]{entry} The @code{header-padding} style property of type @code{:int} (Read) @br{} Number of pixels around the header. @br{} @em{Warning:} The @code{content-padding} has been deprecated since version 3.20 and should not be used in newly written code. This style property is ignored. @br{} Allowed values: >= 0 @br{} Default value: 6 @end{entry} @end{table} @end{dictionary} @begin[Signal Details]{dictionary} @subheading{The \"apply\" signal} @begin{pre} lambda (assistant) :run-last @end{pre} The signal is emitted when the Apply button is clicked. The default behavior of the assistant is to switch to the page after the current page, unless the current page is the last one. A handler for the \"apply\" signal should carry out the actions for which the wizard has collected data. If the action takes a long time to complete, you might consider putting a @code{:progress} page after the @code{:confirm} page and handle this operation within the \"prepare\" signal of the progress page. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"cancel\" signal} @begin{pre} lambda (assistant) :run-last @end{pre} The signal is emitted when the Cancel button is clicked. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"close\" signal} @begin{pre} lambda (assistant) :run-last @end{pre} The signal is emitted either when the Close button of a summary page is clicked, or when the Apply button in the last page in the flow is clicked, which is the @code{:confirm} page. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"escape\" signal} @begin{pre} lambda (assistant) :action @end{pre} No documentation. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"prepare\" signal} @begin{pre} lambda (assistant page) :run-last @end{pre} The signal is emitted when a new page is set as the assistants current page, before making the new page visible. A handler for this signal can do any preparations which are necessary before showing the page. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @entry[page]{The @class{gtk-widget} widget for the current page.} @end{table} @end{dictionary} @see-slot{gtk-assistant-use-header-bar}") ;;; ---------------------------------------------------------------------------- ;;; Property and Accessor Details ;;; ---------------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (register-object-type "GtkAssistant" 'gtk-assistant)) ;;; --- gtk-assistant-use-header-bar ------------------------------------------- #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "use-header-bar" 'gtk-assistant) 't) "The @code{use-header-bar} property of type @code{:int} (Read / Write / Construct) @br{} @em{True} if the assistant uses a header bar for action buttons instead of the action area. For technical reasons, this property is declared as an integer property, use the value 1 for @em{true} or -1 for @em{false}. @br{} Allowed values: [-1, 1] @br{} Default value: -1") #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-use-header-bar atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-use-header-bar 'function) "@version{2021-10-27} @syntax[]{(gtk-assistant-use-header-bar object) => setting} @syntax[]{(setf (gtk-assistant-use-header-bar object) setting)} @argument[object]{a @class{gtk-assistant} widget} @argument[setting]{@em{true} if the assistant uses a header bar} @begin{short} Accessor of the @slot[gtk-assistant]{use-header-bar} slot of the @class{gtk-assistant} class. @end{short} @em{True} if the assistant uses a header bar for action buttons instead of the action area. For technical reasons, this property is declared as an integer property, use the value 1 for @em{true} or -1 for @em{false}. @see-class{gtk-assistant} @see-class{gtk-header-bar}") ;;; ---------------------------------------------------------------------------- ;;; Accessors of the Child Properties ;;; ---------------------------------------------------------------------------- ;;; --- gtk-assistant-child-complete ------------------------------------------- (define-child-property "GtkAssistant" gtk-assistant-child-complete "complete" "gboolean" t t t) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-complete atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-complete 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-complete container child) => complete} @syntax[]{(setf (gtk-assistant-child-complete container child) complete)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[complete]{a boolean whether the page is complete} @begin{short} Accessor of the @code{complete} child property of the @class{gtk-assistant} class. @end{short} Setting the @code{complete} child property to @em{true} marks a page as complete, i.e. all the required fields are filled out. GTK uses this information to control the sensitivity of the navigation buttons. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-page-complete}") ;;; --- gtk-assistant-child-has-padding ---------------------------------------- #+gtk-3-18 (define-child-property "GtkAssistant" gtk-assistant-child-has-padding "has-padding" "gboolean" t t t) #+(and gtk-3-18 cl-cffi-gtk-documentation) (setf (gethash 'gtk-assistant-child-has-padding atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-has-padding 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-has-padding container child) => setting} @syntax[]{(setf (gtk-assistant-child-has-padding container child) setting)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[setting]{a boolean whether the assistant adds padding around the page} @begin{short} Accessor of the @code{has-padding} child property of the @class{gtk-assistant} class. @end{short} Whether the assistant adds padding around the page. Since 3.18 @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-page-has-padding}") ;;; --- gtk-assistant-child-header-image --------------------------------------- ;; not exported (define-child-property "GtkAssistant" gtk-assistant-child-header-image "header-image" "GdkPixbuf" t t nil) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-header-image atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-header-image 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-header-image container child) => image} @syntax[]{(setf (gtk-assistant-child-header-image container child) image)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[image]{a @class{gdk-pixbuf} image} @begin{short} Accessor of the @code{header-image} child property of the @class{gtk-assistant} class. @end{short} The image used to be displayed in the page header. @begin[Warning]{dictionary} The @code{header-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, a header is no longer shown. Add your header decoration to the page content instead. @end{dictionary} @see-class{gtk-assistant} @see-class{gtk-widget} @see-class{gdk-pixbuf}") ;;; --- gtk-assistant-child-page-type ------------------------------------------ (define-child-property "GtkAssistant" gtk-assistant-child-page-type "page-type" "GtkAssistantPageType" t t t) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-page-type atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-page-type 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-page-type container child) => ptype} @syntax[]{(setf (gtk-assistant-child-page-type container child) ptype)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[ptype]{a value of the @symbol{gtk-assistant-page-type} enumeration} @begin{short} Accessor of the @code{page-type} child property of the @class{gtk-assistant} class. @end{short} The page type determines the page behavior in the assistant. @see-class{gtk-assistant} @see-class{gtk-widget} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-child-page-type}") ;;; --- gtk-assistant-child-sidebar-image -------------------------------------- ;; not exported (define-child-property "GtkAssistant" gtk-assistant-child-sidebar-image "sidebar-image" "GdkPixbuf" t t nil) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-sidebar-image atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-sidebar-image 'function) "@version{2021-10-26} @syntax[]{(gtk-assistant-child-sidebar-image container child) => image} @syntax[]{(setf (gtk-assistant-child-sidebar-image container child) image)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[image]{a @class{gdk-pixbuf} image} @begin{short} Accessor of the @code{sidebar-image} child property of the @class{gtk-assistant} class. @end{short} The image used to be displayed in the sidebar. @begin[Warning]{dictionary} The @code{sidebar-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, the sidebar image is no longer shown. @end{dictionary} @see-class{gtk-assistant} @see-class{gtk-widget} @see-class{gdk-pixbuf}") ;;; --- gtk-assistant-child-title ---------------------------------------------- (define-child-property "GtkAssistant" gtk-assistant-child-title "title" "gchararray" t t t) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-title atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-title 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-title container child) => title} @syntax[]{(setf (gtk-assistant-child-title container child) title)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[title]{a string with the title of the page} @begin{short} Accessor of the @code{title} child property of the @class{gtk-assistant} class. @end{short} The title of the page. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-asssistant-page-title}") ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_new () ;;; ---------------------------------------------------------------------------- (defun gtk-assistant-new () #+cl-cffi-gtk-documentation "@version{2021-10-26} @return{A @class{gtk-assistant} widget.} @begin{short} Creates a new assistant. @end{short} @see-class{gtk-assistant}" (make-instance 'gtk-assistant)) (export 'gtk-assistant-new) ;;; ---------------------------------------------------------------------------- gtk_assistant_get_current_page ( ) ;;; gtk_assistant_set_current_page () -> gtk-assistant-current-page ;;; ---------------------------------------------------------------------------- (defun (setf gtk-assistant-current-page) (index assistant) (foreign-funcall "gtk_assistant_set_current_page" (g-object gtk-assistant) assistant :int index :void) index) (defcfun ("gtk_assistant_get_current_page" gtk-assistant-current-page) :int #+cl-cffi-gtk-documentation "@version{*2021-11-1} @syntax[]{(gtk-assistant-current-page assistant) => index} @syntax[]{(setf (gtk-assistant-current-page assistant) index)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[index]{an integer with the index of the page to switch to, starting from 0, if negative, the last page will be used, if greater than the number of pages in the assistant, nothing will be done} @begin{short} Accessor of the current page of the assistant. @end{short} The @sym{gtk-assistant-current-page} function returns the page number of the current page in the assistant. The @sym{(setf gtk-assistant-current-page)} function switches the page in the assistant to @arg{index}. Note that this will only be necessary in custom buttons, as the assistant flow can be set with the @fun{gtk-assistant-set-forward-page-func} function. @see-class{gtk-assistant} @see-function{gtk-assistant-set-forward-page-func}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-current-page) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_get_n_pages () -> gtk-assistant-n-pages ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_get_n_pages" gtk-assistant-n-pages) :int #+cl-cffi-gtk-documentation "@version{*2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @return{An integer with the number of pages in @arg{assistant}.} @begin{short} Returns the number of pages in the assistant. @end{short} @see-class{gtk-assistant}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-n-pages) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_get_nth_page () -> gtk-assistant-nth-page ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_get_nth_page" gtk-assistant-nth-page) (g-object gtk-widget) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @argument[index]{an integer with the index of a page in @arg{assistant}, or -1 to get the last page} @return{The @class{gtk-widget} child widget, or @code{nil} if the @arg{index} argument is out of bounds.} @begin{short} Returns the child widget contained in the assistant with the given page index. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget}" (assistant (g-object gtk-assistant)) (index :int)) (export 'gtk-assistant-nth-page) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_prepend_page () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_prepend_page" gtk-assistant-prepend-page) :int #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of the assistant} @return{An integer with the index starting at 0 of the inserted page.} @begin{short} Prepends a page to the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-append-page} @see-function{gtk-assistant-insert-page} @see-function{gtk-assistant-remove-page}" (assistant (g-object gtk-assistant)) (page (g-object gtk-widget))) (export 'gtk-assistant-prepend-page) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_append_page () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_append_page" gtk-assistant-append-page) :int #+cl-cffi-gtk-documentation "@version{*2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of the assistant} @return{An integer with the index starting at 0 of the inserted page.} @begin{short} Appends a page to the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-prepend-page} @see-function{gtk-assistant-insert-page} @see-function{gtk-assistant-remove-page}" (assistant (g-object gtk-assistant)) (page (g-object gtk-widget))) (export 'gtk-assistant-append-page) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_insert_page () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_insert_page" gtk-assistant-insert-page) :int #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of the assistant} @argument[position]{an integer with the index starting at 0 at which to insert @arg{page}, or -1 to append @arg{page} to the assistant} @return{The index starting from 0 of the inserted page.} @begin{short} Inserts a page in the assistant at a given position. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-append-page} @see-function{gtk-assistant-prepend-page} @see-function{gtk-assistant-remove-page}" (assistant (g-object gtk-assistant)) (page (g-object gtk-widget)) (position :int)) (export 'gtk-assistant-insert-page) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_remove_page () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_remove_page" gtk-assistant-remove-page) :void #+cl-cffi-gtk-documentation "@version{2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @argument[index]{an integer with the index of a page in the assistant, or -1 to remove the last page} @begin{short} Removes the page with the given page index from the assistant. @end{short} @see-class{gtk-assistant} @see-function{gtk-assistant-append-page} @see-function{gtk-assistant-prepend-page} @see-function{gtk-assistant-insert-page}" (assistant (g-object gtk-assistant)) (index :int)) (export 'gtk-assistant-remove-page) ;;; ---------------------------------------------------------------------------- ;;; GtkAssistantPageFunc () ;;; ---------------------------------------------------------------------------- (define-cb-methods gtk-assistant-page-func :int ((current-page :int))) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-page-func atdoc:*symbol-name-alias*) "Callback" (gethash 'gtk-assistant-page-func atdoc:*external-symbols*) "@version{2021-10-26} @begin{short} A callback function used by the @fun{gtk-assistant-set-forward-page-func} function to know which is the next page given a current one. @end{short} It is called both for computing the next page when the user presses the Forward button and for handling the behavior of the Last button. @begin{pre} lambda (current) @end{pre} @begin[code]{table} @entry[current]{An integer with the page number used to calculate the next page.} @entry[Returns]{An integer with the next page number.} @end{table} @see-class{gtk-assistant} @see-function{gtk-assistant-set-forward-page-func}") (export 'gtk-assistant-page-func) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_set_forward_page_func () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_set_forward_page_func" %gtk-assistant-set-forward-page-func) :void (assistant (g-object gtk-assistant)) (func :pointer) (data :pointer) (destroy :pointer)) (defun gtk-assistant-set-forward-page-func (assistant func) #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @argument[func]{a @symbol{gtk-assistant-page-func} page forwarding callback function, or @code{nil} to use the default one} @begin{short} Sets the page forwarding function to be @arg{func}. @end{short} This function will be used to determine what will be the next page when the user presses the Forward button. Setting @arg{func} to @code{nil} will make the assistant to use the default forward function, which just goes to the next visible page. @see-class{gtk-assistant} @see-symbol{gtk-assistant-page-func}" (if func (%gtk-assistant-set-forward-page-func assistant (callback gtk-assistant-page-func) (create-fn-ref assistant func) (callback gtk-assistant-page-func-destroy-notify)) (%gtk-assistant-set-forward-page-func assistant (null-pointer) (null-pointer) (null-pointer)))) (export 'gtk-assistant-set-forward-page-func) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_set_page_type () gtk_assistant_get_page_type ( ) - > gtk - assistant - page - type ;;; ---------------------------------------------------------------------------- (defun (setf gtk-assistant-page-type) (ptype assistant page) (setf (gtk-assistant-child-page-type assistant page) ptype)) (defun gtk-assistant-page-type (assistant page) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @syntax[]{(gtk-assistant-page-type assistant page) => ptype} @syntax[]{(setf (gtk-assistant-page-type assistant page) ptype)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[ptype]{a value of the @symbol{gtk-assistant-page-type} enumeration} @begin{short} Accessor of the page type of a page in the assistant. @end{short} The page type determines the page behavior in the assistant. The function is implemented with the @fun{gtk-assistant-child-pack-type} function. @see-class{gtk-assistant} @see-class{gtk-widget} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-child-page-type}" (gtk-assistant-child-page-type assistant page)) (export 'gtk-assistant-page-type) ;;; ---------------------------------------------------------------------------- gtk_assistant_set_page_title ( ) ;;; gtk_assistant_get_page_title () -> gtk-assistant-page-title ;;; ---------------------------------------------------------------------------- (defun (setf gtk-assistant-page-title) (title assistant page) (setf (gtk-assistant-child-title assistant page) title)) (defun gtk-assistant-page-title (assistant page) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @syntax[]{(gtk-assistant-page-title assistant page) => title} @syntax[]{(setf (gtk-assistant-page-title assistant page) title)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[title]{a string with the new title for @arg{page}} @begin{short} Accessor of the title for the page in the assistant. @end{short} The @sym{gtk-assistant-page-title} function gets the title for the page in the assistant. The @sym{(setf gtk-assistant-page-title)} function sets a title. The title is displayed in the header area of the assistant when the page is the current page. The function is implemented with the @fun{gtk-assistant-child-title} function. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-child-title}" (gtk-assistant-child-title assistant page)) (export 'gtk-assistant-page-title) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_set_page_header_image () ;;; ;;; void gtk_assistant_set_page_header_image (GtkAssistant *assistant, ;;; GtkWidget *page, ;;; GdkPixbuf *pixbuf); ;;; ;;; Warning ;;; gtk_assistant_set_page_header_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , a header is no ;;; longer shown; add your header decoration to the page content instead. ;;; ;;; Sets a header image for page. ;;; ;;; assistant : a GtkAssistant ;;; ;;; page : ;;; a page of assistant ;;; ;;; pixbuf : ;;; the new header image page ;;; Since 2.10 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_get_page_header_image () ;;; ;;; GdkPixbuf * gtk_assistant_get_page_header_image (GtkAssistant *assistant, ;;; GtkWidget *page); ;;; ;;; Warning ;;; gtk_assistant_get_page_header_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , a header is no ;;; longer shown; add your header decoration to the page content instead. ;;; ;;; Gets the header image for page. ;;; ;;; assistant : a GtkAssistant ;;; ;;; page : ;;; a page of assistant ;;; ;;; Returns : ;;; the header image for page, or NULL if there's no header image for the ;;; page ;;; Since 2.10 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_set_page_side_image () ;;; void gtk_assistant_set_page_side_image ( GtkAssistant * assistant , ;;; GtkWidget *page, ;;; GdkPixbuf *pixbuf); ;;; ;;; Warning ;;; gtk_assistant_set_page_side_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , sidebar images are ;;; not shown anymore. ;;; ;;; Sets a side image for page. ;;; ;;; This image used to be displayed in the side area of the assistant when page ;;; is the current page. ;;; ;;; assistant : a GtkAssistant ;;; ;;; page : ;;; a page of assistant ;;; ;;; pixbuf : ;;; the new side image page ;;; Since 2.10 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_get_page_side_image () ;;; ;;; GdkPixbuf * gtk_assistant_get_page_side_image (GtkAssistant *assistant, ;;; GtkWidget *page); ;;; ;;; Warning ;;; gtk_assistant_get_page_side_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , sidebar images are ;;; not shown anymore. ;;; ;;; Gets the side image for page. ;;; ;;; assistant : a GtkAssistant ;;; ;;; page : ;;; a page of assistant ;;; ;;; Returns : ;;; the side image for page, or NULL if there's no side image for the page ;;; Since 2.10 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_set_page_complete () ;;; gtk_assistant_get_page_complete () -> gtk-assistant-page-complete ;;; ---------------------------------------------------------------------------- (defun (setf gtk-assistant-page-complete) (complete assistant page) (setf (gtk-assistant-child-complete assistant page) complete)) (defun gtk-assistant-page-complete (assistant page) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @syntax[]{(gtk-assistant-page-complete assistant page) => complete} @syntax[]{(setf (gtk-assistant-page-complete assistant page) complete)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[complete]{a boolean with the completeness status of the page} @begin{short} Accessor of the completeness status of the page in the assistant. @end{short} The @sym{gtk-assistant-page-complete} function gets whether the page is complete. The @sym{(setf gtk-assistant-page-complete)} function sets whether the page contents are complete. This will make the assistant update the buttons state to be able to continue the task. The function is implemented with the @fun{gtk-assistant-child-complete} function. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-child-complete}" (gtk-assistant-child-complete assistant page)) (export 'gtk-assistant-page-complete) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_set_page_has_padding () ;;; gtk_assistant_get_page_has_padding () -> gtk-assistant-page-has-padding ;;; ---------------------------------------------------------------------------- (defun (setf gtk-assistant-page-has-padding) (setting assistant page) (setf (gtk-assistant-child-has-padding assistant page) setting)) (defun gtk-assistant-page-has-padding (assistant page) "@version{2021-11-2} @syntax[]{(gtk-assistant-page-has-padding assistant page) => setting} @syntax[]{(setf (gtk-assistant-page-has-padding assistant page) setting)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[setting]{a boolean whether the page has padding} @begin{short} Accessor of the has padding status of the page in the assistant. @end{short} The @sym{gtk-assistant-page-has-padding} function gets whether the page has padding. The @sym{(setf gtk-assistant-page-has-padding)} function sets whether the assistant is adding padding around the page. The function is implemented with the @fun{gtk-assistant-child-has-padding} function. Since 3.18 @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-child-has-padding}" (gtk-assistant-child-has-padding assistant page)) (export 'gtk-assistant-page-has-padding) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_add_action_widget () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_add_action_widget" gtk-assistant-add-action-widget) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} child widget} @begin{short} Adds a child widget to the action area of the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-remove-action-widget}" (assistant (g-object gtk-assistant)) (child (g-object gtk-widget))) (export 'gtk-assistant-add-action-widget) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_remove_action_widget () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_remove_action_widget" gtk-assistant-remove-action-widget) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} child widget} @begin{short} Removes a child widget from the action area of the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-add-action-widget}" (assistant (g-object gtk-assistant)) (child (g-object gtk-widget))) (export 'gtk-assistant-remove-action-widget) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_update_buttons_state () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_update_buttons_state" gtk-assistant-update-buttons-state) :void #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Forces the assistant to recompute the buttons state. @end{short} GTK automatically takes care of this in most situations, e.g. when the user goes to a different page, or when the visibility or completeness of a page changes. One situation where it can be necessary to call this function is when changing a value on the current page affects the future page flow of the assistant. @see-class{gtk-assistant}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-update-buttons-state) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_commit () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_commit" gtk-assistant-commit) :void #+cl-cffi-gtk-documentation "@version{*2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Erases the visited page history so the Back button is not shown on the current page, and removes the Cancel button from subsequent pages. @end{short} Use this when the information provided up to the current page is hereafter deemed permanent and cannot be modified or undone. For example, showing a progress page to track a long running, unreversible operation after the user has clicked the Apply button on a confirmation page. @see-class{gtk-assistant}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-commit) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_next_page () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_next_page" gtk-assistant-next-page) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Navigate to the next page. @end{short} It is a programming error to call this function when there is no next page. This function is for use when creating pages with the @code{:custom} value of the @symbol{gtk-assistant-page-type} enumeration. @see-class{gtk-assistant} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-previous-page}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-next-page) ;;; ---------------------------------------------------------------------------- ;;; gtk_assistant_previous_page () ;;; ---------------------------------------------------------------------------- (defcfun ("gtk_assistant_previous_page" gtk-assistant-previous-page) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Navigate to the previous visited page. @end{short} It is a programming error to call this function when no previous page is available. This function is for use when creating pages with the @code{:custom} value of the @symbol{gtk-assistant-page-type} enumeration. @see-class{gtk-assistant} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-next-page}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-previous-page) ;;; --- End of file gtk.assistant.lisp -----------------------------------------
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gtk/gtk.assistant.lisp
lisp
---------------------------------------------------------------------------- gtk.assistant.lisp The documentation of this file is taken from the GTK 3 Reference Manual See <>. The API documentation of the Lisp binding is This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License for Lisp License, or (at your option) any later version and with a preamble to with Lisp programs and is referred as the LLGPL. 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 General Public License. If not, see </> and <>. ---------------------------------------------------------------------------- A widget used to guide users through multi-step operations Types and Values GtkAssistant Functions gtk_assistant_new gtk_assistant_get_current_page gtk_assistant_set_current_page gtk_assistant_get_n_pages gtk_assistant_get_nth_page gtk_assistant_prepend_page gtk_assistant_append_page gtk_assistant_insert_page gtk_assistant_remove_page GtkAssistantPageFunc gtk_assistant_set_forward_page_func gtk_assistant_set_page_type gtk_assistant_get_page_title gtk_assistant_set_page_header_image deprecated gtk_assistant_get_page_header_image deprecated gtk_assistant_set_page_side_image deprecated gtk_assistant_get_page_side_image deprecated gtk_assistant_set_page_complete gtk_assistant_get_page_complete gtk_assistant_set_page_has_padding gtk_assistant_get_page_has_padding gtk_assistant_add_action_widget gtk_assistant_remove_action_widget gtk_assistant_update_buttons_state gtk_assistant_commit gtk_assistant_next_page gtk_assistant_previous_page Properties gint use-header-bar Read / Write / Construct Only Child Properties gboolean has-padding Read / Write GdkPixbuf* header-image Read / Write gchar* title Read / Write Style Properties gint content-padding Read gint header-padding Read Signals void apply Run Last void cancel Run Last void close Run Last void escape Action void prepare Run Last Object Hierarchy GObject ╰── GInitiallyUnowned ╰── GtkAssistant Implemented Interfaces ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Property and Accessor Details ---------------------------------------------------------------------------- --- gtk-assistant-use-header-bar ------------------------------------------- ---------------------------------------------------------------------------- Accessors of the Child Properties ---------------------------------------------------------------------------- --- gtk-assistant-child-complete ------------------------------------------- --- gtk-assistant-child-has-padding ---------------------------------------- --- gtk-assistant-child-header-image --------------------------------------- not exported --- gtk-assistant-child-page-type ------------------------------------------ --- gtk-assistant-child-sidebar-image -------------------------------------- not exported --- gtk-assistant-child-title ---------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_new () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_current_page () -> gtk-assistant-current-page ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_get_n_pages () -> gtk-assistant-n-pages ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_get_nth_page () -> gtk-assistant-nth-page ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_prepend_page () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_append_page () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_insert_page () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_remove_page () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- GtkAssistantPageFunc () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_forward_page_func () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_page_type () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_get_page_title () -> gtk-assistant-page-title ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_page_header_image () void gtk_assistant_set_page_header_image (GtkAssistant *assistant, GtkWidget *page, GdkPixbuf *pixbuf); Warning longer shown; add your header decoration to the page content instead. Sets a header image for page. assistant : page : a page of assistant pixbuf : the new header image page ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_get_page_header_image () GdkPixbuf * gtk_assistant_get_page_header_image (GtkAssistant *assistant, GtkWidget *page); Warning longer shown; add your header decoration to the page content instead. Gets the header image for page. assistant : page : a page of assistant Returns : the header image for page, or NULL if there's no header image for the page ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_page_side_image () GtkWidget *page, GdkPixbuf *pixbuf); Warning not shown anymore. Sets a side image for page. This image used to be displayed in the side area of the assistant when page is the current page. assistant : page : a page of assistant pixbuf : the new side image page ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_get_page_side_image () GdkPixbuf * gtk_assistant_get_page_side_image (GtkAssistant *assistant, GtkWidget *page); Warning not shown anymore. Gets the side image for page. assistant : page : a page of assistant Returns : the side image for page, or NULL if there's no side image for the page ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_page_complete () gtk_assistant_get_page_complete () -> gtk-assistant-page-complete ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_set_page_has_padding () gtk_assistant_get_page_has_padding () -> gtk-assistant-page-has-padding ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_add_action_widget () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_remove_action_widget () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_update_buttons_state () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_commit () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_next_page () ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gtk_assistant_previous_page () ---------------------------------------------------------------------------- --- End of file gtk.assistant.lisp -----------------------------------------
Version 3.24 and modified to document the Lisp binding to the GTK library . available from < -cffi-gtk/ > . Copyright ( C ) 2009 - 2011 Copyright ( C ) 2011 - 2021 as published by the Free Software Foundation , either version 3 of the the GNU Lesser General Public License that clarifies the terms for use 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 and the preamble to the Gnu Lesser GtkAssistant GtkAssistantPageType gtk_assistant_get_page_type gtk_assistant_set_page_title gboolean complete Read / Write GtkAssistantPageType page - type Read / Write GdkPixbuf * sidebar - image Read / Write ╰ ─ ─ ╰ ─ ─ GtkContainer ╰ ─ ─ ╰ ─ ─ GtkWindow GtkAssistant implements AtkImplementorIface and GtkBuildable . (in-package :gtk) enum GtkAssistantPageType (define-g-enum "GtkAssistantPageType" gtk-assistant-page-type (:export t :type-initializer "gtk_assistant_page_type_get_type") (:content 0) (:intro 1) (:confirm 2) (:summary 3) (:progress 4) (:custom 5)) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-page-type atdoc:*symbol-name-alias*) "GEnum" (gethash 'gtk-assistant-page-type atdoc:*external-symbols*) "@version{*2021-12-3} @begin{short} An enumeration for determining the page role inside the @class{gtk-assistant} widget. It is used to handle buttons sensitivity and visibility. @end{short} Note that an assistant needs to end its page flow with a page of @code{:confirm}, @code{:summary} or @code{:progress} type to be correct. The Cancel button will only be shown if the page is not \"committed\". See the @fun{gtk-assistant-commit} function for details. @begin{pre} (define-g-enum \"GtkAssistantPageType\" gtk-assistant-page-type (:export t :type-initializer \"gtk_assistant_page_type_get_type\") (:content 0) (:intro 1) (:confirm 2) (:summary 3) (:progress 4) (:custom 5)) @end{pre} @begin[code]{table} @entry[:content]{The page has regular contents. Both the Back and Forward buttons will be shown.} @entry[:intro]{The page contains an introduction to the assistant task. Only the Forward button will be shown if there is a next page.} @entry[:confirm]{The page lets the user confirm or deny the changes. The Back and Apply buttons will be shown.} @entry[:summary]{The page informs the user of the changes done. Only the Close button will be shown.} @entry[:progress]{Used for tasks that take a long time to complete, blocks the assistant until the page is marked as complete. Only the Back button will be shown.} @entry[:custom]{Used for when other page types are not appropriate. No buttons will be shown, and the application must add its own buttons through the @fun{gtk-assistant-add-action-widget} function.} @end{table} @see-class{gtk-assistant} @see-function{gtk-assistant-commit} @see-function{gtk-assistant-add-action-widget}") struct GtkAssistant (define-g-object-class "GtkAssistant" gtk-assistant (:superclass gtk-window :export t :interfaces ("AtkImplementorIface" "GtkBuildable") :type-initializer "gtk_assistant_get_type") ((use-header-bar gtk-assistant-use-header-bar "use-header-bar" "gint" t t))) #+cl-cffi-gtk-documentation (setf (documentation 'gtk-assistant 'type) "@version{*2021-11-2} @begin{short} A @sym{gtk-assistant} widget is used to represent a generally complex operation splitted in several steps, guiding the user through its pages and controlling the page flow to collect the necessary data. @end{short} @image[assistant]{} The design of the @sym{gtk-assistant} widget is that it controls what buttons to show and to make sensitive, based on what it knows about the page sequence and the type of each page, in addition to state information like the page completion and committed status. If you have a case that does not quite fit in an assistants way of handling buttons, you can use the @code{:custom} page type of the @symbol{gtk-assistant-page-type} enumeration and handle buttons yourself. @begin[GtkAssistant as GtkBuildable]{dictionary} The @sym{gtk-assistant} implementation of the @class{gtk-buildable} interface exposes the action area as internal children with the name @code{\"action_area\"}. To add pages to an assistant in a @class{gtk-builder} object, simply add it as a @code{<child>} to the @sym{gtk-assistant} widget and set its child properties as necessary. @end{dictionary} @begin[CSS nodes]{dictionary} The @sym{gtk-assistant} implementation has a single CSS node with the name @code{assistant}. @end{dictionary} @begin[Child Property Details]{dictionary} @begin[code]{table} @begin[complete]{entry} The @code{complete} child property of type @code{:boolean} (Read / Write) @br{} Setting to @em{true} marks a page as complete, i.e. all the required fields are filled out. GTK uses this information to control the sensitivity of the navigation buttons. @br{} Default value: @em{false} @br{} @end{entry} @begin[has-padding]{entry} The @code{has-padding} child property of type @code{:boolean} (Read / Write) @br{} Whether the assistant adds padding around the page. Since 3.18 @br{} Default value: @em{true} @end{entry} @begin[header-image]{entry} The @code{header-image} child property of type @class{gdk-pixbuf} (Read / Write) @br{} The image used to be displayed in the page header. @br{} @em{Warning:} The @code{header-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, a header is no longer shown. Add your header decoration to the page content instead. @end{entry} @begin[page-type]{entry} The @code{page-type} child property of type @symbol{gtk-assistant-page-type} (Read / Write) @br{} The type of the assistant page. @br{} Default value: @code{:content} @end{entry} @begin[sidebar-image]{entry} The @code{sidebar-image} child property of type @class{gdk-pixbuf} (Read / Write) @br{} The image used to be displayed in the sidebar. @br{} @em{Warning:} The @code{sidebar-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, the sidebar image is no longer shown. @end{entry} @begin[title]{entry} The @code{title} child property of type @code{:string} (Read / Write) @br{} The title of the page. @br{} Default value: @code{nil} @end{entry} @end{table} @end{dictionary} @begin[Style Property Details]{dictionary} @begin[code]{table} @begin[content-padding]{entry} The @code{content-padding} style property of type @code{:int} (Read) @br{} Number of pixels around the content pages. @br{} @em{Warning:} The @code{content-padding} style property has been deprecated since version 3.20 and should not be used in newly written code. This style property is ignored. @br{} Allowed values: >= 0 @br{} Default value: 1 @end{entry} @begin[header-padding]{entry} The @code{header-padding} style property of type @code{:int} (Read) @br{} Number of pixels around the header. @br{} @em{Warning:} The @code{content-padding} has been deprecated since version 3.20 and should not be used in newly written code. This style property is ignored. @br{} Allowed values: >= 0 @br{} Default value: 6 @end{entry} @end{table} @end{dictionary} @begin[Signal Details]{dictionary} @subheading{The \"apply\" signal} @begin{pre} lambda (assistant) :run-last @end{pre} The signal is emitted when the Apply button is clicked. The default behavior of the assistant is to switch to the page after the current page, unless the current page is the last one. A handler for the \"apply\" signal should carry out the actions for which the wizard has collected data. If the action takes a long time to complete, you might consider putting a @code{:progress} page after the @code{:confirm} page and handle this operation within the \"prepare\" signal of the progress page. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"cancel\" signal} @begin{pre} lambda (assistant) :run-last @end{pre} The signal is emitted when the Cancel button is clicked. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"close\" signal} @begin{pre} lambda (assistant) :run-last @end{pre} The signal is emitted either when the Close button of a summary page is clicked, or when the Apply button in the last page in the flow is clicked, which is the @code{:confirm} page. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"escape\" signal} @begin{pre} lambda (assistant) :action @end{pre} No documentation. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @end{table} @subheading{The \"prepare\" signal} @begin{pre} lambda (assistant page) :run-last @end{pre} The signal is emitted when a new page is set as the assistants current page, before making the new page visible. A handler for this signal can do any preparations which are necessary before showing the page. @begin[code]{table} @entry[assistant]{The @sym{gtk-assistant} widget which received the signal.} @entry[page]{The @class{gtk-widget} widget for the current page.} @end{table} @end{dictionary} @see-slot{gtk-assistant-use-header-bar}") (eval-when (:compile-toplevel :load-toplevel :execute) (register-object-type "GtkAssistant" 'gtk-assistant)) #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "use-header-bar" 'gtk-assistant) 't) "The @code{use-header-bar} property of type @code{:int} (Read / Write / Construct) @br{} @em{True} if the assistant uses a header bar for action buttons instead of the action area. For technical reasons, this property is declared as an integer property, use the value 1 for @em{true} or -1 for @em{false}. @br{} Allowed values: [-1, 1] @br{} Default value: -1") #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-use-header-bar atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-use-header-bar 'function) "@version{2021-10-27} @syntax[]{(gtk-assistant-use-header-bar object) => setting} @syntax[]{(setf (gtk-assistant-use-header-bar object) setting)} @argument[object]{a @class{gtk-assistant} widget} @argument[setting]{@em{true} if the assistant uses a header bar} @begin{short} Accessor of the @slot[gtk-assistant]{use-header-bar} slot of the @class{gtk-assistant} class. @end{short} @em{True} if the assistant uses a header bar for action buttons instead of the action area. For technical reasons, this property is declared as an integer property, use the value 1 for @em{true} or -1 for @em{false}. @see-class{gtk-assistant} @see-class{gtk-header-bar}") (define-child-property "GtkAssistant" gtk-assistant-child-complete "complete" "gboolean" t t t) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-complete atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-complete 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-complete container child) => complete} @syntax[]{(setf (gtk-assistant-child-complete container child) complete)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[complete]{a boolean whether the page is complete} @begin{short} Accessor of the @code{complete} child property of the @class{gtk-assistant} class. @end{short} Setting the @code{complete} child property to @em{true} marks a page as complete, i.e. all the required fields are filled out. GTK uses this information to control the sensitivity of the navigation buttons. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-page-complete}") #+gtk-3-18 (define-child-property "GtkAssistant" gtk-assistant-child-has-padding "has-padding" "gboolean" t t t) #+(and gtk-3-18 cl-cffi-gtk-documentation) (setf (gethash 'gtk-assistant-child-has-padding atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-has-padding 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-has-padding container child) => setting} @syntax[]{(setf (gtk-assistant-child-has-padding container child) setting)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[setting]{a boolean whether the assistant adds padding around the page} @begin{short} Accessor of the @code{has-padding} child property of the @class{gtk-assistant} class. @end{short} Whether the assistant adds padding around the page. Since 3.18 @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-page-has-padding}") (define-child-property "GtkAssistant" gtk-assistant-child-header-image "header-image" "GdkPixbuf" t t nil) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-header-image atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-header-image 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-header-image container child) => image} @syntax[]{(setf (gtk-assistant-child-header-image container child) image)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[image]{a @class{gdk-pixbuf} image} @begin{short} Accessor of the @code{header-image} child property of the @class{gtk-assistant} class. @end{short} The image used to be displayed in the page header. @begin[Warning]{dictionary} The @code{header-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, a header is no longer shown. Add your header decoration to the page content instead. @end{dictionary} @see-class{gtk-assistant} @see-class{gtk-widget} @see-class{gdk-pixbuf}") (define-child-property "GtkAssistant" gtk-assistant-child-page-type "page-type" "GtkAssistantPageType" t t t) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-page-type atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-page-type 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-page-type container child) => ptype} @syntax[]{(setf (gtk-assistant-child-page-type container child) ptype)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[ptype]{a value of the @symbol{gtk-assistant-page-type} enumeration} @begin{short} Accessor of the @code{page-type} child property of the @class{gtk-assistant} class. @end{short} The page type determines the page behavior in the assistant. @see-class{gtk-assistant} @see-class{gtk-widget} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-child-page-type}") (define-child-property "GtkAssistant" gtk-assistant-child-sidebar-image "sidebar-image" "GdkPixbuf" t t nil) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-sidebar-image atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-sidebar-image 'function) "@version{2021-10-26} @syntax[]{(gtk-assistant-child-sidebar-image container child) => image} @syntax[]{(setf (gtk-assistant-child-sidebar-image container child) image)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[image]{a @class{gdk-pixbuf} image} @begin{short} Accessor of the @code{sidebar-image} child property of the @class{gtk-assistant} class. @end{short} The image used to be displayed in the sidebar. @begin[Warning]{dictionary} The @code{sidebar-image} child property has been deprecated since version 3.2 and should not be used in newly written code. Since GTK 3.2, the sidebar image is no longer shown. @end{dictionary} @see-class{gtk-assistant} @see-class{gtk-widget} @see-class{gdk-pixbuf}") (define-child-property "GtkAssistant" gtk-assistant-child-title "title" "gchararray" t t t) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-child-title atdoc:*function-name-alias*) "Accessor" (documentation 'gtk-assistant-child-title 'function) "@version{2021-11-2} @syntax[]{(gtk-assistant-child-title container child) => title} @syntax[]{(setf (gtk-assistant-child-title container child) title)} @argument[container]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} page of the assistant} @argument[title]{a string with the title of the page} @begin{short} Accessor of the @code{title} child property of the @class{gtk-assistant} class. @end{short} The title of the page. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-asssistant-page-title}") (defun gtk-assistant-new () #+cl-cffi-gtk-documentation "@version{2021-10-26} @return{A @class{gtk-assistant} widget.} @begin{short} Creates a new assistant. @end{short} @see-class{gtk-assistant}" (make-instance 'gtk-assistant)) (export 'gtk-assistant-new) gtk_assistant_get_current_page ( ) (defun (setf gtk-assistant-current-page) (index assistant) (foreign-funcall "gtk_assistant_set_current_page" (g-object gtk-assistant) assistant :int index :void) index) (defcfun ("gtk_assistant_get_current_page" gtk-assistant-current-page) :int #+cl-cffi-gtk-documentation "@version{*2021-11-1} @syntax[]{(gtk-assistant-current-page assistant) => index} @syntax[]{(setf (gtk-assistant-current-page assistant) index)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[index]{an integer with the index of the page to switch to, starting from 0, if negative, the last page will be used, if greater than the number of pages in the assistant, nothing will be done} @begin{short} Accessor of the current page of the assistant. @end{short} The @sym{gtk-assistant-current-page} function returns the page number of the current page in the assistant. The @sym{(setf gtk-assistant-current-page)} function switches the page in the assistant to @arg{index}. Note that this will only be necessary in custom buttons, as the assistant flow can be set with the @fun{gtk-assistant-set-forward-page-func} function. @see-class{gtk-assistant} @see-function{gtk-assistant-set-forward-page-func}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-current-page) (defcfun ("gtk_assistant_get_n_pages" gtk-assistant-n-pages) :int #+cl-cffi-gtk-documentation "@version{*2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @return{An integer with the number of pages in @arg{assistant}.} @begin{short} Returns the number of pages in the assistant. @end{short} @see-class{gtk-assistant}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-n-pages) (defcfun ("gtk_assistant_get_nth_page" gtk-assistant-nth-page) (g-object gtk-widget) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @argument[index]{an integer with the index of a page in @arg{assistant}, or -1 to get the last page} @return{The @class{gtk-widget} child widget, or @code{nil} if the @arg{index} argument is out of bounds.} @begin{short} Returns the child widget contained in the assistant with the given page index. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget}" (assistant (g-object gtk-assistant)) (index :int)) (export 'gtk-assistant-nth-page) (defcfun ("gtk_assistant_prepend_page" gtk-assistant-prepend-page) :int #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of the assistant} @return{An integer with the index starting at 0 of the inserted page.} @begin{short} Prepends a page to the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-append-page} @see-function{gtk-assistant-insert-page} @see-function{gtk-assistant-remove-page}" (assistant (g-object gtk-assistant)) (page (g-object gtk-widget))) (export 'gtk-assistant-prepend-page) (defcfun ("gtk_assistant_append_page" gtk-assistant-append-page) :int #+cl-cffi-gtk-documentation "@version{*2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of the assistant} @return{An integer with the index starting at 0 of the inserted page.} @begin{short} Appends a page to the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-prepend-page} @see-function{gtk-assistant-insert-page} @see-function{gtk-assistant-remove-page}" (assistant (g-object gtk-assistant)) (page (g-object gtk-widget))) (export 'gtk-assistant-append-page) (defcfun ("gtk_assistant_insert_page" gtk-assistant-insert-page) :int #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of the assistant} @argument[position]{an integer with the index starting at 0 at which to insert @arg{page}, or -1 to append @arg{page} to the assistant} @return{The index starting from 0 of the inserted page.} @begin{short} Inserts a page in the assistant at a given position. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-append-page} @see-function{gtk-assistant-prepend-page} @see-function{gtk-assistant-remove-page}" (assistant (g-object gtk-assistant)) (page (g-object gtk-widget)) (position :int)) (export 'gtk-assistant-insert-page) (defcfun ("gtk_assistant_remove_page" gtk-assistant-remove-page) :void #+cl-cffi-gtk-documentation "@version{2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @argument[index]{an integer with the index of a page in the assistant, or -1 to remove the last page} @begin{short} Removes the page with the given page index from the assistant. @end{short} @see-class{gtk-assistant} @see-function{gtk-assistant-append-page} @see-function{gtk-assistant-prepend-page} @see-function{gtk-assistant-insert-page}" (assistant (g-object gtk-assistant)) (index :int)) (export 'gtk-assistant-remove-page) (define-cb-methods gtk-assistant-page-func :int ((current-page :int))) #+cl-cffi-gtk-documentation (setf (gethash 'gtk-assistant-page-func atdoc:*symbol-name-alias*) "Callback" (gethash 'gtk-assistant-page-func atdoc:*external-symbols*) "@version{2021-10-26} @begin{short} A callback function used by the @fun{gtk-assistant-set-forward-page-func} function to know which is the next page given a current one. @end{short} It is called both for computing the next page when the user presses the Forward button and for handling the behavior of the Last button. @begin{pre} lambda (current) @end{pre} @begin[code]{table} @entry[current]{An integer with the page number used to calculate the next page.} @entry[Returns]{An integer with the next page number.} @end{table} @see-class{gtk-assistant} @see-function{gtk-assistant-set-forward-page-func}") (export 'gtk-assistant-page-func) (defcfun ("gtk_assistant_set_forward_page_func" %gtk-assistant-set-forward-page-func) :void (assistant (g-object gtk-assistant)) (func :pointer) (data :pointer) (destroy :pointer)) (defun gtk-assistant-set-forward-page-func (assistant func) #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @argument[func]{a @symbol{gtk-assistant-page-func} page forwarding callback function, or @code{nil} to use the default one} @begin{short} Sets the page forwarding function to be @arg{func}. @end{short} This function will be used to determine what will be the next page when the user presses the Forward button. Setting @arg{func} to @code{nil} will make the assistant to use the default forward function, which just goes to the next visible page. @see-class{gtk-assistant} @see-symbol{gtk-assistant-page-func}" (if func (%gtk-assistant-set-forward-page-func assistant (callback gtk-assistant-page-func) (create-fn-ref assistant func) (callback gtk-assistant-page-func-destroy-notify)) (%gtk-assistant-set-forward-page-func assistant (null-pointer) (null-pointer) (null-pointer)))) (export 'gtk-assistant-set-forward-page-func) gtk_assistant_get_page_type ( ) - > gtk - assistant - page - type (defun (setf gtk-assistant-page-type) (ptype assistant page) (setf (gtk-assistant-child-page-type assistant page) ptype)) (defun gtk-assistant-page-type (assistant page) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @syntax[]{(gtk-assistant-page-type assistant page) => ptype} @syntax[]{(setf (gtk-assistant-page-type assistant page) ptype)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[ptype]{a value of the @symbol{gtk-assistant-page-type} enumeration} @begin{short} Accessor of the page type of a page in the assistant. @end{short} The page type determines the page behavior in the assistant. The function is implemented with the @fun{gtk-assistant-child-pack-type} function. @see-class{gtk-assistant} @see-class{gtk-widget} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-child-page-type}" (gtk-assistant-child-page-type assistant page)) (export 'gtk-assistant-page-type) gtk_assistant_set_page_title ( ) (defun (setf gtk-assistant-page-title) (title assistant page) (setf (gtk-assistant-child-title assistant page) title)) (defun gtk-assistant-page-title (assistant page) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @syntax[]{(gtk-assistant-page-title assistant page) => title} @syntax[]{(setf (gtk-assistant-page-title assistant page) title)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[title]{a string with the new title for @arg{page}} @begin{short} Accessor of the title for the page in the assistant. @end{short} The @sym{gtk-assistant-page-title} function gets the title for the page in the assistant. The @sym{(setf gtk-assistant-page-title)} function sets a title. The title is displayed in the header area of the assistant when the page is the current page. The function is implemented with the @fun{gtk-assistant-child-title} function. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-child-title}" (gtk-assistant-child-title assistant page)) (export 'gtk-assistant-page-title) gtk_assistant_set_page_header_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , a header is no a GtkAssistant Since 2.10 gtk_assistant_get_page_header_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , a header is no a GtkAssistant Since 2.10 void gtk_assistant_set_page_side_image ( GtkAssistant * assistant , gtk_assistant_set_page_side_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , sidebar images are a GtkAssistant Since 2.10 gtk_assistant_get_page_side_image has been deprecated since version 3.2 and should not be used in newly written code . Since GTK 3.2 , sidebar images are a GtkAssistant Since 2.10 (defun (setf gtk-assistant-page-complete) (complete assistant page) (setf (gtk-assistant-child-complete assistant page) complete)) (defun gtk-assistant-page-complete (assistant page) #+cl-cffi-gtk-documentation "@version{*2021-11-2} @syntax[]{(gtk-assistant-page-complete assistant page) => complete} @syntax[]{(setf (gtk-assistant-page-complete assistant page) complete)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[complete]{a boolean with the completeness status of the page} @begin{short} Accessor of the completeness status of the page in the assistant. @end{short} The @sym{gtk-assistant-page-complete} function gets whether the page is complete. The @sym{(setf gtk-assistant-page-complete)} function sets whether the page contents are complete. This will make the assistant update the buttons state to be able to continue the task. The function is implemented with the @fun{gtk-assistant-child-complete} function. @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-child-complete}" (gtk-assistant-child-complete assistant page)) (export 'gtk-assistant-page-complete) (defun (setf gtk-assistant-page-has-padding) (setting assistant page) (setf (gtk-assistant-child-has-padding assistant page) setting)) (defun gtk-assistant-page-has-padding (assistant page) "@version{2021-11-2} @syntax[]{(gtk-assistant-page-has-padding assistant page) => setting} @syntax[]{(setf (gtk-assistant-page-has-padding assistant page) setting)} @argument[assistant]{a @class{gtk-assistant} widget} @argument[page]{a @class{gtk-widget} page of @arg{assistant}} @argument[setting]{a boolean whether the page has padding} @begin{short} Accessor of the has padding status of the page in the assistant. @end{short} The @sym{gtk-assistant-page-has-padding} function gets whether the page has padding. The @sym{(setf gtk-assistant-page-has-padding)} function sets whether the assistant is adding padding around the page. The function is implemented with the @fun{gtk-assistant-child-has-padding} function. Since 3.18 @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-child-has-padding}" (gtk-assistant-child-has-padding assistant page)) (export 'gtk-assistant-page-has-padding) (defcfun ("gtk_assistant_add_action_widget" gtk-assistant-add-action-widget) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} child widget} @begin{short} Adds a child widget to the action area of the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-remove-action-widget}" (assistant (g-object gtk-assistant)) (child (g-object gtk-widget))) (export 'gtk-assistant-add-action-widget) (defcfun ("gtk_assistant_remove_action_widget" gtk-assistant-remove-action-widget) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @argument[child]{a @class{gtk-widget} child widget} @begin{short} Removes a child widget from the action area of the assistant. @end{short} @see-class{gtk-assistant} @see-class{gtk-widget} @see-function{gtk-assistant-add-action-widget}" (assistant (g-object gtk-assistant)) (child (g-object gtk-widget))) (export 'gtk-assistant-remove-action-widget) (defcfun ("gtk_assistant_update_buttons_state" gtk-assistant-update-buttons-state) :void #+cl-cffi-gtk-documentation "@version{2021-10-26} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Forces the assistant to recompute the buttons state. @end{short} GTK automatically takes care of this in most situations, e.g. when the user goes to a different page, or when the visibility or completeness of a page changes. One situation where it can be necessary to call this function is when changing a value on the current page affects the future page flow of the assistant. @see-class{gtk-assistant}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-update-buttons-state) (defcfun ("gtk_assistant_commit" gtk-assistant-commit) :void #+cl-cffi-gtk-documentation "@version{*2021-11-1} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Erases the visited page history so the Back button is not shown on the current page, and removes the Cancel button from subsequent pages. @end{short} Use this when the information provided up to the current page is hereafter deemed permanent and cannot be modified or undone. For example, showing a progress page to track a long running, unreversible operation after the user has clicked the Apply button on a confirmation page. @see-class{gtk-assistant}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-commit) (defcfun ("gtk_assistant_next_page" gtk-assistant-next-page) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Navigate to the next page. @end{short} It is a programming error to call this function when there is no next page. This function is for use when creating pages with the @code{:custom} value of the @symbol{gtk-assistant-page-type} enumeration. @see-class{gtk-assistant} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-previous-page}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-next-page) (defcfun ("gtk_assistant_previous_page" gtk-assistant-previous-page) :void #+cl-cffi-gtk-documentation "@version{2021-11-2} @argument[assistant]{a @class{gtk-assistant} widget} @begin{short} Navigate to the previous visited page. @end{short} It is a programming error to call this function when no previous page is available. This function is for use when creating pages with the @code{:custom} value of the @symbol{gtk-assistant-page-type} enumeration. @see-class{gtk-assistant} @see-symbol{gtk-assistant-page-type} @see-function{gtk-assistant-next-page}" (assistant (g-object gtk-assistant))) (export 'gtk-assistant-previous-page)
c4b679b55652a8f146cfc7fcc19de7c496421c9572e375c76dfd6bde5f36ca65
EFanZh/EOPL-Exercises
exercise-6.8-inlined.rkt
#lang eopl Exercise 6.8 [ ★ ★ ★ ] Rewrite the interpreter of section 5.4 using a procedural and inlined representation . This is challenging because we effectively have two observers , apply - cont and apply - handler . As a hint , consider modifying the recipe on page 6.1 so that we add to each procedure two extra arguments , one representing the behavior of the continuation under apply - cont and one representing its behavior under apply - handler . ;; Grammar. (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("proc" "(" identifier ")" expression) proc-exp] [expression ("(" expression expression ")") call-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("letrec" identifier "(" identifier ")" "=" expression "in" expression) letrec-exp] [expression ("list" "(" (separated-list number ",") ")") const-list-exp] [expression (unary-op "(" expression ")") unop-exp] [expression ("try" expression "catch" "(" identifier ")" expression) try-exp] [expression ("raise" expression) raise-exp] [unary-op ("null?") null?-unop] [unary-op ("car") car-unop] [unary-op ("cdr") cdr-unop] [unary-op ("zero?") zero?-unop])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) ;; Data structures. (define environment? (list-of (lambda (p) (and (pair? p) (symbol? (car p)))))) (define empty-env (lambda () '())) (define extend-env (lambda (sym val old-env) (cons (list sym val) old-env))) (define extend-env-rec (lambda (p-name b-var p-body saved-env) (cons (list p-name b-var p-body) saved-env))) (define apply-env (lambda (env search-sym) (if (null? env) (eopl:error 'apply-env "No binding for ~s" search-sym) (let* ([binding (car env)] [id (list-ref binding 0)] [expval-or-bvar (list-ref binding 1)]) (cond [(not (eqv? search-sym id)) (apply-env (cdr env) search-sym)] [(not (symbol? expval-or-bvar)) expval-or-bvar] [else (let ([bvar (cadr binding)] [body (caddr binding)]) (proc-val (procedure bvar body env)))]))))) (define-datatype proc proc? [procedure [bvar symbol?] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]] [list-val [lst (list-of expval?)]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define expval->list (lambda (v) (cases expval v [list-val (lst) lst] [else (expval-extractor-error 'list v)]))) ;; Interpreter. (define apply-unop (lambda (unop val) (cases unary-op unop [null?-unop () (bool-val (null? (expval->list val)))] [car-unop () (car (expval->list val))] [cdr-unop () (list-val (cdr (expval->list val)))] [zero?-unop () (bool-val (zero? (expval->num val)))]))) (define apply-procedure (lambda (proc1 arg cont handler) (cases proc proc1 [procedure (var body saved-env) (value-of/k body (extend-env var arg saved-env) cont handler)]))) (define value-of/k (lambda (exp env cont handler) (cases expression exp [const-exp (num) (cont (num-val num))] [const-list-exp (nums) (cont (list-val (map num-val nums)))] [var-exp (var) (cont (apply-env env var))] [diff-exp (exp1 exp2) (value-of/k exp1 env (lambda (val1) (value-of/k exp2 env (lambda (val) (let ([n1 (expval->num val1)] [n2 (expval->num val)]) (cont (num-val (- n1 n2))))) handler)) handler)] [unop-exp (unop exp1) (value-of/k exp1 env (lambda (val) (cont (apply-unop unop val))) handler)] [if-exp (exp1 exp2 exp3) (value-of/k exp1 env (lambda (val) (if (expval->bool val) (value-of/k exp2 env cont handler) (value-of/k exp3 env cont handler))) handler)] [proc-exp (var body) (cont (proc-val (procedure var body env)))] [call-exp (rator rand) (value-of/k rator env (lambda (val1) (value-of/k rand env (lambda (val) (let ([proc (expval->proc val1)]) (apply-procedure proc val cont handler))) handler)) handler)] [let-exp (var exp1 body) (value-of/k (call-exp (proc-exp var body) exp1) env cont handler)] [letrec-exp (p-name b-var p-body letrec-body) (value-of/k letrec-body (extend-env-rec p-name b-var p-body env) cont handler)] [try-exp (exp1 var handler-exp) (value-of/k exp1 env cont (lambda (val) (value-of/k handler-exp (extend-env var val env) cont handler)))] [raise-exp (exp1) (value-of/k exp1 env (lambda (val) (handler val)) handler)]))) (define value-of-program (lambda (pgm) (cases program pgm (a-program (body) (value-of/k body (empty-env) (lambda (val) val) (lambda (val) (eopl:error 'apply-handler "uncaught exception!"))))))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val list-val num-val run)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-6.8-inlined.rkt
racket
Grammar. Data structures. Interpreter.
#lang eopl Exercise 6.8 [ ★ ★ ★ ] Rewrite the interpreter of section 5.4 using a procedural and inlined representation . This is challenging because we effectively have two observers , apply - cont and apply - handler . As a hint , consider modifying the recipe on page 6.1 so that we add to each procedure two extra arguments , one representing the behavior of the continuation under apply - cont and one representing its behavior under apply - handler . (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("proc" "(" identifier ")" expression) proc-exp] [expression ("(" expression expression ")") call-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("letrec" identifier "(" identifier ")" "=" expression "in" expression) letrec-exp] [expression ("list" "(" (separated-list number ",") ")") const-list-exp] [expression (unary-op "(" expression ")") unop-exp] [expression ("try" expression "catch" "(" identifier ")" expression) try-exp] [expression ("raise" expression) raise-exp] [unary-op ("null?") null?-unop] [unary-op ("car") car-unop] [unary-op ("cdr") cdr-unop] [unary-op ("zero?") zero?-unop])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define environment? (list-of (lambda (p) (and (pair? p) (symbol? (car p)))))) (define empty-env (lambda () '())) (define extend-env (lambda (sym val old-env) (cons (list sym val) old-env))) (define extend-env-rec (lambda (p-name b-var p-body saved-env) (cons (list p-name b-var p-body) saved-env))) (define apply-env (lambda (env search-sym) (if (null? env) (eopl:error 'apply-env "No binding for ~s" search-sym) (let* ([binding (car env)] [id (list-ref binding 0)] [expval-or-bvar (list-ref binding 1)]) (cond [(not (eqv? search-sym id)) (apply-env (cdr env) search-sym)] [(not (symbol? expval-or-bvar)) expval-or-bvar] [else (let ([bvar (cadr binding)] [body (caddr binding)]) (proc-val (procedure bvar body env)))]))))) (define-datatype proc proc? [procedure [bvar symbol?] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]] [list-val [lst (list-of expval?)]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define expval->list (lambda (v) (cases expval v [list-val (lst) lst] [else (expval-extractor-error 'list v)]))) (define apply-unop (lambda (unop val) (cases unary-op unop [null?-unop () (bool-val (null? (expval->list val)))] [car-unop () (car (expval->list val))] [cdr-unop () (list-val (cdr (expval->list val)))] [zero?-unop () (bool-val (zero? (expval->num val)))]))) (define apply-procedure (lambda (proc1 arg cont handler) (cases proc proc1 [procedure (var body saved-env) (value-of/k body (extend-env var arg saved-env) cont handler)]))) (define value-of/k (lambda (exp env cont handler) (cases expression exp [const-exp (num) (cont (num-val num))] [const-list-exp (nums) (cont (list-val (map num-val nums)))] [var-exp (var) (cont (apply-env env var))] [diff-exp (exp1 exp2) (value-of/k exp1 env (lambda (val1) (value-of/k exp2 env (lambda (val) (let ([n1 (expval->num val1)] [n2 (expval->num val)]) (cont (num-val (- n1 n2))))) handler)) handler)] [unop-exp (unop exp1) (value-of/k exp1 env (lambda (val) (cont (apply-unop unop val))) handler)] [if-exp (exp1 exp2 exp3) (value-of/k exp1 env (lambda (val) (if (expval->bool val) (value-of/k exp2 env cont handler) (value-of/k exp3 env cont handler))) handler)] [proc-exp (var body) (cont (proc-val (procedure var body env)))] [call-exp (rator rand) (value-of/k rator env (lambda (val1) (value-of/k rand env (lambda (val) (let ([proc (expval->proc val1)]) (apply-procedure proc val cont handler))) handler)) handler)] [let-exp (var exp1 body) (value-of/k (call-exp (proc-exp var body) exp1) env cont handler)] [letrec-exp (p-name b-var p-body letrec-body) (value-of/k letrec-body (extend-env-rec p-name b-var p-body env) cont handler)] [try-exp (exp1 var handler-exp) (value-of/k exp1 env cont (lambda (val) (value-of/k handler-exp (extend-env var val env) cont handler)))] [raise-exp (exp1) (value-of/k exp1 env (lambda (val) (handler val)) handler)]))) (define value-of-program (lambda (pgm) (cases program pgm (a-program (body) (value-of/k body (empty-env) (lambda (val) val) (lambda (val) (eopl:error 'apply-handler "uncaught exception!"))))))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val list-val num-val run)
8e5f601f65879c3252a1772c06d14502d9fea1e7b02a2e9c8da8b9aef1b5e848
prg-titech/baccaml
opt_mem.mli
open MinCaml open Asm open Opt_lib val remove_rw : int M.t -> string M'.t -> t -> t val find_remove_candidate : int M.t -> (string * exp) M'.t -> exp M.t -> t -> exp M.t val remove_unread_write : exp M.t -> t -> t val const_fold_rw : t -> t
null
https://raw.githubusercontent.com/prg-titech/baccaml/a3b95e996a995b5004ca897a4b6419edfee590aa/opt/opt_mem.mli
ocaml
open MinCaml open Asm open Opt_lib val remove_rw : int M.t -> string M'.t -> t -> t val find_remove_candidate : int M.t -> (string * exp) M'.t -> exp M.t -> t -> exp M.t val remove_unread_write : exp M.t -> t -> t val const_fold_rw : t -> t
f25e5e6c506fc868e82fe7600eccdde02baa21661e90d4990733ded8048ad646
clash-lang/clash-compiler
NameInstance.hs
module NameInstance where import qualified Prelude as P import Data.List (isInfixOf) import System.Environment (getArgs) import System.FilePath ((</>), takeDirectory) import Clash.Prelude topEntity :: Bool -> Bool -> (Bool,Bool) topEntity = suffixName @"after" $ setName @"foo" $ prefixName @"before" f f :: Bool -> Bool -> (Bool,Bool) f x y = (y,x) # NOINLINE f # -- File content test assertIn :: String -> String -> IO () assertIn needle haystack | needle `isInfixOf` haystack = return () | otherwise = P.error $ P.concat [ "Expected:\n\n ", needle , "\n\nIn:\n\n", haystack ] mainSystemVerilog :: IO () mainSystemVerilog = do [topDir] <- getArgs content <- readFile (topDir </> show 'topEntity </> "topEntity.sv") assertIn "before_foo_after" content mainVerilog :: IO () mainVerilog = do [topDir] <- getArgs content <- readFile (topDir </> show 'topEntity </> "topEntity.v") assertIn "before_foo_after" content mainVHDL :: IO () mainVHDL = do [topDir] <- getArgs content <- readFile (topDir </> show 'topEntity </> "topEntity.vhdl") assertIn "before_foo_after" content
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/Basic/NameInstance.hs
haskell
File content test
module NameInstance where import qualified Prelude as P import Data.List (isInfixOf) import System.Environment (getArgs) import System.FilePath ((</>), takeDirectory) import Clash.Prelude topEntity :: Bool -> Bool -> (Bool,Bool) topEntity = suffixName @"after" $ setName @"foo" $ prefixName @"before" f f :: Bool -> Bool -> (Bool,Bool) f x y = (y,x) # NOINLINE f # assertIn :: String -> String -> IO () assertIn needle haystack | needle `isInfixOf` haystack = return () | otherwise = P.error $ P.concat [ "Expected:\n\n ", needle , "\n\nIn:\n\n", haystack ] mainSystemVerilog :: IO () mainSystemVerilog = do [topDir] <- getArgs content <- readFile (topDir </> show 'topEntity </> "topEntity.sv") assertIn "before_foo_after" content mainVerilog :: IO () mainVerilog = do [topDir] <- getArgs content <- readFile (topDir </> show 'topEntity </> "topEntity.v") assertIn "before_foo_after" content mainVHDL :: IO () mainVHDL = do [topDir] <- getArgs content <- readFile (topDir </> show 'topEntity </> "topEntity.vhdl") assertIn "before_foo_after" content
bdd048e14d2f2c007f1a5ffc983fbd06c11d86d473698b60451534346cd0eb35
achirkin/vulkan
VK_AMD_buffer_marker.hs
# OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_HADDOCK not - home # {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleInstances # # LANGUAGE ForeignFunctionInterface # {-# LANGUAGE MagicHash #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE Strict #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} module Graphics.Vulkan.Ext.VK_AMD_buffer_marker * Vulkan extension : @VK_AMD_buffer_marker@ -- | -- -- supported: @vulkan@ -- -- contact: @Daniel Rakos @drakos-amd@ -- author : -- -- type: @device@ -- -- Extension number: @180@ VkCmdWriteBufferMarkerAMD, pattern VkCmdWriteBufferMarkerAMD, HS_vkCmdWriteBufferMarkerAMD, PFN_vkCmdWriteBufferMarkerAMD, module Graphics.Vulkan.Marshal, AHardwareBuffer(), ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..), VkDeviceSize(..), VkFlags(..), VkSampleMask(..), VkPipelineBindPoint(..), VkPipelineCacheHeaderVersion(..), VkPipelineCreateBitmask(..), VkPipelineCreationFeedbackBitmaskEXT(..), VkPipelineExecutableStatisticFormatKHR(..), VkPipelineStageBitmask(..), VkPipelineCacheCreateBitmask(..), VkPipelineCacheCreateFlagBits(), VkPipelineCacheCreateFlags(), VkPipelineCompilerControlBitmaskAMD(..), VkPipelineCompilerControlFlagBitsAMD(), VkPipelineCompilerControlFlagsAMD(), VkPipelineCreateFlagBits(), VkPipelineCreateFlags(), VkPipelineCreationFeedbackFlagBitsEXT(), VkPipelineCreationFeedbackFlagsEXT(), VkPipelineShaderStageCreateBitmask(..), VkPipelineShaderStageCreateFlagBits(), VkPipelineShaderStageCreateFlags(), VkPipelineStageFlagBits(), VkPipelineStageFlags(), VkAccelerationStructureKHR, VkAccelerationStructureKHR_T(), VkAccelerationStructureNV, VkAccelerationStructureNV_T(), VkBuffer, VkBufferView, VkBufferView_T(), VkBuffer_T(), VkCommandBuffer, VkCommandBuffer_T(), VkCommandPool, VkCommandPool_T(), VkDebugReportCallbackEXT, VkDebugReportCallbackEXT_T(), VkDebugUtilsMessengerEXT, VkDebugUtilsMessengerEXT_T(), VkDeferredOperationKHR, VkDeferredOperationKHR_T(), VkDescriptorPool, VkDescriptorPool_T(), VkDescriptorSet, VkDescriptorSetLayout, VkDescriptorSetLayout_T(), VkDescriptorSet_T(), VkDescriptorUpdateTemplate, VkDescriptorUpdateTemplateKHR, VkDescriptorUpdateTemplateKHR_T(), VkDescriptorUpdateTemplate_T(), VkDevice, VkDeviceMemory, VkDeviceMemory_T(), VkDevice_T(), VkDisplayKHR, VkDisplayKHR_T(), VkDisplayModeKHR, VkDisplayModeKHR_T(), VkEvent, VkEvent_T(), VkFence, VkFence_T(), VkFramebuffer, VkFramebuffer_T(), VkImage, VkImageView, VkImageView_T(), VkImage_T(), VkIndirectCommandsLayoutNV, VkIndirectCommandsLayoutNV_T(), VkInstance, VkInstance_T(), VkPerformanceConfigurationINTEL, VkPerformanceConfigurationINTEL_T(), VkPhysicalDevice, VkPhysicalDevice_T(), VkPipeline, VkPipelineCache, VkPipelineCache_T(), VkPipelineLayout, VkPipelineLayout_T(), VkPipeline_T(), VkPrivateDataSlotEXT, VkPrivateDataSlotEXT_T(), VkQueryPool, VkQueryPool_T(), VkQueue, VkQueue_T(), VkRenderPass, VkRenderPass_T(), VkSampler, VkSamplerYcbcrConversion, VkSamplerYcbcrConversionKHR, VkSamplerYcbcrConversionKHR_T(), VkSamplerYcbcrConversion_T(), VkSampler_T(), VkSemaphore, VkSemaphore_T(), VkShaderModule, VkShaderModule_T(), VkSurfaceKHR, VkSurfaceKHR_T(), VkSwapchainKHR, VkSwapchainKHR_T(), VkValidationCacheEXT, VkValidationCacheEXT_T(), VK_AMD_BUFFER_MARKER_SPEC_VERSION, pattern VK_AMD_BUFFER_MARKER_SPEC_VERSION, VK_AMD_BUFFER_MARKER_EXTENSION_NAME, pattern VK_AMD_BUFFER_MARKER_EXTENSION_NAME) where import GHC.Ptr (Ptr (..)) import Graphics.Vulkan.Marshal import Graphics.Vulkan.Marshal.Proc (VulkanProc (..)) import Graphics.Vulkan.Types.BaseTypes import Graphics.Vulkan.Types.Enum.Pipeline import Graphics.Vulkan.Types.Handles pattern VkCmdWriteBufferMarkerAMD :: CString pattern VkCmdWriteBufferMarkerAMD <- (is_VkCmdWriteBufferMarkerAMD -> True) where VkCmdWriteBufferMarkerAMD = _VkCmdWriteBufferMarkerAMD {-# INLINE _VkCmdWriteBufferMarkerAMD #-} _VkCmdWriteBufferMarkerAMD :: CString _VkCmdWriteBufferMarkerAMD = Ptr "vkCmdWriteBufferMarkerAMD\NUL"# {-# INLINE is_VkCmdWriteBufferMarkerAMD #-} is_VkCmdWriteBufferMarkerAMD :: CString -> Bool is_VkCmdWriteBufferMarkerAMD = (EQ ==) . cmpCStrings _VkCmdWriteBufferMarkerAMD type VkCmdWriteBufferMarkerAMD = "vkCmdWriteBufferMarkerAMD" -- | Queues: 'transfer', 'graphics', 'compute'. -- Renderpass : @both@ -- -- Pipeline: @transfer@ -- > void vkCmdWriteBufferMarkerAMD > ( VkCommandBuffer commandBuffer -- > , VkPipelineStageFlagBits pipelineStage > , -- > , VkDeviceSize dstOffset > , uint32_t marker -- > ) -- < -extensions/html/vkspec.html#vkCmdWriteBufferMarkerAMD vkCmdWriteBufferMarkerAMD registry at www.khronos.org > type HS_vkCmdWriteBufferMarkerAMD = ^ commandBuffer -> VkPipelineStageFlagBits -- ^ pipelineStage -> VkBuffer -- ^ dstBuffer ^ dstOffset -> Word32 -- ^ marker -> IO () type PFN_vkCmdWriteBufferMarkerAMD = FunPtr HS_vkCmdWriteBufferMarkerAMD foreign import ccall unsafe "dynamic" unwrapVkCmdWriteBufferMarkerAMDUnsafe :: PFN_vkCmdWriteBufferMarkerAMD -> HS_vkCmdWriteBufferMarkerAMD foreign import ccall safe "dynamic" unwrapVkCmdWriteBufferMarkerAMDSafe :: PFN_vkCmdWriteBufferMarkerAMD -> HS_vkCmdWriteBufferMarkerAMD instance VulkanProc "vkCmdWriteBufferMarkerAMD" where type VkProcType "vkCmdWriteBufferMarkerAMD" = HS_vkCmdWriteBufferMarkerAMD vkProcSymbol = _VkCmdWriteBufferMarkerAMD # INLINE vkProcSymbol # unwrapVkProcPtrUnsafe = unwrapVkCmdWriteBufferMarkerAMDUnsafe # INLINE unwrapVkProcPtrUnsafe # unwrapVkProcPtrSafe = unwrapVkCmdWriteBufferMarkerAMDSafe # INLINE unwrapVkProcPtrSafe # pattern VK_AMD_BUFFER_MARKER_SPEC_VERSION :: (Num a, Eq a) => a pattern VK_AMD_BUFFER_MARKER_SPEC_VERSION = 1 type VK_AMD_BUFFER_MARKER_SPEC_VERSION = 1 pattern VK_AMD_BUFFER_MARKER_EXTENSION_NAME :: CString pattern VK_AMD_BUFFER_MARKER_EXTENSION_NAME <- (is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME -> True) where VK_AMD_BUFFER_MARKER_EXTENSION_NAME = _VK_AMD_BUFFER_MARKER_EXTENSION_NAME # INLINE _ VK_AMD_BUFFER_MARKER_EXTENSION_NAME # _VK_AMD_BUFFER_MARKER_EXTENSION_NAME :: CString _VK_AMD_BUFFER_MARKER_EXTENSION_NAME = Ptr "VK_AMD_buffer_marker\NUL"# # INLINE is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME # is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME :: CString -> Bool is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME = (EQ ==) . cmpCStrings _VK_AMD_BUFFER_MARKER_EXTENSION_NAME type VK_AMD_BUFFER_MARKER_EXTENSION_NAME = "VK_AMD_buffer_marker"
null
https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_AMD_buffer_marker.hs
haskell
# LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE MagicHash # # LANGUAGE PatternSynonyms # # LANGUAGE Strict # # LANGUAGE TypeFamilies # # LANGUAGE ViewPatterns # | supported: @vulkan@ contact: @Daniel Rakos @drakos-amd@ type: @device@ Extension number: @180@ # INLINE _VkCmdWriteBufferMarkerAMD # # INLINE is_VkCmdWriteBufferMarkerAMD # | Queues: 'transfer', 'graphics', 'compute'. Pipeline: @transfer@ > , VkPipelineStageFlagBits pipelineStage > , VkDeviceSize dstOffset > ) ^ pipelineStage ^ dstBuffer ^ marker
# OPTIONS_GHC -fno - warn - orphans # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_HADDOCK not - home # # LANGUAGE FlexibleInstances # # LANGUAGE ForeignFunctionInterface # module Graphics.Vulkan.Ext.VK_AMD_buffer_marker * Vulkan extension : @VK_AMD_buffer_marker@ author : VkCmdWriteBufferMarkerAMD, pattern VkCmdWriteBufferMarkerAMD, HS_vkCmdWriteBufferMarkerAMD, PFN_vkCmdWriteBufferMarkerAMD, module Graphics.Vulkan.Marshal, AHardwareBuffer(), ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..), VkDeviceSize(..), VkFlags(..), VkSampleMask(..), VkPipelineBindPoint(..), VkPipelineCacheHeaderVersion(..), VkPipelineCreateBitmask(..), VkPipelineCreationFeedbackBitmaskEXT(..), VkPipelineExecutableStatisticFormatKHR(..), VkPipelineStageBitmask(..), VkPipelineCacheCreateBitmask(..), VkPipelineCacheCreateFlagBits(), VkPipelineCacheCreateFlags(), VkPipelineCompilerControlBitmaskAMD(..), VkPipelineCompilerControlFlagBitsAMD(), VkPipelineCompilerControlFlagsAMD(), VkPipelineCreateFlagBits(), VkPipelineCreateFlags(), VkPipelineCreationFeedbackFlagBitsEXT(), VkPipelineCreationFeedbackFlagsEXT(), VkPipelineShaderStageCreateBitmask(..), VkPipelineShaderStageCreateFlagBits(), VkPipelineShaderStageCreateFlags(), VkPipelineStageFlagBits(), VkPipelineStageFlags(), VkAccelerationStructureKHR, VkAccelerationStructureKHR_T(), VkAccelerationStructureNV, VkAccelerationStructureNV_T(), VkBuffer, VkBufferView, VkBufferView_T(), VkBuffer_T(), VkCommandBuffer, VkCommandBuffer_T(), VkCommandPool, VkCommandPool_T(), VkDebugReportCallbackEXT, VkDebugReportCallbackEXT_T(), VkDebugUtilsMessengerEXT, VkDebugUtilsMessengerEXT_T(), VkDeferredOperationKHR, VkDeferredOperationKHR_T(), VkDescriptorPool, VkDescriptorPool_T(), VkDescriptorSet, VkDescriptorSetLayout, VkDescriptorSetLayout_T(), VkDescriptorSet_T(), VkDescriptorUpdateTemplate, VkDescriptorUpdateTemplateKHR, VkDescriptorUpdateTemplateKHR_T(), VkDescriptorUpdateTemplate_T(), VkDevice, VkDeviceMemory, VkDeviceMemory_T(), VkDevice_T(), VkDisplayKHR, VkDisplayKHR_T(), VkDisplayModeKHR, VkDisplayModeKHR_T(), VkEvent, VkEvent_T(), VkFence, VkFence_T(), VkFramebuffer, VkFramebuffer_T(), VkImage, VkImageView, VkImageView_T(), VkImage_T(), VkIndirectCommandsLayoutNV, VkIndirectCommandsLayoutNV_T(), VkInstance, VkInstance_T(), VkPerformanceConfigurationINTEL, VkPerformanceConfigurationINTEL_T(), VkPhysicalDevice, VkPhysicalDevice_T(), VkPipeline, VkPipelineCache, VkPipelineCache_T(), VkPipelineLayout, VkPipelineLayout_T(), VkPipeline_T(), VkPrivateDataSlotEXT, VkPrivateDataSlotEXT_T(), VkQueryPool, VkQueryPool_T(), VkQueue, VkQueue_T(), VkRenderPass, VkRenderPass_T(), VkSampler, VkSamplerYcbcrConversion, VkSamplerYcbcrConversionKHR, VkSamplerYcbcrConversionKHR_T(), VkSamplerYcbcrConversion_T(), VkSampler_T(), VkSemaphore, VkSemaphore_T(), VkShaderModule, VkShaderModule_T(), VkSurfaceKHR, VkSurfaceKHR_T(), VkSwapchainKHR, VkSwapchainKHR_T(), VkValidationCacheEXT, VkValidationCacheEXT_T(), VK_AMD_BUFFER_MARKER_SPEC_VERSION, pattern VK_AMD_BUFFER_MARKER_SPEC_VERSION, VK_AMD_BUFFER_MARKER_EXTENSION_NAME, pattern VK_AMD_BUFFER_MARKER_EXTENSION_NAME) where import GHC.Ptr (Ptr (..)) import Graphics.Vulkan.Marshal import Graphics.Vulkan.Marshal.Proc (VulkanProc (..)) import Graphics.Vulkan.Types.BaseTypes import Graphics.Vulkan.Types.Enum.Pipeline import Graphics.Vulkan.Types.Handles pattern VkCmdWriteBufferMarkerAMD :: CString pattern VkCmdWriteBufferMarkerAMD <- (is_VkCmdWriteBufferMarkerAMD -> True) where VkCmdWriteBufferMarkerAMD = _VkCmdWriteBufferMarkerAMD _VkCmdWriteBufferMarkerAMD :: CString _VkCmdWriteBufferMarkerAMD = Ptr "vkCmdWriteBufferMarkerAMD\NUL"# is_VkCmdWriteBufferMarkerAMD :: CString -> Bool is_VkCmdWriteBufferMarkerAMD = (EQ ==) . cmpCStrings _VkCmdWriteBufferMarkerAMD type VkCmdWriteBufferMarkerAMD = "vkCmdWriteBufferMarkerAMD" Renderpass : @both@ > void vkCmdWriteBufferMarkerAMD > ( VkCommandBuffer commandBuffer > , > , uint32_t marker < -extensions/html/vkspec.html#vkCmdWriteBufferMarkerAMD vkCmdWriteBufferMarkerAMD registry at www.khronos.org > type HS_vkCmdWriteBufferMarkerAMD = ^ commandBuffer -> -> ^ dstOffset -> IO () type PFN_vkCmdWriteBufferMarkerAMD = FunPtr HS_vkCmdWriteBufferMarkerAMD foreign import ccall unsafe "dynamic" unwrapVkCmdWriteBufferMarkerAMDUnsafe :: PFN_vkCmdWriteBufferMarkerAMD -> HS_vkCmdWriteBufferMarkerAMD foreign import ccall safe "dynamic" unwrapVkCmdWriteBufferMarkerAMDSafe :: PFN_vkCmdWriteBufferMarkerAMD -> HS_vkCmdWriteBufferMarkerAMD instance VulkanProc "vkCmdWriteBufferMarkerAMD" where type VkProcType "vkCmdWriteBufferMarkerAMD" = HS_vkCmdWriteBufferMarkerAMD vkProcSymbol = _VkCmdWriteBufferMarkerAMD # INLINE vkProcSymbol # unwrapVkProcPtrUnsafe = unwrapVkCmdWriteBufferMarkerAMDUnsafe # INLINE unwrapVkProcPtrUnsafe # unwrapVkProcPtrSafe = unwrapVkCmdWriteBufferMarkerAMDSafe # INLINE unwrapVkProcPtrSafe # pattern VK_AMD_BUFFER_MARKER_SPEC_VERSION :: (Num a, Eq a) => a pattern VK_AMD_BUFFER_MARKER_SPEC_VERSION = 1 type VK_AMD_BUFFER_MARKER_SPEC_VERSION = 1 pattern VK_AMD_BUFFER_MARKER_EXTENSION_NAME :: CString pattern VK_AMD_BUFFER_MARKER_EXTENSION_NAME <- (is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME -> True) where VK_AMD_BUFFER_MARKER_EXTENSION_NAME = _VK_AMD_BUFFER_MARKER_EXTENSION_NAME # INLINE _ VK_AMD_BUFFER_MARKER_EXTENSION_NAME # _VK_AMD_BUFFER_MARKER_EXTENSION_NAME :: CString _VK_AMD_BUFFER_MARKER_EXTENSION_NAME = Ptr "VK_AMD_buffer_marker\NUL"# # INLINE is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME # is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME :: CString -> Bool is_VK_AMD_BUFFER_MARKER_EXTENSION_NAME = (EQ ==) . cmpCStrings _VK_AMD_BUFFER_MARKER_EXTENSION_NAME type VK_AMD_BUFFER_MARKER_EXTENSION_NAME = "VK_AMD_buffer_marker"
5052d39033037b3ba19cbc20347366cf1682ac9f152a1e123b6eec4d43abc54a
d-cent/mooncake
feed.clj
(ns mooncake.test.controller.feed (:require [midje.sweet :refer :all] [mooncake.controller.feed :as fc] [mooncake.activity :as a] [mooncake.test.test-helpers.enlive :as eh] [mooncake.test.test-helpers.db :as dbh] [mooncake.db.user :as user] [mooncake.db.mongo :as mongo] [mooncake.db.activity :as adb] [mooncake.config :as config]) (:import (org.bson.types ObjectId))) (def ten-oclock "2015-01-01T10:00:00.000Z") (def eleven-oclock "2015-01-01T11:00:00.000Z") (def twelve-oclock "2015-01-02T12:00:00.000Z") (def next-day "2015-01-02T12:00:00.000Z") (def previous-day "2014-12-31T12:00:00.000Z") (def base-insert-time "564c8f57d4c6d9e63f34c6b") (fact "feed handler displays activities retrieved from activity sources" (let [store (dbh/create-in-memory-store)] (mongo/store! store adb/activity-collection {:actor {:type "Person" :name "JDog"} :published ten-oclock :activity-src "OpenAhjo" :type "Activity"}) (mongo/store! store adb/activity-collection {:actor {:type "Person" :name "KCat"} :published twelve-oclock :activity-src "objective8" :type "Activity"}) (fc/feed store {:context {:activity-sources {:OpenAhjo {:activity-types ["Activity"]} :objective8 {:activity-types ["Activity"]}}} :t (constantly "")}) => (every-checker (eh/check-renders-page :.func--feed-page) (contains {:body (contains "JDog")}) (contains {:body (contains "KCat")})))) (fact "feed handler displays username of logged-in user" (fc/feed (dbh/create-in-memory-store) {:t (constantly "") :session {:username "Barry"}}) => (contains {:body (contains "Barry")})) (def activity-src-1--enabled-type {:actor {:type "Person" :name "Activity source 1: enabled type"} :published ten-oclock :activity-src "activity-src-1" :type "Enabled" :relInsertTime (ObjectId. (str base-insert-time 1))}) (def activity-src-1--previous-day {:actor {:type "Person" :name "Activity source 1: previous day"} :published previous-day :activity-src "activity-src-1" :type "Enabled" :relInsertTime (ObjectId. (str base-insert-time 2))}) (def activity-src-1--disabled-type {:actor {:type "Person" :name "Activity source 1: disabled type"} :published eleven-oclock :activity-src "activity-src-1" :type "Disabled" :relInsertTime (ObjectId. (str base-insert-time 3))}) (def activity-src-2--no-preference-type {:actor {:type "Person" :name "Activity source 2: no preference expressed"} :published twelve-oclock :activity-src "activity-src-2" :type "No-preference" :relInsertTime (ObjectId. (str base-insert-time 4))}) (facts "about which activities feed handler displays" (let [store (dbh/create-in-memory-store) _ (mongo/store! store adb/activity-collection activity-src-1--enabled-type) _ (mongo/store! store adb/activity-collection activity-src-1--disabled-type) _ (mongo/store! store adb/activity-collection activity-src-2--no-preference-type) _ (user/create-user! store ...user-id... ...username...) _ (user/update-feed-settings! store ...username... {:activity-src-1 {:types [{:id "Enabled" :selected true} {:id "Disabled" :selected false}]}}) request {:context {:activity-sources {:activity-src-1 {:activity-types ["Enabled" "Disabled"]} :activity-src-2 {:activity-types ["No-preference"]}}} :t (constantly "") :session {:username ...username...}} response (fc/feed store request)] (fact "enabled activity types are shown" (:body response) => (contains "Activity source 1: enabled type")) (fact "disabled activity types are not shown" (:body response) =not=> (contains "Activity source 1: disabled type")) (fact "no-preference activity types are shown" (:body response) => (contains "Activity source 2: no preference expressed")) (fact "custom message is not shown when there are activities on the page" (:body response) =not=> (contains "clj--empty-activity-item")) (fact "custom message is shown if all activity types are disabled" (user/update-feed-settings! store ...username... {:activity-src-1 {:types [{:id "Disabled" :selected false}]}}) (let [no-activities-request {:context {:activity-sources {:activity-src-1 {:activity-types ["Disabled"]}}} :t (constantly "") :session {:username ...username...}} no-activities-response (fc/feed store no-activities-request)] (:body no-activities-response) => (contains "clj--empty-activity-item"))))) (facts "about generating the activity query map" (let [feed-settings {:activity-src-1 {:types [{:id "Enabled" :selected true} {:id "Disabled" :selected false}]} :activity-src-2 {:types [{:id "Disabled" :selected false}]}} activity-sources {:activity-src-1 {:activity-types ["Enabled" "Disabled" "No-preference"]} :activity-src-2 {:activity-types ["Disabled"]} :activity-src-3 {:activity-types ["No-preference"]}}] (fc/generate-feed-query feed-settings activity-sources) => (just [{:activity-src "activity-src-1" :type ["Enabled" "No-preference"]} {:activity-src "activity-src-3" :type ["No-preference"]}] :in-any-order))) (facts "about pagination" (let [store (dbh/create-in-memory-store) _ (user/create-user! store ...user-id... ...username...) _ (dbh/create-dummy-activities store (+ 1 config/activities-per-page)) valid-page-number "2" invalid-page-number "ABC" too-tiny-of-a-page-number "0" too-big-of-a-page-number "3"] (fact "page number is passed in get request" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number valid-page-number}} response (fc/feed store request)] (:body response) => (contains "TestData0") (:body response) =not=> (contains (str "TestData" config/activities-per-page)))) (fact "empty page number params is passed in get request and defaults to 1" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {}} response (fc/feed store request)] (:body response) =not=> (contains "TestData0") (:body response) => (contains (str "TestData" config/activities-per-page)))) (fact "page number cannot be non-numbers" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number invalid-page-number}} response (fc/feed store request)] (:status response) => nil)) (fact "page number cannot be too small" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number too-tiny-of-a-page-number}} response (fc/feed store request)] (:status response) => nil)) (fact "page number cannot be too big" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number too-big-of-a-page-number}} response (fc/feed store request)] (:status response) => nil)))) (defn request-with-timestamp [timestamp-params] {:context {:activity-sources {:activity-src-1 {:activity-types ["Enabled" "Disabled"]} :activity-src-2 {:activity-types ["No-preference"]}}} :t (constantly "") :session {:username ...username...} :params timestamp-params}) (facts "about which activities are retrieved and updated" (let [store (dbh/create-in-memory-store) _ (mongo/store! store adb/activity-collection activity-src-1--enabled-type) _ (mongo/store! store adb/activity-collection activity-src-1--previous-day) _ (mongo/store! store adb/activity-collection activity-src-1--disabled-type) _ (mongo/store! store adb/activity-collection activity-src-2--no-preference-type) _ (user/create-user! store ...user-id... ...username...) _ (user/update-feed-settings! store ...username... {:activity-src-1 {:types [{:id "Enabled" :selected true} {:id "Disabled" :selected false}]}}) response-for-retrieving (fc/retrieve-activities-html store (request-with-timestamp {:timestamp-to next-day :insert-id (str base-insert-time 5)})) response-for-updating (fc/retrieve-activities-html store (request-with-timestamp {:timestamp-from previous-day :insert-id (str base-insert-time 2)}))] (facts "retrieving older activities" (fact "enabled activity types are shown" (:body response-for-retrieving) => (contains "Activity source 1: enabled type")) (fact "disabled activity types are not shown" (:body response-for-retrieving) =not=> (contains "Activity source 1: disabled type")) (fact "no-preference activity types are shown" (:body response-for-retrieving) => (contains "Activity source 2: no preference expressed"))) (facts "retrieving newer activities" (fact "enabled activity types are shown" (:body response-for-updating) => (contains "Activity source 1: enabled type")) (fact "disabled activity types are not shown" (:body response-for-updating) =not=> (contains "Activity source 1: disabled type")) (fact "no-preference activity types are shown" (:body response-for-updating) => (contains "Activity source 2: no preference expressed")) (fact "activity with timestamp in query parameter is not shown" (:body response-for-updating) =not=> (contains "Activity source 1: previous day"))) (facts "error handling" (let [bad-timestamp "2015-01-0110:00:00.000Z" bad-timestamp-response (fc/retrieve-activities-html store (request-with-timestamp {:timestamp-to bad-timestamp :insert-id (str base-insert-time 1)}))] (fact "valid-timestamp? returns whether a timestamp is in the correct format" (fc/valid-timestamp? next-day) => truthy (fc/valid-timestamp? bad-timestamp) => falsey) (fact "invalid format for timestamp returns Bad Request" (:status bad-timestamp-response) => 400)))))
null
https://raw.githubusercontent.com/d-cent/mooncake/eb16b7239e7580a73b98f7cdacb324ab4e301f9c/test/mooncake/test/controller/feed.clj
clojure
(ns mooncake.test.controller.feed (:require [midje.sweet :refer :all] [mooncake.controller.feed :as fc] [mooncake.activity :as a] [mooncake.test.test-helpers.enlive :as eh] [mooncake.test.test-helpers.db :as dbh] [mooncake.db.user :as user] [mooncake.db.mongo :as mongo] [mooncake.db.activity :as adb] [mooncake.config :as config]) (:import (org.bson.types ObjectId))) (def ten-oclock "2015-01-01T10:00:00.000Z") (def eleven-oclock "2015-01-01T11:00:00.000Z") (def twelve-oclock "2015-01-02T12:00:00.000Z") (def next-day "2015-01-02T12:00:00.000Z") (def previous-day "2014-12-31T12:00:00.000Z") (def base-insert-time "564c8f57d4c6d9e63f34c6b") (fact "feed handler displays activities retrieved from activity sources" (let [store (dbh/create-in-memory-store)] (mongo/store! store adb/activity-collection {:actor {:type "Person" :name "JDog"} :published ten-oclock :activity-src "OpenAhjo" :type "Activity"}) (mongo/store! store adb/activity-collection {:actor {:type "Person" :name "KCat"} :published twelve-oclock :activity-src "objective8" :type "Activity"}) (fc/feed store {:context {:activity-sources {:OpenAhjo {:activity-types ["Activity"]} :objective8 {:activity-types ["Activity"]}}} :t (constantly "")}) => (every-checker (eh/check-renders-page :.func--feed-page) (contains {:body (contains "JDog")}) (contains {:body (contains "KCat")})))) (fact "feed handler displays username of logged-in user" (fc/feed (dbh/create-in-memory-store) {:t (constantly "") :session {:username "Barry"}}) => (contains {:body (contains "Barry")})) (def activity-src-1--enabled-type {:actor {:type "Person" :name "Activity source 1: enabled type"} :published ten-oclock :activity-src "activity-src-1" :type "Enabled" :relInsertTime (ObjectId. (str base-insert-time 1))}) (def activity-src-1--previous-day {:actor {:type "Person" :name "Activity source 1: previous day"} :published previous-day :activity-src "activity-src-1" :type "Enabled" :relInsertTime (ObjectId. (str base-insert-time 2))}) (def activity-src-1--disabled-type {:actor {:type "Person" :name "Activity source 1: disabled type"} :published eleven-oclock :activity-src "activity-src-1" :type "Disabled" :relInsertTime (ObjectId. (str base-insert-time 3))}) (def activity-src-2--no-preference-type {:actor {:type "Person" :name "Activity source 2: no preference expressed"} :published twelve-oclock :activity-src "activity-src-2" :type "No-preference" :relInsertTime (ObjectId. (str base-insert-time 4))}) (facts "about which activities feed handler displays" (let [store (dbh/create-in-memory-store) _ (mongo/store! store adb/activity-collection activity-src-1--enabled-type) _ (mongo/store! store adb/activity-collection activity-src-1--disabled-type) _ (mongo/store! store adb/activity-collection activity-src-2--no-preference-type) _ (user/create-user! store ...user-id... ...username...) _ (user/update-feed-settings! store ...username... {:activity-src-1 {:types [{:id "Enabled" :selected true} {:id "Disabled" :selected false}]}}) request {:context {:activity-sources {:activity-src-1 {:activity-types ["Enabled" "Disabled"]} :activity-src-2 {:activity-types ["No-preference"]}}} :t (constantly "") :session {:username ...username...}} response (fc/feed store request)] (fact "enabled activity types are shown" (:body response) => (contains "Activity source 1: enabled type")) (fact "disabled activity types are not shown" (:body response) =not=> (contains "Activity source 1: disabled type")) (fact "no-preference activity types are shown" (:body response) => (contains "Activity source 2: no preference expressed")) (fact "custom message is not shown when there are activities on the page" (:body response) =not=> (contains "clj--empty-activity-item")) (fact "custom message is shown if all activity types are disabled" (user/update-feed-settings! store ...username... {:activity-src-1 {:types [{:id "Disabled" :selected false}]}}) (let [no-activities-request {:context {:activity-sources {:activity-src-1 {:activity-types ["Disabled"]}}} :t (constantly "") :session {:username ...username...}} no-activities-response (fc/feed store no-activities-request)] (:body no-activities-response) => (contains "clj--empty-activity-item"))))) (facts "about generating the activity query map" (let [feed-settings {:activity-src-1 {:types [{:id "Enabled" :selected true} {:id "Disabled" :selected false}]} :activity-src-2 {:types [{:id "Disabled" :selected false}]}} activity-sources {:activity-src-1 {:activity-types ["Enabled" "Disabled" "No-preference"]} :activity-src-2 {:activity-types ["Disabled"]} :activity-src-3 {:activity-types ["No-preference"]}}] (fc/generate-feed-query feed-settings activity-sources) => (just [{:activity-src "activity-src-1" :type ["Enabled" "No-preference"]} {:activity-src "activity-src-3" :type ["No-preference"]}] :in-any-order))) (facts "about pagination" (let [store (dbh/create-in-memory-store) _ (user/create-user! store ...user-id... ...username...) _ (dbh/create-dummy-activities store (+ 1 config/activities-per-page)) valid-page-number "2" invalid-page-number "ABC" too-tiny-of-a-page-number "0" too-big-of-a-page-number "3"] (fact "page number is passed in get request" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number valid-page-number}} response (fc/feed store request)] (:body response) => (contains "TestData0") (:body response) =not=> (contains (str "TestData" config/activities-per-page)))) (fact "empty page number params is passed in get request and defaults to 1" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {}} response (fc/feed store request)] (:body response) =not=> (contains "TestData0") (:body response) => (contains (str "TestData" config/activities-per-page)))) (fact "page number cannot be non-numbers" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number invalid-page-number}} response (fc/feed store request)] (:status response) => nil)) (fact "page number cannot be too small" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number too-tiny-of-a-page-number}} response (fc/feed store request)] (:status response) => nil)) (fact "page number cannot be too big" (let [request {:context {:activity-sources {:test-source {:activity-types ["Create"]}}} :t (constantly "") :session {:username ...username...} :params {:page-number too-big-of-a-page-number}} response (fc/feed store request)] (:status response) => nil)))) (defn request-with-timestamp [timestamp-params] {:context {:activity-sources {:activity-src-1 {:activity-types ["Enabled" "Disabled"]} :activity-src-2 {:activity-types ["No-preference"]}}} :t (constantly "") :session {:username ...username...} :params timestamp-params}) (facts "about which activities are retrieved and updated" (let [store (dbh/create-in-memory-store) _ (mongo/store! store adb/activity-collection activity-src-1--enabled-type) _ (mongo/store! store adb/activity-collection activity-src-1--previous-day) _ (mongo/store! store adb/activity-collection activity-src-1--disabled-type) _ (mongo/store! store adb/activity-collection activity-src-2--no-preference-type) _ (user/create-user! store ...user-id... ...username...) _ (user/update-feed-settings! store ...username... {:activity-src-1 {:types [{:id "Enabled" :selected true} {:id "Disabled" :selected false}]}}) response-for-retrieving (fc/retrieve-activities-html store (request-with-timestamp {:timestamp-to next-day :insert-id (str base-insert-time 5)})) response-for-updating (fc/retrieve-activities-html store (request-with-timestamp {:timestamp-from previous-day :insert-id (str base-insert-time 2)}))] (facts "retrieving older activities" (fact "enabled activity types are shown" (:body response-for-retrieving) => (contains "Activity source 1: enabled type")) (fact "disabled activity types are not shown" (:body response-for-retrieving) =not=> (contains "Activity source 1: disabled type")) (fact "no-preference activity types are shown" (:body response-for-retrieving) => (contains "Activity source 2: no preference expressed"))) (facts "retrieving newer activities" (fact "enabled activity types are shown" (:body response-for-updating) => (contains "Activity source 1: enabled type")) (fact "disabled activity types are not shown" (:body response-for-updating) =not=> (contains "Activity source 1: disabled type")) (fact "no-preference activity types are shown" (:body response-for-updating) => (contains "Activity source 2: no preference expressed")) (fact "activity with timestamp in query parameter is not shown" (:body response-for-updating) =not=> (contains "Activity source 1: previous day"))) (facts "error handling" (let [bad-timestamp "2015-01-0110:00:00.000Z" bad-timestamp-response (fc/retrieve-activities-html store (request-with-timestamp {:timestamp-to bad-timestamp :insert-id (str base-insert-time 1)}))] (fact "valid-timestamp? returns whether a timestamp is in the correct format" (fc/valid-timestamp? next-day) => truthy (fc/valid-timestamp? bad-timestamp) => falsey) (fact "invalid format for timestamp returns Bad Request" (:status bad-timestamp-response) => 400)))))
5a9ca64508f2d7bd334ea9546529d39d5c8d6563b7a98873233a20c2320cac37
spawngrid/htoad
htoad_htoad.erl
-module(htoad_htoad). -include_lib("htoad/include/htoad.hrl"). -include_lib("htoad/include/toadie.hrl"). -include_lib("htoad/include/stdlib.hrl"). -rules([init]). init(Engine, #init{}) -> Engine1 = htoad:assert(Engine, #htoad{ version = vsn() }), lager:debug("Initialized htoad_htoad"), Engine1. %% private vsn() -> {ok, Vsn} = application:get_key(htoad, vsn), Vsn.
null
https://raw.githubusercontent.com/spawngrid/htoad/f0c7dfbd911b29fb0c406b7c26606f553af11194/apps/htoad/src/htoad_htoad.erl
erlang
private
-module(htoad_htoad). -include_lib("htoad/include/htoad.hrl"). -include_lib("htoad/include/toadie.hrl"). -include_lib("htoad/include/stdlib.hrl"). -rules([init]). init(Engine, #init{}) -> Engine1 = htoad:assert(Engine, #htoad{ version = vsn() }), lager:debug("Initialized htoad_htoad"), Engine1. vsn() -> {ok, Vsn} = application:get_key(htoad, vsn), Vsn.
3a9a8cb2842d2bf8be671fa6e0ac221785809b63db1aeb8bdc4d59f51f214484
djs55/vhd-tool
xenstore.ml
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) let error fmt = Printf.ksprintf (output_string stderr) fmt module Client = Xs_client_unix.Client(Xs_transport_unix_client) let make_client () = try Client.make () with e -> error "Failed to connect to xenstore. The raw error was: %s" (Printexc.to_string e); begin match e with | Unix.Unix_error(Unix.EACCES, _, _) -> error "Access to xenstore was denied."; let euid = Unix.geteuid () in if euid <> 0 then begin error "My effective uid is %d." euid; error "Typically xenstore can only be accessed by root (uid 0)."; error "Please switch to root (uid 0) and retry." end | Unix.Unix_error(Unix.ECONNREFUSED, _, _) -> error "Access to xenstore was refused."; error "This normally indicates that the service is not running."; error "Please start the xenstore service and retry." | _ -> () end; raise e let get_client = let client = ref None in fun () -> match !client with | None -> let c = make_client () in client := Some c; c | Some c -> c type domid = int module Xs = struct type domid = int type xsh = { (* debug: string list -> string; *) directory : string -> string list; read : string -> string; (* readv : string -> string list -> string list; *) write : string -> string -> unit; writev : string -> (string * string) list -> unit; mkdir : string -> unit; rm : string -> unit; getperms : string - > perms ; : string - > string list - > perms - > unit ; release : domid - > unit ; resume : domid - > unit ; getperms : string -> perms; setpermsv : string -> string list -> perms -> unit; release : domid -> unit; resume : domid -> unit; *) setperms : string -> Xs_protocol.ACL.t -> unit; getdomainpath : domid -> string; watch : string -> string -> unit; unwatch : string -> string -> unit; introduce : domid -> nativeint -> int -> unit; set_target : domid -> domid -> unit; } let ops h = { read = Client.read h; directory = Client.directory h; write = Client.write h; writev = (fun base_path -> List.iter (fun (k, v) -> Client.write h (base_path ^ "/" ^ k) v)); mkdir = Client.mkdir h; rm = (fun path -> try Client.rm h path with Xs_protocol.Enoent _ -> ()); setperms = Client.setperms h; getdomainpath = Client.getdomainpath h; watch = Client.watch h; unwatch = Client.unwatch h; introduce = Client.introduce h; set_target = Client.set_target h; } let with_xs f = Client.immediate (get_client ()) (fun h -> f (ops h)) let wait f = Client.wait (get_client ()) (fun h -> f (ops h)) let transaction _ f = Client.transaction (get_client ()) (fun h -> f (ops h)) end module Xst = Xs let with_xs = Xs.with_xs
null
https://raw.githubusercontent.com/djs55/vhd-tool/ef051aae1b52888c6158a54bacdbaa2bf190679d/src/xenstore.ml
ocaml
debug: string list -> string; readv : string -> string list -> string list;
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) let error fmt = Printf.ksprintf (output_string stderr) fmt module Client = Xs_client_unix.Client(Xs_transport_unix_client) let make_client () = try Client.make () with e -> error "Failed to connect to xenstore. The raw error was: %s" (Printexc.to_string e); begin match e with | Unix.Unix_error(Unix.EACCES, _, _) -> error "Access to xenstore was denied."; let euid = Unix.geteuid () in if euid <> 0 then begin error "My effective uid is %d." euid; error "Typically xenstore can only be accessed by root (uid 0)."; error "Please switch to root (uid 0) and retry." end | Unix.Unix_error(Unix.ECONNREFUSED, _, _) -> error "Access to xenstore was refused."; error "This normally indicates that the service is not running."; error "Please start the xenstore service and retry." | _ -> () end; raise e let get_client = let client = ref None in fun () -> match !client with | None -> let c = make_client () in client := Some c; c | Some c -> c type domid = int module Xs = struct type domid = int type xsh = { directory : string -> string list; read : string -> string; write : string -> string -> unit; writev : string -> (string * string) list -> unit; mkdir : string -> unit; rm : string -> unit; getperms : string - > perms ; : string - > string list - > perms - > unit ; release : domid - > unit ; resume : domid - > unit ; getperms : string -> perms; setpermsv : string -> string list -> perms -> unit; release : domid -> unit; resume : domid -> unit; *) setperms : string -> Xs_protocol.ACL.t -> unit; getdomainpath : domid -> string; watch : string -> string -> unit; unwatch : string -> string -> unit; introduce : domid -> nativeint -> int -> unit; set_target : domid -> domid -> unit; } let ops h = { read = Client.read h; directory = Client.directory h; write = Client.write h; writev = (fun base_path -> List.iter (fun (k, v) -> Client.write h (base_path ^ "/" ^ k) v)); mkdir = Client.mkdir h; rm = (fun path -> try Client.rm h path with Xs_protocol.Enoent _ -> ()); setperms = Client.setperms h; getdomainpath = Client.getdomainpath h; watch = Client.watch h; unwatch = Client.unwatch h; introduce = Client.introduce h; set_target = Client.set_target h; } let with_xs f = Client.immediate (get_client ()) (fun h -> f (ops h)) let wait f = Client.wait (get_client ()) (fun h -> f (ops h)) let transaction _ f = Client.transaction (get_client ()) (fun h -> f (ops h)) end module Xst = Xs let with_xs = Xs.with_xs
0158e80cd6451aabd434157922a5d73f7c11e14da3ff12d8db4d7fe11d4bcd7d
erikd/vector-algorithms
Combinators.hs
{-# LANGUAGE Rank2Types, TypeOperators #-} -- --------------------------------------------------------------------------- -- | -- Module : Data.Vector.Algorithms.Combinators Copyright : ( c ) 2008 - 2010 Maintainer : < > -- Stability : Experimental -- Portability : Non-portable (rank-2 types) -- -- The purpose of this module is to supply various combinators for commonly -- used idioms for the algorithms in this package. Examples at the time of -- this writing include running an algorithm keyed on some function of the -- elements (but only computing said function once per element), and safely -- applying the algorithms on mutable arrays to immutable arrays. module Data.Vector.Algorithms.Combinators ( -- , usingKeys -- , usingIxKeys ) where import Prelude hiding (length) import Control.Monad.ST import Data.Ord import Data.Vector.Generic import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Generic.New as N -- | Uses a function to compute a key for each element which the -- algorithm should use in lieu of the actual element . For instance : -- -- > usingKeys f arr -- -- should produce the same results as : -- -- > ( comparing f ) arr -- -- the difference being that usingKeys computes each key only once -- which can be more efficient for expensive key functions . usingKeys : : ( UA e , UA k , Ord k ) = > ( forall e ' . ( UA e ' ) = > Comparison e ' - > MUArr e ' s - > ST s ( ) ) - > ( e - > k ) - > MUArr e s - > ST s ( ) usingKeys algo f arr = usingIxKeys algo ( const f ) arr { - # INLINE usingKeys # -- | Uses a function to compute a key for each element which the -- algorithm should use in lieu of the actual element. For instance: -- -- > usingKeys sortBy f arr -- -- should produce the same results as: -- -- > sortBy (comparing f) arr -- -- the difference being that usingKeys computes each key only once -- which can be more efficient for expensive key functions. usingKeys :: (UA e, UA k, Ord k) => (forall e'. (UA e') => Comparison e' -> MUArr e' s -> ST s ()) -> (e -> k) -> MUArr e s -> ST s () usingKeys algo f arr = usingIxKeys algo (const f) arr {-# INLINE usingKeys #-} -- | As usingKeys, only the key function has access to the array index -- at which each element is stored. usingIxKeys :: (UA e, UA k, Ord k) => (forall e'. (UA e') => Comparison e' -> MUArr e' s -> ST s ()) -> (Int -> e -> k) -> MUArr e s -> ST s () usingIxKeys algo f arr = do keys <- newMU (lengthMU arr) fill len keys algo (comparing fstS) (unsafeZipMU keys arr) where len = lengthMU arr fill k keys | k < 0 = return () | otherwise = readMU arr k >>= writeMU keys k . f k >> fill (k-1) keys # INLINE usingIxKeys # -}
null
https://raw.githubusercontent.com/erikd/vector-algorithms/d25f05648ebf419a96755eeba7352df6b7f7dd3f/src/Data/Vector/Algorithms/Combinators.hs
haskell
# LANGUAGE Rank2Types, TypeOperators # --------------------------------------------------------------------------- | Module : Data.Vector.Algorithms.Combinators Stability : Experimental Portability : Non-portable (rank-2 types) The purpose of this module is to supply various combinators for commonly used idioms for the algorithms in this package. Examples at the time of this writing include running an algorithm keyed on some function of the elements (but only computing said function once per element), and safely applying the algorithms on mutable arrays to immutable arrays. , usingKeys , usingIxKeys | Uses a function to compute a key for each element which the algorithm should use in lieu of the actual element . For instance : > usingKeys f arr should produce the same results as : > ( comparing f ) arr the difference being that usingKeys computes each key only once which can be more efficient for expensive key functions . | Uses a function to compute a key for each element which the algorithm should use in lieu of the actual element. For instance: > usingKeys sortBy f arr should produce the same results as: > sortBy (comparing f) arr the difference being that usingKeys computes each key only once which can be more efficient for expensive key functions. # INLINE usingKeys # | As usingKeys, only the key function has access to the array index at which each element is stored.
Copyright : ( c ) 2008 - 2010 Maintainer : < > module Data.Vector.Algorithms.Combinators ( ) where import Prelude hiding (length) import Control.Monad.ST import Data.Ord import Data.Vector.Generic import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Generic.New as N usingKeys : : ( UA e , UA k , Ord k ) = > ( forall e ' . ( UA e ' ) = > Comparison e ' - > MUArr e ' s - > ST s ( ) ) - > ( e - > k ) - > MUArr e s - > ST s ( ) usingKeys algo f arr = usingIxKeys algo ( const f ) arr { - # INLINE usingKeys # usingKeys :: (UA e, UA k, Ord k) => (forall e'. (UA e') => Comparison e' -> MUArr e' s -> ST s ()) -> (e -> k) -> MUArr e s -> ST s () usingKeys algo f arr = usingIxKeys algo (const f) arr usingIxKeys :: (UA e, UA k, Ord k) => (forall e'. (UA e') => Comparison e' -> MUArr e' s -> ST s ()) -> (Int -> e -> k) -> MUArr e s -> ST s () usingIxKeys algo f arr = do keys <- newMU (lengthMU arr) fill len keys algo (comparing fstS) (unsafeZipMU keys arr) where len = lengthMU arr fill k keys | k < 0 = return () | otherwise = readMU arr k >>= writeMU keys k . f k >> fill (k-1) keys # INLINE usingIxKeys # -}
f0c3f07ef8dc498d6937937cf7bb191f2f10ef539cb3525bb7b49ab280380f98
nilenso/time-tracker
routes.clj
(ns time-tracker.clients.routes (:require [time-tracker.clients.handlers :as handlers] [time-tracker.web.middleware :refer [with-rest-middleware]])) (defn routes [] {"" (with-rest-middleware {:get handlers/list-all :post handlers/create}) [:id "/"] (with-rest-middleware {:put handlers/modify})})
null
https://raw.githubusercontent.com/nilenso/time-tracker/054d0dc6d6b89a4ed234d8f0b0a260b6deeef9e3/src/clj/time_tracker/clients/routes.clj
clojure
(ns time-tracker.clients.routes (:require [time-tracker.clients.handlers :as handlers] [time-tracker.web.middleware :refer [with-rest-middleware]])) (defn routes [] {"" (with-rest-middleware {:get handlers/list-all :post handlers/create}) [:id "/"] (with-rest-middleware {:put handlers/modify})})
a5898f309f398d7b46eec481231cb034de8997304a28627623034e78161d46f1
magnusjonsson/opti
expr.ml
type unop = | Unop_neg | Unop_abs type binop = | Binop_add | Binop_sub | Binop_mul | Binop_div | Binop_min | Binop_max | Binop_le | Binop_ge | Binop_lt | Binop_gt type expr = | Expr_const of float | Expr_ref of string * string list | Expr_unop of unop * expr | Expr_binop of binop * expr * expr | Expr_if of expr * expr * expr if the two indices are equal , then first expr , else second expr let map_subscripts_in_expr (f: string -> string) (e: expr) = let rec process e = match e with | Expr_const _ -> e | Expr_ref(variable_name,subscripts) -> Expr_ref(variable_name, List.map f subscripts) | Expr_unop(u, e1) -> Expr_unop(u, process e1) | Expr_binop(b, e1, e2) -> Expr_binop(b, process e1, process e2) | Expr_index_eq_ne(i1, i2, e1, e2) -> Expr_index_eq_ne(f i1, f i2, process e1, process e2) | Expr_if(e1, e2, e3) -> Expr_if(process e1, process e2, process e3) in process e
null
https://raw.githubusercontent.com/magnusjonsson/opti/dffb7b86b81c8059276b038313ddd88d2e9ff67e/lib/expr.ml
ocaml
type unop = | Unop_neg | Unop_abs type binop = | Binop_add | Binop_sub | Binop_mul | Binop_div | Binop_min | Binop_max | Binop_le | Binop_ge | Binop_lt | Binop_gt type expr = | Expr_const of float | Expr_ref of string * string list | Expr_unop of unop * expr | Expr_binop of binop * expr * expr | Expr_if of expr * expr * expr if the two indices are equal , then first expr , else second expr let map_subscripts_in_expr (f: string -> string) (e: expr) = let rec process e = match e with | Expr_const _ -> e | Expr_ref(variable_name,subscripts) -> Expr_ref(variable_name, List.map f subscripts) | Expr_unop(u, e1) -> Expr_unop(u, process e1) | Expr_binop(b, e1, e2) -> Expr_binop(b, process e1, process e2) | Expr_index_eq_ne(i1, i2, e1, e2) -> Expr_index_eq_ne(f i1, f i2, process e1, process e2) | Expr_if(e1, e2, e3) -> Expr_if(process e1, process e2, process e3) in process e
88b339c6556ba7304bd0e88b7c5d4934bf36743b4ba8b2f26a10f4375fe0b798
grapesmoker/cl-sfml
shape.lisp
(in-package :sfml) SFML implements shapes in a really bizarre way . It asks for you ;; to pass it a callback which it can call upon initialization ;; to get the number of points, followed by a callback which can ;; get a specific point, followed by the actual data of the points. ;; So for now I'm not going to implement the interface to drawing ;; arbitrary shapes, which are likely of limited utility anyway. ;; Still create the top-level class for the shape hierarchy though. ;; Override the accessors for the scale, position, rotation, and origin ;; for semantic convenience. (defclass shape (entity) ((pointer :initarg :pointer :initform nil :accessor shape-pointer) (changed-slots :initform '() :accessor shape-changed-slots) ;; type should be one of :convex-shape, :rectangle, or :circle (type :initarg :type :initform nil :accessor shape-type) ;; origin should store a vector (origin :accessor shape-origin) ;; position should store a vector (position :accessor shape-position) (rotation :accessor shape-rotation) (scale :accessor shape-scale) (size :accessor shape-size) (texture :accessor shape-texture) (texture-rect :accessor shape-texture-rect) (point-count :accessor shape-point-count) ;; bounding boxes are rect classes (local-bbox :reader shape-local-bbox) (global-bbox :reader shape-global-bbox) ;; this should store a color class (fill-color :initarg :fill-color :initform (make-color) :accessor shape-fill-color) (outline-color :initarg :outline-color :initform (make-color) :accessor shape-outline-color) (outline-thickness :initarg :outline-thickness :initform nil :accessor shape-outline-thickness)))
null
https://raw.githubusercontent.com/grapesmoker/cl-sfml/3e587b431bbdd23dde2d0031f979d859ac436bca/graphics/shape.lisp
lisp
to pass it a callback which it can call upon initialization to get the number of points, followed by a callback which can get a specific point, followed by the actual data of the points. So for now I'm not going to implement the interface to drawing arbitrary shapes, which are likely of limited utility anyway. Still create the top-level class for the shape hierarchy though. Override the accessors for the scale, position, rotation, and origin for semantic convenience. type should be one of :convex-shape, :rectangle, or :circle origin should store a vector position should store a vector bounding boxes are rect classes this should store a color class
(in-package :sfml) SFML implements shapes in a really bizarre way . It asks for you (defclass shape (entity) ((pointer :initarg :pointer :initform nil :accessor shape-pointer) (changed-slots :initform '() :accessor shape-changed-slots) (type :initarg :type :initform nil :accessor shape-type) (origin :accessor shape-origin) (position :accessor shape-position) (rotation :accessor shape-rotation) (scale :accessor shape-scale) (size :accessor shape-size) (texture :accessor shape-texture) (texture-rect :accessor shape-texture-rect) (point-count :accessor shape-point-count) (local-bbox :reader shape-local-bbox) (global-bbox :reader shape-global-bbox) (fill-color :initarg :fill-color :initform (make-color) :accessor shape-fill-color) (outline-color :initarg :outline-color :initform (make-color) :accessor shape-outline-color) (outline-thickness :initarg :outline-thickness :initform nil :accessor shape-outline-thickness)))
b5cf97eacecebc4d7e8867b941cda7c82b6f32c73ec47c26e73840ee6fac3c9a
joshvera/effects
Resumable.hs
# LANGUAGE DataKinds , FlexibleContexts , GADTs , LambdaCase , KindSignatures , Rank2Types , TypeOperators # module Control.Monad.Effect.Resumable ( Resumable(..) , SomeExc(..) , throwResumable , runResumable , runResumableWith ) where import Control.DeepSeq import Control.Monad.Effect.Internal import Data.Functor.Classes newtype Resumable exc (m :: * -> *) a = Resumable (exc a) throwResumable :: (Member (Resumable exc) e, Effectful m) => exc v -> m e v throwResumable = send . Resumable runResumable :: (Effectful m, Effects e) => m (Resumable exc ': e) a -> m e (Either (SomeExc exc) a) runResumable = raiseHandler go where go (Return a) = pure (Right a) go (Effect (Resumable e) _) = pure (Left (SomeExc e)) go (Other u k) = liftStatefulHandler (Right ()) (either (pure . Left) runResumable) u k | Run a ' ' effect in an ' Effectful ' context , using a handler to resume computation . runResumableWith :: (Effectful m, PureEffects effects) => (forall resume . exc resume -> m effects resume) -> m (Resumable exc ': effects) a -> m effects a runResumableWith handler = interpret (\ (Resumable e) -> handler e) data SomeExc exc where SomeExc :: exc v -> SomeExc exc instance Eq1 exc => Eq (SomeExc exc) where SomeExc exc1 == SomeExc exc2 = liftEq (const (const True)) exc1 exc2 instance (Show1 exc) => Show (SomeExc exc) where showsPrec num (SomeExc exc) = liftShowsPrec (const (const id)) (const id) num exc instance NFData1 exc => NFData (SomeExc exc) where rnf (SomeExc exc) = liftRnf (\a -> seq a ()) exc instance PureEffect (Resumable exc) instance Effect (Resumable exc) where handleState c dist (Request (Resumable exc) k) = Request (Resumable exc) (dist . (<$ c) . k)
null
https://raw.githubusercontent.com/joshvera/effects/b2693454131dc7c00d2cf45bea69c17b986f0ea5/src/Control/Monad/Effect/Resumable.hs
haskell
# LANGUAGE DataKinds , FlexibleContexts , GADTs , LambdaCase , KindSignatures , Rank2Types , TypeOperators # module Control.Monad.Effect.Resumable ( Resumable(..) , SomeExc(..) , throwResumable , runResumable , runResumableWith ) where import Control.DeepSeq import Control.Monad.Effect.Internal import Data.Functor.Classes newtype Resumable exc (m :: * -> *) a = Resumable (exc a) throwResumable :: (Member (Resumable exc) e, Effectful m) => exc v -> m e v throwResumable = send . Resumable runResumable :: (Effectful m, Effects e) => m (Resumable exc ': e) a -> m e (Either (SomeExc exc) a) runResumable = raiseHandler go where go (Return a) = pure (Right a) go (Effect (Resumable e) _) = pure (Left (SomeExc e)) go (Other u k) = liftStatefulHandler (Right ()) (either (pure . Left) runResumable) u k | Run a ' ' effect in an ' Effectful ' context , using a handler to resume computation . runResumableWith :: (Effectful m, PureEffects effects) => (forall resume . exc resume -> m effects resume) -> m (Resumable exc ': effects) a -> m effects a runResumableWith handler = interpret (\ (Resumable e) -> handler e) data SomeExc exc where SomeExc :: exc v -> SomeExc exc instance Eq1 exc => Eq (SomeExc exc) where SomeExc exc1 == SomeExc exc2 = liftEq (const (const True)) exc1 exc2 instance (Show1 exc) => Show (SomeExc exc) where showsPrec num (SomeExc exc) = liftShowsPrec (const (const id)) (const id) num exc instance NFData1 exc => NFData (SomeExc exc) where rnf (SomeExc exc) = liftRnf (\a -> seq a ()) exc instance PureEffect (Resumable exc) instance Effect (Resumable exc) where handleState c dist (Request (Resumable exc) k) = Request (Resumable exc) (dist . (<$ c) . k)
b2b0df5147827026e934720ef05f06933accb195885fff1cda61007bb5c3fb22
parapluu/Concuerror
system_instant_delivery.erl
-module(system_instant_delivery). -compile(export_all). -concuerror_options_forced([{instant_delivery, true}]). %%------------------------------------------------------------------------------ scenarios() -> [ test ]. %%------------------------------------------------------------------------------ %% This test checks that replies from io server can be instant. test() -> Fun = fun() -> User = erlang:group_leader(), M = erlang:monitor(process, User), P = self(), Command = {put_chars, unicode, io_lib, format, ["Hello world!", []]}, Request = {io_request, P, M, Command}, User ! Request, receive {io_reply, M, ok} -> ok after 0 -> receive {io_reply, M, ok} -> ok end end, demonitor(M, [flush]), spawn(fun() -> P ! ok end), receive ok -> ok after 0 -> ok end end, spawn(Fun), exit(died_to_show_trace).
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/basic_tests/src/system_instant_delivery.erl
erlang
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ This test checks that replies from io server can be instant.
-module(system_instant_delivery). -compile(export_all). -concuerror_options_forced([{instant_delivery, true}]). scenarios() -> [ test ]. test() -> Fun = fun() -> User = erlang:group_leader(), M = erlang:monitor(process, User), P = self(), Command = {put_chars, unicode, io_lib, format, ["Hello world!", []]}, Request = {io_request, P, M, Command}, User ! Request, receive {io_reply, M, ok} -> ok after 0 -> receive {io_reply, M, ok} -> ok end end, demonitor(M, [flush]), spawn(fun() -> P ! ok end), receive ok -> ok after 0 -> ok end end, spawn(Fun), exit(died_to_show_trace).
1b299e1b4ea81ecb07f7df3e38058187bd3d7ff51ab6f24dc5a2790c0758075b
mvaldesdeleon/aoc18
Day25.hs
# LANGUAGE TemplateHaskell # module Day25 ( day25 ) where import Control.Lens import Data.List ((\\)) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) import qualified Data.Set as S import Paths_aoc18 (getDataFileName) import Text.Parsec (Parsec, char, digit, many1, newline, option, parse, sepBy1) data Point = Point { _x :: Integer , _y :: Integer , _z :: Integer , _t :: Integer } deriving (Show, Eq, Ord) makeLenses ''Point distance :: Point -> Point -> Integer distance pa pb = abs (pb ^. x - pa ^. x) + abs (pb ^. y - pa ^. y) + abs (pb ^. z - pa ^. z) + abs (pb ^. t - pa ^. t) parsePoint :: Parsec String () Point parsePoint = Point <$> number <* char ',' <*> number <* char ',' <*> number <* char ',' <*> number where number = read <$> ((:) <$> option ' ' (char '-') <*> many1 digit) parseInput :: String -> [Point] parseInput input = case parse (parsePoint `sepBy1` newline) "" input of Left e -> error $ show e Right ps -> ps loadInput :: IO String loadInput = getDataFileName "inputs/day-25.txt" >>= readFile type Graph = M.Map Point [Point] constellations :: [Point] -> [[Point]] constellations ps = buildConstellations [] (S.fromList ps) where graph = foldl addPoint M.empty ps addPoint gr p = foldl (addNeighbor p) gr ps addNeighbor p gr np = if distance p np <= 3 then M.insertWith (++) p [np] gr else gr buildConstellations :: [[Point]] -> S.Set Point -> [[Point]] buildConstellations cs s = if S.null s then cs else let c = nextConstellation s in buildConstellations (c : cs) (S.difference s (S.fromList c)) nextConstellation :: S.Set Point -> [Point] nextConstellation s = let p = S.findMin s in bfs [] [p] bfs :: [Point] -> [Point] -> [Point] bfs rs st = if null st then rs else let (s:ss) = st in bfs (s : rs) (ss ++ (fromMaybe [] (s `M.lookup` graph) \\ rs)) day25 :: IO () day25 = do input <- parseInput <$> loadInput print $ length . constellations $ input
null
https://raw.githubusercontent.com/mvaldesdeleon/aoc18/1a6f6de7c482e5de264360e36f97a3c7487e2457/src/Day25.hs
haskell
# LANGUAGE TemplateHaskell # module Day25 ( day25 ) where import Control.Lens import Data.List ((\\)) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) import qualified Data.Set as S import Paths_aoc18 (getDataFileName) import Text.Parsec (Parsec, char, digit, many1, newline, option, parse, sepBy1) data Point = Point { _x :: Integer , _y :: Integer , _z :: Integer , _t :: Integer } deriving (Show, Eq, Ord) makeLenses ''Point distance :: Point -> Point -> Integer distance pa pb = abs (pb ^. x - pa ^. x) + abs (pb ^. y - pa ^. y) + abs (pb ^. z - pa ^. z) + abs (pb ^. t - pa ^. t) parsePoint :: Parsec String () Point parsePoint = Point <$> number <* char ',' <*> number <* char ',' <*> number <* char ',' <*> number where number = read <$> ((:) <$> option ' ' (char '-') <*> many1 digit) parseInput :: String -> [Point] parseInput input = case parse (parsePoint `sepBy1` newline) "" input of Left e -> error $ show e Right ps -> ps loadInput :: IO String loadInput = getDataFileName "inputs/day-25.txt" >>= readFile type Graph = M.Map Point [Point] constellations :: [Point] -> [[Point]] constellations ps = buildConstellations [] (S.fromList ps) where graph = foldl addPoint M.empty ps addPoint gr p = foldl (addNeighbor p) gr ps addNeighbor p gr np = if distance p np <= 3 then M.insertWith (++) p [np] gr else gr buildConstellations :: [[Point]] -> S.Set Point -> [[Point]] buildConstellations cs s = if S.null s then cs else let c = nextConstellation s in buildConstellations (c : cs) (S.difference s (S.fromList c)) nextConstellation :: S.Set Point -> [Point] nextConstellation s = let p = S.findMin s in bfs [] [p] bfs :: [Point] -> [Point] -> [Point] bfs rs st = if null st then rs else let (s:ss) = st in bfs (s : rs) (ss ++ (fromMaybe [] (s `M.lookup` graph) \\ rs)) day25 :: IO () day25 = do input <- parseInput <$> loadInput print $ length . constellations $ input
44539d6edf2192a1e41783a486f545a46f4726c2468fbd95cbdfd2df339b0bed
pavlobaron/ErlangOTPBookSamples
strict.erl
-module(strict). -export([strict_eval/1, print/0]). print() -> io:format("I have been called, but what for?.."). strict_eval(X) -> 5.
null
https://raw.githubusercontent.com/pavlobaron/ErlangOTPBookSamples/50094964ad814932760174914490e49618b2b8c2/sprache/strict.erl
erlang
-module(strict). -export([strict_eval/1, print/0]). print() -> io:format("I have been called, but what for?.."). strict_eval(X) -> 5.
87283845a6aa94d706bff027c20de7d717ed1a49a3883606573dc4a52e8e03df
swarmpit/swarmpit
outbound.clj
(ns swarmpit.docker.engine.mapper.outbound "Map swarmpit domain to docker domain" (:require [clojure.string :as str] [swarmpit.docker.engine.mapper.inbound :as mi] [swarmpit.utils :refer [name-value->map ->nano as-bytes]])) (defn ->auth-config "Pass registry or dockeruser entity" [auth-entity] (when (some? auth-entity) {:username (:username auth-entity) :password (:password auth-entity) :serveraddress (:url auth-entity)})) (defn ->service-mode [service] (if (= (:mode service) "global") {:Global {}} {:Replicated {:Replicas (:replicas service)}})) (defn ->service-ports [service] (->> (:ports service) (filter #(and (some? (:containerPort %)) (some? (:hostPort %)) (> (:containerPort %) 0) (> (:hostPort %) 0))) (map (fn [p] {:Protocol (:protocol p) :PublishMode (:mode p) :PublishedPort (:hostPort p) :TargetPort (:containerPort p)})) (into []))) (defn- ->service-networks [service] (->> (:networks service) (map #(hash-map :Target (:networkName %) :Aliases (:serviceAliases %))) (into []))) (defn ->service-hosts [service] (->> (:hosts service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:value p) " " (:name p)))) (into []))) (defn ->service-variables [service] (->> (:variables service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:name p) "=" (:value p)))) (into []))) (defn ->service-labels [service] (->> (:labels service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-container-labels [service] (->> (:containerLabels service) (name-value->map))) (defn ->service-log-options [service] (->> (get-in service [:logdriver :opts]) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-volume-options [service-volume] (when (some? service-volume) {:Labels (:labels service-volume) :DriverConfig {:Name (get-in service-volume [:driver :name]) :Options (name-value->map (get-in service-volume [:driver :options]))}})) (defn ->service-mounts [service] (->> (:mounts service) (map (fn [v] {:ReadOnly (:readOnly v) :Source (:host v) :Target (:containerPath v) :Type (:type v) :VolumeOptions (->service-volume-options (:volumeOptions v))})) (into []))) (defn- ->service-placement-contraints [service] (->> (get-in service [:deployment :placement]) (map (fn [p] (:rule p))) (into []))) (defn- ->secret-id [secret-name secrets] (->> secrets (filter #(= secret-name (:secretName %))) (first) :id)) (defn ->secret-target [secret] (let [secret-target (:secretTarget secret)] (if (str/blank? secret-target) (:secretName secret) secret-target))) (defn ->service-secrets [service secrets] (->> (:secrets service) (map (fn [s] {:SecretName (:secretName s) :SecretID (->secret-id (:secretName s) secrets) :File {:GID "0" :Mode 292 :Name (->secret-target s) :UID "0"}})) (into []))) (defn- ->config-id [config-name configs] (->> configs (filter #(= config-name (:configName %))) (first) :id)) (defn ->config-target [config] (let [config-target (:configTarget config)] (if (str/blank? config-target) (:configName config) config-target))) (defn ->service-configs [service configs] (->> (:configs service) (map (fn [c] {:ConfigName (:configName c) :ConfigID (->config-id (:configName c) configs) :File {:GID "0" :Mode 292 :Name (->config-target c) :UID "0"}})) (into []))) (defn ->service-resource [service-resource] (let [cpu (:cpu service-resource) memory (:memory service-resource)] {:NanoCPUs (when (some? cpu) (-> cpu (->nano) (long))) :MemoryBytes (when (some? memory) (as-bytes memory))})) (defn ->service-update-config [service] (let [update (get-in service [:deployment :update])] {:Parallelism (:parallelism update) :Delay (->nano (:delay update)) :Order (:order update) :FailureAction (:failureAction update)})) (defn ->service-rollback-config [service] (let [rollback (get-in service [:deployment :rollback])] {:Parallelism (:parallelism rollback) :Delay (->nano (:delay rollback)) :Order (:order rollback) :FailureAction (:failureAction rollback)})) (defn ->service-restart-policy [service] (let [policy (get-in service [:deployment :restartPolicy])] {:Condition (:condition policy) :Delay (->nano (:delay policy)) :Window (->nano (:window policy)) :MaxAttempts (:attempts policy)})) (defn ->service-healthcheck [service-healthcheck] (when service-healthcheck {:Test (:test service-healthcheck) :Interval (->nano (:interval service-healthcheck)) :Timeout (->nano (:timeout service-healthcheck)) :Retries (:retries service-healthcheck)})) (defn ->service-image [service digest?] (let [repository (get-in service [:repository :name]) tag (get-in service [:repository :tag]) digest (get-in service [:repository :imageDigest])] (if digest? (str repository ":" tag "@" digest) (str repository ":" tag)))) (defn ->service-links [service] (->> (:links service) (map #(hash-map (keyword (str mi/link-label (:name %))) (:value %))) (into {}))) (defn ->service-metadata [service image] (let [autoredeploy (get-in service [:deployment :autoredeploy]) agent (:agent service) stack (:stack service) immutable (:immutable service) links (:links service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack :com.docker.stack.image image}) (when (some? autoredeploy) {mi/autoredeploy-label (str autoredeploy)}) (when (some? agent) {mi/agent-label (str agent)}) (when (some? immutable) {mi/immutable-label (str immutable)}) (when (not-empty links) (->service-links service))))) (defn ->service-container-metadata [service] (let [stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack})))) (defn ->service [service] {:Name (:serviceName service) :Labels (merge (->service-labels service) (->service-metadata service (->service-image service false))) :TaskTemplate {:ContainerSpec {:Image (->service-image service true) :Labels (merge (->service-container-labels service) (->service-container-metadata service)) :Mounts (->service-mounts service) :Secrets (:secrets service) :Configs (:configs service) :Args (:command service) :TTY (:tty service) :Healthcheck (->service-healthcheck (:healthcheck service)) :Env (->service-variables service) :Hosts (->service-hosts service)} :LogDriver {:Name (get-in service [:logdriver :name]) :Options (->service-log-options service)} :Resources {:Limits (->service-resource (get-in service [:resources :limit])) :Reservations (->service-resource (get-in service [:resources :reservation]))} :RestartPolicy (->service-restart-policy service) :Placement {:Constraints (->service-placement-contraints service)} :ForceUpdate (get-in service [:deployment :forceUpdate]) :Networks (->service-networks service)} :Mode (->service-mode service) :UpdateConfig (->service-update-config service) :RollbackConfig (->service-rollback-config service) :EndpointSpec {:Ports (->service-ports service)}}) (defn ->network-ipam-config [network] (let [ipam (:ipam network) gateway (:gateway ipam) subnet (:subnet ipam)] (if (not (str/blank? subnet)) {:Config [{:Subnet subnet :Gateway gateway}]} {:Config []}))) (defn ->network [network] {:Name (:networkName network) :Driver (:driver network) :Internal (:internal network) :Options (name-value->map (:options network)) :Attachable (:attachable network) :Ingress (:ingress network) :EnableIPv6 (:enableIPv6 network) :IPAM (merge {:Driver "default"} (->network-ipam-config network))}) (defn ->volume [volume] {:Name (:volumeName volume) :Driver (:driver volume) :DriverOpts (name-value->map (:options volume)) :Labels (:labels volume)}) (defn ->secret [secret] {:Name (:secretName secret) :Data (:data secret)}) (defn ->config [config] {:Name (:configName config) :Data (:data config)}) (defn ->node [node] {:Availability (:availability node) :Role (:role node) :Labels (name-value->map (:labels node))})
null
https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/clj/swarmpit/docker/engine/mapper/outbound.clj
clojure
(ns swarmpit.docker.engine.mapper.outbound "Map swarmpit domain to docker domain" (:require [clojure.string :as str] [swarmpit.docker.engine.mapper.inbound :as mi] [swarmpit.utils :refer [name-value->map ->nano as-bytes]])) (defn ->auth-config "Pass registry or dockeruser entity" [auth-entity] (when (some? auth-entity) {:username (:username auth-entity) :password (:password auth-entity) :serveraddress (:url auth-entity)})) (defn ->service-mode [service] (if (= (:mode service) "global") {:Global {}} {:Replicated {:Replicas (:replicas service)}})) (defn ->service-ports [service] (->> (:ports service) (filter #(and (some? (:containerPort %)) (some? (:hostPort %)) (> (:containerPort %) 0) (> (:hostPort %) 0))) (map (fn [p] {:Protocol (:protocol p) :PublishMode (:mode p) :PublishedPort (:hostPort p) :TargetPort (:containerPort p)})) (into []))) (defn- ->service-networks [service] (->> (:networks service) (map #(hash-map :Target (:networkName %) :Aliases (:serviceAliases %))) (into []))) (defn ->service-hosts [service] (->> (:hosts service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:value p) " " (:name p)))) (into []))) (defn ->service-variables [service] (->> (:variables service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:name p) "=" (:value p)))) (into []))) (defn ->service-labels [service] (->> (:labels service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-container-labels [service] (->> (:containerLabels service) (name-value->map))) (defn ->service-log-options [service] (->> (get-in service [:logdriver :opts]) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-volume-options [service-volume] (when (some? service-volume) {:Labels (:labels service-volume) :DriverConfig {:Name (get-in service-volume [:driver :name]) :Options (name-value->map (get-in service-volume [:driver :options]))}})) (defn ->service-mounts [service] (->> (:mounts service) (map (fn [v] {:ReadOnly (:readOnly v) :Source (:host v) :Target (:containerPath v) :Type (:type v) :VolumeOptions (->service-volume-options (:volumeOptions v))})) (into []))) (defn- ->service-placement-contraints [service] (->> (get-in service [:deployment :placement]) (map (fn [p] (:rule p))) (into []))) (defn- ->secret-id [secret-name secrets] (->> secrets (filter #(= secret-name (:secretName %))) (first) :id)) (defn ->secret-target [secret] (let [secret-target (:secretTarget secret)] (if (str/blank? secret-target) (:secretName secret) secret-target))) (defn ->service-secrets [service secrets] (->> (:secrets service) (map (fn [s] {:SecretName (:secretName s) :SecretID (->secret-id (:secretName s) secrets) :File {:GID "0" :Mode 292 :Name (->secret-target s) :UID "0"}})) (into []))) (defn- ->config-id [config-name configs] (->> configs (filter #(= config-name (:configName %))) (first) :id)) (defn ->config-target [config] (let [config-target (:configTarget config)] (if (str/blank? config-target) (:configName config) config-target))) (defn ->service-configs [service configs] (->> (:configs service) (map (fn [c] {:ConfigName (:configName c) :ConfigID (->config-id (:configName c) configs) :File {:GID "0" :Mode 292 :Name (->config-target c) :UID "0"}})) (into []))) (defn ->service-resource [service-resource] (let [cpu (:cpu service-resource) memory (:memory service-resource)] {:NanoCPUs (when (some? cpu) (-> cpu (->nano) (long))) :MemoryBytes (when (some? memory) (as-bytes memory))})) (defn ->service-update-config [service] (let [update (get-in service [:deployment :update])] {:Parallelism (:parallelism update) :Delay (->nano (:delay update)) :Order (:order update) :FailureAction (:failureAction update)})) (defn ->service-rollback-config [service] (let [rollback (get-in service [:deployment :rollback])] {:Parallelism (:parallelism rollback) :Delay (->nano (:delay rollback)) :Order (:order rollback) :FailureAction (:failureAction rollback)})) (defn ->service-restart-policy [service] (let [policy (get-in service [:deployment :restartPolicy])] {:Condition (:condition policy) :Delay (->nano (:delay policy)) :Window (->nano (:window policy)) :MaxAttempts (:attempts policy)})) (defn ->service-healthcheck [service-healthcheck] (when service-healthcheck {:Test (:test service-healthcheck) :Interval (->nano (:interval service-healthcheck)) :Timeout (->nano (:timeout service-healthcheck)) :Retries (:retries service-healthcheck)})) (defn ->service-image [service digest?] (let [repository (get-in service [:repository :name]) tag (get-in service [:repository :tag]) digest (get-in service [:repository :imageDigest])] (if digest? (str repository ":" tag "@" digest) (str repository ":" tag)))) (defn ->service-links [service] (->> (:links service) (map #(hash-map (keyword (str mi/link-label (:name %))) (:value %))) (into {}))) (defn ->service-metadata [service image] (let [autoredeploy (get-in service [:deployment :autoredeploy]) agent (:agent service) stack (:stack service) immutable (:immutable service) links (:links service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack :com.docker.stack.image image}) (when (some? autoredeploy) {mi/autoredeploy-label (str autoredeploy)}) (when (some? agent) {mi/agent-label (str agent)}) (when (some? immutable) {mi/immutable-label (str immutable)}) (when (not-empty links) (->service-links service))))) (defn ->service-container-metadata [service] (let [stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack})))) (defn ->service [service] {:Name (:serviceName service) :Labels (merge (->service-labels service) (->service-metadata service (->service-image service false))) :TaskTemplate {:ContainerSpec {:Image (->service-image service true) :Labels (merge (->service-container-labels service) (->service-container-metadata service)) :Mounts (->service-mounts service) :Secrets (:secrets service) :Configs (:configs service) :Args (:command service) :TTY (:tty service) :Healthcheck (->service-healthcheck (:healthcheck service)) :Env (->service-variables service) :Hosts (->service-hosts service)} :LogDriver {:Name (get-in service [:logdriver :name]) :Options (->service-log-options service)} :Resources {:Limits (->service-resource (get-in service [:resources :limit])) :Reservations (->service-resource (get-in service [:resources :reservation]))} :RestartPolicy (->service-restart-policy service) :Placement {:Constraints (->service-placement-contraints service)} :ForceUpdate (get-in service [:deployment :forceUpdate]) :Networks (->service-networks service)} :Mode (->service-mode service) :UpdateConfig (->service-update-config service) :RollbackConfig (->service-rollback-config service) :EndpointSpec {:Ports (->service-ports service)}}) (defn ->network-ipam-config [network] (let [ipam (:ipam network) gateway (:gateway ipam) subnet (:subnet ipam)] (if (not (str/blank? subnet)) {:Config [{:Subnet subnet :Gateway gateway}]} {:Config []}))) (defn ->network [network] {:Name (:networkName network) :Driver (:driver network) :Internal (:internal network) :Options (name-value->map (:options network)) :Attachable (:attachable network) :Ingress (:ingress network) :EnableIPv6 (:enableIPv6 network) :IPAM (merge {:Driver "default"} (->network-ipam-config network))}) (defn ->volume [volume] {:Name (:volumeName volume) :Driver (:driver volume) :DriverOpts (name-value->map (:options volume)) :Labels (:labels volume)}) (defn ->secret [secret] {:Name (:secretName secret) :Data (:data secret)}) (defn ->config [config] {:Name (:configName config) :Data (:data config)}) (defn ->node [node] {:Availability (:availability node) :Role (:role node) :Labels (name-value->map (:labels node))})
635e62b081aac3059ab58e2665dfa2ff68b9659c510fcd072363dd250cf67677
cxphoe/SICP-solutions
3.7.rkt
(define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount))) (define (dispatch pw m) (if (eq? pw password) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m))) (lambda (x) "Incorrect password"))) dispatch) (define (make-joint acc pw new-pw) (let ((withdraw (acc pw 'withdraw)) (deposit (acc pw 'deposit))) (define (dispatch pw m) (cond ((not (eq? pw new-pw)) (lambda (x) "Incorrect Password")) ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-JOINT" m)))) (if (not (number? (withdraw 0))) (error "Incorrect password for jointed account" (list pw)) dispatch))) (define peter-acc (make-account 100 'open-sesame)) (define paul-acc (make-joint peter-acc 'open-sesame 'rosebud)) ((peter-acc 'open-sesame 'withdraw) 0) ((paul-acc 'open-seasame 'withdraw) 50) ((paul-acc 'rosebud 'withdraw) 50) ((peter-acc 'open-sesame 'withdraw) 0) (define bob-acc (make-joint peter-acc 'openingsesame 'rosebud))
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%203-Modeling%20with%20Mutable%20Data/1.Assignment%20and%20Local%20state/3.7.rkt
racket
(define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount))) (define (dispatch pw m) (if (eq? pw password) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-ACCOUNT" m))) (lambda (x) "Incorrect password"))) dispatch) (define (make-joint acc pw new-pw) (let ((withdraw (acc pw 'withdraw)) (deposit (acc pw 'deposit))) (define (dispatch pw m) (cond ((not (eq? pw new-pw)) (lambda (x) "Incorrect Password")) ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else (error "Unknown request -- MAKE-JOINT" m)))) (if (not (number? (withdraw 0))) (error "Incorrect password for jointed account" (list pw)) dispatch))) (define peter-acc (make-account 100 'open-sesame)) (define paul-acc (make-joint peter-acc 'open-sesame 'rosebud)) ((peter-acc 'open-sesame 'withdraw) 0) ((paul-acc 'open-seasame 'withdraw) 50) ((paul-acc 'rosebud 'withdraw) 50) ((peter-acc 'open-sesame 'withdraw) 0) (define bob-acc (make-joint peter-acc 'openingsesame 'rosebud))
63df0b843a76e28a8084d05b61ac4628c88d2256d47ee3d58c3fc9bd4880f279
mxmxyz/tidal-guiot
Boot.hs
module Sound.Tidal.Guiot.Boot (module B) where import Sound.Tidal.Guiot.Control as B import Sound.Tidal.Guiot.Functions as B import Sound.Tidal.Guiot.Rhythm as B import Sound.Tidal.Guiot.Scales as B import Sound.Tidal.Guiot.Utils as B
null
https://raw.githubusercontent.com/mxmxyz/tidal-guiot/eccea30a5cbef37cf0c4b1978fe65b99cce71bf7/src/Sound/Tidal/Guiot/Boot.hs
haskell
module Sound.Tidal.Guiot.Boot (module B) where import Sound.Tidal.Guiot.Control as B import Sound.Tidal.Guiot.Functions as B import Sound.Tidal.Guiot.Rhythm as B import Sound.Tidal.Guiot.Scales as B import Sound.Tidal.Guiot.Utils as B
1e5b72d658a2b00361f9e6bea3af3d6cf663b4906b42b9159d53d19b205c06ee
nyampass/conceit
csv.clj
(ns conceit.commons.test.csv (use conceit.commons.csv conceit.commons.test clojure.test)) (deftest* csv-value-test (= "\"foo\"" (csv-value "foo")) (= "\"abc\"" (csv-value :abc)) (= "\"HOGE\"" (csv-value 'HOGE)) (= "\"100\"" (csv-value 100)) (= "\"hello \"\"world\"\"!\"" (csv-value "hello \"world\"!")) (= "\"foo, bar\"" (csv-value "foo, bar")) (= "\"\"" (csv-value "")) (= "\"\"" (csv-value nil))) (deftest* csv-row-test (= "\"foo\",\"bar\"" (csv-row [:foo :bar])) (= "\"x\"" (csv-row ["x"])) (= "\"a,b\",\"c\"\"d\",\"efg\",\"10\"" (csv-row ["a,b" "c\"d" "efg" 10])) (= "\"x\",\"\"" (csv-row ["x" ""])) (= "" (csv-row []))) (deftest* csv-rows-test (= "\"foo\",\"bar\"\r\n\"abc\",\"def\"\r\n" (csv-rows [[:foo :bar] ["abc" "def"]])) (= "\"name\",\"age\",\"note\"\r\n\"John\",\"24\",\"foo\"\"bar\"\r\n\"James\",\"30\",\"aaa,bbb,ccc\"\r\n" (csv-rows [[:name :age :note] ["John" 24 "foo\"bar"] ["James" 30 "aaa,bbb,ccc"]])) (= "\r\n\r\n" (csv-rows [[] []])) (= "" (csv-rows []))) (deftest* csv-row-by-map-test (= "\"John\",\"24\",\"foo\"\"bar\"" (csv-row-by-map {:name "John" :age 24 :note "foo\"bar"} [:name :age :note])) (= "\"a\"" (csv-row-by-map {:name :a :value 10} [:name])) (= "" (csv-row-by-map {:name :foo} []))) (deftest* csv-rows-by-maps-test (= "\"John\",\"24\",\"foo\"\"bar\"\r\n\"James\",\"30\",\"aaa,bbb,ccc\"\r\n" (csv-rows-by-maps [{:name "John" :age 24 :note "foo\"bar"} {:name "James" :age 30 :note "aaa,bbb,ccc"}] [:name :age :note])) (= "\"a\"\r\n\"b\"\r\n\"c\"\r\n" (csv-rows-by-maps [{:name :a :value 10} {:name :b :value 20} {:name :c :value 30}] [:name])) (= "\r\n\r\n" (csv-rows-by-maps [{:name :foo} {:name :bar}] [])) (= "" (csv-rows-by-maps [] [:name :age]))) ;; (run-tests)
null
https://raw.githubusercontent.com/nyampass/conceit/2b8ba8cc3d732fe2f58d320e2aa4ecdd6f3f3be5/conceit-commons/test/conceit/commons/test/csv.clj
clojure
(run-tests)
(ns conceit.commons.test.csv (use conceit.commons.csv conceit.commons.test clojure.test)) (deftest* csv-value-test (= "\"foo\"" (csv-value "foo")) (= "\"abc\"" (csv-value :abc)) (= "\"HOGE\"" (csv-value 'HOGE)) (= "\"100\"" (csv-value 100)) (= "\"hello \"\"world\"\"!\"" (csv-value "hello \"world\"!")) (= "\"foo, bar\"" (csv-value "foo, bar")) (= "\"\"" (csv-value "")) (= "\"\"" (csv-value nil))) (deftest* csv-row-test (= "\"foo\",\"bar\"" (csv-row [:foo :bar])) (= "\"x\"" (csv-row ["x"])) (= "\"a,b\",\"c\"\"d\",\"efg\",\"10\"" (csv-row ["a,b" "c\"d" "efg" 10])) (= "\"x\",\"\"" (csv-row ["x" ""])) (= "" (csv-row []))) (deftest* csv-rows-test (= "\"foo\",\"bar\"\r\n\"abc\",\"def\"\r\n" (csv-rows [[:foo :bar] ["abc" "def"]])) (= "\"name\",\"age\",\"note\"\r\n\"John\",\"24\",\"foo\"\"bar\"\r\n\"James\",\"30\",\"aaa,bbb,ccc\"\r\n" (csv-rows [[:name :age :note] ["John" 24 "foo\"bar"] ["James" 30 "aaa,bbb,ccc"]])) (= "\r\n\r\n" (csv-rows [[] []])) (= "" (csv-rows []))) (deftest* csv-row-by-map-test (= "\"John\",\"24\",\"foo\"\"bar\"" (csv-row-by-map {:name "John" :age 24 :note "foo\"bar"} [:name :age :note])) (= "\"a\"" (csv-row-by-map {:name :a :value 10} [:name])) (= "" (csv-row-by-map {:name :foo} []))) (deftest* csv-rows-by-maps-test (= "\"John\",\"24\",\"foo\"\"bar\"\r\n\"James\",\"30\",\"aaa,bbb,ccc\"\r\n" (csv-rows-by-maps [{:name "John" :age 24 :note "foo\"bar"} {:name "James" :age 30 :note "aaa,bbb,ccc"}] [:name :age :note])) (= "\"a\"\r\n\"b\"\r\n\"c\"\r\n" (csv-rows-by-maps [{:name :a :value 10} {:name :b :value 20} {:name :c :value 30}] [:name])) (= "\r\n\r\n" (csv-rows-by-maps [{:name :foo} {:name :bar}] [])) (= "" (csv-rows-by-maps [] [:name :age])))
510b9d99e52fe4b2e438e9d62ae495e4d4a7f7cf5fd69467031f74ddf62ea3c9
nomnom-insights/nomnom.lockjaw
util.clj
(ns lockjaw.util (:import (java.util.zip CRC32))) (defn name-to-id "Converts a string to an int" [name] (let [bytes (.getBytes ^String name "UTF-8") crc (new CRC32)] (.update ^CRC32 crc bytes) (.getValue ^CRC32 crc)))
null
https://raw.githubusercontent.com/nomnom-insights/nomnom.lockjaw/2adc9d39d1b565c639248101114beac2bc2faa94/src/lockjaw/util.clj
clojure
(ns lockjaw.util (:import (java.util.zip CRC32))) (defn name-to-id "Converts a string to an int" [name] (let [bytes (.getBytes ^String name "UTF-8") crc (new CRC32)] (.update ^CRC32 crc bytes) (.getValue ^CRC32 crc)))
b02494ae8e877e031a72beced9119ebc6fd7ece272821623b84920cfdee1b856
google/codeworld
prediction.hs
Copyright 2020 The CodeWorld Authors . 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 . Copyright 2020 The CodeWorld Authors. 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. -} import CodeWorld.Prediction import Data.Bifunctor import qualified Data.IntMap as IM import Data.List import qualified Data.Map as M import System.Exit import Test.QuickCheck import Common type EventsDone = ([TimeStamp], IM.IntMap [TEvent]) type LogEntry = Either Double Event type Log = [LogEntry] type Check = (EventsDone, Either Double (Int, TEvent)) type CheckReport = (Check, Future Log, Future Log, Future Log) -- Fake state and handle functions step :: Double -> Log -> Log step dt = (Left dt :) handle :: Event -> Log -> Log handle dt = (Right dt :) -- Global constant rate :: Double rate = 1 / 4 -- decimal display -- Generation of random schedules -- The actual check: -- Exhaustively search the order in which these events could happen Memoize every initial segment -- Ensure that all possible ways reach the same conclusion. failedChecks :: EventSchedule -> [CheckReport] failedChecks schedule = map mkReport $ filter (not . check) allChecks where allDone :: [EventsDone] allDone = do let (tss, em) = schedule tss' <- inits tss em' <- traverse inits em -- wow! return (tss', em') allChecks :: [Check] allChecks = allDone >>= prevs prevs :: EventsDone -> [Check] prevs (tss, m) = [((init tss, m), Left (last tss)) | not (null tss)] ++ [ ((tss, IM.adjust init i m), Right (i, last done)) | i <- IM.keys m , let done = m IM.! i , not (null done) ] memo :: M.Map EventsDone (Future Log) memo = M.fromList [(eventsDone, recreate eventsDone) | eventsDone <- allDone] recreate :: EventsDone -> Future Log recreate m = case prevs m of [] -> initFuture [] (IM.size (snd m)) (c:_) -> checkActual c check :: Check -> Bool check c = checkActual c `eqFuture` checkExpected c checkExpected :: Check -> Future Log checkExpected (prev, Left t) = memo M.! first (++ [t]) prev checkExpected (prev, Right (p, (t, e))) = memo M.! second (IM.adjust (++ [(t, e)]) p) prev checkActual :: Check -> Future Log checkActual (prev, Left t) = currentTimePasses step rate t $ memo M.! prev checkActual (prev, Right (p, (t, e))) = addEvent step rate p t (handle <$> e) $ memo M.! prev mkReport :: Check -> CheckReport mkReport c = (c, memo M.! fst c, checkExpected c, checkActual c) -- The quickcheck test, with reporting testPrediction :: Property testPrediction = forAllSchedules $ \schedule -> let failed = failedChecks schedule in reportFailedCheck (head failed) `whenFail` null failed reportFailedCheck :: CheckReport -> IO () reportFailedCheck (c, before, expected, actual) = do putStrLn "Failed Check" putStrLn "History:" putStr $ showHistory (fst c) putStrLn "Event:" print (snd c) putStrLn "Before:" printInternalState showLog before putStrLn "Expected:" printInternalState showLog expected putStrLn "Actual:" printInternalState showLog actual putStrLn "" showHistory :: EventsDone -> String showHistory (tss, m) = unlines $ ("Queried at: " ++ intercalate " " (map show tss)) : map go (IM.toList m) where go (p, tes) = "Player " ++ show p ++ ": " ++ intercalate " " (map ste tes) ste (t, Nothing) = show t ste (t, Just e) = show e ++ "@" ++ show t showLog :: Log -> String showLog l = intercalate " " (map sle (reverse l)) where sle (Left x) = show x sle (Right x) = "[" ++ show x ++ "]" -- The main entry point. Set the exit code to please . main :: IO () main = do res <- quickCheckWithResult args testPrediction case res of Success {} -> exitSuccess _ -> exitFailure where args = stdArgs {maxSize = 30} -- more gets too large
null
https://raw.githubusercontent.com/google/codeworld/77b0863075be12e3bc5f182a53fcc38b038c3e16/codeworld-prediction/tests/prediction.hs
haskell
Fake state and handle functions Global constant decimal display Generation of random schedules The actual check: Exhaustively search the order in which these events could happen Ensure that all possible ways reach the same conclusion. wow! The quickcheck test, with reporting The main entry point. more gets too large
Copyright 2020 The CodeWorld Authors . 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 . Copyright 2020 The CodeWorld Authors. 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. -} import CodeWorld.Prediction import Data.Bifunctor import qualified Data.IntMap as IM import Data.List import qualified Data.Map as M import System.Exit import Test.QuickCheck import Common type EventsDone = ([TimeStamp], IM.IntMap [TEvent]) type LogEntry = Either Double Event type Log = [LogEntry] type Check = (EventsDone, Either Double (Int, TEvent)) type CheckReport = (Check, Future Log, Future Log, Future Log) step :: Double -> Log -> Log step dt = (Left dt :) handle :: Event -> Log -> Log handle dt = (Right dt :) rate :: Double Memoize every initial segment failedChecks :: EventSchedule -> [CheckReport] failedChecks schedule = map mkReport $ filter (not . check) allChecks where allDone :: [EventsDone] allDone = do let (tss, em) = schedule tss' <- inits tss return (tss', em') allChecks :: [Check] allChecks = allDone >>= prevs prevs :: EventsDone -> [Check] prevs (tss, m) = [((init tss, m), Left (last tss)) | not (null tss)] ++ [ ((tss, IM.adjust init i m), Right (i, last done)) | i <- IM.keys m , let done = m IM.! i , not (null done) ] memo :: M.Map EventsDone (Future Log) memo = M.fromList [(eventsDone, recreate eventsDone) | eventsDone <- allDone] recreate :: EventsDone -> Future Log recreate m = case prevs m of [] -> initFuture [] (IM.size (snd m)) (c:_) -> checkActual c check :: Check -> Bool check c = checkActual c `eqFuture` checkExpected c checkExpected :: Check -> Future Log checkExpected (prev, Left t) = memo M.! first (++ [t]) prev checkExpected (prev, Right (p, (t, e))) = memo M.! second (IM.adjust (++ [(t, e)]) p) prev checkActual :: Check -> Future Log checkActual (prev, Left t) = currentTimePasses step rate t $ memo M.! prev checkActual (prev, Right (p, (t, e))) = addEvent step rate p t (handle <$> e) $ memo M.! prev mkReport :: Check -> CheckReport mkReport c = (c, memo M.! fst c, checkExpected c, checkActual c) testPrediction :: Property testPrediction = forAllSchedules $ \schedule -> let failed = failedChecks schedule in reportFailedCheck (head failed) `whenFail` null failed reportFailedCheck :: CheckReport -> IO () reportFailedCheck (c, before, expected, actual) = do putStrLn "Failed Check" putStrLn "History:" putStr $ showHistory (fst c) putStrLn "Event:" print (snd c) putStrLn "Before:" printInternalState showLog before putStrLn "Expected:" printInternalState showLog expected putStrLn "Actual:" printInternalState showLog actual putStrLn "" showHistory :: EventsDone -> String showHistory (tss, m) = unlines $ ("Queried at: " ++ intercalate " " (map show tss)) : map go (IM.toList m) where go (p, tes) = "Player " ++ show p ++ ": " ++ intercalate " " (map ste tes) ste (t, Nothing) = show t ste (t, Just e) = show e ++ "@" ++ show t showLog :: Log -> String showLog l = intercalate " " (map sle (reverse l)) where sle (Left x) = show x sle (Right x) = "[" ++ show x ++ "]" Set the exit code to please . main :: IO () main = do res <- quickCheckWithResult args testPrediction case res of Success {} -> exitSuccess _ -> exitFailure where
25e046ae1e923dd0b5dce88a4f61c366282151cc70b45d51ecb5d33168a3dcc7
isovector/type-errors
Errors.hs
# LANGUAGE CPP # ------------------------------------------------------------------------------ -- | This module provides useful tools for writing better type-errors. For -- a quickstart guide to the underlying 'GHC.TypeLits.TypeError' machinery, check out excellent blog post -- <-errors A story told by Type Errors>. module Type.Errors ( -- * Generating Error Messages ErrorMessage (..) , PrettyPrintList , ShowTypeQuoted -- * Emitting Error Messages , TypeError , DelayError , DelayErrorFcf , NoError , NoErrorFcf -- * Observing Stuckness , IfStuck , WhenStuck , UnlessStuck -- * Running Magic Stuck Type Families , te -- * Observing Phantomness , PHANTOM , UnlessPhantom -- * Performing Type Substitutions , Subst , VAR , SubstVar -- * Working With Fcfs , Exp , Eval , Pure ) where import Control.Applicative import Data.Coerce import Data.Generics import Data.Kind import Fcf import GHC.TypeLits import qualified Language.Haskell.TH as TH import Language.Haskell.TH hiding (Type, Exp) -- $setup -- >>> :m +Data.Kind -- >>> :m +Data.Proxy > > > import ( Generic ( .. ) ) > > > : def ! ( \msg - > pure $ " let foo : : DelayError ( " + + msg + + " ) = > ( ) ; foo = ( ) ; in foo " ) > > > : def ! ( \msg - > pure $ " let foo : : ( " + + msg + + " ) = > ( ) ; foo = ( ) ; in foo " ) -- >>> :{ -- data HasNoRep = HasNoRep -- :} ------------------------------------------------------------------------------ -- | Pretty print a list. -- > > > : [ Bool ] -- ... ... ' ' -- ... -- > > > : [ 1 , 2 ] -- ... -- ... '1', and '2' -- ... -- > > > : [ " hello " , " world " , " cool " ] -- ... -- ... "hello", "world", and "cool" -- ... -- @since 0.1.0.0 type family PrettyPrintList (vs :: [k]) :: ErrorMessage where PrettyPrintList '[] = 'Text "" PrettyPrintList '[a] = ShowTypeQuoted a PrettyPrintList '[a, b] = ShowTypeQuoted a ':<>: 'Text ", and " ':<>: ShowTypeQuoted b PrettyPrintList (a ': vs) = ShowTypeQuoted a ':<>: 'Text ", " ':<>: PrettyPrintList vs ------------------------------------------------------------------------------ | Like ' ShowType ' , but quotes the type if necessary . -- > > > : -- ... -- ... 'Int' -- ... -- -- >>> :show_error ShowTypeQuoted "symbols aren't quoted" -- ... -- ... "symbols aren't quoted" -- ... -- @since 0.1.0.0 #if __GLASGOW_HASKELL__ >= 902 type ShowTypeQuoted :: k -> ErrorMessage #endif type family ShowTypeQuoted (t :: k) :: ErrorMessage where ShowTypeQuoted (t :: Symbol) = 'ShowType t ShowTypeQuoted t = 'Text "'" ':<>: 'ShowType t ':<>: 'Text "'" ------------------------------------------------------------------------------ | Error messages produced via ' TypeError ' are often /too strict/ , and will be emitted sooner than you 'd like . The solution is to use ' DelayError ' , -- which will switch the error messages to being consumed lazily. -- -- >>> :{ -- foo :: TypeError ('Text "Too eager; prevents compilation") => () -- foo = () -- :} -- ... -- ... Too eager; prevents compilation -- ... -- -- >>> :{ foo : : DelayError ( ' Text " Lazy ; emitted on use " ) = > ( ) -- foo = () -- :} -- -- >>> foo -- ... -- ... Lazy; emitted on use -- ... -- @since 0.1.0.0 type DelayError err = Eval (DelayErrorFcf err) ------------------------------------------------------------------------------ | Like ' DelayError ' , but implemented as a first - class family . ' DelayErrorFcf ' is useful when used as the last argument to ' ' and -- 'UnlessStuck'. -- @since 0.1.0.0 data DelayErrorFcf :: ErrorMessage -> Exp k type instance Eval (DelayErrorFcf a) = TypeError a ------------------------------------------------------------------------------ -- | A helper definition that /doesn't/ emit a type error. This is occassionally useful to leave as the residual constraint in ' ' when -- you only want to observe if an expression /isn't/ stuck. -- @since 0.1.0.0 type NoError = (() :: Constraint) ------------------------------------------------------------------------------ | Like ' NoError ' , but implemented as a first - class family . ' NoErrorFcf ' is useful when used as the last argument to ' ' and ' UnlessStuck ' . -- @since 0.1.0.0 type NoErrorFcf = Pure NoError ------------------------------------------------------------------------------ | @'IfStuck ' expr b c@ leaves @b@ in the residual constraints whenever @expr@ is stuck , otherwise it ' Eval'uates @c@. -- Often you want to leave a ' DelayError ' in @b@ in order to report an error when @expr@ is stuck . -- The @c@ parameter is a first - class family , which allows you to perform arbitrarily - complicated type - level computations whenever @expr@ is n't stuck . For example , you might want to produce a typeclass ' Constraint ' here . Alternatively , you can nest calls to ' ' in order to do subsequent -- processing. -- This is a generalization of < / kcsongor > 's -- machinery described in < -stuck-families/ detecting the undetectable > . -- @since 0.1.0.0 type family IfStuck (expr :: k) (b :: k1) (c :: Exp k1) :: k1 where -- The type pattern @_ Foo@ is interpretered by the compiler as being of -- any kind. This is great and exactly what we want here, except that things like @forall s. Maybe s@ will get stuck on it . -- So instead , we just propagate out 100 of these type variables and assume that 100 type variables ought to be enough for anyone . IfStuck (_ AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind) b c = b IfStuck a b c = Eval c data AnythingOfAnyKind ------------------------------------------------------------------------------ | Like ' ' , but specialized to the case when you do n't want to do -- anything if @expr@ isn't stuck. -- -- >>> :{ -- observe_no_rep : : -- (Rep t) ( DelayError ( ' Text " No Rep instance for " ' : < > : ShowTypeQuoted t ) ) -- => t -- -> () -- observe_no_rep _ = () -- :} -- -- >>> observe_no_rep HasNoRep -- ... -- ... No Rep instance for 'HasNoRep' -- ... -- -- >>> observe_no_rep True -- () -- @since 0.1.0.0 type WhenStuck expr b = IfStuck expr b NoErrorFcf ------------------------------------------------------------------------------ | Like ' ' , but leaves no residual constraint when @expr@ is stuck . -- This can be used to ensure an expression /isn't/ stuck before analyzing it -- further. -- See the example under ' UnlessPhantom ' for an example of this use - case . -- @since 0.1.0.0 type UnlessStuck expr c = IfStuck expr NoError c ------------------------------------------------------------------------------ -- | This library provides tools for performing lexical substitutions over types . For example , the function ' UnlessPhantom ' asks you to mark phantom variables via ' PHANTOM ' . -- -- Unfortunately, this substitution cannot reliably be performed via -- type families, since it will too often get stuck. Instead we provide 'te', -- which is capable of reasoning about types symbolically. -- -- Any type which comes with the warning /"This type family is always stuck."/ -- __must__ be used in the context of 'te' and the magic @[t|@ quasiquoter. To -- illustrate, the following is stuck: -- -- >>> :{ -- foo :: SubstVar VAR Bool -- foo = True -- :} -- ... -- ... Couldn't match expected type ...SubstVar VAR Bool... -- ... with actual type ...Bool... -- ... -- -- But running it via 'te' makes everything work: -- -- >>> :{ foo : : $ ( te[t| SubstVar | ] ) -- foo = True -- :} -- -- If you don't want to think about when to use 'te', it's a no-op when used -- with everyday types: -- -- >>> :{ bar : : $ ( te[t| | ] ) -- bar = True -- :} -- @since 0.2.0.0 te :: Q TH.Type -> Q TH.Type te = liftA $ everywhere $ mkT parseSubst replaceWhen :: Data a => TH.Type -> TH.Type -> a -> a replaceWhen a b = everywhere $ mkT $ \case x | x == a -> b x -> x parseSubst :: TH.Type -> TH.Type parseSubst (ConT phantom `AppT` expr `AppT` msg) | phantom == ''UnlessPhantom = ConT ''Coercible `AppT` (replaceWhen (ConT ''PHANTOM) (ConT ''Stuck) expr) `AppT` (replaceWhen (ConT ''PHANTOM) (ConT ''DelayError `AppT` msg) expr) parseSubst (ConT subst `AppT` t `AppT` a `AppT` b) | subst == ''Subst = replaceWhen a b t parseSubst (ConT subst `AppT` t `AppT` b) | subst == ''SubstVar = replaceWhen (ConT ''VAR) b t parseSubst a = a ------------------------------------------------------------------------------ -- | __This type family is always stuck. It must be used in the context of 'te'.__ -- -- A meta-variable for marking which argument should be a phantom when working with ' UnlessPhantom ' . -- ' PHANTOM ' is polykinded and can be used in several settings . -- See ' UnlessPhantom ' for examples . -- @since 0.1.0.0 type family PHANTOM :: k ------------------------------------------------------------------------------ -- | __This type family is always stuck. It must be used in the context of 'te'.__ -- @'UnlessPhantom ' expr err@ determines if the type described by @expr@ is phantom in the variables marked via ' PHANTOM ' . If it 's not , it produces -- the error message @err@. -- -- For example, consider the definition: -- -- >>> :{ data Qux a b = Qux b -- :} -- -- which is phantom in @a@: -- > > > : eval_error $ ( te[t| UnlessPhantom ( Qux PHANTOM Int ) ( ' Text " Ok " ) | ] ) -- () -- -- but not in @b@: -- > > > : eval_error $ ( te[t| UnlessPhantom ( Qux Int PHANTOM ) ( ' Text " Bad ! " ) | ] ) -- ... -- ... Bad! -- ... -- -- Unfortunately there is no known way to emit an error message if the variable -- /is/ a phantom. -- Often you 'll want to guard ' UnlessPhantom ' against ' ' , to ensure you -- don't get errors when things are merely ambiguous. You can do this by writing your own fcf whose implementation is ' UnlessPhantom ' : -- -- >>> :{ data NotPhantomErrorFcf : : k - > Exp Constraint -- type instance Eval (NotPhantomErrorFcf f) = $ ( te[t| UnlessPhantom ( f PHANTOM ) -- ( ShowTypeQuoted f -- ':<>: 'Text " is not phantom in its argument!") -- |]) -- :} -- -- >>> :{ -- observe_phantom -- :: UnlessStuck -- f -- (NotPhantomErrorFcf f) -- => f p -- -> () -- observe_phantom _ = () -- :} -- -- We then notice that using @observe_phantom@ against 'Data.Proxy.Proxy' -- doesn't produce any errors, but against 'Maybe' does: -- -- >>> observe_phantom Proxy -- () -- -- >>> observe_phantom (Just 5) -- ... -- ... 'Maybe' is not phantom in its argument! -- ... -- Finally , we leave @observe_phantom@ unsaturated , and therefore is n't yet known . Without guarding the ' UnlessPhantom ' behind ' UnlessStuck ' , this would -- incorrectly produce the message "'f' is not phantom in its argument!" -- -- >>> observe_phantom -- ... -- ... No instance for (Show (f0 p0 -> ())) -- ... -- @since 0.2.0.0 type family UnlessPhantom :: k -> ErrorMessage -> Constraint ------------------------------------------------------------------------------ -- | __This type family is always stuck. It must be used in the context of 'te'.__ -- @'Subst ' expr a b@ substitutes all instances of @a@ for @b@ in @expr@. -- > > > : kind ! $ ( te[t| Subst ( Either Int Int ) Int Bool | ] ) -- ... = Either -- > > > : kind ! $ ( te[t| Subst ( Either Int Bool ) Int [ Char ] | ] ) -- ... -- = Either [Char] Bool -- > > > : kind ! $ ( te[t| Subst ( Either ) Either ( , ) | ] ) -- ... -- = (Int, Bool) -- @since 0.2.0.0 type family Subst :: k1 -> k1 -> k2 -> k2 ------------------------------------------------------------------------------ -- | __This type family is always stuck. It must be used in the context of 'te'.__ -- -- 'VAR' is a meta-varaible which marks a substitution in 'SubstVar'. The result of @'SubstVar ' expr val@ is @expr[val/'VAR']@. -- -- 'VAR' is polykinded and can be used in several settings. -- -- See 'SubstVar' for examples. -- @since 0.2.0.0 type family VAR :: k ------------------------------------------------------------------------------ -- | __This type family is always stuck. It must be used in the context of 'te'.__ -- Like ' Subst ' , but uses the explicit meta - variable ' VAR ' to mark substitution -- points. -- > > > : kind ! $ ( te[t| SubstVar ( Either ) | ] ) -- ... = Either -- > > > : kind ! $ ( te[t| SubstVar ( Either ) [ ] | ] ) -- ... -- = Either [Char] Bool -- > > > : kind ! $ ( te[t| SubstVar ( VAR Int Bool ) ( , ) | ] ) -- ... -- = (Int, Bool) -- @since 0.2.0.0 type family SubstVar :: k1 -> k2 -> k2
null
https://raw.githubusercontent.com/isovector/type-errors/81fd8e2e48f65b83a228cc1ba7db890fcc11cbd7/src/Type/Errors.hs
haskell
---------------------------------------------------------------------------- | This module provides useful tools for writing better type-errors. For a quickstart guide to the underlying 'GHC.TypeLits.TypeError' machinery, <-errors A story told by Type Errors>. * Generating Error Messages * Emitting Error Messages * Observing Stuckness * Running Magic Stuck Type Families * Observing Phantomness * Performing Type Substitutions * Working With Fcfs $setup >>> :m +Data.Kind >>> :m +Data.Proxy >>> :{ data HasNoRep = HasNoRep :} ---------------------------------------------------------------------------- | Pretty print a list. ... ... ... ... '1', and '2' ... ... ... "hello", "world", and "cool" ... ---------------------------------------------------------------------------- ... ... 'Int' ... >>> :show_error ShowTypeQuoted "symbols aren't quoted" ... ... "symbols aren't quoted" ... ---------------------------------------------------------------------------- which will switch the error messages to being consumed lazily. >>> :{ foo :: TypeError ('Text "Too eager; prevents compilation") => () foo = () :} ... ... Too eager; prevents compilation ... >>> :{ foo = () :} >>> foo ... ... Lazy; emitted on use ... ---------------------------------------------------------------------------- 'UnlessStuck'. ---------------------------------------------------------------------------- | A helper definition that /doesn't/ emit a type error. This is you only want to observe if an expression /isn't/ stuck. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- processing. machinery described in The type pattern @_ Foo@ is interpretered by the compiler as being of any kind. This is great and exactly what we want here, except that things ---------------------------------------------------------------------------- anything if @expr@ isn't stuck. >>> :{ observe_no_rep (Rep t) => t -> () observe_no_rep _ = () :} >>> observe_no_rep HasNoRep ... ... No Rep instance for 'HasNoRep' ... >>> observe_no_rep True () ---------------------------------------------------------------------------- This can be used to ensure an expression /isn't/ stuck before analyzing it further. ---------------------------------------------------------------------------- | This library provides tools for performing lexical substitutions over Unfortunately, this substitution cannot reliably be performed via type families, since it will too often get stuck. Instead we provide 'te', which is capable of reasoning about types symbolically. Any type which comes with the warning /"This type family is always stuck."/ __must__ be used in the context of 'te' and the magic @[t|@ quasiquoter. To illustrate, the following is stuck: >>> :{ foo :: SubstVar VAR Bool foo = True :} ... ... Couldn't match expected type ...SubstVar VAR Bool... ... with actual type ...Bool... ... But running it via 'te' makes everything work: >>> :{ foo = True :} If you don't want to think about when to use 'te', it's a no-op when used with everyday types: >>> :{ bar = True :} ---------------------------------------------------------------------------- | __This type family is always stuck. It must be used in the context of 'te'.__ A meta-variable for marking which argument should be a phantom when working ---------------------------------------------------------------------------- | __This type family is always stuck. It must be used in the context of 'te'.__ the error message @err@. For example, consider the definition: >>> :{ :} which is phantom in @a@: () but not in @b@: ... ... Bad! ... Unfortunately there is no known way to emit an error message if the variable /is/ a phantom. don't get errors when things are merely ambiguous. You can do this by >>> :{ type instance Eval (NotPhantomErrorFcf f) = ( ShowTypeQuoted f ':<>: 'Text " is not phantom in its argument!") |]) :} >>> :{ observe_phantom :: UnlessStuck f (NotPhantomErrorFcf f) => f p -> () observe_phantom _ = () :} We then notice that using @observe_phantom@ against 'Data.Proxy.Proxy' doesn't produce any errors, but against 'Maybe' does: >>> observe_phantom Proxy () >>> observe_phantom (Just 5) ... ... 'Maybe' is not phantom in its argument! ... incorrectly produce the message "'f' is not phantom in its argument!" >>> observe_phantom ... ... No instance for (Show (f0 p0 -> ())) ... ---------------------------------------------------------------------------- | __This type family is always stuck. It must be used in the context of 'te'.__ ... ... = Either [Char] Bool ... = (Int, Bool) ---------------------------------------------------------------------------- | __This type family is always stuck. It must be used in the context of 'te'.__ 'VAR' is a meta-varaible which marks a substitution in 'SubstVar'. The 'VAR' is polykinded and can be used in several settings. See 'SubstVar' for examples. ---------------------------------------------------------------------------- | __This type family is always stuck. It must be used in the context of 'te'.__ points. ... ... = Either [Char] Bool ... = (Int, Bool)
# LANGUAGE CPP # check out excellent blog post module Type.Errors ErrorMessage (..) , PrettyPrintList , ShowTypeQuoted , TypeError , DelayError , DelayErrorFcf , NoError , NoErrorFcf , IfStuck , WhenStuck , UnlessStuck , te , PHANTOM , UnlessPhantom , Subst , VAR , SubstVar , Exp , Eval , Pure ) where import Control.Applicative import Data.Coerce import Data.Generics import Data.Kind import Fcf import GHC.TypeLits import qualified Language.Haskell.TH as TH import Language.Haskell.TH hiding (Type, Exp) > > > import ( Generic ( .. ) ) > > > : def ! ( \msg - > pure $ " let foo : : DelayError ( " + + msg + + " ) = > ( ) ; foo = ( ) ; in foo " ) > > > : def ! ( \msg - > pure $ " let foo : : ( " + + msg + + " ) = > ( ) ; foo = ( ) ; in foo " ) > > > : [ Bool ] ... ' ' > > > : [ 1 , 2 ] > > > : [ " hello " , " world " , " cool " ] @since 0.1.0.0 type family PrettyPrintList (vs :: [k]) :: ErrorMessage where PrettyPrintList '[] = 'Text "" PrettyPrintList '[a] = ShowTypeQuoted a PrettyPrintList '[a, b] = ShowTypeQuoted a ':<>: 'Text ", and " ':<>: ShowTypeQuoted b PrettyPrintList (a ': vs) = ShowTypeQuoted a ':<>: 'Text ", " ':<>: PrettyPrintList vs | Like ' ShowType ' , but quotes the type if necessary . > > > : @since 0.1.0.0 #if __GLASGOW_HASKELL__ >= 902 type ShowTypeQuoted :: k -> ErrorMessage #endif type family ShowTypeQuoted (t :: k) :: ErrorMessage where ShowTypeQuoted (t :: Symbol) = 'ShowType t ShowTypeQuoted t = 'Text "'" ':<>: 'ShowType t ':<>: 'Text "'" | Error messages produced via ' TypeError ' are often /too strict/ , and will be emitted sooner than you 'd like . The solution is to use ' DelayError ' , foo : : DelayError ( ' Text " Lazy ; emitted on use " ) = > ( ) @since 0.1.0.0 type DelayError err = Eval (DelayErrorFcf err) | Like ' DelayError ' , but implemented as a first - class family . ' DelayErrorFcf ' is useful when used as the last argument to ' ' and @since 0.1.0.0 data DelayErrorFcf :: ErrorMessage -> Exp k type instance Eval (DelayErrorFcf a) = TypeError a occassionally useful to leave as the residual constraint in ' ' when @since 0.1.0.0 type NoError = (() :: Constraint) | Like ' NoError ' , but implemented as a first - class family . ' NoErrorFcf ' is useful when used as the last argument to ' ' and ' UnlessStuck ' . @since 0.1.0.0 type NoErrorFcf = Pure NoError | @'IfStuck ' expr b c@ leaves @b@ in the residual constraints whenever @expr@ is stuck , otherwise it ' Eval'uates @c@. Often you want to leave a ' DelayError ' in @b@ in order to report an error when @expr@ is stuck . The @c@ parameter is a first - class family , which allows you to perform arbitrarily - complicated type - level computations whenever @expr@ is n't stuck . For example , you might want to produce a typeclass ' Constraint ' here . Alternatively , you can nest calls to ' ' in order to do subsequent This is a generalization of < / kcsongor > 's < -stuck-families/ detecting the undetectable > . @since 0.1.0.0 type family IfStuck (expr :: k) (b :: k1) (c :: Exp k1) :: k1 where like @forall s. Maybe s@ will get stuck on it . So instead , we just propagate out 100 of these type variables and assume that 100 type variables ought to be enough for anyone . IfStuck (_ AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind AnythingOfAnyKind) b c = b IfStuck a b c = Eval c data AnythingOfAnyKind | Like ' ' , but specialized to the case when you do n't want to do : : ( DelayError ( ' Text " No Rep instance for " ' : < > : ShowTypeQuoted t ) ) @since 0.1.0.0 type WhenStuck expr b = IfStuck expr b NoErrorFcf | Like ' ' , but leaves no residual constraint when @expr@ is stuck . See the example under ' UnlessPhantom ' for an example of this use - case . @since 0.1.0.0 type UnlessStuck expr c = IfStuck expr NoError c types . For example , the function ' UnlessPhantom ' asks you to mark phantom variables via ' PHANTOM ' . foo : : $ ( te[t| SubstVar | ] ) bar : : $ ( te[t| | ] ) @since 0.2.0.0 te :: Q TH.Type -> Q TH.Type te = liftA $ everywhere $ mkT parseSubst replaceWhen :: Data a => TH.Type -> TH.Type -> a -> a replaceWhen a b = everywhere $ mkT $ \case x | x == a -> b x -> x parseSubst :: TH.Type -> TH.Type parseSubst (ConT phantom `AppT` expr `AppT` msg) | phantom == ''UnlessPhantom = ConT ''Coercible `AppT` (replaceWhen (ConT ''PHANTOM) (ConT ''Stuck) expr) `AppT` (replaceWhen (ConT ''PHANTOM) (ConT ''DelayError `AppT` msg) expr) parseSubst (ConT subst `AppT` t `AppT` a `AppT` b) | subst == ''Subst = replaceWhen a b t parseSubst (ConT subst `AppT` t `AppT` b) | subst == ''SubstVar = replaceWhen (ConT ''VAR) b t parseSubst a = a with ' UnlessPhantom ' . ' PHANTOM ' is polykinded and can be used in several settings . See ' UnlessPhantom ' for examples . @since 0.1.0.0 type family PHANTOM :: k @'UnlessPhantom ' expr err@ determines if the type described by @expr@ is phantom in the variables marked via ' PHANTOM ' . If it 's not , it produces data Qux a b = Qux b > > > : eval_error $ ( te[t| UnlessPhantom ( Qux PHANTOM Int ) ( ' Text " Ok " ) | ] ) > > > : eval_error $ ( te[t| UnlessPhantom ( Qux Int PHANTOM ) ( ' Text " Bad ! " ) | ] ) Often you 'll want to guard ' UnlessPhantom ' against ' ' , to ensure you writing your own fcf whose implementation is ' UnlessPhantom ' : data NotPhantomErrorFcf : : k - > Exp Constraint $ ( te[t| UnlessPhantom ( f PHANTOM ) Finally , we leave @observe_phantom@ unsaturated , and therefore is n't yet known . Without guarding the ' UnlessPhantom ' behind ' UnlessStuck ' , this would @since 0.2.0.0 type family UnlessPhantom :: k -> ErrorMessage -> Constraint @'Subst ' expr a b@ substitutes all instances of @a@ for @b@ in @expr@. > > > : kind ! $ ( te[t| Subst ( Either Int Int ) Int Bool | ] ) = Either > > > : kind ! $ ( te[t| Subst ( Either Int Bool ) Int [ Char ] | ] ) > > > : kind ! $ ( te[t| Subst ( Either ) Either ( , ) | ] ) @since 0.2.0.0 type family Subst :: k1 -> k1 -> k2 -> k2 result of @'SubstVar ' expr val@ is @expr[val/'VAR']@. @since 0.2.0.0 type family VAR :: k Like ' Subst ' , but uses the explicit meta - variable ' VAR ' to mark substitution > > > : kind ! $ ( te[t| SubstVar ( Either ) | ] ) = Either > > > : kind ! $ ( te[t| SubstVar ( Either ) [ ] | ] ) > > > : kind ! $ ( te[t| SubstVar ( VAR Int Bool ) ( , ) | ] ) @since 0.2.0.0 type family SubstVar :: k1 -> k2 -> k2
79c53baa6e8edafcbc96efff9ee12e9301c3e4e7d5334bbb821cdd9acef9b75e
freizl/dive-into-haskell
Sentence.hs
-- | module Sentence where type Subject = String type Verb = String type Object = String data Sentence = Sentence Subject Verb Object deriving (Eq, Show) s1 = Sentence "dogs" "drool" s2 = Sentence "Julie" "loves" "dogs"
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/readings/haskell-book/06/Sentence.hs
haskell
|
module Sentence where type Subject = String type Verb = String type Object = String data Sentence = Sentence Subject Verb Object deriving (Eq, Show) s1 = Sentence "dogs" "drool" s2 = Sentence "Julie" "loves" "dogs"
3bfb15a3d60e78c309f0e9d5aacfe8918ca5fe908e61e7a742021600a485971f
ryanpbrewster/haskell
GC.hs
-- GC.hs - Problem - - The GC - content of a DNA string is given by the percentage of symbols in the - string that are ' C ' or ' G ' . For example , the GC - content of " AGCTATAG " is - 37.5 % . Note that the reverse complement of any DNA string has the same - GC - content . - - DNA strings must be labeled when they are consolidated into a database . - A commonly used method of string labeling is called FASTA format . In this - format , the string is introduced by a line that begins with ' > ' , followed by - some labeling information . Subsequent lines contain the string itself ; the - first line to begin with ' > ' indicates the label of the next string . - - In 's implementation , a string in FASTA format will be labeled by - the ID " Rosalind_xxxx " , where " xxxx " denotes a four - digit code between 0000 - and 9999 . - - Given : At most 10 DNA strings in FASTA format ( of length at most 1 kbp each ) . - - Return : The ID of the string having the highest GC - content , followed by the - GC - content of that string . allows for a default error of 0.001 in - all decimal answers unless otherwise stated ; please see the note on absolute - error below . - - Sample Dataset - - > Rosalind_6404 - CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC - TCCCACTAATAATTCTGAGG - > Rosalind_5959 - CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT - ATATCCATTTGTCAGCAGACACGC - > Rosalind_0808 - CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC - TGGGAACCTGCGGGCAGTAGGTGGAAT - - Sample Output - - Rosalind_0808 - 60.919540 - Problem - - The GC-content of a DNA string is given by the percentage of symbols in the - string that are 'C' or 'G'. For example, the GC-content of "AGCTATAG" is - 37.5%. Note that the reverse complement of any DNA string has the same - GC-content. - - DNA strings must be labeled when they are consolidated into a database. - A commonly used method of string labeling is called FASTA format. In this - format, the string is introduced by a line that begins with '>', followed by - some labeling information. Subsequent lines contain the string itself; the - first line to begin with '>' indicates the label of the next string. - - In Rosalind's implementation, a string in FASTA format will be labeled by - the ID "Rosalind_xxxx", where "xxxx" denotes a four-digit code between 0000 - and 9999. - - Given: At most 10 DNA strings in FASTA format (of length at most 1 kbp each). - - Return: The ID of the string having the highest GC-content, followed by the - GC-content of that string. Rosalind allows for a default error of 0.001 in - all decimal answers unless otherwise stated; please see the note on absolute - error below. - - Sample Dataset - - >Rosalind_6404 - CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC - TCCCACTAATAATTCTGAGG - >Rosalind_5959 - CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT - ATATCCATTTGTCAGCAGACACGC - >Rosalind_0808 - CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC - TGGGAACCTGCGGGCAGTAGGTGGAAT - - Sample Output - - Rosalind_0808 - 60.919540 -} import System.Environment (getArgs) import Text.Printf import Data.Ord (comparing) import Data.List (maximumBy) import Rosalind.Parsing (parseNucFASTAs) import Rosalind.Structures main = do args <- getArgs txt <- readFile (head args) putStrLn $ solveProblem txt solveProblem txt = let inps = parseNucFASTAs txt ans = maximumBy (comparing (gcContent.getSequence)) inps out = showAnswer ans in out showAnswer fsta@(FASTA id dna) = showID id ++ "\n" ++ printf "%.6f" (100 * gcContent dna) gc :: Nucleotide -> Bool gc (Nucleotide n) = n == 'G' || n == 'C' gcContent :: BioSequence -> Double gcContent ncl_seq = let nucs = getNucs ncl_seq gc_content = length $ filter gc nucs total = length nucs in (fromIntegral gc_content) / (fromIntegral total)
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/Rosalind/GC.hs
haskell
GC.hs
- Problem - - The GC - content of a DNA string is given by the percentage of symbols in the - string that are ' C ' or ' G ' . For example , the GC - content of " AGCTATAG " is - 37.5 % . Note that the reverse complement of any DNA string has the same - GC - content . - - DNA strings must be labeled when they are consolidated into a database . - A commonly used method of string labeling is called FASTA format . In this - format , the string is introduced by a line that begins with ' > ' , followed by - some labeling information . Subsequent lines contain the string itself ; the - first line to begin with ' > ' indicates the label of the next string . - - In 's implementation , a string in FASTA format will be labeled by - the ID " Rosalind_xxxx " , where " xxxx " denotes a four - digit code between 0000 - and 9999 . - - Given : At most 10 DNA strings in FASTA format ( of length at most 1 kbp each ) . - - Return : The ID of the string having the highest GC - content , followed by the - GC - content of that string . allows for a default error of 0.001 in - all decimal answers unless otherwise stated ; please see the note on absolute - error below . - - Sample Dataset - - > Rosalind_6404 - CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC - TCCCACTAATAATTCTGAGG - > Rosalind_5959 - CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT - ATATCCATTTGTCAGCAGACACGC - > Rosalind_0808 - CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC - TGGGAACCTGCGGGCAGTAGGTGGAAT - - Sample Output - - Rosalind_0808 - 60.919540 - Problem - - The GC-content of a DNA string is given by the percentage of symbols in the - string that are 'C' or 'G'. For example, the GC-content of "AGCTATAG" is - 37.5%. Note that the reverse complement of any DNA string has the same - GC-content. - - DNA strings must be labeled when they are consolidated into a database. - A commonly used method of string labeling is called FASTA format. In this - format, the string is introduced by a line that begins with '>', followed by - some labeling information. Subsequent lines contain the string itself; the - first line to begin with '>' indicates the label of the next string. - - In Rosalind's implementation, a string in FASTA format will be labeled by - the ID "Rosalind_xxxx", where "xxxx" denotes a four-digit code between 0000 - and 9999. - - Given: At most 10 DNA strings in FASTA format (of length at most 1 kbp each). - - Return: The ID of the string having the highest GC-content, followed by the - GC-content of that string. Rosalind allows for a default error of 0.001 in - all decimal answers unless otherwise stated; please see the note on absolute - error below. - - Sample Dataset - - >Rosalind_6404 - CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC - TCCCACTAATAATTCTGAGG - >Rosalind_5959 - CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT - ATATCCATTTGTCAGCAGACACGC - >Rosalind_0808 - CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC - TGGGAACCTGCGGGCAGTAGGTGGAAT - - Sample Output - - Rosalind_0808 - 60.919540 -} import System.Environment (getArgs) import Text.Printf import Data.Ord (comparing) import Data.List (maximumBy) import Rosalind.Parsing (parseNucFASTAs) import Rosalind.Structures main = do args <- getArgs txt <- readFile (head args) putStrLn $ solveProblem txt solveProblem txt = let inps = parseNucFASTAs txt ans = maximumBy (comparing (gcContent.getSequence)) inps out = showAnswer ans in out showAnswer fsta@(FASTA id dna) = showID id ++ "\n" ++ printf "%.6f" (100 * gcContent dna) gc :: Nucleotide -> Bool gc (Nucleotide n) = n == 'G' || n == 'C' gcContent :: BioSequence -> Double gcContent ncl_seq = let nucs = getNucs ncl_seq gc_content = length $ filter gc nucs total = length nucs in (fromIntegral gc_content) / (fromIntegral total)
80137ced9d07ecab47caabee51642109f460655c3f467f8767512d687f4e6f83
theodormoroianu/SecondYearCourses
HaskellChurch_20210415163944.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 = "cBool " <> 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 cBool :: Bool -> CBool cBool True = cTrue cBool False = cFalse --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 = "cPair " <> 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 is not 0 then r should be less than n. --hint repeated substraction, iterated for at most m times. cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined -- a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where --An instance to show CLists as regular lists. instance (Show a) => Show (CList a) where show l = "cList " <> (show $ toList l) -- The empty list is that which when aggregated it will always produce the initial value cNil :: CList a cNil = undefined -- Adding an element to a list means that, when aggregating the list, the newly added -- element will be aggregated with the result obtained by aggregating the remainder of the list (.:) :: a -> CList a -> CList a (.:) = undefined we can obtain a CList from a regular list by folding the list cList :: [a] -> CList a cList = undefined builds a CList of CNats corresponding to a list of Integers cNatList :: [Integer] -> CList CNat cNatList = undefined -- sums the elements in the list cSum :: CList CNat -> CNat cSum = undefined -- checks whether a list is nil (similar to cIs0) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue -- gets the head of the list (or the default specified value if the list is empty) cHead :: CList a -> a -> a cHead = undefined -- gets the head of the list (or the default specified value if the list is empty) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415163944.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 is not 0 then r should be less than n. hint repeated substraction, iterated for at most m times. a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. An instance to show CLists as regular lists. The empty list is that which when aggregated it will always produce the initial value Adding an element to a list means that, when aggregating the list, the newly added element will be aggregated with the result obtained by aggregating the remainder of the list sums the elements in the list checks whether a list is nil (similar to cIs0) gets the head of the list (or the default specified value if the list is empty) gets the head of the list (or the default specified value if the list is empty)
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 = "cBool " <> 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 cBool :: Bool -> CBool cBool True = cTrue cBool False = cFalse 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 = "cPair " <> 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 = undefined newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where instance (Show a) => Show (CList a) where show l = "cList " <> (show $ toList l) cNil :: CList a cNil = undefined (.:) :: a -> CList a -> CList a (.:) = undefined we can obtain a CList from a regular list by folding the list cList :: [a] -> CList a cList = undefined builds a CList of CNats corresponding to a list of Integers cNatList :: [Integer] -> CList CNat cNatList = undefined cSum :: CList CNat -> CNat cSum = undefined cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue cHead :: CList a -> a -> a cHead = undefined cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
f2b6a033086b133b8834a9fd1143779fec282c7600a63af56b685252d8500c68
siers/zn
TLS.hs
#file-fetch-url-hs-L27 -- stack -v runghc --package connection --package http-client --package http-client-tls --package tls --package data-default {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - deprecations # module Zn.TLS (mkHttpManager) where import qualified Network.Connection as NC import qualified Network.HTTP.Client as Http import qualified Network.HTTP.Client.TLS as Http import qualified Network.TLS as TLS import qualified Network.TLS.Extra as TLS (ciphersuite_all) import qualified System.X509 as TLS import Data.Default import Data.Maybe import Network.HTTP.Client import System.Environment import Prelude main :: IO () main = do murl <- getArgs case listToMaybe murl of (fmap parseUrl -> Just (Just req)) -> do mgr <- mkHttpManager True res <- httpLbs req mgr print (show (responseStatus res)) _ -> error "usage: fetch-url [URL] (must include http:// or https://" -- | Create an HTTP 'Manager' for running a 'Test' mkHttpManager :: Bool -- ^ validate ssl -> IO Manager mkHttpManager validateSsl = do scs <- TLS.getSystemCertificateStore let tlsSettings = NC.TLSSettings (cp scs) mngrCfg = Http.mkManagerSettings tlsSettings Nothing Http.newManager mngrCfg where cp scs = (TLS.defaultParamsClient "" "") { TLS.clientSupported = def { TLS.supportedCiphers = TLS.ciphersuite_all , TLS.supportedHashSignatures = hashSignatures , TLS.supportedVersions [ TLS10 , TLS11 , TLS12 ] } , TLS.clientShared = def { TLS.sharedCAStore = scs , TLS.sharedValidationCache = validationCache } } hashSignatures = [ (TLS.HashSHA512, TLS.SignatureRSA) , (TLS.HashSHA384, TLS.SignatureRSA) , (TLS.HashSHA256, TLS.SignatureRSA) , (TLS.HashSHA224, TLS.SignatureRSA) , (TLS.HashSHA1, TLS.SignatureRSA) , (TLS.HashSHA1, TLS.SignatureDSS) " bad SignatureECDSA for ecdhparams " " bad SignatureECDSA for ecdhparams " , (TLS.HashSHA256, TLS.SignatureECDSA) , (TLS.HashSHA224, TLS.SignatureECDSA) , (TLS.HashSHA1, TLS.SignatureECDSA) ] validationCache = if not validateSsl then TLS.ValidationCache (\_ _ _ -> return TLS.ValidationCachePass) (\_ _ _ -> return ()) else def
null
https://raw.githubusercontent.com/siers/zn/b78692910fc5c4c725b3133cb91f5e1e3da94808/src/Zn/TLS.hs
haskell
stack -v runghc --package connection --package http-client --package http-client-tls --package tls --package data-default # LANGUAGE OverloadedStrings # | Create an HTTP 'Manager' for running a 'Test' ^ validate ssl
#file-fetch-url-hs-L27 # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - deprecations # module Zn.TLS (mkHttpManager) where import qualified Network.Connection as NC import qualified Network.HTTP.Client as Http import qualified Network.HTTP.Client.TLS as Http import qualified Network.TLS as TLS import qualified Network.TLS.Extra as TLS (ciphersuite_all) import qualified System.X509 as TLS import Data.Default import Data.Maybe import Network.HTTP.Client import System.Environment import Prelude main :: IO () main = do murl <- getArgs case listToMaybe murl of (fmap parseUrl -> Just (Just req)) -> do mgr <- mkHttpManager True res <- httpLbs req mgr print (show (responseStatus res)) _ -> error "usage: fetch-url [URL] (must include http:// or https://" -> IO Manager mkHttpManager validateSsl = do scs <- TLS.getSystemCertificateStore let tlsSettings = NC.TLSSettings (cp scs) mngrCfg = Http.mkManagerSettings tlsSettings Nothing Http.newManager mngrCfg where cp scs = (TLS.defaultParamsClient "" "") { TLS.clientSupported = def { TLS.supportedCiphers = TLS.ciphersuite_all , TLS.supportedHashSignatures = hashSignatures , TLS.supportedVersions [ TLS10 , TLS11 , TLS12 ] } , TLS.clientShared = def { TLS.sharedCAStore = scs , TLS.sharedValidationCache = validationCache } } hashSignatures = [ (TLS.HashSHA512, TLS.SignatureRSA) , (TLS.HashSHA384, TLS.SignatureRSA) , (TLS.HashSHA256, TLS.SignatureRSA) , (TLS.HashSHA224, TLS.SignatureRSA) , (TLS.HashSHA1, TLS.SignatureRSA) , (TLS.HashSHA1, TLS.SignatureDSS) " bad SignatureECDSA for ecdhparams " " bad SignatureECDSA for ecdhparams " , (TLS.HashSHA256, TLS.SignatureECDSA) , (TLS.HashSHA224, TLS.SignatureECDSA) , (TLS.HashSHA1, TLS.SignatureECDSA) ] validationCache = if not validateSsl then TLS.ValidationCache (\_ _ _ -> return TLS.ValidationCachePass) (\_ _ _ -> return ()) else def
3f7010936ec07bc382bacd368a6be7e57edf8dfa7f4255315f28fbbd6815dd3a
GaloisInc/flexdis86
Flexdis86.hs
| Module : $ Header$ Copyright : ( c ) Galois , Inc , 2016 Maintainer : Top - level module for . Module : $Header$ Copyright : (c) Galois, Inc, 2016 Maintainer : Top-level module for Flexdis. -} module Flexdis86 ( module Flexdis86.InstructionSet , module Flexdis86.Prefixes , module Flexdis86.Register , module Flexdis86.Relocation , module Flexdis86.Segment , module Flexdis86.Operand * , disassembleInstruction , tryDisassemble , disassembleBuffer , D.DisassembledAddr(..) , module Flexdis86.ByteReader -- * Assembler , mkInstruction , A.assembleInstruction , A.InstructionEncodingException(..) ) where import Control.Monad ( MonadPlus ) import qualified Data.ByteString as B import qualified Flexdis86.Assembler as A import Flexdis86.ByteReader import Flexdis86.DefaultParser import qualified Flexdis86.Disassembler as D import Flexdis86.InstructionSet import Flexdis86.Operand import Flexdis86.Prefixes import Flexdis86.Register import Flexdis86.Relocation import Flexdis86.Segment | Parse instruction using byte reader . disassembleInstruction :: ByteReader m => m InstructionInstance disassembleInstruction = D.disassembleInstruction defaultX64Disassembler -- | Try disassemble returns the numbers of bytes read and an instruction instance. tryDisassemble :: B.ByteString -> (Int, Maybe InstructionInstance) tryDisassemble = D.tryDisassemble defaultX64Disassembler disassembleBuffer :: B.ByteString -- ^ Buffer to decompose -> [D.DisassembledAddr] disassembleBuffer = D.disassembleBuffer defaultX64Disassembler | Create zero or more instruction instances from a string and arguments . mkInstruction :: MonadPlus m => String -- ^ Mnemonic -> [Value] -- ^ Arguments -> m InstructionInstance mkInstruction = A.mkInstruction defaultX64Assembler
null
https://raw.githubusercontent.com/GaloisInc/flexdis86/9bd6fc6a9480d2ea0cd22d04fd5a5e4ae532504a/src/Flexdis86.hs
haskell
* Assembler | Try disassemble returns the numbers of bytes read and an instruction instance. ^ Buffer to decompose ^ Mnemonic ^ Arguments
| Module : $ Header$ Copyright : ( c ) Galois , Inc , 2016 Maintainer : Top - level module for . Module : $Header$ Copyright : (c) Galois, Inc, 2016 Maintainer : Top-level module for Flexdis. -} module Flexdis86 ( module Flexdis86.InstructionSet , module Flexdis86.Prefixes , module Flexdis86.Register , module Flexdis86.Relocation , module Flexdis86.Segment , module Flexdis86.Operand * , disassembleInstruction , tryDisassemble , disassembleBuffer , D.DisassembledAddr(..) , module Flexdis86.ByteReader , mkInstruction , A.assembleInstruction , A.InstructionEncodingException(..) ) where import Control.Monad ( MonadPlus ) import qualified Data.ByteString as B import qualified Flexdis86.Assembler as A import Flexdis86.ByteReader import Flexdis86.DefaultParser import qualified Flexdis86.Disassembler as D import Flexdis86.InstructionSet import Flexdis86.Operand import Flexdis86.Prefixes import Flexdis86.Register import Flexdis86.Relocation import Flexdis86.Segment | Parse instruction using byte reader . disassembleInstruction :: ByteReader m => m InstructionInstance disassembleInstruction = D.disassembleInstruction defaultX64Disassembler tryDisassemble :: B.ByteString -> (Int, Maybe InstructionInstance) tryDisassemble = D.tryDisassemble defaultX64Disassembler disassembleBuffer :: B.ByteString -> [D.DisassembledAddr] disassembleBuffer = D.disassembleBuffer defaultX64Disassembler | Create zero or more instruction instances from a string and arguments . mkInstruction :: MonadPlus m => String -> [Value] -> m InstructionInstance mkInstruction = A.mkInstruction defaultX64Assembler
5d9022d90ecf7e040abe2c73a33ae1de66a0cd7d7c01fb2c6349e938fafc9c72
dancrossnyc/multics
e_interact_.lisp
;;; *********************************************************** ;;; * * * Copyright , ( C ) Honeywell Bull Inc. , 1988 * ;;; * * * Copyright , ( C ) Honeywell Information Systems Inc. , 1982 * ;;; * * * Copyright ( c ) 1978 by Massachusetts Institute of * * Technology and Honeywell Information Systems , Inc. * ;;; * * ;;; *********************************************************** ;;; ;;; ;;; e_interact_ ;;; ;;; All that of the basic editor which deals with being interactive ;;; commands, prefixes, etc., as opposed to being an editor. ;;; HISTORY COMMENTS: 1 ) change(84 - 01 - 30,Margolin ) , approve ( ) , audit ( ) , install ( ): ;;; pre-hcom history: ;;; Split off from e_ when he grew too gravid. ;;; BSG 8/4/78 ;;; Modified 1978.11.27-29 to reorganize interrupt stuff, etc. by rsl. Macro facility redone 2/11/79 by BSG . Modified 06/20/79 by GMP for CTL prologue / epilogue handlers . ;;; Modified 08/21/79 by GMP for negative arguments. Modified : August 1979 by GMP for new command invocation mechanism . Modified : June 1981 by RMSoley for understanding of emacs _ call . Modified : July 1981 RMSoley for pl1 argument parsing , and support ;;; of multiple emacs's, tasking. Modified : March 1982 RMSoley for undo . Modified : June 1982 B - get - top - level - char - innards nulls ;;; out previous-command after echo-negotiation. Also, last-input-char ;;; is maintained by get-a-char, not process-char, so it is more correct . Added JSL 's new command executor stuff . ;;; Set up the &undo property on more commands. Modified : 25 November 1983 to add " ^ [ " as a valid ;;; escape prefix in parse-key-description. Modified : 19 January 1984 to comment out register - option ;;; forms, as they were moved to e_option_defaults_. Modified : 19 January 1984 Barmar to reject esc-<number > in genset - key . Modified : 30 January 1984 Barmar to fix kmacro - display - interpret to properly interpret " ESC + NUM " and meta characters . 2 ) change(84 - 12 - 25,Margolin ) , approve(86 - 02 - 24,MCR7186 ) , ;;; audit(86-08-12,Harvey), install(86-08-20,MR12.0-1136): ;;; to fix wrong-type-arg error in multiplier command , change lambda into let , use defmacro . 3 ) change(84 - 12 - 26,Margolin ) , approve(86 - 02 - 24,MCR7186 ) , ;;; audit(86-08-12,Harvey), install(86-08-20,MR12.0-1136): ;;; to fix bug in the rewrite of permanently-set. 4 ) change(84 - 12 - 30,Margolin ) , approve(86 - 02 - 24,MCR7186 ) , ;;; audit(86-08-12,Harvey), install(86-08-20,MR12.0-1136): ;;; to remove top-level setq of ;;; suppress-remarks, as it has been set in e_option_defaults_; changed ;;; set-emacs-interrupt to grow the handler and handle arrays if ;;; necessary, changed extended-command to ignore null command lines, ;;; fixed some problems in key binding management, changed special ;;; declaration to defvar, moved %include's to before declarations. 5 ) change(88 - 01 - 07,Schroth ) , approve(88 - 02 - 29,MCR7851 ) , ;;; audit(88-06-08,RBarstad), install(88-08-01,MR12.2-1071): Implement 8 - bit extended ASCII I / O. Used ' new ' macros in various ;;; places to improve readibility. 6 ) change(88 - 01 - 07,Schroth ) , approve(88 - 02 - 29,MCR7852 ) , ;;; audit(88-06-08,RBarstad), install(88-08-01,MR12.2-1071): Added support for split - screen display : revert to one split on ;;; exit and restore screen splits when later restarted. ;;; END HISTORY COMMENTS (declare (genprefix /!eia_)) (%include e-macros) (%include backquote) (%include defmacro) (declare (macros nil)) (%include e-define-command) (%include other_other) (%include sharpsign) (declare (*lexpr display-error display-com-error display-error-noabort display-com-error-noabort minibuffer-print minibuffer-print-noclear minibuffer-remark)) (declare (*expr DCTL-epilogue DCTL-prologue assert-minor-mode clear-the-screen convert_status_code_ cur-hpos decimal-rep display-init e_argument_parse_$get_one_path e_pl1_$init e_argument_parse_$get_startup_info e_argument_parse_$new_arguments e_lap_$rtrim e_lap_$trim e_pl1_$assign_channel e_pl1_$dump_output_buffer e_pl1_$echo_negotiate_get_char e_pl1_$get_char e_pl1_$get_editing_chars e_pl1_$get_emacs_interrupt e_pl1_$get_emacs_interrupt_array e_pl1_$real_have_chars e_pl1_$set_break_char e_pl1_$set_emacs_tty_modes e_pl1_$set_multics_tty_modes e_tasking_$destroy_me e_pl1_$set_extended_ascii e_pl1_$get_output_conv_table e_tasking_$get_tasking_flag e_tasking_$quit echo-buffer-clear echo-buffer-clear-all echo-buffer-outprint echo-buffer-print echo-buffer-rubout echo-buffer-utter editor-main-init emacs$set_emacs_return_code empty-buffer-p end-local-displays error_table_ exists-file find-file-subr full-redisplay get-buffer-state go-to-or-create-buffer init-local-displays intern-minibuf-response jetteur-des-gazongues lisp-quit-function loadfile local-display-generator-nnl map-over-emacs-buffers minibuf-response negate-minor-mode nullstringp randomize-redisplay rdis-find-non-displayable redisplay ring-tty-bell set-autoload-lib set-lisp-rdis-meters user_info_$homedir user_info_$whoami yesp)) (declare (array* (notype (key-bindings 256. 2)))) (declare (array* (notype (saved-command-history 50.)))) (array saved-command-history t 50.) ;;; The key binding arrays. ;;; These are created and initialized at dump time so that the ;;; user needn't wait through them at startup time. (array key-bindings t 256. 2) (fillarray 'key-bindings '(undefined-command)) (array alternate-key-bindings t 256. 2) (fillarray 'alternate-key-bindings '(undefined-command)) (setq permanize-key-bindings t) (defvar ( tty is a TELNET connection *transparent-commands* ;never becomes previous-command last-time-sample ;for command bell command-bell ;option for command bell command-bell-count ;also meter-commands ;option for command metering for complete - command , ESC - SPACE tty-type ;Terminal type. NowDumpingEmacs ;t at dump time tasking-emacs ;t if we are running tasked. tasking-restarted ;t if we've been restarted. emacs-name ;called name of this incarnation: emacs / new_emacs / emacs _ suppress utterances by quit-on-break ;whether or not to quit on typed BREAK ;during emacs_ invocation. documentation-dir ;for help command history-next-index ;for command history next-multics-argno buffer-minor-modes ;used for checking macro hack buffer-modified-flag suppress-redisplay-flag ;controls whether redisplay is enabled e-quit-transparency ;Allows quits not to screen-hack terminal needs hacking on setting Emacs tty modes DCTL-epilogue-availablep ;terminal needs hacking on setting Multics tty modes delayed-interrupt ;interrupt went off in minibuffer damaged-flag ;redisplay, do all the work! in . known-buflist ;list of known buffers kparse-list ;used in key parsing. numarg ;numeric argument to current function, or nil if none undo ;whether or not to undo; like numarg list of MCS escape ( \ ) , erase ( # ) , and kill ( @ ) characters MCS-escape-character ;MCS escape character (\) emacs-epilogue-action-list ;things to be done on exit last-input-char ;current char, for self-inserts last-command-triplet-1 ;current/last command being executed last-command-triplet-mpfxk ;continuation of above, encoded. current-buffer ;symbol name of current buffer list-of-known-options ;for option mechanism, list thereof. macrostack ;format is (macro restart count) macro-collection-in-progress last-macro-definition pointer on current xec list nobreak-functions ;functions that don't break echnego as it says , assq list permanize-key-bindings ;on at init time, until start-up over previous-buffer ;buffer we came from current-command ;command being executed last command invoked in this Emacs previous-argument-list ;argument list used to invoke last cmd user-display-variable ;for user opinion on mode line locechnego-ctr ;meters locechnego-meter next-interrupt-channel ;lowest unused entry in interrupt handler table recursion-level ;records when interrupt handler may cause a redisplay e-lisp-error-mode ;how to treat lisp errors inhibit-default-start-up-execution emacs-start-ups-need-running NLCHARSTRING ;a newline as string object TAB ;ascii TAB ESC ;ascii escape CRET ;carriage return symbol CR ;that too NL Formfeed VT ;Vertical Tab put in mbuf by pi - handler args:apply-arg args:ns args:paths args:ll args:pl tasking-arg terminal can do 8bit ASCII 177 normally or 377 if 8 - bit )) (defvar ( split-mode-p ;on if split screens )) (declare (*expr rdis-restore-screen-to-one-split rdis-recreate-splits-on-screen)) (defun display-load-time-error n (princ (apply 'catenate (listify n))) (terpri) (break load-time-error t)) (putprop 'display-error '(lambda n (apply 'display-load-time-error (listify n))) 'expr) (putprop 'minibuffer-print '(lambda n (apply 'display-load-time-error (listify n))) 'expr) Macros to test bits in left - half of a fixnum : ( tlnX value mask ) (defmacro tlnn (value mask) ;t if any bit is on `(not (tlne ,value ,mask))) (defmacro tlne (value mask) ;t if all bits are off `(zerop (logand ,value (lsh ,mask 18.)))) ;;; ;;; ;;; Character function binding generators. ;;; (defmacro permanently-set (&body forms) `(let ((permanize-key-bindings t)) .,forms)) (defcom set-perm-key &arguments ((key &symbol &prompt "Key: ") (function &symbol &prompt "Function: ")) &numeric-argument (&reject) (permanently-set (set-key key function))) (defcom-synonym set-permanent-key set-perm-key) (defcom set-key &arguments ((key &symbol &prompt "Key: ") (function &symbol &prompt "Function: ")) &numeric-argument (&reject) (let ((result (parse-key-description key))) (genset-key (caddr result) (car result) (cadr result) function))) ;;; ;;; This is the setter of all keys. ;;; (defvar permit-setting-esc-number nil) (defun genset-key (prefix metap key function) (or permit-setting-esc-number (= metap 0) (and (not (= key (CtoI "+"))) (not (= key (CtoI "-"))) (or (< key (CtoI "0")) (> key (CtoI "9")))) ;; esc-<number> (display-error "esc-<number> may not be bound.")) (and (or prefix (= metap 1)) (> key (1- (CtoI "a"))) (< key (1+ (CtoI "z"))) (setq key (- key 40))) (cond (prefix (or (not (symbolp (key-bindings prefix 0))) (genset-key nil 0 prefix (let ((x (fillarray (*array (gensym) t 256.) '(undefined-command)))) (store (x 7) 'ignore-prefix) x))) ;make ^G punt prefix only (setq metap (key-bindings prefix 0)) ; this is array. (cond (permanize-key-bindings (remove-local-key-binding 0 key prefix)) ;override ((arraycall t metap key) ;one there already (update-perm-key-bindings 0 key prefix (arraycall t metap key)) (update-local-key-bindings 0 key prefix function))) (store (arraycall t metap key) function)) (t (cond (permanize-key-bindings (remove-local-key-binding metap key nil)) ((key-bindings key metap) (update-perm-key-bindings metap key nil (key-bindings key metap)) (update-local-key-bindings metap key nil function))) (or NowDumpingEmacs (cond ((memq (key-bindings key metap) nobreak-functions) (e_pl1_$set_break_char key 1))) (cond ((memq function nobreak-functions) (e_pl1_$set_break_char key 0)))) (store (key-bindings key metap) function)))) (defun update-perm-key-bindings (metap key prefix function) (let ((keyrep (key-total-printed-symbol metap key prefix))) (or (and (not permanize-key-bindings) ;this redundant clause is a way out (assq keyrep per-buffer-key-bindings)) ;dont overpush (putprop keyrep function 'perm-key-function)))) (defun update-local-key-bindings (metap key prefix function) (let ((keyrep (key-total-printed-symbol metap key prefix)) (listrep (key-fixnum-rep-encode metap key prefix))) (let ((assq-answer (assq keyrep per-buffer-key-bindings))) (cond (assq-answer (rplaca (cdr assq-answer) function)) (t (setq per-buffer-key-bindings (cons (cons keyrep (cons function listrep)) per-buffer-key-bindings))))))) (defun remove-local-key-binding (metap key prefix) (let ((key-symbol (key-total-printed-symbol metap key prefix))) (let ((assq-answer (assq key-symbol per-buffer-key-bindings))) (if assq-answer (setq per-buffer-key-bindings (delq assq-answer per-buffer-key-bindings)))))) (defun key-total-printed-symbol (metap key prefix) (intern (make_atom (cond (prefix (catenate (printable prefix)(printable key))) ((= 0 metap)(printable key)) (t (catenate "esc-" (printable key))))))) ;;; Get printable name of a key (defun get-key-name (key-list) (apply 'key-total-printed-symbol key-list)) (defun key-fixnum-rep-encode (metap key prefix) (list metap key prefix)) (defun reorganize-local-key-bindings (revert) (let ((permanize-key-bindings t) (saved-local-bindings (append per-buffer-key-bindings nil))) ;copy list (unwind-protect (progn (mapc '(lambda (x) (prog (y) (setq y (cond (revert (get (car x) 'perm-key-function)) (t (cadr x)))) -non - prefix first (genset-key nil (car (cddr x)) (cadr (cddr x)) y)))) per-buffer-key-bindings) (mapc '(lambda (x) (prog (y) (setq y (cond (revert (get (car x) 'perm-key-function)) (t (cadr x)))) (and (caddr (cddr x)) ; prefixed ones (genset-key (caddr (cddr x)) 0 (cadr (cddr x)) y)))) per-buffer-key-bindings)) (setq per-buffer-key-bindings saved-local-bindings)))) (defun revert-local-key-bindings ()(reorganize-local-key-bindings t)) (defun instate-local-key-bindings ()(reorganize-local-key-bindings nil)) (defun printable (x) (let ((y (cond ((numberp x) x) (t (getcharn x 1))))) 8 - bit or META ((= y 33) "ESC") ((= y 15) "CR") ((= y 177) "\177") ((= y 40) "SPACE") ((< y 40) (catenate "^" (ascii (bit-set 100 y)))) ((numberp x)(ascii x)) (t x)))) (defun printable-8-bit-char (ch-num) the display rep of char that is either an 8 - bit ASCII or a meta char (cond (DCTL-extended-ascii (printable-extended-ascii ch-num)) (t (printable-meta-char ch-num)))) (defun printable-extended-ascii (ch-num) returns the display representation of an 8 - bit ASCII code (let ((ch (ascii ch-num))) (cond ((> (rdis-find-non-displayable ch 1 0) 0) ch) ;displayable (t (catenate "ext-" (printable (bit-clear 200 ch-num))))))) ;not displayable (defun printable-meta-char (ch-num) ;; returns the display rep of a meta-char ;; For R11/ITS telnet ^_l (catenate "meta-" (printable (bit-clear 200 ch-num)))) (defun prinkeyrep-to-num (x) (cadr (parse-key-description x))) ;compatibility ;;; Swaps "alternate-key-bindings" (the emacs_ table) with "key-bindings," ;;; the standard full-emacs table. (defun swap-binding-tables () (do a 0 (1+ a) (= a 2) (do b 0 (1+ b) (= b 256.) (store (key-bindings b a) (prog1 (alternate-key-bindings b a) (store (alternate-key-bindings b a) (key-bindings b a))))))) ;;; ;;; Full-hog key parser, BSG 8/5/78 Saturday morning . ;;; (defun parse-key-description (desc) ;returns (m k p) (prog (prefix metap key) (setq kparse-list (exploden desc)) ;char-by-char (cond ((or (parse-key-match-list '(e s c a p e -)) (parse-key-match-list '(e s c -)) (parse-key-match-list '(m e t a -)) (parse-key-match-list '(m -)) (parse-key-match-list '(^ [ -)) (parse-key-match-list '(^ [))) (setq metap 1)) (t (setq metap 0) try for 1 frob . (or kparse-list (return (list 0 prefix nil))) ;non-meta, non-prefix (parse-key-match-list '(-)) ;rip out minus (or kparse-list (kparse-error desc)) (or (< prefix (CtoI " ")) (kparse-error (catenate (printable prefix) " may not be a prefix character."))))) (setq key (parse-key-description-syllable desc)) (and (or (= 1 metap) prefix) (> key (1- (CtoI "a"))) (< key (1+ (CtoI "z")))(setq key (- key 40))) (and kparse-list (kparse-error desc)) (return (list metap key prefix)))) (defun parse-key-description-syllable (desc) (cond ((not kparse-list)(kparse-error desc)) control frob , = " ^ " (setq kparse-list (cdr kparse-list)) (cond ((not kparse-list) 136) ;plain old hat (t (parse-key-controllify)))) ((or (parse-key-match-list '(c -)) (parse-key-match-list '(c t l -)) (parse-key-match-list '(c o n t r o l -))) (parse-key-controllify)) added Dec 84 EDSchroth (or (parse-key-match-list '(x -)) (parse-key-match-list '(e x t -)) (parse-key-match-list '(e x t e n d e d -)))) (parse-key-extendify desc)) ;make it an extended ASCII ((parse-key-match-list '(e s c)) 33) ((parse-key-match-list '(c r)) 15) ((parse-key-match-list '(\ /1 /7 /7)) 177) ((parse-key-match-list '(t a b)) 11) ((parse-key-match-list '(s p a c e)) 40) ((parse-key-match-list '(s p)) 40) (t (prog1 (car kparse-list) (setq kparse-list (cdr kparse-list)))))) (defun parse-key-controllify () (or kparse-list (kparse-error "Unspecified control character.")) (let ((kdesc (car kparse-list))) (and (> kdesc (1- (CtoI "a"))) (< kdesc (1+ (CtoI "z"))) (setq kdesc (- kdesc 40))) (or (and (< kdesc (1+ (CtoI "_"))) (> kdesc (1- (CtoI "@")))) (kparse-error (catenate "^" (ascii kdesc) " is not ASCII."))) (setq kparse-list (cdr kparse-list)) (- kdesc 100))) Handles extended ascii key descriptions . Dec 84 EDSchroth (defun parse-key-extendify (desc) (or kparse-list (kparse-error "Unspecified extended character.")) make 8 - bit ASCII (defun parse-key-match-list (matchee) (do ((data kparse-list (cdr data)) (pattern matchee (cdr pattern)) (chara)(charb)(chardata)) ((null pattern)(setq kparse-list data) t) (or data (return nil)) ;nothing more (setq chardata (car data)) (setq chara (getcharn (car pattern) 1)) (setq charb (cond ((and (< chara (1+ (CtoI "z"))) (> chara (1- (CtoI "a")))) (- chara 40)) (t chara))) (or (= chardata chara)(= chardata charb)(return nil)))) (defun kparse-error (desc) (display-error "Invalid key description: " desc)) ;;; ;;; Randomness ;;; (setq NLCHARSTRING (ItoC 012) ESC (ascii 033)) (setq TAB (ascii 011) BACKSPACE (ascii 010) SPACE (ascii 040) CR (ascii 15) CRET (ascii 015) NL (ascii 012) FF (ascii 14) VT (ascii 13)) ;;; ;;; Initialize the option mechanism first . ;;; (setq list-of-known-options nil) (defun require-symbol (putative-symbol) (cond ((not (symbolp putative-symbol)) (display-error "This function requires a symbol.")))) (defun register-option (sym val) (require-symbol sym) (or (memq sym list-of-known-options) (setq list-of-known-options (sort (cons sym list-of-known-options) 'alphalessp))) (remprop sym 'value-must-be-numeric) (remprop sym 'value-ok-true-false) (or (boundp sym)(set sym val))) ;;;(register-option 'eval:eval t) ; Unfortunately ;;; moved to e_option_defaults_ ;;;(register-option 'eval:assume-atom nil) ;;; moved to e_option_defaults_ ;;;(register-option 'eval:correct-errors nil) ;;; moved to e_option_defaults_ ( register - option ' eval : prinlevel 3 ) ; ; ; moved to e_option_defaults _ ( register - option ' eval : 6 ) ; ; ; moved to e_option_defaults _ ;;; ;;; Listener ;;; and toplevels. ;;; (defun listener-level () (start) (std-yggdrasil)) (defun start () 11/3/80 (setq e-quit-transparency nil) Lisp errors to minibuf (and (eq emacs-name 'emacs_) (swap-binding-tables)) (get-editing-characters) ;read erase, kill, escape chars (editor-main-init) ;init the guts of the editor. (or (boundp 'next-multics-argno) (setq next-multics-argno 1)) (setq history-next-index 0) (setq macro-collection-in-progress nil previous-command nil last-macro-definition nil) (setq emacs-epilogue-action-list nil) (sstatus cleanup '((run-emacs-epilogue-actions))) (*rset nil) (e_pl1_$set_emacs_tty_modes) (sstatus mulpi t) (sstatus interrupt 16. 'emacs-quit-handler) (sstatus mulquit 16.) (init-echnego-bittab) (setq errlist '((pi-handler))) ;CTRL/g escapes lossages init rsl 's hack . (display-init) ;initialize the redisplay fix up for possible 8 - bit And the PL / I redisplay . (interrupt-init) ;And the interrupt scheme. (setq permanize-key-bindings nil) (reset-top-level-editor-state) (setq emacs-start-ups-need-running t)) Initialize the 8 - bit printing character scan table at dump time ;;; This should be in e_redisplay_ but is done here as the per invocation ;;; stuff is done here. (declare 7bit non - printing 8bit non - printing (defvar 7bit-tabscan-table (fillarray (*array '7bit-tabscan-table 'fixnum 128.) '(-1))) (defvar 8bit-tabscan-table (fillarray (*array '8bit-tabscan-table 'fixnum 128.) '(-1))) 040 ... 173 print nicely ((= i 31.)) (store (arraycall fixnum 7bit-tabscan-table i) 0) (store (arraycall fixnum 8bit-tabscan-table i) 0)) nix 177 nix 177 ;;; Takes care of per invocation set-up for extended ASCII Dec 1984 EDSchroth (defun init-extended-ascii-land () (setq char-input-mask 177) the ctl knows about 8 - bit ! (setq char-input-mask 377) (e_pl1_$set_extended_ascii 1) add 8 - bit self - inserts based on TTT output conversion table Also , define 8 - bit non - printing scan table (let ((convtab (*array nil 'fixnum 64.))) (e_pl1_$get_output_conv_table convtab) do 8 - bit chars only (next-byte-of (rot 777 -9.) (rot next-byte-of -9.))) ;successive bytes stop after # o377 (or (bit-test next-byte-of (arraycall fixnum convtab (// i 4))) ;pick a byte if zero copy entries for 200 ... 377 ((= i 64.)) ;to scan table (store (arraycall fixnum 8bit-tabscan-table i) (arraycall fixnum convtab i)))) (e_pl1_$set_emacs_tty_modes)))) ;fix-up modes (defvar emacs-start-up-error-message) (defun run-emacs-start-up-error (arg) arg (display-error-noabort emacs-start-up-error-message) (throw () emacs-start-up-tag)) (defun run-emacs-start-up-actions () (setq inhibit-default-start-up-execution nil) (or (eq emacs-name 'emacs_) (run-user-start-up (catenate (e_lap_$trim (user_info_$homedir)) ">start_up.emacs")) (run-user-start-up (catenate (user-project-dir) ">start_up.emacs")) (run-user-start-up ">site>start_up.emacs")) (and (eq emacs-name 'emacs_) (go-to-or-create-buffer 'main)) (or inhibit-default-start-up-execution (default-emacs-start-up)) (cond ((eq current-buffer '|<start_up_emacs_buffer>|) (go-to-or-create-buffer 'main) (setq previous-buffer 'main)) ((eq previous-buffer '|<start_up_emacs_buffer>|) (setq previous-buffer current-buffer))) (setq known-buflist (delq '|<start_up_emacs_buffer>| known-buflist))) (defun user-project-dir () (catenate ">user_dir_dir>" (e_lap_$trim (cadr (user_info_$whoami))))) (defun run-user-start-up (filename) (cond (args:ns 't) ((exists-file filename 4) (setq emacs-start-up-error-message "Error in start_up.emacs") (catch (let ((e-lisp-error-mode 'run-emacs-start-up-error)) (loadfile filename)) emacs-start-up-tag) 't) ('else nil))) Re - written by GMP , 9/4/78 . Re - written by RMSoley , 21 July 1981 (defun default-emacs-start-up () (setq inhibit-default-start-up-execution t) ;; File-file the pathnames and macro files. (do ((paths args:paths (1- paths))) ((zerop paths)) (let ((info (e_argument_parse_$get_one_path))) (cond ((zerop (cadr info)) (setq emacs-start-up-error-message (catenate "Can't load file " (car info))) (catch (let ((e-lisp-error-mode 'run-emacs-start-up-error)) (load (e_lap_$trim (car info)))) emacs-start-up-tag)) (t (catch (find-file-subr (e_lap_$trim (car info))) pgazonga))))) ;; Do -apply arguments. (cond ((> args:apply-arg -1) (setq emacs-start-up-error-message "Can't do -apply.") (catch (let ((e-lisp-error-mode 'run-emacs-start-up-error)) (apply (make_atom (status arg args:apply-arg)) (multics-args-as-list (1+ args:apply-arg)))) emacs-start-up-tag))) (and tasking-restarted (full-redisplay)) (setq tasking-restarted nil)) (defun multics-args-as-list (first-argno) (do ((count first-argno (1+ count)) (l)) ((not (status arg count)) (nreverse l)) (setq l (cons (status arg count) l)))) (setq pi-handler-minibuffer-print nil tasking-restarted nil) (defun pi-handler () (e_pl1_$set_emacs_tty_modes) (randomize-redisplay) (and DCTL-prologue-availablep (DCTL-prologue)) (and split-mode-p (rdis-recreate-splits-on-screen)) (reset-top-level-editor-state) (cond ((zerop (e_argument_parse_$new_arguments)) (full-redisplay)) (t (tasking-restart-internal))) (cond (pi-handler-minibuffer-print (minibuffer-print pi-handler-minibuffer-print) (setq pi-handler-minibuffer-print nil))) (std-yggdrasil)) (defun reset-top-level-editor-state () (or minibufferp (instate-local-key-bindings)) (setq suppress-redisplay-flag nil) ;restart redisplay if stopped (cond ((memq 'Macro/ Learn buffer-minor-modes) (negate-minor-mode 'Macro/ Learn))) (setq damaged-flag t ;force redisplay to work on it numarg nil undo nil macro-execution-in-progress nil macro-collection-in-progress nil macrostack nil) (or minibufferp (setq recursion-level 0))) Modified 28 June 1981 RMSoley to use set_break_sequence Modified Dec 1984 EDSchroth for 8bit ASCII . ;;; Extended chars break echonego by default (defun init-echnego-bittab () (do ((char 0 (1+ char)) (number 0) (nlist ()) (count 0 (1+ count))) ((= char 256.) (apply 'e_pl1_$set_break_sequence (nreverse (cons number nlist)))) (and (not (zerop char)) (zerop (\ count 32.)) (setq nlist (cons number nlist) count 0 number 0)) (setq number (lsh number 1)) (or (and (> char 31.) (< char 127.) (memq (key-bindings char 0) nobreak-functions)) (setq number (1+ number))))) (defcom debug-e &numeric-argument (&reject) (*rset t) (nouuo t) (sstatus uuolinks nil) ;et in saecula saeculorum amen (setq e-lisp-error-mode 'lisp-break) (sstatus mulpi 1) ;pi -> ^b interrupt (sstatus interrupt 2 '(lambda (z)(pi-handler) z))) ;CTRL/a -> reenter (defun get-editing-characters () (let ((editing-chars (e_pl1_$get_editing_chars))) (setq MCS-editing-characters (mapcar 'CtoI editing-chars) MCS-escape-character (car editing-chars)) (set-editing-key (car editing-chars) 'escape-char) (set-editing-key (cadr editing-chars) 'rubout-char) (set-editing-key (caddr editing-chars) 'kill-to-beginning-of-line))) (defun set-editing-key (character function) (cond ((eq (get-key-binding (parse-key-description character)) 'self-insert) (set-perm-key character function)))) ;;; ;;; Following is all of Multics EMACS. ;;; (defun std-yggdrasil () ;Root tree of universe (do ()(nil) ceci est jet'e ;seulement par ^G (redisplay) ;gratuitous (ring-tty-bell) (reset-top-level-editor-state))) (defun charlisten () (let ((recursion-level recursion-level)) (do nil (nil) (or macro-execution-in-progress emacs-start-ups-need-running (redisplay)) (catch (errset (let ((fail-act 'e-lisp-lossage-handler) (pdl-overflow 'e-lisp-lossage-handler) (wrng-type-arg 'e-lisp-lossage-handler) (*rset-trap 'e-lisp-lossage-handler) (unbnd-vrbl 'e-lisp-lossage-handler) (undf-fnctn 'e-lisp-lossage-handler) (unseen-go-tag 'e-lisp-lossage-handler) (wrng-no-args 'e-lisp-lossage-handler) (errset 'e-lisp-lossage-handler)) (cond ((eq emacs-start-ups-need-running t) (setq emacs-start-ups-need-running nil) (run-emacs-start-up-actions)) (emacs-start-ups-need-running (funcall (prog1 emacs-start-ups-need-running (setq emacs-start-ups-need-running nil))))) (do ((numarg nil nil) (undo nil nil)) (nil) (process-char (get-top-level-char)))) nil) pgazonga) (reset-top-level-editor-state)))) (defun e-lisp-lossage-handler (arg) (setq arg (caddr (errframe nil))) (cond (e-quit-transparency (errprint nil)) (t (minibuffer-print (car arg) " " (maknam (explodec (cadr arg)))))) (cond ((eq e-lisp-error-mode 'lisp-break) (let ((e-quit-transparency 'transparent)) (e_pl1_$set_multics_tty_modes) (terpri)(terpri) (princ (catenate "Lisp error in buffer " current-buffer)) (terpri) (setq arg (eval (list 'break (caddr arg) t))) (e_pl1_$set_emacs_tty_modes) (full-redisplay)) (cond (arg)(t (command-prompt-abort)))) ((null e-lisp-error-mode)(command-quit)) (t (funcall e-lisp-error-mode arg)))) (defcom lisp-error-mode &arguments ((mode &symbol &prompt "Mode: " ;&valid on off, when ready &default off)) ;default to "normal" &numeric-argument (&reject) (cond ((memq mode '(nil reset off 0)) ;ick (setq e-lisp-error-mode nil)) ((memq mode '(t set on 1 lisp-break)) (setq e-lisp-error-mode 'lisp-break)) (t (display-error "Unknown lisp error mode: " mode)))) ;;; ;;; ;;; Character readers ;;; (declare (array* (notype (emacs-interrupt-handlers ?)(emacs-interrupt-handles ?)) (fixnum (emacs-interrupt-array ?)))) (defun get-top-level-char () (get-a-char 'toplevel-char 'get-top-level-char-innards)) (defun get-char () (get-a-char 'input-char 'e_pl1_$get_char)) (defun get-a-char (type get-char-function) (let ((new-ch (cond ((and macro-execution-in-progress (kmacro-get-one-cmd type))) (t (do ((ch (funcall get-char-function) (funcall get-char-function))) (nil) (or (= 0 (emacs-interrupt-array 0)) (setq delayed-interrupt t)) (store (emacs-interrupt-array 0) 0) (and (not minibufferp) delayed-interrupt (emacs-interrupt-processor)) (or (= ch -1) (progn (store (saved-command-history history-next-index) ch) (setq history-next-index (cond ((= history-next-index 49.) 0) (t (1+ history-next-index)))) (and macro-collection-in-progress (kmacro-record-input ch type)) (return ch)))))))) last - input - char = char without META new-ch)) ;;; Highly local specials for redisplay ( echo negotiation ) . Goddamn backpanel wires to every board in the machine . (defvar (X howmuchigot-sym rdis-upd-locecho-flg screenlinelen touchy-damaged-flag rdis-suppress-redisplay)) (defvar (rdis-multiwindowed-buflist rdis-inhibit-echnego)) (defvar (curlinel curstuff work-string curpointpos hard-enforce-fill-column fill-column)) (defun get-top-level-char-innards () (let ((ordi rdis-suppress-redisplay) (chpos 0)) THIS NEXT STATEMENT IS PERHAPS THE MOST IMPORTANT IN MULTICS EMACS ;;; IT CAUSES REDISPLAY TO OCCUR WHEN THERE IS NO PENDING INPUT. ;;; ALMOST ALL REDISPLAY IN THE WORLD IS INVOKED RIGHT HERE. (and (= 0 (e_pl1_$real_have_chars))(redisplay)) ;;; Attempt PL/I (and poss. better) echo negotiation. (cond ((and ;try super-opt (eq curstuff work-string) ;line gotta be open (= curpointpos (1- curlinel)) ;gotta be at eol (not macro-collection-in-progress) (not ordi) ;old rdis-suppr-rdis (not suppress-redisplay-flag) (not (and hard-enforce-fill-column (not (< (setq chpos (cur-hpos)) fill-column)))) (not rdis-inhibit-echnego) (prog2 (redisplay) ;update all parms (not (and minibufferp (> X (- screenlinelen 10.))))) (or (not (memq current-buffer rdis-multiwindowed-buflist)) minibufferp)) ;echnego ok minibuf even so (setq locechnego-ctr (1+ locechnego-ctr)) (prog2 (set 'howmuchigot-sym 0) (e_pl1_$echo_negotiate_get_char work-string 'howmuchigot-sym (cond (hard-enforce-fill-column (min (- screenlinelen X) (- fill-column chpos))) (minibufferp (- screenlinelen X 7)) (t (- screenlinelen X)))) (cond ((> howmuchigot-sym 0) (store (saved-command-history history-next-index) (substr work-string (1+ curpointpos) howmuchigot-sym)) (setq history-next-index (cond ((= history-next-index 49.) 0) (t (1+ history-next-index)))) (setq X (+ X howmuchigot-sym)) (setq locechnego-meter (+ locechnego-meter howmuchigot-sym)) (setq curpointpos (+ curpointpos howmuchigot-sym)) (setq curlinel (+ curlinel howmuchigot-sym)) (setq touchy-damaged-flag t) (setq previous-command nil) ;since we never actually execute a command (let ((rdis-upd-locecho-flg t)) (redisplay)))))) (t (e_pl1_$get_char))))) ;;; ;;; interrupt handling integrated into e_interact _ 1978.11.21 by ;;; ;;; ;;; how it works: ;;; There are two types of interrupt numbers , namely ;;; internal and external. Internal numbers are assigned ;;; sequentially from the variable next-interrupt-channel. ;;; Internal numbers are used to index into the array ;;; emacs-interrupt-handlers, and are returned by ;;; e_pl1_$get_emacs_interrupt. External numbers are ;;; assigned by e_pl1_$assign_channel, and are computed ;;; as 64*emacs_recursion_level + internal_number. It is ;;; these external numbers which must be passed to ;;; e_pl1_$set_emacs_interrupt, and therefore it is these ;;; which set-emacs-interrupt-handler returns. ;;; (defun emacs-interrupt-processor () (setq delayed-interrupt nil) (do ((int-info (e_pl1_$get_emacs_interrupt) (e_pl1_$get_emacs_interrupt))) ((< (car int-info) 0) (and (= recursion-level 0) (not rdis-suppress-redisplay) ; don't destroy local display (redisplay))) (let ((intno (car int-info))) (cond ((emacs-interrupt-handlers intno) (funcall (emacs-interrupt-handlers intno) intno (emacs-interrupt-handles intno) (cadr int-info))))))) (defvar max-emacs-interrupt-channel 64.) (defun set-emacs-interrupt-handler (handler handle) ; returns interrupt channel number (setq next-interrupt-channel (1+ next-interrupt-channel)) (if (= next-interrupt-channel max-emacs-interrupt-channel) ;ran out of channels (setq max-emacs-interrupt-channel (* 2 max-emacs-interrupt-channel)) (*rearray 'emacs-interrupt-handlers t max-emacs-interrupt-channel) (*rearray 'emacs-interrupt-handles t max-emacs-interrupt-channel)) (store (emacs-interrupt-handlers next-interrupt-channel) handler) (store (emacs-interrupt-handles next-interrupt-channel) handle) (e_pl1_$assign_channel next-interrupt-channel)) (defun interrupt-init () (*array 'emacs-interrupt-array 'external (e_pl1_$get_emacs_interrupt_array) 2) (*array 'emacs-interrupt-handlers t max-emacs-interrupt-channel) (*array 'emacs-interrupt-handles t max-emacs-interrupt-channel) (setq delayed-interrupt nil) (setq next-interrupt-channel -1)) ;;; ;;; ;;; Functions to print errors/messages in the minibuffer ;;; (defvar (suppress-minibuffer)) ;;;(register-option 'suppress-minibuffer nil) ;;; moved to e_option_defaults_ ;;; Print an error message. (defun display-error-noabort n (or suppress-minibuffer (echo-buffer-print (apply 'catenate (listify n))))) ;;; Print an error message and abort. (defun display-error n (or suppress-minibuffer (apply 'display-error-noabort (listify n))) (command-quit)) Print an error message : first argument is Multics error code . (defun display-com-error-noabort n (or suppress-minibuffer (let ((prefix (cond ((= 0 (arg 1)) "") (t (catenate (e_lap_$rtrim (cadr (convert_status_code_ (arg 1)))) (cond ((> n 1) " ") (t "")))))) (message (cond ((> n 1) (apply 'catenate (listify (- 1 n)))) (t "")))) (echo-buffer-print (catenate prefix message))))) Print an error message and abort : first argument is Multics error code . (defun display-com-error n (apply 'display-com-error-noabort (listify n)) (command-quit)) ;;; Clear out the minibuffer. (defun minibuffer-clear-all () (echo-buffer-clear-all)) ;;; Print a message in the minibuffer. (defun minibuffer-print n (or macro-execution-in-progress suppress-minibuffer (echo-buffer-print (apply 'catenate (listify n))))) ;;; Print a message in the minibuffer without clearing current contents. (defun minibuffer-print-noclear n (or macro-execution-in-progress suppress-minibuffer (echo-buffer-outprint (apply 'catenate (listify n))))) ;;; Delete the last N characters from the minibuffer. (defun minibuffer-rubout (n) (or macro-execution-in-progress (echo-buffer-rubout n))) ;;; Make a very transient remark. (defun minibuffer-remark n (or macro-execution-in-progress suppress-remarks suppress-minibuffer (echo-buffer-utter (apply 'catenate (listify n))))) (defun display-error-remark n (or suppress-minibuffer (echo-buffer-utter (apply 'catenate (listify n))))) ;;; Clear the last minibuffer statement. (defun minibuffer-clear ()(echo-buffer-clear)) ;;; ;;; Self-documentation primitives - see e_self_documentor_. ;;; (defun get-cmd-symbol-3args (metap key prefix) (cond ((and (= metap 1) prefix) nil) ((not prefix) (cond ((subrp (key-bindings key metap)) nil) (t (key-bindings key metap)))) (t (cond ((not (subrp (key-bindings prefix 0))) nil) (t (arraycall t (key-bindings prefix 0) key)))))) ;;; Get the function bound to a key (defun get-key-binding (key-list) (apply 'get-cmd-symbol-3args key-list)) ;;; Read the name of key (defun key-prompt (prompt) (prog (ch1) (minibuffer-print prompt) (setq ch1 (get-char)) (return (cond ((= ch1 377) (setq ch1 (get-char)) (cond ((= ch1 377) (minibuffer-print-noclear "esc-" (printable 177)) '(1 177 nil)) (t (return (telnet-loser ch1))))) ((> ch1 char-input-mask) (minibuffer-print-noclear "esc-") (key-prompt-1 1 (bit-clear 200 ch1) nil)) (t (key-prompt-1 0 ch1 nil)))))) (defun key-prompt-1 (metap key prefix) (prog (mf1) (and (or prefix (= metap 1)) (< key (1+ (CtoI "z")))(> key (1- (CtoI "a"))) (setq key (- key 40))) (setq mf1 (cond (prefix (arraycall t (key-bindings prefix 0) key)) (t (key-bindings key metap)))) (cond ((eq mf1 'escape) (minibuffer-print-noclear "esc-") (return (key-prompt-1 1 (get-char) nil))) ((not (symbolp mf1)) (minibuffer-print-noclear (printable key) " (prefix char): ") (return (key-prompt-1 0 (get-char) key))) (t (minibuffer-print-noclear (printable key)) (return (list metap key prefix)))))) ;;; Compatability (defun key-prompt-3args () (key-prompt "?: ")) ;;; Execute supplied function on all keys defined in current buffer (defun map-over-emacs-commands (fun arg) (do i 0 (1+ i) (= i 256.) ;i hated fortran as a child (do j 0 (1+ j) (= j 2) ;and i hate it now as a programmer. (let ((element (key-bindings i j))) (cond ((not (symbolp element)) (do k 0 (1+ k)(= k 256.) (or (not (arraycall t element k)) (eq (arraycall t element k) 'undefined-command) (funcall fun (key-total-printed-symbol 0 k i) (arraycall t element k) arg)))) ((eq element 'undefined-command)) (element (funcall fun (key-total-printed-symbol j i nil) element arg))))))) ;;; ;;; ESC Processing and Numeric Argument Readers ;;; ;;; Command to quit to editor top level (defcom command-quit &numeric-argument (&ignore) &undo &ignore (ring-tty-bell) (throw 'les-petites-gazongues pgazonga)) ;;; Command to "ignore" a prefix character, by default on prefix-^G (defcom ignore-prefix &undo &ignore &numeric-argument (&ignore) (ring-tty-bell)) ;;; Command to throw to top level or nearest yggdrasil (ldebug, multics mode ;;; are the only others beside top level) (defcom command-prompt-abort &numeric-argument (&ignore) &undo &ignore (throw nil gazongue-a-l/'yggdrasil)) Command bound to ESC key (defcom escape &undo-function &pass &numeric-argument (&pass) (and (eq minibufferp ESC) (jetteur-des-gazongues)) (escape-dont-exit-minibuf)) (defprop throw-to-toplevel jetteur-des-gazongues expr) (defcom-synonym escape-dont-exit-minibuffer escape-dont-exit-minibuf) ;;; Set the undo switch. (defcom undo-prefix &numeric-argument &pass &undo &pass (setq undo (not undo)) (process-char (get-char))) Command that does real work of ESC (defcom escape-dont-exit-minibuf &numeric-argument (&pass) &undo &pass (prog (nxcn numf negate) a (setq nxcn (get-char)) (cond ((and (> nxcn (1- (CtoI "0"))) (< nxcn (1+ (CtoI "9")))) ;number (or numarg (setq numarg 0)) (setq numarg (+ (- nxcn (CtoI "0")) (* 10. numarg))) (setq numf t) (go a)) ((and (not numf) (= nxcn (CtoI "-"))) ;want negative argument (setq negate t numf t) (go a)) ((and (not numf) (= nxcn (CtoI "+"))) ;want positive argument (setq numf t) (go a)) (t (and numf negate ;negative argument (default -1) (setq numarg (- (or numarg 1)))) (cond (numf (process-char nxcn)) (t (execute-key 1 nxcn nil))))))) Command to collect numeric argument or use powers of 4 (defcom multiplier &undo &pass &numeric-argument (&pass) (prog (nxcn numf multf negate plus-given my-char) (setq my-char last-input-char) ;character used to invoke this a (setq nxcn (get-char)) (cond ((and (> nxcn (1- (CtoI "0"))) (< nxcn (1+ (CtoI "9")))) ;number (or numf (setq numf 0)) (setq numf (+ (- nxcn (CtoI "0"))(* 10. numf))) (go a)) ((and (not numf) (= nxcn (CtoI "-"))) ;negative argument (setq numf 0 negate t) (go a)) ((and (not numf) (= nxcn (CtoI "+"))) ;positive argument (setq numf 0 plus-given t) (go a)) ((and (< nxcn 200) (eq (ascii nxcn) my-char)) ;NOTE- this code is buggy (cond ((and (not numf) (not multf)) (setq multf 4)) ((not numf) (setq multf (* multf 4))) (numf (setq numf nil)) (t (setq multf nil numf nil))) (go a)) (t (and (or negate plus-given) (= numf 0) (setq numf 1)) ;default number if only + given (and negate (setq numf (- numf))) ;negate number (with -1 as default) (setq numarg (cond ((and numf multf) (* numf multf)) (numf) (multf (* 4 multf)) (t 4))) (process-char nxcn))))) Read a " metazied " number ( from Network mostly ) (defcom read-meta-argument &undo &pass &numeric-argument (&ignore) (prog (negate nxcn plus-given) (setq nxcn (CtoI last-input-char)) ;get charater invoked by (without meta-bit) (setq numarg 0) (cond ((= nxcn (CtoI "+")) (setq plus-given t)) ((= nxcn (CtoI "-")) (setq negate t)) (t ;assume a digit (setq numarg (- nxcn (CtoI "0"))))) a (setq nxcn (get-char)) (cond ((and (> nxcn (1- (+ 200 (CtoI "0")))) (< nxcn (1+ (+ 200 (CtoI "9"))))) (setq numarg (+ (- nxcn (+ 200 (CtoI "0"))) (* 10. numarg))) (go a)) (t ;have character to execute (and (= numarg 0) (or negate plus-given) (setq numarg 1)) ;a sign given, set default (and negate (setq numarg (- numarg))) (process-char nxcn))))) ;;; ;;; ;;; Character/Key/Command Execution ;;; ;;; Process a character: determine if it is a "meta" character and then ;;; execute the key corresponding to the character (defun process-char (ch) (or (fixp ch) (setq ch (CtoI ch))) (let ((recursion-level (1+ recursion-level))) (cond ((and (not (zerop network-flag)) TELNET IAC (setq ch (get-char)) (cond ((= ch 377) (execute-key 1 177 nil)) (t (telnet-loser ch)))) ((> ch char-input-mask) ;meta-foo (setq ch (logand char-input-mask ch)) ;non-meta foo (execute-key 1 ch nil)) (t (execute-key 0 ch nil))))) Execute a " key " as an Emacs command : A " key " is the triplet consisting ;;; of a character, "meta"-bit, and prefix character used to determine the ;;; exact command to be executed. (defun execute-key (metap ch prefix) (let ((command)) ;the command to execute (and (or (= metap 1) prefix) (and (< ch (1+ (CtoI "z"))) (> ch (1- (CtoI "a"))) (setq ch (- ch 40)))) (cond ((not prefix) (setq command (key-bindings ch metap))) (t (setq command (arraycall t (key-bindings prefix 0) ch)))) (cond ((symbolp command) ;normal command (setq last-command-triplet-mpfxk (cond ((= metap 1) 'meta) (t prefix)) last-command-triplet-1 ch) (execute-command command (last-command-triplet) nil)) (t ;a prefix character (execute-key 0 (get-char) ch))))) (defvar (autoload-inform)) ;;;(register-option 'autoload-inform nil) ;;; moved to e_option_defaults_ ;;; Ensure that autoloads are done early in the execution phase. (defun ensure-autoload (command) (cond ((getl command '(editor-macro subr expr))) ((not (get command 'autoload))) ('else (if autoload-inform (minibuffer-print "Autoloading " command " ... ")) (protect (loadfile (get command 'autoload)) &success (if autoload-inform (minibuffer-print-noclear "done.")) &failure (if autoload-inform (minibuffer-print-noclear "failed.")))))) (setq last-time-sample nil) Execute an Emacs command (defun execute-command (command key argument-list) (ensure-autoload command) (setq current-command command) (or last-time-sample (setq last-time-sample (time))) (let ((last-time-sample 'dont-sample)) (cond ((get command 'editor-macro) ;keyboard macro (or (null argument-list) (display-error (ed-get-name command key) " does not accept arguments.")) (push-editor-macro-level (get command 'editor-macro) (editor-macro-arg-interp numarg)) (setq previous-command command previous-argument-list nil)) ((get command 'editor-command) ;new-style command (execute-new-command command key argument-list)) (t ;old-style command (or (null argument-list) (display-error (ed-get-name command key) " does not accept arguments.")) (execute-old-command command (last-command-triplet))))) (and (or command-bell meter-commands) ;Avoid call if we can. (command-timing last-time-sample)) (setq numarg nil undo nil last-time-sample nil)) ;;; Handle command timing. nil= > no bell . otherwise threshhold in seconds ;;;(register-option 'command-bell nil) ;;; moved to e_option_defaults_ ;;; nil=> no bell. fixnum=>number of bells. otherwise function to call. ;;;(register-option 'command-bell-count nil) ;;; moved to e_option_defaults_ ;;; nil=> no metering. t=> minibuffer metering. otherwise function. ;;;(register-option 'meter-commands nil) ;;; moved to e_option_defaults_ ;;; Moved to e_option_defaults ( defprop command - bell t value - ok - anything ) ( defprop command - bell - count t value - ok - anything ) ;;;(defprop meter-commands t value-ok-anything) (defun command-timing (sample) (or (null sample) (not (floatp sample)) (let ((difference (-$ (time) sample))) (and command-bell (> difference (float command-bell)) (cond ((fixp command-bell-count) (do-times command-bell-count (ring-tty-bell))) (command-bell-count (funcall command-bell-count difference)))) (cond ((eq meter-commands 't) (minibuffer-print (decimal-rep difference) "s")) (meter-commands (funcall meter-commands difference)))))) ;;; Returns command name for error messages (defun ed-get-name (command key) (catenate command (cond ((get command 'editor-macro) " (keyboard macro)") (t "")) (cond (key (catenate " (" (get-key-name key) ")")) (t "")))) ;;; Try to convert an argument to a fixnum and return nil if not valid (defun ed-cv-fixnum-check (argument) (let ((argument-list (exploden argument))) (do ((digit (car argument-list) (car argument-list)) (negate) (value)) ((not digit) (and negate (setq value (- value))) value) + as first char (setq value 0)) ((and (= digit #/-) (not value)) (setq value 0 negate t)) ((and (> digit (1- #/0)) (< digit (1+ #/9))) (setq value (+ (- digit #/0) (* 10. (or value 0))))) (t ;not valid in a number (return nil))) (setq argument-list (cdr argument-list))))) ;;; (setq *transparent-commands* '(escape multiplier noop re-execute-command extended-command)) Invoke a new - style Emacs command JSL 's new version - June 1982 (defun execute-new-command (command key argument-list) (do ((done) (flags (get command 'editor-command)) (function command) (ignore-rejected-numarg) (prologue-info) (result) (times)) (done result) ;; ;; Check for synonym command. ;; (and (symbolp flags) (return (execute-command flags key argument-list))) ;; ;; Check for undo. ;; (if undo (and (tlnn flags 000500) (setq undo nil)) (and (tlnn flags 000400) (return (execute-command (get command 'ed-undo-function) key argument-list))) (and (tlne flags 000700) (display-error (ed-get-name command key) " does not accept the undo prefix."))) ;; ;; Here to process numeric arguments. ;; (if numarg ;; ;; Check for &numeric-function. ;; (if (tlnn flags 001000) (setq function (get function 'ed-numeric-function)) (ensure-autoload function) (or (and function (getl function '(subr lsubr fsubr expr lexpr fexpr))) (display-error (ed-get-name command key) " does not accept a numeric argument.")) (setq flags (or (get function 'editor-command) 0) ignore-rejected-numarg t)) ;; ;; Check for &negative function. ;; (if (and (< numarg 0) (tlnn flags 200000)) (setq function (get function 'ed-negative-function)) (ensure-autoload function) (or (and function (getl function '(subr lsubr fsubr expr lexpr fexpr))) (display-error (ed-get-name command key) " does not " "accept a negative numeric argument.")) (setq flags (or (get function 'editor-command) 0) numarg (- numarg) ignore-rejected-numarg t)) ;; ;; Now process &repeat, &reject, &ignore and check bounds. ;; (let ((numarg-type (logand flags (lsh 070000 18.))) (numarg-range (and (tlnn flags 100000) (get function 'ed-numeric-range)))) (setq times (ed-interpret-numarg command key numarg-type numarg-range ignore-rejected-numarg)))) ;; ;; Simple case. ;; (if (and (null argument-list) (tlne flags 406040)) ; Has no special handling needed. ;; ;; Deal with numeric argument, if any. ;; (cond (times (setq numarg nil)) (t (setq times 1))) ;; ;; Call the function, and return its result. ;; (return (cond ((eq (cadr function) 'subr) (do ((i 1 (1+ i)) (f (caddr function)) (inv (or (memq command *transparent-commands*) (memq command nobreak-functions)))) ((> i times) result) (setq result (subrcall t f)) (or inv (setq previous-command command previous-argument-list nil)))) (t (do ((i 1 (1+ i)) (inv (or (memq command *transparent-commands*) (memq command nobreak-functions)))) ((> i times) result) (setq result (funcall function)) (or inv (setq previous-command command previous-argument-list nil))))))) ;; ;; Prepare for cleanup handler, in case specified. ;; (unwind-protect (progn ;; ;; Do prologue if specified. ;; (and (tlnn flags 004000) ;has prologue code. (setq prologue-info (funcall (get function 'ed-prologue-function)))) ;; ;; Process arguments. ;; (and (or (tlnn flags 400000) ;wants arguments (not (null argument-list))) (setq argument-list (ed-interpret-arguments command key function flags argument-list))) ;; ;; Clear numarg for &repeat case. ;; (cond (times (setq numarg nil)) (t (setq times 1))) ;; ;; Do the command as many times as necessary, calling the ;; prologue after each invocation, if there is one. ;; (do ((epilogue (and (tlnn flags 002000) (get function 'ed-epilogue-function))) (i 1 (1+ i)) (inv (or (memq command *transparent-commands*) (memq command nobreak-functions)))) ((> i times)) (setq result (apply function argument-list)) (and epilogue (setq result (funcall epilogue prologue-info result (= i times)))) (or inv (setq previous-command command previous-argument-list argument-list))) ;; ;; We won't need cleanup handler anymore. ;; (setq done (> times 0))) ;; ;; Here we check for cleanup handler. ;; (and (not done) (setq done t) (tlnn flags 000040) (setq flags (get function 'ed-cleanup-function)) (funcall flags prologue-info))))) ;;; Interpret the numeric argument JSL 's new version - June 1982 (defun ed-interpret-numarg (command key numarg-type numarg-range ignore-rejected-numarg) (and numarg-range ;a range is specified (let ((lower (car numarg-range)) (upper (cdr numarg-range))) (cond (lower ;lower bound specified (setq lower (ed-get-encoded-value lower)) (and (< numarg lower) ;lose, lose (display-error (ed-get-name command key) " does not accept a " (cond ((= lower 0) ;a special case "negative numeric argument.") (t (catenate "numeric argument < " (decimal-rep lower) "; you supplied " (decimal-rep numarg) "."))))))) (cond (upper ;upper bound specified (setq upper (ed-get-encoded-value upper)) (and (> numarg upper) ;lose, lose (display-error (ed-get-name command key) " does not accept a " (cond ((= upper -1) ;a special case "positive numeric argument.") (t (catenate "numeric argument > " (decimal-rep upper) "; you supplied " (decimal-rep numarg) "."))))))))) (cond ((zerop numarg-type) ; Pass numeric argument. nil) ((= numarg-type (lsh 010000 18.)) ; Repeat numeric argument. numarg) ((= numarg-type (lsh 020000 18.)) ; Ignore numeric argument. (setq numarg nil)) ;; ;; If we get here, numarg-type = (lsh 030000 18.) Reject. ;; (ignore-rejected-numarg (setq numarg nil)) (t (display-error (ed-get-name command key) " does not accept a numeric argument.")))) ;;; Interpret and complete the command's argument list ;;; Slightly modified by JSL summer '82 (defun ed-interpret-arguments (command key function flags argument-list) (let ((nargs-given (length argument-list)) (nargs-wanted (logand flags 777777)) (args-template (get function 'ed-argument-list))) (and (= nargs-wanted 0) ;no arguments allowed (> nargs-given 0) ;but some were supplied (display-error (ed-get-name command key) " does not accept arguments.")) (do ((i 1 (1+ i)) ;go through the arguments (args-wanted args-template (cdr args-wanted)) (args-given argument-list (cdr args-given)) (new-arguments)) ((> i nargs-wanted) ;until all args processed (nreverse new-arguments)) ;'twas built in reverse (setq new-arguments (cons (ed-interpret-single-arg command key nargs-wanted nargs-given i (car args-wanted) (car args-given) (= i nargs-wanted) (cdr args-given)) new-arguments))))) ;;; Interpretation of a single argument (defun ed-interpret-single-arg (command key nargs-wanted nargs-given arg-no arg-template arg-supplied last-argp rest-of-args-supplied) (let ((data-type ;data type of argument (logand (car arg-template) (lsh 700000 18.))) non - zero = > prompt if missing (tlnn (car arg-template) 040000)) non - zero = > default value exists (tlnn (car arg-template) 020000)) non - zero = > value is restricted (tlnn (car arg-template) 010000)) (prompt-info (cadr arg-template)) (default-info (caddr arg-template)) (restriction-info (cadddr arg-template)) (show-error (cond ((tlnn (car arg-template) 040000) ;;can prompt for new value 'display-error-noabort) (t 'display-error))) (completion-list (eval (car (cddddr arg-template))))) (do ((the-argument arg-supplied) ;start with what's given (have-argument)) (have-argument the-argument) ;return constructed arg (cond ((or (= data-type (lsh 300000 18.)) ;&rest-as-string (= data-type (lsh 400000 18.))) ;&rest-as-list (or last-argp (display-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " is a rest-of-arguments type, but " "is not the last argument.")) (setq have-argument t ;this will succeed the-argument (cond ((= data-type (lsh 300000 18.)) ;;wants a string (catenate (or arg-supplied "") (do ((args rest-of-args-supplied (cdr args)) (x "" (catenate x " " (car args)))) ((null args) x)))) (t ;wants a list (append (and arg-supplied (list arg-supplied)) rest-of-args-supplied))))) ((and last-argp rest-of-args-supplied) (display-error (ed-get-name command key) " expects " (decimal-rep nargs-wanted) " arguments;" " you supplied " (decimal-rep nargs-given) ".")) (the-argument ;;something here, check it for legality (cond ((zerop data-type) ;string argument, no checking (setq have-argument t)) ((= data-type (lsh 100000 18.)) ;wants a symbol (let ((x (ed-interpret-symbol-arg command key arg-no the-argument show-error have-restrictions restriction-info))) (setq the-argument (car x) have-argument (cdr x)))) ((= data-type (lsh 200000 18.)) ;;wants an integer (let ((x (ed-interpret-integer-arg command key arg-no the-argument show-error have-restrictions restriction-info))) (setq the-argument (car x) have-argument (cdr x)))) (t ;unknown data type (display-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " has an unknown data type.")))) (t ;prompt or use default (cond (have-prompt ;prompt for it (setq the-argument (minibuf-response (ed-get-encoded-value (car prompt-info)) (cdr prompt-info))) (and have-default ;if there's a default (nullstringp the-argument) ;no value given (setq the-argument (ed-get-encoded-value default-info)))) (have-default ;have default value (setq the-argument (ed-get-encoded-value default-info))) (t ;no prompt, no default (display-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " has no prompt or default value.") ))))))) ;;; ;;; Interpretation of an argument which should be a symbol ;;; (defun ed-interpret-symbol-arg (command key arg-no the-argument show-error have-restrictions restriction-info) (let ((argument (intern (make_atom (e_lap_$trim the-argument)))) (have-argument nil)) ;not found yet (cond (have-restrictions ;but it's value is limited (let ((possible-values (ed-get-encoded-value restriction-info))) (cond ((memq the-argument possible-values) (setq have-argument t)) (t ;not good (funcall show-error "Argument # " (decimal-rep arg-no) " of " (ed-get-name command key) " must be one of:" (do ((values possible-values (cdr possible-values)) (x "" (catenate x " " (car values)))) ((null values) x))) (setq argument nil))))) ;force prompt (t ;value not restricted, got it (setq have-argument t))) (cons argument have-argument))) ;;; ;;; Interpretation of an argument which should be an integer ;;; (defun ed-interpret-integer-arg (command key arg-no the-argument show-error have-restrictions restriction-info) (let ((value (cond ((fixp the-argument) the-argument) (t (ed-cv-fixnum-check the-argument)))) (have-argument)) ;none yet (cond (value ;got something (cond (have-restrictions ;but restricted (let ((lower (car restriction-info)) (upper (cdr restriction-info))) (cond (lower ;has lower bound (setq lower (ed-get-encoded-value lower)) (cond ((< value lower) (cond ((= lower 0) (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must not be " "negative.")) (t (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must be >= " (decimal-rep lower) "; you supplied " (decimal-rep value) "."))) (setq value nil))))) ;;force prompt (cond (upper ;has upper bound (setq upper (ed-get-encoded-value upper)) (cond ((> value upper) (cond ((= upper -1) (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must not be " "positive.")) (t (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must be <= " (decimal-rep upper) "; you supplied " (decimal-rep value) "."))) (setq value nil)))))) ;force prompt (and value ;passed the tests (setq have-argument t))) (t ;unrestricted, got it (setq have-argument t)))) (t ;not a number (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must be an integer, not " the-argument ".") (setq have-argument nil))) ;force prompt (cons value have-argument))) ;;; ;;; Evaluate an encoded value. ;;; (defun ed-get-encoded-value (encoded-value) (let ((type (car encoded-value)) (value (cadr encoded-value))) (cond ((eq type 'quote) value) ;actual value is here ((eq type 'eval) (funcall value)) ;value from function (t ;unknown (display-error "Unknown value encoding: " type))))) ;;; Execute an old style Emacs command Slightly modified by JSL ( mostly format ) - June 1982 (defun execute-old-command (command key) (let ((function command) (numarg-repeat)) (setq numarg-repeat (get command 'argwants)) (and (< (or numarg 1) 0) numarg-repeat (setq numarg (- numarg) function (or (get command 'negative-arg-function) 'bad-negative-argument))) (or (eq (cadr function) 'subr) (get function 'subr) (get function 'expr) (get function 'autoload) (display-error "Undefined function " function " for " command " (" (get-key-name key) ")")) (setq numarg-repeat (cond (numarg-repeat (or numarg 1)) (t 1))) (cond ((eq (cadr function) 'subr) (do ((i 1 (1+ i)) (f (caddr function))) ((> i numarg-repeat)) (subrcall t f) (setq previous-command command previous-argument-list nil))) (t (do ((i 1 (1+ i))) ((> i numarg-repeat)) (funcall function) (setq previous-command command previous-argument-list nil)))))) ;;; Execute an actual command the specified number of times ;;; with the given arguments. (defun execute-command-function (command function ntimes argument-list) (cond ((and (eq (cadr function) 'subr) (< (length argument-list) 5)) (do ((i 1 (1+ i)) (f (caddr function)) (nargs (length argument-list))) ((> i ntimes)) (cond ((= nargs 0) (subrcall t f)) ((= nargs 1) (subrcall t f (car argument-list))) ((= nargs 2) (subrcall t f (car argument-list) (cadr argument-list))) ((= nargs 3) (subrcall t f (car argument-list) (cadr argument-list) (caddr argument-list))) ((= nargs 4) (subrcall t f (car argument-list) (cadr argument-list) (caddr argument-list) (car (cdddr argument-list))))) (or (memq command '(escape multiplier noop re-execute-command extended-command)) (setq previous-command command previous-argument-list argument-list)))) (t (do i 1 (1+ i) (> i ntimes) (apply function argument-list) (or (memq command '(escape multiplier noop re-execute-command extended-command)) (setq previous-command command previous-argument-list argument-list)))))) Emacs command to re - execute the last command (defcom re-execute-command &undo &pass &numeric-argument (&pass) (or previous-command (display-error "No saved previous command")) (execute-command previous-command nil previous-argument-list)) Emacs command invoked for an unbound key (defcom undefined-command &numeric-argument (&ignore) &undo &ignore (display-error "Unknown command: " (get-key-name (last-command-triplet)))) Emacs command invoked for a key whose command does n't accept negative arguments (defcom bad-negative-argument &undo &ignore &numeric-argument (&ignore) (display-error "Command rejected negative argument: " (get-key-name (last-command-triplet)))) ;;; Function to return the last key typed by the user (defun last-command-triplet () (cond ((eq last-command-triplet-mpfxk 'meta) (list 1 last-command-triplet-1 nil)) (t (list 0 last-command-triplet-1 last-command-triplet-mpfxk)))) ;;; ;;; ESC - X Command New version : 27 August 1979 by GMP ;;; Invoke an Emacs command with arguments as read from mini - buffer (defcom extended-command &arguments ((command-line &prompt "Command: " &completions Fundamental/.ext-commands)) &numeric-argument (&pass) &undo &pass (let ((command-list (parse-command-line command-line))) ;split into pieces (if (not (null command-list)) (let ((command-name (car command-list)) (arguments (cdr command-list))) (or (nullstringp command-name) ;if nothing there (let ((command (intern (make_atom command-name)))) (ensure-autoload command) (cond ((getl command '(editor-command editor-macro)) (execute-command command nil arguments)) (t (execute-old-extended-command command arguments))))))))) Parse a line into tokens , obeying the Multics quoting convention (defun parse-command-line (line) (do ((input (exploden line)) (answer nil)) (nil) (setq input (do ((input1 input (cdr input1))) ((or (null input1) (not (member (car input1) '(#^I #^J #/ )))) input1))) (cond ((null input) (return (nreverse answer))) (t (setq answer (cons (do ((result "")) ((or (null input) (member (car input) '(#^I #^J #/ ))) result) (setq result (catenate result (cond ((= (car input) #/") (do ((input1 (cdr input) (cdr input1)) (quoted t) (piece "")) ((not quoted) (setq input input1) piece) (cond ((null input1) (display-error "Unbalanced quotes.")) ((and (= (car input1) #/") (equal (cadr input1) #/")) (setq input1 (cdr input1) piece (catenate piece """"))) ((= (car input1) #/") (setq quoted nil)) (t (setq piece (catenate piece (ItoC (car input1)))))))) (t (do ((input1 (cdr input) (cdr input1)) (piece (ItoC (car input)) (catenate piece (ItoC (car input1))))) ((or (null input1) (member (car input1) '(#^I #^J #/ #/"))) (setq input input1) piece))))))) answer)))))) ;;; Invoke an old-style extended command (no prompting, etc.) (defun execute-old-extended-command (command arguments) (or (getl command '(expr subr lsubr autoload)) (display-error "Unknown command: " command)) (ensure-autoload command) (let ((argsprop (args command)) (nargs (length arguments))) (cond ((null argsprop) nil) ;unknown number wanted ((and (not (< nargs (or (car argsprop) (cdr argsprop)))) (not (> nargs (cdr argsprop)))) nil) ;correct number supplied (t (display-error "Wrong number of arguments to extended command " command ".")))) (apply command ;execute command (do ((args arguments (cdr args)) ;intern/convert all arguments (new-arg-list nil (cons (let ((argument (car args)) (value)) (setq value (ed-cv-fixnum-check argument)) (cond (value value) (t (intern (make_atom argument))))) new-arg-list))) ((null args) (nreverse new-arg-list))))) ;;; ;;; ;;; O boy hairy "macro" feature. Appreciations to " EINE " E.L.E. , ;;; The state of the art advances now with my cursor. Redone pretty much wholesale 2/11/79 to allow " input chars " . Have a good time in California , DLW , thanks for everything , -bsg . ;;; When a macro is being executed, this is called to supply input from the ;;; executing macro. (defun kmacro-get-one-cmd (expected-type) (let ((this (car macro-execution-in-progress)) (rest (cdr macro-execution-in-progress))) (cond ((and (numberp this)(eq expected-type 'input-char)) (setq macro-execution-in-progress rest) this) ((eq expected-type 'toplevel-char) (cond ((eq this 'macend) (execute-single-editor-enmacroed-command 'macend) (cond (macro-execution-in-progress (kmacro-get-one-cmd expected-type)) (t nil))) ((atom this) (display-error "Keyboard macro lost synchrony.")) ((eq (car this) 'toplevel-char) (setq macro-execution-in-progress rest) (cdr this)) (t nil))) ((eq expected-type 'input-char) ;;^U ^F, the ^F is like this in "articifially generated" ;;macros. char will get this, i.e., nothing at all, ;;and go to the tty for input (setq macro-execution-in-progress rest) ;1/29/80 fix bsg (cdr this))))) ;;; When a macro is being recorded, this is called to record a single input character . Toplevelness is stored for ease in displaying definition . ( An idea by ) (defun kmacro-record-input (ch type) (setq macro-collection-in-progress (cons (cond ((eq type 'toplevel-char) (cons 'toplevel-char ch)) (t ch)) macro-collection-in-progress))) The commands to start and stop collecting macroes ( macros ? , macreaux ? ) (defcom begin-macro-collection &numeric-argument (&reject) (cond (macro-collection-in-progress (display-error "Macro already in collection.")) aaah , (command-quit)) (t (assert-minor-mode 'Macro/ Learn) (setq macro-collection-in-progress (list nil))))) (defcom end-macro-collection &numeric-argument (&pass) (wrap-up-macro-definition) (and numarg (execute-last-editor-macro))) (defun editor-macro-arg-interp (arg) (cond ((not arg) 1) ;once ((= arg 0) 'query) ((< arg 0) 'forever) ((> arg 9999.) 'forever) (t arg))) (defun push-editor-macro-level (mac ntimes) (and (> (length macrostack) 20.) (display-error "Too much macro recursion.")) (and macrostack (rplaca (cdr (car macrostack)) macro-execution-in-progress)) (setq macrostack (cons (list mac mac ntimes) macrostack)) (setq macro-execution-in-progress (cadr (car macrostack)))) (defun wrap-up-macro-definition () (or macro-collection-in-progress (display-error "No macro in progress.")) (negate-minor-mode 'Macro/ Learn) (setq last-macro-definition (cdr (nreverse (cons 'macend (do ((l macro-collection-in-progress (cdr l))) ((null l)(display-error "Void macro.")) (and (not (atom (car l))) (eq (caar l) 'toplevel-char) (return (cdr l)))))))) (setq macro-collection-in-progress nil)) (defcom execute-last-editor-macro &numeric-argument (&pass) (or last-macro-definition (display-error "No macro to run.")) (push-editor-macro-level last-macro-definition (editor-macro-arg-interp numarg))) (defun execute-single-editor-enmacroed-command (x) (cond ((eq x nil)) ;empty in list ((eq x 'halt) (setq macrostack (cdr macrostack)) (setq macro-execution-in-progress (cadar macrostack))) ((eq x 'repeat) (setq macro-execution-in-progress (caar macrostack)) (rplaca (cdar macrostack) macro-execution-in-progress)) ((eq x 'macend) (let ((count (caddar macrostack))) (cond ((eq count 'query) (cond ((macro-query-get-answer) (execute-single-editor-enmacroed-command 'repeat)) (t (execute-single-editor-enmacroed-command 'halt)))) ((eq count 'forever) (execute-single-editor-enmacroed-command 'repeat)) ((< count 2) (execute-single-editor-enmacroed-command 'halt)) (t (rplaca (cddar macrostack) (1- count)) (setq macro-execution-in-progress (caar macrostack)) (rplaca (cdar macrostack) macro-execution-in-progress))))) (t (display-error "Internal macro format error: " x))))))) ;;; ;;; Macro utilities ;;; ;;; Save a macro definition (defcom save-macro &prologue &eval (or last-macro-definition (display-error "No macro defintion to store.")) &arguments ((macro-name &symbol &default &eval (let ((name (intern-minibuf-response "Macro name? " NL))) (cond ((getl name '(editor-command expr subr autoload)) (display-error name " is not an acceptable name.")) (t name)))) (macro-key &symbol &default &eval (get-key-name (key-prompt "On what key? ")))) &numeric-argument (&reject) (putprop macro-name last-macro-definition 'editor-macro) (or (memq macro-key '(CR ^J)) ;don't want it anywhere (set-key macro-key macro-name))) (defcom show-last-or-current-macro &numeric-argument (&pass) (cond (macro-collection-in-progress (wrap-up-macro-definition))) (show-editor-macro last-macro-definition)) (defcom show-macro &arguments ((macro-name &symbol &prompt "Macro name: ")) &numeric-argument (&pass) (cond ((get macro-name 'editor-macro) (show-editor-macro (get macro-name 'editor-macro))) (t (display-error macro-name " is not a defined macro.")))) (defun kmacro-display-interpret (x) (prog (the-interpretation the-input fun prefix metap numbering stringing l2list whoops) (setq the-input (nreverse (cdr (reverse x)))) tlc (cond ((null the-input) (cond (stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation)))) (return (nreverse the-interpretation)))) (setq x (car the-input) the-input (cdr the-input)) (cond ((not (atom x))(setq x (cdr x)))) ;ignore tlc, ok here. (setq prefix nil) (cond ((> x char-input-mask) (setq x (bit-clear 200 x) metap 1)) (t (setq metap 0))) (setq fun (get-key-binding (list metap x nil)) whoops x) (cond (numbering (cond ((kmacro-numberp x) (setq numbering (cons x numbering)) (go tlc)) (t (setq the-interpretation (cons (cons (implode (nreverse numbering)) 'Numeric/ argument) the-interpretation) numbering nil))))) ARRAYP (setq prefix x)) ((or (eq fun 'escape) (eq fun 'escape-dont-exit-minibuf)) (and stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation) stringing nil)) (cond ((and (eq fun 'escape) the-input (not (atom (car the-input))))) probbly was ESC ending minibuffer , next was tlc . ((and the-input (kmacro-number-or-plusminusp (car the-input))) (setq numbering (list (kmacro-number-or-plusminusp (car the-input))) the-input (cdr the-input)) (setq the-interpretation (cons (cons (key-total-printed-symbol metap x prefix) fun) the-interpretation)) (go tlc)) (t (setq metap 1) (cond ((null the-input) (setq x whoops prefix nil metap 0)) (t (setq x (cond ((numberp (car the-input)) (car the-input)) (t (cdar the-input))) the-input (cdr the-input)) (and (> x (1- (CtoI "a"))) (< x (1+ (CtoI "z"))) (setq x (- x 40)))))))) ((eq fun 'multiplier) (and stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation) stringing nil)) (setq the-interpretation (cons (cons (key-total-printed-symbol metap x prefix) fun) the-interpretation)) (cond ((and the-input (kmacro-number-or-plusminusp (car the-input))) (setq numbering (list (kmacro-number-or-plusminusp (car the-input))) the-input (cdr the-input)))) (go tlc))) (cond ((not (null prefix)) (cond ((null the-input)(setq x whoops prefix nil metap 0)) (t (setq x (cond ((numberp (car the-input)) (car the-input)) (t (cdar the-input))) the-input (cdr the-input)) (and (> x (1- (CtoI "a")))(< x (1+ (CtoI "z"))) (setq x (- x 40))))))) (setq fun (get-cmd-symbol-3args metap x prefix)) (cond ((memq fun '(self-insert overwrite-mode-self-insert)) (setq stringing (cons (ascii x) stringing))) (t (cond (stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation) stringing nil))) (setq the-interpretation (cons (cons (key-total-printed-symbol metap x prefix) (get-cmd-symbol-3args metap x prefix)) the-interpretation)))) (setq l2list nil) cl2c (cond ((or (null the-input) collect lev 2 ch (eq (caar the-input) 'toplevel-char))) (cond (l2list (setq the-interpretation (cons (cons (apply 'catenate (nreverse l2list)) 'Input/ Characters) the-interpretation)))) (go tlc)) (t (setq l2list (cons (ascii (car the-input)) l2list) the-input (cdr the-input)) (go cl2c))))) (defun kmacro-stringing-util (s int) (map '(lambda (x)(cond ((eq (car x) '/")(rplaca x """""")))) s) (cons (cons (catenate """" (apply 'catenate (nreverse s)) """") 'String) int)) (defun kmacro-numberp (x) (cond ((numberp x)) ((not (atom x))(setq x (cdr x)))) (and (> x (1- (CtoI "0"))) (< x (1+ (CtoI "9"))) x)) (defun kmacro-number-or-plusminusp (x) (cond ((numberp x)) ((not (atom x)) (setq x (cdr x)))) (cond ((and (> x (1- (CtoI "0"))) (< x (1+ (CtoI "9")))) x) ((= x (CtoI "+")) '+) ((= x (CtoI "-")) '-))) (defun show-editor-macro (x) Figger out what it means . (init-local-displays) (cond (numarg (mapc 'show-editor-macro-2 x)) ;hairy kind (t (local-display-generator-nnl (do ((mac x (cdr mac)) (stuff nil (cons (caar mac) stuff))) WARNING 511 limit (mapcar '(lambda (y)(catenate " " y)) (nreverse stuff)))))))) (end-local-displays)) (defun show-editor-macro-2 (x) (local-display-generator-nnl (catenate (car x) TAB (cond ((getl (setq x (cdr x)) '(expr subr autoload)) x) ((memq x '(String Input/ Characters Numeric/ argument)) x) ((get x 'editor-macro) (catenate x " (keyboard macro)")) (t "--????--"))))) (defcom macro-query &numeric-argument (&reject) (cond (macro-collection-in-progress (display-error-noabort "Inserting query at this point.")) ((not macro-execution-in-progress) (display-error "macro query: no macro running.")) (t (cond ((not (macro-query-get-answer)) (setq macro-execution-in-progress (caar macrostack))))))) (defun macro-query-get-answer () (let ((macro-execution-in-progress nil) (macro-collection-in-progress nil)) (echo-buffer-print "ok? :") (redisplay) (do ((ans (get-char)(get-char))) (nil) (cond ((= ans 7)(command-quit)) ((= ans 161)(command-quit)) ((= ans 12)) ((= ans 40)(return t)) ((= ans 15)(return nil)) ((= ans 131)(return t)) ;y ((= ans 156)(return nil)) ;n (t (return nil)))))) ;;; ;;; ;;; Quit handling and no-op department - done right BSG 3/28/79 Improvements for process preservation - BSG 3 December ' 79 (defun emacs-quit-handler (arg) (setq arg arg) (signalquit)) (defcom signalquit &undo &ignore &numeric-argument (&ignore) (cond ((eq e-quit-transparency 'transparent) This is to check flag safely even if NIL gets clobbered ! If this thing blows , you simply ca n't hit quit on Emacs . (t (let ((oqt e-quit-transparency) ;So that we can quit cleanly (e-quit-transparency 'transparent)) (randomize-redisplay) ;in case quit was caused by (or oqt (progn (e_pl1_$set_emacs_tty_modes) ;tty reconnect (clear-the-screen) (and split-mode-p (rdis-restore-screen-to-one-split)))) (and DCTL-epilogue-availablep (DCTL-epilogue)) (e_pl1_$dump_output_buffer) (e_pl1_$set_multics_tty_modes) (terpri) (cond ((and (eq emacs-name 'emacs_) quit-on-break) (emacs$set_emacs_return_code (error_table_ 'action_not_performed)) (or tasking-emacs (lisp-quit-function)))) (signalquit-hardcore-vt132-writearound) (ioc z) (e_pl1_$set_emacs_tty_modes) (and DCTL-prologue-availablep (DCTL-prologue)) (and split-mode-p (rdis-recreate-splits-on-screen)) (or oqt (progn ;Redisplay suppressed (full-redisplay) (display-error-noabort "Restarting from QUIT... ") (redisplay))))))) Writearound for the hardcore / vt132 bug that causes screen to not ;;; be cleared on ^Z^Z or BREAK. The problem looks like this: ;;; ( 1 ) Emacs sends characters to fix up screen . ( 2 ) Emacs does ( ioc z ) , causing signal _ quit . ( 3 ) default_error_handler _ does a resetwrite . ( 4 ) Hardcore has not yet sent the clearing characters ; they get eaten . ( 5 ) Screen stays screwed , though no longer in Emacs . ( 6 ) User gets confused . ;;; The only solutions are : ( 1 ) Do write_status 's until all output is out , or ( 2 ) Just do a ( sleep ) of some interesting length . I chose the sleep ;;; option. If hardcore ever gets fixed, it would be nice to do a ;;; force_out operation to make sure the characters get out. 14 November 1981 (defun signalquit-hardcore-vt132-writearound () (and (eq tty-type 'vt132) (sleep 2))) (defcom noop &numeric-argument (&ignore) &undo &ignore ) ;;; This hack hides the lisp "quit" function, rebinding "quit" to " quit - the - editor " , a much nicer function from Emacs ' point of view . (putprop 'lisp-quit-function (get 'quit 'subr) 'subr) (remprop 'quit 'subr) (defcom-synonym quit quit-the-editor) Exit from EMACS (defcom quit-force &numeric-argument (&reject) (clear-reset) (set-lisp-rdis-meters) (alarmclock 'time nil) (alarmclock 'runtime nil) (cond ((zerop (e_tasking_$quit)) (tasking-restart)) (t (lisp-quit-function)))) (defun clear-reset () (clear-the-screen) (and split-mode-p (rdis-restore-screen-to-one-split)) (and DCTL-epilogue-availablep (DCTL-epilogue)) (e_pl1_$dump_output_buffer) (e_pl1_$set_multics_tty_modes)) Restart a tasking Emacs . (defun tasking-restart () (tasking-restart-internal) (pi-handler)) (defun tasking-restart-internal () (e_pl1_$init) (e_pl1_$set_emacs_tty_modes) (randomize-redisplay) (and DCTL-prologue-availablep (DCTL-prologue)) (let ((su-args (e_argument_parse_$get_startup_info))) (setq args:apply-arg (caddr (cddddr su-args)) args:paths (caddr su-args)) (setq emacs-start-ups-need-running 'default-emacs-start-up) (init-echnego-bittab)) (clear-the-screen) (setq tasking-restarted t)) ;;; Decide if it's okay to quit now. (defun okay-to-quit? () (do ((buffers known-buflist (cdr buffers)) (found nil)) ((null buffers) (cond ((not found) t) (t (init-local-displays) (local-display-generator-nnl "Modified Buffers:") (local-display-generator-nnl "") (mapc 'local-display-buffer-info found) (local-display-generator-nnl "-------------------------") (yesp "Modified buffers exist. Quit?")))) (and (not (get (car buffers) 'dont-notice-modified-buffer)) (not (empty-buffer-p (car buffers))) (get-buffer-state (car buffers) 'buffer-modified-flag) (setq found (cons (car buffers) found))))) (defun local-display-buffer-info (buffer) (let ((path (get-buffer-state buffer 'fpathname))) (local-display-generator-nnl (catenate (cond ((eq current-buffer buffer) ">") ((eq previous-buffer buffer) "<") (t " ")) (cond ((get-buffer-state buffer 'buffer-modified-flag) "*") (t " ")) (cond (path (catenate buffer (substr " " 1 (max (- 25. (stringlength buffer)) 1)) path)) (t buffer)))))) Mark this Emacs as dead if tasking , then quit . (defcom destroy-task (and minibufferp (display-error "No quitting while in the minibuffer.")) (cond ((not tasking-emacs) (display-error "This is not a tasking Emacs.")) ((not (okay-to-quit?)) (command-quit)) (t (e_tasking_$destroy_me) (run-emacs-epilogue-actions) (quit-force)))) Exit from EMACS if no buffers are modified or user says OK (defcom quit-the-editor &numeric-argument (&reject) (and minibufferp (display-error "No quitting while in the minibuffer.")) (cond (tasking-emacs (clear-reset) (e_tasking_$quit) (tasking-restart)) ((okay-to-quit?) (run-emacs-epilogue-actions) (quit-force)) (t (command-quit)))) 5/6/80 (do nil ((null emacs-epilogue-action-list)) (errset (apply (caar emacs-epilogue-action-list) (cdar emacs-epilogue-action-list))) (setq emacs-epilogue-action-list (cdr emacs-epilogue-action-list)))) (defun set-emacs-epilogue-handler (fnandargs dupflg) (or (and dupflg (assq (car fnandargs) emacs-epilogue-action-list)) (setq emacs-epilogue-action-list (cons fnandargs emacs-epilogue-action-list)))) ;;; (defun telnet-loser (c) (cond ((or (= c 363)(= c 364)) ;BREAK, IP (signalquit)) IAC DO (setq c (e_pl1_$get_char)) (cond ((not (= c 1)) ;DO ECHO (display-error-noabort "Ignoring TELNET IAC DO " (implode (explodec c)))))) IAC DONT (setq c (e_pl1_$get_char)) (cond ((not (= c 1)) ;DONT ECHO (display-error-noabort "Ignoring TELNET IAC DONT " (implode (explodec c)))))) (t (display-error-noabort "Ignoring TELNET IAC " (implode (explodec c)) "(octal). Good luck.")))) (defun define-autoload-lib fexpr (x) (mapc '(lambda (y)(set-autoload-lib y (car x)))(cdr x))) ;;; ;;; HELP ! What did I type ? ! ? ! ? 2/11/79 ;;; (defcom help &undo &ignore &numeric-argument (&ignore) (init-local-displays) (local-display-generator-nnl (catenate "Help segments on Emacs are found in " documentation-dir ".")) (mapc 'local-display-generator-nnl '("See emacs.gi.info there for full information on everything." "Type the escape key, the question mark key, and some key that" "you want to know about to find out about it. Type a control underscore" "at any time to get more help. Type control underscore" "and a question mark for all help commands." "Type two linefeeds to remove this display," "or any other display that ends with -- * * * * * * * --," "from your screen.")) (end-local-displays)) (defcom-synonym ? help) (defcom help-on-tap &numeric-argument (&ignore) &undo &ignore (minibuffer-print "HELP: (? for more info): ") (do x (get-char)(get-char) nil (and (> x (1- #/a)) (< x (1+ #/z)) (setq x (- x 40))) (cond ((= x 12)) ((= x #/H)(help)) ((= x #/C)(execute-command 'describe-key nil nil)) ((= x #/D)(execute-command 'describe nil nil)) ((= x #/A)(execute-command 'apropos nil nil)) ((= x #/L)(help-list-typin)) ((= x #/?)(help-whats-on-tap)) ((= x 7)(command-quit)) ;^G (t (help-whats-on-tap))) (or (= x 12)(return nil))) (minibuffer-print "")) (defun help-whats-on-tap () (init-local-displays) (mapc 'local-display-generator-nnl '("^_ H gives general help info." "^_ ? gives this list of what ^_ can do." "^_ A followed by a word and a CR looks for appropriate" " matching commands. Type ^_ D apropos CR for more on this." "^_ C prompts for a character (or key sequence) and tells what it does." "^_ D followed by an extended command name and a CR tells" " about the extended command." "^_ L Lists the last 50 characters or commands typed.")) (local-display-generator-nnl "Type two linefeeds to remove this display from your screen.") (end-local-displays)) (defun help-list-typin () (do ((stop (cond ((= history-next-index 0) 50.) (t history-next-index))) (cur history-next-index (1+ cur)) (first t nil) (nl) (l)) ((and (not first)(= cur stop)) (do c 0 (1+ c)(= c 50.) (or l (return nil)) (setq nl (cons (car l) nl) l (cdr l))) (init-local-displays) (do ((line (catenate (printable (car nl)) " ") (catenate line (cond (nl (printable (car nl))) (t "")) " "))) ((null nl) (or (nullstringp line)(samepnamep line " ") (local-display-generator-nnl line))) (cond ((> (stringlength line)(- screenlinelen 6)) (local-display-generator-nnl line) (setq line ""))) (setq nl (cdr nl)))) (and (= cur 50.)(setq cur 0)) (cond ((numberp (saved-command-history cur)) (setq l (cons (saved-command-history cur) l))) ((null (saved-command-history cur))) Next case is combined chars from get - top - level - char - innards (t (setq l (append (nreverse (explodec (saved-command-history cur))) l))))) (local-display-generator-nnl "Type two linefeeds to remove this display from the screen.") (end-local-displays))
null
https://raw.githubusercontent.com/dancrossnyc/multics/dc291689edf955c660e57236da694630e2217151/library_dir_dir/system_library_unbundled/source/bound_multics_emacs_.s.archive/e_interact_.lisp
lisp
*********************************************************** * * * * * * * * *********************************************************** e_interact_ All that of the basic editor which deals with being interactive commands, prefixes, etc., as opposed to being an editor. HISTORY COMMENTS: pre-hcom history: Split off from e_ when he grew too gravid. BSG 8/4/78 Modified 1978.11.27-29 to reorganize interrupt stuff, etc. by rsl. Modified 08/21/79 by GMP for negative arguments. of multiple emacs's, tasking. out previous-command after echo-negotiation. Also, last-input-char is maintained by get-a-char, not process-char, so it is Set up the &undo property on more commands. escape prefix in parse-key-description. forms, as they were moved to e_option_defaults_. audit(86-08-12,Harvey), install(86-08-20,MR12.0-1136): to fix wrong-type-arg error audit(86-08-12,Harvey), install(86-08-20,MR12.0-1136): to fix bug in the rewrite of permanently-set. audit(86-08-12,Harvey), install(86-08-20,MR12.0-1136): to remove top-level setq of suppress-remarks, as it has been set in e_option_defaults_; changed set-emacs-interrupt to grow the handler and handle arrays if necessary, changed extended-command to ignore null command lines, fixed some problems in key binding management, changed special declaration to defvar, moved %include's to before declarations. audit(88-06-08,RBarstad), install(88-08-01,MR12.2-1071): places to improve readibility. audit(88-06-08,RBarstad), install(88-08-01,MR12.2-1071): exit and restore screen splits when later restarted. END HISTORY COMMENTS The key binding arrays. These are created and initialized at dump time so that the user needn't wait through them at startup time. never becomes previous-command for command bell option for command bell also option for command metering Terminal type. t at dump time t if we are running tasked. t if we've been restarted. called name of this incarnation: whether or not to quit on typed BREAK during emacs_ invocation. for help command for command history used for checking macro hack controls whether redisplay is enabled Allows quits not to screen-hack terminal needs hacking on setting Multics tty modes interrupt went off in minibuffer redisplay, do all the work! list of known buffers used in key parsing. numeric argument to current function, or nil if none whether or not to undo; like numarg MCS escape character (\) things to be done on exit current char, for self-inserts current/last command being executed continuation of above, encoded. symbol name of current buffer for option mechanism, list thereof. format is (macro restart count) functions that don't break echnego on at init time, until start-up over buffer we came from command being executed argument list used to invoke last cmd for user opinion on mode line meters lowest unused entry in interrupt handler table records when interrupt handler may cause a redisplay how to treat lisp errors a newline as string object ascii TAB ascii escape carriage return symbol that too Vertical Tab on if split screens t if any bit is on t if all bits are off Character function binding generators. This is the setter of all keys. esc-<number> make ^G punt prefix only this is array. override one there already this redundant clause is a way out dont overpush Get printable name of a key copy list prefixed ones displayable not displayable returns the display rep of a meta-char For R11/ITS telnet ^_l compatibility Swaps "alternate-key-bindings" (the emacs_ table) with "key-bindings," the standard full-emacs table. Full-hog key parser, returns (m k p) char-by-char non-meta, non-prefix rip out minus plain old hat make it an extended ASCII nothing more Randomness (register-option 'eval:eval t) ; Unfortunately ;;; moved to e_option_defaults_ (register-option 'eval:assume-atom nil) ;;; moved to e_option_defaults_ (register-option 'eval:correct-errors nil) ;;; moved to e_option_defaults_ ; ; moved to e_option_defaults _ ; ; moved to e_option_defaults _ Listener and toplevels. read erase, kill, escape chars init the guts of the editor. CTRL/g escapes lossages initialize the redisplay And the interrupt scheme. This should be in e_redisplay_ but is done here as the per invocation stuff is done here. Takes care of per invocation set-up for extended ASCII successive bytes pick a byte to scan table fix-up modes File-file the pathnames and macro files. Do -apply arguments. restart redisplay if stopped force redisplay to work on it Extended chars break echonego by default et in saecula saeculorum amen pi -> ^b interrupt CTRL/a -> reenter Following is all of Multics EMACS. Root tree of universe seulement par ^G gratuitous &valid on off, when ready default to "normal" ick Character readers IT CAUSES REDISPLAY TO OCCUR WHEN THERE IS NO PENDING INPUT. ALMOST ALL REDISPLAY IN THE WORLD IS INVOKED RIGHT HERE. Attempt PL/I (and poss. better) echo negotiation. try super-opt line gotta be open gotta be at eol old rdis-suppr-rdis update all parms echnego ok minibuf even so since we never actually execute a command how it works: internal and external. Internal numbers are assigned sequentially from the variable next-interrupt-channel. Internal numbers are used to index into the array emacs-interrupt-handlers, and are returned by e_pl1_$get_emacs_interrupt. External numbers are assigned by e_pl1_$assign_channel, and are computed as 64*emacs_recursion_level + internal_number. It is these external numbers which must be passed to e_pl1_$set_emacs_interrupt, and therefore it is these which set-emacs-interrupt-handler returns. don't destroy local display returns interrupt channel number ran out of channels Functions to print errors/messages in the minibuffer (register-option 'suppress-minibuffer nil) ;;; moved to e_option_defaults_ Print an error message. Print an error message and abort. Clear out the minibuffer. Print a message in the minibuffer. Print a message in the minibuffer without clearing current contents. Delete the last N characters from the minibuffer. Make a very transient remark. Clear the last minibuffer statement. Self-documentation primitives - see e_self_documentor_. Get the function bound to a key Read the name of key Compatability Execute supplied function on all keys defined in current buffer i hated fortran as a child and i hate it now as a programmer. Command to quit to editor top level Command to "ignore" a prefix character, by default on prefix-^G Command to throw to top level or nearest yggdrasil (ldebug, multics mode are the only others beside top level) Set the undo switch. number want negative argument want positive argument negative argument (default -1) character used to invoke this number negative argument positive argument NOTE- this code is buggy default number if only + given negate number (with -1 as default) get charater invoked by (without meta-bit) assume a digit have character to execute a sign given, set default Character/Key/Command Execution Process a character: determine if it is a "meta" character and then execute the key corresponding to the character meta-foo non-meta foo of a character, "meta"-bit, and prefix character used to determine the exact command to be executed. the command to execute normal command a prefix character (register-option 'autoload-inform nil) ;;; moved to e_option_defaults_ Ensure that autoloads are done early in the execution phase. keyboard macro new-style command old-style command Avoid call if we can. Handle command timing. (register-option 'command-bell nil) ;;; moved to e_option_defaults_ nil=> no bell. fixnum=>number of bells. otherwise function to call. (register-option 'command-bell-count nil) ;;; moved to e_option_defaults_ nil=> no metering. t=> minibuffer metering. otherwise function. (register-option 'meter-commands nil) ;;; moved to e_option_defaults_ Moved to e_option_defaults (defprop meter-commands t value-ok-anything) Returns command name for error messages Try to convert an argument to a fixnum and return nil if not valid not valid in a number Check for synonym command. Check for undo. Here to process numeric arguments. Check for &numeric-function. Check for &negative function. Now process &repeat, &reject, &ignore and check bounds. Simple case. Has no special handling needed. Deal with numeric argument, if any. Call the function, and return its result. Prepare for cleanup handler, in case specified. Do prologue if specified. has prologue code. Process arguments. wants arguments Clear numarg for &repeat case. Do the command as many times as necessary, calling the prologue after each invocation, if there is one. We won't need cleanup handler anymore. Here we check for cleanup handler. Interpret the numeric argument a range is specified lower bound specified lose, lose a special case upper bound specified lose, lose a special case Pass numeric argument. Repeat numeric argument. Ignore numeric argument. If we get here, numarg-type = (lsh 030000 18.) Reject. Interpret and complete the command's argument list Slightly modified by JSL summer '82 no arguments allowed but some were supplied go through the arguments until all args processed 'twas built in reverse Interpretation of a single argument data type of argument can prompt for new value start with what's given return constructed arg &rest-as-string &rest-as-list this will succeed wants a string wants a list something here, check it for legality string argument, no checking wants a symbol wants an integer unknown data type prompt or use default prompt for it if there's a default no value given have default value no prompt, no default Interpretation of an argument which should be a symbol not found yet but it's value is limited not good force prompt value not restricted, got it Interpretation of an argument which should be an integer none yet got something but restricted has lower bound force prompt has upper bound force prompt passed the tests unrestricted, got it not a number force prompt Evaluate an encoded value. actual value is here value from function unknown Execute an actual command the specified number of times with the given arguments. Function to return the last key typed by the user split into pieces if nothing there Invoke an old-style extended command (no prompting, etc.) unknown number wanted correct number supplied execute command intern/convert all arguments O boy hairy "macro" feature. The state of the art advances now with my cursor. When a macro is being executed, this is called to supply input from the executing macro. ^U ^F, the ^F is like this in "articifially generated" macros. char will get this, i.e., nothing at all, and go to the tty for input 1/29/80 fix bsg When a macro is being recorded, this is called to record a single input once empty in list Save a macro definition don't want it anywhere ignore tlc, ok here. hairy kind y n Quit handling and no-op department - done right BSG 3/28/79 So that we can quit cleanly in case quit was caused by tty reconnect Redisplay suppressed be cleared on ^Z^Z or BREAK. The problem looks like this: they get eaten . option. If hardcore ever gets fixed, it would be nice to do a force_out operation to make sure the characters get out. This hack hides the lisp "quit" function, rebinding "quit" Decide if it's okay to quit now. BREAK, IP DO ECHO DONT ECHO ^G
* Copyright , ( C ) Honeywell Bull Inc. , 1988 * * Copyright , ( C ) Honeywell Information Systems Inc. , 1982 * * Copyright ( c ) 1978 by Massachusetts Institute of * * Technology and Honeywell Information Systems , Inc. * 1 ) change(84 - 01 - 30,Margolin ) , approve ( ) , audit ( ) , install ( ): Macro facility redone 2/11/79 by BSG . Modified 06/20/79 by GMP for CTL prologue / epilogue handlers . Modified : August 1979 by GMP for new command invocation mechanism . Modified : June 1981 by RMSoley for understanding of emacs _ call . Modified : July 1981 RMSoley for pl1 argument parsing , and support Modified : March 1982 RMSoley for undo . Modified : June 1982 B - get - top - level - char - innards nulls more correct . Added JSL 's new command executor stuff . Modified : 25 November 1983 to add " ^ [ " as a valid Modified : 19 January 1984 to comment out register - option Modified : 19 January 1984 Barmar to reject esc-<number > in genset - key . Modified : 30 January 1984 Barmar to fix kmacro - display - interpret to properly interpret " ESC + NUM " and meta characters . 2 ) change(84 - 12 - 25,Margolin ) , approve(86 - 02 - 24,MCR7186 ) , in multiplier command , change lambda into let , use defmacro . 3 ) change(84 - 12 - 26,Margolin ) , approve(86 - 02 - 24,MCR7186 ) , 4 ) change(84 - 12 - 30,Margolin ) , approve(86 - 02 - 24,MCR7186 ) , 5 ) change(88 - 01 - 07,Schroth ) , approve(88 - 02 - 29,MCR7851 ) , Implement 8 - bit extended ASCII I / O. Used ' new ' macros in various 6 ) change(88 - 01 - 07,Schroth ) , approve(88 - 02 - 29,MCR7852 ) , Added support for split - screen display : revert to one split on (declare (genprefix /!eia_)) (%include e-macros) (%include backquote) (%include defmacro) (declare (macros nil)) (%include e-define-command) (%include other_other) (%include sharpsign) (declare (*lexpr display-error display-com-error display-error-noabort display-com-error-noabort minibuffer-print minibuffer-print-noclear minibuffer-remark)) (declare (*expr DCTL-epilogue DCTL-prologue assert-minor-mode clear-the-screen convert_status_code_ cur-hpos decimal-rep display-init e_argument_parse_$get_one_path e_pl1_$init e_argument_parse_$get_startup_info e_argument_parse_$new_arguments e_lap_$rtrim e_lap_$trim e_pl1_$assign_channel e_pl1_$dump_output_buffer e_pl1_$echo_negotiate_get_char e_pl1_$get_char e_pl1_$get_editing_chars e_pl1_$get_emacs_interrupt e_pl1_$get_emacs_interrupt_array e_pl1_$real_have_chars e_pl1_$set_break_char e_pl1_$set_emacs_tty_modes e_pl1_$set_multics_tty_modes e_tasking_$destroy_me e_pl1_$set_extended_ascii e_pl1_$get_output_conv_table e_tasking_$get_tasking_flag e_tasking_$quit echo-buffer-clear echo-buffer-clear-all echo-buffer-outprint echo-buffer-print echo-buffer-rubout echo-buffer-utter editor-main-init emacs$set_emacs_return_code empty-buffer-p end-local-displays error_table_ exists-file find-file-subr full-redisplay get-buffer-state go-to-or-create-buffer init-local-displays intern-minibuf-response jetteur-des-gazongues lisp-quit-function loadfile local-display-generator-nnl map-over-emacs-buffers minibuf-response negate-minor-mode nullstringp randomize-redisplay rdis-find-non-displayable redisplay ring-tty-bell set-autoload-lib set-lisp-rdis-meters user_info_$homedir user_info_$whoami yesp)) (declare (array* (notype (key-bindings 256. 2)))) (declare (array* (notype (saved-command-history 50.)))) (array saved-command-history t 50.) (array key-bindings t 256. 2) (fillarray 'key-bindings '(undefined-command)) (array alternate-key-bindings t 256. 2) (fillarray 'alternate-key-bindings '(undefined-command)) (setq permanize-key-bindings t) (defvar ( tty is a TELNET connection for complete - command , ESC - SPACE emacs / new_emacs / emacs _ suppress utterances by next-multics-argno buffer-modified-flag terminal needs hacking on setting Emacs tty modes in . list of MCS escape ( \ ) , erase ( # ) , and kill ( @ ) characters macro-collection-in-progress last-macro-definition pointer on current xec list as it says , assq list last command invoked in this Emacs locechnego-meter inhibit-default-start-up-execution emacs-start-ups-need-running NL Formfeed put in mbuf by pi - handler args:apply-arg args:ns args:paths args:ll args:pl tasking-arg terminal can do 8bit ASCII 177 normally or 377 if 8 - bit )) (defvar ( )) (declare (*expr rdis-restore-screen-to-one-split rdis-recreate-splits-on-screen)) (defun display-load-time-error n (princ (apply 'catenate (listify n))) (terpri) (break load-time-error t)) (putprop 'display-error '(lambda n (apply 'display-load-time-error (listify n))) 'expr) (putprop 'minibuffer-print '(lambda n (apply 'display-load-time-error (listify n))) 'expr) Macros to test bits in left - half of a fixnum : ( tlnX value mask ) `(not (tlne ,value ,mask))) `(zerop (logand ,value (lsh ,mask 18.)))) (defmacro permanently-set (&body forms) `(let ((permanize-key-bindings t)) .,forms)) (defcom set-perm-key &arguments ((key &symbol &prompt "Key: ") (function &symbol &prompt "Function: ")) &numeric-argument (&reject) (permanently-set (set-key key function))) (defcom-synonym set-permanent-key set-perm-key) (defcom set-key &arguments ((key &symbol &prompt "Key: ") (function &symbol &prompt "Function: ")) &numeric-argument (&reject) (let ((result (parse-key-description key))) (genset-key (caddr result) (car result) (cadr result) function))) (defvar permit-setting-esc-number nil) (defun genset-key (prefix metap key function) (or permit-setting-esc-number (= metap 0) (and (not (= key (CtoI "+"))) (not (= key (CtoI "-"))) (or (< key (CtoI "0")) (> key (CtoI "9")))) (display-error "esc-<number> may not be bound.")) (and (or prefix (= metap 1)) (> key (1- (CtoI "a"))) (< key (1+ (CtoI "z"))) (setq key (- key 40))) (cond (prefix (or (not (symbolp (key-bindings prefix 0))) (genset-key nil 0 prefix (let ((x (fillarray (*array (gensym) t 256.) '(undefined-command)))) (store (x 7) 'ignore-prefix) (cond (permanize-key-bindings (update-perm-key-bindings 0 key prefix (arraycall t metap key)) (update-local-key-bindings 0 key prefix function))) (store (arraycall t metap key) function)) (t (cond (permanize-key-bindings (remove-local-key-binding metap key nil)) ((key-bindings key metap) (update-perm-key-bindings metap key nil (key-bindings key metap)) (update-local-key-bindings metap key nil function))) (or NowDumpingEmacs (cond ((memq (key-bindings key metap) nobreak-functions) (e_pl1_$set_break_char key 1))) (cond ((memq function nobreak-functions) (e_pl1_$set_break_char key 0)))) (store (key-bindings key metap) function)))) (defun update-perm-key-bindings (metap key prefix function) (let ((keyrep (key-total-printed-symbol metap key prefix))) (putprop keyrep function 'perm-key-function)))) (defun update-local-key-bindings (metap key prefix function) (let ((keyrep (key-total-printed-symbol metap key prefix)) (listrep (key-fixnum-rep-encode metap key prefix))) (let ((assq-answer (assq keyrep per-buffer-key-bindings))) (cond (assq-answer (rplaca (cdr assq-answer) function)) (t (setq per-buffer-key-bindings (cons (cons keyrep (cons function listrep)) per-buffer-key-bindings))))))) (defun remove-local-key-binding (metap key prefix) (let ((key-symbol (key-total-printed-symbol metap key prefix))) (let ((assq-answer (assq key-symbol per-buffer-key-bindings))) (if assq-answer (setq per-buffer-key-bindings (delq assq-answer per-buffer-key-bindings)))))) (defun key-total-printed-symbol (metap key prefix) (intern (make_atom (cond (prefix (catenate (printable prefix)(printable key))) ((= 0 metap)(printable key)) (t (catenate "esc-" (printable key))))))) (defun get-key-name (key-list) (apply 'key-total-printed-symbol key-list)) (defun key-fixnum-rep-encode (metap key prefix) (list metap key prefix)) (defun reorganize-local-key-bindings (revert) (let ((permanize-key-bindings t) (unwind-protect (progn (mapc '(lambda (x) (prog (y) (setq y (cond (revert (get (car x) 'perm-key-function)) (t (cadr x)))) -non - prefix first (genset-key nil (car (cddr x)) (cadr (cddr x)) y)))) per-buffer-key-bindings) (mapc '(lambda (x) (prog (y) (setq y (cond (revert (get (car x) 'perm-key-function)) (t (cadr x)))) (genset-key (caddr (cddr x)) 0 (cadr (cddr x)) y)))) per-buffer-key-bindings)) (setq per-buffer-key-bindings saved-local-bindings)))) (defun revert-local-key-bindings ()(reorganize-local-key-bindings t)) (defun instate-local-key-bindings ()(reorganize-local-key-bindings nil)) (defun printable (x) (let ((y (cond ((numberp x) x) (t (getcharn x 1))))) 8 - bit or META ((= y 33) "ESC") ((= y 15) "CR") ((= y 177) "\177") ((= y 40) "SPACE") ((< y 40) (catenate "^" (ascii (bit-set 100 y)))) ((numberp x)(ascii x)) (t x)))) (defun printable-8-bit-char (ch-num) the display rep of char that is either an 8 - bit ASCII or a meta char (cond (DCTL-extended-ascii (printable-extended-ascii ch-num)) (t (printable-meta-char ch-num)))) (defun printable-extended-ascii (ch-num) returns the display representation of an 8 - bit ASCII code (let ((ch (ascii ch-num))) (defun printable-meta-char (ch-num) (catenate "meta-" (printable (bit-clear 200 ch-num)))) (defun swap-binding-tables () (do a 0 (1+ a) (= a 2) (do b 0 (1+ b) (= b 256.) (store (key-bindings b a) (prog1 (alternate-key-bindings b a) (store (alternate-key-bindings b a) (key-bindings b a))))))) BSG 8/5/78 Saturday morning . (prog (prefix metap key) (cond ((or (parse-key-match-list '(e s c a p e -)) (parse-key-match-list '(e s c -)) (parse-key-match-list '(m e t a -)) (parse-key-match-list '(m -)) (parse-key-match-list '(^ [ -)) (parse-key-match-list '(^ [))) (setq metap 1)) (t (setq metap 0) try for 1 frob . (or kparse-list (kparse-error desc)) (or (< prefix (CtoI " ")) (kparse-error (catenate (printable prefix) " may not be a prefix character."))))) (setq key (parse-key-description-syllable desc)) (and (or (= 1 metap) prefix) (> key (1- (CtoI "a"))) (< key (1+ (CtoI "z")))(setq key (- key 40))) (and kparse-list (kparse-error desc)) (return (list metap key prefix)))) (defun parse-key-description-syllable (desc) (cond ((not kparse-list)(kparse-error desc)) control frob , = " ^ " (setq kparse-list (cdr kparse-list)) (t (parse-key-controllify)))) ((or (parse-key-match-list '(c -)) (parse-key-match-list '(c t l -)) (parse-key-match-list '(c o n t r o l -))) (parse-key-controllify)) added Dec 84 EDSchroth (or (parse-key-match-list '(x -)) (parse-key-match-list '(e x t -)) (parse-key-match-list '(e x t e n d e d -)))) ((parse-key-match-list '(e s c)) 33) ((parse-key-match-list '(c r)) 15) ((parse-key-match-list '(\ /1 /7 /7)) 177) ((parse-key-match-list '(t a b)) 11) ((parse-key-match-list '(s p a c e)) 40) ((parse-key-match-list '(s p)) 40) (t (prog1 (car kparse-list) (setq kparse-list (cdr kparse-list)))))) (defun parse-key-controllify () (or kparse-list (kparse-error "Unspecified control character.")) (let ((kdesc (car kparse-list))) (and (> kdesc (1- (CtoI "a"))) (< kdesc (1+ (CtoI "z"))) (setq kdesc (- kdesc 40))) (or (and (< kdesc (1+ (CtoI "_"))) (> kdesc (1- (CtoI "@")))) (kparse-error (catenate "^" (ascii kdesc) " is not ASCII."))) (setq kparse-list (cdr kparse-list)) (- kdesc 100))) Handles extended ascii key descriptions . Dec 84 EDSchroth (defun parse-key-extendify (desc) (or kparse-list (kparse-error "Unspecified extended character.")) make 8 - bit ASCII (defun parse-key-match-list (matchee) (do ((data kparse-list (cdr data)) (pattern matchee (cdr pattern)) (chara)(charb)(chardata)) ((null pattern)(setq kparse-list data) t) (setq chardata (car data)) (setq chara (getcharn (car pattern) 1)) (setq charb (cond ((and (< chara (1+ (CtoI "z"))) (> chara (1- (CtoI "a")))) (- chara 40)) (t chara))) (or (= chardata chara)(= chardata charb)(return nil)))) (defun kparse-error (desc) (display-error "Invalid key description: " desc)) (setq NLCHARSTRING (ItoC 012) ESC (ascii 033)) (setq TAB (ascii 011) BACKSPACE (ascii 010) SPACE (ascii 040) CR (ascii 15) CRET (ascii 015) NL (ascii 012) FF (ascii 14) VT (ascii 13)) Initialize the option mechanism first . (setq list-of-known-options nil) (defun require-symbol (putative-symbol) (cond ((not (symbolp putative-symbol)) (display-error "This function requires a symbol.")))) (defun register-option (sym val) (require-symbol sym) (or (memq sym list-of-known-options) (setq list-of-known-options (sort (cons sym list-of-known-options) 'alphalessp))) (remprop sym 'value-must-be-numeric) (remprop sym 'value-ok-true-false) (or (boundp sym)(set sym val))) (defun listener-level () (start) (std-yggdrasil)) (defun start () 11/3/80 (setq e-quit-transparency nil) Lisp errors to minibuf (and (eq emacs-name 'emacs_) (swap-binding-tables)) (or (boundp 'next-multics-argno) (setq next-multics-argno 1)) (setq history-next-index 0) (setq macro-collection-in-progress nil previous-command nil last-macro-definition nil) (setq emacs-epilogue-action-list nil) (sstatus cleanup '((run-emacs-epilogue-actions))) (*rset nil) (e_pl1_$set_emacs_tty_modes) (sstatus mulpi t) (sstatus interrupt 16. 'emacs-quit-handler) (sstatus mulquit 16.) (init-echnego-bittab) init rsl 's hack . fix up for possible 8 - bit And the PL / I redisplay . (setq permanize-key-bindings nil) (reset-top-level-editor-state) (setq emacs-start-ups-need-running t)) Initialize the 8 - bit printing character scan table at dump time (declare 7bit non - printing 8bit non - printing (defvar 7bit-tabscan-table (fillarray (*array '7bit-tabscan-table 'fixnum 128.) '(-1))) (defvar 8bit-tabscan-table (fillarray (*array '8bit-tabscan-table 'fixnum 128.) '(-1))) 040 ... 173 print nicely ((= i 31.)) (store (arraycall fixnum 7bit-tabscan-table i) 0) (store (arraycall fixnum 8bit-tabscan-table i) 0)) nix 177 nix 177 Dec 1984 EDSchroth (defun init-extended-ascii-land () (setq char-input-mask 177) the ctl knows about 8 - bit ! (setq char-input-mask 377) (e_pl1_$set_extended_ascii 1) add 8 - bit self - inserts based on TTT output conversion table Also , define 8 - bit non - printing scan table (let ((convtab (*array nil 'fixnum 64.))) (e_pl1_$get_output_conv_table convtab) do 8 - bit chars only stop after # o377 if zero copy entries for 200 ... 377 (store (arraycall fixnum 8bit-tabscan-table i) (arraycall fixnum convtab i)))) (defvar emacs-start-up-error-message) (defun run-emacs-start-up-error (arg) arg (display-error-noabort emacs-start-up-error-message) (throw () emacs-start-up-tag)) (defun run-emacs-start-up-actions () (setq inhibit-default-start-up-execution nil) (or (eq emacs-name 'emacs_) (run-user-start-up (catenate (e_lap_$trim (user_info_$homedir)) ">start_up.emacs")) (run-user-start-up (catenate (user-project-dir) ">start_up.emacs")) (run-user-start-up ">site>start_up.emacs")) (and (eq emacs-name 'emacs_) (go-to-or-create-buffer 'main)) (or inhibit-default-start-up-execution (default-emacs-start-up)) (cond ((eq current-buffer '|<start_up_emacs_buffer>|) (go-to-or-create-buffer 'main) (setq previous-buffer 'main)) ((eq previous-buffer '|<start_up_emacs_buffer>|) (setq previous-buffer current-buffer))) (setq known-buflist (delq '|<start_up_emacs_buffer>| known-buflist))) (defun user-project-dir () (catenate ">user_dir_dir>" (e_lap_$trim (cadr (user_info_$whoami))))) (defun run-user-start-up (filename) (cond (args:ns 't) ((exists-file filename 4) (setq emacs-start-up-error-message "Error in start_up.emacs") (catch (let ((e-lisp-error-mode 'run-emacs-start-up-error)) (loadfile filename)) emacs-start-up-tag) 't) ('else nil))) Re - written by GMP , 9/4/78 . Re - written by RMSoley , 21 July 1981 (defun default-emacs-start-up () (setq inhibit-default-start-up-execution t) (do ((paths args:paths (1- paths))) ((zerop paths)) (let ((info (e_argument_parse_$get_one_path))) (cond ((zerop (cadr info)) (setq emacs-start-up-error-message (catenate "Can't load file " (car info))) (catch (let ((e-lisp-error-mode 'run-emacs-start-up-error)) (load (e_lap_$trim (car info)))) emacs-start-up-tag)) (t (catch (find-file-subr (e_lap_$trim (car info))) pgazonga))))) (cond ((> args:apply-arg -1) (setq emacs-start-up-error-message "Can't do -apply.") (catch (let ((e-lisp-error-mode 'run-emacs-start-up-error)) (apply (make_atom (status arg args:apply-arg)) (multics-args-as-list (1+ args:apply-arg)))) emacs-start-up-tag))) (and tasking-restarted (full-redisplay)) (setq tasking-restarted nil)) (defun multics-args-as-list (first-argno) (do ((count first-argno (1+ count)) (l)) ((not (status arg count)) (nreverse l)) (setq l (cons (status arg count) l)))) (setq pi-handler-minibuffer-print nil tasking-restarted nil) (defun pi-handler () (e_pl1_$set_emacs_tty_modes) (randomize-redisplay) (and DCTL-prologue-availablep (DCTL-prologue)) (and split-mode-p (rdis-recreate-splits-on-screen)) (reset-top-level-editor-state) (cond ((zerop (e_argument_parse_$new_arguments)) (full-redisplay)) (t (tasking-restart-internal))) (cond (pi-handler-minibuffer-print (minibuffer-print pi-handler-minibuffer-print) (setq pi-handler-minibuffer-print nil))) (std-yggdrasil)) (defun reset-top-level-editor-state () (or minibufferp (instate-local-key-bindings)) (cond ((memq 'Macro/ Learn buffer-minor-modes) (negate-minor-mode 'Macro/ Learn))) numarg nil undo nil macro-execution-in-progress nil macro-collection-in-progress nil macrostack nil) (or minibufferp (setq recursion-level 0))) Modified 28 June 1981 RMSoley to use set_break_sequence Modified Dec 1984 EDSchroth for 8bit ASCII . (defun init-echnego-bittab () (do ((char 0 (1+ char)) (number 0) (nlist ()) (count 0 (1+ count))) ((= char 256.) (apply 'e_pl1_$set_break_sequence (nreverse (cons number nlist)))) (and (not (zerop char)) (zerop (\ count 32.)) (setq nlist (cons number nlist) count 0 number 0)) (setq number (lsh number 1)) (or (and (> char 31.) (< char 127.) (memq (key-bindings char 0) nobreak-functions)) (setq number (1+ number))))) (defcom debug-e &numeric-argument (&reject) (setq e-lisp-error-mode 'lisp-break) (defun get-editing-characters () (let ((editing-chars (e_pl1_$get_editing_chars))) (setq MCS-editing-characters (mapcar 'CtoI editing-chars) MCS-escape-character (car editing-chars)) (set-editing-key (car editing-chars) 'escape-char) (set-editing-key (cadr editing-chars) 'rubout-char) (set-editing-key (caddr editing-chars) 'kill-to-beginning-of-line))) (defun set-editing-key (character function) (cond ((eq (get-key-binding (parse-key-description character)) 'self-insert) (set-perm-key character function)))) (do ()(nil) ceci est jet'e (ring-tty-bell) (reset-top-level-editor-state))) (defun charlisten () (let ((recursion-level recursion-level)) (do nil (nil) (or macro-execution-in-progress emacs-start-ups-need-running (redisplay)) (catch (errset (let ((fail-act 'e-lisp-lossage-handler) (pdl-overflow 'e-lisp-lossage-handler) (wrng-type-arg 'e-lisp-lossage-handler) (*rset-trap 'e-lisp-lossage-handler) (unbnd-vrbl 'e-lisp-lossage-handler) (undf-fnctn 'e-lisp-lossage-handler) (unseen-go-tag 'e-lisp-lossage-handler) (wrng-no-args 'e-lisp-lossage-handler) (errset 'e-lisp-lossage-handler)) (cond ((eq emacs-start-ups-need-running t) (setq emacs-start-ups-need-running nil) (run-emacs-start-up-actions)) (emacs-start-ups-need-running (funcall (prog1 emacs-start-ups-need-running (setq emacs-start-ups-need-running nil))))) (do ((numarg nil nil) (undo nil nil)) (nil) (process-char (get-top-level-char)))) nil) pgazonga) (reset-top-level-editor-state)))) (defun e-lisp-lossage-handler (arg) (setq arg (caddr (errframe nil))) (cond (e-quit-transparency (errprint nil)) (t (minibuffer-print (car arg) " " (maknam (explodec (cadr arg)))))) (cond ((eq e-lisp-error-mode 'lisp-break) (let ((e-quit-transparency 'transparent)) (e_pl1_$set_multics_tty_modes) (terpri)(terpri) (princ (catenate "Lisp error in buffer " current-buffer)) (terpri) (setq arg (eval (list 'break (caddr arg) t))) (e_pl1_$set_emacs_tty_modes) (full-redisplay)) (cond (arg)(t (command-prompt-abort)))) ((null e-lisp-error-mode)(command-quit)) (t (funcall e-lisp-error-mode arg)))) (defcom lisp-error-mode &numeric-argument (&reject) (setq e-lisp-error-mode nil)) ((memq mode '(t set on 1 lisp-break)) (setq e-lisp-error-mode 'lisp-break)) (t (display-error "Unknown lisp error mode: " mode)))) (declare (array* (notype (emacs-interrupt-handlers ?)(emacs-interrupt-handles ?)) (fixnum (emacs-interrupt-array ?)))) (defun get-top-level-char () (get-a-char 'toplevel-char 'get-top-level-char-innards)) (defun get-char () (get-a-char 'input-char 'e_pl1_$get_char)) (defun get-a-char (type get-char-function) (let ((new-ch (cond ((and macro-execution-in-progress (kmacro-get-one-cmd type))) (t (do ((ch (funcall get-char-function) (funcall get-char-function))) (nil) (or (= 0 (emacs-interrupt-array 0)) (setq delayed-interrupt t)) (store (emacs-interrupt-array 0) 0) (and (not minibufferp) delayed-interrupt (emacs-interrupt-processor)) (or (= ch -1) (progn (store (saved-command-history history-next-index) ch) (setq history-next-index (cond ((= history-next-index 49.) 0) (t (1+ history-next-index)))) (and macro-collection-in-progress (kmacro-record-input ch type)) (return ch)))))))) last - input - char = char without META new-ch)) Highly local specials for redisplay ( echo negotiation ) . Goddamn backpanel wires to every board in the machine . (defvar (X howmuchigot-sym rdis-upd-locecho-flg screenlinelen touchy-damaged-flag rdis-suppress-redisplay)) (defvar (rdis-multiwindowed-buflist rdis-inhibit-echnego)) (defvar (curlinel curstuff work-string curpointpos hard-enforce-fill-column fill-column)) (defun get-top-level-char-innards () (let ((ordi rdis-suppress-redisplay) (chpos 0)) THIS NEXT STATEMENT IS PERHAPS THE MOST IMPORTANT IN MULTICS EMACS (and (= 0 (e_pl1_$real_have_chars))(redisplay)) (not macro-collection-in-progress) (not suppress-redisplay-flag) (not (and hard-enforce-fill-column (not (< (setq chpos (cur-hpos)) fill-column)))) (not rdis-inhibit-echnego) (not (and minibufferp (> X (- screenlinelen 10.))))) (or (not (memq current-buffer rdis-multiwindowed-buflist)) (setq locechnego-ctr (1+ locechnego-ctr)) (prog2 (set 'howmuchigot-sym 0) (e_pl1_$echo_negotiate_get_char work-string 'howmuchigot-sym (cond (hard-enforce-fill-column (min (- screenlinelen X) (- fill-column chpos))) (minibufferp (- screenlinelen X 7)) (t (- screenlinelen X)))) (cond ((> howmuchigot-sym 0) (store (saved-command-history history-next-index) (substr work-string (1+ curpointpos) howmuchigot-sym)) (setq history-next-index (cond ((= history-next-index 49.) 0) (t (1+ history-next-index)))) (setq X (+ X howmuchigot-sym)) (setq locechnego-meter (+ locechnego-meter howmuchigot-sym)) (setq curpointpos (+ curpointpos howmuchigot-sym)) (setq curlinel (+ curlinel howmuchigot-sym)) (setq touchy-damaged-flag t) (let ((rdis-upd-locecho-flg t)) (redisplay)))))) (t (e_pl1_$get_char))))) interrupt handling integrated into e_interact _ 1978.11.21 by There are two types of interrupt numbers , namely (defun emacs-interrupt-processor () (setq delayed-interrupt nil) (do ((int-info (e_pl1_$get_emacs_interrupt) (e_pl1_$get_emacs_interrupt))) ((< (car int-info) 0) (and (= recursion-level 0) (redisplay))) (let ((intno (car int-info))) (cond ((emacs-interrupt-handlers intno) (funcall (emacs-interrupt-handlers intno) intno (emacs-interrupt-handles intno) (cadr int-info))))))) (defvar max-emacs-interrupt-channel 64.) (setq next-interrupt-channel (1+ next-interrupt-channel)) (setq max-emacs-interrupt-channel (* 2 max-emacs-interrupt-channel)) (*rearray 'emacs-interrupt-handlers t max-emacs-interrupt-channel) (*rearray 'emacs-interrupt-handles t max-emacs-interrupt-channel)) (store (emacs-interrupt-handlers next-interrupt-channel) handler) (store (emacs-interrupt-handles next-interrupt-channel) handle) (e_pl1_$assign_channel next-interrupt-channel)) (defun interrupt-init () (*array 'emacs-interrupt-array 'external (e_pl1_$get_emacs_interrupt_array) 2) (*array 'emacs-interrupt-handlers t max-emacs-interrupt-channel) (*array 'emacs-interrupt-handles t max-emacs-interrupt-channel) (setq delayed-interrupt nil) (setq next-interrupt-channel -1)) (defvar (suppress-minibuffer)) (defun display-error-noabort n (or suppress-minibuffer (echo-buffer-print (apply 'catenate (listify n))))) (defun display-error n (or suppress-minibuffer (apply 'display-error-noabort (listify n))) (command-quit)) Print an error message : first argument is Multics error code . (defun display-com-error-noabort n (or suppress-minibuffer (let ((prefix (cond ((= 0 (arg 1)) "") (t (catenate (e_lap_$rtrim (cadr (convert_status_code_ (arg 1)))) (cond ((> n 1) " ") (t "")))))) (message (cond ((> n 1) (apply 'catenate (listify (- 1 n)))) (t "")))) (echo-buffer-print (catenate prefix message))))) Print an error message and abort : first argument is Multics error code . (defun display-com-error n (apply 'display-com-error-noabort (listify n)) (command-quit)) (defun minibuffer-clear-all () (echo-buffer-clear-all)) (defun minibuffer-print n (or macro-execution-in-progress suppress-minibuffer (echo-buffer-print (apply 'catenate (listify n))))) (defun minibuffer-print-noclear n (or macro-execution-in-progress suppress-minibuffer (echo-buffer-outprint (apply 'catenate (listify n))))) (defun minibuffer-rubout (n) (or macro-execution-in-progress (echo-buffer-rubout n))) (defun minibuffer-remark n (or macro-execution-in-progress suppress-remarks suppress-minibuffer (echo-buffer-utter (apply 'catenate (listify n))))) (defun display-error-remark n (or suppress-minibuffer (echo-buffer-utter (apply 'catenate (listify n))))) (defun minibuffer-clear ()(echo-buffer-clear)) (defun get-cmd-symbol-3args (metap key prefix) (cond ((and (= metap 1) prefix) nil) ((not prefix) (cond ((subrp (key-bindings key metap)) nil) (t (key-bindings key metap)))) (t (cond ((not (subrp (key-bindings prefix 0))) nil) (t (arraycall t (key-bindings prefix 0) key)))))) (defun get-key-binding (key-list) (apply 'get-cmd-symbol-3args key-list)) (defun key-prompt (prompt) (prog (ch1) (minibuffer-print prompt) (setq ch1 (get-char)) (return (cond ((= ch1 377) (setq ch1 (get-char)) (cond ((= ch1 377) (minibuffer-print-noclear "esc-" (printable 177)) '(1 177 nil)) (t (return (telnet-loser ch1))))) ((> ch1 char-input-mask) (minibuffer-print-noclear "esc-") (key-prompt-1 1 (bit-clear 200 ch1) nil)) (t (key-prompt-1 0 ch1 nil)))))) (defun key-prompt-1 (metap key prefix) (prog (mf1) (and (or prefix (= metap 1)) (< key (1+ (CtoI "z")))(> key (1- (CtoI "a"))) (setq key (- key 40))) (setq mf1 (cond (prefix (arraycall t (key-bindings prefix 0) key)) (t (key-bindings key metap)))) (cond ((eq mf1 'escape) (minibuffer-print-noclear "esc-") (return (key-prompt-1 1 (get-char) nil))) ((not (symbolp mf1)) (minibuffer-print-noclear (printable key) " (prefix char): ") (return (key-prompt-1 0 (get-char) key))) (t (minibuffer-print-noclear (printable key)) (return (list metap key prefix)))))) (defun key-prompt-3args () (key-prompt "?: ")) (defun map-over-emacs-commands (fun arg) (let ((element (key-bindings i j))) (cond ((not (symbolp element)) (do k 0 (1+ k)(= k 256.) (or (not (arraycall t element k)) (eq (arraycall t element k) 'undefined-command) (funcall fun (key-total-printed-symbol 0 k i) (arraycall t element k) arg)))) ((eq element 'undefined-command)) (element (funcall fun (key-total-printed-symbol j i nil) element arg))))))) ESC Processing and Numeric Argument Readers (defcom command-quit &numeric-argument (&ignore) &undo &ignore (ring-tty-bell) (throw 'les-petites-gazongues pgazonga)) (defcom ignore-prefix &undo &ignore &numeric-argument (&ignore) (ring-tty-bell)) (defcom command-prompt-abort &numeric-argument (&ignore) &undo &ignore (throw nil gazongue-a-l/'yggdrasil)) Command bound to ESC key (defcom escape &undo-function &pass &numeric-argument (&pass) (and (eq minibufferp ESC) (jetteur-des-gazongues)) (escape-dont-exit-minibuf)) (defprop throw-to-toplevel jetteur-des-gazongues expr) (defcom-synonym escape-dont-exit-minibuffer escape-dont-exit-minibuf) (defcom undo-prefix &numeric-argument &pass &undo &pass (setq undo (not undo)) (process-char (get-char))) Command that does real work of ESC (defcom escape-dont-exit-minibuf &numeric-argument (&pass) &undo &pass (prog (nxcn numf negate) a (setq nxcn (get-char)) (or numarg (setq numarg 0)) (setq numarg (+ (- nxcn (CtoI "0")) (* 10. numarg))) (setq numf t) (go a)) (setq negate t numf t) (go a)) (setq numf t) (go a)) (setq numarg (- (or numarg 1)))) (cond (numf (process-char nxcn)) (t (execute-key 1 nxcn nil))))))) Command to collect numeric argument or use powers of 4 (defcom multiplier &undo &pass &numeric-argument (&pass) (prog (nxcn numf multf negate plus-given my-char) a (setq nxcn (get-char)) (or numf (setq numf 0)) (setq numf (+ (- nxcn (CtoI "0"))(* 10. numf))) (go a)) (setq numf 0 negate t) (go a)) (setq numf 0 plus-given t) (go a)) (cond ((and (not numf) (not multf)) (setq multf 4)) ((not numf) (setq multf (* multf 4))) (numf (setq numf nil)) (t (setq multf nil numf nil))) (go a)) (t (and (or negate plus-given) (= numf 0) (setq numarg (cond ((and numf multf) (* numf multf)) (numf) (multf (* 4 multf)) (t 4))) (process-char nxcn))))) Read a " metazied " number ( from Network mostly ) (defcom read-meta-argument &undo &pass &numeric-argument (&ignore) (prog (negate nxcn plus-given) (setq numarg 0) (cond ((= nxcn (CtoI "+")) (setq plus-given t)) ((= nxcn (CtoI "-")) (setq negate t)) (setq numarg (- nxcn (CtoI "0"))))) a (setq nxcn (get-char)) (cond ((and (> nxcn (1- (+ 200 (CtoI "0")))) (< nxcn (1+ (+ 200 (CtoI "9"))))) (setq numarg (+ (- nxcn (+ 200 (CtoI "0"))) (* 10. numarg))) (go a)) (and (= numarg 0) (or negate plus-given) (and negate (setq numarg (- numarg))) (process-char nxcn))))) (defun process-char (ch) (or (fixp ch) (setq ch (CtoI ch))) (let ((recursion-level (1+ recursion-level))) (cond ((and (not (zerop network-flag)) TELNET IAC (setq ch (get-char)) (cond ((= ch 377) (execute-key 1 177 nil)) (t (telnet-loser ch)))) (execute-key 1 ch nil)) (t (execute-key 0 ch nil))))) Execute a " key " as an Emacs command : A " key " is the triplet consisting (defun execute-key (metap ch prefix) (and (or (= metap 1) prefix) (and (< ch (1+ (CtoI "z"))) (> ch (1- (CtoI "a"))) (setq ch (- ch 40)))) (cond ((not prefix) (setq command (key-bindings ch metap))) (t (setq command (arraycall t (key-bindings prefix 0) ch)))) (setq last-command-triplet-mpfxk (cond ((= metap 1) 'meta) (t prefix)) last-command-triplet-1 ch) (execute-command command (last-command-triplet) nil)) (execute-key 0 (get-char) ch))))) (defvar (autoload-inform)) (defun ensure-autoload (command) (cond ((getl command '(editor-macro subr expr))) ((not (get command 'autoload))) ('else (if autoload-inform (minibuffer-print "Autoloading " command " ... ")) (protect (loadfile (get command 'autoload)) &success (if autoload-inform (minibuffer-print-noclear "done.")) &failure (if autoload-inform (minibuffer-print-noclear "failed.")))))) (setq last-time-sample nil) Execute an Emacs command (defun execute-command (command key argument-list) (ensure-autoload command) (setq current-command command) (or last-time-sample (setq last-time-sample (time))) (let ((last-time-sample 'dont-sample)) (or (null argument-list) (display-error (ed-get-name command key) " does not accept arguments.")) (push-editor-macro-level (get command 'editor-macro) (editor-macro-arg-interp numarg)) (setq previous-command command previous-argument-list nil)) (execute-new-command command key argument-list)) (or (null argument-list) (display-error (ed-get-name command key) " does not accept arguments.")) (execute-old-command command (last-command-triplet))))) (command-timing last-time-sample)) (setq numarg nil undo nil last-time-sample nil)) nil= > no bell . otherwise threshhold in seconds ( defprop command - bell t value - ok - anything ) ( defprop command - bell - count t value - ok - anything ) (defun command-timing (sample) (or (null sample) (not (floatp sample)) (let ((difference (-$ (time) sample))) (and command-bell (> difference (float command-bell)) (cond ((fixp command-bell-count) (do-times command-bell-count (ring-tty-bell))) (command-bell-count (funcall command-bell-count difference)))) (cond ((eq meter-commands 't) (minibuffer-print (decimal-rep difference) "s")) (meter-commands (funcall meter-commands difference)))))) (defun ed-get-name (command key) (catenate command (cond ((get command 'editor-macro) " (keyboard macro)") (t "")) (cond (key (catenate " (" (get-key-name key) ")")) (t "")))) (defun ed-cv-fixnum-check (argument) (let ((argument-list (exploden argument))) (do ((digit (car argument-list) (car argument-list)) (negate) (value)) ((not digit) (and negate (setq value (- value))) value) + as first char (setq value 0)) ((and (= digit #/-) (not value)) (setq value 0 negate t)) ((and (> digit (1- #/0)) (< digit (1+ #/9))) (setq value (+ (- digit #/0) (* 10. (or value 0))))) (return nil))) (setq argument-list (cdr argument-list))))) (setq *transparent-commands* '(escape multiplier noop re-execute-command extended-command)) Invoke a new - style Emacs command JSL 's new version - June 1982 (defun execute-new-command (command key argument-list) (do ((done) (flags (get command 'editor-command)) (function command) (ignore-rejected-numarg) (prologue-info) (result) (times)) (done result) (and (symbolp flags) (return (execute-command flags key argument-list))) (if undo (and (tlnn flags 000500) (setq undo nil)) (and (tlnn flags 000400) (return (execute-command (get command 'ed-undo-function) key argument-list))) (and (tlne flags 000700) (display-error (ed-get-name command key) " does not accept the undo prefix."))) (if numarg (if (tlnn flags 001000) (setq function (get function 'ed-numeric-function)) (ensure-autoload function) (or (and function (getl function '(subr lsubr fsubr expr lexpr fexpr))) (display-error (ed-get-name command key) " does not accept a numeric argument.")) (setq flags (or (get function 'editor-command) 0) ignore-rejected-numarg t)) (if (and (< numarg 0) (tlnn flags 200000)) (setq function (get function 'ed-negative-function)) (ensure-autoload function) (or (and function (getl function '(subr lsubr fsubr expr lexpr fexpr))) (display-error (ed-get-name command key) " does not " "accept a negative numeric argument.")) (setq flags (or (get function 'editor-command) 0) numarg (- numarg) ignore-rejected-numarg t)) (let ((numarg-type (logand flags (lsh 070000 18.))) (numarg-range (and (tlnn flags 100000) (get function 'ed-numeric-range)))) (setq times (ed-interpret-numarg command key numarg-type numarg-range ignore-rejected-numarg)))) (if (and (null argument-list) (cond (times (setq numarg nil)) (t (setq times 1))) (return (cond ((eq (cadr function) 'subr) (do ((i 1 (1+ i)) (f (caddr function)) (inv (or (memq command *transparent-commands*) (memq command nobreak-functions)))) ((> i times) result) (setq result (subrcall t f)) (or inv (setq previous-command command previous-argument-list nil)))) (t (do ((i 1 (1+ i)) (inv (or (memq command *transparent-commands*) (memq command nobreak-functions)))) ((> i times) result) (setq result (funcall function)) (or inv (setq previous-command command previous-argument-list nil))))))) (unwind-protect (progn (setq prologue-info (funcall (get function 'ed-prologue-function)))) (not (null argument-list))) (setq argument-list (ed-interpret-arguments command key function flags argument-list))) (cond (times (setq numarg nil)) (t (setq times 1))) (do ((epilogue (and (tlnn flags 002000) (get function 'ed-epilogue-function))) (i 1 (1+ i)) (inv (or (memq command *transparent-commands*) (memq command nobreak-functions)))) ((> i times)) (setq result (apply function argument-list)) (and epilogue (setq result (funcall epilogue prologue-info result (= i times)))) (or inv (setq previous-command command previous-argument-list argument-list))) (setq done (> times 0))) (and (not done) (setq done t) (tlnn flags 000040) (setq flags (get function 'ed-cleanup-function)) (funcall flags prologue-info))))) JSL 's new version - June 1982 (defun ed-interpret-numarg (command key numarg-type numarg-range ignore-rejected-numarg) (let ((lower (car numarg-range)) (upper (cdr numarg-range))) (setq lower (ed-get-encoded-value lower)) (display-error (ed-get-name command key) " does not accept a " "negative numeric argument.") (t (catenate "numeric argument < " (decimal-rep lower) "; you supplied " (decimal-rep numarg) "."))))))) (setq upper (ed-get-encoded-value upper)) (display-error (ed-get-name command key) " does not accept a " "positive numeric argument.") (t (catenate "numeric argument > " (decimal-rep upper) "; you supplied " (decimal-rep numarg) "."))))))))) nil) numarg) (setq numarg nil)) (ignore-rejected-numarg (setq numarg nil)) (t (display-error (ed-get-name command key) " does not accept a numeric argument.")))) (defun ed-interpret-arguments (command key function flags argument-list) (let ((nargs-given (length argument-list)) (nargs-wanted (logand flags 777777)) (args-template (get function 'ed-argument-list))) (display-error (ed-get-name command key) " does not accept arguments.")) (args-wanted args-template (cdr args-wanted)) (args-given argument-list (cdr args-given)) (new-arguments)) (setq new-arguments (cons (ed-interpret-single-arg command key nargs-wanted nargs-given i (car args-wanted) (car args-given) (= i nargs-wanted) (cdr args-given)) new-arguments))))) (defun ed-interpret-single-arg (command key nargs-wanted nargs-given arg-no arg-template arg-supplied last-argp rest-of-args-supplied) (logand (car arg-template) (lsh 700000 18.))) non - zero = > prompt if missing (tlnn (car arg-template) 040000)) non - zero = > default value exists (tlnn (car arg-template) 020000)) non - zero = > value is restricted (tlnn (car arg-template) 010000)) (prompt-info (cadr arg-template)) (default-info (caddr arg-template)) (restriction-info (cadddr arg-template)) (show-error (cond ((tlnn (car arg-template) 040000) 'display-error-noabort) (t 'display-error))) (completion-list (eval (car (cddddr arg-template))))) (have-argument)) (cond (or last-argp (display-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " is a rest-of-arguments type, but " "is not the last argument.")) the-argument (cond ((= data-type (lsh 300000 18.)) (catenate (or arg-supplied "") (do ((args rest-of-args-supplied (cdr args)) (x "" (catenate x " " (car args)))) ((null args) x)))) (append (and arg-supplied (list arg-supplied)) rest-of-args-supplied))))) ((and last-argp rest-of-args-supplied) (display-error (ed-get-name command key) " expects " (decimal-rep nargs-wanted) " arguments;" " you supplied " (decimal-rep nargs-given) ".")) (the-argument (setq have-argument t)) (let ((x (ed-interpret-symbol-arg command key arg-no the-argument show-error have-restrictions restriction-info))) (setq the-argument (car x) have-argument (cdr x)))) ((= data-type (lsh 200000 18.)) (let ((x (ed-interpret-integer-arg command key arg-no the-argument show-error have-restrictions restriction-info))) (setq the-argument (car x) have-argument (cdr x)))) (display-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " has an unknown data type.")))) (setq the-argument (minibuf-response (ed-get-encoded-value (car prompt-info)) (cdr prompt-info))) (setq the-argument (ed-get-encoded-value default-info)))) (setq the-argument (ed-get-encoded-value default-info))) (display-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " has no prompt or default value.") ))))))) (defun ed-interpret-symbol-arg (command key arg-no the-argument show-error have-restrictions restriction-info) (let ((argument (intern (make_atom (e_lap_$trim the-argument)))) (let ((possible-values (ed-get-encoded-value restriction-info))) (cond ((memq the-argument possible-values) (setq have-argument t)) (funcall show-error "Argument # " (decimal-rep arg-no) " of " (ed-get-name command key) " must be one of:" (do ((values possible-values (cdr possible-values)) (x "" (catenate x " " (car values)))) ((null values) x))) (setq have-argument t))) (cons argument have-argument))) (defun ed-interpret-integer-arg (command key arg-no the-argument show-error have-restrictions restriction-info) (let ((value (cond ((fixp the-argument) the-argument) (t (ed-cv-fixnum-check the-argument)))) (let ((lower (car restriction-info)) (upper (cdr restriction-info))) (setq lower (ed-get-encoded-value lower)) (cond ((< value lower) (cond ((= lower 0) (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must not be " "negative.")) (t (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must be >= " (decimal-rep lower) "; you supplied " (decimal-rep value) "."))) (setq value nil))))) (setq upper (ed-get-encoded-value upper)) (cond ((> value upper) (cond ((= upper -1) (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must not be " "positive.")) (t (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must be <= " (decimal-rep upper) "; you supplied " (decimal-rep value) "."))) (setq value nil)))))) (setq have-argument t))) (setq have-argument t)))) (funcall show-error "Argument #" (decimal-rep arg-no) " of " (ed-get-name command key) " must be an integer, not " the-argument ".") (cons value have-argument))) (defun ed-get-encoded-value (encoded-value) (let ((type (car encoded-value)) (value (cadr encoded-value))) (display-error "Unknown value encoding: " type))))) Execute an old style Emacs command Slightly modified by JSL ( mostly format ) - June 1982 (defun execute-old-command (command key) (let ((function command) (numarg-repeat)) (setq numarg-repeat (get command 'argwants)) (and (< (or numarg 1) 0) numarg-repeat (setq numarg (- numarg) function (or (get command 'negative-arg-function) 'bad-negative-argument))) (or (eq (cadr function) 'subr) (get function 'subr) (get function 'expr) (get function 'autoload) (display-error "Undefined function " function " for " command " (" (get-key-name key) ")")) (setq numarg-repeat (cond (numarg-repeat (or numarg 1)) (t 1))) (cond ((eq (cadr function) 'subr) (do ((i 1 (1+ i)) (f (caddr function))) ((> i numarg-repeat)) (subrcall t f) (setq previous-command command previous-argument-list nil))) (t (do ((i 1 (1+ i))) ((> i numarg-repeat)) (funcall function) (setq previous-command command previous-argument-list nil)))))) (defun execute-command-function (command function ntimes argument-list) (cond ((and (eq (cadr function) 'subr) (< (length argument-list) 5)) (do ((i 1 (1+ i)) (f (caddr function)) (nargs (length argument-list))) ((> i ntimes)) (cond ((= nargs 0) (subrcall t f)) ((= nargs 1) (subrcall t f (car argument-list))) ((= nargs 2) (subrcall t f (car argument-list) (cadr argument-list))) ((= nargs 3) (subrcall t f (car argument-list) (cadr argument-list) (caddr argument-list))) ((= nargs 4) (subrcall t f (car argument-list) (cadr argument-list) (caddr argument-list) (car (cdddr argument-list))))) (or (memq command '(escape multiplier noop re-execute-command extended-command)) (setq previous-command command previous-argument-list argument-list)))) (t (do i 1 (1+ i) (> i ntimes) (apply function argument-list) (or (memq command '(escape multiplier noop re-execute-command extended-command)) (setq previous-command command previous-argument-list argument-list)))))) Emacs command to re - execute the last command (defcom re-execute-command &undo &pass &numeric-argument (&pass) (or previous-command (display-error "No saved previous command")) (execute-command previous-command nil previous-argument-list)) Emacs command invoked for an unbound key (defcom undefined-command &numeric-argument (&ignore) &undo &ignore (display-error "Unknown command: " (get-key-name (last-command-triplet)))) Emacs command invoked for a key whose command does n't accept negative arguments (defcom bad-negative-argument &undo &ignore &numeric-argument (&ignore) (display-error "Command rejected negative argument: " (get-key-name (last-command-triplet)))) (defun last-command-triplet () (cond ((eq last-command-triplet-mpfxk 'meta) (list 1 last-command-triplet-1 nil)) (t (list 0 last-command-triplet-1 last-command-triplet-mpfxk)))) ESC - X Command New version : 27 August 1979 by GMP Invoke an Emacs command with arguments as read from mini - buffer (defcom extended-command &arguments ((command-line &prompt "Command: " &completions Fundamental/.ext-commands)) &numeric-argument (&pass) &undo &pass (if (not (null command-list)) (let ((command-name (car command-list)) (arguments (cdr command-list))) (let ((command (intern (make_atom command-name)))) (ensure-autoload command) (cond ((getl command '(editor-command editor-macro)) (execute-command command nil arguments)) (t (execute-old-extended-command command arguments))))))))) Parse a line into tokens , obeying the Multics quoting convention (defun parse-command-line (line) (do ((input (exploden line)) (answer nil)) (nil) (setq input (do ((input1 input (cdr input1))) ((or (null input1) (not (member (car input1) '(#^I #^J #/ )))) input1))) (cond ((null input) (return (nreverse answer))) (t (setq answer (cons (do ((result "")) ((or (null input) (member (car input) '(#^I #^J #/ ))) result) (setq result (catenate result (cond ((= (car input) #/") (do ((input1 (cdr input) (cdr input1)) (quoted t) (piece "")) ((not quoted) (setq input input1) piece) (cond ((null input1) (display-error "Unbalanced quotes.")) ((and (= (car input1) #/") (equal (cadr input1) #/")) (setq input1 (cdr input1) piece (catenate piece """"))) ((= (car input1) #/") (setq quoted nil)) (t (setq piece (catenate piece (ItoC (car input1)))))))) (t (do ((input1 (cdr input) (cdr input1)) (piece (ItoC (car input)) (catenate piece (ItoC (car input1))))) ((or (null input1) (member (car input1) '(#^I #^J #/ #/"))) (setq input input1) piece))))))) answer)))))) (defun execute-old-extended-command (command arguments) (or (getl command '(expr subr lsubr autoload)) (display-error "Unknown command: " command)) (ensure-autoload command) (let ((argsprop (args command)) (nargs (length arguments))) ((and (not (< nargs (or (car argsprop) (cdr argsprop)))) (not (> nargs (cdr argsprop)))) (t (display-error "Wrong number of arguments to extended command " command ".")))) (new-arg-list nil (cons (let ((argument (car args)) (value)) (setq value (ed-cv-fixnum-check argument)) (cond (value value) (t (intern (make_atom argument))))) new-arg-list))) ((null args) (nreverse new-arg-list))))) Appreciations to " EINE " E.L.E. , Redone pretty much wholesale 2/11/79 to allow " input chars " . Have a good time in California , DLW , thanks for everything , -bsg . (defun kmacro-get-one-cmd (expected-type) (let ((this (car macro-execution-in-progress)) (rest (cdr macro-execution-in-progress))) (cond ((and (numberp this)(eq expected-type 'input-char)) (setq macro-execution-in-progress rest) this) ((eq expected-type 'toplevel-char) (cond ((eq this 'macend) (execute-single-editor-enmacroed-command 'macend) (cond (macro-execution-in-progress (kmacro-get-one-cmd expected-type)) (t nil))) ((atom this) (display-error "Keyboard macro lost synchrony.")) ((eq (car this) 'toplevel-char) (setq macro-execution-in-progress rest) (cdr this)) (t nil))) ((eq expected-type 'input-char) (cdr this))))) character . Toplevelness is stored for ease in displaying definition . ( An idea by ) (defun kmacro-record-input (ch type) (setq macro-collection-in-progress (cons (cond ((eq type 'toplevel-char) (cons 'toplevel-char ch)) (t ch)) macro-collection-in-progress))) The commands to start and stop collecting macroes ( macros ? , macreaux ? ) (defcom begin-macro-collection &numeric-argument (&reject) (cond (macro-collection-in-progress (display-error "Macro already in collection.")) aaah , (command-quit)) (t (assert-minor-mode 'Macro/ Learn) (setq macro-collection-in-progress (list nil))))) (defcom end-macro-collection &numeric-argument (&pass) (wrap-up-macro-definition) (and numarg (execute-last-editor-macro))) (defun editor-macro-arg-interp (arg) ((= arg 0) 'query) ((< arg 0) 'forever) ((> arg 9999.) 'forever) (t arg))) (defun push-editor-macro-level (mac ntimes) (and (> (length macrostack) 20.) (display-error "Too much macro recursion.")) (and macrostack (rplaca (cdr (car macrostack)) macro-execution-in-progress)) (setq macrostack (cons (list mac mac ntimes) macrostack)) (setq macro-execution-in-progress (cadr (car macrostack)))) (defun wrap-up-macro-definition () (or macro-collection-in-progress (display-error "No macro in progress.")) (negate-minor-mode 'Macro/ Learn) (setq last-macro-definition (cdr (nreverse (cons 'macend (do ((l macro-collection-in-progress (cdr l))) ((null l)(display-error "Void macro.")) (and (not (atom (car l))) (eq (caar l) 'toplevel-char) (return (cdr l)))))))) (setq macro-collection-in-progress nil)) (defcom execute-last-editor-macro &numeric-argument (&pass) (or last-macro-definition (display-error "No macro to run.")) (push-editor-macro-level last-macro-definition (editor-macro-arg-interp numarg))) (defun execute-single-editor-enmacroed-command (x) ((eq x 'halt) (setq macrostack (cdr macrostack)) (setq macro-execution-in-progress (cadar macrostack))) ((eq x 'repeat) (setq macro-execution-in-progress (caar macrostack)) (rplaca (cdar macrostack) macro-execution-in-progress)) ((eq x 'macend) (let ((count (caddar macrostack))) (cond ((eq count 'query) (cond ((macro-query-get-answer) (execute-single-editor-enmacroed-command 'repeat)) (t (execute-single-editor-enmacroed-command 'halt)))) ((eq count 'forever) (execute-single-editor-enmacroed-command 'repeat)) ((< count 2) (execute-single-editor-enmacroed-command 'halt)) (t (rplaca (cddar macrostack) (1- count)) (setq macro-execution-in-progress (caar macrostack)) (rplaca (cdar macrostack) macro-execution-in-progress))))) (t (display-error "Internal macro format error: " x))))))) Macro utilities (defcom save-macro &prologue &eval (or last-macro-definition (display-error "No macro defintion to store.")) &arguments ((macro-name &symbol &default &eval (let ((name (intern-minibuf-response "Macro name? " NL))) (cond ((getl name '(editor-command expr subr autoload)) (display-error name " is not an acceptable name.")) (t name)))) (macro-key &symbol &default &eval (get-key-name (key-prompt "On what key? ")))) &numeric-argument (&reject) (putprop macro-name last-macro-definition 'editor-macro) (set-key macro-key macro-name))) (defcom show-last-or-current-macro &numeric-argument (&pass) (cond (macro-collection-in-progress (wrap-up-macro-definition))) (show-editor-macro last-macro-definition)) (defcom show-macro &arguments ((macro-name &symbol &prompt "Macro name: ")) &numeric-argument (&pass) (cond ((get macro-name 'editor-macro) (show-editor-macro (get macro-name 'editor-macro))) (t (display-error macro-name " is not a defined macro.")))) (defun kmacro-display-interpret (x) (prog (the-interpretation the-input fun prefix metap numbering stringing l2list whoops) (setq the-input (nreverse (cdr (reverse x)))) tlc (cond ((null the-input) (cond (stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation)))) (return (nreverse the-interpretation)))) (setq x (car the-input) the-input (cdr the-input)) (setq prefix nil) (cond ((> x char-input-mask) (setq x (bit-clear 200 x) metap 1)) (t (setq metap 0))) (setq fun (get-key-binding (list metap x nil)) whoops x) (cond (numbering (cond ((kmacro-numberp x) (setq numbering (cons x numbering)) (go tlc)) (t (setq the-interpretation (cons (cons (implode (nreverse numbering)) 'Numeric/ argument) the-interpretation) numbering nil))))) ARRAYP (setq prefix x)) ((or (eq fun 'escape) (eq fun 'escape-dont-exit-minibuf)) (and stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation) stringing nil)) (cond ((and (eq fun 'escape) the-input (not (atom (car the-input))))) probbly was ESC ending minibuffer , next was tlc . ((and the-input (kmacro-number-or-plusminusp (car the-input))) (setq numbering (list (kmacro-number-or-plusminusp (car the-input))) the-input (cdr the-input)) (setq the-interpretation (cons (cons (key-total-printed-symbol metap x prefix) fun) the-interpretation)) (go tlc)) (t (setq metap 1) (cond ((null the-input) (setq x whoops prefix nil metap 0)) (t (setq x (cond ((numberp (car the-input)) (car the-input)) (t (cdar the-input))) the-input (cdr the-input)) (and (> x (1- (CtoI "a"))) (< x (1+ (CtoI "z"))) (setq x (- x 40)))))))) ((eq fun 'multiplier) (and stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation) stringing nil)) (setq the-interpretation (cons (cons (key-total-printed-symbol metap x prefix) fun) the-interpretation)) (cond ((and the-input (kmacro-number-or-plusminusp (car the-input))) (setq numbering (list (kmacro-number-or-plusminusp (car the-input))) the-input (cdr the-input)))) (go tlc))) (cond ((not (null prefix)) (cond ((null the-input)(setq x whoops prefix nil metap 0)) (t (setq x (cond ((numberp (car the-input)) (car the-input)) (t (cdar the-input))) the-input (cdr the-input)) (and (> x (1- (CtoI "a")))(< x (1+ (CtoI "z"))) (setq x (- x 40))))))) (setq fun (get-cmd-symbol-3args metap x prefix)) (cond ((memq fun '(self-insert overwrite-mode-self-insert)) (setq stringing (cons (ascii x) stringing))) (t (cond (stringing (setq the-interpretation (kmacro-stringing-util stringing the-interpretation) stringing nil))) (setq the-interpretation (cons (cons (key-total-printed-symbol metap x prefix) (get-cmd-symbol-3args metap x prefix)) the-interpretation)))) (setq l2list nil) cl2c (cond ((or (null the-input) collect lev 2 ch (eq (caar the-input) 'toplevel-char))) (cond (l2list (setq the-interpretation (cons (cons (apply 'catenate (nreverse l2list)) 'Input/ Characters) the-interpretation)))) (go tlc)) (t (setq l2list (cons (ascii (car the-input)) l2list) the-input (cdr the-input)) (go cl2c))))) (defun kmacro-stringing-util (s int) (map '(lambda (x)(cond ((eq (car x) '/")(rplaca x """""")))) s) (cons (cons (catenate """" (apply 'catenate (nreverse s)) """") 'String) int)) (defun kmacro-numberp (x) (cond ((numberp x)) ((not (atom x))(setq x (cdr x)))) (and (> x (1- (CtoI "0"))) (< x (1+ (CtoI "9"))) x)) (defun kmacro-number-or-plusminusp (x) (cond ((numberp x)) ((not (atom x)) (setq x (cdr x)))) (cond ((and (> x (1- (CtoI "0"))) (< x (1+ (CtoI "9")))) x) ((= x (CtoI "+")) '+) ((= x (CtoI "-")) '-))) (defun show-editor-macro (x) Figger out what it means . (init-local-displays) (t (local-display-generator-nnl (do ((mac x (cdr mac)) (stuff nil (cons (caar mac) stuff))) WARNING 511 limit (mapcar '(lambda (y)(catenate " " y)) (nreverse stuff)))))))) (end-local-displays)) (defun show-editor-macro-2 (x) (local-display-generator-nnl (catenate (car x) TAB (cond ((getl (setq x (cdr x)) '(expr subr autoload)) x) ((memq x '(String Input/ Characters Numeric/ argument)) x) ((get x 'editor-macro) (catenate x " (keyboard macro)")) (t "--????--"))))) (defcom macro-query &numeric-argument (&reject) (cond (macro-collection-in-progress (display-error-noabort "Inserting query at this point.")) ((not macro-execution-in-progress) (display-error "macro query: no macro running.")) (t (cond ((not (macro-query-get-answer)) (setq macro-execution-in-progress (caar macrostack))))))) (defun macro-query-get-answer () (let ((macro-execution-in-progress nil) (macro-collection-in-progress nil)) (echo-buffer-print "ok? :") (redisplay) (do ((ans (get-char)(get-char))) (nil) (cond ((= ans 7)(command-quit)) ((= ans 161)(command-quit)) ((= ans 12)) ((= ans 40)(return t)) ((= ans 15)(return nil)) (t (return nil)))))) Improvements for process preservation - BSG 3 December ' 79 (defun emacs-quit-handler (arg) (setq arg arg) (signalquit)) (defcom signalquit &undo &ignore &numeric-argument (&ignore) (cond ((eq e-quit-transparency 'transparent) This is to check flag safely even if NIL gets clobbered ! If this thing blows , you simply ca n't hit quit on Emacs . (e-quit-transparency 'transparent)) (or oqt (progn (clear-the-screen) (and split-mode-p (rdis-restore-screen-to-one-split)))) (and DCTL-epilogue-availablep (DCTL-epilogue)) (e_pl1_$dump_output_buffer) (e_pl1_$set_multics_tty_modes) (terpri) (cond ((and (eq emacs-name 'emacs_) quit-on-break) (emacs$set_emacs_return_code (error_table_ 'action_not_performed)) (or tasking-emacs (lisp-quit-function)))) (signalquit-hardcore-vt132-writearound) (ioc z) (e_pl1_$set_emacs_tty_modes) (and DCTL-prologue-availablep (DCTL-prologue)) (and split-mode-p (rdis-recreate-splits-on-screen)) (full-redisplay) (display-error-noabort "Restarting from QUIT... ") (redisplay))))))) Writearound for the hardcore / vt132 bug that causes screen to not ( 1 ) Emacs sends characters to fix up screen . ( 2 ) Emacs does ( ioc z ) , causing signal _ quit . ( 3 ) default_error_handler _ does a resetwrite . ( 5 ) Screen stays screwed , though no longer in Emacs . ( 6 ) User gets confused . The only solutions are : ( 1 ) Do write_status 's until all output is out , or ( 2 ) Just do a ( sleep ) of some interesting length . I chose the sleep 14 November 1981 (defun signalquit-hardcore-vt132-writearound () (and (eq tty-type 'vt132) (sleep 2))) (defcom noop &numeric-argument (&ignore) &undo &ignore ) to " quit - the - editor " , a much nicer function from Emacs ' point of view . (putprop 'lisp-quit-function (get 'quit 'subr) 'subr) (remprop 'quit 'subr) (defcom-synonym quit quit-the-editor) Exit from EMACS (defcom quit-force &numeric-argument (&reject) (clear-reset) (set-lisp-rdis-meters) (alarmclock 'time nil) (alarmclock 'runtime nil) (cond ((zerop (e_tasking_$quit)) (tasking-restart)) (t (lisp-quit-function)))) (defun clear-reset () (clear-the-screen) (and split-mode-p (rdis-restore-screen-to-one-split)) (and DCTL-epilogue-availablep (DCTL-epilogue)) (e_pl1_$dump_output_buffer) (e_pl1_$set_multics_tty_modes)) Restart a tasking Emacs . (defun tasking-restart () (tasking-restart-internal) (pi-handler)) (defun tasking-restart-internal () (e_pl1_$init) (e_pl1_$set_emacs_tty_modes) (randomize-redisplay) (and DCTL-prologue-availablep (DCTL-prologue)) (let ((su-args (e_argument_parse_$get_startup_info))) (setq args:apply-arg (caddr (cddddr su-args)) args:paths (caddr su-args)) (setq emacs-start-ups-need-running 'default-emacs-start-up) (init-echnego-bittab)) (clear-the-screen) (setq tasking-restarted t)) (defun okay-to-quit? () (do ((buffers known-buflist (cdr buffers)) (found nil)) ((null buffers) (cond ((not found) t) (t (init-local-displays) (local-display-generator-nnl "Modified Buffers:") (local-display-generator-nnl "") (mapc 'local-display-buffer-info found) (local-display-generator-nnl "-------------------------") (yesp "Modified buffers exist. Quit?")))) (and (not (get (car buffers) 'dont-notice-modified-buffer)) (not (empty-buffer-p (car buffers))) (get-buffer-state (car buffers) 'buffer-modified-flag) (setq found (cons (car buffers) found))))) (defun local-display-buffer-info (buffer) (let ((path (get-buffer-state buffer 'fpathname))) (local-display-generator-nnl (catenate (cond ((eq current-buffer buffer) ">") ((eq previous-buffer buffer) "<") (t " ")) (cond ((get-buffer-state buffer 'buffer-modified-flag) "*") (t " ")) (cond (path (catenate buffer (substr " " 1 (max (- 25. (stringlength buffer)) 1)) path)) (t buffer)))))) Mark this Emacs as dead if tasking , then quit . (defcom destroy-task (and minibufferp (display-error "No quitting while in the minibuffer.")) (cond ((not tasking-emacs) (display-error "This is not a tasking Emacs.")) ((not (okay-to-quit?)) (command-quit)) (t (e_tasking_$destroy_me) (run-emacs-epilogue-actions) (quit-force)))) Exit from EMACS if no buffers are modified or user says OK (defcom quit-the-editor &numeric-argument (&reject) (and minibufferp (display-error "No quitting while in the minibuffer.")) (cond (tasking-emacs (clear-reset) (e_tasking_$quit) (tasking-restart)) ((okay-to-quit?) (run-emacs-epilogue-actions) (quit-force)) (t (command-quit)))) 5/6/80 (do nil ((null emacs-epilogue-action-list)) (errset (apply (caar emacs-epilogue-action-list) (cdar emacs-epilogue-action-list))) (setq emacs-epilogue-action-list (cdr emacs-epilogue-action-list)))) (defun set-emacs-epilogue-handler (fnandargs dupflg) (or (and dupflg (assq (car fnandargs) emacs-epilogue-action-list)) (setq emacs-epilogue-action-list (cons fnandargs emacs-epilogue-action-list)))) (defun telnet-loser (c) (signalquit)) IAC DO (setq c (e_pl1_$get_char)) (display-error-noabort "Ignoring TELNET IAC DO " (implode (explodec c)))))) IAC DONT (setq c (e_pl1_$get_char)) (display-error-noabort "Ignoring TELNET IAC DONT " (implode (explodec c)))))) (t (display-error-noabort "Ignoring TELNET IAC " (implode (explodec c)) "(octal). Good luck.")))) (defun define-autoload-lib fexpr (x) (mapc '(lambda (y)(set-autoload-lib y (car x)))(cdr x))) HELP ! What did I type ? ! ? ! ? 2/11/79 (defcom help &undo &ignore &numeric-argument (&ignore) (init-local-displays) (local-display-generator-nnl (catenate "Help segments on Emacs are found in " documentation-dir ".")) (mapc 'local-display-generator-nnl '("See emacs.gi.info there for full information on everything." "Type the escape key, the question mark key, and some key that" "you want to know about to find out about it. Type a control underscore" "at any time to get more help. Type control underscore" "and a question mark for all help commands." "Type two linefeeds to remove this display," "or any other display that ends with -- * * * * * * * --," "from your screen.")) (end-local-displays)) (defcom-synonym ? help) (defcom help-on-tap &numeric-argument (&ignore) &undo &ignore (minibuffer-print "HELP: (? for more info): ") (do x (get-char)(get-char) nil (and (> x (1- #/a)) (< x (1+ #/z)) (setq x (- x 40))) (cond ((= x 12)) ((= x #/H)(help)) ((= x #/C)(execute-command 'describe-key nil nil)) ((= x #/D)(execute-command 'describe nil nil)) ((= x #/A)(execute-command 'apropos nil nil)) ((= x #/L)(help-list-typin)) ((= x #/?)(help-whats-on-tap)) (t (help-whats-on-tap))) (or (= x 12)(return nil))) (minibuffer-print "")) (defun help-whats-on-tap () (init-local-displays) (mapc 'local-display-generator-nnl '("^_ H gives general help info." "^_ ? gives this list of what ^_ can do." "^_ A followed by a word and a CR looks for appropriate" " matching commands. Type ^_ D apropos CR for more on this." "^_ C prompts for a character (or key sequence) and tells what it does." "^_ D followed by an extended command name and a CR tells" " about the extended command." "^_ L Lists the last 50 characters or commands typed.")) (local-display-generator-nnl "Type two linefeeds to remove this display from your screen.") (end-local-displays)) (defun help-list-typin () (do ((stop (cond ((= history-next-index 0) 50.) (t history-next-index))) (cur history-next-index (1+ cur)) (first t nil) (nl) (l)) ((and (not first)(= cur stop)) (do c 0 (1+ c)(= c 50.) (or l (return nil)) (setq nl (cons (car l) nl) l (cdr l))) (init-local-displays) (do ((line (catenate (printable (car nl)) " ") (catenate line (cond (nl (printable (car nl))) (t "")) " "))) ((null nl) (or (nullstringp line)(samepnamep line " ") (local-display-generator-nnl line))) (cond ((> (stringlength line)(- screenlinelen 6)) (local-display-generator-nnl line) (setq line ""))) (setq nl (cdr nl)))) (and (= cur 50.)(setq cur 0)) (cond ((numberp (saved-command-history cur)) (setq l (cons (saved-command-history cur) l))) ((null (saved-command-history cur))) Next case is combined chars from get - top - level - char - innards (t (setq l (append (nreverse (explodec (saved-command-history cur))) l))))) (local-display-generator-nnl "Type two linefeeds to remove this display from the screen.") (end-local-displays))
fd8db4ce33861c13c5e3e302f6d0f3ba287390f2a1fe16678c87c4b43b7fce91
dbuenzli/remat
remat.ml
--------------------------------------------------------------------------- Copyright 2012 . All rights reserved . Distributed under the BSD3 license , see license at the end of the file . % % NAME%% release % % --------------------------------------------------------------------------- Copyright 2012 Daniel C. Bünzli. All rights reserved. Distributed under the BSD3 license, see license at the end of the file. %%NAME%% release %%VERSION%% ---------------------------------------------------------------------------*) * Remat main program . open Cmdliner let cmds = [ Cmd_convert.cmd; Cmd_browser.cmd; Cmd_publish.cmd; Cmd_help.cmd ] let main () = match Term.eval_choice Cmd_default.cmd cmds with | `Ok ret -> exit ret | `Error _ -> exit 1 | `Help | `Version -> exit 0 let () = main () --------------------------------------------------------------------------- Copyright 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 : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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 . --------------------------------------------------------------------------- Copyright 2012 Daniel C. Bünzli All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Daniel C. Bünzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/remat/28d572e77bbd1ad46bbfde87c0ba8bd0ab99ed28/src-remat/remat.ml
ocaml
--------------------------------------------------------------------------- Copyright 2012 . All rights reserved . Distributed under the BSD3 license , see license at the end of the file . % % NAME%% release % % --------------------------------------------------------------------------- Copyright 2012 Daniel C. Bünzli. All rights reserved. Distributed under the BSD3 license, see license at the end of the file. %%NAME%% release %%VERSION%% ---------------------------------------------------------------------------*) * Remat main program . open Cmdliner let cmds = [ Cmd_convert.cmd; Cmd_browser.cmd; Cmd_publish.cmd; Cmd_help.cmd ] let main () = match Term.eval_choice Cmd_default.cmd cmds with | `Ok ret -> exit ret | `Error _ -> exit 1 | `Help | `Version -> exit 0 let () = main () --------------------------------------------------------------------------- Copyright 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 : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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 . --------------------------------------------------------------------------- Copyright 2012 Daniel C. Bünzli All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Daniel C. Bünzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*)
dbfcb5455b01b168a539376a311e6a2722034f016b866a219481ddf20af31892
rjnw/sham
arith-stx.rkt
#lang racket (require syntax/parse) (require sham/sam/transform) (require "../ast/basic-math.rkt") #;(define-ast math (expr [neg ('- e)] [div ('/ n d)] [add ('+ e ...)] [sub ('- e1 e2 ...)] [mul ('* e ...)]) #:with struct-helpers sexp-printer #:format (#f - #f - -)) (define-transform (parse-math) (rkt-syntax -> math-ast) (mexpr (stx -> val) [n:integer (make-num (syntax-e n))] [('- e:mexpr e2:mexpr ...) (make-sub e e2)] [('/ n:mexpr d:mexpr) (make-div n d)] [('+ es:mexpr ...) (make-add es)] [('* es:mexpr ...) (make-mul es)])) (module+ test (require rackunit) )
null
https://raw.githubusercontent.com/rjnw/sham/6e0524b1eb01bcda83ae7a5be6339da4257c6781/sham-sam/sham/sam/test/transform/arith-stx.rkt
racket
(define-ast math
#lang racket (require syntax/parse) (require sham/sam/transform) (require "../ast/basic-math.rkt") (expr [neg ('- e)] [div ('/ n d)] [add ('+ e ...)] [sub ('- e1 e2 ...)] [mul ('* e ...)]) #:with struct-helpers sexp-printer #:format (#f - #f - -)) (define-transform (parse-math) (rkt-syntax -> math-ast) (mexpr (stx -> val) [n:integer (make-num (syntax-e n))] [('- e:mexpr e2:mexpr ...) (make-sub e e2)] [('/ n:mexpr d:mexpr) (make-div n d)] [('+ es:mexpr ...) (make-add es)] [('* es:mexpr ...) (make-mul es)])) (module+ test (require rackunit) )
e1c1bc29f1b966a1eb079e3dddf7a118b0d444e89b7d19fb535320baca02c129
scrintal/heroicons-reagent
archive_box.cljs
(ns com.scrintal.heroicons.outline.archive-box) (defn render [] [:svg {:xmlns "" :fill "none" :viewBox "0 0 24 24" :strokeWidth "1.5" :stroke "currentColor" :aria-hidden "true"} [:path {:strokeLinecap "round" :strokeLinejoin "round" :d "M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/outline/archive_box.cljs
clojure
(ns com.scrintal.heroicons.outline.archive-box) (defn render [] [:svg {:xmlns "" :fill "none" :viewBox "0 0 24 24" :strokeWidth "1.5" :stroke "currentColor" :aria-hidden "true"} [:path {:strokeLinecap "round" :strokeLinejoin "round" :d "M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z"}]])
45629757a3989becd0502f844da05972633455d5c0580769a7855ed0bf46416e
mdsebald/link_blox_app
lblx_sample_hold.erl
%%% @doc BLOCKTYPE %%% Sample and Hold input values %%% DESCRIPTION %%% Output values will equal corresponding input values as long as hold input is false %%% When hold input value is true, outputs will be held at the last value %%% regardless of the input values. %%% LINKS %%% @end -module(lblx_sample_hold). -author("Mark Sebald"). -include("../block_state.hrl"). %% ==================================================================== %% API functions %% ==================================================================== -export([groups/0, version/0]). -export([create/2, create/4, create/5, upgrade/1, initialize/1, execute/2, delete/1]). groups() -> [control]. version() -> "0.1.0". %% Merge the block type specific, Config, Input, and Output attributes %% with the common Config, Input, and Output attributes, that all block types have -spec default_configs(BlockName :: block_name(), Description :: string()) -> config_attribs(). default_configs(BlockName, Description) -> attrib_utils:merge_attribute_lists( block_common:configs(BlockName, ?MODULE, version(), Description), [ {num_of_values, {1}} %| int | 1 | 1..99 | ]). -spec default_inputs() -> input_attribs(). default_inputs() -> attrib_utils:merge_attribute_lists( block_common:inputs(), [ {hold, {false, {false}}}, %| bool | false | true, false | {inputs, [{empty, {empty}}]} %| array of any | empty | N/A | ]). -spec default_outputs() -> output_attribs(). default_outputs() -> attrib_utils:merge_attribute_lists( block_common:outputs(), [ {outputs, [{null, []}]} %| array of any | null | N/A | ]). %% %% Create a set of block attributes for this block type. Init attributes are used to override the default attribute values %% and to add attributes to the lists of default attributes %% -spec create(BlockName :: block_name(), Description :: string()) -> block_defn(). create(BlockName, Description) -> create(BlockName, Description, [], [], []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs) -> create(BlockName, Description, InitConfig, InitInputs, []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs(), InitOutputs :: output_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs, InitOutputs) -> % Update Default Config, Input, Output, and Private attribute values % with the initial values passed into this function. % % If any of the intial attributes do not already exist in the % default attribute lists, merge_attribute_lists() will create them. Config = attrib_utils:merge_attribute_lists(default_configs(BlockName, Description), InitConfig), Inputs = attrib_utils:merge_attribute_lists(default_inputs(), InitInputs), Outputs = attrib_utils:merge_attribute_lists(default_outputs(), InitOutputs), % This is the block definition, {Config, Inputs, Outputs}. %% %% Upgrade block attribute values, when block code and block data versions are different %% -spec upgrade(BlockDefn :: block_defn()) -> {ok, block_defn()} | {error, atom()}. upgrade({Config, Inputs, Outputs}) -> ModuleVer = version(), {BlockName, BlockModule, ConfigVer} = config_utils:name_module_version(Config), BlockType = type_utils:type_name(BlockModule), case attrib_utils:set_value(Config, version, version()) of {ok, UpdConfig} -> m_logger:info(block_type_upgraded_from_ver_to, [BlockName, BlockType, ConfigVer, ModuleVer]), {ok, {UpdConfig, Inputs, Outputs}}; {error, Reason} -> m_logger:error(err_upgrading_block_type_from_ver_to, [Reason, BlockName, BlockType, ConfigVer, ModuleVer]), {error, Reason} end. %% Initialize block values %% Perform any setup here as needed before starting execution %% -spec initialize(BlockState :: block_state()) -> block_state(). initialize({Config, Inputs, Outputs, Private}) -> case config_utils:get_integer_range(Config, num_of_values, 1, 99) of {ok, NumOfValues} -> Create N inputs and outputs BlockName = config_utils:name(Config), Inputs1 = input_utils:resize_attribute_array_value(BlockName, Inputs, inputs, NumOfValues, {empty, {empty}}), Outputs1 = output_utils:resize_attribute_array_value(Outputs, outputs, NumOfValues, {null, []}), Value = null, Status = initialed; {error, Reason} -> Inputs1 = Inputs, Outputs1 = Outputs, {Value, Status} = config_utils:log_error(Config, num_of_values, Reason) end, Outputs2 = output_utils:set_value_status(Outputs1, Value, Status), % This is the block state {Config, Inputs1, Outputs2, Private}. %% %% Execute the block specific functionality %% -spec execute(BlockState :: block_state(), ExecMethod :: exec_method()) -> block_state(). execute({Config, Inputs, Outputs, Private}, disable) -> Outputs1 = output_utils:update_all_outputs(Outputs, null, disabled), {Config, Inputs, Outputs1, Private}; execute({Config, Inputs, Outputs, Private}, _ExecMethod) -> case input_utils:get_boolean(Inputs, hold) of {ok, true} -> % Outputs are held at last value, don't update Value = true, Status = normal, Outputs1 = Outputs; {ok, Value} -> % hold input value is false or null, Status = normal, % Pass input values through to outputs. % Quantity of input and output values are the same {ok, {inputs, InputVals}} = attrib_utils:get_attribute(Inputs, inputs), OutputVals = lists:map(fun({InputVal, {_DefVal}}) -> InputVal end, InputVals), Outputs1 = output_utils:set_array_values(Outputs, outputs, OutputVals); {error, Reason} -> {Value, Status} = input_utils:log_error(Config, hold, Reason), {ok, NumOfValues} = config_utils:get_integer(Config, num_of_values), % Set array of output values to null NullVals = lists:duplicate(NumOfValues, null), Outputs1 = output_utils:set_array_values(Outputs, outputs, NullVals) end, Outputs2 = output_utils:set_value_status(Outputs1, Value, Status), % Return updated block state {Config, Inputs, Outputs2, Private}. %% %% Delete the block %% -spec delete(BlockState :: block_state()) -> block_defn(). delete({Config, Inputs, Outputs, _Private}) -> {Config, Inputs, Outputs}. %% ==================================================================== Internal functions %% ==================================================================== %% ==================================================================== %% Tests %% ==================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -include("block_io_test_gen.hrl"). test_sets() -> [ % Test bad config values {[{num_of_values, -1}],[{hold, "Bad Value"}], [{status, config_err}, {value, null}, {{outputs, 1}, null}]}, {[{num_of_values, 100}],[], [{status, config_err}, {value, null}, {{outputs, 1}, null}]}, % Test bad input values {[{num_of_values, 1}], [], [{status, input_err}, {value, null}, {{outputs, 1}, null}]}, {[{hold, true}, {{inputs, 1}, "something"}], [{status, normal}, {value, true}, {{outputs, 1}, null}]}, {[{hold, false}], [{status, normal}, {value, false}, {{outputs, 1}, "something"}]}, {[{hold, false}, {{inputs, 1}, "something else"}], [{status, normal}, {value, false}, {{outputs, 1}, "something else"}]}, {[{num_of_values, 10}], [{hold, true}, {{inputs, 1}, 1},{{inputs, 5}, 5}, {{inputs, 10}, 10}], [{status, normal}, {value, true}, {{outputs, 1}, "something else"}, {{outputs, 5}, null}, {{outputs, 10}, null}]}, {[{hold, false}], [{status, normal}, {value, false}, {{outputs, 1}, 1}, {{outputs, 5}, 5}, {{outputs, 10}, 10}]} ]. -endif.
null
https://raw.githubusercontent.com/mdsebald/link_blox_app/64034fa5854759ad16625b93e3dde65a9c65f615/src/block_types/lblx_sample_hold.erl
erlang
@doc Sample and Hold input values DESCRIPTION Output values will equal corresponding input values as long as hold input is false When hold input value is true, outputs will be held at the last value regardless of the input values. LINKS @end ==================================================================== API functions ==================================================================== Merge the block type specific, Config, Input, and Output attributes with the common Config, Input, and Output attributes, that all block types have | int | 1 | 1..99 | | bool | false | true, false | | array of any | empty | N/A | | array of any | null | N/A | Create a set of block attributes for this block type. and to add attributes to the lists of default attributes Update Default Config, Input, Output, and Private attribute values with the initial values passed into this function. If any of the intial attributes do not already exist in the default attribute lists, merge_attribute_lists() will create them. This is the block definition, Upgrade block attribute values, when block code and block data versions are different Perform any setup here as needed before starting execution This is the block state Execute the block specific functionality Outputs are held at last value, don't update hold input value is false or null, Pass input values through to outputs. Quantity of input and output values are the same Set array of output values to null Return updated block state Delete the block ==================================================================== ==================================================================== ==================================================================== Tests ==================================================================== Test bad config values Test bad input values
BLOCKTYPE -module(lblx_sample_hold). -author("Mark Sebald"). -include("../block_state.hrl"). -export([groups/0, version/0]). -export([create/2, create/4, create/5, upgrade/1, initialize/1, execute/2, delete/1]). groups() -> [control]. version() -> "0.1.0". -spec default_configs(BlockName :: block_name(), Description :: string()) -> config_attribs(). default_configs(BlockName, Description) -> attrib_utils:merge_attribute_lists( block_common:configs(BlockName, ?MODULE, version(), Description), [ ]). -spec default_inputs() -> input_attribs(). default_inputs() -> attrib_utils:merge_attribute_lists( block_common:inputs(), [ ]). -spec default_outputs() -> output_attribs(). default_outputs() -> attrib_utils:merge_attribute_lists( block_common:outputs(), [ ]). Init attributes are used to override the default attribute values -spec create(BlockName :: block_name(), Description :: string()) -> block_defn(). create(BlockName, Description) -> create(BlockName, Description, [], [], []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs) -> create(BlockName, Description, InitConfig, InitInputs, []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs(), InitOutputs :: output_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs, InitOutputs) -> Config = attrib_utils:merge_attribute_lists(default_configs(BlockName, Description), InitConfig), Inputs = attrib_utils:merge_attribute_lists(default_inputs(), InitInputs), Outputs = attrib_utils:merge_attribute_lists(default_outputs(), InitOutputs), {Config, Inputs, Outputs}. -spec upgrade(BlockDefn :: block_defn()) -> {ok, block_defn()} | {error, atom()}. upgrade({Config, Inputs, Outputs}) -> ModuleVer = version(), {BlockName, BlockModule, ConfigVer} = config_utils:name_module_version(Config), BlockType = type_utils:type_name(BlockModule), case attrib_utils:set_value(Config, version, version()) of {ok, UpdConfig} -> m_logger:info(block_type_upgraded_from_ver_to, [BlockName, BlockType, ConfigVer, ModuleVer]), {ok, {UpdConfig, Inputs, Outputs}}; {error, Reason} -> m_logger:error(err_upgrading_block_type_from_ver_to, [Reason, BlockName, BlockType, ConfigVer, ModuleVer]), {error, Reason} end. Initialize block values -spec initialize(BlockState :: block_state()) -> block_state(). initialize({Config, Inputs, Outputs, Private}) -> case config_utils:get_integer_range(Config, num_of_values, 1, 99) of {ok, NumOfValues} -> Create N inputs and outputs BlockName = config_utils:name(Config), Inputs1 = input_utils:resize_attribute_array_value(BlockName, Inputs, inputs, NumOfValues, {empty, {empty}}), Outputs1 = output_utils:resize_attribute_array_value(Outputs, outputs, NumOfValues, {null, []}), Value = null, Status = initialed; {error, Reason} -> Inputs1 = Inputs, Outputs1 = Outputs, {Value, Status} = config_utils:log_error(Config, num_of_values, Reason) end, Outputs2 = output_utils:set_value_status(Outputs1, Value, Status), {Config, Inputs1, Outputs2, Private}. -spec execute(BlockState :: block_state(), ExecMethod :: exec_method()) -> block_state(). execute({Config, Inputs, Outputs, Private}, disable) -> Outputs1 = output_utils:update_all_outputs(Outputs, null, disabled), {Config, Inputs, Outputs1, Private}; execute({Config, Inputs, Outputs, Private}, _ExecMethod) -> case input_utils:get_boolean(Inputs, hold) of {ok, true} -> Value = true, Status = normal, Outputs1 = Outputs; Status = normal, {ok, {inputs, InputVals}} = attrib_utils:get_attribute(Inputs, inputs), OutputVals = lists:map(fun({InputVal, {_DefVal}}) -> InputVal end, InputVals), Outputs1 = output_utils:set_array_values(Outputs, outputs, OutputVals); {error, Reason} -> {Value, Status} = input_utils:log_error(Config, hold, Reason), {ok, NumOfValues} = config_utils:get_integer(Config, num_of_values), NullVals = lists:duplicate(NumOfValues, null), Outputs1 = output_utils:set_array_values(Outputs, outputs, NullVals) end, Outputs2 = output_utils:set_value_status(Outputs1, Value, Status), {Config, Inputs, Outputs2, Private}. -spec delete(BlockState :: block_state()) -> block_defn(). delete({Config, Inputs, Outputs, _Private}) -> {Config, Inputs, Outputs}. Internal functions -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -include("block_io_test_gen.hrl"). test_sets() -> [ {[{num_of_values, -1}],[{hold, "Bad Value"}], [{status, config_err}, {value, null}, {{outputs, 1}, null}]}, {[{num_of_values, 100}],[], [{status, config_err}, {value, null}, {{outputs, 1}, null}]}, {[{num_of_values, 1}], [], [{status, input_err}, {value, null}, {{outputs, 1}, null}]}, {[{hold, true}, {{inputs, 1}, "something"}], [{status, normal}, {value, true}, {{outputs, 1}, null}]}, {[{hold, false}], [{status, normal}, {value, false}, {{outputs, 1}, "something"}]}, {[{hold, false}, {{inputs, 1}, "something else"}], [{status, normal}, {value, false}, {{outputs, 1}, "something else"}]}, {[{num_of_values, 10}], [{hold, true}, {{inputs, 1}, 1},{{inputs, 5}, 5}, {{inputs, 10}, 10}], [{status, normal}, {value, true}, {{outputs, 1}, "something else"}, {{outputs, 5}, null}, {{outputs, 10}, null}]}, {[{hold, false}], [{status, normal}, {value, false}, {{outputs, 1}, 1}, {{outputs, 5}, 5}, {{outputs, 10}, 10}]} ]. -endif.
a28eb8dedd600167acdcb323f6f2cc533092fe8c7c4ac59e48beae61e7f5eb01
well-typed/large-records
R030.hs
{-# LANGUAGE RankNTypes #-} #if PROFILE_CORESIZE {-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-} #endif #if PROFILE_TIMING {-# OPTIONS_GHC -ddump-to-file -ddump-timings #-} #endif module Experiment.Applicative.Sized.R030 where import Bench.Types import Experiment.SimpleRecord.Sized.R030 zipRecordWith :: Applicative f => (forall n. T n -> T n -> f (T n)) -> R -> R -> f R zipRecordWith f r r' = pure MkR 1 .. 10 <*> f (field1 r) (field1 r') <*> f (field2 r) (field2 r') <*> f (field3 r) (field3 r') <*> f (field4 r) (field4 r') <*> f (field5 r) (field5 r') <*> f (field6 r) (field6 r') <*> f (field7 r) (field7 r') <*> f (field8 r) (field8 r') <*> f (field9 r) (field9 r') <*> f (field10 r) (field10 r') 11 .. 20 <*> f (field11 r) (field11 r') <*> f (field12 r) (field12 r') <*> f (field13 r) (field13 r') <*> f (field14 r) (field14 r') <*> f (field15 r) (field15 r') <*> f (field16 r) (field16 r') <*> f (field17 r) (field17 r') <*> f (field18 r) (field18 r') <*> f (field19 r) (field19 r') <*> f (field20 r) (field20 r') 21 .. 30 <*> f (field21 r) (field21 r') <*> f (field22 r) (field22 r') <*> f (field23 r) (field23 r') <*> f (field24 r) (field24 r') <*> f (field25 r) (field25 r') <*> f (field26 r) (field26 r') <*> f (field27 r) (field27 r') <*> f (field28 r) (field28 r') <*> f (field29 r) (field29 r') <*> f (field30 r) (field30 r')
null
https://raw.githubusercontent.com/well-typed/large-records/c6c2b51af11e90f30822543d7ce4d1cb28cee294/large-records-benchmarks/bench/experiments/Experiment/Applicative/Sized/R030.hs
haskell
# LANGUAGE RankNTypes # # OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl # # OPTIONS_GHC -ddump-to-file -ddump-timings #
#if PROFILE_CORESIZE #endif #if PROFILE_TIMING #endif module Experiment.Applicative.Sized.R030 where import Bench.Types import Experiment.SimpleRecord.Sized.R030 zipRecordWith :: Applicative f => (forall n. T n -> T n -> f (T n)) -> R -> R -> f R zipRecordWith f r r' = pure MkR 1 .. 10 <*> f (field1 r) (field1 r') <*> f (field2 r) (field2 r') <*> f (field3 r) (field3 r') <*> f (field4 r) (field4 r') <*> f (field5 r) (field5 r') <*> f (field6 r) (field6 r') <*> f (field7 r) (field7 r') <*> f (field8 r) (field8 r') <*> f (field9 r) (field9 r') <*> f (field10 r) (field10 r') 11 .. 20 <*> f (field11 r) (field11 r') <*> f (field12 r) (field12 r') <*> f (field13 r) (field13 r') <*> f (field14 r) (field14 r') <*> f (field15 r) (field15 r') <*> f (field16 r) (field16 r') <*> f (field17 r) (field17 r') <*> f (field18 r) (field18 r') <*> f (field19 r) (field19 r') <*> f (field20 r) (field20 r') 21 .. 30 <*> f (field21 r) (field21 r') <*> f (field22 r) (field22 r') <*> f (field23 r) (field23 r') <*> f (field24 r) (field24 r') <*> f (field25 r) (field25 r') <*> f (field26 r) (field26 r') <*> f (field27 r) (field27 r') <*> f (field28 r) (field28 r') <*> f (field29 r) (field29 r') <*> f (field30 r) (field30 r')
d4878527f655d0c5a5e46992bee879085c91f5f5057c6fe04723a65530cdd1a1
cffi/cffi
bindings.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; libtest.lisp --- Setup CFFI bindings for libtest. ;;; Copyright ( C ) 2005 - 2007 , loliveira(@)common - lisp.net > ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. ;;; (in-package #:cffi-tests) (define-foreign-library (libtest :type :test) (:darwin (:or "libtest.dylib" "libtest32.dylib")) (:unix (:or "libtest.so" "libtest32.so")) (:windows "libtest.dll") (t (:default "libtest"))) (define-foreign-library (libtest2 :type :test) (:darwin (:or "libtest2.dylib" "libtest2_32.dylib")) (:unix (:or "libtest2.so" "libtest2_32.so")) (t (:default "libtest2"))) (define-foreign-library (libfsbv :type :test) (:darwin (:or "libfsbv.dylib" "libfsbv32.dylib")) (:unix (:or "libfsbv.so" "libfsbv_32.so")) (:windows "libfsbv.dll") (t (:default "libfsbv"))) (define-foreign-library libc (:windows "msvcrt.dll")) (define-foreign-library libm #+(and lispworks darwin) ; not sure why the full path is necessary (:darwin "/usr/lib/libm.dylib") (t (:default "libm"))) (defmacro deftest (name &rest body) (destructuring-bind (name &key expected-to-fail) (alexandria:ensure-list name) (let ((result `(rtest:deftest ,name ,@body))) (when expected-to-fail (setf result `(progn (when ,expected-to-fail (pushnew ',name rtest::*expected-failures*)) ,result))) result))) (defun call-within-new-thread (fn &rest args) (let (result error (cv (bordeaux-threads:make-condition-variable)) (lock (bordeaux-threads:make-lock))) (bordeaux-threads:with-lock-held (lock) (bordeaux-threads:make-thread (lambda () (multiple-value-setq (result error) (ignore-errors (apply fn args))) (bordeaux-threads:with-lock-held (lock) (bordeaux-threads:condition-notify cv)))) (bordeaux-threads:condition-wait cv lock) (values result error)))) As of OSX 10.6.6 , loading CoreFoundation on something other than ;;; the initial thread results in a crash. (deftest load-core-foundation (progn #+bordeaux-threads (call-within-new-thread 'load-foreign-library '(:framework "CoreFoundation")) t) t) ;;; Return the directory containing the source when compiling or ;;; loading this file. We don't use *LOAD-TRUENAME* because the fasl ;;; file may be in a different directory than the source with certain ;;; ASDF extensions loaded. (defun load-directory () (let ((here #.(or *compile-file-truename* *load-truename*))) (make-pathname :name nil :type nil :version nil :defaults here))) (defun load-test-libraries () (let ((*foreign-library-directories* (list (load-directory)))) (load-foreign-library 'libtest) (load-foreign-library 'libtest2) (load-foreign-library 'libfsbv) (load-foreign-library 'libc) #+(or abcl lispworks) (load-foreign-library 'libm))) #-(:and :ecl (:not :dffi)) (load-test-libraries) #+(:and :ecl (:not :dffi)) (ffi:load-foreign-library #.(make-pathname :name "libtest" :type "so" :defaults (or *compile-file-truename* *load-truename*))) ;;; check libtest version (defparameter *required-dll-version* "20120107") (defcvar "dll_version" :string) (unless (string= *dll-version* *required-dll-version*) (error "version check failed: expected ~s but libtest reports ~s" *required-dll-version* *dll-version*)) ;;; The maximum and minimum values for single and double precision C ;;; floating point values, which may be quite different from the ;;; corresponding Lisp versions. (defcvar "float_max" :float) (defcvar "float_min" :float) (defcvar "double_max" :double) (defcvar "double_min" :double) (defun run-cffi-tests (&key (compiled nil)) (let ((regression-test::*compile-tests* compiled) (*package* (find-package '#:cffi-tests))) (format t "~&;;; running tests (~Acompiled)" (if compiled "" "un")) (do-tests) (set-difference (regression-test:pending-tests) regression-test::*expected-failures*))) (defun run-all-cffi-tests () (let ((unexpected-failures (append (run-cffi-tests :compiled nil) (run-cffi-tests :compiled t)))) (format t "~%~%Overall unexpected failures: ~{~% ~A~}~%" unexpected-failures) unexpected-failures)) (defmacro expecting-error (&body body) `(handler-case (progn ,@body :no-error) (error () :error)))
null
https://raw.githubusercontent.com/cffi/cffi/384d96bdf83959adf62249e0690acda4b7011ea6/tests/bindings.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- libtest.lisp --- Setup CFFI bindings for libtest. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. not sure why the full path is necessary the initial thread results in a crash. Return the directory containing the source when compiling or loading this file. We don't use *LOAD-TRUENAME* because the fasl file may be in a different directory than the source with certain ASDF extensions loaded. check libtest version The maximum and minimum values for single and double precision C floating point values, which may be quite different from the corresponding Lisp versions.
Copyright ( C ) 2005 - 2007 , loliveira(@)common - lisp.net > files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package #:cffi-tests) (define-foreign-library (libtest :type :test) (:darwin (:or "libtest.dylib" "libtest32.dylib")) (:unix (:or "libtest.so" "libtest32.so")) (:windows "libtest.dll") (t (:default "libtest"))) (define-foreign-library (libtest2 :type :test) (:darwin (:or "libtest2.dylib" "libtest2_32.dylib")) (:unix (:or "libtest2.so" "libtest2_32.so")) (t (:default "libtest2"))) (define-foreign-library (libfsbv :type :test) (:darwin (:or "libfsbv.dylib" "libfsbv32.dylib")) (:unix (:or "libfsbv.so" "libfsbv_32.so")) (:windows "libfsbv.dll") (t (:default "libfsbv"))) (define-foreign-library libc (:windows "msvcrt.dll")) (define-foreign-library libm (:darwin "/usr/lib/libm.dylib") (t (:default "libm"))) (defmacro deftest (name &rest body) (destructuring-bind (name &key expected-to-fail) (alexandria:ensure-list name) (let ((result `(rtest:deftest ,name ,@body))) (when expected-to-fail (setf result `(progn (when ,expected-to-fail (pushnew ',name rtest::*expected-failures*)) ,result))) result))) (defun call-within-new-thread (fn &rest args) (let (result error (cv (bordeaux-threads:make-condition-variable)) (lock (bordeaux-threads:make-lock))) (bordeaux-threads:with-lock-held (lock) (bordeaux-threads:make-thread (lambda () (multiple-value-setq (result error) (ignore-errors (apply fn args))) (bordeaux-threads:with-lock-held (lock) (bordeaux-threads:condition-notify cv)))) (bordeaux-threads:condition-wait cv lock) (values result error)))) As of OSX 10.6.6 , loading CoreFoundation on something other than (deftest load-core-foundation (progn #+bordeaux-threads (call-within-new-thread 'load-foreign-library '(:framework "CoreFoundation")) t) t) (defun load-directory () (let ((here #.(or *compile-file-truename* *load-truename*))) (make-pathname :name nil :type nil :version nil :defaults here))) (defun load-test-libraries () (let ((*foreign-library-directories* (list (load-directory)))) (load-foreign-library 'libtest) (load-foreign-library 'libtest2) (load-foreign-library 'libfsbv) (load-foreign-library 'libc) #+(or abcl lispworks) (load-foreign-library 'libm))) #-(:and :ecl (:not :dffi)) (load-test-libraries) #+(:and :ecl (:not :dffi)) (ffi:load-foreign-library #.(make-pathname :name "libtest" :type "so" :defaults (or *compile-file-truename* *load-truename*))) (defparameter *required-dll-version* "20120107") (defcvar "dll_version" :string) (unless (string= *dll-version* *required-dll-version*) (error "version check failed: expected ~s but libtest reports ~s" *required-dll-version* *dll-version*)) (defcvar "float_max" :float) (defcvar "float_min" :float) (defcvar "double_max" :double) (defcvar "double_min" :double) (defun run-cffi-tests (&key (compiled nil)) (let ((regression-test::*compile-tests* compiled) (*package* (find-package '#:cffi-tests))) (format t "~&;;; running tests (~Acompiled)" (if compiled "" "un")) (do-tests) (set-difference (regression-test:pending-tests) regression-test::*expected-failures*))) (defun run-all-cffi-tests () (let ((unexpected-failures (append (run-cffi-tests :compiled nil) (run-cffi-tests :compiled t)))) (format t "~%~%Overall unexpected failures: ~{~% ~A~}~%" unexpected-failures) unexpected-failures)) (defmacro expecting-error (&body body) `(handler-case (progn ,@body :no-error) (error () :error)))
838029224f14fd13a07735807e4da68b743d22df4414168653b14d3f5f609ef7
jrm-code-project/LISP-Machine
storage.lisp
-*- Mode : LISP ; Package : SYSTEM - INTERNALS ; Cold - Load : T ; : CL ; Base:8 -*- ( c ) Copyright 1985 , Lisp Machine Incorporated ( LMI ) . ;;; This is a cold-load file. See also STORAGE-DEFS. ; forwarded to a-mem (defvar-resettable %inhibit-read-only nil nil "Bind this to T to do nasty horrible things behind the virtual memory system's back.") (defvar *area-list* :unbound "Call (CURRENT-AREA-LIST) for list of active areas.") (defun %region-free-pointer (region) (without-interrupts (compiler::invalidate-cons-caches) ;(%p-contents-offset (%region-origin region-free-pointer) region) (aref #'region-free-pointer region) )) (defun set-%region-free-pointer (region value) (without-interrupts (compiler::invalidate-cons-caches) ;(%p-store-contents-offset value (%region-origin region-free-pointer) region) (setf (aref #'region-free-pointer region) value) )) ( defsetf % region - free - pointer set-%region - free - pointer ) -- in storage - defs ;(defun %reset-temporary-area (area &optional inhibit-error) ; "Reclaim all storage associated with AREA. There must not be any references to storage ;in the area. References from unused storage are not permitted. References from active ;stack frames are not permitted. References from internal processor registers are not ;permitted. References from other stack groups, including inactive ones, are not permitted. ;In short, you shouldn't be using this. Use the garbage collector." ; (unless (or inhibit-error (area-temporary? area)) ; (multiple-cerror () () ( " The area ~S ( ~S ) was not created as temporary . " ( area - name area ) area ) ; ("Don't reset this area" (return-from %reset-temporary-area nil)) ; ("Make area temporary, and the reset it" (make-area-temporary area)))) ; (without-interrupts ; ;; We can't just iterate over the region tables here (because %free-region modifies ; ;; them), so we build a list of the regions we want to free, then %free-region them. ; (mapc #'%free-region ; (loop for region = (%area-region-list area) then (%region-list-thread region) ; until (minusp region) ; collect region)))) (defun reset-temporary-area (area &optional inhibit) area inhibit ;; Let's put the fear of God into casual users of this thing. ; (multiple-cerror () () ; ("RESET-TEMPORARY-AREA is obsolete and dangerous.") ; ("Don't reset this area." ()) ( " Reset this area using SI::%RESET - TEMPORARY - AREA . " ( % reset - temporary - area area inhibit ) ) ) (ferror nil "RESET-TEMPORARY-AREA is no longer supported.") ) (make-obsolete reset-temporary-area "is no longer supported.") ;(defun %reset-region-free-pointer (region new-fp) ; (unless inhibit-scheduling-flag ; (ferror "This function must be called with scheduling inhibited.")) ; (let ((old-fp (%region-free-pointer region))) ; (when (< new-fp old-fp) ( setf ( % region - free - pointer region ) new - fp ) ; ; Reset the structure - handles in the affected area . On the first page ; ; ( page - number new - fp ) , reset the first - header iff it needs to be lower . ; ;; For the following pages, just indicate no header and no initial qs. ; ;; Careful about the very last page -- if it's in the next region don't ; ;; touch it. ; (when (= old-fp (%region-length region)) (decf old-fp)) ; (setq old-fp (%pointer-plus old-fp (%region-origin region))) ; (setq new-fp (%pointer-plus new-fp (%region-origin region))) ; ;; If this function ever needs to be fast, use %BLT here. ; (loop initially ; (when (> (page-first-header (page-number new-fp)) (page-index new-fp)) ( setf ( page - first - header ( page - number new - fp ) ) ( page - index new - fp ) ) ) ; for page from (1+ (page-number new-fp)) to (page-number old-fp) do ( setf ( page - first - header page ) # o400 ) do ( setf ( page - initial - qs page ) 0 ) ) ; (%gc-scav-reset region)))) ;(make-obsolete %reset-region-free-pointer "use garbage collector") ;(defun %free-region (region) " Removes all trace of REGION from the area , virtual memory , and GC tables . " ; (unless inhibit-scheduling-flag ; (ferror "This function must be called with scheduling inhibited.")) ; (let ((area (%region-area region)) ( area - region - list - base ( % region - origin sys : area - region - list ) ) ( region - list - thread - base ( % region - origin sys : region - list - thread ) ) ) ; ; This function needs to be pretty fast , to keep GC : RECLAIM - OLDSPACE from ; ;; consuming too much time without interrupts. Define some magic accessors ; ;; for the relevant region tables. (Note the local variables above.) ( macrolet ( ( % area - region - list ( area ) ; `(%p-pointer (+ area-region-list-base ,area))) ; (%region-list-thread (region) ; `(%p-pointer (+ region-list-thread-base ,region)))) ; ; If it 's the first region in the area , delete from the start of the thread . ; (if (eq region (%area-region-list area)) ( setf ( % area - region - list area ) ( % region - list - thread region ) ) ; ;; Otherwise search for the region and snap it out of the thread. ; (loop with this = (%area-region-list area) ; for next = (%region-list-thread this) ; until (eq next region) ; do (setq this next) finally ( setf ( % region - list - thread this ) ( % region - list - thread next ) ) ) ) ) ; (%gc-free-region region))) (defun %deallocate-end-of-region (region) "Return unused quantums in region to free pool." (unless inhibit-scheduling-flag (ferror "This function must be called with scheduling disabled.")) (let ((quantum-size %address-space-quantum-size) (origin (%region-origin region)) (length (%region-length region)) (free-pointer (%region-free-pointer region))) If less than one quantum long , or if there is less than one quantum of free space , ;; don't do anything. It is illegal to have regions with no quantums. (unless (or (<= length quantum-size) (<= (- length free-pointer) quantum-size)) (loop with first-free-quantum = (ceiling free-pointer quantum-size) with new-length = (* first-free-quantum quantum-size) with origin-quantum = (truncate (si::%pointer-unsigned origin) quantum-size) with array = #'address-space-map initially (setf (%region-length region) new-length) for quantum from first-free-quantum below (truncate length quantum-size) do (setf (aref array (+ origin-quantum quantum)) 0) finally (%deallocate-pages (%pointer-plus origin new-length) (%pointer-plus origin length)))))) (defun %deallocate-pages (vma-start vma-bound) "Remove the pages between START and BOUND from the maps and the page-hash-table." (unless inhibit-scheduling-flag (ferror "This function must be called with scheduling disabled.")) special variable . ;; Map gets Map Status: read/write unmodified, Map Access: no access. with bits = #o300 Bit 30 in swap - status argument means disconnect virtual page from page frame . ;; It also makes the page unmodified in the other way, the details of which I almost understood at one point , but no longer . - oh . with swap-status = (%logdpb 1 (byte 1 #o30) %pht-swap-status-flushable) for address = vma-start then (%pointer-plus address page) until (= address vma-bound) do (%change-page-status address swap-status bits))) (defun %invalidate-region-mapping (region) "Decache all information about REGION from the virtual memory maps." (loop with page = page-size with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for address = origin then (%pointer-plus address page) until (eq address bound) do (%change-page-status address nil nil))) (defun %invalidate-area-mapping (area) "Decache all information about AREA from the virtual memory maps." (for-every-region-in-area (region area) (%invalidate-region-mapping region))) ;;; The following functions don't work at all. (defun %make-region-not-read-only (region) (let* ((old-region-bits (%region-bits region)) (old-access-status-meta (ldb %%region-map-bits old-region-bits)) (new-access-status-meta (%logdpb %pht-map-status-read-write-first %%region-map-status-code (%logdpb 3 %%region-map-access-code old-region-bits))) (new-region-bits (%logdpb new-access-status-meta %%region-map-bits old-region-bits))) (declare (ignore old-access-status-meta)) (setf (%region-bits region) new-region-bits) (loop with page = page-size with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for address = origin then (%pointer-plus address page) until (eq address bound) do (%change-page-status address nil new-region-bits)))) (defun %make-region-read-only (region) (let* ((old-region-bits (%region-bits region)) (old-access-status-meta (ldb %%region-map-bits old-region-bits)) (new-access-status-meta (%logdpb %pht-map-status-read-only %%region-map-status-code (%logdpb 2 %%region-map-access-code old-region-bits))) (new-region-bits (%logdpb new-access-status-meta %%region-map-bits old-region-bits))) (declare (ignore old-access-status-meta)) (setf (%region-bits region) new-region-bits) (loop with page = page-size with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for address = origin then (%pointer-plus address page) until (eq address bound) do (%change-page-status address nil new-region-bits)))) ;;; (defun current-area-list () "Use this instead of the variable AREA-LIST. That can get clobbered if someone reads in QCOM or something." (if (not (boundp '*area-list*)) (setq *area-list* (g-l-p (symbol-function 'area-name)))) *area-list* ;(g-l-p (symbol-function 'area-name)) was the old thing. As areas get deallocated, ; can be completely wrong now. ) (defun allocated-regions () (loop for region from 0 below sys:number-of-regions counting ( (%region-type region) %region-space-free))) (defun allocated-areas () (length (current-area-list)) ;(fill-pointer (symbol-function 'area-name)) ) ( defvar area - temporary - flag - array : unbound " Array index by area number containing 1 if area is temporary , else 0 . " ) (defun area-temporary-p (area) area "Return T if the specified area is a temporary area." ( not ( zerop ( aref area - temporary - flag - array area ) ) ) nil ) (defun area-temporary? (area) area "Return T if the specified area is a temporary area." ( not ( zerop ( aref area - temporary - flag - array area ) ) ) nil ) ;(defun make-area-temporary (area) ; "Mark an area (specified by number) as temporary." ( setf ( aref area - temporary - flag - array area ) 1 ) ) (defvar *room* :unbound "Areas to mention when ROOM is called with no arguments.") (forward-value-cell '*room* 'room) (defun make-area (&key name (region-size #o40000) (gc :dynamic) (read-only ()) (volatility 3 volatilityp) (room ()) (swap-recommendations 0) &allow-other-keys) "Create a new area, or modify an existing one. Returns the area number. Takes keyword argument pairs as follows: :NAME - Symbol which provides name of area. This symbol, which must be supplied, is SET to the area number. :REGION-SIZE - size for regions, between #o40000 and #o4000000 words. :GC - :DYNAMIC - garbage-collector treats this area normally (the default); :STATIC - garbage-collector ignores this area; :FIXED - garbage-collector ignores this area, which may not be consed in. :MOBY-CONSABLE - can be consed in. Moby regions are effectively STATIC for gc purposes. :MOBY-FIXED - already allocated or consable on another machine. Not consable here. :VOLATILITY - The volatility (number between 0 and 3) of newspace regions in this area. :READ-ONLY - If T, the area may not be written or consed in. :ROOM - if specified, push this area onto ROOM, so that (ROOM) will list it. :SWAP-RECOMMENDATIONS - pages prefetched upon a page fault." (declare (unspecial room)) ; (unless (variable-boundp area-temporary-flag-array) ( setq area - temporary - flag - array ( make - array # o400 : element - type ' bit ) ) ) (check-type name (and symbol (not null))) (check-type region-size (integer #o40000 #o4000000)) (check-type gc (member :static :dynamic :fixed :moby-consable :moby-fixed)) (check-type volatility (integer 0 3)) (check-type read-only (member t nil)) (check-type swap-recommendations (integer 0 31.)) (and volatilityp (neq gc ':dynamic) (ferror "~S specified, but ~S is not ~S" :volatility :gc :dynamic)) (let ((bits (%logdpb (case gc (:static %region-space-static) ;(:temporary %region-space-static) (:dynamic %region-space-new) (:fixed %region-space-fixed) (:moby-consable %region-space-moby-new) (:moby-fixed %region-space-moby-fixed)) %%region-space-type ;; I think you have to say "no scavenge" for the area so ;; new space regions don't get scavenged. when the microcode ;; allocates a copy region, it automatically turns this on. ;; This is the same behavior as the cold load builder. - Pace 17-Feb-86 (%logdpb (ecase gc (:static 1) (: temporary 1 ) (:dynamic 0) (:fixed 1) (:moby-consable 1) (:moby-fixed 1)) %%region-scavenge-enable (%logdpb swap-recommendations %%region-swapin-quantum (%logdpb volatility %%region-volatility (%logdpb 1 %%region-oldspace-meta-bit (%logdpb 1 %%region-extra-pdl-meta-bit (%logdpb 2 %%region-representation-type (%logdpb (if read-only %pht-map-status-read-only %pht-map-status-read-write-first) %%region-map-status-code (%logdpb (if read-only 2 3) %%region-map-access-code 0)))))))))) (number)) (without-interrupts (gc:without-scavenging (gc:without-flipping (cond ((memq name (current-area-list)) (setq number (symbol-value name))) (t (setq number (aref #'system-communication-area %sys-com-free-area#-list)) (when (= number 0) (ferror "Out of area numbers, cannot create ~S" name)) (setf (aref #'system-communication-area %sys-com-free-area#-list) (%area-region-list number)) (setf (%area-region-list number) (%logdpb 1 %%q-boxed-sign-bit number)) ( setf ( array - leader # ' area - name 0 ) number ) ;(vector-push name #'area-name) (setf (aref #'area-name number) name) (setf (symbol-value name) number) (do ((p (current-area-list) (cdr p)) (last-p (value-cell-location '*area-list*) p)) ((null p) (rplacd last-p (list name))) (cond ((not (< (symeval (car p)) number)) (return (rplacd last-p (cons name (cdr last-p))))))))) (setf (%area-region-size number) region-size) (setf (%area-region-bits number) bits) (when (and room (not (memq name *room*))) (push name *room*)) ; (when (eq gc ':temporary) ; (make-area-temporary number)) number))))) (defun rename-area (old-area-name new-area-name &aux tem) "Change the name of an area. This should not be done casually." (check-type old-area-name (and symbol (not null))) (check-type new-area-name (and symbol (not null))) (let ((number (symbol-value old-area-name))) (without-interrupts (gc:without-scavenging (gc:without-flipping (cond ((null (setq tem (memq old-area-name (current-area-list)))) (ferror "~S is not an active area" old-area-name)) ((not (eq old-area-name (aref #'area-name number))) (ferror "Area structure for ~s inconsistant" old-area-name))) (setf (aref #'area-name number) new-area-name) (rplaca tem new-area-name) (makunbound old-area-name) (setf (symbol-value new-area-name) number) (cond ((setq tem (memq old-area-name *room*)) (rplaca tem new-area-name))) number))))) (defun delete-null-areas () (dolist (a-n (current-area-list)) (let ((area-number (symbol-value a-n)) (count 0)) (for-every-region-in-area (region area-number) (incf count)) (if (zerop count) (delete-area a-n))))) (defun delete-area (a-n &aux tem) "Delete an area name. Area must have 0 regions." (check-type a-n (and symbol (not null))) (let ((number (symbol-value a-n))) (cond ((not (eq (%area-region-list number) (%logdpb 1 %%q-boxed-sign-bit number))) (ferror "Area to be deleted has regions."))) (cond ((null (setq tem (memq a-n (current-area-list)))) (ferror "~S is not an active area" a-n)) ((not (eq a-n (aref #'area-name number))) (ferror "Area structure for ~s inconsistant" a-n))) (without-interrupts (gc:without-scavenging (gc:without-flipping (setq *area-list* (delq a-n *area-list*)) (setf (%area-region-list number) (aref #'system-communication-area %sys-com-free-area#-list)) (setf (aref #'system-communication-area %sys-com-free-area#-list) number) (setf (aref #'area-name number) nil) (makunbound a-n) (setq *room* (delq a-n *room*)) number))))) ;;; Structure-handles initialization. This is called right at the beginning ;;; of SI::QLD. (defun setup-structure-handles-for-region (region) (loop with origin = (%region-origin region) with object = origin with page = -1 until (= object (%pointer-plus origin (%region-free-pointer region))) for boxed = (%structure-boxed-size object) for total = (%structure-total-size object) when ( (page-number object) page) do (setf (page-first-header (page-number object)) (page-index object)) for boundary = (+ (page-index object) boxed) when (> boundary #o400) do (loop for p from (1+ (page-number object)) do (decf boundary #o400) until (< boundary #o400) do (setf (page-first-header p) #o400) do (setf (page-initial-qs p) #o400) finally (setf (page-initial-qs p) (page-index boundary))) do (setq page (page-number object)) do (setq object (%pointer-plus object total)) finally (when (= (page-first-header (page-number object)) #o400) (setf (page-first-header (page-number object)) (page-index object))))) (defun setup-structure-handles-for-area (area) (for-every-region-in-area (region area) (initialize-structure-handles-for-region region) (unless (= (%region-representation-type region) %region-representation-type-unstructured) (setup-structure-handles-for-region region)))) (defun initialize-structure-handles-for-region (region) "Define every page in the region to contain #o400 unboxed words." (loop with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for page from (page-number origin) below (page-number bound) do (setf (page-first-header page) #o400);No header on this page. do (setf (page-initial-qs page) 0))) ;No initial Qs on this page. (defvar *structure-handles-setup* nil) (defun setup-structure-handles () (loop for symbolic-area in (current-area-list) for area = (symbol-value symbolic-area) do (setup-structure-handles-for-area area) finally (setf (%region-free-pointer virtual-page-data) (%region-length virtual-page-data))) (setq *structure-handles-setup* t) (enable-structure-handles-error-checks)) (defun enable-structure-handles-error-checks () (if *structure-handles-setup* (%p-dpb 1 %%m-flags-check-structure-handles (locf si:%mode-flags)))) (add-initialization 'enable-structure-handles-error-checks '(enable-structure-handles-error-checks) :system) ;;; This is a moderately critical function for the gc process, and is currently crippled by the ( aref # ' address - space - map ... ) . This function could be made about 4 times faster by converting the address space map into a one - word - per - quantum table , which could be scanned ;;; quickly using the sort of address arithmetic used in gc::compute-storage-distribution. (defun unallocated-space () "The amount of space not allocated to any region." ;; LOOP can't (declare (unspecial base)) (let ((base (truncate (%pointer-plus (%region-origin init-list-area) (%region-length init-list-area)) %address-space-quantum-size)) (bound (truncate virtual-memory-size %address-space-quantum-size))) (declare (unspecial base)) (* (loop for i from base below bound count (zerop (aref #'address-space-map i))) %address-space-quantum-size))) (defun unused-space () "The amount of space allocated to regions but not yet used by them." (with-quick-region-area-accessors (loop with bound = sys:number-of-regions with %%type = sys:%%region-space-type for region from 0 below bound when (memq (%logldb %%type (%region-bits region)) '#.(list %region-space-new %region-space-copy %region-space-static)) sum (- (%region-length region) (%region-free-pointer region))))) To be conservative , " free space " , as far as the human or the GC are concerned , ;;; is the amount of space in unallocated quantums. Unused space in regions may or ;;; may not be usable. (deff free-space 'unallocated-space) Crufty name has proliferated .
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/sys/storage.lisp
lisp
Package : SYSTEM - INTERNALS ; Cold - Load : T ; : CL ; Base:8 -*- This is a cold-load file. See also STORAGE-DEFS. forwarded to a-mem (%p-contents-offset (%region-origin region-free-pointer) region) (%p-store-contents-offset value (%region-origin region-free-pointer) region) (defun %reset-temporary-area (area &optional inhibit-error) "Reclaim all storage associated with AREA. There must not be any references to storage in the area. References from unused storage are not permitted. References from active stack frames are not permitted. References from internal processor registers are not permitted. References from other stack groups, including inactive ones, are not permitted. In short, you shouldn't be using this. Use the garbage collector." (unless (or inhibit-error (area-temporary? area)) (multiple-cerror () () ("Don't reset this area" (return-from %reset-temporary-area nil)) ("Make area temporary, and the reset it" (make-area-temporary area)))) (without-interrupts ;; We can't just iterate over the region tables here (because %free-region modifies ;; them), so we build a list of the regions we want to free, then %free-region them. (mapc #'%free-region (loop for region = (%area-region-list area) then (%region-list-thread region) until (minusp region) collect region)))) Let's put the fear of God into casual users of this thing. (multiple-cerror () () ("RESET-TEMPORARY-AREA is obsolete and dangerous.") ("Don't reset this area." ()) (defun %reset-region-free-pointer (region new-fp) (unless inhibit-scheduling-flag (ferror "This function must be called with scheduling inhibited.")) (let ((old-fp (%region-free-pointer region))) (when (< new-fp old-fp) ; Reset the structure - handles in the affected area . On the first page ; ( page - number new - fp ) , reset the first - header iff it needs to be lower . ;; For the following pages, just indicate no header and no initial qs. ;; Careful about the very last page -- if it's in the next region don't ;; touch it. (when (= old-fp (%region-length region)) (decf old-fp)) (setq old-fp (%pointer-plus old-fp (%region-origin region))) (setq new-fp (%pointer-plus new-fp (%region-origin region))) ;; If this function ever needs to be fast, use %BLT here. (loop initially (when (> (page-first-header (page-number new-fp)) (page-index new-fp)) for page from (1+ (page-number new-fp)) to (page-number old-fp) (%gc-scav-reset region)))) (make-obsolete %reset-region-free-pointer "use garbage collector") (defun %free-region (region) (unless inhibit-scheduling-flag (ferror "This function must be called with scheduling inhibited.")) (let ((area (%region-area region)) ; This function needs to be pretty fast , to keep GC : RECLAIM - OLDSPACE from ;; consuming too much time without interrupts. Define some magic accessors ;; for the relevant region tables. (Note the local variables above.) `(%p-pointer (+ area-region-list-base ,area))) (%region-list-thread (region) `(%p-pointer (+ region-list-thread-base ,region)))) ; If it 's the first region in the area , delete from the start of the thread . (if (eq region (%area-region-list area)) ;; Otherwise search for the region and snap it out of the thread. (loop with this = (%area-region-list area) for next = (%region-list-thread this) until (eq next region) do (setq this next) (%gc-free-region region))) don't do anything. It is illegal to have regions with no quantums. Map gets Map Status: read/write unmodified, Map Access: no access. It also makes the page unmodified in the other way, the details of which The following functions don't work at all. (g-l-p (symbol-function 'area-name)) was the old thing. As areas get deallocated, can be completely wrong now. (fill-pointer (symbol-function 'area-name)) (defun make-area-temporary (area) "Mark an area (specified by number) as temporary." (unless (variable-boundp area-temporary-flag-array) (:temporary %region-space-static) I think you have to say "no scavenge" for the area so new space regions don't get scavenged. when the microcode allocates a copy region, it automatically turns this on. This is the same behavior as the cold load builder. - Pace 17-Feb-86 (vector-push name #'area-name) (when (eq gc ':temporary) (make-area-temporary number)) Structure-handles initialization. This is called right at the beginning of SI::QLD. No header on this page. No initial Qs on this page. This is a moderately critical function for the gc process, and is currently crippled by quickly using the sort of address arithmetic used in gc::compute-storage-distribution. LOOP can't (declare (unspecial base)) is the amount of space in unallocated quantums. Unused space in regions may or may not be usable.
( c ) Copyright 1985 , Lisp Machine Incorporated ( LMI ) . (defvar-resettable %inhibit-read-only nil nil "Bind this to T to do nasty horrible things behind the virtual memory system's back.") (defvar *area-list* :unbound "Call (CURRENT-AREA-LIST) for list of active areas.") (defun %region-free-pointer (region) (without-interrupts (compiler::invalidate-cons-caches) (aref #'region-free-pointer region) )) (defun set-%region-free-pointer (region value) (without-interrupts (compiler::invalidate-cons-caches) (setf (aref #'region-free-pointer region) value) )) ( defsetf % region - free - pointer set-%region - free - pointer ) -- in storage - defs ( " The area ~S ( ~S ) was not created as temporary . " ( area - name area ) area ) (defun reset-temporary-area (area &optional inhibit) area inhibit ( " Reset this area using SI::%RESET - TEMPORARY - AREA . " ( % reset - temporary - area area inhibit ) ) ) (ferror nil "RESET-TEMPORARY-AREA is no longer supported.") ) (make-obsolete reset-temporary-area "is no longer supported.") ( setf ( % region - free - pointer region ) new - fp ) ( setf ( page - first - header ( page - number new - fp ) ) ( page - index new - fp ) ) ) do ( setf ( page - first - header page ) # o400 ) do ( setf ( page - initial - qs page ) 0 ) ) " Removes all trace of REGION from the area , virtual memory , and GC tables . " ( area - region - list - base ( % region - origin sys : area - region - list ) ) ( region - list - thread - base ( % region - origin sys : region - list - thread ) ) ) ( macrolet ( ( % area - region - list ( area ) ( setf ( % area - region - list area ) ( % region - list - thread region ) ) finally ( setf ( % region - list - thread this ) ( % region - list - thread next ) ) ) ) ) (defun %deallocate-end-of-region (region) "Return unused quantums in region to free pool." (unless inhibit-scheduling-flag (ferror "This function must be called with scheduling disabled.")) (let ((quantum-size %address-space-quantum-size) (origin (%region-origin region)) (length (%region-length region)) (free-pointer (%region-free-pointer region))) If less than one quantum long , or if there is less than one quantum of free space , (unless (or (<= length quantum-size) (<= (- length free-pointer) quantum-size)) (loop with first-free-quantum = (ceiling free-pointer quantum-size) with new-length = (* first-free-quantum quantum-size) with origin-quantum = (truncate (si::%pointer-unsigned origin) quantum-size) with array = #'address-space-map initially (setf (%region-length region) new-length) for quantum from first-free-quantum below (truncate length quantum-size) do (setf (aref array (+ origin-quantum quantum)) 0) finally (%deallocate-pages (%pointer-plus origin new-length) (%pointer-plus origin length)))))) (defun %deallocate-pages (vma-start vma-bound) "Remove the pages between START and BOUND from the maps and the page-hash-table." (unless inhibit-scheduling-flag (ferror "This function must be called with scheduling disabled.")) special variable . with bits = #o300 Bit 30 in swap - status argument means disconnect virtual page from page frame . I almost understood at one point , but no longer . - oh . with swap-status = (%logdpb 1 (byte 1 #o30) %pht-swap-status-flushable) for address = vma-start then (%pointer-plus address page) until (= address vma-bound) do (%change-page-status address swap-status bits))) (defun %invalidate-region-mapping (region) "Decache all information about REGION from the virtual memory maps." (loop with page = page-size with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for address = origin then (%pointer-plus address page) until (eq address bound) do (%change-page-status address nil nil))) (defun %invalidate-area-mapping (area) "Decache all information about AREA from the virtual memory maps." (for-every-region-in-area (region area) (%invalidate-region-mapping region))) (defun %make-region-not-read-only (region) (let* ((old-region-bits (%region-bits region)) (old-access-status-meta (ldb %%region-map-bits old-region-bits)) (new-access-status-meta (%logdpb %pht-map-status-read-write-first %%region-map-status-code (%logdpb 3 %%region-map-access-code old-region-bits))) (new-region-bits (%logdpb new-access-status-meta %%region-map-bits old-region-bits))) (declare (ignore old-access-status-meta)) (setf (%region-bits region) new-region-bits) (loop with page = page-size with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for address = origin then (%pointer-plus address page) until (eq address bound) do (%change-page-status address nil new-region-bits)))) (defun %make-region-read-only (region) (let* ((old-region-bits (%region-bits region)) (old-access-status-meta (ldb %%region-map-bits old-region-bits)) (new-access-status-meta (%logdpb %pht-map-status-read-only %%region-map-status-code (%logdpb 2 %%region-map-access-code old-region-bits))) (new-region-bits (%logdpb new-access-status-meta %%region-map-bits old-region-bits))) (declare (ignore old-access-status-meta)) (setf (%region-bits region) new-region-bits) (loop with page = page-size with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for address = origin then (%pointer-plus address page) until (eq address bound) do (%change-page-status address nil new-region-bits)))) (defun current-area-list () "Use this instead of the variable AREA-LIST. That can get clobbered if someone reads in QCOM or something." (if (not (boundp '*area-list*)) (setq *area-list* (g-l-p (symbol-function 'area-name)))) *area-list* ) (defun allocated-regions () (loop for region from 0 below sys:number-of-regions counting ( (%region-type region) %region-space-free))) (defun allocated-areas () ) ( defvar area - temporary - flag - array : unbound " Array index by area number containing 1 if area is temporary , else 0 . " ) (defun area-temporary-p (area) area "Return T if the specified area is a temporary area." ( not ( zerop ( aref area - temporary - flag - array area ) ) ) nil ) (defun area-temporary? (area) area "Return T if the specified area is a temporary area." ( not ( zerop ( aref area - temporary - flag - array area ) ) ) nil ) ( setf ( aref area - temporary - flag - array area ) 1 ) ) (defvar *room* :unbound "Areas to mention when ROOM is called with no arguments.") (forward-value-cell '*room* 'room) (defun make-area (&key name (region-size #o40000) (gc :dynamic) (read-only ()) (volatility 3 volatilityp) (room ()) (swap-recommendations 0) &allow-other-keys) "Create a new area, or modify an existing one. Returns the area number. Takes keyword argument pairs as follows: :NAME - Symbol which provides name of area. This symbol, which must be supplied, is SET to the area number. :REGION-SIZE - size for regions, between #o40000 and #o4000000 words. :FIXED - garbage-collector ignores this area, which may not be consed in. :MOBY-CONSABLE - can be consed in. Moby regions are effectively STATIC for gc purposes. :MOBY-FIXED - already allocated or consable on another machine. Not consable here. :VOLATILITY - The volatility (number between 0 and 3) of newspace regions in this area. :READ-ONLY - If T, the area may not be written or consed in. :ROOM - if specified, push this area onto ROOM, so that (ROOM) will list it. :SWAP-RECOMMENDATIONS - pages prefetched upon a page fault." (declare (unspecial room)) ( setq area - temporary - flag - array ( make - array # o400 : element - type ' bit ) ) ) (check-type name (and symbol (not null))) (check-type region-size (integer #o40000 #o4000000)) (check-type gc (member :static :dynamic :fixed :moby-consable :moby-fixed)) (check-type volatility (integer 0 3)) (check-type read-only (member t nil)) (check-type swap-recommendations (integer 0 31.)) (and volatilityp (neq gc ':dynamic) (ferror "~S specified, but ~S is not ~S" :volatility :gc :dynamic)) (let ((bits (%logdpb (case gc (:static %region-space-static) (:dynamic %region-space-new) (:fixed %region-space-fixed) (:moby-consable %region-space-moby-new) (:moby-fixed %region-space-moby-fixed)) %%region-space-type (%logdpb (ecase gc (:static 1) (: temporary 1 ) (:dynamic 0) (:fixed 1) (:moby-consable 1) (:moby-fixed 1)) %%region-scavenge-enable (%logdpb swap-recommendations %%region-swapin-quantum (%logdpb volatility %%region-volatility (%logdpb 1 %%region-oldspace-meta-bit (%logdpb 1 %%region-extra-pdl-meta-bit (%logdpb 2 %%region-representation-type (%logdpb (if read-only %pht-map-status-read-only %pht-map-status-read-write-first) %%region-map-status-code (%logdpb (if read-only 2 3) %%region-map-access-code 0)))))))))) (number)) (without-interrupts (gc:without-scavenging (gc:without-flipping (cond ((memq name (current-area-list)) (setq number (symbol-value name))) (t (setq number (aref #'system-communication-area %sys-com-free-area#-list)) (when (= number 0) (ferror "Out of area numbers, cannot create ~S" name)) (setf (aref #'system-communication-area %sys-com-free-area#-list) (%area-region-list number)) (setf (%area-region-list number) (%logdpb 1 %%q-boxed-sign-bit number)) ( setf ( array - leader # ' area - name 0 ) number ) (setf (aref #'area-name number) name) (setf (symbol-value name) number) (do ((p (current-area-list) (cdr p)) (last-p (value-cell-location '*area-list*) p)) ((null p) (rplacd last-p (list name))) (cond ((not (< (symeval (car p)) number)) (return (rplacd last-p (cons name (cdr last-p))))))))) (setf (%area-region-size number) region-size) (setf (%area-region-bits number) bits) (when (and room (not (memq name *room*))) (push name *room*)) number))))) (defun rename-area (old-area-name new-area-name &aux tem) "Change the name of an area. This should not be done casually." (check-type old-area-name (and symbol (not null))) (check-type new-area-name (and symbol (not null))) (let ((number (symbol-value old-area-name))) (without-interrupts (gc:without-scavenging (gc:without-flipping (cond ((null (setq tem (memq old-area-name (current-area-list)))) (ferror "~S is not an active area" old-area-name)) ((not (eq old-area-name (aref #'area-name number))) (ferror "Area structure for ~s inconsistant" old-area-name))) (setf (aref #'area-name number) new-area-name) (rplaca tem new-area-name) (makunbound old-area-name) (setf (symbol-value new-area-name) number) (cond ((setq tem (memq old-area-name *room*)) (rplaca tem new-area-name))) number))))) (defun delete-null-areas () (dolist (a-n (current-area-list)) (let ((area-number (symbol-value a-n)) (count 0)) (for-every-region-in-area (region area-number) (incf count)) (if (zerop count) (delete-area a-n))))) (defun delete-area (a-n &aux tem) "Delete an area name. Area must have 0 regions." (check-type a-n (and symbol (not null))) (let ((number (symbol-value a-n))) (cond ((not (eq (%area-region-list number) (%logdpb 1 %%q-boxed-sign-bit number))) (ferror "Area to be deleted has regions."))) (cond ((null (setq tem (memq a-n (current-area-list)))) (ferror "~S is not an active area" a-n)) ((not (eq a-n (aref #'area-name number))) (ferror "Area structure for ~s inconsistant" a-n))) (without-interrupts (gc:without-scavenging (gc:without-flipping (setq *area-list* (delq a-n *area-list*)) (setf (%area-region-list number) (aref #'system-communication-area %sys-com-free-area#-list)) (setf (aref #'system-communication-area %sys-com-free-area#-list) number) (setf (aref #'area-name number) nil) (makunbound a-n) (setq *room* (delq a-n *room*)) number))))) (defun setup-structure-handles-for-region (region) (loop with origin = (%region-origin region) with object = origin with page = -1 until (= object (%pointer-plus origin (%region-free-pointer region))) for boxed = (%structure-boxed-size object) for total = (%structure-total-size object) when ( (page-number object) page) do (setf (page-first-header (page-number object)) (page-index object)) for boundary = (+ (page-index object) boxed) when (> boundary #o400) do (loop for p from (1+ (page-number object)) do (decf boundary #o400) until (< boundary #o400) do (setf (page-first-header p) #o400) do (setf (page-initial-qs p) #o400) finally (setf (page-initial-qs p) (page-index boundary))) do (setq page (page-number object)) do (setq object (%pointer-plus object total)) finally (when (= (page-first-header (page-number object)) #o400) (setf (page-first-header (page-number object)) (page-index object))))) (defun setup-structure-handles-for-area (area) (for-every-region-in-area (region area) (initialize-structure-handles-for-region region) (unless (= (%region-representation-type region) %region-representation-type-unstructured) (setup-structure-handles-for-region region)))) (defun initialize-structure-handles-for-region (region) "Define every page in the region to contain #o400 unboxed words." (loop with origin = (%region-origin region) with bound = (%pointer-plus origin (%region-length region)) for page from (page-number origin) below (page-number bound) (defvar *structure-handles-setup* nil) (defun setup-structure-handles () (loop for symbolic-area in (current-area-list) for area = (symbol-value symbolic-area) do (setup-structure-handles-for-area area) finally (setf (%region-free-pointer virtual-page-data) (%region-length virtual-page-data))) (setq *structure-handles-setup* t) (enable-structure-handles-error-checks)) (defun enable-structure-handles-error-checks () (if *structure-handles-setup* (%p-dpb 1 %%m-flags-check-structure-handles (locf si:%mode-flags)))) (add-initialization 'enable-structure-handles-error-checks '(enable-structure-handles-error-checks) :system) the ( aref # ' address - space - map ... ) . This function could be made about 4 times faster by converting the address space map into a one - word - per - quantum table , which could be scanned (defun unallocated-space () "The amount of space not allocated to any region." (let ((base (truncate (%pointer-plus (%region-origin init-list-area) (%region-length init-list-area)) %address-space-quantum-size)) (bound (truncate virtual-memory-size %address-space-quantum-size))) (declare (unspecial base)) (* (loop for i from base below bound count (zerop (aref #'address-space-map i))) %address-space-quantum-size))) (defun unused-space () "The amount of space allocated to regions but not yet used by them." (with-quick-region-area-accessors (loop with bound = sys:number-of-regions with %%type = sys:%%region-space-type for region from 0 below bound when (memq (%logldb %%type (%region-bits region)) '#.(list %region-space-new %region-space-copy %region-space-static)) sum (- (%region-length region) (%region-free-pointer region))))) To be conservative , " free space " , as far as the human or the GC are concerned , (deff free-space 'unallocated-space) Crufty name has proliferated .
66bb0ed077a54d6792776d7afa836b5372d4d6e5af927f97db44b9be20cca183
flipstone/orville
RowValues.hs
# LANGUAGE GeneralizedNewtypeDeriving # | Module : Orville . PostgreSQL.Internal . Expr . Insert . RowValues Copyright : Flipstone Technology Partners 2016 - 2021 License : MIT Module : Orville.PostgreSQL.Internal.Expr.Insert.RowValues Copyright : Flipstone Technology Partners 2016-2021 License : MIT -} module Orville.PostgreSQL.Internal.Expr.Insert.RowValues ( RowValues, rowValues, ) where import qualified Orville.PostgreSQL.Internal.RawSql as RawSql import Orville.PostgreSQL.Internal.SqlValue (SqlValue) newtype RowValues = RowValues RawSql.RawSql deriving (RawSql.SqlExpression) rowValues :: [SqlValue] -> RowValues rowValues values = RowValues $ mconcat [ RawSql.leftParen , RawSql.intercalate RawSql.comma (fmap RawSql.parameter values) , RawSql.rightParen ]
null
https://raw.githubusercontent.com/flipstone/orville/d68cc4a85bf84269e4883d232cf7bf91a626662b/orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/Expr/Insert/RowValues.hs
haskell
# LANGUAGE GeneralizedNewtypeDeriving # | Module : Orville . PostgreSQL.Internal . Expr . Insert . RowValues Copyright : Flipstone Technology Partners 2016 - 2021 License : MIT Module : Orville.PostgreSQL.Internal.Expr.Insert.RowValues Copyright : Flipstone Technology Partners 2016-2021 License : MIT -} module Orville.PostgreSQL.Internal.Expr.Insert.RowValues ( RowValues, rowValues, ) where import qualified Orville.PostgreSQL.Internal.RawSql as RawSql import Orville.PostgreSQL.Internal.SqlValue (SqlValue) newtype RowValues = RowValues RawSql.RawSql deriving (RawSql.SqlExpression) rowValues :: [SqlValue] -> RowValues rowValues values = RowValues $ mconcat [ RawSql.leftParen , RawSql.intercalate RawSql.comma (fmap RawSql.parameter values) , RawSql.rightParen ]
092dffca0b50acea69076c92a55c540584f975496a421c3e33e63f55d4f05bac
static-analysis-engineering/codehawk
bCHStructTables.mli
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2022 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2022 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) (* bchlib *) open BCHLibTypes val structtables: struct_tables_int
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/f3ca3a16d7f42e4e08ca3efe6dc66810548408c6/CodeHawk/CHB/bchlib/bCHStructTables.mli
ocaml
bchlib
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2022 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2022 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) open BCHLibTypes val structtables: struct_tables_int
7ce2771bfbeef4ef8994d18ce53233b345fa05e9c82036798432792138559754
rtoal/ple
another_mystery.hs
mystery (x, y) z = (y / 2.0, z, [x, x, x])
null
https://raw.githubusercontent.com/rtoal/ple/b24cab4de2beca6970833a09d05af6ef96ec3921/haskell/another_mystery.hs
haskell
mystery (x, y) z = (y / 2.0, z, [x, x, x])
4ce7da949ed1f4f7d67524c863bba37b67f247c2a3e82ef9fd5166cc17a81015
aelve/guide
Error.hs
# LANGUAGE FlexibleInstances # module Guide.Api.Error ( ErrorResponse, ) where import Imports import Data.Swagger import GHC.TypeLits import Servant import Servant.Swagger Taken from -servant/servant-swagger/issues/59 data ErrorResponse (code :: Nat) (description :: Symbol) instance ( HasSwagger api , KnownNat code , KnownSymbol desc ) => HasSwagger (ErrorResponse code desc :> api) where toSwagger _ = toSwagger (Proxy :: Proxy api) & setResponse (fromInteger code) (return responseSchema) where code = natVal (Proxy :: Proxy code) desc = symbolVal (Proxy :: Proxy desc) responseSchema = mempty & description .~ toText desc instance HasLink sub => HasLink (ErrorResponse code desc :> sub) where type MkLink (ErrorResponse code desc :> sub) a = MkLink sub a toLink f _ l = toLink f (Proxy :: Proxy sub) l instance HasServer api ctx => HasServer (ErrorResponse code desc :> api) ctx where type ServerT (ErrorResponse code desc :> api) m = ServerT api m route _ = route (Proxy :: Proxy api) hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt s
null
https://raw.githubusercontent.com/aelve/guide/96a338d61976344d2405a16b11567e5464820a9e/back/src/Guide/Api/Error.hs
haskell
# LANGUAGE FlexibleInstances # module Guide.Api.Error ( ErrorResponse, ) where import Imports import Data.Swagger import GHC.TypeLits import Servant import Servant.Swagger Taken from -servant/servant-swagger/issues/59 data ErrorResponse (code :: Nat) (description :: Symbol) instance ( HasSwagger api , KnownNat code , KnownSymbol desc ) => HasSwagger (ErrorResponse code desc :> api) where toSwagger _ = toSwagger (Proxy :: Proxy api) & setResponse (fromInteger code) (return responseSchema) where code = natVal (Proxy :: Proxy code) desc = symbolVal (Proxy :: Proxy desc) responseSchema = mempty & description .~ toText desc instance HasLink sub => HasLink (ErrorResponse code desc :> sub) where type MkLink (ErrorResponse code desc :> sub) a = MkLink sub a toLink f _ l = toLink f (Proxy :: Proxy sub) l instance HasServer api ctx => HasServer (ErrorResponse code desc :> api) ctx where type ServerT (ErrorResponse code desc :> api) m = ServerT api m route _ = route (Proxy :: Proxy api) hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt s
2863e19688c7e255ace8375247765ea0515568e1662c3bf7525a5a51b1d750d0
kowainik/membrain
Constructors.hs
| Copyright : ( c ) 2018 - 2020 Kowainik SPDX - License - Identifier : MPL-2.0 Maintainer : < > This module implements smart constructors for creating values of type ' Memory ' . Copyright: (c) 2018-2020 Kowainik SPDX-License-Identifier: MPL-2.0 Maintainer: Kowainik <> This module implements smart constructors for creating values of type 'Memory'. -} module Membrain.Constructors ( -- * Smart constructors bit , nibble , byte , kilobyte , megabyte , gigabyte , terabyte , petabyte , exabyte , zettabyte , yottabyte , kibibyte , mebibyte , gibibyte , tebibyte , pebibyte , exbibyte , zebibyte , yobibyte ) where import GHC.Natural (Natural) import Membrain.Memory (Memory (..), memory) import Membrain.Units (Bit, Byte, Exabyte, Exbibyte, Gibibyte, Gigabyte, Kibibyte, Kilobyte, Mebibyte, Megabyte, Nibble, Pebibyte, Petabyte, Tebibyte, Terabyte, Yobibyte, Yottabyte, Zebibyte, Zettabyte) $ setup > > > import >>> import Membrain -} | Creates ' Memory ' in ' Bit 's from given ' Natural ' as the number of bits . > > > showMemory $ bit 42 " 42b " >>> showMemory $ bit 42 "42b" -} bit :: Natural -> Memory Bit bit = Memory # INLINE bit # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of nibbles . > > > showMemory $ nibble 42 " 42n " >>> showMemory $ nibble 42 "42n" -} nibble :: Natural -> Memory Nibble nibble = memory # INLINE nibble # | Creates ' Memory ' in ' Byte 's from given ' Natural ' as the number of bytes . > > > showMemory $ byte 42 " 42B " >>> showMemory $ byte 42 "42B" -} byte :: Natural -> Memory Byte byte = memory # INLINE byte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of kilobytes . > > > showMemory $ kilobyte 42 " 42kB " >>> showMemory $ kilobyte 42 "42kB" -} kilobyte :: Natural -> Memory Kilobyte kilobyte = memory # INLINE kilobyte # | Creates ' Memory ' in ' Megabyte 's from given ' Natural ' as the number of megabytes . > > > showMemory $ megabyte 42 " 42 MB " >>> showMemory $ megabyte 42 "42MB" -} megabyte :: Natural -> Memory Megabyte megabyte = memory # INLINE megabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of gigabytes . > > > showMemory $ gigabyte 42 " 42 GB " >>> showMemory $ gigabyte 42 "42GB" -} gigabyte :: Natural -> Memory Gigabyte gigabyte = memory # INLINE gigabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of terabytes . > > > showMemory $ terabyte 42 " 42 TB " >>> showMemory $ terabyte 42 "42TB" -} terabyte :: Natural -> Memory Terabyte terabyte = memory # INLINE terabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of petabytes . > > > showMemory $ petabyte 42 " 42PB " >>> showMemory $ petabyte 42 "42PB" -} petabyte :: Natural -> Memory Petabyte petabyte = memory # INLINE petabyte # | Creates ' Memory ' in ' Exabyte 's from given ' Natural ' as the number of exabytes . > > > showMemory $ exabyte 42 " 42EB " >>> showMemory $ exabyte 42 "42EB" -} exabyte :: Natural -> Memory Exabyte exabyte = memory # INLINE exabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of zettabytes . > > > showMemory $ zettabyte 42 " 42ZB " >>> showMemory $ zettabyte 42 "42ZB" -} zettabyte :: Natural -> Memory Zettabyte zettabyte = memory # INLINE zettabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of yottabytes . > > > showMemory $ yottabyte 42 " 42YB " >>> showMemory $ yottabyte 42 "42YB" -} yottabyte :: Natural -> Memory Yottabyte yottabyte = memory # INLINE yottabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of kibibytes . > > > showMemory $ kibibyte 42 " 42KiB " >>> showMemory $ kibibyte 42 "42KiB" -} kibibyte :: Natural -> Memory Kibibyte kibibyte = memory # INLINE kibibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of mebibytes . > > > showMemory $ mebibyte 42 " 42MiB " >>> showMemory $ mebibyte 42 "42MiB" -} mebibyte :: Natural -> Memory Mebibyte mebibyte = memory # INLINE mebibyte # | Creates ' Memory ' in ' Gibibyte 's from given ' Natural ' as the number of gibibytes . > > > showMemory $ gibibyte 42 " 42GiB " >>> showMemory $ gibibyte 42 "42GiB" -} gibibyte :: Natural -> Memory Gibibyte gibibyte = memory # INLINE gibibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of tebibytes . > > > showMemory $ tebibyte 42 " 42TiB " >>> showMemory $ tebibyte 42 "42TiB" -} tebibyte :: Natural -> Memory Tebibyte tebibyte = memory # INLINE tebibyte # | Creates ' Memory ' in ' Pebibyte 's from given ' Natural ' as the number of pebibytes . > > > showMemory $ pebibyte 42 " 42PiB " >>> showMemory $ pebibyte 42 "42PiB" -} pebibyte :: Natural -> Memory Pebibyte pebibyte = memory # INLINE pebibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of exbibytes . > > > showMemory $ exbibyte 42 " 42EiB " >>> showMemory $ exbibyte 42 "42EiB" -} exbibyte :: Natural -> Memory Exbibyte exbibyte = memory # INLINE exbibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of zebibytes . > > > showMemory $ zebibyte 42 " 42ZiB " >>> showMemory $ zebibyte 42 "42ZiB" -} zebibyte :: Natural -> Memory Zebibyte zebibyte = memory # INLINE zebibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of yobibytes . > > > showMemory $ yobibyte 42 " 42YiB " >>> showMemory $ yobibyte 42 "42YiB" -} yobibyte :: Natural -> Memory Yobibyte yobibyte = memory # INLINE yobibyte #
null
https://raw.githubusercontent.com/kowainik/membrain/c7c3e9ad9b56fbe48677a7a7f5b2e2146cbd8bb1/src/Membrain/Constructors.hs
haskell
* Smart constructors
| Copyright : ( c ) 2018 - 2020 Kowainik SPDX - License - Identifier : MPL-2.0 Maintainer : < > This module implements smart constructors for creating values of type ' Memory ' . Copyright: (c) 2018-2020 Kowainik SPDX-License-Identifier: MPL-2.0 Maintainer: Kowainik <> This module implements smart constructors for creating values of type 'Memory'. -} module Membrain.Constructors bit , nibble , byte , kilobyte , megabyte , gigabyte , terabyte , petabyte , exabyte , zettabyte , yottabyte , kibibyte , mebibyte , gibibyte , tebibyte , pebibyte , exbibyte , zebibyte , yobibyte ) where import GHC.Natural (Natural) import Membrain.Memory (Memory (..), memory) import Membrain.Units (Bit, Byte, Exabyte, Exbibyte, Gibibyte, Gigabyte, Kibibyte, Kilobyte, Mebibyte, Megabyte, Nibble, Pebibyte, Petabyte, Tebibyte, Terabyte, Yobibyte, Yottabyte, Zebibyte, Zettabyte) $ setup > > > import >>> import Membrain -} | Creates ' Memory ' in ' Bit 's from given ' Natural ' as the number of bits . > > > showMemory $ bit 42 " 42b " >>> showMemory $ bit 42 "42b" -} bit :: Natural -> Memory Bit bit = Memory # INLINE bit # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of nibbles . > > > showMemory $ nibble 42 " 42n " >>> showMemory $ nibble 42 "42n" -} nibble :: Natural -> Memory Nibble nibble = memory # INLINE nibble # | Creates ' Memory ' in ' Byte 's from given ' Natural ' as the number of bytes . > > > showMemory $ byte 42 " 42B " >>> showMemory $ byte 42 "42B" -} byte :: Natural -> Memory Byte byte = memory # INLINE byte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of kilobytes . > > > showMemory $ kilobyte 42 " 42kB " >>> showMemory $ kilobyte 42 "42kB" -} kilobyte :: Natural -> Memory Kilobyte kilobyte = memory # INLINE kilobyte # | Creates ' Memory ' in ' Megabyte 's from given ' Natural ' as the number of megabytes . > > > showMemory $ megabyte 42 " 42 MB " >>> showMemory $ megabyte 42 "42MB" -} megabyte :: Natural -> Memory Megabyte megabyte = memory # INLINE megabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of gigabytes . > > > showMemory $ gigabyte 42 " 42 GB " >>> showMemory $ gigabyte 42 "42GB" -} gigabyte :: Natural -> Memory Gigabyte gigabyte = memory # INLINE gigabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of terabytes . > > > showMemory $ terabyte 42 " 42 TB " >>> showMemory $ terabyte 42 "42TB" -} terabyte :: Natural -> Memory Terabyte terabyte = memory # INLINE terabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of petabytes . > > > showMemory $ petabyte 42 " 42PB " >>> showMemory $ petabyte 42 "42PB" -} petabyte :: Natural -> Memory Petabyte petabyte = memory # INLINE petabyte # | Creates ' Memory ' in ' Exabyte 's from given ' Natural ' as the number of exabytes . > > > showMemory $ exabyte 42 " 42EB " >>> showMemory $ exabyte 42 "42EB" -} exabyte :: Natural -> Memory Exabyte exabyte = memory # INLINE exabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of zettabytes . > > > showMemory $ zettabyte 42 " 42ZB " >>> showMemory $ zettabyte 42 "42ZB" -} zettabyte :: Natural -> Memory Zettabyte zettabyte = memory # INLINE zettabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of yottabytes . > > > showMemory $ yottabyte 42 " 42YB " >>> showMemory $ yottabyte 42 "42YB" -} yottabyte :: Natural -> Memory Yottabyte yottabyte = memory # INLINE yottabyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of kibibytes . > > > showMemory $ kibibyte 42 " 42KiB " >>> showMemory $ kibibyte 42 "42KiB" -} kibibyte :: Natural -> Memory Kibibyte kibibyte = memory # INLINE kibibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of mebibytes . > > > showMemory $ mebibyte 42 " 42MiB " >>> showMemory $ mebibyte 42 "42MiB" -} mebibyte :: Natural -> Memory Mebibyte mebibyte = memory # INLINE mebibyte # | Creates ' Memory ' in ' Gibibyte 's from given ' Natural ' as the number of gibibytes . > > > showMemory $ gibibyte 42 " 42GiB " >>> showMemory $ gibibyte 42 "42GiB" -} gibibyte :: Natural -> Memory Gibibyte gibibyte = memory # INLINE gibibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of tebibytes . > > > showMemory $ tebibyte 42 " 42TiB " >>> showMemory $ tebibyte 42 "42TiB" -} tebibyte :: Natural -> Memory Tebibyte tebibyte = memory # INLINE tebibyte # | Creates ' Memory ' in ' Pebibyte 's from given ' Natural ' as the number of pebibytes . > > > showMemory $ pebibyte 42 " 42PiB " >>> showMemory $ pebibyte 42 "42PiB" -} pebibyte :: Natural -> Memory Pebibyte pebibyte = memory # INLINE pebibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of exbibytes . > > > showMemory $ exbibyte 42 " 42EiB " >>> showMemory $ exbibyte 42 "42EiB" -} exbibyte :: Natural -> Memory Exbibyte exbibyte = memory # INLINE exbibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of zebibytes . > > > showMemory $ zebibyte 42 " 42ZiB " >>> showMemory $ zebibyte 42 "42ZiB" -} zebibyte :: Natural -> Memory Zebibyte zebibyte = memory # INLINE zebibyte # | Creates ' Memory ' in ' 's from given ' Natural ' as the number of yobibytes . > > > showMemory $ yobibyte 42 " 42YiB " >>> showMemory $ yobibyte 42 "42YiB" -} yobibyte :: Natural -> Memory Yobibyte yobibyte = memory # INLINE yobibyte #
8e99d7781d3e79252b25b48e801807d3423414edabf69f0a95a31148c517424f
unisonweb/unison
Desugar.hs
module Unison.PatternMatchCoverage.Desugar ( desugarMatch, ) where import Data.List.NonEmpty (NonEmpty (..)) import qualified U.Core.ABT as ABT import Unison.Pattern import qualified Unison.Pattern as Pattern import Unison.PatternMatchCoverage.Class import Unison.PatternMatchCoverage.Fix import Unison.PatternMatchCoverage.GrdTree import Unison.PatternMatchCoverage.PmGrd import qualified Unison.PatternMatchCoverage.PmLit as PmLit import Unison.Term (MatchCase (..), Term', app, var) import Unison.Type (Type) import qualified Unison.Type as Type | a match into a ' GrdTree ' desugarMatch :: forall loc vt v m. (Pmc vt v loc m) => -- | loc of match loc -> -- | scrutinee type Type vt loc -> -- | scrutinee variable v -> -- | match cases [MatchCase loc (Term' vt v loc)] -> m (GrdTree (PmGrd vt v loc) loc) desugarMatch loc0 scrutineeType v0 cs0 = traverse desugarClause cs0 >>= \case [] -> pure $ Leaf loc0 x : xs -> pure $ Fork (x :| xs) where desugarClause :: MatchCase loc (Term' vt v loc) -> m (GrdTree (PmGrd vt v loc) loc) desugarClause MatchCase {matchPattern, matchGuard} = desugarPattern scrutineeType v0 matchPattern (finalK (Pattern.loc matchPattern) matchGuard) [] finalK :: loc -> Maybe (Term' vt v loc) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) finalK loc mterm vs = case mterm of Nothing -> pure (Leaf loc) Just grdExpr -> do let ann = ABT.annotation grdExpr expr = foldr (\a b -> app ann (var ann a) b) grdExpr vs typ = Type.boolean ann v <- fresh pure (Grd (PmLet v expr typ) (Grd (PmLit v (PmLit.Boolean True)) (Leaf loc))) desugarPattern :: forall v vt loc m. (Pmc vt v loc m) => Type vt loc -> v -> Pattern loc -> ([v] -> m (GrdTree (PmGrd vt v loc) loc)) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) desugarPattern typ v0 pat k vs = case pat of Unbound _ -> k vs Var _ -> k (v0 : vs) Boolean _ x -> Grd (PmLit v0 $ PmLit.Boolean x) <$> k vs Int _ x -> Grd (PmLit v0 $ PmLit.Int x) <$> k vs Nat _ x -> Grd (PmLit v0 $ PmLit.Nat x) <$> k vs Float _ x -> Grd (PmLit v0 $ PmLit.Float x) <$> k vs Text _ x -> Grd (PmLit v0 $ PmLit.Text x) <$> k vs Char _ x -> Grd (PmLit v0 $ PmLit.Char x) <$> k vs Constructor _loc consRef pats -> do contyps <- getConstructorVarTypes typ consRef patvars <- assignFreshPatternVars pats let c = PmCon v0 consRef convars convars :: [(v, Type vt loc)] convars = map (\(v, _, t) -> (v, t)) tpatvars tpatvars = zipWith (\(v, p) t -> (v, p, t)) patvars contyps rest <- foldr (\(v, pat, t) b -> desugarPattern t v pat b) k tpatvars vs pure (Grd c rest) As _ rest -> desugarPattern typ v0 rest k (v0 : vs) EffectPure {} -> k vs EffectBind {} -> k vs SequenceLiteral {} -> handleSequence typ v0 pat k vs SequenceOp {} -> handleSequence typ v0 pat k vs handleSequence :: forall v vt loc m. (Pmc vt v loc m) => Type vt loc -> v -> Pattern loc -> ([v] -> m (GrdTree (PmGrd vt v loc) loc)) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) handleSequence typ v pat k vs = do let listArg = case typ of Type.App' _list arg -> arg _ -> error "list type is not an application?" listToGrdTree typ listArg v (normalizeList pat) k vs listToGrdTree :: forall v vt loc m. (Pmc vt v loc m) => Type vt loc -> Type vt loc -> v -> NormalizedList loc -> ([v] -> m (GrdTree (PmGrd vt v loc) loc)) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) listToGrdTree _listTyp elemTyp listVar nl0 k0 vs0 = let (minLen, maxLen) = countMinListLen nl0 in Grd (PmListInterval listVar minLen maxLen) <$> go 0 0 nl0 k0 vs0 where go consCount snocCount (Fix pat) k vs = case pat of N'ConsF x xs -> do element <- fresh let grd = PmListHead listVar consCount element elemTyp let !consCount' = consCount + 1 Grd grd <$> desugarPattern elemTyp element x (go consCount' snocCount xs k) vs N'SnocF xs x -> do element <- fresh let grd = PmListTail listVar snocCount element elemTyp let !snocCount' = snocCount + 1 Grd grd <$> go consCount snocCount' xs (desugarPattern elemTyp element x k) vs N'NilF -> k vs N'VarF _ -> k (listVar : vs) N'UnboundF _ -> k vs countMinListLen :: NormalizedList loc -> (Int, Int) countMinListLen = ($ 0) . cata \case N'ConsF _ b -> \acc -> b $! acc + 1 N'SnocF b _ -> \acc -> b $! acc + 1 N'NilF -> \ !n -> (n, n) N'VarF _ -> \ !n -> (n, maxBound) N'UnboundF _ -> \ !n -> (n, maxBound) data NormalizedListF loc a = N'ConsF (Pattern loc) a | N'SnocF a (Pattern loc) | N'NilF | N'VarF loc | N'UnboundF loc deriving stock (Functor) type NormalizedList loc = Fix (NormalizedListF loc) pattern N'Cons :: Pattern loc -> Fix (NormalizedListF loc) -> Fix (NormalizedListF loc) pattern N'Cons x xs = Fix (N'ConsF x xs) pattern N'Snoc :: Fix (NormalizedListF loc) -> Pattern loc -> Fix (NormalizedListF loc) pattern N'Snoc xs x = Fix (N'SnocF xs x) pattern N'Nil :: Fix (NormalizedListF loc) pattern N'Nil = Fix N'NilF pattern N'Var :: loc -> Fix (NormalizedListF loc) pattern N'Var x = Fix (N'VarF x) pattern N'Unbound :: loc -> Fix (NormalizedListF loc) pattern N'Unbound x = Fix (N'UnboundF x) | strip out sequence literals and concats normalizeList :: Pattern loc -> NormalizedList loc normalizeList pat0 = case goCons pat0 of Left f -> f N'Nil Right x -> x where goCons :: Pattern loc -> Either (NormalizedList loc -> NormalizedList loc) (NormalizedList loc) goCons = \case SequenceLiteral _loc xs -> Left \nil -> foldr N'Cons nil xs SequenceOp _loc lhs op rhs -> case op of Cons -> case goCons rhs of Left f -> Left (N'Cons lhs . f) Right x -> Right (N'Cons lhs x) Snoc -> case goCons lhs of Left f -> Left (f . N'Cons rhs) Right x -> Right (N'Snoc x rhs) Concat -> case goCons lhs of Left f -> case goCons rhs of Left g -> Left (f . g) Right x -> Right (f x) Right x -> Right (goSnoc rhs x) Var loc -> Right (N'Var loc) Unbound loc -> Right (N'Unbound loc) -- as-patterns are not handled properly here, which is fine while we -- only have boolean guards, but this needs to be fixed if we -- introduce pattern guards As _loc pat -> goCons pat _ -> error "goCons: unexpected pattern" goSnoc :: Pattern loc -> NormalizedList loc -> NormalizedList loc goSnoc pat nlp = case pat of SequenceLiteral _loc xs -> foldl N'Snoc nlp xs SequenceOp _loc lhs op rhs -> case op of Cons -> goSnoc rhs (N'Snoc nlp lhs) Snoc -> N'Snoc (goSnoc rhs nlp) lhs Concat -> goSnoc rhs (goSnoc lhs nlp) As _loc pat -> goSnoc pat nlp _ -> error "goSnoc: unexpected pattern" assignFreshPatternVars :: (Pmc vt v loc m) => [Pattern loc] -> m [(v, Pattern loc)] assignFreshPatternVars pats = traverse (\p -> (,p) <$> fresh) pats
null
https://raw.githubusercontent.com/unisonweb/unison/61b65bfe5b16df10d2ba9ba05afecfaffc016d0b/parser-typechecker/src/Unison/PatternMatchCoverage/Desugar.hs
haskell
| loc of match | scrutinee type | scrutinee variable | match cases as-patterns are not handled properly here, which is fine while we only have boolean guards, but this needs to be fixed if we introduce pattern guards
module Unison.PatternMatchCoverage.Desugar ( desugarMatch, ) where import Data.List.NonEmpty (NonEmpty (..)) import qualified U.Core.ABT as ABT import Unison.Pattern import qualified Unison.Pattern as Pattern import Unison.PatternMatchCoverage.Class import Unison.PatternMatchCoverage.Fix import Unison.PatternMatchCoverage.GrdTree import Unison.PatternMatchCoverage.PmGrd import qualified Unison.PatternMatchCoverage.PmLit as PmLit import Unison.Term (MatchCase (..), Term', app, var) import Unison.Type (Type) import qualified Unison.Type as Type | a match into a ' GrdTree ' desugarMatch :: forall loc vt v m. (Pmc vt v loc m) => loc -> Type vt loc -> v -> [MatchCase loc (Term' vt v loc)] -> m (GrdTree (PmGrd vt v loc) loc) desugarMatch loc0 scrutineeType v0 cs0 = traverse desugarClause cs0 >>= \case [] -> pure $ Leaf loc0 x : xs -> pure $ Fork (x :| xs) where desugarClause :: MatchCase loc (Term' vt v loc) -> m (GrdTree (PmGrd vt v loc) loc) desugarClause MatchCase {matchPattern, matchGuard} = desugarPattern scrutineeType v0 matchPattern (finalK (Pattern.loc matchPattern) matchGuard) [] finalK :: loc -> Maybe (Term' vt v loc) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) finalK loc mterm vs = case mterm of Nothing -> pure (Leaf loc) Just grdExpr -> do let ann = ABT.annotation grdExpr expr = foldr (\a b -> app ann (var ann a) b) grdExpr vs typ = Type.boolean ann v <- fresh pure (Grd (PmLet v expr typ) (Grd (PmLit v (PmLit.Boolean True)) (Leaf loc))) desugarPattern :: forall v vt loc m. (Pmc vt v loc m) => Type vt loc -> v -> Pattern loc -> ([v] -> m (GrdTree (PmGrd vt v loc) loc)) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) desugarPattern typ v0 pat k vs = case pat of Unbound _ -> k vs Var _ -> k (v0 : vs) Boolean _ x -> Grd (PmLit v0 $ PmLit.Boolean x) <$> k vs Int _ x -> Grd (PmLit v0 $ PmLit.Int x) <$> k vs Nat _ x -> Grd (PmLit v0 $ PmLit.Nat x) <$> k vs Float _ x -> Grd (PmLit v0 $ PmLit.Float x) <$> k vs Text _ x -> Grd (PmLit v0 $ PmLit.Text x) <$> k vs Char _ x -> Grd (PmLit v0 $ PmLit.Char x) <$> k vs Constructor _loc consRef pats -> do contyps <- getConstructorVarTypes typ consRef patvars <- assignFreshPatternVars pats let c = PmCon v0 consRef convars convars :: [(v, Type vt loc)] convars = map (\(v, _, t) -> (v, t)) tpatvars tpatvars = zipWith (\(v, p) t -> (v, p, t)) patvars contyps rest <- foldr (\(v, pat, t) b -> desugarPattern t v pat b) k tpatvars vs pure (Grd c rest) As _ rest -> desugarPattern typ v0 rest k (v0 : vs) EffectPure {} -> k vs EffectBind {} -> k vs SequenceLiteral {} -> handleSequence typ v0 pat k vs SequenceOp {} -> handleSequence typ v0 pat k vs handleSequence :: forall v vt loc m. (Pmc vt v loc m) => Type vt loc -> v -> Pattern loc -> ([v] -> m (GrdTree (PmGrd vt v loc) loc)) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) handleSequence typ v pat k vs = do let listArg = case typ of Type.App' _list arg -> arg _ -> error "list type is not an application?" listToGrdTree typ listArg v (normalizeList pat) k vs listToGrdTree :: forall v vt loc m. (Pmc vt v loc m) => Type vt loc -> Type vt loc -> v -> NormalizedList loc -> ([v] -> m (GrdTree (PmGrd vt v loc) loc)) -> [v] -> m (GrdTree (PmGrd vt v loc) loc) listToGrdTree _listTyp elemTyp listVar nl0 k0 vs0 = let (minLen, maxLen) = countMinListLen nl0 in Grd (PmListInterval listVar minLen maxLen) <$> go 0 0 nl0 k0 vs0 where go consCount snocCount (Fix pat) k vs = case pat of N'ConsF x xs -> do element <- fresh let grd = PmListHead listVar consCount element elemTyp let !consCount' = consCount + 1 Grd grd <$> desugarPattern elemTyp element x (go consCount' snocCount xs k) vs N'SnocF xs x -> do element <- fresh let grd = PmListTail listVar snocCount element elemTyp let !snocCount' = snocCount + 1 Grd grd <$> go consCount snocCount' xs (desugarPattern elemTyp element x k) vs N'NilF -> k vs N'VarF _ -> k (listVar : vs) N'UnboundF _ -> k vs countMinListLen :: NormalizedList loc -> (Int, Int) countMinListLen = ($ 0) . cata \case N'ConsF _ b -> \acc -> b $! acc + 1 N'SnocF b _ -> \acc -> b $! acc + 1 N'NilF -> \ !n -> (n, n) N'VarF _ -> \ !n -> (n, maxBound) N'UnboundF _ -> \ !n -> (n, maxBound) data NormalizedListF loc a = N'ConsF (Pattern loc) a | N'SnocF a (Pattern loc) | N'NilF | N'VarF loc | N'UnboundF loc deriving stock (Functor) type NormalizedList loc = Fix (NormalizedListF loc) pattern N'Cons :: Pattern loc -> Fix (NormalizedListF loc) -> Fix (NormalizedListF loc) pattern N'Cons x xs = Fix (N'ConsF x xs) pattern N'Snoc :: Fix (NormalizedListF loc) -> Pattern loc -> Fix (NormalizedListF loc) pattern N'Snoc xs x = Fix (N'SnocF xs x) pattern N'Nil :: Fix (NormalizedListF loc) pattern N'Nil = Fix N'NilF pattern N'Var :: loc -> Fix (NormalizedListF loc) pattern N'Var x = Fix (N'VarF x) pattern N'Unbound :: loc -> Fix (NormalizedListF loc) pattern N'Unbound x = Fix (N'UnboundF x) | strip out sequence literals and concats normalizeList :: Pattern loc -> NormalizedList loc normalizeList pat0 = case goCons pat0 of Left f -> f N'Nil Right x -> x where goCons :: Pattern loc -> Either (NormalizedList loc -> NormalizedList loc) (NormalizedList loc) goCons = \case SequenceLiteral _loc xs -> Left \nil -> foldr N'Cons nil xs SequenceOp _loc lhs op rhs -> case op of Cons -> case goCons rhs of Left f -> Left (N'Cons lhs . f) Right x -> Right (N'Cons lhs x) Snoc -> case goCons lhs of Left f -> Left (f . N'Cons rhs) Right x -> Right (N'Snoc x rhs) Concat -> case goCons lhs of Left f -> case goCons rhs of Left g -> Left (f . g) Right x -> Right (f x) Right x -> Right (goSnoc rhs x) Var loc -> Right (N'Var loc) Unbound loc -> Right (N'Unbound loc) As _loc pat -> goCons pat _ -> error "goCons: unexpected pattern" goSnoc :: Pattern loc -> NormalizedList loc -> NormalizedList loc goSnoc pat nlp = case pat of SequenceLiteral _loc xs -> foldl N'Snoc nlp xs SequenceOp _loc lhs op rhs -> case op of Cons -> goSnoc rhs (N'Snoc nlp lhs) Snoc -> N'Snoc (goSnoc rhs nlp) lhs Concat -> goSnoc rhs (goSnoc lhs nlp) As _loc pat -> goSnoc pat nlp _ -> error "goSnoc: unexpected pattern" assignFreshPatternVars :: (Pmc vt v loc m) => [Pattern loc] -> m [(v, Pattern loc)] assignFreshPatternVars pats = traverse (\p -> (,p) <$> fresh) pats
240b1d71c8e344b85ad43e6aeb20e3dcfa95237b13f83b6d89f93b5a2feda9a1
plum-umd/fundamentals
zip.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname zip) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; Session ID: 887722 A ListofInt is one of : ;; - '() - ( cons Integer ListofInt ) A ListofPairofInt is one of : ;; - '() - ( cons PairofInt ListofPairofInt ) A PairofInt is a ( make - pair ) (define-struct pair (left right)) zip : ListofInt ListofInt - > ListofPairofInt ;; Zip together the given lists into a list of pairs ;; Stops zipping at end of the shortest list (check-expect (zip (list 1 2 3) (list 4 5 6)) (list (make-pair 1 4) (make-pair 2 5) (make-pair 3 6))) (check-expect (zip (list 1 2) (list 4 5 6)) (list (make-pair 1 4) (make-pair 2 5))) (check-expect (zip (list 1 2 3) (list 4 5)) (list (make-pair 1 4) (make-pair 2 5))) #; (define (zip ls1 ls2) (cond [(empty? ls1) '()] [(cons? ls1) (cond [(empty? ls2) '()] [(cons? ls2) (cons (make-pair (first ls1) (first ls2)) (zip (rest ls1) (rest ls2)))])])) (define (zip ls1 ls2) (cond [(empty? ls1) '()] [(cons? ls1) (zip-cons ls2 (first ls1) (rest ls1))])) zip - cons : ListofInt Integer ListofInteger - > ListofPairofInteger (define (zip-cons ls2 first-ls1 rest-ls1) (cond [(empty? ls2) '()] [(cons? ls2) (cons (make-pair first-ls1 (first ls2)) (zip rest-ls1 (rest ls2)))]))
null
https://raw.githubusercontent.com/plum-umd/fundamentals/eb01ac528d42855be53649991a17d19c025a97ad/2/www/lectures/4/zip.rkt
racket
about the language level of this file in a form that our tools can easily process. Session ID: 887722 - '() - '() Zip together the given lists into a list of pairs Stops zipping at end of the shortest list
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname zip) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) A ListofInt is one of : - ( cons Integer ListofInt ) A ListofPairofInt is one of : - ( cons PairofInt ListofPairofInt ) A PairofInt is a ( make - pair ) (define-struct pair (left right)) zip : ListofInt ListofInt - > ListofPairofInt (check-expect (zip (list 1 2 3) (list 4 5 6)) (list (make-pair 1 4) (make-pair 2 5) (make-pair 3 6))) (check-expect (zip (list 1 2) (list 4 5 6)) (list (make-pair 1 4) (make-pair 2 5))) (check-expect (zip (list 1 2 3) (list 4 5)) (list (make-pair 1 4) (make-pair 2 5))) (define (zip ls1 ls2) (cond [(empty? ls1) '()] [(cons? ls1) (cond [(empty? ls2) '()] [(cons? ls2) (cons (make-pair (first ls1) (first ls2)) (zip (rest ls1) (rest ls2)))])])) (define (zip ls1 ls2) (cond [(empty? ls1) '()] [(cons? ls1) (zip-cons ls2 (first ls1) (rest ls1))])) zip - cons : ListofInt Integer ListofInteger - > ListofPairofInteger (define (zip-cons ls2 first-ls1 rest-ls1) (cond [(empty? ls2) '()] [(cons? ls2) (cons (make-pair first-ls1 (first ls2)) (zip rest-ls1 (rest ls2)))]))
dbac1e188be88f0adcb4b9284a5821536b224eaf5430e95b8800a7bd04cf6a6a
Paczesiowa/virthualenv
Skeletons.hs
# LANGUAGE TemplateHaskell # module Skeletons where import Data.FileEmbed (embedFile) import Data.ByteString.Char8 (unpack) import System.FilePath ((</>)) activateSkel :: String activateSkel = unpack $(embedFile $ "skeletons" </> "activate") cabalWrapperSkel :: String cabalWrapperSkel = unpack $(embedFile $ "skeletons" </> "cabal") cabalConfigSkel :: String cabalConfigSkel = unpack $(embedFile $ "skeletons" </> "cabal_config")
null
https://raw.githubusercontent.com/Paczesiowa/virthualenv/aab89dad9de7dac5268472eaa50c11eb40b02380/src/Skeletons.hs
haskell
# LANGUAGE TemplateHaskell # module Skeletons where import Data.FileEmbed (embedFile) import Data.ByteString.Char8 (unpack) import System.FilePath ((</>)) activateSkel :: String activateSkel = unpack $(embedFile $ "skeletons" </> "activate") cabalWrapperSkel :: String cabalWrapperSkel = unpack $(embedFile $ "skeletons" </> "cabal") cabalConfigSkel :: String cabalConfigSkel = unpack $(embedFile $ "skeletons" </> "cabal_config")
131f2ed5beb6e87d918e79fa89ab4c117c43b3bcb05c907a13a336a5d0996cb2
pat227/ocaml-db-model
date_time_extended.mli
module Date_time_extended : sig (*type t = Core.Time.t*) include (module type of Core.Time) val show : ?zoneoffset:int -> t -> Ppx_deriving_runtime.string val to_string : ?zoneoffset:int -> t -> string (*of_string internally supports parsing date time values without time zone offsets since mysql does not display time zone offsets even if a time zone offset was supplied when inserting the value.*) val of_string : ?zoneoffset:int -> string -> t val compare : t -> t -> Ppx_deriving_runtime.int val equal : t -> t -> Ppx_deriving_runtime.bool Type json changed to type t sometime after 4.06.0 val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or Not useful unless have local hacked version of csvfields MUST use these val to_xml : t - > Csvfields.Xml.xml list val of_xml : Csvfields.Xml.xml - > t val xsd : Csvfields.Xml.xml list MUST use these val to_xml : t -> Csvfields.Xml.xml list val of_xml : Csvfields.Xml.xml -> t val xsd : Csvfields.Xml.xml list*) end
null
https://raw.githubusercontent.com/pat227/ocaml-db-model/d117aabcaee88a309ce3af3e11dec031edd3bed4/src/lib/date_time_extended.mli
ocaml
type t = Core.Time.t of_string internally supports parsing date time values without time zone offsets since mysql does not display time zone offsets even if a time zone offset was supplied when inserting the value.
module Date_time_extended : sig include (module type of Core.Time) val show : ?zoneoffset:int -> t -> Ppx_deriving_runtime.string val to_string : ?zoneoffset:int -> t -> string val of_string : ?zoneoffset:int -> string -> t val compare : t -> t -> Ppx_deriving_runtime.int val equal : t -> t -> Ppx_deriving_runtime.bool Type json changed to type t sometime after 4.06.0 val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or Not useful unless have local hacked version of csvfields MUST use these val to_xml : t - > Csvfields.Xml.xml list val of_xml : Csvfields.Xml.xml - > t val xsd : Csvfields.Xml.xml list MUST use these val to_xml : t -> Csvfields.Xml.xml list val of_xml : Csvfields.Xml.xml -> t val xsd : Csvfields.Xml.xml list*) end
8f347658d668d82da9ff8899ceb54a2420677b17540e0b20aad19959d35afce8
herbie-fp/regraph
precompute.rkt
#lang racket code extracted and simplified from v1.4 master April 25 2020 (require math/flonum math/base math/special-functions math/bigfloat racket/hash) (provide eval-application) (define (cbrt x) (expt x (/ 1 3))) (define (exp2 x) (expt 2 x)) (define (log10 x) (log x 10)) (define (copysign x y) (if (>= y 0) (abs x) (- (abs x)))) (define (fdim x y) (max (- x y) 0)) (define (fma x y z) (bigfloat->flonum (bf+ (bf* (bf x) (bf y)) (bf z)))) (define (fmax x y) (cond ((nan? x) y) ((nan? y) x) (else (max x y)))) (define (fmin x y) (cond ((nan? x) y) ((nan? y) x) (else (min x y)))) (define (logb x) (floor (log (abs x) 2))) (define real-fns (list + - * / acos acosh asin asinh atan atanh cbrt copysign cos cosh erf erfc exp exp2 fdim floor fma fmax fmin log log10 logb remainder round sin sinh sqrt tan tanh)) (define (no-complex fun) (λ xs (define res (apply fun xs)) (if (real? res) res +nan.0))) (define real-operations (for/hash ([fn real-fns]) (values (object-name fn) (no-complex fn)))) (define (from-bigfloat bff) (λ args (bigfloat->flonum (apply bff (map bf args))))) (define (bffmod x mod) (bf- x (bf* (bftruncate (bf/ x mod)) mod))) (define from-bf-operations (hash 'expm1 (from-bigfloat bfexpm1) 'fmod (from-bigfloat bffmod) 'hypot (from-bigfloat bfhypot) 'j0 (from-bigfloat bfbesj0) 'j1 (from-bigfloat bfbesj1) 'log1p (from-bigfloat bflog1p) 'log2 (from-bigfloat bflog2) 'y0 (from-bigfloat bfbesy0) 'y1 (from-bigfloat bfbesy1))) (define complex-operations (hash '+.c + '-.c - '*.c * '/.c / 'exp.c exp 'log.c log 'pow.c expt 'sqrt.c sqrt 'complex make-rectangular 're real-part 'im imag-part 'conj conjugate 'neg.c -)) (define ((comparator test) . args) (for/and ([left args] [right (cdr args)]) (test left right))) (define (if-fn test if-true if-false) (if test if-true if-false)) (define (and-fn . as) (andmap identity as)) (define (or-fn . as) (ormap identity as)) (define (!=-fn . args) (not (check-duplicates args =))) (define other-operations (hash 'ceil ceiling 'atan2 (no-complex atan) 'fabs abs 'lgamma log-gamma 'pow (no-complex expt) 'rint round 'tgamma gamma 'trunc truncate '== (comparator =) '!= !=-fn '< (comparator <) '> (comparator >) '<= (comparator <=) '>= (comparator >=) 'if if-fn 'not not 'and and-fn 'or or-fn)) (define operations (hash-union complex-operations real-operations from-bf-operations other-operations)) (define (val-to-type val) (match val [#t 'TRUE] [#f 'FALSE] [(? real?) val])) (define (exact-noncomplex-value? val) (and (not (and (complex? val) (not (real? val)))) (exact? val))) (define (eval-application op . args) (if (and (not (null? args)) (andmap (conjoin number? exact?) args)) (with-handlers ([exn:fail:contract:divide-by-zero? (const #f)]) (define res (apply (hash-ref operations op) args)) (and (exact-noncomplex-value? res) (val-to-type res))) false))
null
https://raw.githubusercontent.com/herbie-fp/regraph/1725355df2cd1ffef7e0c8f01cde848d0f3dcfbf/infra/precompute.rkt
racket
#lang racket code extracted and simplified from v1.4 master April 25 2020 (require math/flonum math/base math/special-functions math/bigfloat racket/hash) (provide eval-application) (define (cbrt x) (expt x (/ 1 3))) (define (exp2 x) (expt 2 x)) (define (log10 x) (log x 10)) (define (copysign x y) (if (>= y 0) (abs x) (- (abs x)))) (define (fdim x y) (max (- x y) 0)) (define (fma x y z) (bigfloat->flonum (bf+ (bf* (bf x) (bf y)) (bf z)))) (define (fmax x y) (cond ((nan? x) y) ((nan? y) x) (else (max x y)))) (define (fmin x y) (cond ((nan? x) y) ((nan? y) x) (else (min x y)))) (define (logb x) (floor (log (abs x) 2))) (define real-fns (list + - * / acos acosh asin asinh atan atanh cbrt copysign cos cosh erf erfc exp exp2 fdim floor fma fmax fmin log log10 logb remainder round sin sinh sqrt tan tanh)) (define (no-complex fun) (λ xs (define res (apply fun xs)) (if (real? res) res +nan.0))) (define real-operations (for/hash ([fn real-fns]) (values (object-name fn) (no-complex fn)))) (define (from-bigfloat bff) (λ args (bigfloat->flonum (apply bff (map bf args))))) (define (bffmod x mod) (bf- x (bf* (bftruncate (bf/ x mod)) mod))) (define from-bf-operations (hash 'expm1 (from-bigfloat bfexpm1) 'fmod (from-bigfloat bffmod) 'hypot (from-bigfloat bfhypot) 'j0 (from-bigfloat bfbesj0) 'j1 (from-bigfloat bfbesj1) 'log1p (from-bigfloat bflog1p) 'log2 (from-bigfloat bflog2) 'y0 (from-bigfloat bfbesy0) 'y1 (from-bigfloat bfbesy1))) (define complex-operations (hash '+.c + '-.c - '*.c * '/.c / 'exp.c exp 'log.c log 'pow.c expt 'sqrt.c sqrt 'complex make-rectangular 're real-part 'im imag-part 'conj conjugate 'neg.c -)) (define ((comparator test) . args) (for/and ([left args] [right (cdr args)]) (test left right))) (define (if-fn test if-true if-false) (if test if-true if-false)) (define (and-fn . as) (andmap identity as)) (define (or-fn . as) (ormap identity as)) (define (!=-fn . args) (not (check-duplicates args =))) (define other-operations (hash 'ceil ceiling 'atan2 (no-complex atan) 'fabs abs 'lgamma log-gamma 'pow (no-complex expt) 'rint round 'tgamma gamma 'trunc truncate '== (comparator =) '!= !=-fn '< (comparator <) '> (comparator >) '<= (comparator <=) '>= (comparator >=) 'if if-fn 'not not 'and and-fn 'or or-fn)) (define operations (hash-union complex-operations real-operations from-bf-operations other-operations)) (define (val-to-type val) (match val [#t 'TRUE] [#f 'FALSE] [(? real?) val])) (define (exact-noncomplex-value? val) (and (not (and (complex? val) (not (real? val)))) (exact? val))) (define (eval-application op . args) (if (and (not (null? args)) (andmap (conjoin number? exact?) args)) (with-handlers ([exn:fail:contract:divide-by-zero? (const #f)]) (define res (apply (hash-ref operations op) args)) (and (exact-noncomplex-value? res) (val-to-type res))) false))
964991f73ff6fd1599ca16ad75ea46c9ccaffd3f7d24d33034fe74f0e8115944
billstclair/trubanc-lisp
length.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : FLEXI - STREAMS ; Base : 10 -*- $ Header : /usr / local / cvsrep / flexi - streams / length.lisp , v 1.6 2008/05/29 10:25:14 edi Exp $ Copyright ( c ) 2005 - 2008 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defgeneric encoding-factor (format) (:documentation "Given an external format FORMAT, returns a factor which denotes the octets to characters ratio to expect when encoding/decoding. If the returned value is an integer, the factor is assumed to be exact. If it is a \(double) float, the factor is supposed to be based on heuristics and usually not exact. This factor is used in string.lisp.") (declare #.*standard-optimize-settings*)) (defmethod encoding-factor ((format flexi-8-bit-format)) (declare #.*standard-optimize-settings*) 8 - bit encodings map octets to characters in an exact one - to - one ;; fashion 1) (defmethod encoding-factor ((format flexi-utf-8-format)) (declare #.*standard-optimize-settings*) UTF-8 characters can be anything from one to six octets , but we assume that the " overhead " is only about 5 percent - this ;; estimate is obviously very much dependant on the content 1.05d0) (defmethod encoding-factor ((format flexi-utf-16-format)) (declare #.*standard-optimize-settings*) usually one character maps to two octets , but characters with code points above # x10000 map to four octets - we assume that we ;; usually don't see these characters but of course have to return a ;; float 2.0d0) (defmethod encoding-factor ((format flexi-utf-32-format)) (declare #.*standard-optimize-settings*) UTF-32 always matches every character to four octets 4) (defmethod encoding-factor ((format flexi-crlf-mixin)) (declare #.*standard-optimize-settings*) ;; if the sequence #\Return #\Linefeed is the line-end marker, this ;; obviously makes encodings potentially longer and definitely makes ;; the estimate unexact (* 1.02d0 (call-next-method))) (defgeneric check-end (format start end i) (declare #.*fixnum-optimize-settings*) (:documentation "Helper function used below to determine if we tried to read past the end of the sequence.") (:method (format start end i) (declare #.*fixnum-optimize-settings*) (declare (ignore start)) (declare (fixnum end i)) (when (> i end) (signal-encoding-error format "This sequence can't be decoded ~ using ~A as it is too short. ~A octet~:P missing at then end." (external-format-name format) (- i end)))) (:method ((format flexi-utf-16-format) start end i) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end i)) (declare (ignore i)) ;; don't warn twice (when (evenp (- end start)) (call-next-method)))) (defgeneric compute-number-of-chars (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "Computes the exact number of characters required to decode the sequence of octets in SEQUENCE from START to END using the external format FORMAT.")) (defmethod compute-number-of-chars :around (format (list list) start end) (declare #.*standard-optimize-settings*) (call-next-method format (coerce list 'vector) start end)) (defmethod compute-number-of-chars ((format flexi-8-bit-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (- end start)) (defmethod compute-number-of-chars ((format flexi-crlf-mixin) sequence start end) this method only applies to the 8 - bit formats as all other ;; formats with CRLF line endings have their own specialized methods ;; below (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (- end start))) (declare (fixnum i length)) (loop (when (>= i end) (return)) (let ((position (search #.(vector +cr+ +lf+) sequence :start2 i :end2 end :test #'=))) (unless position (return)) (setq i (1+ position)) (decf length))) length)) (defmethod compute-number-of-chars ((format flexi-utf-8-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((octet (aref sequence i)) ;; note that there are no validity checks here (length (cond ((not (logbitp 7 octet)) 1) ((= #b11000000 (logand* octet #b11100000)) 2) ((= #b11100000 (logand* octet #b11110000)) 3) (t 4)))) (declare (fixnum length) (type octet octet)) (incf sum) (incf i length))) (check-end format start end i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-8-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (loop (when (>= i end) (return)) (let* ((octet (aref sequence i)) ;; note that there are no validity checks here (length (cond ((not (logbitp 7 octet)) 1) ((= #b11000000 (logand* octet #b11100000)) 2) ((= #b11100000 (logand* octet #b11110000)) 3) (t 4)))) (declare (fixnum length) (type octet octet)) (unless (and (= octet +lf+) (= last-octet +cr+)) (incf sum)) (incf i length) (setq last-octet octet))) (check-end format start end i) sum)) (defmethod compute-number-of-chars :before ((format flexi-utf-16-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (declare (ignore sequence)) (when (oddp (- end start)) (signal-encoding-error format "~A octet~:P cannot be decoded ~ using UTF-16 as ~:*~A is not even." (- end start)))) (defmethod compute-number-of-chars ((format flexi-utf-16-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence (1+ i))) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (incf sum) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-utf-16-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence i)) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (incf sum) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-16-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence (1+ i))) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (unless (and (zerop high-octet) (= (the octet (aref sequence i)) +lf+) (= last-octet +cr+)) (incf sum)) (setq last-octet (if (zerop high-octet) (aref sequence i) 0)) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-16-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence i)) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (unless (and (zerop high-octet) (= (the octet (aref sequence (1+ i))) +lf+) (= last-octet +cr+)) (incf sum)) (setq last-octet (if (zerop high-octet) (aref sequence (1+ i)) 0)) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars :before ((format flexi-utf-32-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (let ((length (- end start))) (when (plusp (mod length 4)) (signal-encoding-error format "~A octet~:P cannot be decoded ~ using UTF-32 as ~:*~A is not a multiple-value of four." length)))) (defmethod compute-number-of-chars ((format flexi-utf-32-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (ceiling (- end start) 4)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-32-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (ceiling (- end start) 4))) (decf end 8) (loop (when (> i end) (return)) (cond ((loop for j of-type fixnum from i for octet across #.(vector +cr+ 0 0 0 +lf+ 0 0 0) always (= octet (aref sequence j))) (decf length) (incf i 8)) (t (incf i 4)))) length)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-32-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (ceiling (- end start) 4))) (decf end 8) (loop (when (> i end) (return)) (cond ((loop for j of-type fixnum from i for octet across #.(vector 0 0 0 +cr+ 0 0 0 +lf+) always (= octet (aref sequence j))) (decf length) (incf i 8)) (t (incf i 4)))) length)) (defgeneric compute-number-of-octets (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "Computes the exact number of octets required to encode the sequence of characters in SEQUENCE from START to END using the external format FORMAT.")) (defmethod compute-number-of-octets :around (format (list list) start end) (declare #.*standard-optimize-settings*) (call-next-method format (coerce list 'string*) start end)) (defmethod compute-number-of-octets ((format flexi-8-bit-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore string)) (- end start)) (defmethod compute-number-of-octets ((format flexi-utf-8-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((< char-code #x80) 1) ((< char-code #x800) 2) ((< char-code #x10000) 3) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-8-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 2) ((< char-code #x80) 1) ((< char-code #x800) 2) ((< char-code #x10000) 3) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-utf-16-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-16-le-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 4) ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-16-be-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 4) ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-utf-32-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore string)) (* 4 (- end start))) (defmethod compute-number-of-octets ((format flexi-crlf-mixin) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (+ (call-next-method) (* (case (external-format-name format) (:utf-32 4) (otherwise 1)) (count #\Newline string :start start :end end :test #'char=)))) (defgeneric character-length (format char) (declare #.*fixnum-optimize-settings*) (:documentation "Returns the number of octets needed to encode the single character CHAR.") (:method (format char) (compute-number-of-octets format (string char) 0 1))) (defmethod character-length :around ((format flexi-crlf-mixin) (char (eql #\Newline))) (declare #.*fixnum-optimize-settings*) (+ (call-next-method format +cr+) (call-next-method format +lf+))) (defmethod character-length ((format flexi-8-bit-format) char) (declare #.*fixnum-optimize-settings*) (declare (ignore char)) 1) (defmethod character-length ((format flexi-utf-32-format) char) (declare #.*fixnum-optimize-settings*) (declare (ignore char)) 4)
null
https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/flexi-streams-1.0.7/length.lisp
lisp
Syntax : COMMON - LISP ; Package : FLEXI - STREAMS ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 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. fashion estimate is obviously very much dependant on the content usually don't see these characters but of course have to return a float if the sequence #\Return #\Linefeed is the line-end marker, this obviously makes encodings potentially longer and definitely makes the estimate unexact don't warn twice formats with CRLF line endings have their own specialized methods below note that there are no validity checks here note that there are no validity checks here
$ Header : /usr / local / cvsrep / flexi - streams / length.lisp , v 1.6 2008/05/29 10:25:14 edi Exp $ Copyright ( c ) 2005 - 2008 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :flexi-streams) (defgeneric encoding-factor (format) (:documentation "Given an external format FORMAT, returns a factor which denotes the octets to characters ratio to expect when encoding/decoding. If the returned value is an integer, the factor is assumed to be exact. If it is a \(double) float, the factor is supposed to be based on heuristics and usually not exact. This factor is used in string.lisp.") (declare #.*standard-optimize-settings*)) (defmethod encoding-factor ((format flexi-8-bit-format)) (declare #.*standard-optimize-settings*) 8 - bit encodings map octets to characters in an exact one - to - one 1) (defmethod encoding-factor ((format flexi-utf-8-format)) (declare #.*standard-optimize-settings*) UTF-8 characters can be anything from one to six octets , but we assume that the " overhead " is only about 5 percent - this 1.05d0) (defmethod encoding-factor ((format flexi-utf-16-format)) (declare #.*standard-optimize-settings*) usually one character maps to two octets , but characters with code points above # x10000 map to four octets - we assume that we 2.0d0) (defmethod encoding-factor ((format flexi-utf-32-format)) (declare #.*standard-optimize-settings*) UTF-32 always matches every character to four octets 4) (defmethod encoding-factor ((format flexi-crlf-mixin)) (declare #.*standard-optimize-settings*) (* 1.02d0 (call-next-method))) (defgeneric check-end (format start end i) (declare #.*fixnum-optimize-settings*) (:documentation "Helper function used below to determine if we tried to read past the end of the sequence.") (:method (format start end i) (declare #.*fixnum-optimize-settings*) (declare (ignore start)) (declare (fixnum end i)) (when (> i end) (signal-encoding-error format "This sequence can't be decoded ~ using ~A as it is too short. ~A octet~:P missing at then end." (external-format-name format) (- i end)))) (:method ((format flexi-utf-16-format) start end i) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end i)) (declare (ignore i)) (when (evenp (- end start)) (call-next-method)))) (defgeneric compute-number-of-chars (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "Computes the exact number of characters required to decode the sequence of octets in SEQUENCE from START to END using the external format FORMAT.")) (defmethod compute-number-of-chars :around (format (list list) start end) (declare #.*standard-optimize-settings*) (call-next-method format (coerce list 'vector) start end)) (defmethod compute-number-of-chars ((format flexi-8-bit-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (- end start)) (defmethod compute-number-of-chars ((format flexi-crlf-mixin) sequence start end) this method only applies to the 8 - bit formats as all other (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (- end start))) (declare (fixnum i length)) (loop (when (>= i end) (return)) (let ((position (search #.(vector +cr+ +lf+) sequence :start2 i :end2 end :test #'=))) (unless position (return)) (setq i (1+ position)) (decf length))) length)) (defmethod compute-number-of-chars ((format flexi-utf-8-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((octet (aref sequence i)) (length (cond ((not (logbitp 7 octet)) 1) ((= #b11000000 (logand* octet #b11100000)) 2) ((= #b11100000 (logand* octet #b11110000)) 3) (t 4)))) (declare (fixnum length) (type octet octet)) (incf sum) (incf i length))) (check-end format start end i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-8-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (loop (when (>= i end) (return)) (let* ((octet (aref sequence i)) (length (cond ((not (logbitp 7 octet)) 1) ((= #b11000000 (logand* octet #b11100000)) 2) ((= #b11100000 (logand* octet #b11110000)) 3) (t 4)))) (declare (fixnum length) (type octet octet)) (unless (and (= octet +lf+) (= last-octet +cr+)) (incf sum)) (incf i length) (setq last-octet octet))) (check-end format start end i) sum)) (defmethod compute-number-of-chars :before ((format flexi-utf-16-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (declare (ignore sequence)) (when (oddp (- end start)) (signal-encoding-error format "~A octet~:P cannot be decoded ~ using UTF-16 as ~:*~A is not even." (- end start)))) (defmethod compute-number-of-chars ((format flexi-utf-16-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence (1+ i))) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (incf sum) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-utf-16-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence i)) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (incf sum) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-16-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence (1+ i))) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (unless (and (zerop high-octet) (= (the octet (aref sequence i)) +lf+) (= last-octet +cr+)) (incf sum)) (setq last-octet (if (zerop high-octet) (aref sequence i) 0)) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-16-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence i)) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (unless (and (zerop high-octet) (= (the octet (aref sequence (1+ i))) +lf+) (= last-octet +cr+)) (incf sum)) (setq last-octet (if (zerop high-octet) (aref sequence (1+ i)) 0)) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars :before ((format flexi-utf-32-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (let ((length (- end start))) (when (plusp (mod length 4)) (signal-encoding-error format "~A octet~:P cannot be decoded ~ using UTF-32 as ~:*~A is not a multiple-value of four." length)))) (defmethod compute-number-of-chars ((format flexi-utf-32-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (ceiling (- end start) 4)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-32-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (ceiling (- end start) 4))) (decf end 8) (loop (when (> i end) (return)) (cond ((loop for j of-type fixnum from i for octet across #.(vector +cr+ 0 0 0 +lf+ 0 0 0) always (= octet (aref sequence j))) (decf length) (incf i 8)) (t (incf i 4)))) length)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-32-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (ceiling (- end start) 4))) (decf end 8) (loop (when (> i end) (return)) (cond ((loop for j of-type fixnum from i for octet across #.(vector 0 0 0 +cr+ 0 0 0 +lf+) always (= octet (aref sequence j))) (decf length) (incf i 8)) (t (incf i 4)))) length)) (defgeneric compute-number-of-octets (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "Computes the exact number of octets required to encode the sequence of characters in SEQUENCE from START to END using the external format FORMAT.")) (defmethod compute-number-of-octets :around (format (list list) start end) (declare #.*standard-optimize-settings*) (call-next-method format (coerce list 'string*) start end)) (defmethod compute-number-of-octets ((format flexi-8-bit-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore string)) (- end start)) (defmethod compute-number-of-octets ((format flexi-utf-8-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((< char-code #x80) 1) ((< char-code #x800) 2) ((< char-code #x10000) 3) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-8-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 2) ((< char-code #x80) 1) ((< char-code #x800) 2) ((< char-code #x10000) 3) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-utf-16-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-16-le-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 4) ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-16-be-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 4) ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-utf-32-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore string)) (* 4 (- end start))) (defmethod compute-number-of-octets ((format flexi-crlf-mixin) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (+ (call-next-method) (* (case (external-format-name format) (:utf-32 4) (otherwise 1)) (count #\Newline string :start start :end end :test #'char=)))) (defgeneric character-length (format char) (declare #.*fixnum-optimize-settings*) (:documentation "Returns the number of octets needed to encode the single character CHAR.") (:method (format char) (compute-number-of-octets format (string char) 0 1))) (defmethod character-length :around ((format flexi-crlf-mixin) (char (eql #\Newline))) (declare #.*fixnum-optimize-settings*) (+ (call-next-method format +cr+) (call-next-method format +lf+))) (defmethod character-length ((format flexi-8-bit-format) char) (declare #.*fixnum-optimize-settings*) (declare (ignore char)) 1) (defmethod character-length ((format flexi-utf-32-format) char) (declare #.*fixnum-optimize-settings*) (declare (ignore char)) 4)
8d5aca731ffd760f8b6e48d84cf85f8623963377e8f9df66e9864223935e7130
clojure-interop/google-cloud-clients
core.clj
(ns com.google.cloud.vision.v1p3beta1.core (:refer-clojure :only [require comment defn ->]) (:import )) (require '[com.google.cloud.vision.v1p3beta1.ImageAnnotatorClient]) (require '[com.google.cloud.vision.v1p3beta1.ImageAnnotatorSettings$Builder]) (require '[com.google.cloud.vision.v1p3beta1.ImageAnnotatorSettings]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductSetsFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductSetsPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductSetsPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsInProductSetFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsInProductSetPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsInProductSetPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListReferenceImagesFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListReferenceImagesPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListReferenceImagesPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchSettings$Builder]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchSettings])
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.vision/src/com/google/cloud/vision/v1p3beta1/core.clj
clojure
(ns com.google.cloud.vision.v1p3beta1.core (:refer-clojure :only [require comment defn ->]) (:import )) (require '[com.google.cloud.vision.v1p3beta1.ImageAnnotatorClient]) (require '[com.google.cloud.vision.v1p3beta1.ImageAnnotatorSettings$Builder]) (require '[com.google.cloud.vision.v1p3beta1.ImageAnnotatorSettings]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductSetsFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductSetsPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductSetsPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsInProductSetFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsInProductSetPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsInProductSetPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListProductsPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListReferenceImagesFixedSizeCollection]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListReferenceImagesPage]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient$ListReferenceImagesPagedResponse]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchClient]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchSettings$Builder]) (require '[com.google.cloud.vision.v1p3beta1.ProductSearchSettings])
83518376c5efd1a15355a5fb078b9037ade0ea067400d1a14a405dd68295a39f
appleshan/cl-http
translations.lisp
-*- Syntax : Ansi - Common - Lisp ; Base : 10 ; Mode : lisp ; Package : common - lisp - user -*- ;;; Copyright , 1994 - 1995 ;;; All rights reserved. ;;; Tried to make MAC - TRANSLATIONS.LISP more portable - OBC Copyright ( C ) 1995 , OBC for non MCL Genera ports . ;;; ;;;;;;------------------------------------------------------------------- ;;; ;;; LOGICAL PATHNAME HOST FOR HTTP ;;; (defun http-pathname (&rest dirnames) (merge-pathnames (make-pathname :directory (append '(:relative) dirnames)) *cl-http-directory*)) (defun rooted-pathname (&rest dirnames) (make-pathname :directory (append '(:absolute) dirnames '(:wild-inferiors)) :name :wild :type :wild)) (defun wildify (wild-bit logical-subdirectory &rest dirnames) (list (concatenate 'string logical-subdirectory (and logical-subdirectory ";") wild-bit ".*") (let ((http-pathname (apply 'http-pathname dirnames))) (namestring (merge-pathnames (substitute #\/ #\; (format nil "~A.~~*~~" wild-bit)) http-pathname))))) (setf (logical-pathname-translations "http") `(,(wildify "*.*" "http") ,(wildify "**;*.*" "client" "client") ,(wildify "**;*.*" "docs" "docs") ,(wildify "**;*.*" "lispm" "lispm") ,(wildify "**;*.*" "logs" "log") ,(wildify "**;*.*" "mcl" "mcl") ,(wildify "**;*.*" "pw" "log" "pw") ,(wildify "**;*.*" "server" "server") ,(wildify "**;*.*" "sources" ) ,(wildify "**;*.*" "standards" "standards") ,(wildify "**;*.*" "www" "www") ,(wildify "**;*.*" "cmucl" "cmucl") ("root;**;*.*.*" ,(rooted-pathname)) ,(wildify "**;*.*" nil)))
null
https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/scl/translations.lisp
lisp
Base : 10 ; Mode : lisp ; Package : common - lisp - user -*- All rights reserved. ------------------------------------------------------------------- LOGICAL PATHNAME HOST FOR HTTP (format nil "~A.~~*~~" wild-bit))
Copyright , 1994 - 1995 Tried to make MAC - TRANSLATIONS.LISP more portable - OBC Copyright ( C ) 1995 , OBC for non MCL Genera ports . (defun http-pathname (&rest dirnames) (merge-pathnames (make-pathname :directory (append '(:relative) dirnames)) *cl-http-directory*)) (defun rooted-pathname (&rest dirnames) (make-pathname :directory (append '(:absolute) dirnames '(:wild-inferiors)) :name :wild :type :wild)) (defun wildify (wild-bit logical-subdirectory &rest dirnames) (list (concatenate 'string logical-subdirectory (and logical-subdirectory ";") wild-bit ".*") (let ((http-pathname (apply 'http-pathname dirnames))) (namestring http-pathname))))) (setf (logical-pathname-translations "http") `(,(wildify "*.*" "http") ,(wildify "**;*.*" "client" "client") ,(wildify "**;*.*" "docs" "docs") ,(wildify "**;*.*" "lispm" "lispm") ,(wildify "**;*.*" "logs" "log") ,(wildify "**;*.*" "mcl" "mcl") ,(wildify "**;*.*" "pw" "log" "pw") ,(wildify "**;*.*" "server" "server") ,(wildify "**;*.*" "sources" ) ,(wildify "**;*.*" "standards" "standards") ,(wildify "**;*.*" "www" "www") ,(wildify "**;*.*" "cmucl" "cmucl") ("root;**;*.*.*" ,(rooted-pathname)) ,(wildify "**;*.*" nil)))
e205bf7b1229600201837bdce2d9bf67be61a9db8865db01b5e4b8a481331458
takikawa/racket-ppa
semaphore.rkt
#lang racket/base (require racket/unsafe/ops "check.rkt" "../common/queue.rkt" "internal-error.rkt" "host.rkt" "atomic.rkt" "parameter.rkt" "waiter.rkt" "evt.rkt" "pre-poll.rkt" "error.rkt") (provide make-semaphore semaphore? semaphore-post semaphore-post-all semaphore-wait semaphore-try-wait? semaphore-peek-evt semaphore-peek-evt? semaphore-any-waiters? semaphore-post/atomic semaphore-wait/atomic semaphore-post-all/atomic unsafe-semaphore-post unsafe-semaphore-wait) (struct semaphore queue ([count #:mutable]) ; -1 => non-empty queue #:authentic #:property host:prop:unsafe-authentic-override #t ; allow evt chaperone #:property prop:evt (poller (lambda (s poll-ctx) (semaphore-wait/poll s s poll-ctx)))) (define count-field-pos 2) ; used with `unsafe-struct*-cas!` (struct semaphore-peek-evt (sema) #:property prop:evt (poller (lambda (sp poll-ctx) (semaphore-wait/poll (semaphore-peek-evt-sema sp) sp poll-ctx #:peek? #t #:result sp)))) (struct semaphore-peek-select-waiter select-waiter ()) (define/who (make-semaphore [init 0]) (check who exact-nonnegative-integer? init) (unless (fixnum? init) (raise (exn:fail (error-message->string who (string-append "starting value " (number->string init) " is too large")) (current-continuation-marks)))) (semaphore #f #f init)) ;; ---------------------------------------- (define/who (semaphore-post s) (check who semaphore? s) (unsafe-semaphore-post s)) (define (unsafe-semaphore-post s) (define c (semaphore-count s)) (cond [(and (c . >= . 0) (not (current-future)) (unsafe-struct*-cas! s count-field-pos c (add1 c))) (void)] [else (atomically (semaphore-post/atomic s) (void))])) ;; In atomic mode: (define (semaphore-post/atomic s) (assert-atomic-mode) (let loop () (define w (queue-remove! s)) (cond [(not w) (set-semaphore-count! s (add1 (semaphore-count s)))] [else (waiter-resume! w s) (when (queue-empty? s) allow CAS again (when (semaphore-peek-select-waiter? w) ;; Don't consume a post for a peek waiter (loop))]))) ;; In atomic mode (define (semaphore-post-all/atomic s) (assert-atomic-mode) (set-semaphore-count! s +inf.0) (queue-remove-all! s (lambda (w) (waiter-resume! w s)))) (define (semaphore-post-all s) (atomically (semaphore-post-all/atomic s) (void))) ;; In atomic mode: (define (semaphore-any-waiters? s) (assert-atomic-mode) (not (queue-empty? s))) ;; ---------------------------------------- (define/who (semaphore-try-wait? s) (check who semaphore? s) (atomically (call-pre-poll-external-callbacks) (define c (semaphore-count s)) (cond [(positive? c) (set-semaphore-count! s (sub1 c)) #t] [else #f]))) (define/who (semaphore-wait s) (check who semaphore? s) (unsafe-semaphore-wait s)) (define (unsafe-semaphore-wait s) (define c (semaphore-count s)) (cond [(and (positive? c) (not (current-future)) (unsafe-struct*-cas! s count-field-pos c (sub1 c))) (void)] [else ((atomically (define c (semaphore-count s)) (cond [(positive? c) (set-semaphore-count! s (sub1 c)) void] [else (define w (current-thread/in-atomic)) (define n (queue-add! s w)) so CAS not tried for ` semaphore - post ` (waiter-suspend! w ;; On break/kill/suspend: (lambda () (queue-remove-node! s n) (when (queue-empty? s) allow CAS again ;; This callback is used if the thread receives a break ;; signal but doesn't escape (either because breaks are ;; disabled or the handler continues), or if the ;; interrupt was to suspend and the thread is resumed: (lambda () (unsafe-semaphore-wait s))))])))])) ;; In atomic mode (define (semaphore-wait/poll s self poll-ctx #:peek? [peek? #f] #:result [result s]) ;; Similar to `semaphore-wait, but as called by `sync`, ;; so use a select waiter instead of the current thread (assert-atomic-mode) (define c (semaphore-count s)) (cond [(positive? c) (unless peek? (set-semaphore-count! s (sub1 c))) (values (list result) #f)] [(poll-ctx-poll? poll-ctx) (values #f self)] [else (define w (if peek? (semaphore-peek-select-waiter (poll-ctx-select-proc poll-ctx)) (select-waiter (poll-ctx-select-proc poll-ctx)))) (define n (queue-add! s w)) so CAS not tried for ` semaphore - post ` ;; Replace with `async-evt`, but the `sema-waiter` can select the ;; event through a callback. Pair the event with a nack callback ;; to get back out of line. (values #f (control-state-evt async-evt (lambda (v) result) (lambda () (assert-atomic-mode) (queue-remove-node! s n) (when (queue-empty? s) allow CAS again void (lambda () ;; Retry: decrement or requeue (assert-atomic-mode) (define c (semaphore-count s)) (cond [(positive? c) (unless peek? (set-semaphore-count! s (sub1 c))) (values result #t)] [else (set! n (queue-add! s w)) so CAS not tried for ` semaphore - post ` (values #f #f)]))))])) ;; Called only when it should immediately succeed: (define (semaphore-wait/atomic s) (define c (semaphore-count s)) (cond [(positive? c) (set-semaphore-count! s (sub1 c))] [else (internal-error "semaphore-wait/atomic: cannot decrement semaphore")]))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/caff086a1cd48208815cec2a22645a3091c11d4c/src/thread/semaphore.rkt
racket
-1 => non-empty queue allow evt chaperone used with `unsafe-struct*-cas!` ---------------------------------------- In atomic mode: Don't consume a post for a peek waiter In atomic mode In atomic mode: ---------------------------------------- On break/kill/suspend: This callback is used if the thread receives a break signal but doesn't escape (either because breaks are disabled or the handler continues), or if the interrupt was to suspend and the thread is resumed: In atomic mode Similar to `semaphore-wait, but as called by `sync`, so use a select waiter instead of the current thread Replace with `async-evt`, but the `sema-waiter` can select the event through a callback. Pair the event with a nack callback to get back out of line. Retry: decrement or requeue Called only when it should immediately succeed:
#lang racket/base (require racket/unsafe/ops "check.rkt" "../common/queue.rkt" "internal-error.rkt" "host.rkt" "atomic.rkt" "parameter.rkt" "waiter.rkt" "evt.rkt" "pre-poll.rkt" "error.rkt") (provide make-semaphore semaphore? semaphore-post semaphore-post-all semaphore-wait semaphore-try-wait? semaphore-peek-evt semaphore-peek-evt? semaphore-any-waiters? semaphore-post/atomic semaphore-wait/atomic semaphore-post-all/atomic unsafe-semaphore-post unsafe-semaphore-wait) #:authentic #:property prop:evt (poller (lambda (s poll-ctx) (semaphore-wait/poll s s poll-ctx)))) (struct semaphore-peek-evt (sema) #:property prop:evt (poller (lambda (sp poll-ctx) (semaphore-wait/poll (semaphore-peek-evt-sema sp) sp poll-ctx #:peek? #t #:result sp)))) (struct semaphore-peek-select-waiter select-waiter ()) (define/who (make-semaphore [init 0]) (check who exact-nonnegative-integer? init) (unless (fixnum? init) (raise (exn:fail (error-message->string who (string-append "starting value " (number->string init) " is too large")) (current-continuation-marks)))) (semaphore #f #f init)) (define/who (semaphore-post s) (check who semaphore? s) (unsafe-semaphore-post s)) (define (unsafe-semaphore-post s) (define c (semaphore-count s)) (cond [(and (c . >= . 0) (not (current-future)) (unsafe-struct*-cas! s count-field-pos c (add1 c))) (void)] [else (atomically (semaphore-post/atomic s) (void))])) (define (semaphore-post/atomic s) (assert-atomic-mode) (let loop () (define w (queue-remove! s)) (cond [(not w) (set-semaphore-count! s (add1 (semaphore-count s)))] [else (waiter-resume! w s) (when (queue-empty? s) allow CAS again (when (semaphore-peek-select-waiter? w) (loop))]))) (define (semaphore-post-all/atomic s) (assert-atomic-mode) (set-semaphore-count! s +inf.0) (queue-remove-all! s (lambda (w) (waiter-resume! w s)))) (define (semaphore-post-all s) (atomically (semaphore-post-all/atomic s) (void))) (define (semaphore-any-waiters? s) (assert-atomic-mode) (not (queue-empty? s))) (define/who (semaphore-try-wait? s) (check who semaphore? s) (atomically (call-pre-poll-external-callbacks) (define c (semaphore-count s)) (cond [(positive? c) (set-semaphore-count! s (sub1 c)) #t] [else #f]))) (define/who (semaphore-wait s) (check who semaphore? s) (unsafe-semaphore-wait s)) (define (unsafe-semaphore-wait s) (define c (semaphore-count s)) (cond [(and (positive? c) (not (current-future)) (unsafe-struct*-cas! s count-field-pos c (sub1 c))) (void)] [else ((atomically (define c (semaphore-count s)) (cond [(positive? c) (set-semaphore-count! s (sub1 c)) void] [else (define w (current-thread/in-atomic)) (define n (queue-add! s w)) so CAS not tried for ` semaphore - post ` (waiter-suspend! w (lambda () (queue-remove-node! s n) (when (queue-empty? s) allow CAS again (lambda () (unsafe-semaphore-wait s))))])))])) (define (semaphore-wait/poll s self poll-ctx #:peek? [peek? #f] #:result [result s]) (assert-atomic-mode) (define c (semaphore-count s)) (cond [(positive? c) (unless peek? (set-semaphore-count! s (sub1 c))) (values (list result) #f)] [(poll-ctx-poll? poll-ctx) (values #f self)] [else (define w (if peek? (semaphore-peek-select-waiter (poll-ctx-select-proc poll-ctx)) (select-waiter (poll-ctx-select-proc poll-ctx)))) (define n (queue-add! s w)) so CAS not tried for ` semaphore - post ` (values #f (control-state-evt async-evt (lambda (v) result) (lambda () (assert-atomic-mode) (queue-remove-node! s n) (when (queue-empty? s) allow CAS again void (lambda () (assert-atomic-mode) (define c (semaphore-count s)) (cond [(positive? c) (unless peek? (set-semaphore-count! s (sub1 c))) (values result #t)] [else (set! n (queue-add! s w)) so CAS not tried for ` semaphore - post ` (values #f #f)]))))])) (define (semaphore-wait/atomic s) (define c (semaphore-count s)) (cond [(positive? c) (set-semaphore-count! s (sub1 c))] [else (internal-error "semaphore-wait/atomic: cannot decrement semaphore")]))
0cf95eb45e69cad19559d56e556008cc29a54a61ba0f734e561de37dadbf1efe
solita/mnt-teet
admin_commands_test.clj
(ns ^:db teet.admin.admin-commands-test (:require [clojure.test :refer :all] teet.admin.admin-commands [teet.util.datomic :as du] [teet.test.utils :as tu] [teet.user.user-db :as user-db] [datomic.client.api :as d])) (use-fixtures :each tu/with-environment (tu/with-db) tu/with-global-data) (deftest create-user (tu/give-admin-permission tu/mock-user-boss) (testing "New user can be created" (is (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE44556677880" :user/email ""}))) (testing "Proper permissions are required" (is (thrown? Exception (tu/local-command tu/mock-user-carla-consultant :admin/create-user {:user/person-id "EE44556677880" :user/email ""})))) (testing "Person id needs to be provided and valid (for some value of valid)" (is (:body (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "invalid" :user/email ""})) "Spec validation failed") (is (:body (tu/local-command tu/mock-user-boss :admin/create-user {})) "Spec validation failed")) (testing "Creating another user with the same email fails" (tu/is-thrown-with-data? {:teet/error :email-address-already-in-use} (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE55667788990" :user/email ""})))) (deftest edit-user-checks-unique-email (tu/give-admin-permission tu/mock-user-boss) (doseq [u [{:user/person-id "EE11223344556" :user/email ""} {:user/person-id "EE11223344557" :user/email ""}]] (tu/local-command tu/mock-user-boss :admin/create-user u)) (tu/is-thrown-with-data? {:teet/error :email-address-already-in-use} (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE11223344557" :user/email ""})) (is (= "" (:user/email (d/pull (tu/db) [:user/email] [:user/person-id "EE11223344557"]))) "email hasn't been changed") (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE11223344557" :user/email ""}) (is (= "" (:user/email (d/pull (tu/db) [:user/email] [:user/person-id "EE11223344557"]))) "email has been changed")) (deftest create-user-global-permissions (tu/give-admin-permission tu/mock-user-boss) (testing "New user can be granted a global role" (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE44556677880" :user/global-role :admin :user/email ""}) (let [new-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE44556677880"]) :user/permissions)] (is (= (count new-user-permissions) 1)) (is (= (-> new-user-permissions first :permission/role) :admin)))) (testing "Existing user can be granted a global role" (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE55667788990" :user/email ""}) (let [new-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE55667788990"]) :user/permissions)] (is (= (count new-user-permissions) 0))) (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE55667788990" :user/global-role :admin :user/email ""}) (let [existing-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE55667788990"]) :user/permissions)] (is (= (count existing-user-permissions) 1)) (is (= (-> existing-user-permissions first :permission/role) :admin))) ;; Can't add the same global role multiple times (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE55667788990" :user/global-role :admin}) (let [existing-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE55667788990"]) :user/permissions)] (is (= (count existing-user-permissions) 1) "Will override the previous permission") (is (= (-> existing-user-permissions first :permission/role) :admin))) ;; Can add multiple global roles (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE55667788990" :user/email "" :user/global-role :ta-consultant}) (let [existing-user-permissions (user-db/users-valid-global-permissions (tu/db) (:db/id (du/entity (tu/db) [:user/person-id "EE55667788990"]))) ] (is (= (count existing-user-permissions) 1) "Can't add multiple global roles") (is (= (->> existing-user-permissions (map :permission/role) set) #{:ta-consultant}) "The latest global role stays as the only valid role"))))
null
https://raw.githubusercontent.com/solita/mnt-teet/0e6b16acbc13d22b1a42b8ef0b174a4c88c864ee/app/backend/test/teet/admin/admin_commands_test.clj
clojure
Can't add the same global role multiple times Can add multiple global roles
(ns ^:db teet.admin.admin-commands-test (:require [clojure.test :refer :all] teet.admin.admin-commands [teet.util.datomic :as du] [teet.test.utils :as tu] [teet.user.user-db :as user-db] [datomic.client.api :as d])) (use-fixtures :each tu/with-environment (tu/with-db) tu/with-global-data) (deftest create-user (tu/give-admin-permission tu/mock-user-boss) (testing "New user can be created" (is (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE44556677880" :user/email ""}))) (testing "Proper permissions are required" (is (thrown? Exception (tu/local-command tu/mock-user-carla-consultant :admin/create-user {:user/person-id "EE44556677880" :user/email ""})))) (testing "Person id needs to be provided and valid (for some value of valid)" (is (:body (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "invalid" :user/email ""})) "Spec validation failed") (is (:body (tu/local-command tu/mock-user-boss :admin/create-user {})) "Spec validation failed")) (testing "Creating another user with the same email fails" (tu/is-thrown-with-data? {:teet/error :email-address-already-in-use} (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE55667788990" :user/email ""})))) (deftest edit-user-checks-unique-email (tu/give-admin-permission tu/mock-user-boss) (doseq [u [{:user/person-id "EE11223344556" :user/email ""} {:user/person-id "EE11223344557" :user/email ""}]] (tu/local-command tu/mock-user-boss :admin/create-user u)) (tu/is-thrown-with-data? {:teet/error :email-address-already-in-use} (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE11223344557" :user/email ""})) (is (= "" (:user/email (d/pull (tu/db) [:user/email] [:user/person-id "EE11223344557"]))) "email hasn't been changed") (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE11223344557" :user/email ""}) (is (= "" (:user/email (d/pull (tu/db) [:user/email] [:user/person-id "EE11223344557"]))) "email has been changed")) (deftest create-user-global-permissions (tu/give-admin-permission tu/mock-user-boss) (testing "New user can be granted a global role" (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE44556677880" :user/global-role :admin :user/email ""}) (let [new-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE44556677880"]) :user/permissions)] (is (= (count new-user-permissions) 1)) (is (= (-> new-user-permissions first :permission/role) :admin)))) (testing "Existing user can be granted a global role" (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE55667788990" :user/email ""}) (let [new-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE55667788990"]) :user/permissions)] (is (= (count new-user-permissions) 0))) (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE55667788990" :user/global-role :admin :user/email ""}) (let [existing-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE55667788990"]) :user/permissions)] (is (= (count existing-user-permissions) 1)) (is (= (-> existing-user-permissions first :permission/role) :admin))) (tu/local-command tu/mock-user-boss :admin/create-user {:user/person-id "EE55667788990" :user/global-role :admin}) (let [existing-user-permissions (-> (du/entity (tu/db) [:user/person-id "EE55667788990"]) :user/permissions)] (is (= (count existing-user-permissions) 1) "Will override the previous permission") (is (= (-> existing-user-permissions first :permission/role) :admin))) (tu/local-command tu/mock-user-boss :admin/edit-user {:user/person-id "EE55667788990" :user/email "" :user/global-role :ta-consultant}) (let [existing-user-permissions (user-db/users-valid-global-permissions (tu/db) (:db/id (du/entity (tu/db) [:user/person-id "EE55667788990"]))) ] (is (= (count existing-user-permissions) 1) "Can't add multiple global roles") (is (= (->> existing-user-permissions (map :permission/role) set) #{:ta-consultant}) "The latest global role stays as the only valid role"))))
da48e6d0341ae8725fe7767462c14ed5336664bf97f1d3d3398894277410143d
bluelisp/hemlock
qt.lisp
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- (in-package :hemlock.qt) (pushnew :qt hi::*available-backends*) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (named-readtables:find-readtable :hemlock.qt) (named-readtables:defreadtable :hemlock.qt (:merge :qt) (:dispatch-macro-char #\# #\k 'hemlock-ext::parse-key-fun)))) (named-readtables:in-readtable :hemlock.qt) (defun enable-syntax () (named-readtables:in-readtable :hemlock.qt) nil) (defvar *settings-organization* "Hemlock") (defvar *settings-application* "Hemlock") (defvar *font*) (defvar *modeline-font*) (defvar *tabs*) (defvar *buffers-to-tabs*) (defvar *main-stack*) (defvar *main-hunk-widget*) (defvar *executor*) (defvar *notifier*) (defun qsettings () (#_new QSettings *settings-organization* *settings-application*)) (defun save-window-geometry (window) (with-object (sx (qsettings)) (#_setValue sx "geometry" (#_new QVariant (#_saveGeometry window))))) (defcommand "Save Window Geometry" (p) "Save current window's geometry in Qt settings." "" (declare (ignore p)) (save-window-geometry (#_window (qt-hunk-widget (window-hunk (current-window)))))) (defun restore-window-geometry (window) (with-object (sx (qsettings)) (#_restoreGeometry window (#_toByteArray (#_value sx "geometry"))))) (defcommand "Restore Window Geometry" (p) "Restore the current window's geometry from Qt settings." "" (declare (ignore p)) (restore-window-geometry (#_window (qt-hunk-widget (window-hunk (current-window)))))) (defun save-font () (with-object (sx (qsettings)) (format t "setting font ~A~%" (#_toString *font*)) (#_setValue sx "main font" (#_toString *font*)))) (defun qvariant-string (x) fixme : CommonQt now string QVariants automatically , so ;; (#_toString ...) fails on those pre-unmarshalled strings. But sometimes we get a default QVariant , which CommonQt does n't unpack , ;; and we need to call (#_toString) after all. This doesn't seem ;; ideal... (if (stringp x) x (#_toString x))) (defun restore-font () (with-object (sx (qsettings)) (let ((str (qvariant-string (#_value sx "main font")))) (when (plusp (length str)) (setf *font* (let ((font (#_new QFont))) (#_fromString font str) font)))))) (defcommand "Select Font" (p) "Open a font dialog and change the current display font." "" (declare (ignore p)) (let (font) (unless (qt::with-&bool (arg nil) (setf font (#_QFontDialog::getFont arg *font*))) (editor-error "Font dialog cancelled")) (setf *font* font) (save-font))) (defparameter *gutter* 10 "The gutter to place between between the matter in a hemlock pane and its margin to improve legibility (sp?, damn i miss ispell).") (defclass qt-device (device) ((cursor-hunk :initform nil :documentation "The hunk that has the cursor." :accessor device-cursor-hunk) (cursor-item :initform nil :accessor device-cursor-item) #+nil (windows :initform nil) (main-window :initform nil :accessor device-main-window))) (defun current-device () (device-hunk-device (window-hunk (current-window)))) (defclass qt-hunk (device-hunk) ((widget :initarg :widget :reader qt-hunk-widget) (native-widget-item :initform nil :accessor hunk-native-widget-item) (item :initarg :item :accessor qt-hunk-item) (item-group :initform nil :accessor hunk-item-group) (background-items :initform nil :accessor hunk-background-items) (want-background-p :initarg :want-background-p :initform nil :accessor qt-hunk-want-background-p) (itab :initform (make-array 0 :adjustable t :initial-element nil)) (text-position :initarg :text-position :accessor device-hunk-text-position) (text-height :initarg :text-height :accessor device-hunk-text-height) (cw) (ch) (ts))) (defun line-items (hunk i) (with-slots (itab) hunk (unless (< i (length itab)) (adjust-array itab (* 2 (max 1 i)) :initial-element nil)) (elt itab i))) (defun (setf line-items) (newval hunk i) (with-slots (itab) hunk (unless (< i (length itab)) (adjust-array itab (* 2 (max 1 i)))) (setf (elt itab i) newval))) (defvar *steal-focus-out* t) (defclass hunk-widget () ((hunk :accessor widget-hunk) (centerize :initform nil :initarg :centerize :accessor centerize-widget-p) (paint-margin :initform nil :initarg :paint-margin :accessor paint-widget-margin-p) (background-pixmap :initform nil :accessor hunk-widget-background-pixmap) (background-pixmap-item :initform nil :accessor hunk-widget-background-pixmap-item) (white-item-1 :initform nil :accessor hunk-widget-rect-pixmap-item) (white-item-2 :initform nil :accessor hunk-widget-rect-pixmap-item) (height :initform 0 :accessor hunk-widget-height)) (:metaclass qt-class) (:qt-superclass "QGraphicsView") (:override ("resizeEvent" resize-event) ("keyPressEvent" key-press-event) ("focusOutEvent" focus-out-event) ("event" intercept-event) ("contextMenuEvent" context-menu-event) #+nil ("mousePressEvent" mouse-press-event) #+nil ("mouseMoveEvent" mouse-move-event) #+nil ("mouseReleaseEvent" mouse-release-event))) (defun focus-out-event (this event) (declare (ignore event)) (when *steal-focus-out* (let ((*steal-focus-out* nil)) (#_setFocus this)))) (defvar *interesting-event-received* nil "Did Qt just receive an event that matters to Hemlock? Anyone using :OVERRIDE or #_connect for code that might affect Hemlock state is required to set this variable to true. See the comment in DISPATCH-EVENTS for details.") (defun intercept-event (instance event) ;; ;; Rather than have this separately in each hunk-widget method, do ;; it centrally here: (setf *interesting-event-received* t) ;; Qt consumes key events for its own purposes . Using this event ;; interceptor, we can steal them in time. (let (casted) (cond ((and (enum= (#_type event) (#_QEvent::KeyPress)) (setf casted (make-instance 'qobject :class (qt:find-qclass "QKeyEvent") :pointer (qt::qobject-pointer event))) (eql (#_key casted) (primitive-value (#_Qt::Key_Tab)))) (key-press-event instance casted) t) (t (call-next-qmethod))))) (defmethod initialize-instance :after ((instance hunk-widget) &key) (new instance) (#_setFocusPolicy instance (#_Qt::StrongFocus)) (#_setScene instance (#_new QGraphicsScene instance)) (#_setHorizontalScrollBarPolicy instance (#_Qt::ScrollBarAlwaysOff)) (#_setVerticalScrollBarPolicy instance (#_Qt::ScrollBarAlwaysOff))) (defmethod device-init ((device qt-device)) ;; (redisplay-all) ) (defmethod device-exit ((device qt-device))) (defmacro with-timer (&body body) `(call-with-timer (lambda () ,@body))) (defun call-with-timer (fun) (let ((a (get-internal-real-time))) (multiple-value-prog1 (funcall fun) (let ((b (get-internal-real-time))) (format *trace-output* " ~D" (round(* (- b a) (/ 1000 internal-time-units-per-second)))) (force-output *trace-output*))))) (defmethod device-smart-redisplay ((device qt-device) window) (dumb-or-smart-redisplay device window nil)) (defmethod device-dumb-redisplay ((device qt-device) window) (dumb-or-smart-redisplay device window t)) (defmethod device-after-redisplay ((device qt-device)) ) (defmethod device-clear ((device qt-device)) ) (defmethod device-note-read-wait ((device qt-device) on-off) ) (defvar *processing-events-p* nil) (defun exhaustively-dispatch-events-no-hang () ;; Must dispatch all remaining events here (but not actually block). ;; Redisplay can lead to events being posted , and Hemlock 's event loop ;; is built to alternate between INTERNAL-REDISPLAY and ;; DISPATCH-EVENTS, with the expectation that only meaningful events ;; like keyboard or socket interaction will make event dispatching ;; return. So if redisplay exited with a pending event, ;; editor-input-method would degenerate into a busy loop. (assert (not *processing-events-p*)) (let ((ev (#_QAbstractEventDispatcher::instance)) (*processing-events-p* t)) (iter (while (#_processEvents ev (#_QEventLoop::AllEvents)))))) (defmethod device-force-output ((device qt-device)) (unless *processing-events-p* (exhaustively-dispatch-events-no-hang))) (defmethod device-finish-output ((device qt-device) window) ) (defmethod device-put-cursor ((device qt-device) hunk x y) (with-slots (cursor-item cursor-hunk) device (when (and cursor-item (not (eq hunk cursor-hunk))) (let ((*steal-focus-out* nil)) (#_removeItem (#_scene cursor-item) cursor-item)) (setf cursor-item nil)) (setf cursor-hunk hunk) (with-slots (cw ch) hunk (unless cursor-item (setf cursor-item (with-objects ((path (#_new QPainterPath)) (pen (#_new QPen (#_Qt::NoPen))) (color (#_new QColor 0 180 180 64)) (brush (#_new QBrush color))) (#_addRect path 0 0 cw ch) (let* ((scene (#_scene (qt-hunk-widget hunk))) (group (ensure-hunk-item-group scene hunk)) (item (#_new QGraphicsPathItem path group))) (qt::cancel-finalization item) (#_setPen item pen) (#_setBrush item brush) item)))) (#_setPos cursor-item (* x cw) (* y ch))) (#_setZValue cursor-item 3))) (defmethod device-show-mark ((device qt-device) window x y time) ) Windows (defmethod device-next-window ((device qt-device) window) (device-hunk-window (device-hunk-next (window-hunk window)))) (defmethod device-previous-window ((device qt-device) window) (device-hunk-window (device-hunk-previous (window-hunk window)))) (defvar *currently-selected-hunk* nil) (defmethod device-delete-window ((device qt-device) window) (let* ((hunk (window-hunk window)) (prev (device-hunk-previous hunk)) (next (device-hunk-next hunk)) (device (device-hunk-device hunk)) (group (hunk-item-group hunk))) (when group (when (eq hunk (device-cursor-hunk device)) (setf (device-cursor-item device) nil)) (setf (hunk-native-widget-item hunk) nil) (with-slots (itab) hunk (fill itab nil)) (#_delete group)) (setf (device-hunk-next prev) next) (setf (device-hunk-previous next) prev) (let ((buffer (window-buffer window))) (setf (buffer-windows buffer) (delete window (buffer-windows buffer)))) (let ((new-lines (device-hunk-height hunk))) (declare (fixnum new-lines)) (cond ((eq hunk (device-hunks (device-hunk-device next))) (incf (device-hunk-height next) new-lines) (incf (device-hunk-text-height next) new-lines) (let ((w (device-hunk-window next))) (hi::change-window-image-height w (+ new-lines (window-height w))))) (t (incf (device-hunk-height prev) new-lines) (incf (device-hunk-position prev) new-lines) (incf (device-hunk-text-height prev) new-lines) (incf (device-hunk-text-position prev) new-lines) (let ((w (device-hunk-window prev))) (hi::change-window-image-height w (+ new-lines (window-height w))))))) (when (eq hunk (device-hunks device)) (setf (device-hunks device) next))) (setf *currently-selected-hunk* nil) (setf hi::*screen-image-trashed* t)) (defmethod device-make-window ((device qt-device) start modelinep window font-family ask-user x y width height proportion) (declare (ignore window font-family ask-user x y width height)) (let* ((old-window (current-window)) (victim (window-hunk old-window)) (text-height (device-hunk-text-height victim)) (availability (if modelinep (1- text-height) text-height))) (when (> availability 1) (let* ((new-lines (truncate (* availability proportion))) (old-lines (- availability new-lines)) (pos (device-hunk-position victim)) (new-height (if modelinep (1+ new-lines) new-lines)) (new-text-pos (if modelinep (1- pos) pos)) (widget (qt-hunk-widget (window-hunk *current-window*))) (new-hunk (make-instance 'qt-hunk :position pos :height new-height :text-position new-text-pos :text-height new-lines :device device :widget widget)) (new-window (internal-make-window :hunk new-hunk))) (with-object (metrics (#_new QFontMetrics *font*)) (setf (slot-value new-hunk 'cw) (+ 0 (#_width metrics "m")) (slot-value new-hunk 'ch) (+ 2 (#_height metrics)))) (setf (device-hunk-window new-hunk) new-window) (let* ((old-text-pos-diff (- pos (device-hunk-text-position victim))) (old-win-new-pos (- pos new-height))) (declare (fixnum old-text-pos-diff old-win-new-pos)) (setf (device-hunk-height victim) (- (device-hunk-height victim) new-height)) (setf (device-hunk-text-height victim) old-lines) (setf (device-hunk-position victim) old-win-new-pos) (setf (device-hunk-text-position victim) (- old-win-new-pos old-text-pos-diff))) (hi::setup-window-image start new-window new-lines (window-width old-window)) (prepare-window-for-redisplay new-window) (when modelinep (setup-modeline-image (line-buffer (mark-line start)) new-window)) (hi::change-window-image-height old-window old-lines) (shiftf (device-hunk-previous new-hunk) (device-hunk-previous (device-hunk-next victim)) new-hunk) (shiftf (device-hunk-next new-hunk) (device-hunk-next victim) new-hunk) (setf *currently-selected-hunk* nil) (setf hi::*screen-image-trashed* t) new-window)))) (defmethod resize-event ((widget hunk-widget) resize-event) (call-next-qmethod) #+nil (#_setMaximumWidth *tabs* (#_width wrapper)) (update-full-screen-items widget) (hi::enlarge-device (current-device) (recompute-hunk-widget-height widget)) (hi::internal-redisplay)) (defvar *standard-column-width* 80) (defun standard-width-in-pixels () (with-object (metrics (#_new QFontMetrics *font*)) (+ (* *standard-column-width* (#_width metrics "m")) ;; leave space for the gutter on the left side ;; (but not the right side, so that the column width is cut off cleanly) *gutter*))) (defun offset-on-each-side (widget) (if (centerize-widget-p widget) (let ((white-width (standard-width-in-pixels)) (full-width (#_width widget))) (max 0.0d0 (/ (- full-width white-width) 2.0d0))) 0.0d0)) (defmethod device-beep ((device qt-device) stream) ) (defclass qt-editor-input (editor-input) ()) (defvar *alt-is-meta* t) (defvar *qt-initialized-p* nil) (defmethod context-menu-event ((instance hunk-widget) event) ;; (call-next-qmethod) (let ((menu (#_new QMenu))) (add-menus menu) (#_exec menu (#_globalPos event)))) (defmethod key-press-event ((instance hunk-widget) event) ;; (call-next-qmethod) (hi::q-event *editor-input* (qevent-to-key-event event))) (defun parse-modifiers (event) (let ((mods (#_modifiers event))) (logior (if (logtest mods (qt::primitive-value (#_Qt::ControlModifier))) (hemlock-ext:key-event-bits #k"control-a") 0) (if (or (logtest mods (qt::primitive-value (#_Qt::MetaModifier))) (and *alt-is-meta* (logtest mods (qt::primitive-value (#_Qt::AltModifier))))) (hemlock-ext:key-event-bits #k"meta-a") 0)))) (defun parse-key (event) (let ((k (#_key event))) (cond ((or (eql k (primitive-value (#_Qt::Key_Return))) (eql k (primitive-value (#_Qt::Key_Enter)))) (hemlock-ext:key-event-keysym #k"Return")) ((eql k (primitive-value (#_Qt::Key_Tab))) (hemlock-ext:key-event-keysym #k"tab")) ((eql k (primitive-value (#_Qt::Key_Escape))) (hemlock-ext:key-event-keysym #k"Escape")) ((eql k (primitive-value (#_Qt::Key_Backspace))) (hemlock-ext:key-event-keysym #k"Backspace")) ((eql k (primitive-value (#_Qt::Key_Delete))) (hemlock-ext:key-event-keysym #k"delete")) ((eql k (primitive-value (#_Qt::Key_Space))) (hemlock-ext:key-event-keysym #k"space")) (t nil)))) (defun qevent-to-key-event (event) (let* ((text (map 'string (lambda (c) (if (< (char-code c) 32) (code-char (+ 96 (char-code c))) c)) (#_text event))) (mask (parse-modifiers event)) (keysym (or (parse-key event) (hemlock-ext::name-keysym text)))) (when keysym (hemlock-ext:make-key-event keysym mask)))) (defmethod get-key-event ((stream qt-editor-input) &optional ignore-abort-attempts-p) (hi::%editor-input-method stream ignore-abort-attempts-p)) (defun in-main-qthread-p () (and hi::*in-the-editor* (typep (current-device) 'qt-device))) (defmethod hi::dispatch-events-with-backend ((backend (eql :qt))) ;; The whole *INTERESTING-EVENT-RECEIVED* business is here to prevent ;; calling into INTERNAL-REDISPLAY too often (which is particularly ;; bad because even no-op redisplay is currently expensive enough to ;; be noticable, but would seem suboptimal in any case). ;; ;; #_processEvents as called here is already a blocking call, but apparently has a timeout event somewhere that is set to two ;; seconds. As a result, the redisplay loop would call us to block, only to enter INTERNAL - REDISPLAY again after 2s , even though no ;; events have been received that are relevant to redisplay. ;; ;; The workaround is to simply go back into Qt until a signal or ;; method has indicated that we did something which might have affected Hemlock state . ;; ;; On my machine, this makes the difference between hemlock.qt always showing up with 1 % CPU usage in top , and not showing up . ;; ;; Note that processEvents has flags to inhibit processing of certain ;; events, which end up matching our relevancy test (user input and ;; socket stuff), but they are only useful in the opposite situation ;; of not wanting to block, and briefly wanting to ignore those kinds ;; of events. (assert (not *processing-events-p*)) (setf *interesting-event-received* nil) (let ((*processing-events-p* t)) (iter (until *interesting-event-received*) (#_processEvents (#_QAbstractEventDispatcher::instance) (#_QEventLoop::WaitForMoreEvents))))) (defmethod hi::dispatch-events-no-hang-with-backend ((backend (eql :qt))) (assert (not *processing-events-p*)) (let ((*processing-events-p* t)) (#_processEvents (#_QAbstractEventDispatcher::instance) (#_QEventLoop::AllEvents)))) (defmethod unget-key-event (key-event (stream qt-editor-input)) (hi::un-event key-event stream)) (defmethod clear-editor-input ((stream qt-editor-input)) ;; hmm? ) (defmethod listen-editor-input ((stream qt-editor-input)) (hi::input-event-next (hi::editor-input-head stream))) (defun make-hemlock-widget () (let* ((vbox (#_new QVBoxLayout)) (tabs (#_new QTabBar)) (main (make-instance 'hunk-widget :centerize t :paint-margin t)) (font (let ((font (#_new QFont))) (#_fromString font *font-family*) (#_setPointSize font *font-size*) font)) (*font* font) (font (progn (restore-font) *font*)) (*modeline-font* (let ((font (#_new QFont))) (#_fromString font *modeline-font-family*) (#_setPointSize font (#_pointSize *font*)) font))) (#_addWidget vbox tabs) (#_hide tabs) (let ((main-stack (#_new QStackedWidget))) (setf *main-stack* main-stack) (setf *main-hunk-widget* main) (#_addWidget vbox main-stack) (#_addWidget main-stack main)) (#_setFocusPolicy tabs (#_Qt::NoFocus)) (#_setSpacing vbox 0) (#_setMargin vbox 0) (let ((central-widget (#_new QWidget))) (#_setLayout central-widget vbox) (values main font *modeline-font* central-widget tabs)))) (defun add-buffer-tab-hook (buffer) (when (in-main-qthread-p) (#_addTab *tabs* (buffer-name buffer)))) (defun buffer-tab-index (buffer) (dotimes (i (#_count *tabs*)) (when (equal (#_tabText *tabs* i) (buffer-name buffer)) (return i)))) (defun delete-buffer-tab-hook (buffer) (when (in-main-qthread-p) (let ((idx (buffer-tab-index buffer))) (if idx (#_removeTab *tabs* idx) (warn "buffer tab missing"))))) (defun update-buffer-tab-hook (buffer new-name) (when (in-main-qthread-p) (let ((idx (buffer-tab-index buffer))) (if idx (#_setTabText *tabs* idx new-name) (warn "buffer tab missing"))))) (defun set-buffer-tab-hook (buffer) (when (in-main-qthread-p) (let ((idx (buffer-tab-index buffer))) (if idx (#_setCurrentIndex *tabs* idx) (warn "buffer tab missing"))))) (defun set-stack-widget-hook (buffer) (when (in-main-qthread-p) (#_setCurrentWidget *main-stack* *main-hunk-widget*))) (add-hook hemlock::make-buffer-hook 'add-buffer-tab-hook) (add-hook hemlock::delete-buffer-hook 'delete-buffer-tab-hook) (add-hook hemlock::buffer-name-hook 'update-buffer-tab-hook) (add-hook hemlock::set-buffer-hook 'set-buffer-tab-hook) (add-hook hemlock::set-buffer-hook 'set-stack-widget-hook) (defun splitter-sizes (splitter) (qt::qlist-to-list (#_sizes splitter))) (defun (setf splitter-sizes) (newval splitter) (#_setSizes splitter (qt::qlist-append (qt::make-qlist<int>) newval)) newval) (defun resize-echo-area (nlines backgroundp) (setf (device-hunk-height (window-hunk *echo-area-window*)) nlines) (setf (device-hunk-text-height (window-hunk *echo-area-window*)) nlines) (hi::change-window-image-height *echo-area-window* nlines) (setf (qt-hunk-want-background-p (window-hunk *echo-area-window*)) backgroundp) (redisplay-all) #+nil (let* ((widget (or widget (qt-hunk-widget (window-hunk *echo-area-window*)))) (splitter (#_centralWidget (#_window widget))) (new-height (with-object (metrics (#_new QFontMetrics *font*)) (+ (* 2 *gutter*) (* nlines (#_height metrics)))))) (#_setMinimumHeight widget 1) (destructuring-bind (top bottom) (splitter-sizes splitter) (let ((diff (- new-height bottom))) (setf (splitter-sizes splitter) (list (- top diff) new-height)))))) (defun minimize-echo-area () (resize-echo-area 1 nil)) (defun enlarge-echo-area () (resize-echo-area 5 t)) (defun set-window-hook (new-window) (when (in-main-qthread-p) (cond ((eq new-window *echo-area-window*) (enlarge-echo-area)) ((eq *current-window* *echo-area-window*) (minimize-echo-area))))) (add-hook hemlock::set-window-hook 'set-window-hook) (defun signal-receiver (function) (make-instance 'signal-receiver :function (lambda (&rest args) (setf *interesting-event-received* t) (apply function args)))) (defun connect (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke()")))) (defun connect/int (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke(int)")))) (defun connect/string (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke(const QString&)")))) (defun connect/boolean (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke(bool)")))) (defclass signal-receiver () ((function :initarg :function :accessor signal-receiver-function)) (:metaclass qt-class) (:qt-superclass "QObject") (:slots ("invoke()" (lambda (this &rest args) (apply (signal-receiver-function this) args))) ("invoke(int)" (lambda (this &rest args) (apply (signal-receiver-function this) args))) ("invoke(const QString&)" (lambda (this &rest args) (apply (signal-receiver-function this) args))) ("invoke(bool)" (lambda (this &rest args) (apply (signal-receiver-function this) args))))) (defmethod initialize-instance :after ((instance signal-receiver) &key) (new instance)) (defclass command-action-receiver () ((command :initarg :command :accessor command-action-receiver-command)) (:metaclass qt-class) (:qt-superclass "QWidget") (:slots ("triggered()" (lambda (this) (funcall (command-function (command-action-receiver-command this)) nil) (hi::internal-redisplay))))) (defmethod initialize-instance :after ((instance command-action-receiver) &key) (new instance)) (defvar *do-not-gc-list*) (defun add-command-action (menu command &optional suffix) (let* ((receiver (make-instance 'command-action-receiver :command (getstring command hi::*command-names*))) (action (#_addAction menu (concatenate 'string command suffix) receiver (qslot "triggered()")))) (push action *do-not-gc-list*) (push receiver *do-not-gc-list*))) #+(or) (defun control-g-handler (&rest *) (let ((widget *echo-hunk-widget*)) (cond ((#_hasFocus widget) (hi::q-event *editor-input* #k"control-g")) (t (setf *steal-focus-out* t) (#_setFocus *echo-hunk-widget*) (clear-echo-area) (message "Focus restored. Welcome back to Hemlock."))))) (defun control-g-handler (&rest *) (setf *steal-focus-out* t) (#_setFocus *main-hunk-widget*) (clear-echo-area) (hi::q-event *editor-input* #k"control-g")) (defvar *invoke-later-thunks*) (defvar *invoke-later-timer*) (defmethod hi::invoke-later ((backend (eql :qt)) fun) (push fun *invoke-later-thunks*) (#_setSingleShot *invoke-later-timer* t) (#_start *invoke-later-timer*)) (defun process-invoke-later-thunks () (iter (while *invoke-later-thunks*) (funcall (pop *invoke-later-thunks*)))) (defmethod hi::backend-init-raw-io ((backend (eql :qt)) display) (declare (ignore display)) (setf hi::*editor-input* (make-instance 'qt-editor-input))) (defun add-menus (parent) (let ((menu (#_addMenu parent "File"))) (add-command-action menu "Find File") (add-command-action menu "Save File") (#_addSeparator menu) (add-command-action menu "Write File") (#_addSeparator menu) (add-command-action menu "Save All Files and Exit")) (let ((menu (#_addMenu parent "View"))) (add-command-action menu "Toggle Menu Bar") (add-command-action menu "Toggle Tab Bar") (add-command-action menu "Toggle Full Screen")) (let ((menu (#_addMenu parent "Lisp"))) (add-command-action menu "Start Slave Thread") (add-command-action menu "Start Slave Process") (add-command-action menu "List Slaves")) (let ((menu (#_addMenu parent "Buffer"))) (add-command-action menu "Bufed")) (let ((menu (#_addMenu parent "Browser"))) (add-command-action menu "Browse") (add-command-action menu "Browse Qt Class") (add-command-action menu "CLHS") (add-command-action menu "Google") (#_addSeparator menu) (add-command-action menu "Enter Foreign Widget") (add-command-action menu "Leave Foreign Widget")) (let ((menu (#_addMenu parent "Preferences"))) (add-command-action menu "Select Font") (#_addSeparator menu) (add-command-action menu "Save Window Geometry") (add-command-action menu "Restore Window Geometry"))) (defmethod hi::%init-screen-manager ((backend-type (eql :qt)) (display t)) (declare (ignore display)) (let (main central-widget) (setf (values main *font* *modeline-font* central-widget *tabs*) (make-hemlock-widget)) (let* ((device (make-instance 'qt-device)) (window (#_new QMainWindow))) (setf (device-name device) "Qt" (device-bottom-window-base device) nil) keep the QMainWindow from being GCed : (setf (device-main-window device) window) (#_setWindowTitle window "Hemlock") (#_setCentralWidget window central-widget) (add-menus (#_menuBar window)) (#_hide (#_menuBar window)) (setf hi::*real-editor-input* *editor-input*) (set-up-qt-hunks device main) (dolist (buffer hi::*buffer-list*) (unless (eq buffer *echo-area-buffer*) (add-buffer-tab-hook buffer))) (connect/int *tabs* (qsignal "currentChanged(int)") (lambda (index) (change-to-buffer (hemlock-ext::find-buffer (#_tabText *tabs* index))))) (with-object (key (#_new QKeySequence "Ctrl+G")) (connect (#_new QShortcut key (#_window *main-hunk-widget*)) (QSIGNAL "activated()") 'control-g-handler)) #+nil (#_setMinimumHeight echo (with-object (metrics (#_new QFontMetrics *font*)) (+ (* 2 *gutter*) (#_height metrics)))) (restore-window-geometry window) (#_show window) ;; (minimize-echo-area echo) ;; undo the minimum set before, so that it's only a default ;; (fixme: it still overrides a saved geometry): #+nil (#_setMinimumSize widget 0 0) (setf *notifier* (make-instance 'qt-repl::repl-notifier)) (setf *executor* (make-instance 'qt-repl::repl-executer :notifier *notifier*))))) (defmethod hi::make-event-loop ((backend (eql :qt))) 'qt-event-loop) (defmethod hi::invoke-with-existing-event-loop ((backend (eql :qt)) loop fun) (assert (eq loop 'qt-event-loop)) (hi::invoke-with-new-event-loop backend fun)) (defmethod hi::invoke-with-new-event-loop ((backend (eql :qt)) fun &aux keep) (unless *qt-initialized-p* HACK ! Disable SBCL 's SIGCHLD handler . I do n't know what exactly it is doing wrong , but if SBCL sets a signal handler for this , it ;; leads to segfaults whenever a process started by Qt exits. ;; ;; It doesn't matter what the handler would do; a no-op lambda ;; already has this effect. ;; ;; [Perhaps it's due to the way Qt tries to chain call our handler, or perhaps we are interrupting FFI code , or is it an altstack thing ? ;; I have no idea.] #+sbcl (sb-kernel::default-interrupt sb-unix:sigchld) (format t "Loading shared libraries [") (let ((first t)) (dolist (module '(:qtcore :qtgui :qtnetwork :qtsvg :qtwebkit)) (if first (setf first nil) (write-string ", ")) (format t "~A" (string-downcase module)) (force-output) (ensure-smoke module))) (format t "].~%Connecting to window system...") (force-output) (push (make-qapplication) keep) (format t "done.~%") (force-output) (setf *qt-initialized-p* t)) ;; When in a slave, we need to create a QEventLoop here, otherwise we will later . Let 's just do it unconditionally : (push (#_new QEventLoop) keep) (let* ((*do-not-gc-list* '()) (*invoke-later-thunks* '()) (*invoke-later-timer* (#_new QTimer)) (*interesting-event-received* nil)) (connect *invoke-later-timer* (QSIGNAL "timeout()") #'process-invoke-later-thunks) #-sbcl (funcall fun) #+sbcl (sb-int:with-float-traps-masked (:overflow :invalid :divide-by-zero) (funcall fun)))) Keysym translations (defun qt-character-keysym (gesture) (cond # # # hmm (hemlock-ext:key-event-keysym #k"Return")) # # # hmm (hemlock-ext:key-event-keysym #k"Tab")) ((eql gesture #\Backspace) (hemlock-ext:key-event-keysym #k"Backspace")) ((eql gesture #\Escape) (hemlock-ext:key-event-keysym #k"Escape")) ((eql gesture #\rubout) (hemlock-ext:key-event-keysym #k"delete")) (t (char-code gesture)))) ;;;; (defun effective-hunk-widget-width (widget) (- (#_width widget) (offset-on-each-side widget))) (defun probe-namestring (x) (when (and x (probe-file x)) (etypecase x (string x) (pathname (namestring x))))) (defun find-background-svg () (etypecase hemlock:*background-image* ((or string pathname) (or (probe-namestring hemlock:*background-image*) (progn (format t "Specified background image not found: ~A~%" hemlock:*background-image*) nil))) ((eql :auto) (or (probe-namestring (merge-pathnames ".hemlock/background.svg" (user-homedir-pathname))) (probe-namestring (merge-pathnames "background.svg" (hi::installation-directory))))) (null))) (defun update-full-screen-items (widget) (when t ;;(qt-hunk-want-background-p hunk) (with-slots (background-pixmap background-pixmap-item) widget (setf background-pixmap (let ((file (find-background-svg))) (if file (let ((pixmap (#_new QPixmap (#_width widget) (#_height widget)))) (with-objects ((renderer (#_new QSvgRenderer file)) (painter (#_new QPainter pixmap))) (#_render renderer painter) (#_end painter) pixmap)) nil))) (when background-pixmap-item (#_removeItem (#_scene background-pixmap-item) background-pixmap-item) (setf background-pixmap-item nil)) (when background-pixmap (setf background-pixmap-item (#_addPixmap (#_scene widget) background-pixmap)) (#_setZValue background-pixmap-item -2) #+nil (#_setBackgroundBrush (#_scene widget) (#_new QBrush background-pixmap))))) (with-slots (white-item-1 white-item-2) widget (when white-item-1 (#_removeItem (#_scene white-item-1) white-item-1) (setf white-item-1 nil)) (when white-item-2 (#_removeItem (#_scene white-item-2) white-item-2) (setf white-item-2 nil)) (let ((offset (truncate (offset-on-each-side widget)))) (with-object (~) (setf white-item-1 (#_addRect (#_scene widget) (#_new QRectF offset 0 (- (#_width widget) (* 2 offset)) (#_height widget)) (~ (#_new QPen (#_Qt::NoPen))) (~ (#_new QBrush (~ (#_new QBrush (~ (#_new QColor 255 255 255 210))))))))) (with-object (~) (setf white-item-2 (#_addRect (#_scene widget) (~ (#_new QRectF (- (#_width widget) offset) 0 offset (#_height widget))) (~ (#_new QPen (#_Qt::NoPen))) (~ (#_new QBrush (~ (#_new QBrush (~ (#_new QColor 255 255 255 180)))))))))) (#_setZValue white-item-1 -1) (#_setZValue white-item-2 -1))) (defun old-resize-junk () #+nil (let ((window (device-hunk-window hunk))) ;; ;; Nuke all the lines in the window image. (unless (eq (cdr (window-first-line window)) the-sentinel) (shiftf (cdr (window-last-line window)) (window-spare-lines window) (cdr (window-first-line window)) the-sentinel)) # # # ( setf ( bitmap - hunk - start hunk ) ( cdr ( window - first - line window ) ) ) ;; ;; Add some new spare lines if needed. If width is greater, ;; reallocate the dis-line-chars. (let* ((res (window-spare-lines window)) (new-width (max 5 (floor (- (effective-hunk-widget-width (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'cw)))) (new-height (max 2 (1- (floor (- (#_height (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'ch))))) (width (length (the simple-string (dis-line-chars (car res)))))) (declare (list res)) (when (> new-width width) (setq width new-width) (dolist (dl res) (setf (dis-line-chars dl) (make-string new-width)))) (setf (window-height window) new-height (window-width window) new-width) (do ((i (- (* new-height 2) (length res)) (1- i))) ((minusp i)) (push (make-window-dis-line (make-string width)) res)) (setf (window-spare-lines window) res) ;; Force modeline update . (let ((ml-buffer (window-modeline-buffer window))) (when ml-buffer (let ((dl (window-modeline-dis-line window)) (chars (make-string new-width)) (len (min new-width (window-modeline-buffer-len window)))) (setf (dis-line-old-chars dl) nil) (setf (dis-line-chars dl) chars) (replace chars ml-buffer :end1 len :end2 len) (setf (dis-line-length dl) len) (setf (dis-line-flags dl) changed-bit))))) ;; ;; Prepare for redisplay. (setf (window-tick window) (tick)) (update-window-image window) (when (eq window *current-window*) (maybe-recenter-window window)) hunk)) (defmethod hi::device-enlarge-window ((device qt-device) window offset) (let* ((hunk (window-hunk window)) (victim (cond ((eq hunk (device-hunks (device-hunk-device hunk))) we 're the first hunk (let ((victim (device-hunk-next hunk))) (when (eq hunk victim) ... the first and only hunk (editor-error "Cannot enlarge only window")) ;; move the victim down (incf (device-hunk-position hunk) offset) (incf (device-hunk-text-position hunk) offset) victim)) (t we 're not first hunk , so there is a victim in front of us ;; move us up (let ((victim (device-hunk-previous hunk))) (decf (device-hunk-position victim) offset) (decf (device-hunk-text-position victim) offset) victim))))) ;; bump up our height (incf (device-hunk-height hunk) offset) (incf (device-hunk-text-height hunk) offset) ;; make the victim smaller (decf (device-hunk-height victim) offset) (decf (device-hunk-text-height victim) offset) ;; housekeeping (let ((w (device-hunk-window victim))) (hi::change-window-image-height w (- offset (window-height w)))) (let ((w (device-hunk-window hunk))) (hi::change-window-image-height w (+ offset (window-height w)))) (setf hi::*screen-image-trashed* t))) (defmethod hi::enlarge-device ((device qt-device) offset) #+nil (hi::set-up-screen-image device) (let ((first (device-hunks device))) (incf (device-hunk-position first) offset) (incf (device-hunk-text-position first) offset) (incf (device-hunk-height first) offset) (incf (device-hunk-text-height first) offset) (let ((w (device-hunk-window first))) (hi::change-window-image-height w (+ offset (window-height w)))) (do ((hunk (device-hunk-next first) (device-hunk-next hunk))) ((eq hunk first)) (incf (device-hunk-position hunk) offset) (incf (device-hunk-text-position hunk) offset)) (let ((hunk (window-hunk *echo-area-window*))) (incf (device-hunk-position hunk) offset) (incf (device-hunk-text-position hunk) offset)) (setf hi::*screen-image-trashed* t))) (defun recompute-hunk-widget-height (widget) (let ((new (with-object (metrics (#_new QFontMetrics *font*)) (max 2 (floor (- (#_height widget) (* 2 *gutter*)) (+ 2 (#_height metrics)))))) (old (hunk-widget-height widget))) (setf (hunk-widget-height widget) new) (- new old))) (defun set-up-qt-hunks (device main-widget) (progn ;;with-object (metrics (#_new QFontMetrics *font*)) (let* ((buffer *current-buffer*) (start (buffer-start-mark buffer)) (first (cons dummy-line the-sentinel)) #+nil (width (max 5 (floor (- (#_width (qt-hunk-widget hunk)) (* 2 *gutter*)) (+ 0 (#_width metrics "m"))))) (height (recompute-hunk-widget-height main-widget)) (echo-height #+nil (value hemlock::echo-area-height) 1) (main-lines (- height echo-height 1)) ;-1 for echo modeline. (main-text-lines (1- main-lines)) ;also main-modeline-pos ) (declare (ignorable start first)) (setf (buffer-windows buffer) nil (buffer-windows *echo-area-buffer*) nil) (let* ((window (hi::internal-make-window)) (last-text-line (1- main-text-lines)) (hunk (make-instance 'qt-hunk :position main-lines ;main-text-lines :height main-lines :text-position last-text-line :text-height main-text-lines :widget main-widget))) (redraw-widget device window hunk buffer t) (setf *current-window* window) #+nil (push window (slot-value device 'windows)) (setf (device-hunk-previous hunk) hunk) (setf (device-hunk-next hunk) hunk) (setf (device-hunks device) hunk)) (let ((echo-window (hi::internal-make-window)) (echo-hunk (make-instance 'qt-hunk :position (1- height) :height echo-height :text-position (- height 2) :text-height echo-height :widget main-widget))) (redraw-widget device echo-window echo-hunk *echo-area-buffer* nil) (setf *echo-area-window* echo-window))))) (defvar *font-family* "Fixed [Misc]" #+nil "Courier New") (defvar *modeline-font-family* "Sans") (defvar *font-size* 10) (defun redraw-widget (device window hunk buffer modelinep) (setf (slot-value (qt-hunk-widget hunk) 'hunk) hunk) (let* ((start (buffer-start-mark buffer)) (first (cons dummy-line the-sentinel)) (font *font*) width height) (with-object (metrics (#_new QFontMetrics font)) (setf (slot-value hunk 'cw) (+ 0 (#_width metrics "m")) (slot-value hunk 'ch) (+ 2 (#_height metrics)) width (max 5 (floor (- (#_width (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'cw))) height (max 2 (floor (- (#_height (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'ch))) (device-hunk-window hunk) window ;; (device-hunk-position hunk) 0 ;; (device-hunk-height hunk) height (device-hunk-next hunk) nil (device-hunk-previous hunk) nil (device-hunk-device hunk) device (window-tick window) -1 ; The last time this window was updated. (window-%buffer window) buffer ; buffer displayed in this window. (window-height window) (device-hunk-height hunk) ; Height of window in lines. (window-width window) width ; Width of the window in characters. The charpos of the first char displayed . (window-first-line window) first ; The head of the list of dis-lines. (window-last-line window) the-sentinel ; The last dis-line displayed. The first changed dis - line on last update . (window-last-changed window) first ; The last changed dis-line. (window-spare-lines window) nil ; The head of the list of unused dis-lines (window-hunk window) hunk ; The device hunk that displays this window. (window-display-start window) (copy-mark start :right-inserting) ; first character position displayed (window-display-end window) (copy-mark start :right-inserting) ; last character displayed (window-point window) (copy-mark (buffer-point buffer)) ; Where the cursor is in this window. (window-modeline-dis-line window) nil ; Dis-line for modeline display. (window-modeline-buffer window) nil ; Complete string of all modeline data. (window-modeline-buffer-len window) nil ; Valid chars in modeline-buffer. (window-display-recentering window) nil ; ) (setup-dis-lines window width height) (when modelinep (setup-modeline-image buffer window)) (push window (buffer-windows buffer)) (push window *window-list*) (hi::update-window-image window)))) (defun setup-dis-lines (window width height) (do ((i (- height) (1+ i)) (res () (cons (make-window-dis-line (make-string width)) res))) ((= i height) (setf (window-spare-lines window) res)))) ;;;; Redisplay (defvar *tick* 0) ;;; (defun dis-line-rect (hunk dl) ;;; (let* ((h (slot-value hunk 'ch)) ;;; (w (slot-value hunk 'cw)) ;;; (xo *gutter*) ;;; (yo *gutter*) ( ( dis - line - chars dl ) ) ( start 0 ) ; ... ;;; (end (dis-line-length dl)) ;... ;;; (x1 (+ xo (* w start))) ;;; (y1 (+ 1 yo (* (dis-line-position dl) h))) ;;; (m (#_new QFontMetrics *font*)) ( ww ( # _ width m ( subseq chrs start end ) ) ) ;;; (hh (#_ascent m))) ( # _ new QRect x1 y1 ww ( * 2 hh ) ) ) ) #+(or) (defun dis-line-rect (hunk dl) (nth-line-rect hunk (dis-line-position dl))) #+(or) (defun nth-line-rect (hunk i) (let* ((x *gutter*) (y (+ *gutter* (* i (slot-value hunk 'ch)))) (w (- (#_width (qt-hunk-widget hunk)) (ceiling (offset-on-each-side (qt-hunk-widget hunk))))) (h (slot-value hunk 'ch))) (#_new QRect x y w h))) #+(or) (defun cursor-rect (hunk x y) (with-slots (cw ch) hunk (when (and x y cw ch) (#_new QRect (+ *gutter* (* x cw)) (+ *gutter* (* y ch)) (1+ cw) (1+ ch))))) (defun clear-line-items (scene hunk position) (declare (ignore scene)) (dolist (old-item (line-items hunk position)) (#_delete old-item)) (setf (line-items hunk position) nil)) (defun update-modeline-items (scene hunk dl) (let* ((position (+ (dis-line-position dl) ;; fixme? (device-hunk-text-height hunk))) (h (slot-value hunk 'ch)) #+nil (w (slot-value hunk 'cw)) (widget (qt-hunk-widget hunk)) (offset (truncate (offset-on-each-side widget))) (chrs (dis-line-chars dl)) (y (* position h))) (unless (zerop (dis-line-flags dl)) (setf (hi::dis-line-tick dl) (incf *tick*))) (clear-line-items scene hunk position) (with-objects ((pen (#_new QPen (#_Qt::NoPen))) (color (#_new QColor 255 255 255 210)) (oops (#_new QBrush color)) (brush (#_new QBrush oops)) (rect (#_new QRectF (- (+ offset *gutter*)) y (#_width widget) h))) (let ((item (#_new QGraphicsRectItem rect (ensure-hunk-item-group scene hunk)))) (qt::cancel-finalization item) (#_setPen item pen) (#_setBrush item brush) (#_setZValue item 0) (push item (line-items hunk position)))) (let ((len (dis-line-length dl))) (push (add-chunk-item scene hunk chrs 0 (+ 1 y) 0 len 0 *modeline-font*) (line-items hunk position)))) (setf (dis-line-flags dl) unaltered-bits (dis-line-delta dl) 0)) (defun update-line-items (scene hunk dl) (let* ((position (dis-line-position dl)) (h (slot-value hunk 'ch)) (w (slot-value hunk 'cw)) ;; (widget (qt-hunk-widget hunk)) ;; (offset (truncate (offset-on-each-side widget))) (chrs (dis-line-chars dl)) (y (* position h))) (unless (zerop (dis-line-flags dl)) (setf (hi::dis-line-tick dl) (incf *tick*))) (clear-line-items scene hunk position) ;; (handler-case (let* ((no (hi::tag-line-number (hi::dis-line-tag dl))) (str (princ-to-string no))) (push (add-chunk-item scene hunk str (- (+ (* w (length str)) (* 2 *gutter*))) (+ 1 y) 0 (length str) (if (zerop (mod no 5)) 16 15)) (line-items hunk position))) (error (c) (warn "~A" c))) ;; font changes (let ((start 0) (font 0) (end (dis-line-length dl)) (changes (dis-line-font-changes dl))) (iter (cond ((null changes) (push (add-chunk-item scene hunk chrs (* w start) (+ 1 y) start end font) (line-items hunk position)) (return)) (t (push (add-chunk-item scene hunk chrs (* w start) (+ 1 y) start (font-change-x changes) font) (line-items hunk position)) (setf font (font-change-font changes) start (font-change-x changes) changes (font-change-next changes))))))) (setf (dis-line-flags dl) unaltered-bits (dis-line-delta dl) 0)) (defun clear-all-line-items (scene hunk) (with-slots (itab) hunk (iter (for i from 0) (for items in-vector itab) (dolist (old-item items) (#_removeItem scene old-item)) (setf (elt itab i) nil)))) (defun reset-hunk-background (window hunk) (declare (ignore window)) (let* ((widget (qt-hunk-widget hunk)) (scene (#_scene widget))) (dolist (item (hunk-background-items hunk)) (#_delete item)) (setf (hunk-background-items hunk) (when (qt-hunk-want-background-p hunk) (let ((offset (offset-on-each-side widget))) (with-objects ((pen1 (#_new QPen (#_Qt::SolidLine))) (pen2 (#_new QPen (#_Qt::NoPen))) (color1 (#_new QColor 255 255 255 210)) (color2 (#_new QColor 255 255 255 128)) (oops1 (#_new QBrush color1)) (oops2 (#_new QBrush color2)) (brush1 (#_new QBrush oops1)) (brush2 (#_new QBrush oops2)) (rect1 (#_new QRectF (- (+ (* 2 *gutter*) (truncate offset 2))) (- *gutter*) (+ (- (#_width widget) offset) (* 2 *gutter*)) (+ (* (slot-value hunk 'ch) (device-hunk-height hunk)) (* 2 *gutter*)))) (rect2 (#_new QRectF rect1))) (#_setColor pen1 (#_new QColor (#_Qt::black))) (#_adjust rect2 -5 -5 5 5) (let* ((group (ensure-hunk-item-group scene hunk)) (item1 (#_new QGraphicsRectItem rect1 group)) (item2 (#_new QGraphicsRectItem rect2 group))) (qt::cancel-finalization item1) (qt::cancel-finalization item2) (#_setPen item1 pen1) (#_setPen item2 pen2) (#_setBrush item1 brush1) (#_setBrush item2 brush2) (#_setZValue item1 1) (#_setZValue item2 1) (#_setZValue group 3) (list item1 item2)))))))) Smart is n't very smart , but still much better for " a single line changed " ;; kind of situations. (defun dumb-or-smart-redisplay (device window dumb) (declare (ignore device)) (let* ((widget (qt-hunk-widget (window-hunk window))) (hunk (window-hunk window)) (first (window-first-line window)) (offset (truncate (offset-on-each-side widget))) (scene (#_scene widget))) (when dumb (reset-hunk-background window hunk) (clear-all-line-items scene hunk)) (let* ((native-widget (hi::buffer-widget (window-buffer window))) (current-item (hunk-native-widget-item hunk)) (current-widget (and current-item (#_widget current-item)))) (unless (eq native-widget current-widget) (let ((group (ensure-hunk-item-group scene hunk))) (when current-item (setf (hunk-native-widget-item hunk) nil) (#_setWidget current-item (qt::null-qobject "QWidget")) (#_delete current-item)) (when native-widget (let ((item (#_new QGraphicsProxyWidget))) (#_setParent native-widget (qt::null-qobject "QWidget")) (#_setWidget item native-widget) (#_setParentItem item group) (#_setPos item (- offset) 0) (#_setZValue item 4) ;;; (#_setAcceptHoverEvents item t) ;;; (#_setEnabled native-widget t) (#_setFocusPolicy native-widget (#_Qt::StrongFocus)) ;;; (#_setFocusProxy widget native-widget) (#_setGeometry native-widget (- (+ offset)) 0 (- (#_width widget) (* 2 *gutter*)) (* (slot-value hunk 'ch) (device-hunk-text-height hunk))) #+nil (#_setTransform item (#_scale (#_rotate (#_new QTransform) 10) 0.75 0.75) nil) (setf (hunk-native-widget-item hunk) item)))))) ;; "empty" lines (let ((pos (dis-line-position (car (window-last-line window)))) (old (window-old-lines window))) (when (and pos old) (iter:iter (iter:for i from (1+ pos) to old) (clear-line-items scene hunk i))) (setf (window-old-lines window) pos)) ;; render "changed" lines (do ((i 0 (1+ i)) (dl (cdr first) (cdr dl))) ((eq dl the-sentinel) (setf (window-old-lines window) (1- i))) (let ((dis-line (car dl))) ;; fixme. See comment in COMPUTE-LINE-IMAGE: (hi::sync-dis-line-tag (hi::dis-line-line dis-line) dis-line) (when (or dumb (plusp (dis-line-flags dis-line))) (update-line-items scene hunk dis-line)))) ;; modeline (when (window-modeline-buffer window) (update-modeline-fields (window-buffer window) window) (let ((dl (window-modeline-dis-line window))) (update-modeline-items scene hunk dl) (setf (dis-line-flags dl) unaltered-bits)) (setf (dis-line-flags (window-modeline-dis-line window)) unaltered-bits))) ;; tell the redisplay algorithm that we did our job, otherwise it ;; retries forever: (let* ((first (window-first-line window)) ;; (hunk (window-hunk window)) #+nil (device (device-hunk-device hunk))) (setf (window-first-changed window) the-sentinel (window-last-changed window) first))) (defun ensure-hunk-item-group (scene hunk) (or (hunk-item-group hunk) (setf (hunk-item-group hunk) (let ((g (#_new QGraphicsItemGroup))) (#_addItem scene g) (qt::cancel-finalization g) g)))) (defun add-chunk-item (scene hunk string x y start end font-color &optional (font *font*)) (let* ((item (#_new QGraphicsSimpleTextItem (ensure-hunk-item-group scene hunk))) (widget (qt-hunk-widget hunk)) (offset (truncate (offset-on-each-side widget)))) (qt::cancel-finalization item) ( # _ setPos ( hunk - item - group hunk ) 50 50 ) (with-objects ((t2 (#_translate (#_new QTransform) (+ offset *gutter*) (+ *gutter* (progn ;; with-object (metrics (#_new QFontMetrics *font*)) (* (slot-value hunk 'ch) (- (device-hunk-position hunk) (device-hunk-height hunk)))))))) (#_setTransform (hunk-item-group hunk) t2 nil)) (#_setText item (subseq string start end)) (#_setFont item font) (let ((color (elt #( ;fg bg #x000000 #xffffff 1 = comments 2 = backquote 3 = unquote 4 = strings 5 = quote 6 = # + 7 = # - #x000000 #xbebebe #xff0000 #xbebebe #x00aa00 #xbebebe #xffff00 #xbebebe #x0000ff #xbebebe #xff00ff #xbebebe #x00ffff #xbebebe #xbebebe #x000000 #xffffff #x000000) (* 2 (mod font-color 17))))) (with-objects ((color (#_new QColor (ldb (byte 8 16) color) (ldb (byte 8 8) color) (ldb (byte 8 0) color))) (brush (#_new QBrush color))) (#_setBrush item brush))) (#_setPos item x y) (#_setZValue item 2) item)) (defun make-virtual-buffer (name widget &rest args) (let ((buffer (apply #'make-buffer name args))) (when buffer (setf (buffer-writable buffer) nil) (setf (hi::buffer-widget buffer) widget) ;; (#_addWidget *main-stack* widget) buffer))) ;; (defcommand "Enter Foreign Widget" (p) "" "" (declare (ignore p)) (let ((widget (hi::buffer-widget (current-buffer)))) (unless widget (editor-error "Not a foreign widget.")) (setf *steal-focus-out* nil) (#_setFocus widget) (clear-echo-area) (message "Focus set to foreign widget. Type C-g to go back."))) (defcommand "Leave Foreign Widget" (p) "Like control-g-handler, except for the C-g behaviour." "" (declare (ignore p)) (let ((main *main-hunk-widget*)) (unless (#_hasFocus main) (setf *steal-focus-out* t) (#_setFocus main) (clear-echo-area) (message "Focus restored. Welcome back to Hemlock.")))) (defcommand "Disable Steal Focus" (p) "" "" (declare (ignore p)) (setf *steal-focus-out* nil) (message "Focus stealing disabled")) (defcommand "Enable Steal Focus" (p) "" "" (declare (ignore p)) (setf *steal-focus-out* t) (#_setFocus *main-hunk-widget*)) #+nil (defcommand "Abc" (p) "" "" (let ((w (qt-hunk-item (window-hunk (current-window))))) (#_setZValue w 500) (#_setTransform (let* ((old (qt::qobject-class w)) (old-ptr (qt::qobject-pointer w)) (new (qt::find-qclass "QGraphicsItem")) (new-ptr (qt::%cast old-ptr (qt::unbash old) (qt::unbash new)))) (make-instance 'qt::qobject :class new :pointer new-ptr)) (#_translate (if p (#_rotate (#_scale (#_new QTransform) 0.75 0.75) 45) (#_new QTransform)) 200 0) nil))) (defcommand "Toggle Tab Bar" (p) "" "" (#_setVisible *tabs* (not (#_isVisible *tabs*)))) (defun main-window () (#_window (qt-hunk-widget (window-hunk (current-window))))) (defcommand "Toggle Menu Bar" (p) "" "" (let ((menubar (#_menuBar (main-window)))) (#_setVisible menubar (not (#_isVisible menubar))))) (defcommand "Toggle Full Screen" (p) "" "" (let ((win (main-window))) (if (logtest (#_windowState win) (primitive-value (#_Qt::WindowFullScreen))) (#_showNormal win) (#_showFullScreen win)))) #+nil (defcommand "Def" (p) "" "" (let* ((widget (#_new QWebView)) (w (#_addWidget (#_scene (qt-hunk-widget (window-hunk (current-window)))) widget))) (push widget *do-not-gc-list*) (push w *do-not-gc-list*) (#_setUrl widget (#_new QUrl "")) #+nil (#_setZValue w 500) #+nil (let* ((new-class (qt::find-qclass "QGraphicsItem")) (new-ptr (qt::%cast w new-class))) (make-instance 'qt::qobject :class new-class :pointer new-ptr)) (#_setTransform w #+nil (#_translate (#_new QTransform) 1 2) (#_translate (if p (#_rotate (#_scale (#_new QTransform) 0.75 0.75) 45) (#_new QTransform)) 400 0) nil)))
null
https://raw.githubusercontent.com/bluelisp/hemlock/47e16ba731a0cf4ffd7fb2110e17c764ae757170/src/qt.lisp
lisp
-*- Mode: Lisp; indent-tabs-mode: nil -*- (#_toString ...) fails on those pre-unmarshalled strings. But and we need to call (#_toString) after all. This doesn't seem ideal... Rather than have this separately in each hunk-widget method, do it centrally here: interceptor, we can steal them in time. (redisplay-all) Must dispatch all remaining events here (but not actually block). is built to alternate between INTERNAL-REDISPLAY and DISPATCH-EVENTS, with the expectation that only meaningful events like keyboard or socket interaction will make event dispatching return. So if redisplay exited with a pending event, editor-input-method would degenerate into a busy loop. leave space for the gutter on the left side (but not the right side, so that the column width is cut off cleanly) (call-next-qmethod) (call-next-qmethod) The whole *INTERESTING-EVENT-RECEIVED* business is here to prevent calling into INTERNAL-REDISPLAY too often (which is particularly bad because even no-op redisplay is currently expensive enough to be noticable, but would seem suboptimal in any case). #_processEvents as called here is already a blocking call, but seconds. As a result, the redisplay loop would call us to block, events have been received that are relevant to redisplay. The workaround is to simply go back into Qt until a signal or method has indicated that we did something which might have On my machine, this makes the difference between hemlock.qt always Note that processEvents has flags to inhibit processing of certain events, which end up matching our relevancy test (user input and socket stuff), but they are only useful in the opposite situation of not wanting to block, and briefly wanting to ignore those kinds of events. hmm? (minimize-echo-area echo) undo the minimum set before, so that it's only a default (fixme: it still overrides a saved geometry): leads to segfaults whenever a process started by Qt exits. It doesn't matter what the handler would do; a no-op lambda already has this effect. [Perhaps it's due to the way Qt tries to chain call our handler, I have no idea.] When in a slave, we need to create a QEventLoop here, otherwise (qt-hunk-want-background-p hunk) Nuke all the lines in the window image. Add some new spare lines if needed. If width is greater, reallocate the dis-line-chars. Prepare for redisplay. move the victim down move us up bump up our height make the victim smaller housekeeping with-object (metrics (#_new QFontMetrics *font*)) -1 for echo modeline. also main-modeline-pos main-text-lines (device-hunk-position hunk) 0 (device-hunk-height hunk) height The last time this window was updated. buffer displayed in this window. Height of window in lines. Width of the window in characters. The head of the list of dis-lines. The last dis-line displayed. The last changed dis-line. The head of the list of unused dis-lines The device hunk that displays this window. first character position displayed last character displayed Where the cursor is in this window. Dis-line for modeline display. Complete string of all modeline data. Valid chars in modeline-buffer. Redisplay (defun dis-line-rect (hunk dl) (let* ((h (slot-value hunk 'ch)) (w (slot-value hunk 'cw)) (xo *gutter*) (yo *gutter*) ... (end (dis-line-length dl)) ;... (x1 (+ xo (* w start))) (y1 (+ 1 yo (* (dis-line-position dl) h))) (m (#_new QFontMetrics *font*)) (hh (#_ascent m))) fixme? (widget (qt-hunk-widget hunk)) (offset (truncate (offset-on-each-side widget))) font changes kind of situations. (#_setAcceptHoverEvents item t) (#_setEnabled native-widget t) (#_setFocusProxy widget native-widget) "empty" lines render "changed" lines fixme. See comment in COMPUTE-LINE-IMAGE: modeline tell the redisplay algorithm that we did our job, otherwise it retries forever: (hunk (window-hunk window)) with-object (metrics (#_new QFontMetrics *font*)) fg bg (#_addWidget *main-stack* widget)
(in-package :hemlock.qt) (pushnew :qt hi::*available-backends*) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (named-readtables:find-readtable :hemlock.qt) (named-readtables:defreadtable :hemlock.qt (:merge :qt) (:dispatch-macro-char #\# #\k 'hemlock-ext::parse-key-fun)))) (named-readtables:in-readtable :hemlock.qt) (defun enable-syntax () (named-readtables:in-readtable :hemlock.qt) nil) (defvar *settings-organization* "Hemlock") (defvar *settings-application* "Hemlock") (defvar *font*) (defvar *modeline-font*) (defvar *tabs*) (defvar *buffers-to-tabs*) (defvar *main-stack*) (defvar *main-hunk-widget*) (defvar *executor*) (defvar *notifier*) (defun qsettings () (#_new QSettings *settings-organization* *settings-application*)) (defun save-window-geometry (window) (with-object (sx (qsettings)) (#_setValue sx "geometry" (#_new QVariant (#_saveGeometry window))))) (defcommand "Save Window Geometry" (p) "Save current window's geometry in Qt settings." "" (declare (ignore p)) (save-window-geometry (#_window (qt-hunk-widget (window-hunk (current-window)))))) (defun restore-window-geometry (window) (with-object (sx (qsettings)) (#_restoreGeometry window (#_toByteArray (#_value sx "geometry"))))) (defcommand "Restore Window Geometry" (p) "Restore the current window's geometry from Qt settings." "" (declare (ignore p)) (restore-window-geometry (#_window (qt-hunk-widget (window-hunk (current-window)))))) (defun save-font () (with-object (sx (qsettings)) (format t "setting font ~A~%" (#_toString *font*)) (#_setValue sx "main font" (#_toString *font*)))) (defun qvariant-string (x) fixme : CommonQt now string QVariants automatically , so sometimes we get a default QVariant , which CommonQt does n't unpack , (if (stringp x) x (#_toString x))) (defun restore-font () (with-object (sx (qsettings)) (let ((str (qvariant-string (#_value sx "main font")))) (when (plusp (length str)) (setf *font* (let ((font (#_new QFont))) (#_fromString font str) font)))))) (defcommand "Select Font" (p) "Open a font dialog and change the current display font." "" (declare (ignore p)) (let (font) (unless (qt::with-&bool (arg nil) (setf font (#_QFontDialog::getFont arg *font*))) (editor-error "Font dialog cancelled")) (setf *font* font) (save-font))) (defparameter *gutter* 10 "The gutter to place between between the matter in a hemlock pane and its margin to improve legibility (sp?, damn i miss ispell).") (defclass qt-device (device) ((cursor-hunk :initform nil :documentation "The hunk that has the cursor." :accessor device-cursor-hunk) (cursor-item :initform nil :accessor device-cursor-item) #+nil (windows :initform nil) (main-window :initform nil :accessor device-main-window))) (defun current-device () (device-hunk-device (window-hunk (current-window)))) (defclass qt-hunk (device-hunk) ((widget :initarg :widget :reader qt-hunk-widget) (native-widget-item :initform nil :accessor hunk-native-widget-item) (item :initarg :item :accessor qt-hunk-item) (item-group :initform nil :accessor hunk-item-group) (background-items :initform nil :accessor hunk-background-items) (want-background-p :initarg :want-background-p :initform nil :accessor qt-hunk-want-background-p) (itab :initform (make-array 0 :adjustable t :initial-element nil)) (text-position :initarg :text-position :accessor device-hunk-text-position) (text-height :initarg :text-height :accessor device-hunk-text-height) (cw) (ch) (ts))) (defun line-items (hunk i) (with-slots (itab) hunk (unless (< i (length itab)) (adjust-array itab (* 2 (max 1 i)) :initial-element nil)) (elt itab i))) (defun (setf line-items) (newval hunk i) (with-slots (itab) hunk (unless (< i (length itab)) (adjust-array itab (* 2 (max 1 i)))) (setf (elt itab i) newval))) (defvar *steal-focus-out* t) (defclass hunk-widget () ((hunk :accessor widget-hunk) (centerize :initform nil :initarg :centerize :accessor centerize-widget-p) (paint-margin :initform nil :initarg :paint-margin :accessor paint-widget-margin-p) (background-pixmap :initform nil :accessor hunk-widget-background-pixmap) (background-pixmap-item :initform nil :accessor hunk-widget-background-pixmap-item) (white-item-1 :initform nil :accessor hunk-widget-rect-pixmap-item) (white-item-2 :initform nil :accessor hunk-widget-rect-pixmap-item) (height :initform 0 :accessor hunk-widget-height)) (:metaclass qt-class) (:qt-superclass "QGraphicsView") (:override ("resizeEvent" resize-event) ("keyPressEvent" key-press-event) ("focusOutEvent" focus-out-event) ("event" intercept-event) ("contextMenuEvent" context-menu-event) #+nil ("mousePressEvent" mouse-press-event) #+nil ("mouseMoveEvent" mouse-move-event) #+nil ("mouseReleaseEvent" mouse-release-event))) (defun focus-out-event (this event) (declare (ignore event)) (when *steal-focus-out* (let ((*steal-focus-out* nil)) (#_setFocus this)))) (defvar *interesting-event-received* nil "Did Qt just receive an event that matters to Hemlock? Anyone using :OVERRIDE or #_connect for code that might affect Hemlock state is required to set this variable to true. See the comment in DISPATCH-EVENTS for details.") (defun intercept-event (instance event) (setf *interesting-event-received* t) Qt consumes key events for its own purposes . Using this event (let (casted) (cond ((and (enum= (#_type event) (#_QEvent::KeyPress)) (setf casted (make-instance 'qobject :class (qt:find-qclass "QKeyEvent") :pointer (qt::qobject-pointer event))) (eql (#_key casted) (primitive-value (#_Qt::Key_Tab)))) (key-press-event instance casted) t) (t (call-next-qmethod))))) (defmethod initialize-instance :after ((instance hunk-widget) &key) (new instance) (#_setFocusPolicy instance (#_Qt::StrongFocus)) (#_setScene instance (#_new QGraphicsScene instance)) (#_setHorizontalScrollBarPolicy instance (#_Qt::ScrollBarAlwaysOff)) (#_setVerticalScrollBarPolicy instance (#_Qt::ScrollBarAlwaysOff))) (defmethod device-init ((device qt-device)) ) (defmethod device-exit ((device qt-device))) (defmacro with-timer (&body body) `(call-with-timer (lambda () ,@body))) (defun call-with-timer (fun) (let ((a (get-internal-real-time))) (multiple-value-prog1 (funcall fun) (let ((b (get-internal-real-time))) (format *trace-output* " ~D" (round(* (- b a) (/ 1000 internal-time-units-per-second)))) (force-output *trace-output*))))) (defmethod device-smart-redisplay ((device qt-device) window) (dumb-or-smart-redisplay device window nil)) (defmethod device-dumb-redisplay ((device qt-device) window) (dumb-or-smart-redisplay device window t)) (defmethod device-after-redisplay ((device qt-device)) ) (defmethod device-clear ((device qt-device)) ) (defmethod device-note-read-wait ((device qt-device) on-off) ) (defvar *processing-events-p* nil) (defun exhaustively-dispatch-events-no-hang () Redisplay can lead to events being posted , and Hemlock 's event loop (assert (not *processing-events-p*)) (let ((ev (#_QAbstractEventDispatcher::instance)) (*processing-events-p* t)) (iter (while (#_processEvents ev (#_QEventLoop::AllEvents)))))) (defmethod device-force-output ((device qt-device)) (unless *processing-events-p* (exhaustively-dispatch-events-no-hang))) (defmethod device-finish-output ((device qt-device) window) ) (defmethod device-put-cursor ((device qt-device) hunk x y) (with-slots (cursor-item cursor-hunk) device (when (and cursor-item (not (eq hunk cursor-hunk))) (let ((*steal-focus-out* nil)) (#_removeItem (#_scene cursor-item) cursor-item)) (setf cursor-item nil)) (setf cursor-hunk hunk) (with-slots (cw ch) hunk (unless cursor-item (setf cursor-item (with-objects ((path (#_new QPainterPath)) (pen (#_new QPen (#_Qt::NoPen))) (color (#_new QColor 0 180 180 64)) (brush (#_new QBrush color))) (#_addRect path 0 0 cw ch) (let* ((scene (#_scene (qt-hunk-widget hunk))) (group (ensure-hunk-item-group scene hunk)) (item (#_new QGraphicsPathItem path group))) (qt::cancel-finalization item) (#_setPen item pen) (#_setBrush item brush) item)))) (#_setPos cursor-item (* x cw) (* y ch))) (#_setZValue cursor-item 3))) (defmethod device-show-mark ((device qt-device) window x y time) ) Windows (defmethod device-next-window ((device qt-device) window) (device-hunk-window (device-hunk-next (window-hunk window)))) (defmethod device-previous-window ((device qt-device) window) (device-hunk-window (device-hunk-previous (window-hunk window)))) (defvar *currently-selected-hunk* nil) (defmethod device-delete-window ((device qt-device) window) (let* ((hunk (window-hunk window)) (prev (device-hunk-previous hunk)) (next (device-hunk-next hunk)) (device (device-hunk-device hunk)) (group (hunk-item-group hunk))) (when group (when (eq hunk (device-cursor-hunk device)) (setf (device-cursor-item device) nil)) (setf (hunk-native-widget-item hunk) nil) (with-slots (itab) hunk (fill itab nil)) (#_delete group)) (setf (device-hunk-next prev) next) (setf (device-hunk-previous next) prev) (let ((buffer (window-buffer window))) (setf (buffer-windows buffer) (delete window (buffer-windows buffer)))) (let ((new-lines (device-hunk-height hunk))) (declare (fixnum new-lines)) (cond ((eq hunk (device-hunks (device-hunk-device next))) (incf (device-hunk-height next) new-lines) (incf (device-hunk-text-height next) new-lines) (let ((w (device-hunk-window next))) (hi::change-window-image-height w (+ new-lines (window-height w))))) (t (incf (device-hunk-height prev) new-lines) (incf (device-hunk-position prev) new-lines) (incf (device-hunk-text-height prev) new-lines) (incf (device-hunk-text-position prev) new-lines) (let ((w (device-hunk-window prev))) (hi::change-window-image-height w (+ new-lines (window-height w))))))) (when (eq hunk (device-hunks device)) (setf (device-hunks device) next))) (setf *currently-selected-hunk* nil) (setf hi::*screen-image-trashed* t)) (defmethod device-make-window ((device qt-device) start modelinep window font-family ask-user x y width height proportion) (declare (ignore window font-family ask-user x y width height)) (let* ((old-window (current-window)) (victim (window-hunk old-window)) (text-height (device-hunk-text-height victim)) (availability (if modelinep (1- text-height) text-height))) (when (> availability 1) (let* ((new-lines (truncate (* availability proportion))) (old-lines (- availability new-lines)) (pos (device-hunk-position victim)) (new-height (if modelinep (1+ new-lines) new-lines)) (new-text-pos (if modelinep (1- pos) pos)) (widget (qt-hunk-widget (window-hunk *current-window*))) (new-hunk (make-instance 'qt-hunk :position pos :height new-height :text-position new-text-pos :text-height new-lines :device device :widget widget)) (new-window (internal-make-window :hunk new-hunk))) (with-object (metrics (#_new QFontMetrics *font*)) (setf (slot-value new-hunk 'cw) (+ 0 (#_width metrics "m")) (slot-value new-hunk 'ch) (+ 2 (#_height metrics)))) (setf (device-hunk-window new-hunk) new-window) (let* ((old-text-pos-diff (- pos (device-hunk-text-position victim))) (old-win-new-pos (- pos new-height))) (declare (fixnum old-text-pos-diff old-win-new-pos)) (setf (device-hunk-height victim) (- (device-hunk-height victim) new-height)) (setf (device-hunk-text-height victim) old-lines) (setf (device-hunk-position victim) old-win-new-pos) (setf (device-hunk-text-position victim) (- old-win-new-pos old-text-pos-diff))) (hi::setup-window-image start new-window new-lines (window-width old-window)) (prepare-window-for-redisplay new-window) (when modelinep (setup-modeline-image (line-buffer (mark-line start)) new-window)) (hi::change-window-image-height old-window old-lines) (shiftf (device-hunk-previous new-hunk) (device-hunk-previous (device-hunk-next victim)) new-hunk) (shiftf (device-hunk-next new-hunk) (device-hunk-next victim) new-hunk) (setf *currently-selected-hunk* nil) (setf hi::*screen-image-trashed* t) new-window)))) (defmethod resize-event ((widget hunk-widget) resize-event) (call-next-qmethod) #+nil (#_setMaximumWidth *tabs* (#_width wrapper)) (update-full-screen-items widget) (hi::enlarge-device (current-device) (recompute-hunk-widget-height widget)) (hi::internal-redisplay)) (defvar *standard-column-width* 80) (defun standard-width-in-pixels () (with-object (metrics (#_new QFontMetrics *font*)) (+ (* *standard-column-width* (#_width metrics "m")) *gutter*))) (defun offset-on-each-side (widget) (if (centerize-widget-p widget) (let ((white-width (standard-width-in-pixels)) (full-width (#_width widget))) (max 0.0d0 (/ (- full-width white-width) 2.0d0))) 0.0d0)) (defmethod device-beep ((device qt-device) stream) ) (defclass qt-editor-input (editor-input) ()) (defvar *alt-is-meta* t) (defvar *qt-initialized-p* nil) (defmethod context-menu-event ((instance hunk-widget) event) (let ((menu (#_new QMenu))) (add-menus menu) (#_exec menu (#_globalPos event)))) (defmethod key-press-event ((instance hunk-widget) event) (hi::q-event *editor-input* (qevent-to-key-event event))) (defun parse-modifiers (event) (let ((mods (#_modifiers event))) (logior (if (logtest mods (qt::primitive-value (#_Qt::ControlModifier))) (hemlock-ext:key-event-bits #k"control-a") 0) (if (or (logtest mods (qt::primitive-value (#_Qt::MetaModifier))) (and *alt-is-meta* (logtest mods (qt::primitive-value (#_Qt::AltModifier))))) (hemlock-ext:key-event-bits #k"meta-a") 0)))) (defun parse-key (event) (let ((k (#_key event))) (cond ((or (eql k (primitive-value (#_Qt::Key_Return))) (eql k (primitive-value (#_Qt::Key_Enter)))) (hemlock-ext:key-event-keysym #k"Return")) ((eql k (primitive-value (#_Qt::Key_Tab))) (hemlock-ext:key-event-keysym #k"tab")) ((eql k (primitive-value (#_Qt::Key_Escape))) (hemlock-ext:key-event-keysym #k"Escape")) ((eql k (primitive-value (#_Qt::Key_Backspace))) (hemlock-ext:key-event-keysym #k"Backspace")) ((eql k (primitive-value (#_Qt::Key_Delete))) (hemlock-ext:key-event-keysym #k"delete")) ((eql k (primitive-value (#_Qt::Key_Space))) (hemlock-ext:key-event-keysym #k"space")) (t nil)))) (defun qevent-to-key-event (event) (let* ((text (map 'string (lambda (c) (if (< (char-code c) 32) (code-char (+ 96 (char-code c))) c)) (#_text event))) (mask (parse-modifiers event)) (keysym (or (parse-key event) (hemlock-ext::name-keysym text)))) (when keysym (hemlock-ext:make-key-event keysym mask)))) (defmethod get-key-event ((stream qt-editor-input) &optional ignore-abort-attempts-p) (hi::%editor-input-method stream ignore-abort-attempts-p)) (defun in-main-qthread-p () (and hi::*in-the-editor* (typep (current-device) 'qt-device))) (defmethod hi::dispatch-events-with-backend ((backend (eql :qt))) apparently has a timeout event somewhere that is set to two only to enter INTERNAL - REDISPLAY again after 2s , even though no affected Hemlock state . showing up with 1 % CPU usage in top , and not showing up . (assert (not *processing-events-p*)) (setf *interesting-event-received* nil) (let ((*processing-events-p* t)) (iter (until *interesting-event-received*) (#_processEvents (#_QAbstractEventDispatcher::instance) (#_QEventLoop::WaitForMoreEvents))))) (defmethod hi::dispatch-events-no-hang-with-backend ((backend (eql :qt))) (assert (not *processing-events-p*)) (let ((*processing-events-p* t)) (#_processEvents (#_QAbstractEventDispatcher::instance) (#_QEventLoop::AllEvents)))) (defmethod unget-key-event (key-event (stream qt-editor-input)) (hi::un-event key-event stream)) (defmethod clear-editor-input ((stream qt-editor-input)) ) (defmethod listen-editor-input ((stream qt-editor-input)) (hi::input-event-next (hi::editor-input-head stream))) (defun make-hemlock-widget () (let* ((vbox (#_new QVBoxLayout)) (tabs (#_new QTabBar)) (main (make-instance 'hunk-widget :centerize t :paint-margin t)) (font (let ((font (#_new QFont))) (#_fromString font *font-family*) (#_setPointSize font *font-size*) font)) (*font* font) (font (progn (restore-font) *font*)) (*modeline-font* (let ((font (#_new QFont))) (#_fromString font *modeline-font-family*) (#_setPointSize font (#_pointSize *font*)) font))) (#_addWidget vbox tabs) (#_hide tabs) (let ((main-stack (#_new QStackedWidget))) (setf *main-stack* main-stack) (setf *main-hunk-widget* main) (#_addWidget vbox main-stack) (#_addWidget main-stack main)) (#_setFocusPolicy tabs (#_Qt::NoFocus)) (#_setSpacing vbox 0) (#_setMargin vbox 0) (let ((central-widget (#_new QWidget))) (#_setLayout central-widget vbox) (values main font *modeline-font* central-widget tabs)))) (defun add-buffer-tab-hook (buffer) (when (in-main-qthread-p) (#_addTab *tabs* (buffer-name buffer)))) (defun buffer-tab-index (buffer) (dotimes (i (#_count *tabs*)) (when (equal (#_tabText *tabs* i) (buffer-name buffer)) (return i)))) (defun delete-buffer-tab-hook (buffer) (when (in-main-qthread-p) (let ((idx (buffer-tab-index buffer))) (if idx (#_removeTab *tabs* idx) (warn "buffer tab missing"))))) (defun update-buffer-tab-hook (buffer new-name) (when (in-main-qthread-p) (let ((idx (buffer-tab-index buffer))) (if idx (#_setTabText *tabs* idx new-name) (warn "buffer tab missing"))))) (defun set-buffer-tab-hook (buffer) (when (in-main-qthread-p) (let ((idx (buffer-tab-index buffer))) (if idx (#_setCurrentIndex *tabs* idx) (warn "buffer tab missing"))))) (defun set-stack-widget-hook (buffer) (when (in-main-qthread-p) (#_setCurrentWidget *main-stack* *main-hunk-widget*))) (add-hook hemlock::make-buffer-hook 'add-buffer-tab-hook) (add-hook hemlock::delete-buffer-hook 'delete-buffer-tab-hook) (add-hook hemlock::buffer-name-hook 'update-buffer-tab-hook) (add-hook hemlock::set-buffer-hook 'set-buffer-tab-hook) (add-hook hemlock::set-buffer-hook 'set-stack-widget-hook) (defun splitter-sizes (splitter) (qt::qlist-to-list (#_sizes splitter))) (defun (setf splitter-sizes) (newval splitter) (#_setSizes splitter (qt::qlist-append (qt::make-qlist<int>) newval)) newval) (defun resize-echo-area (nlines backgroundp) (setf (device-hunk-height (window-hunk *echo-area-window*)) nlines) (setf (device-hunk-text-height (window-hunk *echo-area-window*)) nlines) (hi::change-window-image-height *echo-area-window* nlines) (setf (qt-hunk-want-background-p (window-hunk *echo-area-window*)) backgroundp) (redisplay-all) #+nil (let* ((widget (or widget (qt-hunk-widget (window-hunk *echo-area-window*)))) (splitter (#_centralWidget (#_window widget))) (new-height (with-object (metrics (#_new QFontMetrics *font*)) (+ (* 2 *gutter*) (* nlines (#_height metrics)))))) (#_setMinimumHeight widget 1) (destructuring-bind (top bottom) (splitter-sizes splitter) (let ((diff (- new-height bottom))) (setf (splitter-sizes splitter) (list (- top diff) new-height)))))) (defun minimize-echo-area () (resize-echo-area 1 nil)) (defun enlarge-echo-area () (resize-echo-area 5 t)) (defun set-window-hook (new-window) (when (in-main-qthread-p) (cond ((eq new-window *echo-area-window*) (enlarge-echo-area)) ((eq *current-window* *echo-area-window*) (minimize-echo-area))))) (add-hook hemlock::set-window-hook 'set-window-hook) (defun signal-receiver (function) (make-instance 'signal-receiver :function (lambda (&rest args) (setf *interesting-event-received* t) (apply function args)))) (defun connect (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke()")))) (defun connect/int (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke(int)")))) (defun connect/string (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke(const QString&)")))) (defun connect/boolean (source signal cont) (let ((receiver (signal-receiver cont))) (push receiver *do-not-gc-list*) (#_QObject::connect source signal receiver (QSLOT "invoke(bool)")))) (defclass signal-receiver () ((function :initarg :function :accessor signal-receiver-function)) (:metaclass qt-class) (:qt-superclass "QObject") (:slots ("invoke()" (lambda (this &rest args) (apply (signal-receiver-function this) args))) ("invoke(int)" (lambda (this &rest args) (apply (signal-receiver-function this) args))) ("invoke(const QString&)" (lambda (this &rest args) (apply (signal-receiver-function this) args))) ("invoke(bool)" (lambda (this &rest args) (apply (signal-receiver-function this) args))))) (defmethod initialize-instance :after ((instance signal-receiver) &key) (new instance)) (defclass command-action-receiver () ((command :initarg :command :accessor command-action-receiver-command)) (:metaclass qt-class) (:qt-superclass "QWidget") (:slots ("triggered()" (lambda (this) (funcall (command-function (command-action-receiver-command this)) nil) (hi::internal-redisplay))))) (defmethod initialize-instance :after ((instance command-action-receiver) &key) (new instance)) (defvar *do-not-gc-list*) (defun add-command-action (menu command &optional suffix) (let* ((receiver (make-instance 'command-action-receiver :command (getstring command hi::*command-names*))) (action (#_addAction menu (concatenate 'string command suffix) receiver (qslot "triggered()")))) (push action *do-not-gc-list*) (push receiver *do-not-gc-list*))) #+(or) (defun control-g-handler (&rest *) (let ((widget *echo-hunk-widget*)) (cond ((#_hasFocus widget) (hi::q-event *editor-input* #k"control-g")) (t (setf *steal-focus-out* t) (#_setFocus *echo-hunk-widget*) (clear-echo-area) (message "Focus restored. Welcome back to Hemlock."))))) (defun control-g-handler (&rest *) (setf *steal-focus-out* t) (#_setFocus *main-hunk-widget*) (clear-echo-area) (hi::q-event *editor-input* #k"control-g")) (defvar *invoke-later-thunks*) (defvar *invoke-later-timer*) (defmethod hi::invoke-later ((backend (eql :qt)) fun) (push fun *invoke-later-thunks*) (#_setSingleShot *invoke-later-timer* t) (#_start *invoke-later-timer*)) (defun process-invoke-later-thunks () (iter (while *invoke-later-thunks*) (funcall (pop *invoke-later-thunks*)))) (defmethod hi::backend-init-raw-io ((backend (eql :qt)) display) (declare (ignore display)) (setf hi::*editor-input* (make-instance 'qt-editor-input))) (defun add-menus (parent) (let ((menu (#_addMenu parent "File"))) (add-command-action menu "Find File") (add-command-action menu "Save File") (#_addSeparator menu) (add-command-action menu "Write File") (#_addSeparator menu) (add-command-action menu "Save All Files and Exit")) (let ((menu (#_addMenu parent "View"))) (add-command-action menu "Toggle Menu Bar") (add-command-action menu "Toggle Tab Bar") (add-command-action menu "Toggle Full Screen")) (let ((menu (#_addMenu parent "Lisp"))) (add-command-action menu "Start Slave Thread") (add-command-action menu "Start Slave Process") (add-command-action menu "List Slaves")) (let ((menu (#_addMenu parent "Buffer"))) (add-command-action menu "Bufed")) (let ((menu (#_addMenu parent "Browser"))) (add-command-action menu "Browse") (add-command-action menu "Browse Qt Class") (add-command-action menu "CLHS") (add-command-action menu "Google") (#_addSeparator menu) (add-command-action menu "Enter Foreign Widget") (add-command-action menu "Leave Foreign Widget")) (let ((menu (#_addMenu parent "Preferences"))) (add-command-action menu "Select Font") (#_addSeparator menu) (add-command-action menu "Save Window Geometry") (add-command-action menu "Restore Window Geometry"))) (defmethod hi::%init-screen-manager ((backend-type (eql :qt)) (display t)) (declare (ignore display)) (let (main central-widget) (setf (values main *font* *modeline-font* central-widget *tabs*) (make-hemlock-widget)) (let* ((device (make-instance 'qt-device)) (window (#_new QMainWindow))) (setf (device-name device) "Qt" (device-bottom-window-base device) nil) keep the QMainWindow from being GCed : (setf (device-main-window device) window) (#_setWindowTitle window "Hemlock") (#_setCentralWidget window central-widget) (add-menus (#_menuBar window)) (#_hide (#_menuBar window)) (setf hi::*real-editor-input* *editor-input*) (set-up-qt-hunks device main) (dolist (buffer hi::*buffer-list*) (unless (eq buffer *echo-area-buffer*) (add-buffer-tab-hook buffer))) (connect/int *tabs* (qsignal "currentChanged(int)") (lambda (index) (change-to-buffer (hemlock-ext::find-buffer (#_tabText *tabs* index))))) (with-object (key (#_new QKeySequence "Ctrl+G")) (connect (#_new QShortcut key (#_window *main-hunk-widget*)) (QSIGNAL "activated()") 'control-g-handler)) #+nil (#_setMinimumHeight echo (with-object (metrics (#_new QFontMetrics *font*)) (+ (* 2 *gutter*) (#_height metrics)))) (restore-window-geometry window) (#_show window) #+nil (#_setMinimumSize widget 0 0) (setf *notifier* (make-instance 'qt-repl::repl-notifier)) (setf *executor* (make-instance 'qt-repl::repl-executer :notifier *notifier*))))) (defmethod hi::make-event-loop ((backend (eql :qt))) 'qt-event-loop) (defmethod hi::invoke-with-existing-event-loop ((backend (eql :qt)) loop fun) (assert (eq loop 'qt-event-loop)) (hi::invoke-with-new-event-loop backend fun)) (defmethod hi::invoke-with-new-event-loop ((backend (eql :qt)) fun &aux keep) (unless *qt-initialized-p* HACK ! Disable SBCL 's SIGCHLD handler . I do n't know what exactly it is doing wrong , but if SBCL sets a signal handler for this , it or perhaps we are interrupting FFI code , or is it an altstack thing ? #+sbcl (sb-kernel::default-interrupt sb-unix:sigchld) (format t "Loading shared libraries [") (let ((first t)) (dolist (module '(:qtcore :qtgui :qtnetwork :qtsvg :qtwebkit)) (if first (setf first nil) (write-string ", ")) (format t "~A" (string-downcase module)) (force-output) (ensure-smoke module))) (format t "].~%Connecting to window system...") (force-output) (push (make-qapplication) keep) (format t "done.~%") (force-output) (setf *qt-initialized-p* t)) we will later . Let 's just do it unconditionally : (push (#_new QEventLoop) keep) (let* ((*do-not-gc-list* '()) (*invoke-later-thunks* '()) (*invoke-later-timer* (#_new QTimer)) (*interesting-event-received* nil)) (connect *invoke-later-timer* (QSIGNAL "timeout()") #'process-invoke-later-thunks) #-sbcl (funcall fun) #+sbcl (sb-int:with-float-traps-masked (:overflow :invalid :divide-by-zero) (funcall fun)))) Keysym translations (defun qt-character-keysym (gesture) (cond # # # hmm (hemlock-ext:key-event-keysym #k"Return")) # # # hmm (hemlock-ext:key-event-keysym #k"Tab")) ((eql gesture #\Backspace) (hemlock-ext:key-event-keysym #k"Backspace")) ((eql gesture #\Escape) (hemlock-ext:key-event-keysym #k"Escape")) ((eql gesture #\rubout) (hemlock-ext:key-event-keysym #k"delete")) (t (char-code gesture)))) (defun effective-hunk-widget-width (widget) (- (#_width widget) (offset-on-each-side widget))) (defun probe-namestring (x) (when (and x (probe-file x)) (etypecase x (string x) (pathname (namestring x))))) (defun find-background-svg () (etypecase hemlock:*background-image* ((or string pathname) (or (probe-namestring hemlock:*background-image*) (progn (format t "Specified background image not found: ~A~%" hemlock:*background-image*) nil))) ((eql :auto) (or (probe-namestring (merge-pathnames ".hemlock/background.svg" (user-homedir-pathname))) (probe-namestring (merge-pathnames "background.svg" (hi::installation-directory))))) (null))) (defun update-full-screen-items (widget) (with-slots (background-pixmap background-pixmap-item) widget (setf background-pixmap (let ((file (find-background-svg))) (if file (let ((pixmap (#_new QPixmap (#_width widget) (#_height widget)))) (with-objects ((renderer (#_new QSvgRenderer file)) (painter (#_new QPainter pixmap))) (#_render renderer painter) (#_end painter) pixmap)) nil))) (when background-pixmap-item (#_removeItem (#_scene background-pixmap-item) background-pixmap-item) (setf background-pixmap-item nil)) (when background-pixmap (setf background-pixmap-item (#_addPixmap (#_scene widget) background-pixmap)) (#_setZValue background-pixmap-item -2) #+nil (#_setBackgroundBrush (#_scene widget) (#_new QBrush background-pixmap))))) (with-slots (white-item-1 white-item-2) widget (when white-item-1 (#_removeItem (#_scene white-item-1) white-item-1) (setf white-item-1 nil)) (when white-item-2 (#_removeItem (#_scene white-item-2) white-item-2) (setf white-item-2 nil)) (let ((offset (truncate (offset-on-each-side widget)))) (with-object (~) (setf white-item-1 (#_addRect (#_scene widget) (#_new QRectF offset 0 (- (#_width widget) (* 2 offset)) (#_height widget)) (~ (#_new QPen (#_Qt::NoPen))) (~ (#_new QBrush (~ (#_new QBrush (~ (#_new QColor 255 255 255 210))))))))) (with-object (~) (setf white-item-2 (#_addRect (#_scene widget) (~ (#_new QRectF (- (#_width widget) offset) 0 offset (#_height widget))) (~ (#_new QPen (#_Qt::NoPen))) (~ (#_new QBrush (~ (#_new QBrush (~ (#_new QColor 255 255 255 180)))))))))) (#_setZValue white-item-1 -1) (#_setZValue white-item-2 -1))) (defun old-resize-junk () #+nil (let ((window (device-hunk-window hunk))) (unless (eq (cdr (window-first-line window)) the-sentinel) (shiftf (cdr (window-last-line window)) (window-spare-lines window) (cdr (window-first-line window)) the-sentinel)) # # # ( setf ( bitmap - hunk - start hunk ) ( cdr ( window - first - line window ) ) ) (let* ((res (window-spare-lines window)) (new-width (max 5 (floor (- (effective-hunk-widget-width (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'cw)))) (new-height (max 2 (1- (floor (- (#_height (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'ch))))) (width (length (the simple-string (dis-line-chars (car res)))))) (declare (list res)) (when (> new-width width) (setq width new-width) (dolist (dl res) (setf (dis-line-chars dl) (make-string new-width)))) (setf (window-height window) new-height (window-width window) new-width) (do ((i (- (* new-height 2) (length res)) (1- i))) ((minusp i)) (push (make-window-dis-line (make-string width)) res)) (setf (window-spare-lines window) res) Force modeline update . (let ((ml-buffer (window-modeline-buffer window))) (when ml-buffer (let ((dl (window-modeline-dis-line window)) (chars (make-string new-width)) (len (min new-width (window-modeline-buffer-len window)))) (setf (dis-line-old-chars dl) nil) (setf (dis-line-chars dl) chars) (replace chars ml-buffer :end1 len :end2 len) (setf (dis-line-length dl) len) (setf (dis-line-flags dl) changed-bit))))) (setf (window-tick window) (tick)) (update-window-image window) (when (eq window *current-window*) (maybe-recenter-window window)) hunk)) (defmethod hi::device-enlarge-window ((device qt-device) window offset) (let* ((hunk (window-hunk window)) (victim (cond ((eq hunk (device-hunks (device-hunk-device hunk))) we 're the first hunk (let ((victim (device-hunk-next hunk))) (when (eq hunk victim) ... the first and only hunk (editor-error "Cannot enlarge only window")) (incf (device-hunk-position hunk) offset) (incf (device-hunk-text-position hunk) offset) victim)) (t we 're not first hunk , so there is a victim in front of us (let ((victim (device-hunk-previous hunk))) (decf (device-hunk-position victim) offset) (decf (device-hunk-text-position victim) offset) victim))))) (incf (device-hunk-height hunk) offset) (incf (device-hunk-text-height hunk) offset) (decf (device-hunk-height victim) offset) (decf (device-hunk-text-height victim) offset) (let ((w (device-hunk-window victim))) (hi::change-window-image-height w (- offset (window-height w)))) (let ((w (device-hunk-window hunk))) (hi::change-window-image-height w (+ offset (window-height w)))) (setf hi::*screen-image-trashed* t))) (defmethod hi::enlarge-device ((device qt-device) offset) #+nil (hi::set-up-screen-image device) (let ((first (device-hunks device))) (incf (device-hunk-position first) offset) (incf (device-hunk-text-position first) offset) (incf (device-hunk-height first) offset) (incf (device-hunk-text-height first) offset) (let ((w (device-hunk-window first))) (hi::change-window-image-height w (+ offset (window-height w)))) (do ((hunk (device-hunk-next first) (device-hunk-next hunk))) ((eq hunk first)) (incf (device-hunk-position hunk) offset) (incf (device-hunk-text-position hunk) offset)) (let ((hunk (window-hunk *echo-area-window*))) (incf (device-hunk-position hunk) offset) (incf (device-hunk-text-position hunk) offset)) (setf hi::*screen-image-trashed* t))) (defun recompute-hunk-widget-height (widget) (let ((new (with-object (metrics (#_new QFontMetrics *font*)) (max 2 (floor (- (#_height widget) (* 2 *gutter*)) (+ 2 (#_height metrics)))))) (old (hunk-widget-height widget))) (setf (hunk-widget-height widget) new) (- new old))) (defun set-up-qt-hunks (device main-widget) (let* ((buffer *current-buffer*) (start (buffer-start-mark buffer)) (first (cons dummy-line the-sentinel)) #+nil (width (max 5 (floor (- (#_width (qt-hunk-widget hunk)) (* 2 *gutter*)) (+ 0 (#_width metrics "m"))))) (height (recompute-hunk-widget-height main-widget)) (echo-height #+nil (value hemlock::echo-area-height) 1) ) (declare (ignorable start first)) (setf (buffer-windows buffer) nil (buffer-windows *echo-area-buffer*) nil) (let* ((window (hi::internal-make-window)) (last-text-line (1- main-text-lines)) (hunk (make-instance 'qt-hunk :height main-lines :text-position last-text-line :text-height main-text-lines :widget main-widget))) (redraw-widget device window hunk buffer t) (setf *current-window* window) #+nil (push window (slot-value device 'windows)) (setf (device-hunk-previous hunk) hunk) (setf (device-hunk-next hunk) hunk) (setf (device-hunks device) hunk)) (let ((echo-window (hi::internal-make-window)) (echo-hunk (make-instance 'qt-hunk :position (1- height) :height echo-height :text-position (- height 2) :text-height echo-height :widget main-widget))) (redraw-widget device echo-window echo-hunk *echo-area-buffer* nil) (setf *echo-area-window* echo-window))))) (defvar *font-family* "Fixed [Misc]" #+nil "Courier New") (defvar *modeline-font-family* "Sans") (defvar *font-size* 10) (defun redraw-widget (device window hunk buffer modelinep) (setf (slot-value (qt-hunk-widget hunk) 'hunk) hunk) (let* ((start (buffer-start-mark buffer)) (first (cons dummy-line the-sentinel)) (font *font*) width height) (with-object (metrics (#_new QFontMetrics font)) (setf (slot-value hunk 'cw) (+ 0 (#_width metrics "m")) (slot-value hunk 'ch) (+ 2 (#_height metrics)) width (max 5 (floor (- (#_width (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'cw))) height (max 2 (floor (- (#_height (qt-hunk-widget hunk)) (* 2 *gutter*)) (slot-value hunk 'ch))) (device-hunk-window hunk) window (device-hunk-next hunk) nil (device-hunk-previous hunk) nil (device-hunk-device hunk) device The charpos of the first char displayed . The first changed dis - line on last update . ) (setup-dis-lines window width height) (when modelinep (setup-modeline-image buffer window)) (push window (buffer-windows buffer)) (push window *window-list*) (hi::update-window-image window)))) (defun setup-dis-lines (window width height) (do ((i (- height) (1+ i)) (res () (cons (make-window-dis-line (make-string width)) res))) ((= i height) (setf (window-spare-lines window) res)))) (defvar *tick* 0) ( ( dis - line - chars dl ) ) ( ww ( # _ width m ( subseq chrs start end ) ) ) ( # _ new QRect x1 y1 ww ( * 2 hh ) ) ) ) #+(or) (defun dis-line-rect (hunk dl) (nth-line-rect hunk (dis-line-position dl))) #+(or) (defun nth-line-rect (hunk i) (let* ((x *gutter*) (y (+ *gutter* (* i (slot-value hunk 'ch)))) (w (- (#_width (qt-hunk-widget hunk)) (ceiling (offset-on-each-side (qt-hunk-widget hunk))))) (h (slot-value hunk 'ch))) (#_new QRect x y w h))) #+(or) (defun cursor-rect (hunk x y) (with-slots (cw ch) hunk (when (and x y cw ch) (#_new QRect (+ *gutter* (* x cw)) (+ *gutter* (* y ch)) (1+ cw) (1+ ch))))) (defun clear-line-items (scene hunk position) (declare (ignore scene)) (dolist (old-item (line-items hunk position)) (#_delete old-item)) (setf (line-items hunk position) nil)) (defun update-modeline-items (scene hunk dl) (let* ((position (+ (dis-line-position dl) (device-hunk-text-height hunk))) (h (slot-value hunk 'ch)) #+nil (w (slot-value hunk 'cw)) (widget (qt-hunk-widget hunk)) (offset (truncate (offset-on-each-side widget))) (chrs (dis-line-chars dl)) (y (* position h))) (unless (zerop (dis-line-flags dl)) (setf (hi::dis-line-tick dl) (incf *tick*))) (clear-line-items scene hunk position) (with-objects ((pen (#_new QPen (#_Qt::NoPen))) (color (#_new QColor 255 255 255 210)) (oops (#_new QBrush color)) (brush (#_new QBrush oops)) (rect (#_new QRectF (- (+ offset *gutter*)) y (#_width widget) h))) (let ((item (#_new QGraphicsRectItem rect (ensure-hunk-item-group scene hunk)))) (qt::cancel-finalization item) (#_setPen item pen) (#_setBrush item brush) (#_setZValue item 0) (push item (line-items hunk position)))) (let ((len (dis-line-length dl))) (push (add-chunk-item scene hunk chrs 0 (+ 1 y) 0 len 0 *modeline-font*) (line-items hunk position)))) (setf (dis-line-flags dl) unaltered-bits (dis-line-delta dl) 0)) (defun update-line-items (scene hunk dl) (let* ((position (dis-line-position dl)) (h (slot-value hunk 'ch)) (w (slot-value hunk 'cw)) (chrs (dis-line-chars dl)) (y (* position h))) (unless (zerop (dis-line-flags dl)) (setf (hi::dis-line-tick dl) (incf *tick*))) (clear-line-items scene hunk position) (handler-case (let* ((no (hi::tag-line-number (hi::dis-line-tag dl))) (str (princ-to-string no))) (push (add-chunk-item scene hunk str (- (+ (* w (length str)) (* 2 *gutter*))) (+ 1 y) 0 (length str) (if (zerop (mod no 5)) 16 15)) (line-items hunk position))) (error (c) (warn "~A" c))) (let ((start 0) (font 0) (end (dis-line-length dl)) (changes (dis-line-font-changes dl))) (iter (cond ((null changes) (push (add-chunk-item scene hunk chrs (* w start) (+ 1 y) start end font) (line-items hunk position)) (return)) (t (push (add-chunk-item scene hunk chrs (* w start) (+ 1 y) start (font-change-x changes) font) (line-items hunk position)) (setf font (font-change-font changes) start (font-change-x changes) changes (font-change-next changes))))))) (setf (dis-line-flags dl) unaltered-bits (dis-line-delta dl) 0)) (defun clear-all-line-items (scene hunk) (with-slots (itab) hunk (iter (for i from 0) (for items in-vector itab) (dolist (old-item items) (#_removeItem scene old-item)) (setf (elt itab i) nil)))) (defun reset-hunk-background (window hunk) (declare (ignore window)) (let* ((widget (qt-hunk-widget hunk)) (scene (#_scene widget))) (dolist (item (hunk-background-items hunk)) (#_delete item)) (setf (hunk-background-items hunk) (when (qt-hunk-want-background-p hunk) (let ((offset (offset-on-each-side widget))) (with-objects ((pen1 (#_new QPen (#_Qt::SolidLine))) (pen2 (#_new QPen (#_Qt::NoPen))) (color1 (#_new QColor 255 255 255 210)) (color2 (#_new QColor 255 255 255 128)) (oops1 (#_new QBrush color1)) (oops2 (#_new QBrush color2)) (brush1 (#_new QBrush oops1)) (brush2 (#_new QBrush oops2)) (rect1 (#_new QRectF (- (+ (* 2 *gutter*) (truncate offset 2))) (- *gutter*) (+ (- (#_width widget) offset) (* 2 *gutter*)) (+ (* (slot-value hunk 'ch) (device-hunk-height hunk)) (* 2 *gutter*)))) (rect2 (#_new QRectF rect1))) (#_setColor pen1 (#_new QColor (#_Qt::black))) (#_adjust rect2 -5 -5 5 5) (let* ((group (ensure-hunk-item-group scene hunk)) (item1 (#_new QGraphicsRectItem rect1 group)) (item2 (#_new QGraphicsRectItem rect2 group))) (qt::cancel-finalization item1) (qt::cancel-finalization item2) (#_setPen item1 pen1) (#_setPen item2 pen2) (#_setBrush item1 brush1) (#_setBrush item2 brush2) (#_setZValue item1 1) (#_setZValue item2 1) (#_setZValue group 3) (list item1 item2)))))))) Smart is n't very smart , but still much better for " a single line changed " (defun dumb-or-smart-redisplay (device window dumb) (declare (ignore device)) (let* ((widget (qt-hunk-widget (window-hunk window))) (hunk (window-hunk window)) (first (window-first-line window)) (offset (truncate (offset-on-each-side widget))) (scene (#_scene widget))) (when dumb (reset-hunk-background window hunk) (clear-all-line-items scene hunk)) (let* ((native-widget (hi::buffer-widget (window-buffer window))) (current-item (hunk-native-widget-item hunk)) (current-widget (and current-item (#_widget current-item)))) (unless (eq native-widget current-widget) (let ((group (ensure-hunk-item-group scene hunk))) (when current-item (setf (hunk-native-widget-item hunk) nil) (#_setWidget current-item (qt::null-qobject "QWidget")) (#_delete current-item)) (when native-widget (let ((item (#_new QGraphicsProxyWidget))) (#_setParent native-widget (qt::null-qobject "QWidget")) (#_setWidget item native-widget) (#_setParentItem item group) (#_setPos item (- offset) 0) (#_setZValue item 4) (#_setFocusPolicy native-widget (#_Qt::StrongFocus)) (#_setGeometry native-widget (- (+ offset)) 0 (- (#_width widget) (* 2 *gutter*)) (* (slot-value hunk 'ch) (device-hunk-text-height hunk))) #+nil (#_setTransform item (#_scale (#_rotate (#_new QTransform) 10) 0.75 0.75) nil) (setf (hunk-native-widget-item hunk) item)))))) (let ((pos (dis-line-position (car (window-last-line window)))) (old (window-old-lines window))) (when (and pos old) (iter:iter (iter:for i from (1+ pos) to old) (clear-line-items scene hunk i))) (setf (window-old-lines window) pos)) (do ((i 0 (1+ i)) (dl (cdr first) (cdr dl))) ((eq dl the-sentinel) (setf (window-old-lines window) (1- i))) (let ((dis-line (car dl))) (hi::sync-dis-line-tag (hi::dis-line-line dis-line) dis-line) (when (or dumb (plusp (dis-line-flags dis-line))) (update-line-items scene hunk dis-line)))) (when (window-modeline-buffer window) (update-modeline-fields (window-buffer window) window) (let ((dl (window-modeline-dis-line window))) (update-modeline-items scene hunk dl) (setf (dis-line-flags dl) unaltered-bits)) (setf (dis-line-flags (window-modeline-dis-line window)) unaltered-bits))) (let* ((first (window-first-line window)) #+nil (device (device-hunk-device hunk))) (setf (window-first-changed window) the-sentinel (window-last-changed window) first))) (defun ensure-hunk-item-group (scene hunk) (or (hunk-item-group hunk) (setf (hunk-item-group hunk) (let ((g (#_new QGraphicsItemGroup))) (#_addItem scene g) (qt::cancel-finalization g) g)))) (defun add-chunk-item (scene hunk string x y start end font-color &optional (font *font*)) (let* ((item (#_new QGraphicsSimpleTextItem (ensure-hunk-item-group scene hunk))) (widget (qt-hunk-widget hunk)) (offset (truncate (offset-on-each-side widget)))) (qt::cancel-finalization item) ( # _ setPos ( hunk - item - group hunk ) 50 50 ) (with-objects ((t2 (#_translate (#_new QTransform) (+ offset *gutter*) (+ *gutter* (* (slot-value hunk 'ch) (- (device-hunk-position hunk) (device-hunk-height hunk)))))))) (#_setTransform (hunk-item-group hunk) t2 nil)) (#_setText item (subseq string start end)) (#_setFont item font) (let ((color #x000000 #xffffff 1 = comments 2 = backquote 3 = unquote 4 = strings 5 = quote 6 = # + 7 = # - #x000000 #xbebebe #xff0000 #xbebebe #x00aa00 #xbebebe #xffff00 #xbebebe #x0000ff #xbebebe #xff00ff #xbebebe #x00ffff #xbebebe #xbebebe #x000000 #xffffff #x000000) (* 2 (mod font-color 17))))) (with-objects ((color (#_new QColor (ldb (byte 8 16) color) (ldb (byte 8 8) color) (ldb (byte 8 0) color))) (brush (#_new QBrush color))) (#_setBrush item brush))) (#_setPos item x y) (#_setZValue item 2) item)) (defun make-virtual-buffer (name widget &rest args) (let ((buffer (apply #'make-buffer name args))) (when buffer (setf (buffer-writable buffer) nil) (setf (hi::buffer-widget buffer) widget) buffer))) (defcommand "Enter Foreign Widget" (p) "" "" (declare (ignore p)) (let ((widget (hi::buffer-widget (current-buffer)))) (unless widget (editor-error "Not a foreign widget.")) (setf *steal-focus-out* nil) (#_setFocus widget) (clear-echo-area) (message "Focus set to foreign widget. Type C-g to go back."))) (defcommand "Leave Foreign Widget" (p) "Like control-g-handler, except for the C-g behaviour." "" (declare (ignore p)) (let ((main *main-hunk-widget*)) (unless (#_hasFocus main) (setf *steal-focus-out* t) (#_setFocus main) (clear-echo-area) (message "Focus restored. Welcome back to Hemlock.")))) (defcommand "Disable Steal Focus" (p) "" "" (declare (ignore p)) (setf *steal-focus-out* nil) (message "Focus stealing disabled")) (defcommand "Enable Steal Focus" (p) "" "" (declare (ignore p)) (setf *steal-focus-out* t) (#_setFocus *main-hunk-widget*)) #+nil (defcommand "Abc" (p) "" "" (let ((w (qt-hunk-item (window-hunk (current-window))))) (#_setZValue w 500) (#_setTransform (let* ((old (qt::qobject-class w)) (old-ptr (qt::qobject-pointer w)) (new (qt::find-qclass "QGraphicsItem")) (new-ptr (qt::%cast old-ptr (qt::unbash old) (qt::unbash new)))) (make-instance 'qt::qobject :class new :pointer new-ptr)) (#_translate (if p (#_rotate (#_scale (#_new QTransform) 0.75 0.75) 45) (#_new QTransform)) 200 0) nil))) (defcommand "Toggle Tab Bar" (p) "" "" (#_setVisible *tabs* (not (#_isVisible *tabs*)))) (defun main-window () (#_window (qt-hunk-widget (window-hunk (current-window))))) (defcommand "Toggle Menu Bar" (p) "" "" (let ((menubar (#_menuBar (main-window)))) (#_setVisible menubar (not (#_isVisible menubar))))) (defcommand "Toggle Full Screen" (p) "" "" (let ((win (main-window))) (if (logtest (#_windowState win) (primitive-value (#_Qt::WindowFullScreen))) (#_showNormal win) (#_showFullScreen win)))) #+nil (defcommand "Def" (p) "" "" (let* ((widget (#_new QWebView)) (w (#_addWidget (#_scene (qt-hunk-widget (window-hunk (current-window)))) widget))) (push widget *do-not-gc-list*) (push w *do-not-gc-list*) (#_setUrl widget (#_new QUrl "")) #+nil (#_setZValue w 500) #+nil (let* ((new-class (qt::find-qclass "QGraphicsItem")) (new-ptr (qt::%cast w new-class))) (make-instance 'qt::qobject :class new-class :pointer new-ptr)) (#_setTransform w #+nil (#_translate (#_new QTransform) 1 2) (#_translate (if p (#_rotate (#_scale (#_new QTransform) 0.75 0.75) 45) (#_new QTransform)) 400 0) nil)))
9afba6151966eb15a1cbfd80c912a979bf83dcaa2bc9391e03b2333af4e2ac3b
tsloughter/kuberl
kuberl_v1beta1_supplemental_groups_strategy_options.erl
-module(kuberl_v1beta1_supplemental_groups_strategy_options). -export([encode/1]). -export_type([kuberl_v1beta1_supplemental_groups_strategy_options/0]). -type kuberl_v1beta1_supplemental_groups_strategy_options() :: #{ 'ranges' => list(), 'rule' => binary() }. encode(#{ 'ranges' := Ranges, 'rule' := Rule }) -> #{ 'ranges' => Ranges, 'rule' => Rule }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_supplemental_groups_strategy_options.erl
erlang
-module(kuberl_v1beta1_supplemental_groups_strategy_options). -export([encode/1]). -export_type([kuberl_v1beta1_supplemental_groups_strategy_options/0]). -type kuberl_v1beta1_supplemental_groups_strategy_options() :: #{ 'ranges' => list(), 'rule' => binary() }. encode(#{ 'ranges' := Ranges, 'rule' := Rule }) -> #{ 'ranges' => Ranges, 'rule' => Rule }.
b8e98a3fd943cfbb44179a214096180d9ec3644b70f4422557dc685b9e76a361
LambdaHack/LambdaHack
SessionUIUnitTests.hs
module SessionUIUnitTests (macroTests) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Data.Map.Strict as M import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck import qualified Game.LambdaHack.Client.UI.Content.Input as IC import qualified Game.LambdaHack.Client.UI.HumanCmd as HumanCmd import qualified Game.LambdaHack.Client.UI.Key as K import Game.LambdaHack.Client.UI.SessionUI import qualified Client.UI.Content.Input as Content.Input import SessionUIMock Run @test -p " In - game " --quickcheck - verbose@ to verify that quickcheck -- properties are not too often satisfied voidly. macroTests :: TestTree macroTests = testGroup "macroTests" $ let coinput = IC.makeData Nothing Content.Input.standardKeysAndMouse stringToKeyMacro = KeyMacro . map (K.mkKM . (: [])) listToKeyMacro = KeyMacro . map K.mkKM bindInput l input = let ltriple = M.fromList $ map (\(k, ks) -> (K.mkKM k, ([], "", HumanCmd.Macro $ map (: []) ks))) l in input {IC.bcmdMap = M.union ltriple $ IC.bcmdMap input} in [ testCase "Macro 1 from PR#192 description" $ fst <$> unwindMacros coinput (stringToKeyMacro "'j''j'") @?= [ [ (Right "", "'j''j'", "") ] , [ (Left "", "j''j'", "") ] , [ (Left "j", "''j'", "j") ] , [ (Right "j", "'j'", "j") ] , [ (Left "", "j'", "j") ] , [ (Left "j", "'", "j") ] , [ (Right "j", "", "j") ] ] , testCase "Macro 1 from Issue#189 description" $ snd (last (unwindMacros (bindInput [ ("a", "'bc'V") , ("c", "'aaa'V") ] coinput) (stringToKeyMacro "a"))) @?= "Macro looped" , testCase "Macro 2 from Issue#189 description" $ snd (last (unwindMacros (bindInput [("a", "'x'")] coinput) (stringToKeyMacro "'a'"))) @?= "x" , testCase "Macro 3 from Issue#189 description" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x''x'"))) @?= "xx" , testCase "Macro 4 from Issue#189 description" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x''x'V"))) @?= "xxx" , testCase "Macro 5 from Issue#189 description" $ snd (last (unwindMacros coinput (stringToKeyMacro "x'x'V"))) @?= "xxx" , testCase "Macro test 10" $ snd (last (unwindMacros coinput (stringToKeyMacro "x'y'V"))) @?= "xyy" , testCase "Macro test 11" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x''y'V"))) @?= "xyy" , testCase "Macro test 12" $ snd (last (unwindMacros coinput (listToKeyMacro ["x", "C-V"]))) @?= "x" , testCase "Macro test 13" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "C-V"]))) @?= "xxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "Macro test 14" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "y", "C-V"]))) @?= "xyxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "Macro test 15" $ snd (last (unwindMacros (bindInput [("a", "x")] coinput) (stringToKeyMacro "'a'V"))) @?= "xx" , testCase "Macro test 16" $ snd (last (unwindMacros (bindInput [("a", "'x'")] coinput) (stringToKeyMacro "'a'V"))) @?= "xx" , testCase "Macro test 17" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "a"))) @?= "xx" , testCase "Macro test 18" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "'a'"))) @?= "xx" , testCase "Macro test 19" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "'a'V"))) @?= "xxxx" , testCase "Macro test 20" $ snd (last (unwindMacros (bindInput [ ("a", "'bz'V") , ("c", "'aaa'V") ] coinput) (stringToKeyMacro "c"))) @?= "bzbzbzbzbzbzbzbzbzbzbzbz" , testCase "RepeatLast test 10" $ snd (last (unwindMacros coinput (stringToKeyMacro "x'y'v"))) @?= "xyy" , testCase "RepeatLast test 11" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x'yv"))) @?= "xyy" , testCase "RepeatLast test 12" $ snd (last (unwindMacros coinput (listToKeyMacro ["v", "C-v"]))) @?= "" , testCase "RepeatLast test 13" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "C-v"]))) @?= "xxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "RepeatLast test 14" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "V", "C-v"]))) @?= "xxxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "RepeatLast test 15" $ snd (last (unwindMacros (bindInput [("a", "x")] coinput) (stringToKeyMacro "av"))) @?= "xx" , testCase "RepeatLast test 16" $ snd (last (unwindMacros (bindInput [("a", "'x'")] coinput) (stringToKeyMacro "'a'v"))) @?= "xx" , testCase "RepeatLast test 17" $ snd (last (unwindMacros (bindInput [("a", "'x'v")] coinput) (stringToKeyMacro "a"))) @?= "xx" , testCase "RepeatLast test 18" $ snd (last (unwindMacros (bindInput [("a", "'x'v")] coinput) (stringToKeyMacro "'a'"))) @?= "xx" , testCase "RepeatLast test 19" $ snd (last (unwindMacros (bindInput [("a", "'x'v")] coinput) (stringToKeyMacro "'a'v"))) @?= "xxxx" , testCase "RepeatLast test 20" $ snd (last (unwindMacros (bindInput [ ("a", "'bz'v") , ("c", "'aaa'v") ] coinput) (stringToKeyMacro "c"))) @?= "bzzbzzbzzbzz" , testCase "RepeatLast test 21" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "'a'v"))) @?= "xxxx" , testCase "RepeatLast test 22" $ snd (last (unwindMacros (bindInput [("a", "'xy'V")] coinput) (stringToKeyMacro "'aa'v"))) @?= "xyxyxyxyxyxy" , testCase "RepeatLast test 23" $ snd (last (unwindMacros (bindInput [("a", "'xy'v")] coinput) (stringToKeyMacro "'aa'V"))) @?= "xyyxyyxyyxyy" , testCase "RepeatLast test 24" $ snd (last (unwindMacros (bindInput [("a", "'xy'vv")] coinput) (stringToKeyMacro "'aa'vv"))) @?= "xyyyxyyyxyyyxyyy" , testCase "RepeatLast test 25" $ snd (last (unwindMacros (bindInput [("a", "'xyv'v")] coinput) (stringToKeyMacro "'a'a'vv'"))) @?= "xyyyxyyyxyyyxyyy" , testCase "RepeatLast test 26" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'v") , ("c", "'ab'v") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyxyyzxyyxyyxyyzxyyxyyzxyyxyy" , testCase "RepeatLast test 27" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'V") , ("b", "'za'v") , ("c", "'ab'v") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyxyzxyxyxyxyzxyxyxyxyxyxyzxyxyxyxyzxyxyxyxy" , testCase "RepeatLast test 28" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") , ("c", "'ab'v") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyzxyyzxyyzxyyxyyzxyyzxyyzxyyzxyy" , testCase "RepeatLast test 29" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") , ("c", "'ab'V") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 30" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") , ("c", "'ab'V") ] coinput) (stringToKeyMacro "'c'V"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 31" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'v") , ("c", "'ab'V") ] coinput) (stringToKeyMacro "'c'V"))) @?= "xyyzxyyxyyxyyzxyyxyyxyyzxyyxyyxyyzxyyxyy" , testCase "RepeatLast test 32" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'v") ] coinput) (stringToKeyMacro "'ab'vv"))) @?= "xyyzxyyxyyzxyyxyyzxyyxyy" , testCase "RepeatLast test 33" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'V") ] coinput) (stringToKeyMacro "a'za'vvv"))) @?= "xyxyzxyxyxyxyxyxyxyxy" , testCase "RepeatLast test 34" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("c", "a'za'Vv") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyzxyyzxyyxyyzxyyzxyyzxyy" , testCase "RepeatLast test 35" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") ] coinput) (stringToKeyMacro "'ab'Vv"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 36" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "za'za'") ] coinput) (stringToKeyMacro "'ab'V'ab'V"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 37" $ snd (last (unwindMacros (bindInput [ ("b", "z'xy'vv") , ("c", "'xyvb'V") ] coinput) (stringToKeyMacro "'c'V"))) @?= "xyyzxyyyxyyzxyyyxyyzxyyyxyyzxyyy" , testCase "RepeatLast test 38" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xv'V"))) @?= "xxxx" , testCase "RepeatLast test 39" $ fst <$> unwindMacros coinput (stringToKeyMacro "'xv'V") @?= [[(Right "", "'xv'V", "")], [(Left "", "xv'V", "")], [(Left "x", "v'V", "x")], [(Left "x", "x'V", "x")], [(Left "xx", "'V", "x")], [(Right "xx", "V", "x")], [(Right "", "xx", ""), (Right "xx", "", "V")], [(Right "", "x", "x"), (Right "xx", "", "V")], [(Right "xx", "", "V")]] , testCase "RepeatLast test 40" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xy'Vv"))) @?= "xyxyxy" , testCase "RepeatLast test 41; named macros not referentially transparent" $ snd (last (unwindMacros (bindInput [("a", "'xy'V")] coinput) (stringToKeyMacro "av"))) @?= "xyxyxyxy" -- because @a@ repeated; good! , testCase "RepeatLast test 42" $ snd (last (unwindMacros (bindInput [("a", "xy")] coinput) (stringToKeyMacro "'a'Vv"))) because @V@ repeated ; good ! , testCase "RepeatLast test 43" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xyV'V"))) @?= "xyxy" , testCase "RepeatLast test 44" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xyV'v"))) @?= "xyxy" , testCase "RepeatLast test 45" $ snd (last (unwindMacros (bindInput [("a", "xyV")] coinput) (stringToKeyMacro "'a'V"))) @?= "xyxy" , testCase "RepeatLast test 46" $ snd (last (unwindMacros (bindInput [("a", "xyV")] coinput) (stringToKeyMacro "'a'v"))) @?= "xyxy" , testProperty "In-game macro and equivalent predefined macro agree" $ forAll (listOf (elements "`ABvV")) $ \macro -> let bindings = bindInput [("a", macro)] coinput inGameResult = snd (last (unwindMacros coinput (stringToKeyMacro macro))) in inGameResult === snd (last (unwindMacros bindings (stringToKeyMacro "a"))) .&&. inGameResult =/= "Macro looped" -- may not loop , testProperty "In-game and predefined with limited minimal bindings" $ forAll (listOf (elements "````''''ABCABCABCABCvVvVvVa")) $ -- may loop \macro -> let bindings = bindInput [("a", macro)] coinput in snd (last (unwindMacros bindings (stringToKeyMacro macro))) === snd (last (unwindMacros bindings (stringToKeyMacro "a"))) , testProperty "In-game and predefined with limited multiple bindings" $ forAll (listOf (elements "```ABCDvVabccc")) $ \macro -> -- The macros may still loop due to mutual recursion, -- even though direct recursion is ruled out by filtering. let macroA = filter (/= 'a') macro macroB = filter (/= 'b') $ take 5 $ reverse macro bindings = bindInput [ ("a", macroA) , ("b", macroB) , ("c", "A'B''CD'") ] coinput in snd (last (unwindMacros bindings (stringToKeyMacro macroA))) === snd (last (unwindMacros bindings (stringToKeyMacro "a"))) ]
null
https://raw.githubusercontent.com/LambdaHack/LambdaHack/5b3773967479dd031eff440e7ca7132a6c795df2/test/SessionUIUnitTests.hs
haskell
quickcheck - verbose@ to verify that quickcheck properties are not too often satisfied voidly. because @a@ repeated; good! may not loop may loop The macros may still loop due to mutual recursion, even though direct recursion is ruled out by filtering.
module SessionUIUnitTests (macroTests) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Data.Map.Strict as M import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck import qualified Game.LambdaHack.Client.UI.Content.Input as IC import qualified Game.LambdaHack.Client.UI.HumanCmd as HumanCmd import qualified Game.LambdaHack.Client.UI.Key as K import Game.LambdaHack.Client.UI.SessionUI import qualified Client.UI.Content.Input as Content.Input import SessionUIMock macroTests :: TestTree macroTests = testGroup "macroTests" $ let coinput = IC.makeData Nothing Content.Input.standardKeysAndMouse stringToKeyMacro = KeyMacro . map (K.mkKM . (: [])) listToKeyMacro = KeyMacro . map K.mkKM bindInput l input = let ltriple = M.fromList $ map (\(k, ks) -> (K.mkKM k, ([], "", HumanCmd.Macro $ map (: []) ks))) l in input {IC.bcmdMap = M.union ltriple $ IC.bcmdMap input} in [ testCase "Macro 1 from PR#192 description" $ fst <$> unwindMacros coinput (stringToKeyMacro "'j''j'") @?= [ [ (Right "", "'j''j'", "") ] , [ (Left "", "j''j'", "") ] , [ (Left "j", "''j'", "j") ] , [ (Right "j", "'j'", "j") ] , [ (Left "", "j'", "j") ] , [ (Left "j", "'", "j") ] , [ (Right "j", "", "j") ] ] , testCase "Macro 1 from Issue#189 description" $ snd (last (unwindMacros (bindInput [ ("a", "'bc'V") , ("c", "'aaa'V") ] coinput) (stringToKeyMacro "a"))) @?= "Macro looped" , testCase "Macro 2 from Issue#189 description" $ snd (last (unwindMacros (bindInput [("a", "'x'")] coinput) (stringToKeyMacro "'a'"))) @?= "x" , testCase "Macro 3 from Issue#189 description" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x''x'"))) @?= "xx" , testCase "Macro 4 from Issue#189 description" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x''x'V"))) @?= "xxx" , testCase "Macro 5 from Issue#189 description" $ snd (last (unwindMacros coinput (stringToKeyMacro "x'x'V"))) @?= "xxx" , testCase "Macro test 10" $ snd (last (unwindMacros coinput (stringToKeyMacro "x'y'V"))) @?= "xyy" , testCase "Macro test 11" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x''y'V"))) @?= "xyy" , testCase "Macro test 12" $ snd (last (unwindMacros coinput (listToKeyMacro ["x", "C-V"]))) @?= "x" , testCase "Macro test 13" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "C-V"]))) @?= "xxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "Macro test 14" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "y", "C-V"]))) @?= "xyxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "Macro test 15" $ snd (last (unwindMacros (bindInput [("a", "x")] coinput) (stringToKeyMacro "'a'V"))) @?= "xx" , testCase "Macro test 16" $ snd (last (unwindMacros (bindInput [("a", "'x'")] coinput) (stringToKeyMacro "'a'V"))) @?= "xx" , testCase "Macro test 17" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "a"))) @?= "xx" , testCase "Macro test 18" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "'a'"))) @?= "xx" , testCase "Macro test 19" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "'a'V"))) @?= "xxxx" , testCase "Macro test 20" $ snd (last (unwindMacros (bindInput [ ("a", "'bz'V") , ("c", "'aaa'V") ] coinput) (stringToKeyMacro "c"))) @?= "bzbzbzbzbzbzbzbzbzbzbzbz" , testCase "RepeatLast test 10" $ snd (last (unwindMacros coinput (stringToKeyMacro "x'y'v"))) @?= "xyy" , testCase "RepeatLast test 11" $ snd (last (unwindMacros coinput (stringToKeyMacro "'x'yv"))) @?= "xyy" , testCase "RepeatLast test 12" $ snd (last (unwindMacros coinput (listToKeyMacro ["v", "C-v"]))) @?= "" , testCase "RepeatLast test 13" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "C-v"]))) @?= "xxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "RepeatLast test 14" $ snd (last (unwindMacros coinput (listToKeyMacro ["'", "x", "'", "V", "C-v"]))) @?= "xxxxxxxxxxxxxxxxxxxxxxxxxxx" , testCase "RepeatLast test 15" $ snd (last (unwindMacros (bindInput [("a", "x")] coinput) (stringToKeyMacro "av"))) @?= "xx" , testCase "RepeatLast test 16" $ snd (last (unwindMacros (bindInput [("a", "'x'")] coinput) (stringToKeyMacro "'a'v"))) @?= "xx" , testCase "RepeatLast test 17" $ snd (last (unwindMacros (bindInput [("a", "'x'v")] coinput) (stringToKeyMacro "a"))) @?= "xx" , testCase "RepeatLast test 18" $ snd (last (unwindMacros (bindInput [("a", "'x'v")] coinput) (stringToKeyMacro "'a'"))) @?= "xx" , testCase "RepeatLast test 19" $ snd (last (unwindMacros (bindInput [("a", "'x'v")] coinput) (stringToKeyMacro "'a'v"))) @?= "xxxx" , testCase "RepeatLast test 20" $ snd (last (unwindMacros (bindInput [ ("a", "'bz'v") , ("c", "'aaa'v") ] coinput) (stringToKeyMacro "c"))) @?= "bzzbzzbzzbzz" , testCase "RepeatLast test 21" $ snd (last (unwindMacros (bindInput [("a", "'x'V")] coinput) (stringToKeyMacro "'a'v"))) @?= "xxxx" , testCase "RepeatLast test 22" $ snd (last (unwindMacros (bindInput [("a", "'xy'V")] coinput) (stringToKeyMacro "'aa'v"))) @?= "xyxyxyxyxyxy" , testCase "RepeatLast test 23" $ snd (last (unwindMacros (bindInput [("a", "'xy'v")] coinput) (stringToKeyMacro "'aa'V"))) @?= "xyyxyyxyyxyy" , testCase "RepeatLast test 24" $ snd (last (unwindMacros (bindInput [("a", "'xy'vv")] coinput) (stringToKeyMacro "'aa'vv"))) @?= "xyyyxyyyxyyyxyyy" , testCase "RepeatLast test 25" $ snd (last (unwindMacros (bindInput [("a", "'xyv'v")] coinput) (stringToKeyMacro "'a'a'vv'"))) @?= "xyyyxyyyxyyyxyyy" , testCase "RepeatLast test 26" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'v") , ("c", "'ab'v") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyxyyzxyyxyyxyyzxyyxyyzxyyxyy" , testCase "RepeatLast test 27" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'V") , ("b", "'za'v") , ("c", "'ab'v") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyxyzxyxyxyxyzxyxyxyxyxyxyzxyxyxyxyzxyxyxyxy" , testCase "RepeatLast test 28" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") , ("c", "'ab'v") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyzxyyzxyyzxyyxyyzxyyzxyyzxyyzxyy" , testCase "RepeatLast test 29" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") , ("c", "'ab'V") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 30" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") , ("c", "'ab'V") ] coinput) (stringToKeyMacro "'c'V"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 31" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'v") , ("c", "'ab'V") ] coinput) (stringToKeyMacro "'c'V"))) @?= "xyyzxyyxyyxyyzxyyxyyxyyzxyyxyyxyyzxyyxyy" , testCase "RepeatLast test 32" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'v") ] coinput) (stringToKeyMacro "'ab'vv"))) @?= "xyyzxyyxyyzxyyxyyzxyyxyy" , testCase "RepeatLast test 33" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'V") ] coinput) (stringToKeyMacro "a'za'vvv"))) @?= "xyxyzxyxyxyxyxyxyxyxy" , testCase "RepeatLast test 34" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("c", "a'za'Vv") ] coinput) (stringToKeyMacro "'c'v"))) @?= "xyyzxyyzxyyzxyyxyyzxyyzxyyzxyy" , testCase "RepeatLast test 35" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "'za'V") ] coinput) (stringToKeyMacro "'ab'Vv"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 36" $ snd (last (unwindMacros (bindInput [ ("a", "'xy'v") , ("b", "za'za'") ] coinput) (stringToKeyMacro "'ab'V'ab'V"))) @?= "xyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyyxyyzxyyzxyy" , testCase "RepeatLast test 37" $ snd (last (unwindMacros (bindInput [ ("b", "z'xy'vv") , ("c", "'xyvb'V") ] coinput) (stringToKeyMacro "'c'V"))) @?= "xyyzxyyyxyyzxyyyxyyzxyyyxyyzxyyy" , testCase "RepeatLast test 38" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xv'V"))) @?= "xxxx" , testCase "RepeatLast test 39" $ fst <$> unwindMacros coinput (stringToKeyMacro "'xv'V") @?= [[(Right "", "'xv'V", "")], [(Left "", "xv'V", "")], [(Left "x", "v'V", "x")], [(Left "x", "x'V", "x")], [(Left "xx", "'V", "x")], [(Right "xx", "V", "x")], [(Right "", "xx", ""), (Right "xx", "", "V")], [(Right "", "x", "x"), (Right "xx", "", "V")], [(Right "xx", "", "V")]] , testCase "RepeatLast test 40" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xy'Vv"))) @?= "xyxyxy" , testCase "RepeatLast test 41; named macros not referentially transparent" $ snd (last (unwindMacros (bindInput [("a", "'xy'V")] coinput) (stringToKeyMacro "av"))) , testCase "RepeatLast test 42" $ snd (last (unwindMacros (bindInput [("a", "xy")] coinput) (stringToKeyMacro "'a'Vv"))) because @V@ repeated ; good ! , testCase "RepeatLast test 43" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xyV'V"))) @?= "xyxy" , testCase "RepeatLast test 44" $ snd (last (unwindMacros coinput (stringToKeyMacro "'xyV'v"))) @?= "xyxy" , testCase "RepeatLast test 45" $ snd (last (unwindMacros (bindInput [("a", "xyV")] coinput) (stringToKeyMacro "'a'V"))) @?= "xyxy" , testCase "RepeatLast test 46" $ snd (last (unwindMacros (bindInput [("a", "xyV")] coinput) (stringToKeyMacro "'a'v"))) @?= "xyxy" , testProperty "In-game macro and equivalent predefined macro agree" $ forAll (listOf (elements "`ABvV")) $ \macro -> let bindings = bindInput [("a", macro)] coinput inGameResult = snd (last (unwindMacros coinput (stringToKeyMacro macro))) in inGameResult === snd (last (unwindMacros bindings (stringToKeyMacro "a"))) , testProperty "In-game and predefined with limited minimal bindings" $ \macro -> let bindings = bindInput [("a", macro)] coinput in snd (last (unwindMacros bindings (stringToKeyMacro macro))) === snd (last (unwindMacros bindings (stringToKeyMacro "a"))) , testProperty "In-game and predefined with limited multiple bindings" $ forAll (listOf (elements "```ABCDvVabccc")) $ \macro -> let macroA = filter (/= 'a') macro macroB = filter (/= 'b') $ take 5 $ reverse macro bindings = bindInput [ ("a", macroA) , ("b", macroB) , ("c", "A'B''CD'") ] coinput in snd (last (unwindMacros bindings (stringToKeyMacro macroA))) === snd (last (unwindMacros bindings (stringToKeyMacro "a"))) ]
1a3b74d67962ad0bca5ea8c5a967a67a1046c21017b75d5a2e8f91608ff798c0
wilbowma/cur
info.rkt
#lang info (define collection 'multi) (define deps '("cur-lib" "cur-doc" "cur-test")) (define implies '("cur-lib" "cur-doc" "cur-test")) (define pkg-desc "Dependent types with parenthesis and meta-programming.") (define pkg-authors '(wilbowma))
null
https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur/info.rkt
racket
#lang info (define collection 'multi) (define deps '("cur-lib" "cur-doc" "cur-test")) (define implies '("cur-lib" "cur-doc" "cur-test")) (define pkg-desc "Dependent types with parenthesis and meta-programming.") (define pkg-authors '(wilbowma))
f9f80c4d9a2160bf9d9b3f6e21add70e1b4c90b1801700701ed2188990819860
magnolia-lang/magnolia-lang
PPrint.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -Wno - orphans # module Magnolia.PPrint (pprint, pprintList, pshow, render) where import Control.Monad (join) import qualified Data.List.NonEmpty as NE import qualified Data.Map as M import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as TIO import Prettyprinter import Prettyprinter.Render.Text import Data.Void (absurd) import Backend import Env import Err import Magnolia.Syntax -- The below pprinting and error-handling related utils are directly inspired from their equivalent in -research/dex-lang . p :: Pretty a => a -> Doc ann p = pretty -- TODO: Text.Lazy -> Text.Strict (renderLazy -> renderStrict) pprint :: Pretty a => a -> IO () pprint = printDoc . p printDoc :: Doc ann -> IO () printDoc = TIO.putStrLn . render render :: Doc ann -> T.Text render = renderLazy . layoutPretty defaultLayoutOptions pshow :: Pretty a => a -> T.Text pshow = render . p pprintList :: Pretty a => [a] -> IO () pprintList = printDoc . vsep . punctuate line . map p instance Pretty Err where -- TODO: change error to have error types pretty (Err errType src parentScopes txt) = p src <> ":" <+> p errType <> (case parentScopes of [] -> "" ps -> " in " <> concatWith (surround dot) (map p ps)) <> ":" <+> p txt instance Pretty SrcCtx where pretty (SrcCtx msrcInfo) = case msrcInfo of Nothing -> "<unknown location>" Just ((filename, startLine, startColumn), _) -> p filename <> ":" <> p startLine <> ":" <> p startColumn instance Pretty ErrType where pretty e = case e of AmbiguousFunctionRefErr -> ambiguous "functions" AmbiguousTopLevelRefErr -> ambiguous "top-level references" AmbiguousProcedureRefErr -> ambiguous "procedures" CompilerErr -> "Compiler bug!" <> line <> "Please report this at github.com/magnolia-lang/magnolia-lang" <> line CyclicErr -> "Error: found cyclic dependency" DeclContextErr -> "Declaration context error" InvalidDeclErr -> "Declaration error" MiscErr -> "Error" ModeMismatchErr -> "Mode error" NotImplementedErr -> "Not implemented" ParseErr -> "Parse error" TypeErr -> "Type error" UnboundFunctionErr -> unbound "function" UnboundTopLevelErr -> unbound "top-level reference" UnboundNameErr -> unbound "name" UnboundProcedureErr -> unbound "procedure" UnboundTypeErr -> unbound "type" UnboundVarErr -> unbound "variable" where ambiguous s = "Error: could not disambiguate between" <+> s unbound s = "Error:" <+> s <+> "not in scope" instance Pretty Name where pretty (Name _ str) = p str instance Pretty NameSpace where pretty ns = (case ns of NSDirectory -> "directory" NSFunction -> "function" NSGenerated -> "generated" NSModule -> "module" NSPackage -> "package" NSProcedure -> "procedure" NSRenaming -> "renaming" NSSatisfaction -> "satisfaction" NSType -> "type" NSUnspecified -> "unspecified" NSVariable -> "variable") <+> "namespace" instance Pretty FullyQualifiedName where pretty (FullyQualifiedName mscopeName targetName) = maybe "" (\n -> p n <> ".") mscopeName <> p targetName instance (Show (e p), Pretty (e p)) => Pretty (Ann p e) where pretty = p . _elem instance Pretty (MPackage' PhCheck) where pretty (MPackage name decls deps) = let importHeader = case deps of [] -> "" _ -> "imports" <+> align (vsep (punctuate comma (map p deps))) in "package" <+> p name <+> importHeader <+> ";" <> "\n\n" <> vsep (map p (join (M.elems decls))) instance Pretty (MPackageDep' PhCheck) where pretty (MPackageDep name) = p name instance Pretty (MTopLevelDecl PhCheck) where pretty decl = case decl of MNamedRenamingDecl namedRenaming -> p namedRenaming MModuleDecl modul -> p modul MSatisfactionDecl satisfaction -> p satisfaction instance Pretty (MNamedRenaming' PhCheck) where pretty (MNamedRenaming name block) = "renaming" <+> p name <+> "=" <+> p block instance Pretty (MSatisfaction' PhCheck) where TODO instance Pretty (MModule' PhCheck) where pretty (MModule moduleType name moduleExpr) = p moduleType <+> p name <+> "=" <+> p moduleExpr instance Pretty (MModuleExpr' PhCheck) where pretty (MModuleDef decls deps renamingBlocks) = lbrace <> line <> indent 4 (vsep (map p deps <> map ((<> semi) . p) (join (M.elems decls)))) <> line <> rbrace <> align (vsep $ map p renamingBlocks) pretty (MModuleRef v _) = absurd v pretty (MModuleAsSignature v _) = absurd v pretty (MModuleExternal backend fqn moduleExpr') = "external" <+> p backend <+> p fqn <+> p moduleExpr' instance Pretty (MModuleDep' PhCheck) where pretty (MModuleDep mmoduleDepType mmoduleDepModuleExpr) = p mmoduleDepType <+> p mmoduleDepModuleExpr instance Pretty MModuleDepType where pretty mmoduleDepType = case mmoduleDepType of MModuleDepRequire -> "require" MModuleDepUse -> "use" instance Pretty (MRenamingBlock' PhCheck) where pretty (MRenamingBlock renamingBlockTy renamings) = let content = hsep (punctuate comma (map p renamings)) in case renamingBlockTy of PartialRenamingBlock -> "[[" <> content <> "]]" TotalRenamingBlock -> brackets content instance Pretty (MRenaming' PhCheck) where pretty renaming = case renaming of InlineRenaming (src, tgt) -> p src <+> "=>" <+> p tgt RefRenaming v -> absurd v instance Pretty MModuleType where pretty typ = case typ of Signature -> "signature" Concept -> "concept" Implementation -> "implementation" Program -> "program" instance Pretty Backend where pretty backend = case backend of Cxx -> "C++" JavaScript -> "JavaScript" Python -> "Python" instance Pretty (MDecl PhCheck) where pretty decl = case decl of MTypeDecl modifiers tdecl -> hsep (map p modifiers) <+> pretty tdecl MCallableDecl modifiers cdecl -> hsep (map p modifiers) <+> pretty cdecl instance Pretty MModifier where pretty Require = "require" instance Pretty (MTypeDecl' p) where pretty (Type typ) = "type" <+> p typ instance Pretty (MCallableDecl' PhCheck) where pretty (Callable callableType name args ret mguard cbody) = let pret = if callableType == Function then " : " <> p ret else "" pbody = case cbody of EmptyBody -> "" MagnoliaBody body -> " = " <> p body ExternalBody () -> " = <external impl>;" BuiltinBody -> " (builtin);" pguard = case mguard of Nothing -> "" Just guard -> " guard " <> p guard in p callableType <+> p name <> prettyArgs <> pret <> pguard <> pbody where prettyArgs :: Doc ann prettyArgs = case callableType of Procedure -> parens $ hsep $ punctuate comma (map p args) _ -> parens $ hsep $ punctuate comma $ map (\(Ann _ a) -> p (nodeName a) <+> ":" <+> p (_varType a)) args instance Pretty MCallableType where pretty callableType = case callableType of Axiom -> "axiom" Function -> "function" Predicate -> "predicate" Procedure -> "procedure" instance Pretty (MExpr' p) where pretty e = pNoSemi e <> semi where pNoSemi :: MExpr' p -> Doc ann pNoSemi expr = case expr of MVar v -> p (nodeName v) MCall name args mcast -> let parglist = map (pNoSemi . _elem) args in p name <> parens (hsep (punctuate comma parglist)) <> (case mcast of Nothing -> ""; Just cast -> " : " <> p cast) MBlockExpr _ block -> vsep [ nest 4 (vsep ( "{" : map p (NE.toList block))) , "}" ] MValue expr' -> "value" <+> p expr' TODO : modes are for now ignore in MLet MLet (Ann _ (Var _ name mcast)) mass -> let pcast = case mcast of Nothing -> ""; Just cast -> " : " <> p cast pass = case mass of Nothing -> "" Just ass -> " = " <> pNoSemi (_elem ass) in "var" <+> p name <> pcast <> pass MIf cond etrue efalse -> align $ vsep [ "if" <+> p cond , "then" <+> p etrue , "else" <+> p efalse <+> "end" ] MAssert aexpr -> "assert" <+> pNoSemi (_elem aexpr) MSkip -> "skip" instance Pretty (MaybeTypedVar' p) where pretty (Var mode name mtyp) = case mtyp of Nothing -> p mode <+> p name Just typ -> p mode <+> p name <+> ":" <+> p typ instance Pretty (TypedVar' p) where pretty (Var mode name typ) = p mode <+> p name <+> ":" <+> p typ instance Pretty MVarMode where pretty mode = case mode of MObs -> "obs" MOut -> "out" MUnk -> "unk" MUpd -> "upd"
null
https://raw.githubusercontent.com/magnolia-lang/magnolia-lang/ff29126a72c9f7bec7d098c25e74606fef5464e5/src/lib/Magnolia/PPrint.hs
haskell
# LANGUAGE OverloadedStrings # The below pprinting and error-handling related utils are directly inspired TODO: Text.Lazy -> Text.Strict (renderLazy -> renderStrict) TODO: change error to have error types
# LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -Wno - orphans # module Magnolia.PPrint (pprint, pprintList, pshow, render) where import Control.Monad (join) import qualified Data.List.NonEmpty as NE import qualified Data.Map as M import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as TIO import Prettyprinter import Prettyprinter.Render.Text import Data.Void (absurd) import Backend import Env import Err import Magnolia.Syntax from their equivalent in -research/dex-lang . p :: Pretty a => a -> Doc ann p = pretty pprint :: Pretty a => a -> IO () pprint = printDoc . p printDoc :: Doc ann -> IO () printDoc = TIO.putStrLn . render render :: Doc ann -> T.Text render = renderLazy . layoutPretty defaultLayoutOptions pshow :: Pretty a => a -> T.Text pshow = render . p pprintList :: Pretty a => [a] -> IO () pprintList = printDoc . vsep . punctuate line . map p pretty (Err errType src parentScopes txt) = p src <> ":" <+> p errType <> (case parentScopes of [] -> "" ps -> " in " <> concatWith (surround dot) (map p ps)) <> ":" <+> p txt instance Pretty SrcCtx where pretty (SrcCtx msrcInfo) = case msrcInfo of Nothing -> "<unknown location>" Just ((filename, startLine, startColumn), _) -> p filename <> ":" <> p startLine <> ":" <> p startColumn instance Pretty ErrType where pretty e = case e of AmbiguousFunctionRefErr -> ambiguous "functions" AmbiguousTopLevelRefErr -> ambiguous "top-level references" AmbiguousProcedureRefErr -> ambiguous "procedures" CompilerErr -> "Compiler bug!" <> line <> "Please report this at github.com/magnolia-lang/magnolia-lang" <> line CyclicErr -> "Error: found cyclic dependency" DeclContextErr -> "Declaration context error" InvalidDeclErr -> "Declaration error" MiscErr -> "Error" ModeMismatchErr -> "Mode error" NotImplementedErr -> "Not implemented" ParseErr -> "Parse error" TypeErr -> "Type error" UnboundFunctionErr -> unbound "function" UnboundTopLevelErr -> unbound "top-level reference" UnboundNameErr -> unbound "name" UnboundProcedureErr -> unbound "procedure" UnboundTypeErr -> unbound "type" UnboundVarErr -> unbound "variable" where ambiguous s = "Error: could not disambiguate between" <+> s unbound s = "Error:" <+> s <+> "not in scope" instance Pretty Name where pretty (Name _ str) = p str instance Pretty NameSpace where pretty ns = (case ns of NSDirectory -> "directory" NSFunction -> "function" NSGenerated -> "generated" NSModule -> "module" NSPackage -> "package" NSProcedure -> "procedure" NSRenaming -> "renaming" NSSatisfaction -> "satisfaction" NSType -> "type" NSUnspecified -> "unspecified" NSVariable -> "variable") <+> "namespace" instance Pretty FullyQualifiedName where pretty (FullyQualifiedName mscopeName targetName) = maybe "" (\n -> p n <> ".") mscopeName <> p targetName instance (Show (e p), Pretty (e p)) => Pretty (Ann p e) where pretty = p . _elem instance Pretty (MPackage' PhCheck) where pretty (MPackage name decls deps) = let importHeader = case deps of [] -> "" _ -> "imports" <+> align (vsep (punctuate comma (map p deps))) in "package" <+> p name <+> importHeader <+> ";" <> "\n\n" <> vsep (map p (join (M.elems decls))) instance Pretty (MPackageDep' PhCheck) where pretty (MPackageDep name) = p name instance Pretty (MTopLevelDecl PhCheck) where pretty decl = case decl of MNamedRenamingDecl namedRenaming -> p namedRenaming MModuleDecl modul -> p modul MSatisfactionDecl satisfaction -> p satisfaction instance Pretty (MNamedRenaming' PhCheck) where pretty (MNamedRenaming name block) = "renaming" <+> p name <+> "=" <+> p block instance Pretty (MSatisfaction' PhCheck) where TODO instance Pretty (MModule' PhCheck) where pretty (MModule moduleType name moduleExpr) = p moduleType <+> p name <+> "=" <+> p moduleExpr instance Pretty (MModuleExpr' PhCheck) where pretty (MModuleDef decls deps renamingBlocks) = lbrace <> line <> indent 4 (vsep (map p deps <> map ((<> semi) . p) (join (M.elems decls)))) <> line <> rbrace <> align (vsep $ map p renamingBlocks) pretty (MModuleRef v _) = absurd v pretty (MModuleAsSignature v _) = absurd v pretty (MModuleExternal backend fqn moduleExpr') = "external" <+> p backend <+> p fqn <+> p moduleExpr' instance Pretty (MModuleDep' PhCheck) where pretty (MModuleDep mmoduleDepType mmoduleDepModuleExpr) = p mmoduleDepType <+> p mmoduleDepModuleExpr instance Pretty MModuleDepType where pretty mmoduleDepType = case mmoduleDepType of MModuleDepRequire -> "require" MModuleDepUse -> "use" instance Pretty (MRenamingBlock' PhCheck) where pretty (MRenamingBlock renamingBlockTy renamings) = let content = hsep (punctuate comma (map p renamings)) in case renamingBlockTy of PartialRenamingBlock -> "[[" <> content <> "]]" TotalRenamingBlock -> brackets content instance Pretty (MRenaming' PhCheck) where pretty renaming = case renaming of InlineRenaming (src, tgt) -> p src <+> "=>" <+> p tgt RefRenaming v -> absurd v instance Pretty MModuleType where pretty typ = case typ of Signature -> "signature" Concept -> "concept" Implementation -> "implementation" Program -> "program" instance Pretty Backend where pretty backend = case backend of Cxx -> "C++" JavaScript -> "JavaScript" Python -> "Python" instance Pretty (MDecl PhCheck) where pretty decl = case decl of MTypeDecl modifiers tdecl -> hsep (map p modifiers) <+> pretty tdecl MCallableDecl modifiers cdecl -> hsep (map p modifiers) <+> pretty cdecl instance Pretty MModifier where pretty Require = "require" instance Pretty (MTypeDecl' p) where pretty (Type typ) = "type" <+> p typ instance Pretty (MCallableDecl' PhCheck) where pretty (Callable callableType name args ret mguard cbody) = let pret = if callableType == Function then " : " <> p ret else "" pbody = case cbody of EmptyBody -> "" MagnoliaBody body -> " = " <> p body ExternalBody () -> " = <external impl>;" BuiltinBody -> " (builtin);" pguard = case mguard of Nothing -> "" Just guard -> " guard " <> p guard in p callableType <+> p name <> prettyArgs <> pret <> pguard <> pbody where prettyArgs :: Doc ann prettyArgs = case callableType of Procedure -> parens $ hsep $ punctuate comma (map p args) _ -> parens $ hsep $ punctuate comma $ map (\(Ann _ a) -> p (nodeName a) <+> ":" <+> p (_varType a)) args instance Pretty MCallableType where pretty callableType = case callableType of Axiom -> "axiom" Function -> "function" Predicate -> "predicate" Procedure -> "procedure" instance Pretty (MExpr' p) where pretty e = pNoSemi e <> semi where pNoSemi :: MExpr' p -> Doc ann pNoSemi expr = case expr of MVar v -> p (nodeName v) MCall name args mcast -> let parglist = map (pNoSemi . _elem) args in p name <> parens (hsep (punctuate comma parglist)) <> (case mcast of Nothing -> ""; Just cast -> " : " <> p cast) MBlockExpr _ block -> vsep [ nest 4 (vsep ( "{" : map p (NE.toList block))) , "}" ] MValue expr' -> "value" <+> p expr' TODO : modes are for now ignore in MLet MLet (Ann _ (Var _ name mcast)) mass -> let pcast = case mcast of Nothing -> ""; Just cast -> " : " <> p cast pass = case mass of Nothing -> "" Just ass -> " = " <> pNoSemi (_elem ass) in "var" <+> p name <> pcast <> pass MIf cond etrue efalse -> align $ vsep [ "if" <+> p cond , "then" <+> p etrue , "else" <+> p efalse <+> "end" ] MAssert aexpr -> "assert" <+> pNoSemi (_elem aexpr) MSkip -> "skip" instance Pretty (MaybeTypedVar' p) where pretty (Var mode name mtyp) = case mtyp of Nothing -> p mode <+> p name Just typ -> p mode <+> p name <+> ":" <+> p typ instance Pretty (TypedVar' p) where pretty (Var mode name typ) = p mode <+> p name <+> ":" <+> p typ instance Pretty MVarMode where pretty mode = case mode of MObs -> "obs" MOut -> "out" MUnk -> "unk" MUpd -> "upd"
d8615b679641d2d2118fd4ba915f061839274d782d75fc107d095cae0b6edf2f
tsloughter/kuberl
kuberl_policy_v1beta1_allowed_flex_volume.erl
-module(kuberl_policy_v1beta1_allowed_flex_volume). -export([encode/1]). -export_type([kuberl_policy_v1beta1_allowed_flex_volume/0]). -type kuberl_policy_v1beta1_allowed_flex_volume() :: #{ 'driver' := binary() }. encode(#{ 'driver' := Driver }) -> #{ 'driver' => Driver }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_policy_v1beta1_allowed_flex_volume.erl
erlang
-module(kuberl_policy_v1beta1_allowed_flex_volume). -export([encode/1]). -export_type([kuberl_policy_v1beta1_allowed_flex_volume/0]). -type kuberl_policy_v1beta1_allowed_flex_volume() :: #{ 'driver' := binary() }. encode(#{ 'driver' := Driver }) -> #{ 'driver' => Driver }.
479d8595150481c1443a7ed6af426a0e496978785d02c837c414592870d4662c
alexprut/earth-defender
monitor_mesh.erl
-module(monitor_mesh). %% External exports -export([start_monitor_mesh/0]). %% Internal exports -export([monitor_mesh/0]). %%% --------------------------------------------------- %%% %%% Monitor all mesh nodes. %%% %%% --------------------------------------------------- start_monitor_mesh() -> spawn(?MODULE, monitor_mesh, []). monitor_mesh() -> net_kernel:monitor_nodes(true), utils:log("Monitoring mesh nodes. ~n", []), monitor_mesh_loop(). monitor_mesh_loop() -> receive {nodeup, Node} -> utils:log("Node: ~p is up, detected at node: ~p~n", [Node, node()]), monitor_mesh_loop(); {nodedown, Node} -> utils:log("Node: ~p is down, detected at node: ~p~n", [Node, node()]), case local_rooms_state:is_master() of true -> utils:log("Slave died, node: ~p~n", [Node]), local_rooms_state:remove_slave(Node); false -> utils:log("Maybe a master died.~n", []), {Master_name, _} = slave_handler:get_master_data(), utils:log("Last master name: ~p~n", [Master_name]), case Master_name == Node of true -> % Master died, election algorithm (Bully algorithm modified version) utils:log("Master died, node: ~p~n", [Node]), New_master = lists:max([node() | nodes()]), case New_master == node() of true -> utils:log("I'm the new master, takeover.~n", []), local_rooms_state ! master_takeover; false -> utils:log("The new master should be: ~p~n", [New_master]), Master_service_url = rpc:call(New_master, utils, get_service_url, [], 2000), case Master_service_url of {badrpc, _} -> utils:log("Badrpc at node: ~p~n", [Node]), ok; _ -> utils:log("Temp master data, the next master node could be: ~p~n", [New_master]), slave_handler:set_master_data({New_master, Master_service_url}) end end; false -> % A slave died utils:log("A slave died.~n", []), ok end end, monitor_mesh_loop(); stop -> exit(kill, self()) end.
null
https://raw.githubusercontent.com/alexprut/earth-defender/5d4d8f0832fc74882a701d6a0dedee23fd494648/server/src/monitor_mesh.erl
erlang
External exports Internal exports --------------------------------------------------- Monitor all mesh nodes. --------------------------------------------------- Master died, election algorithm (Bully algorithm modified version) A slave died
-module(monitor_mesh). -export([start_monitor_mesh/0]). -export([monitor_mesh/0]). start_monitor_mesh() -> spawn(?MODULE, monitor_mesh, []). monitor_mesh() -> net_kernel:monitor_nodes(true), utils:log("Monitoring mesh nodes. ~n", []), monitor_mesh_loop(). monitor_mesh_loop() -> receive {nodeup, Node} -> utils:log("Node: ~p is up, detected at node: ~p~n", [Node, node()]), monitor_mesh_loop(); {nodedown, Node} -> utils:log("Node: ~p is down, detected at node: ~p~n", [Node, node()]), case local_rooms_state:is_master() of true -> utils:log("Slave died, node: ~p~n", [Node]), local_rooms_state:remove_slave(Node); false -> utils:log("Maybe a master died.~n", []), {Master_name, _} = slave_handler:get_master_data(), utils:log("Last master name: ~p~n", [Master_name]), case Master_name == Node of true -> utils:log("Master died, node: ~p~n", [Node]), New_master = lists:max([node() | nodes()]), case New_master == node() of true -> utils:log("I'm the new master, takeover.~n", []), local_rooms_state ! master_takeover; false -> utils:log("The new master should be: ~p~n", [New_master]), Master_service_url = rpc:call(New_master, utils, get_service_url, [], 2000), case Master_service_url of {badrpc, _} -> utils:log("Badrpc at node: ~p~n", [Node]), ok; _ -> utils:log("Temp master data, the next master node could be: ~p~n", [New_master]), slave_handler:set_master_data({New_master, Master_service_url}) end end; false -> utils:log("A slave died.~n", []), ok end end, monitor_mesh_loop(); stop -> exit(kill, self()) end.
253a734a1aa829ff1b4e49b43cbd207dea10d9b69a7836c2011181da63420c21
icicle-lang/disorder.hs-ambiata
test.hs
import Control.Monad import qualified Test.Disorder.Corpus import System.Exit import System.IO main :: IO () main = hSetBuffering stdout LineBuffering >> mapM id [ Test.Disorder.Corpus.tests ] >>= \rs -> when (not . all id $ rs) exitFailure
null
https://raw.githubusercontent.com/icicle-lang/disorder.hs-ambiata/0068d9a0dd9aea45e772fb664cf4e7e71636dbe5/disorder-corpus/test/test.hs
haskell
import Control.Monad import qualified Test.Disorder.Corpus import System.Exit import System.IO main :: IO () main = hSetBuffering stdout LineBuffering >> mapM id [ Test.Disorder.Corpus.tests ] >>= \rs -> when (not . all id $ rs) exitFailure
f96f1e4180749812f370fa3ecf8d77bbe52fd21fd1480b179068355c17155be2
emotiq/emotiq
lazy.lisp
;; Lazy.lisp -- class for lazy evaluation and memoization of results ;; DM / MCFA 10/01 DM / RAL 12/08 -- more efficient implementation ;; ----------------------------------------------------------- (in-package "LAZY") (defclass lazy-form () ((expr-fn :reader expr-fn :initarg :expr-fn))) (defclass memoized-lazy-evaluation () ((expr :reader force :initarg :forced))) (defmacro lazy (expr) `(make-instance 'lazy-form :expr-fn (lambda () ,expr))) (defmethod force (val) val) (defmethod force ((val lazy-form)) (let ((ans (funcall (expr-fn val)))) (change-class val 'memoized-lazy-evaluation :forced ans) ans))
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/useful-macros/old-code/lazy.lisp
lisp
Lazy.lisp -- class for lazy evaluation and memoization of results -----------------------------------------------------------
DM / MCFA 10/01 DM / RAL 12/08 -- more efficient implementation (in-package "LAZY") (defclass lazy-form () ((expr-fn :reader expr-fn :initarg :expr-fn))) (defclass memoized-lazy-evaluation () ((expr :reader force :initarg :forced))) (defmacro lazy (expr) `(make-instance 'lazy-form :expr-fn (lambda () ,expr))) (defmethod force (val) val) (defmethod force ((val lazy-form)) (let ((ans (funcall (expr-fn val)))) (change-class val 'memoized-lazy-evaluation :forced ans) ans))
b544aad19c50bf366bf0f30f8916a6408eac56476e9488e1e7a1821caa018e9b
tweag/linear-base
Linear.hs
{-# LANGUAGE LinearTypes #-} # LANGUAGE NoImplicitPrelude # TODO : Disabled while we still support GHC 9.2 to enable -- the import of the empty TypeEq module there. # OPTIONS_GHC -Wno - dodgy - exports -Wno - unused - imports # | This module provides a replacement for ' Prelude ' with -- support for linear programming via linear versions of -- standard data types, functions and type classes. -- -- A simple example: -- -- >>> :set -XLinearTypes -- >>> :set -XNoImplicitPrelude > > > import Prelude . Linear -- >>> :{ -- boolToInt :: Bool %1-> Int boolToInt False = 0 boolToInt True = 1 -- :} -- -- >>> :{ -- makeInt :: Either Int Bool %1-> Int -- makeInt = either id boolToInt -- :} -- -- This module is designed to be imported unqualifed. module Prelude.Linear ( -- * Standard Types, Classes and Related Functions -- ** Basic data types module Data.Bool.Linear, Prelude.Char, module Data.Maybe.Linear, module Data.Either.Linear, module Prelude.Linear.Internal.TypeEq, * Tuples Prelude.fst, Prelude.snd, curry, uncurry, -- ** Basic type classes module Data.Ord.Linear, Prelude.Enum (..), Prelude.Bounded (..), -- ** Numbers Prelude.Int, Prelude.Integer, Prelude.Float, Prelude.Double, Prelude.Rational, Prelude.Word, module Data.Num.Linear, Prelude.Real (..), Prelude.Integral (..), Prelude.Floating (..), Prelude.Fractional (..), Prelude.RealFrac (..), Prelude.RealFloat (..), -- *** Numeric functions Prelude.subtract, Prelude.even, Prelude.odd, Prelude.gcd, Prelude.lcm, (Prelude.^), (Prelude.^^), Prelude.fromIntegral, Prelude.realToFrac, -- ** Monads and functors (<*), * * and monoids module Data.Monoid.Linear, -- ** Miscellaneous functions id, const, (.), flip, ($), (&), Prelude.until, Prelude.error, Prelude.errorWithoutStackTrace, Prelude.undefined, seq, ($!), -- * List operations module Data.List.Linear, -- * Functions on strings -- TODO: Implement a linear counterpart of this module Data.String, -- * Converting to and from String Prelude.ShowS, Prelude.Show (..), Prelude.shows, Prelude.showChar, Prelude.showString, Prelude.showParen, Prelude.ReadS, Prelude.Read (..), Prelude.reads, Prelude.readParen, Prelude.read, Prelude.lex, -- * Basic input and output Prelude.IO, Prelude.putChar, Prelude.putStr, Prelude.putStrLn, Prelude.print, Prelude.getChar, Prelude.getLine, Prelude.getContents, Prelude.interact, -- ** Files Prelude.FilePath, Prelude.readFile, Prelude.writeFile, Prelude.appendFile, Prelude.readIO, Prelude.readLn, * Using ' Ur ' values in linear code -- $ Ur (..), unur, -- * Doing non-linear operations inside linear functions -- $ Consumable (..), Dupable (..), Movable (..), lseq, dup, dup3, forget, ) where import Data.Bool.Linear import Data.Either.Linear import qualified Data.Functor.Linear as Data import Data.List.Linear import Data.Maybe.Linear import Data.Monoid.Linear import Data.Num.Linear import Data.Ord.Linear import Data.String import Data.Tuple.Linear import Data.Unrestricted.Linear import Prelude.Linear.Internal import Prelude.Linear.Internal.TypeEq import qualified Prelude -- | Replacement for the flip function with generalized multiplicities. flip :: (a %p -> b %q -> c) %r -> b %q -> a %p -> c flip f b a = f a b -- | Linearly typed replacement for the standard '(Prelude.<*)' function. (<*) :: (Data.Applicative f, Consumable b) => f a %1 -> f b %1 -> f a fa <* fb = Data.fmap (flip lseq) fa Data.<*> fb infixl 4 <* -- same fixity as base.<*
null
https://raw.githubusercontent.com/tweag/linear-base/6869779b4f8a675125784063ddd2a89e49f61b38/src/Prelude/Linear.hs
haskell
# LANGUAGE LinearTypes # the import of the empty TypeEq module there. support for linear programming via linear versions of standard data types, functions and type classes. A simple example: >>> :set -XLinearTypes >>> :set -XNoImplicitPrelude >>> :{ boolToInt :: Bool %1-> Int :} >>> :{ makeInt :: Either Int Bool %1-> Int makeInt = either id boolToInt :} This module is designed to be imported unqualifed. * Standard Types, Classes and Related Functions ** Basic data types ** Basic type classes ** Numbers *** Numeric functions ** Monads and functors ** Miscellaneous functions * List operations * Functions on strings TODO: Implement a linear counterpart of this * Converting to and from String * Basic input and output ** Files $ * Doing non-linear operations inside linear functions $ | Replacement for the flip function with generalized multiplicities. | Linearly typed replacement for the standard '(Prelude.<*)' function. same fixity as base.<*
# LANGUAGE NoImplicitPrelude # TODO : Disabled while we still support GHC 9.2 to enable # OPTIONS_GHC -Wno - dodgy - exports -Wno - unused - imports # | This module provides a replacement for ' Prelude ' with > > > import Prelude . Linear boolToInt False = 0 boolToInt True = 1 module Prelude.Linear module Data.Bool.Linear, Prelude.Char, module Data.Maybe.Linear, module Data.Either.Linear, module Prelude.Linear.Internal.TypeEq, * Tuples Prelude.fst, Prelude.snd, curry, uncurry, module Data.Ord.Linear, Prelude.Enum (..), Prelude.Bounded (..), Prelude.Int, Prelude.Integer, Prelude.Float, Prelude.Double, Prelude.Rational, Prelude.Word, module Data.Num.Linear, Prelude.Real (..), Prelude.Integral (..), Prelude.Floating (..), Prelude.Fractional (..), Prelude.RealFrac (..), Prelude.RealFloat (..), Prelude.subtract, Prelude.even, Prelude.odd, Prelude.gcd, Prelude.lcm, (Prelude.^), (Prelude.^^), Prelude.fromIntegral, Prelude.realToFrac, (<*), * * and monoids module Data.Monoid.Linear, id, const, (.), flip, ($), (&), Prelude.until, Prelude.error, Prelude.errorWithoutStackTrace, Prelude.undefined, seq, ($!), module Data.List.Linear, module Data.String, Prelude.ShowS, Prelude.Show (..), Prelude.shows, Prelude.showChar, Prelude.showString, Prelude.showParen, Prelude.ReadS, Prelude.Read (..), Prelude.reads, Prelude.readParen, Prelude.read, Prelude.lex, Prelude.IO, Prelude.putChar, Prelude.putStr, Prelude.putStrLn, Prelude.print, Prelude.getChar, Prelude.getLine, Prelude.getContents, Prelude.interact, Prelude.FilePath, Prelude.readFile, Prelude.writeFile, Prelude.appendFile, Prelude.readIO, Prelude.readLn, * Using ' Ur ' values in linear code Ur (..), unur, Consumable (..), Dupable (..), Movable (..), lseq, dup, dup3, forget, ) where import Data.Bool.Linear import Data.Either.Linear import qualified Data.Functor.Linear as Data import Data.List.Linear import Data.Maybe.Linear import Data.Monoid.Linear import Data.Num.Linear import Data.Ord.Linear import Data.String import Data.Tuple.Linear import Data.Unrestricted.Linear import Prelude.Linear.Internal import Prelude.Linear.Internal.TypeEq import qualified Prelude flip :: (a %p -> b %q -> c) %r -> b %q -> a %p -> c flip f b a = f a b (<*) :: (Data.Applicative f, Consumable b) => f a %1 -> f b %1 -> f a fa <* fb = Data.fmap (flip lseq) fa Data.<*> fb
7517518169ba9f07f4f8690b05a9138b4131369e1c87ff61a19fdbbf1193afab
fission-codes/fission
Class.hs
| Database mutations for ' LoosePin 's module Fission.Web.Server.LoosePin.Destroyer.Class (Destroyer (..)) where import Database.Esqueleto.Legacy import Network.IPFS.CID.Types as IPFS.CID import Fission.Prelude import Fission.Web.Server.Models import Fission.Web.Server.MonadDB.Types -- | Actions for destroying @LoosePin@s class Monad m => Destroyer m where -- | Destroy a specific @LoosePin@ destroy :: UserId -> CID -> m () -- | Destroy several @LoosePin@s by they primary keys destroyMany :: UserId -> [LoosePinId] -> m () instance MonadIO m => Destroyer (Transaction m) where destroyMany userId userCidIds = delete $ from \pin -> where_ $ pin ^. LoosePinId `in_` valList userCidIds &&. pin ^. LoosePinOwnerId ==. val userId destroy userId cid = delete $ from \pin -> where_ $ pin ^. LoosePinCid ==. val cid &&. pin ^. LoosePinOwnerId ==. val userId
null
https://raw.githubusercontent.com/fission-codes/fission/ae177407dccc20be67948a901956b99f40d37ac8/fission-web-server/library/Fission/Web/Server/LoosePin/Destroyer/Class.hs
haskell
| Actions for destroying @LoosePin@s | Destroy a specific @LoosePin@ | Destroy several @LoosePin@s by they primary keys
| Database mutations for ' LoosePin 's module Fission.Web.Server.LoosePin.Destroyer.Class (Destroyer (..)) where import Database.Esqueleto.Legacy import Network.IPFS.CID.Types as IPFS.CID import Fission.Prelude import Fission.Web.Server.Models import Fission.Web.Server.MonadDB.Types class Monad m => Destroyer m where destroy :: UserId -> CID -> m () destroyMany :: UserId -> [LoosePinId] -> m () instance MonadIO m => Destroyer (Transaction m) where destroyMany userId userCidIds = delete $ from \pin -> where_ $ pin ^. LoosePinId `in_` valList userCidIds &&. pin ^. LoosePinOwnerId ==. val userId destroy userId cid = delete $ from \pin -> where_ $ pin ^. LoosePinCid ==. val cid &&. pin ^. LoosePinOwnerId ==. val userId
83d18938a2789506c17a3709e06dadabb1833b5297aa0e95fb0dab6c2823cdcf
zachsully/dl
FreeVars.hs
module DL.Utils.FreeVars where import Data.Set import DL.General.Variable -------------------------------------------------------------------------------- Free Variable -- -------------------------------------------------------------------------------- class FV a where fvs :: a -> Set Variable
null
https://raw.githubusercontent.com/zachsully/dl/c99cdfa8a3b59b1977a34876f397c467518091b6/haskell/DL/Utils/FreeVars.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
module DL.Utils.FreeVars where import Data.Set import DL.General.Variable class FV a where fvs :: a -> Set Variable
6ca57b6f953cc75ad90367759c436c5839a3d025aaa7dba27b512d50bd2e9310
may-liu/qtalk
adhoc.erl
%%%---------------------------------------------------------------------- %%% File : adhoc.erl Author : < > Purpose : Provide helper functions for ad - hoc commands ( XEP-0050 ) Created : 31 Oct 2005 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%---------------------------------------------------------------------- -module(adhoc). -author(''). -export([ parse_request/1, produce_response/2, produce_response/1 ]). -include("ejabberd.hrl"). -include("logger.hrl"). -include("jlib.hrl"). -include("adhoc.hrl"). Parse an ad - hoc request . Return either an adhoc_request record or an { error , ErrorType } tuple . %% -spec(parse_request/1 :: ( IQ :: iq_request()) -> adhoc_response() %% | {error, _} ). parse_request(#iq{type = set, lang = Lang, sub_el = SubEl, xmlns = ?NS_COMMANDS}) -> ?DEBUG("entering parse_request...", []), Node = xml:get_tag_attr_s(<<"node">>, SubEl), SessionID = xml:get_tag_attr_s(<<"sessionid">>, SubEl), Action = xml:get_tag_attr_s(<<"action">>, SubEl), XData = find_xdata_el(SubEl), #xmlel{children = AllEls} = SubEl, Others = case XData of false -> AllEls; _ -> lists:delete(XData, AllEls) end, #adhoc_request{ lang = Lang, node = Node, sessionid = SessionID, action = Action, xdata = XData, others = Others }; parse_request(_) -> {error, ?ERR_BAD_REQUEST}. Borrowed from mod_vcard.erl find_xdata_el(#xmlel{children = SubEls}) -> find_xdata_el1(SubEls). find_xdata_el1([]) -> false; find_xdata_el1([El | Els]) when is_record(El, xmlel) -> case xml:get_tag_attr_s(<<"xmlns">>, El) of ?NS_XDATA -> El; _ -> find_xdata_el1(Els) end; find_xdata_el1([_ | Els]) -> find_xdata_el1(Els). %% Produce a <command/> node to use as response from an adhoc_response %% record, filling in values for language, node and session id from %% the request. %% -spec(produce_response/2 :: ( Adhoc_Request :: adhoc_request(), Adhoc_Response :: adhoc_response()) -> Xmlel::xmlel() ). %% Produce a <command/> node to use as response from an adhoc_response %% record. produce_response(#adhoc_request{lang = Lang, node = Node, sessionid = SessionID}, Adhoc_Response) -> produce_response(Adhoc_Response#adhoc_response{ lang = Lang, node = Node, sessionid = SessionID }). %% -spec(produce_response/1 :: ( Adhoc_Response::adhoc_response()) -> Xmlel::xmlel() ). produce_response( #adhoc_response{ lang = _ , node = Node, sessionid = ProvidedSessionID, status = Status, defaultaction = DefaultAction, actions = Actions, notes = Notes, elements = Elements }) -> SessionID = if is_binary(ProvidedSessionID), ProvidedSessionID /= <<"">> -> ProvidedSessionID; true -> jlib:now_to_utc_string(os:timestamp()) end, case Actions of [] -> ActionsEls = []; _ -> case DefaultAction of <<"">> -> ActionsElAttrs = []; _ -> ActionsElAttrs = [{<<"execute">>, DefaultAction}] end, ActionsEls = [ #xmlel{ name = <<"actions">>, attrs = ActionsElAttrs, children = [ #xmlel{name = Action, attrs = [], children = []} || Action <- Actions] } ] end, NotesEls = lists:map(fun({Type, Text}) -> #xmlel{ name = <<"note">>, attrs = [{<<"type">>, Type}], children = [{xmlcdata, Text}] } end, Notes), #xmlel{ name = <<"command">>, attrs = [ {<<"xmlns">>, ?NS_COMMANDS}, {<<"sessionid">>, SessionID}, {<<"node">>, Node}, {<<"status">>, iolist_to_binary(atom_to_list(Status))} ], children = ActionsEls ++ NotesEls ++ Elements }.
null
https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/adhoc.erl
erlang
---------------------------------------------------------------------- File : adhoc.erl This program is free software; you can redistribute it and/or 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. ---------------------------------------------------------------------- Produce a <command/> node to use as response from an adhoc_response record, filling in values for language, node and session id from the request. Produce a <command/> node to use as response from an adhoc_response record.
Author : < > Purpose : Provide helper functions for ad - hoc commands ( XEP-0050 ) Created : 31 Oct 2005 by < > ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(adhoc). -author(''). -export([ parse_request/1, produce_response/2, produce_response/1 ]). -include("ejabberd.hrl"). -include("logger.hrl"). -include("jlib.hrl"). -include("adhoc.hrl"). Parse an ad - hoc request . Return either an adhoc_request record or an { error , ErrorType } tuple . -spec(parse_request/1 :: ( IQ :: iq_request()) -> adhoc_response() | {error, _} ). parse_request(#iq{type = set, lang = Lang, sub_el = SubEl, xmlns = ?NS_COMMANDS}) -> ?DEBUG("entering parse_request...", []), Node = xml:get_tag_attr_s(<<"node">>, SubEl), SessionID = xml:get_tag_attr_s(<<"sessionid">>, SubEl), Action = xml:get_tag_attr_s(<<"action">>, SubEl), XData = find_xdata_el(SubEl), #xmlel{children = AllEls} = SubEl, Others = case XData of false -> AllEls; _ -> lists:delete(XData, AllEls) end, #adhoc_request{ lang = Lang, node = Node, sessionid = SessionID, action = Action, xdata = XData, others = Others }; parse_request(_) -> {error, ?ERR_BAD_REQUEST}. Borrowed from mod_vcard.erl find_xdata_el(#xmlel{children = SubEls}) -> find_xdata_el1(SubEls). find_xdata_el1([]) -> false; find_xdata_el1([El | Els]) when is_record(El, xmlel) -> case xml:get_tag_attr_s(<<"xmlns">>, El) of ?NS_XDATA -> El; _ -> find_xdata_el1(Els) end; find_xdata_el1([_ | Els]) -> find_xdata_el1(Els). -spec(produce_response/2 :: ( Adhoc_Request :: adhoc_request(), Adhoc_Response :: adhoc_response()) -> Xmlel::xmlel() ). produce_response(#adhoc_request{lang = Lang, node = Node, sessionid = SessionID}, Adhoc_Response) -> produce_response(Adhoc_Response#adhoc_response{ lang = Lang, node = Node, sessionid = SessionID }). -spec(produce_response/1 :: ( Adhoc_Response::adhoc_response()) -> Xmlel::xmlel() ). produce_response( #adhoc_response{ lang = _ , node = Node, sessionid = ProvidedSessionID, status = Status, defaultaction = DefaultAction, actions = Actions, notes = Notes, elements = Elements }) -> SessionID = if is_binary(ProvidedSessionID), ProvidedSessionID /= <<"">> -> ProvidedSessionID; true -> jlib:now_to_utc_string(os:timestamp()) end, case Actions of [] -> ActionsEls = []; _ -> case DefaultAction of <<"">> -> ActionsElAttrs = []; _ -> ActionsElAttrs = [{<<"execute">>, DefaultAction}] end, ActionsEls = [ #xmlel{ name = <<"actions">>, attrs = ActionsElAttrs, children = [ #xmlel{name = Action, attrs = [], children = []} || Action <- Actions] } ] end, NotesEls = lists:map(fun({Type, Text}) -> #xmlel{ name = <<"note">>, attrs = [{<<"type">>, Type}], children = [{xmlcdata, Text}] } end, Notes), #xmlel{ name = <<"command">>, attrs = [ {<<"xmlns">>, ?NS_COMMANDS}, {<<"sessionid">>, SessionID}, {<<"node">>, Node}, {<<"status">>, iolist_to_binary(atom_to_list(Status))} ], children = ActionsEls ++ NotesEls ++ Elements }.
7e2b4647b3cb9f4a6548cf20402d6a2683461008638b671b06eab161f879b285
mfp/obigstore
obs_data_model.mli
* Copyright ( C ) 2011 - 2013 < > * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Copyright (C) 2011-2013 Mauricio Fernandez <> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * { 2 Type definitions } * Exception raised when inserting an invalid BSON [ @column ] . exception Invalid_BSON_column of string (** column name *) (** Exception raised when a watched key/column has been modified while a write * transaction is being performed. *) exception Dirty_data (** Exception raised by the {!lock} operation if a deadlock is detected. *) exception Deadlock (** Operation denied owning to insufficient permissions or invalid * credentials. *) exception Denied type table = private string val string_of_table : table -> string val table_of_string : string -> table type key = string type 'data column = { name : column_name; data : 'data; timestamp : timestamp; } and column_name = string and timestamp = No_timestamp | Timestamp of Int64.t type decoded_data = Binary of string | BSON of Obs_bson.document | Malformed_BSON of string type ('key, 'data) key_data = { key : 'key; last_column : string; (** Name of last column in the following list *) columns : 'data column list; } type ('key, 'data) slice = 'key option * ('key, 'data) key_data list (** last_key * data *) * Range representing elements between [ first ] ( inclusive if reverse is * false , exclusive otherwise ) and [ up_to ] * ( exclusive if reverse is false , inclusive otherwise ) . If [ first ] is not * provided , the range starts with the first available element ( last , if * [ reverse ] is [ true ] ) ; likewise , if [ up_to ] is not provided , the elements * until the last ( first , if [ reverse is [ true ] ) one are selected . * * Summarizing : * * * if reverse is false , elements x such that [ first < = x < up_to ] * * if reverse is true , elements x such that [ first > x > = up_to ] * * where a side of the inequality disappears if the corresponding value * ( [ first ] or [ up_to ] ) is [ None ] . * * false, exclusive otherwise) and [up_to] * (exclusive if reverse is false, inclusive otherwise). If [first] is not * provided, the range starts with the first available element (last, if * [reverse] is [true]); likewise, if [up_to] is not provided, the elements * until the last (first, if [reverse is [true]) one are selected. * * Summarizing: * * * if reverse is false, elements x such that [first <= x < up_to] * * if reverse is true, elements x such that [first > x >= up_to] * * where a side of the inequality disappears if the corresponding value * ([first] or [up_to]) is [None]. * *) type 'key range = { first : 'key option; up_to : 'key option; reverse : bool; } type 'key cont_or_discrete_range = [ `Continuous of 'key range | `Discrete of 'key list ] type 'key key_range = [ 'key cont_or_discrete_range | `All] type column_range = [ string key_range | `Union of string cont_or_discrete_range list ] (** Predicate on the value of a colum *) type column_val_rel = | Any (** don't care about the value *) | EQ of string | LT of string | GT of string | GE of string | LE of string | Between of string * bool * string * bool (** each bool indicating whether inclusive *) type simple_row_predicate = | Column_val of string * column_val_rel (** [name, predicate] *) type row_predicate_and = Satisfy_all of simple_row_predicate list (* all of them *) type row_predicate = Satisfy_any of row_predicate_and list (* any of them *) type backup_format = int type raw_dump_timestamp = Int64.t type tx_id = Int64.t type lock_kind = [`SHARED | `EXCLUSIVE] type tx_info = { tx_id : tx_id; started_at : float; wanted_locks : (string * lock_kind) list; held_locks : (string * lock_kind) list; } (** Specify transaction semantics. *) type sync_mode = [ `Sync (** Synchronous commit, with full fsync (unless disabled globally) *) | `Async (** Asynchronous commit, without fsync. Durability not guaranteed * in the event of system crashes. *) | `Default (** In outermost transaction: use synchronous commit. * In nested transactions: inherit parent mode * (can still be modified by a child transaction). *) ] { 2 Data model } module type RAW_DUMP = sig type db type raw_dump (** Request that the current state of the DB be dumped. *) val dump : db -> mode:[`Sync | `Async | `No_stream] -> raw_dump Lwt.t (** Allow to release the resources associated to the dump (e.g., delete * the actual data). Further operations on the dump will fail. *) val release : raw_dump -> keep_files:bool -> unit Lwt.t val timestamp : raw_dump -> raw_dump_timestamp Lwt.t val localdir : raw_dump -> string Lwt.t val list_files : raw_dump -> (string * Int64.t) list Lwt.t val file_digest : raw_dump -> string -> string option Lwt.t val open_file : raw_dump -> ?offset:Int64.t -> string -> Lwt_io.input_channel option Lwt.t end (** DB operations with opaque columns. *) module type RAW_S = sig type db type keyspace val list_keyspaces : db -> string list Lwt.t * Register the keyspace in the DB and return a new [ keyspace ] object . * Different calls to [ register_keyspace name ] with the same [ name ] * return different values ( allowing to perform transactions on them * independently ) . * Different calls to [register_keyspace name] with the same [name] * return different values (allowing to perform transactions on them * independently). *) val register_keyspace : db -> string -> keyspace Lwt.t (** Similar to [register_keyspace], but only returns [Some ks] if the * keyspace exists in the DB. *) val get_keyspace : db -> string -> keyspace option Lwt.t val keyspace_name : keyspace -> string val keyspace_id : keyspace -> int (** List the tables that contained data at the time the outermost * transaction began. *) val list_tables : keyspace -> table list Lwt.t (** @return approximate size on disk of the data for the given table. *) val table_size_on_disk : keyspace -> table -> Int64.t Lwt.t (** @return approximate size on disk of the data for the given key range in * the specified table. *) val key_range_size_on_disk : keyspace -> ?first:string -> ?up_to:string -> table -> Int64.t Lwt.t * { 3 Transactions } * [ read_committed_transaction ks f ] runs [ f ] in a transaction . * Within [ f ] , the effect of other transactions committed after its * evaluation started will be visible . * * Note that nested transactions can be executed concurrenty * ( with [ lwt x = read_committed_transaction f a and * y = read_committed_transaction f b ] , [ Lwt.join ] or similar ) * but the server can choose to serialize their execution . * * Also note that " simple " operations such as { ! } are performed * within an implicit transaction . * * This means that code like the following is dangerous : * { [ * read_committed_transaction ks ( * * Within [f], the effect of other transactions committed after its * evaluation started will be visible. * * Note that nested transactions can be executed concurrenty * (with [lwt x = read_committed_transaction f a and * y = read_committed_transaction f b], [Lwt.join] or similar) * but the server can choose to serialize their execution. * * Also note that "simple" operations such as {!put_columns} are performed * within an implicit transaction. * * This means that code like the following is dangerous: * {[ * read_committed_transaction ks (* TX1 *) * (fun ks -> * read_committed_transaction ks (* TX2 *) * (fun ks2 -> * put_columns ks tbl key cols (* TX3 *) >> * put_columns ks2 tbl2 key2 cols2)) * ]} * This code can hang if the server serializes concurrent, nested * transaction, because [put_columns ks ...] starts an implicit * transaction [TX3] whose execution will start only once the * [TX2] transaction completes, but [TX2] will not finish until [TX3] is * done. * * @param sync Specify sync mode. The final sync mode used on commit for * the outermost transaction is the most restrictive amongst the ones * specified by it and its descendents (e.g., if any uses [~sync:`Sync], * this is the mode that will be used, regardless of what [sync] mode was * used in the outermost transaction). Default value: [`Default] (refer to * {!sync_mode}. *) val read_committed_transaction : ?sync:sync_mode -> keyspace -> (keyspace -> 'a Lwt.t) -> 'a Lwt.t * [ repeatable_read_transaction ks f ] runs [ f ] in a transaction . * Two read operations with the same parameters performed in [ f ] 's scope * are guaranteed to return the same results ( unless [ f ] itself wrote * data ) , regardless of whether other transactions have committed data or * not . * * Refer to { ! read_committed_transaction } for information on concurrent * execution of nested transactions . * * Two read operations with the same parameters performed in [f]'s scope * are guaranteed to return the same results (unless [f] itself wrote * data), regardless of whether other transactions have committed data or * not. * * Refer to {!read_committed_transaction} for information on concurrent * execution of nested transactions. * *) val repeatable_read_transaction : ?sync:sync_mode -> keyspace -> (keyspace -> 'a Lwt.t) -> 'a Lwt.t * [ ks ] returns the ID of the current and outermost * transaction ( useful for logging and reporting ) , or None if not inside a * transaction . * transaction (useful for logging and reporting), or None if not inside a * transaction. *) val transaction_id : keyspace -> (int * int) option Lwt.t * [ lock ks ~shared l ] acquire locks with names given in [ l ] for the DB * keyspace [ ks ] . Each DB keyspace defines a different * lock namespace ; therefore different [ keyspace ] values for the same * underlying DB keyspace share the same namespace . * The locks will be released automatically when the outermost transaction * is committed or aborted . [ lock ] is a NOP unless inside a transaction . * * @param shared indicates whether shared or exclusive locks are to be * acquired * keyspace [keyspace_name ks]. Each DB keyspace defines a different * lock namespace; therefore different [keyspace] values for the same * underlying DB keyspace share the same namespace. * The locks will be released automatically when the outermost transaction * is committed or aborted. [lock] is a NOP unless inside a transaction. * * @param shared indicates whether shared or exclusive locks are to be * acquired *) val lock : keyspace -> shared:bool -> string list -> unit Lwt.t * [ watch_keys ks table keys ] will make write transactions raise * [ Dirty_data ] if a column belonging to any of the given keys is modified * ( added , updated or deleted ) after the call to [ watch_keys ] . * * It is used to perform optimistic concurrency control as follows : * { [ * let attempt ( ) = * begin fun ks - > * watch_keys ks accounts [ account_key ] > > * lwt n = get_column ks accounts account_key " balance " > |= * fst > |= int_of_string * in * put_columns ks accounts account_key * [ { name = " balance " ; data = string_of_int ( n + 1 ) ; * timestamp = No_timestamp ; } ] * end in * let rec retry_if_needed ( ) = * try_lwt attempt ( ) with Dirty_data - > retry_if_needed ( ) * in * ( * perform transaction * [Dirty_data] if a column belonging to any of the given keys is modified * (added, updated or deleted) after the call to [watch_keys]. * * It is used to perform optimistic concurrency control as follows: * {[ * let attempt () = * read_committed_transaction ks begin fun ks -> * watch_keys ks accounts [account_key] >> * lwt n = get_column ks accounts account_key "balance" >|= * fst >|= int_of_string * in * put_columns ks accounts account_key * [ { name = "balance"; data = string_of_int (n + 1); * timestamp = No_timestamp; } ] * end in * let rec retry_if_needed () = * try_lwt attempt () with Dirty_data -> retry_if_needed () * in * (* perform transaction *) * retry_if_needed () * ]} * *) val watch_keys : keyspace -> table -> string list -> unit Lwt.t * [ watch_columns ks table l ] is similar to { ! watch_keys } , but instead of * watching the whole keys , only the specified columns are considered , e.g. * [ watch_keys ks table [ " key1 " , [ " col1 " , " col2 " ] ; " key2 " , [ " col2 " ] ] ] . * watching the whole keys, only the specified columns are considered, e.g. * [watch_keys ks table ["key1", ["col1", "col2"]; "key2", ["col2"]]]. *) val watch_columns : keyspace -> table -> (string * string list) list -> unit Lwt.t (** [watch_prefixes ks table prefixes] is similar to {!watch_keys}, but is * given a prefix of the keys to watch; e.g., if you do * [watch_prefixes ks tbl ["foo"; "bar"]], write transactions will abort * with [Dirty_data] if any keys starting with [foo] or [bar] (inclusive) * are modified by a concurrent transaction *) val watch_prefixes : keyspace -> table -> string list -> unit Lwt.t * { 3 Read operations } (** Return up to [max_keys] keys (default: [max_int]) in the given range. *) val get_keys : keyspace -> table -> ?max_keys:int -> string key_range -> string list Lwt.t (** [exists_key ks table k] returns [true] if any column with the given * [key] exists in the given [table] within the keyspace [ks]. *) val exists_key : keyspace -> table -> string -> bool Lwt.t (** [exist_keys ks table keys] returns a list of bools indicating whether * each key in [keys] has got any column in the given [table] within the * keyspace [ks]. *) val exist_keys : keyspace -> table -> string list -> bool list Lwt.t * Count the keys in the given range : [ count_keys tx table range ] is * functionality equivalent to [ get_keys tx table range > |= ] * but somewhat faster , by a constant factor , and more memory - efficient . * functionality equivalent to [get_keys tx table range >|= List.length] * but somewhat faster, by a constant factor, and more memory-efficient. *) val count_keys : keyspace -> table -> string key_range -> Int64.t Lwt.t * [ get_slice tx table ? max_keys ? max_columns ? decode_timestamp * key_range ? predicate column_range ] returns a data slice corresponding * to the keys included in the [ key_range ] which contain at least one of * the columns specified in the [ column_range ] and satisfy the * [ predicate ] . * * If the key range is [ ` Discrete l ] and the column range is a [ Column_range ] * the columns will be returned : * * in lexicographic order , if the column range is not reverse * * in reverse lexicographic order , if the column range is reverse * * For the sake of efficiency , if the key range is [ ` Continuous _ ] , the * columns are selected : * * in lexicographic order , if the key range is not [ reverse ] * * in reverse lexicographic order , if the key range is [ reverse ] * * @param max_keys return no more than [ max_keys ] keys * @param return no more than [ max_columns ] columns per key * @param decode_timestamp whether to decode the timestamp ( default : false ) * * key_range ?predicate column_range] returns a data slice corresponding * to the keys included in the [key_range] which contain at least one of * the columns specified in the [column_range] and satisfy the * [predicate]. * * If the key range is [`Discrete l] and the column range is a [Column_range] * the columns will be returned: * * in lexicographic order, if the column range is not reverse * * in reverse lexicographic order, if the column range is reverse * * For the sake of efficiency, if the key range is [`Continuous _], the * columns are selected: * * in lexicographic order, if the key range is not [reverse] * * in reverse lexicographic order, if the key range is [reverse] * * @param max_keys return no more than [max_keys] keys * @param max_columns return no more than [max_columns] columns per key * @param decode_timestamp whether to decode the timestamp (default: false) * *) val get_slice : keyspace -> table -> ?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool -> string key_range -> ?predicate:row_predicate -> column_range -> (string, string) slice Lwt.t * [ get_slice_values tx table key_range [ " col1 " ; " col2 " ] ] * returns [ Some last_key , l ] if at least a key was selected , where [ l ] is * an associative list whose elements are pairs containing the key and a list * of value options corresponding to the requested columns ( in the order they * were given to [ get_slice_values ] ) . A key is selected if : * * it is specified in a [ ` Discrete l ] range * * it exists in the given [ ` Continuous r ] range * returns [Some last_key, l] if at least a key was selected, where [l] is * an associative list whose elements are pairs containing the key and a list * of value options corresponding to the requested columns (in the order they * were given to [get_slice_values]). A key is selected if: * * it is specified in a [`Discrete l] range * * it exists in the given [`Continuous r] range *) val get_slice_values : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * string option list) list) Lwt.t * Similar to [ get_slice_values ] , but returning the data and the * timestamp in since the beginning of the Unix epoch . * timestamp in microsends since the beginning of the Unix epoch. *) val get_slice_values_with_timestamps : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * (string * Int64.t) option list) list) Lwt.t (** @return [Some last_column_name, column_list] if any column exists for the * selected key, [None] otherwise. *) val get_columns : keyspace -> table -> ?max_columns:int -> ?decode_timestamps:bool -> key -> column_range -> (column_name * (string column list)) option Lwt.t (** [get_column_values tx table key columns] returns the data associated to * the given [columns] (if existent). If [key] doesn't exist (that is, it has * got no associated columns), all the values will be [None]. *) val get_column_values : keyspace -> table -> key -> column_name list -> string option list Lwt.t val get_column : keyspace -> table -> key -> column_name -> (string * timestamp) option Lwt.t * { 3 } Write operations val put_columns : keyspace -> table -> key -> string column list -> unit Lwt.t val put_multi_columns : keyspace -> table -> (key * string column list) list -> unit Lwt.t val delete_columns : keyspace -> table -> key -> column_name list -> unit Lwt.t val delete_key : keyspace -> table -> key -> unit Lwt.t val delete_keys : keyspace -> table -> string key_range -> unit Lwt.t * { 3 } Asynchronous notifications * [ listen ] allows to receive notifications sent to the specified * [ topic ] in the keyspace [ ks ] . Note that [ listen ] is not affected by * surrounding transactions , i.e. , the subscription is performed even if * the surrounding transaction is canceled . * Note that subscriptions are per [ keyspace ] , not per keyspace name : it is * possible to subscribe to different topics in two different [ keyspace ] * objects which operate on the same DB keyspace . * * [topic] in the keyspace [ks]. Note that [listen] is not affected by * surrounding transactions, i.e., the subscription is performed even if * the surrounding transaction is canceled. * Note that subscriptions are per [keyspace], not per keyspace name: it is * possible to subscribe to different topics in two different [keyspace] * objects which operate on the same DB keyspace. * *) val listen : keyspace -> string -> unit Lwt.t * [ listen_prefix ks prefix ] allows to receive notifications sent to topics * which are ( possibly improper ) suffixes of [ prefix ] in the keyspace [ ks ] . * Note that [ listen_prefix ] is not affected by surrounding transactions , * i.e. , the subscription is performed even if the surrounding transaction * is canceled . * * If a notification would match several regular topics and prefixes , only * one notification is returned . * * Note that subscriptions are per [ keyspace ] , not per keyspace name : it is * possible to subscribe to different topics in two different [ keyspace ] * objects which operate on the same DB keyspace . * * which are (possibly improper) suffixes of [prefix] in the keyspace [ks]. * Note that [listen_prefix] is not affected by surrounding transactions, * i.e., the subscription is performed even if the surrounding transaction * is canceled. * * If a notification would match several regular topics and prefixes, only * one notification is returned. * * Note that subscriptions are per [keyspace], not per keyspace name: it is * possible to subscribe to different topics in two different [keyspace] * objects which operate on the same DB keyspace. * *) val listen_prefix : keyspace -> string -> unit Lwt.t (** [unlisten ks topìc] signals that further notifications sent to the [topic] * in the keyspace [ks] will not be received. Notifications that were * already queued in the server will not be discarded, however. * Note that [unlisten] is not affected by surrounding transactions, i.e., * the unsubscription is performed even if the surrounding transaction is * canceled. *) val unlisten : keyspace -> string -> unit Lwt.t (** [unlisten_prefix ks prefix] signals that further notifications sent to * topics which are (possibly improper) suffixes of [prefix] are not to be * received anymore. Notifications that were already queued in the server * will not be discarded, however. * * Note that [unlisten_prefix] is not affected by surrounding transactions, * i.e., the unsubscription is performed even if the surrounding * transaction is canceled. *) val unlisten_prefix : keyspace -> string -> unit Lwt.t (** [notify ks topic] sends a notification associated to the given [topic] * in keyspace [ks], which will be received by all the connections that * performed [listen] on the same [ks]/[topic]. [notify] honors surrounding * transactions, i.e., the notification will be actually performed only * when/if the outermost surrounding transaction is committed, and no * notification is sent if any of the surrounding transactions is aborted. * * Multiple notifications for the same topic within a transaction might be * coalesced, and no assumption should be made about the order in which the * notifications are reported to the listeners. * *) val notify : keyspace -> string -> unit Lwt.t (** Return queued notifications, blocking if there is none yet. * An empty list will be returned when there are no more queued * notifications and the underlying connection is closed. * *) val await_notifications : keyspace -> string list Lwt.t * { 3 Backup } type backup_cursor val dump : keyspace -> ?format:backup_format -> ?only_tables:table list -> ?offset:backup_cursor -> unit -> (string * backup_cursor option) option Lwt.t (** [load tx data] returns [false] if the data is in an unknown format. *) val load : keyspace -> string -> bool Lwt.t module Raw_dump : RAW_DUMP with type db := db (** {3 Administration} *) (** Load statistics *) val load_stats : keyspace -> Obs_load_stats.stats Lwt.t (** [dump_info property] returns information about the state of the DB if * [property] is understood by the DB implementation. *) val get_property : db -> string -> string option Lwt.t (** Trigger whole keyspace compaction. *) val compact : keyspace -> unit Lwt.t * [ compact_table ks table ? from_key ? to_key ( ) ] compacts the table between * keys [ from_key ] and [ to_key ] ( inclusive , defaulting to the beginning / end * of the table if not suppplied ) . * keys [from_key] and [to_key] (inclusive, defaulting to the beginning/end * of the table if not suppplied). *) val compact_table : keyspace -> table -> ?from_key:string -> ?to_key:string -> unit -> unit Lwt.t (** List currently executing transactions. *) val list_transactions : keyspace -> tx_info list Lwt.t (** List keys of tables modified so far in the specified transaction. *) val changed_tables : keyspace -> tx_id -> string list Lwt.t end * DB operations with BSON - encoded columns : columns whose name begins with * ' @ ' are BSON - encoded . All the extra functions in { ! S } are similar to those * in { ! RAW_S } but decode / encode properly such columns . * '@' are BSON-encoded. All the extra functions in {!S} are similar to those * in {!RAW_S} but decode/encode properly such columns. *) module type S = sig include RAW_S * { 3 Read operations } * Similar to { ! get_slice } , but decodes the BSON - encoded records in columns * whose name begins with [ @ ] . * whose name begins with [@]. *) val get_bson_slice : keyspace -> table -> ?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool -> string key_range -> ?predicate:row_predicate -> column_range -> (string, decoded_data) slice Lwt.t (** Refer to {!get_slice_values}. *) val get_bson_slice_values : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * decoded_data option list) list) Lwt.t * Refer to { ! } . val get_bson_slice_values_with_timestamps : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * (decoded_data * Int64.t) option list) list) Lwt.t (** Refer to {!get_columns}. *) val get_bson_columns : keyspace -> table -> ?max_columns:int -> ?decode_timestamps:bool -> key -> column_range -> (column_name * (decoded_data column list)) option Lwt.t (** Refer to {!get_column_values}. *) val get_bson_column_values : keyspace -> table -> key -> column_name list -> decoded_data option list Lwt.t (** Refer to {!get_column}. *) val get_bson_column : keyspace -> table -> key -> column_name -> (decoded_data * timestamp) option Lwt.t * { 3 Write operations } * Refer to { ! } . * @raise Invalid_BSON_column if the data for any is not [ BSON x ] . * @raise Invalid_BSON_column if the data for any @column is not [BSON x]. *) val put_bson_columns : keyspace -> table -> key -> decoded_data column list -> unit Lwt.t * Refer to { ! } . * @raise Invalid_BSON_column if the data for any is not [ BSON x ] . * @raise Invalid_BSON_column if the data for any @column is not [BSON x]. *) val put_multi_bson_columns : keyspace -> table -> (key * decoded_data column list) list -> unit Lwt.t end module type BACKUP_SUPPORT = sig type backup_cursor val string_of_cursor : backup_cursor -> string val cursor_of_string : string -> backup_cursor option end
null
https://raw.githubusercontent.com/mfp/obigstore/1b078eeb21e11c8de986717150c7108a94778095/src/core/obs_data_model.mli
ocaml
* column name * Exception raised when a watched key/column has been modified while a write * transaction is being performed. * Exception raised by the {!lock} operation if a deadlock is detected. * Operation denied owning to insufficient permissions or invalid * credentials. * Name of last column in the following list * last_key * data * Predicate on the value of a colum * don't care about the value * each bool indicating whether inclusive * [name, predicate] all of them any of them * Specify transaction semantics. * Synchronous commit, with full fsync (unless disabled globally) * Asynchronous commit, without fsync. Durability not guaranteed * in the event of system crashes. * In outermost transaction: use synchronous commit. * In nested transactions: inherit parent mode * (can still be modified by a child transaction). * Request that the current state of the DB be dumped. * Allow to release the resources associated to the dump (e.g., delete * the actual data). Further operations on the dump will fail. * DB operations with opaque columns. * Similar to [register_keyspace], but only returns [Some ks] if the * keyspace exists in the DB. * List the tables that contained data at the time the outermost * transaction began. * @return approximate size on disk of the data for the given table. * @return approximate size on disk of the data for the given key range in * the specified table. TX1 TX2 TX3 perform transaction * [watch_prefixes ks table prefixes] is similar to {!watch_keys}, but is * given a prefix of the keys to watch; e.g., if you do * [watch_prefixes ks tbl ["foo"; "bar"]], write transactions will abort * with [Dirty_data] if any keys starting with [foo] or [bar] (inclusive) * are modified by a concurrent transaction * Return up to [max_keys] keys (default: [max_int]) in the given range. * [exists_key ks table k] returns [true] if any column with the given * [key] exists in the given [table] within the keyspace [ks]. * [exist_keys ks table keys] returns a list of bools indicating whether * each key in [keys] has got any column in the given [table] within the * keyspace [ks]. * @return [Some last_column_name, column_list] if any column exists for the * selected key, [None] otherwise. * [get_column_values tx table key columns] returns the data associated to * the given [columns] (if existent). If [key] doesn't exist (that is, it has * got no associated columns), all the values will be [None]. * [unlisten ks topìc] signals that further notifications sent to the [topic] * in the keyspace [ks] will not be received. Notifications that were * already queued in the server will not be discarded, however. * Note that [unlisten] is not affected by surrounding transactions, i.e., * the unsubscription is performed even if the surrounding transaction is * canceled. * [unlisten_prefix ks prefix] signals that further notifications sent to * topics which are (possibly improper) suffixes of [prefix] are not to be * received anymore. Notifications that were already queued in the server * will not be discarded, however. * * Note that [unlisten_prefix] is not affected by surrounding transactions, * i.e., the unsubscription is performed even if the surrounding * transaction is canceled. * [notify ks topic] sends a notification associated to the given [topic] * in keyspace [ks], which will be received by all the connections that * performed [listen] on the same [ks]/[topic]. [notify] honors surrounding * transactions, i.e., the notification will be actually performed only * when/if the outermost surrounding transaction is committed, and no * notification is sent if any of the surrounding transactions is aborted. * * Multiple notifications for the same topic within a transaction might be * coalesced, and no assumption should be made about the order in which the * notifications are reported to the listeners. * * Return queued notifications, blocking if there is none yet. * An empty list will be returned when there are no more queued * notifications and the underlying connection is closed. * * [load tx data] returns [false] if the data is in an unknown format. * {3 Administration} * Load statistics * [dump_info property] returns information about the state of the DB if * [property] is understood by the DB implementation. * Trigger whole keyspace compaction. * List currently executing transactions. * List keys of tables modified so far in the specified transaction. * Refer to {!get_slice_values}. * Refer to {!get_columns}. * Refer to {!get_column_values}. * Refer to {!get_column}.
* Copyright ( C ) 2011 - 2013 < > * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Copyright (C) 2011-2013 Mauricio Fernandez <> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) * { 2 Type definitions } * Exception raised when inserting an invalid BSON [ @column ] . exception Dirty_data exception Deadlock exception Denied type table = private string val string_of_table : table -> string val table_of_string : string -> table type key = string type 'data column = { name : column_name; data : 'data; timestamp : timestamp; } and column_name = string and timestamp = No_timestamp | Timestamp of Int64.t type decoded_data = Binary of string | BSON of Obs_bson.document | Malformed_BSON of string type ('key, 'data) key_data = { key : 'key; columns : 'data column list; } * Range representing elements between [ first ] ( inclusive if reverse is * false , exclusive otherwise ) and [ up_to ] * ( exclusive if reverse is false , inclusive otherwise ) . If [ first ] is not * provided , the range starts with the first available element ( last , if * [ reverse ] is [ true ] ) ; likewise , if [ up_to ] is not provided , the elements * until the last ( first , if [ reverse is [ true ] ) one are selected . * * Summarizing : * * * if reverse is false , elements x such that [ first < = x < up_to ] * * if reverse is true , elements x such that [ first > x > = up_to ] * * where a side of the inequality disappears if the corresponding value * ( [ first ] or [ up_to ] ) is [ None ] . * * false, exclusive otherwise) and [up_to] * (exclusive if reverse is false, inclusive otherwise). If [first] is not * provided, the range starts with the first available element (last, if * [reverse] is [true]); likewise, if [up_to] is not provided, the elements * until the last (first, if [reverse is [true]) one are selected. * * Summarizing: * * * if reverse is false, elements x such that [first <= x < up_to] * * if reverse is true, elements x such that [first > x >= up_to] * * where a side of the inequality disappears if the corresponding value * ([first] or [up_to]) is [None]. * *) type 'key range = { first : 'key option; up_to : 'key option; reverse : bool; } type 'key cont_or_discrete_range = [ `Continuous of 'key range | `Discrete of 'key list ] type 'key key_range = [ 'key cont_or_discrete_range | `All] type column_range = [ string key_range | `Union of string cont_or_discrete_range list ] type column_val_rel = | EQ of string | LT of string | GT of string | GE of string | LE of string type simple_row_predicate = type backup_format = int type raw_dump_timestamp = Int64.t type tx_id = Int64.t type lock_kind = [`SHARED | `EXCLUSIVE] type tx_info = { tx_id : tx_id; started_at : float; wanted_locks : (string * lock_kind) list; held_locks : (string * lock_kind) list; } type sync_mode = ] { 2 Data model } module type RAW_DUMP = sig type db type raw_dump val dump : db -> mode:[`Sync | `Async | `No_stream] -> raw_dump Lwt.t val release : raw_dump -> keep_files:bool -> unit Lwt.t val timestamp : raw_dump -> raw_dump_timestamp Lwt.t val localdir : raw_dump -> string Lwt.t val list_files : raw_dump -> (string * Int64.t) list Lwt.t val file_digest : raw_dump -> string -> string option Lwt.t val open_file : raw_dump -> ?offset:Int64.t -> string -> Lwt_io.input_channel option Lwt.t end module type RAW_S = sig type db type keyspace val list_keyspaces : db -> string list Lwt.t * Register the keyspace in the DB and return a new [ keyspace ] object . * Different calls to [ register_keyspace name ] with the same [ name ] * return different values ( allowing to perform transactions on them * independently ) . * Different calls to [register_keyspace name] with the same [name] * return different values (allowing to perform transactions on them * independently). *) val register_keyspace : db -> string -> keyspace Lwt.t val get_keyspace : db -> string -> keyspace option Lwt.t val keyspace_name : keyspace -> string val keyspace_id : keyspace -> int val list_tables : keyspace -> table list Lwt.t val table_size_on_disk : keyspace -> table -> Int64.t Lwt.t val key_range_size_on_disk : keyspace -> ?first:string -> ?up_to:string -> table -> Int64.t Lwt.t * { 3 Transactions } * [ read_committed_transaction ks f ] runs [ f ] in a transaction . * Within [ f ] , the effect of other transactions committed after its * evaluation started will be visible . * * Note that nested transactions can be executed concurrenty * ( with [ lwt x = read_committed_transaction f a and * y = read_committed_transaction f b ] , [ Lwt.join ] or similar ) * but the server can choose to serialize their execution . * * Also note that " simple " operations such as { ! } are performed * within an implicit transaction . * * This means that code like the following is dangerous : * { [ * read_committed_transaction ks ( * * Within [f], the effect of other transactions committed after its * evaluation started will be visible. * * Note that nested transactions can be executed concurrenty * (with [lwt x = read_committed_transaction f a and * y = read_committed_transaction f b], [Lwt.join] or similar) * but the server can choose to serialize their execution. * * Also note that "simple" operations such as {!put_columns} are performed * within an implicit transaction. * * This means that code like the following is dangerous: * {[ * (fun ks -> * (fun ks2 -> * put_columns ks2 tbl2 key2 cols2)) * ]} * This code can hang if the server serializes concurrent, nested * transaction, because [put_columns ks ...] starts an implicit * transaction [TX3] whose execution will start only once the * [TX2] transaction completes, but [TX2] will not finish until [TX3] is * done. * * @param sync Specify sync mode. The final sync mode used on commit for * the outermost transaction is the most restrictive amongst the ones * specified by it and its descendents (e.g., if any uses [~sync:`Sync], * this is the mode that will be used, regardless of what [sync] mode was * used in the outermost transaction). Default value: [`Default] (refer to * {!sync_mode}. *) val read_committed_transaction : ?sync:sync_mode -> keyspace -> (keyspace -> 'a Lwt.t) -> 'a Lwt.t * [ repeatable_read_transaction ks f ] runs [ f ] in a transaction . * Two read operations with the same parameters performed in [ f ] 's scope * are guaranteed to return the same results ( unless [ f ] itself wrote * data ) , regardless of whether other transactions have committed data or * not . * * Refer to { ! read_committed_transaction } for information on concurrent * execution of nested transactions . * * Two read operations with the same parameters performed in [f]'s scope * are guaranteed to return the same results (unless [f] itself wrote * data), regardless of whether other transactions have committed data or * not. * * Refer to {!read_committed_transaction} for information on concurrent * execution of nested transactions. * *) val repeatable_read_transaction : ?sync:sync_mode -> keyspace -> (keyspace -> 'a Lwt.t) -> 'a Lwt.t * [ ks ] returns the ID of the current and outermost * transaction ( useful for logging and reporting ) , or None if not inside a * transaction . * transaction (useful for logging and reporting), or None if not inside a * transaction. *) val transaction_id : keyspace -> (int * int) option Lwt.t * [ lock ks ~shared l ] acquire locks with names given in [ l ] for the DB * keyspace [ ks ] . Each DB keyspace defines a different * lock namespace ; therefore different [ keyspace ] values for the same * underlying DB keyspace share the same namespace . * The locks will be released automatically when the outermost transaction * is committed or aborted . [ lock ] is a NOP unless inside a transaction . * * @param shared indicates whether shared or exclusive locks are to be * acquired * keyspace [keyspace_name ks]. Each DB keyspace defines a different * lock namespace; therefore different [keyspace] values for the same * underlying DB keyspace share the same namespace. * The locks will be released automatically when the outermost transaction * is committed or aborted. [lock] is a NOP unless inside a transaction. * * @param shared indicates whether shared or exclusive locks are to be * acquired *) val lock : keyspace -> shared:bool -> string list -> unit Lwt.t * [ watch_keys ks table keys ] will make write transactions raise * [ Dirty_data ] if a column belonging to any of the given keys is modified * ( added , updated or deleted ) after the call to [ watch_keys ] . * * It is used to perform optimistic concurrency control as follows : * { [ * let attempt ( ) = * begin fun ks - > * watch_keys ks accounts [ account_key ] > > * lwt n = get_column ks accounts account_key " balance " > |= * fst > |= int_of_string * in * put_columns ks accounts account_key * [ { name = " balance " ; data = string_of_int ( n + 1 ) ; * timestamp = No_timestamp ; } ] * end in * let rec retry_if_needed ( ) = * try_lwt attempt ( ) with Dirty_data - > retry_if_needed ( ) * in * ( * perform transaction * [Dirty_data] if a column belonging to any of the given keys is modified * (added, updated or deleted) after the call to [watch_keys]. * * It is used to perform optimistic concurrency control as follows: * {[ * let attempt () = * read_committed_transaction ks begin fun ks -> * watch_keys ks accounts [account_key] >> * lwt n = get_column ks accounts account_key "balance" >|= * fst >|= int_of_string * in * put_columns ks accounts account_key * [ { name = "balance"; data = string_of_int (n + 1); * timestamp = No_timestamp; } ] * end in * let rec retry_if_needed () = * try_lwt attempt () with Dirty_data -> retry_if_needed () * in * retry_if_needed () * ]} * *) val watch_keys : keyspace -> table -> string list -> unit Lwt.t * [ watch_columns ks table l ] is similar to { ! watch_keys } , but instead of * watching the whole keys , only the specified columns are considered , e.g. * [ watch_keys ks table [ " key1 " , [ " col1 " , " col2 " ] ; " key2 " , [ " col2 " ] ] ] . * watching the whole keys, only the specified columns are considered, e.g. * [watch_keys ks table ["key1", ["col1", "col2"]; "key2", ["col2"]]]. *) val watch_columns : keyspace -> table -> (string * string list) list -> unit Lwt.t val watch_prefixes : keyspace -> table -> string list -> unit Lwt.t * { 3 Read operations } val get_keys : keyspace -> table -> ?max_keys:int -> string key_range -> string list Lwt.t val exists_key : keyspace -> table -> string -> bool Lwt.t val exist_keys : keyspace -> table -> string list -> bool list Lwt.t * Count the keys in the given range : [ count_keys tx table range ] is * functionality equivalent to [ get_keys tx table range > |= ] * but somewhat faster , by a constant factor , and more memory - efficient . * functionality equivalent to [get_keys tx table range >|= List.length] * but somewhat faster, by a constant factor, and more memory-efficient. *) val count_keys : keyspace -> table -> string key_range -> Int64.t Lwt.t * [ get_slice tx table ? max_keys ? max_columns ? decode_timestamp * key_range ? predicate column_range ] returns a data slice corresponding * to the keys included in the [ key_range ] which contain at least one of * the columns specified in the [ column_range ] and satisfy the * [ predicate ] . * * If the key range is [ ` Discrete l ] and the column range is a [ Column_range ] * the columns will be returned : * * in lexicographic order , if the column range is not reverse * * in reverse lexicographic order , if the column range is reverse * * For the sake of efficiency , if the key range is [ ` Continuous _ ] , the * columns are selected : * * in lexicographic order , if the key range is not [ reverse ] * * in reverse lexicographic order , if the key range is [ reverse ] * * @param max_keys return no more than [ max_keys ] keys * @param return no more than [ max_columns ] columns per key * @param decode_timestamp whether to decode the timestamp ( default : false ) * * key_range ?predicate column_range] returns a data slice corresponding * to the keys included in the [key_range] which contain at least one of * the columns specified in the [column_range] and satisfy the * [predicate]. * * If the key range is [`Discrete l] and the column range is a [Column_range] * the columns will be returned: * * in lexicographic order, if the column range is not reverse * * in reverse lexicographic order, if the column range is reverse * * For the sake of efficiency, if the key range is [`Continuous _], the * columns are selected: * * in lexicographic order, if the key range is not [reverse] * * in reverse lexicographic order, if the key range is [reverse] * * @param max_keys return no more than [max_keys] keys * @param max_columns return no more than [max_columns] columns per key * @param decode_timestamp whether to decode the timestamp (default: false) * *) val get_slice : keyspace -> table -> ?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool -> string key_range -> ?predicate:row_predicate -> column_range -> (string, string) slice Lwt.t * [ get_slice_values tx table key_range [ " col1 " ; " col2 " ] ] * returns [ Some last_key , l ] if at least a key was selected , where [ l ] is * an associative list whose elements are pairs containing the key and a list * of value options corresponding to the requested columns ( in the order they * were given to [ get_slice_values ] ) . A key is selected if : * * it is specified in a [ ` Discrete l ] range * * it exists in the given [ ` Continuous r ] range * returns [Some last_key, l] if at least a key was selected, where [l] is * an associative list whose elements are pairs containing the key and a list * of value options corresponding to the requested columns (in the order they * were given to [get_slice_values]). A key is selected if: * * it is specified in a [`Discrete l] range * * it exists in the given [`Continuous r] range *) val get_slice_values : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * string option list) list) Lwt.t * Similar to [ get_slice_values ] , but returning the data and the * timestamp in since the beginning of the Unix epoch . * timestamp in microsends since the beginning of the Unix epoch. *) val get_slice_values_with_timestamps : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * (string * Int64.t) option list) list) Lwt.t val get_columns : keyspace -> table -> ?max_columns:int -> ?decode_timestamps:bool -> key -> column_range -> (column_name * (string column list)) option Lwt.t val get_column_values : keyspace -> table -> key -> column_name list -> string option list Lwt.t val get_column : keyspace -> table -> key -> column_name -> (string * timestamp) option Lwt.t * { 3 } Write operations val put_columns : keyspace -> table -> key -> string column list -> unit Lwt.t val put_multi_columns : keyspace -> table -> (key * string column list) list -> unit Lwt.t val delete_columns : keyspace -> table -> key -> column_name list -> unit Lwt.t val delete_key : keyspace -> table -> key -> unit Lwt.t val delete_keys : keyspace -> table -> string key_range -> unit Lwt.t * { 3 } Asynchronous notifications * [ listen ] allows to receive notifications sent to the specified * [ topic ] in the keyspace [ ks ] . Note that [ listen ] is not affected by * surrounding transactions , i.e. , the subscription is performed even if * the surrounding transaction is canceled . * Note that subscriptions are per [ keyspace ] , not per keyspace name : it is * possible to subscribe to different topics in two different [ keyspace ] * objects which operate on the same DB keyspace . * * [topic] in the keyspace [ks]. Note that [listen] is not affected by * surrounding transactions, i.e., the subscription is performed even if * the surrounding transaction is canceled. * Note that subscriptions are per [keyspace], not per keyspace name: it is * possible to subscribe to different topics in two different [keyspace] * objects which operate on the same DB keyspace. * *) val listen : keyspace -> string -> unit Lwt.t * [ listen_prefix ks prefix ] allows to receive notifications sent to topics * which are ( possibly improper ) suffixes of [ prefix ] in the keyspace [ ks ] . * Note that [ listen_prefix ] is not affected by surrounding transactions , * i.e. , the subscription is performed even if the surrounding transaction * is canceled . * * If a notification would match several regular topics and prefixes , only * one notification is returned . * * Note that subscriptions are per [ keyspace ] , not per keyspace name : it is * possible to subscribe to different topics in two different [ keyspace ] * objects which operate on the same DB keyspace . * * which are (possibly improper) suffixes of [prefix] in the keyspace [ks]. * Note that [listen_prefix] is not affected by surrounding transactions, * i.e., the subscription is performed even if the surrounding transaction * is canceled. * * If a notification would match several regular topics and prefixes, only * one notification is returned. * * Note that subscriptions are per [keyspace], not per keyspace name: it is * possible to subscribe to different topics in two different [keyspace] * objects which operate on the same DB keyspace. * *) val listen_prefix : keyspace -> string -> unit Lwt.t val unlisten : keyspace -> string -> unit Lwt.t val unlisten_prefix : keyspace -> string -> unit Lwt.t val notify : keyspace -> string -> unit Lwt.t val await_notifications : keyspace -> string list Lwt.t * { 3 Backup } type backup_cursor val dump : keyspace -> ?format:backup_format -> ?only_tables:table list -> ?offset:backup_cursor -> unit -> (string * backup_cursor option) option Lwt.t val load : keyspace -> string -> bool Lwt.t module Raw_dump : RAW_DUMP with type db := db val load_stats : keyspace -> Obs_load_stats.stats Lwt.t val get_property : db -> string -> string option Lwt.t val compact : keyspace -> unit Lwt.t * [ compact_table ks table ? from_key ? to_key ( ) ] compacts the table between * keys [ from_key ] and [ to_key ] ( inclusive , defaulting to the beginning / end * of the table if not suppplied ) . * keys [from_key] and [to_key] (inclusive, defaulting to the beginning/end * of the table if not suppplied). *) val compact_table : keyspace -> table -> ?from_key:string -> ?to_key:string -> unit -> unit Lwt.t val list_transactions : keyspace -> tx_info list Lwt.t val changed_tables : keyspace -> tx_id -> string list Lwt.t end * DB operations with BSON - encoded columns : columns whose name begins with * ' @ ' are BSON - encoded . All the extra functions in { ! S } are similar to those * in { ! RAW_S } but decode / encode properly such columns . * '@' are BSON-encoded. All the extra functions in {!S} are similar to those * in {!RAW_S} but decode/encode properly such columns. *) module type S = sig include RAW_S * { 3 Read operations } * Similar to { ! get_slice } , but decodes the BSON - encoded records in columns * whose name begins with [ @ ] . * whose name begins with [@]. *) val get_bson_slice : keyspace -> table -> ?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool -> string key_range -> ?predicate:row_predicate -> column_range -> (string, decoded_data) slice Lwt.t val get_bson_slice_values : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * decoded_data option list) list) Lwt.t * Refer to { ! } . val get_bson_slice_values_with_timestamps : keyspace -> table -> ?max_keys:int -> string key_range -> column_name list -> (key option * (key * (decoded_data * Int64.t) option list) list) Lwt.t val get_bson_columns : keyspace -> table -> ?max_columns:int -> ?decode_timestamps:bool -> key -> column_range -> (column_name * (decoded_data column list)) option Lwt.t val get_bson_column_values : keyspace -> table -> key -> column_name list -> decoded_data option list Lwt.t val get_bson_column : keyspace -> table -> key -> column_name -> (decoded_data * timestamp) option Lwt.t * { 3 Write operations } * Refer to { ! } . * @raise Invalid_BSON_column if the data for any is not [ BSON x ] . * @raise Invalid_BSON_column if the data for any @column is not [BSON x]. *) val put_bson_columns : keyspace -> table -> key -> decoded_data column list -> unit Lwt.t * Refer to { ! } . * @raise Invalid_BSON_column if the data for any is not [ BSON x ] . * @raise Invalid_BSON_column if the data for any @column is not [BSON x]. *) val put_multi_bson_columns : keyspace -> table -> (key * decoded_data column list) list -> unit Lwt.t end module type BACKUP_SUPPORT = sig type backup_cursor val string_of_cursor : backup_cursor -> string val cursor_of_string : string -> backup_cursor option end
88e78424740a27a550dec1966b98709e7da26417a2de2fc9c545702bc44c6b98
evrim/core-server
filesystem.lisp
Core Server : Web Application Server Copyright ( C ) 2006 - 2008 , Aycan iRiCAN ;; 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 3 of the License , or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;; Filesystem abstraction as a service ;;+---------------------------------------------------------------------------- ;; ;; Usage: create a filesystem service, ;; ;; (defparameter *fs* ;; (make-instance 'filesystem :root *project-docs-root* :label *project-name*)) ;; Second parameter must be a relative pathname , ;; ;; (writefile *fs* #P"staff/introduction.txt" "Here we go...") ;; (readfile *fs* #P"staff/introduction.txt") ( list - directory * fs * # P"pictures/ " : recursive t ) ;; /~sabetts/slurp.html (defun slurp-stream5 (stream) (let ((seq (make-array (file-length stream) :element-type 'character :fill-pointer t))) (setf (fill-pointer seq) (read-sequence seq stream)) seq)) (defclass filesystem (local-unit) ((label :accessor filesystem.label :initarg :label :initform "") (root :accessor filesystem.root :initarg :root :initform (error "Filesystem root must be set!")))) security & validator layer (defmacro with-guard ((fs filepath) &body body) (let* ((errors (gensym))) `(let ((,errors (list #'(lambda () (error "Filesystem null!")) #'(lambda () (error "You must use relative paths!")))) (ret (cond ((null ,fs) (function car)) ((and (pathname-directory ,filepath) (not (eq :RELATIVE (car (pathname-directory ,filepath))))) (function cadr)) (t (let ((res (progn ,@body))) #'(lambda (x) (declare (ignore x)) #'(lambda () res))))))) (funcall (funcall ret ,errors))))) ;; filesystem -> pathname -> IO String (defmethod/unit readfile :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (with-open-file (s (merge-pathnames filepath (filesystem.root self))) (slurp-stream5 s)))) ;; filesystem -> pathname -> data -> IO String (defmethod/unit writefile :async-no-return ((self filesystem) filepath data) (with-guard (self filepath) (with-output-to-file (s (merge-pathnames filepath (filesystem.root self))) :if-exists :overwrite :if-does-not-exist :create (write-sequence data s)))) ;; filesystem -> pathname -> IO Bool (defmethod/unit deletefile :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (delete-file (merge-pathnames filepath (filesystem.root self))))) ;; filesystem -> pathname -> pathname -> IO Bool (defmethod/unit movefile :async-no-return ((self filesystem) src dst) (error "Not implemented yet.")) ;; filesystem -> pathname -> IO [pathname] (defmethod/unit ls :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (cl-fad::list-directory (merge-pathnames filepath (filesystem.root self))))) (defmethod/unit fold-directory :async-no-return ((self filesystem) filepath fun) (with-guard (self filepath) (cl-fad:walk-directory (merge-pathnames filepath (filesystem.root self)) fun :directories t :if-does-not-exist :error)))
null
https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/src/services/filesystem.lisp
lisp
This program is free software: you can redistribute it and/or modify (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. along with this program. If not, see </>. +---------------------------------------------------------------------------- Filesystem abstraction as a service +---------------------------------------------------------------------------- Usage: create a filesystem service, (defparameter *fs* (make-instance 'filesystem :root *project-docs-root* :label *project-name*)) (writefile *fs* #P"staff/introduction.txt" "Here we go...") (readfile *fs* #P"staff/introduction.txt") /~sabetts/slurp.html filesystem -> pathname -> IO String filesystem -> pathname -> data -> IO String filesystem -> pathname -> IO Bool filesystem -> pathname -> pathname -> IO Bool filesystem -> pathname -> IO [pathname]
Core Server : Web Application Server Copyright ( C ) 2006 - 2008 , Aycan iRiCAN it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (in-package :tr.gen.core.server) Second parameter must be a relative pathname , ( list - directory * fs * # P"pictures/ " : recursive t ) (defun slurp-stream5 (stream) (let ((seq (make-array (file-length stream) :element-type 'character :fill-pointer t))) (setf (fill-pointer seq) (read-sequence seq stream)) seq)) (defclass filesystem (local-unit) ((label :accessor filesystem.label :initarg :label :initform "") (root :accessor filesystem.root :initarg :root :initform (error "Filesystem root must be set!")))) security & validator layer (defmacro with-guard ((fs filepath) &body body) (let* ((errors (gensym))) `(let ((,errors (list #'(lambda () (error "Filesystem null!")) #'(lambda () (error "You must use relative paths!")))) (ret (cond ((null ,fs) (function car)) ((and (pathname-directory ,filepath) (not (eq :RELATIVE (car (pathname-directory ,filepath))))) (function cadr)) (t (let ((res (progn ,@body))) #'(lambda (x) (declare (ignore x)) #'(lambda () res))))))) (funcall (funcall ret ,errors))))) (defmethod/unit readfile :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (with-open-file (s (merge-pathnames filepath (filesystem.root self))) (slurp-stream5 s)))) (defmethod/unit writefile :async-no-return ((self filesystem) filepath data) (with-guard (self filepath) (with-output-to-file (s (merge-pathnames filepath (filesystem.root self))) :if-exists :overwrite :if-does-not-exist :create (write-sequence data s)))) (defmethod/unit deletefile :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (delete-file (merge-pathnames filepath (filesystem.root self))))) (defmethod/unit movefile :async-no-return ((self filesystem) src dst) (error "Not implemented yet.")) (defmethod/unit ls :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (cl-fad::list-directory (merge-pathnames filepath (filesystem.root self))))) (defmethod/unit fold-directory :async-no-return ((self filesystem) filepath fun) (with-guard (self filepath) (cl-fad:walk-directory (merge-pathnames filepath (filesystem.root self)) fun :directories t :if-does-not-exist :error)))
6ccdd483578e22af4afd1c97ecd92566c2d1d8dbbb480864af4cff1f9c221170
Kappa-Dev/KappaTools
dynamicArray.mli
module DynArray: functor (_:GenArray.GenArray) -> GenArray.GenArray
null
https://raw.githubusercontent.com/Kappa-Dev/KappaTools/5e756eb3529db9976cf0a0884a22676925985978/core/dataStructures/dynamicArray.mli
ocaml
module DynArray: functor (_:GenArray.GenArray) -> GenArray.GenArray
dc2437e68a7bcd911633f0604bb9110feaeb148c816c70ccec6492ca2f0fc0b0
mirage/colombe
domain.mli
type t = | IPv4 of Ipaddr.V4.t | IPv6 of Ipaddr.V6.t | Extension of string * string | Domain of string list val compare : t -> t -> int val equal : t -> t -> bool val pp : t Fmt.t module Decoder : sig val ( or ) : ('a -> bool) -> ('a -> bool) -> 'a -> bool val is_alpha : char -> bool val is_digit : char -> bool val is_dash : char -> bool val is_dcontent : char -> bool val ipv4_address_literal : Ipaddr.V4.t Angstrom.t val ipv6_addr : Ipaddr.V6.t Angstrom.t val address_literal : t Angstrom.t val domain : t Angstrom.t end val of_string : string -> (t, [ `Msg of string ]) result val of_string_exn : string -> t val to_string : t -> string val extension : string -> string -> (t, [ `Msg of string ]) result type atom val atom : string -> (atom, [ `Msg of string ]) result val atom_exn : string -> atom val a : string -> atom module Peano : sig type z = Z type 'a s = S end type 'a domain = | ( :: ) : atom * 'a domain -> 'a Peano.s domain | [] : Peano.z domain val unsafe_domain_of_list_exn : string list -> t type 'a w val domain : 'a domain w val ipv4 : Ipaddr.V4.t w val ipv6 : Ipaddr.V6.t w val make : 'a w -> 'a -> (t, [ `Msg of string ]) result val v : 'a w -> 'a -> t
null
https://raw.githubusercontent.com/mirage/colombe/bbecbb17b581fa1db70a61de14efb51a66f30451/src/domain.mli
ocaml
type t = | IPv4 of Ipaddr.V4.t | IPv6 of Ipaddr.V6.t | Extension of string * string | Domain of string list val compare : t -> t -> int val equal : t -> t -> bool val pp : t Fmt.t module Decoder : sig val ( or ) : ('a -> bool) -> ('a -> bool) -> 'a -> bool val is_alpha : char -> bool val is_digit : char -> bool val is_dash : char -> bool val is_dcontent : char -> bool val ipv4_address_literal : Ipaddr.V4.t Angstrom.t val ipv6_addr : Ipaddr.V6.t Angstrom.t val address_literal : t Angstrom.t val domain : t Angstrom.t end val of_string : string -> (t, [ `Msg of string ]) result val of_string_exn : string -> t val to_string : t -> string val extension : string -> string -> (t, [ `Msg of string ]) result type atom val atom : string -> (atom, [ `Msg of string ]) result val atom_exn : string -> atom val a : string -> atom module Peano : sig type z = Z type 'a s = S end type 'a domain = | ( :: ) : atom * 'a domain -> 'a Peano.s domain | [] : Peano.z domain val unsafe_domain_of_list_exn : string list -> t type 'a w val domain : 'a domain w val ipv4 : Ipaddr.V4.t w val ipv6 : Ipaddr.V6.t w val make : 'a w -> 'a -> (t, [ `Msg of string ]) result val v : 'a w -> 'a -> t
a299e1a785ea2dd32edfc2be66108fb07288c909d5aa8a04eb4be20cbfa0aa31
wangsix/VMO_repeated_themes_discovery
converter.lisp
;(in-package :common-lisp-user) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "csv-files" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "humdrum-by-col" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "midi-save" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "Pattern rating") :name "musical-properties" :type "lisp") *lisp-code-root*)) (setq *path&name* (merge-pathnames (make-pathname :directory '(:relative "mozartK282Mvt2" "monophonic" "repeatedPatterns" "schoenberg" "E")) *music-data-root*)) (setq csv-destination (merge-pathnames (make-pathname :directory '(:relative "csv") :name "sonata04-2" :type "csv") *path&name*)) (setq MIDI-destination (merge-pathnames (make-pathname :directory '(:relative "midi") :name "sonata04-2" :type "mid") *path&name*)) (setq dataset-destination (merge-pathnames (make-pathname :directory '(:relative "lisp") :name "sonata04-2" :type "txt") *path&name*)) (progn (setq *scale* 1000) (setq *anacrusis* -1) (setq dataset (sky-line-clipped (kern-file2dataset-by-col (merge-pathnames (make-pathname :directory '(:relative "kern") :name "sonata04-2" :type "krn") *path&name*)))) (saveit MIDI-destination (modify-to-check-dataset dataset *scale*)) (write-to-file (mapcar #'(lambda (x) (append (list (+ (first x) *anacrusis*)) (rest x))) dataset) dataset-destination) (dataset2csv dataset-destination csv-destination))
null
https://raw.githubusercontent.com/wangsix/VMO_repeated_themes_discovery/0082b3c55e64ed447c8b68bcb705fd6da8e3541f/JKUPDD-Aug2013/groundTruth/mozartK282Mvt2/monophonic/repeatedPatterns/schoenberg/E/script/converter.lisp
lisp
(in-package :common-lisp-user)
(load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "csv-files" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "humdrum-by-col" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "midi-save" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "Pattern rating") :name "musical-properties" :type "lisp") *lisp-code-root*)) (setq *path&name* (merge-pathnames (make-pathname :directory '(:relative "mozartK282Mvt2" "monophonic" "repeatedPatterns" "schoenberg" "E")) *music-data-root*)) (setq csv-destination (merge-pathnames (make-pathname :directory '(:relative "csv") :name "sonata04-2" :type "csv") *path&name*)) (setq MIDI-destination (merge-pathnames (make-pathname :directory '(:relative "midi") :name "sonata04-2" :type "mid") *path&name*)) (setq dataset-destination (merge-pathnames (make-pathname :directory '(:relative "lisp") :name "sonata04-2" :type "txt") *path&name*)) (progn (setq *scale* 1000) (setq *anacrusis* -1) (setq dataset (sky-line-clipped (kern-file2dataset-by-col (merge-pathnames (make-pathname :directory '(:relative "kern") :name "sonata04-2" :type "krn") *path&name*)))) (saveit MIDI-destination (modify-to-check-dataset dataset *scale*)) (write-to-file (mapcar #'(lambda (x) (append (list (+ (first x) *anacrusis*)) (rest x))) dataset) dataset-destination) (dataset2csv dataset-destination csv-destination))