_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
4e822485f093dd6288e2794dc51059f88ce8b54d1882f60ec497efd47246778e
gfour/gic
Poly2.hs
module Poly2 where main :: IO () main = putStrLn (show result) result :: Int result = (double inc 1) + lengthZ (double ident [1, 2, 3]) double :: (a->a) -> a -> a double f x = f (f x) inc :: Int -> Int inc z = z + 1 ident :: a -> a ident x = x lengthZ :: [Int] -> Int lengthZ z = case z of [] -> 0 x:xs -> 1 + (lengthZ xs)
null
https://raw.githubusercontent.com/gfour/gic/d5f2e506b31a1a28e02ca54af9610b3d8d618e9a/Examples/Polymorphic/Poly2.hs
haskell
module Poly2 where main :: IO () main = putStrLn (show result) result :: Int result = (double inc 1) + lengthZ (double ident [1, 2, 3]) double :: (a->a) -> a -> a double f x = f (f x) inc :: Int -> Int inc z = z + 1 ident :: a -> a ident x = x lengthZ :: [Int] -> Int lengthZ z = case z of [] -> 0 x:xs -> 1 + (lengthZ xs)
fc99fc4e423a39d98f82ddd70101ad571ee2a9e8dc600e9a0da7b3215abb3ae4
KaroshiBee/weevil
dap_event_message.mli
include Dap_message_types.EVENT_T
null
https://raw.githubusercontent.com/KaroshiBee/weevil/1b166ba053062498c1ec05c885e04fba4ae7d831/lib/dapper/dap_event_message.mli
ocaml
include Dap_message_types.EVENT_T
810f20e3082028d7b880bcecea6a76deaf5f35a1ef7733706a8b5793ffeedb48
mathematical-systems/clml
dlasq6.lisp
;;; Compiled by f2cl version: ( " $ I d : f2cl1.l , v 1.209 2008/09/11 14:59:55 rtoy Exp $ " " $ I d : f2cl2.l , v 1.37 2008/02/22 22:19:33 " " $ I d : f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Rel $ " " $ I d : f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Rel $ " " $ I d : f2cl5.l , v 1.197 2008/09/11 15:03:25 rtoy Exp $ " " $ I d : f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " $ I d : macros.l , v 1.106 2008/09/15 15:27:36 " ) Using Lisp International Allegro CL Enterprise Edition 8.1 [ 64 - bit Linux ( x86 - 64 ) ] ( Oct 7 , 2008 17:13 ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) ;;; (:relaxed-array-decls t) (:coerce-assigns :as-needed) ;;; (:array-type ':array) (:array-slicing t) ;;; (:declare-common nil) (:float-format double-float)) (in-package "LAPACK") (let* ((zero 0.0)) (declare (type (double-float 0.0 0.0) zero) (ignorable zero)) (defun dlasq6 (i0 n0 z pp dmin dmin1$ dmin2 dn dnm1 dnm2) (declare (type (double-float) dnm2 dnm1 dn dmin2 dmin1$ dmin) (type (array double-float (*)) z) (type (f2cl-lib:integer4) pp n0 i0)) (f2cl-lib:with-multi-array-data ((z double-float z-%data% z-%offset%)) (prog ((d 0.0) (emin 0.0) (safmin 0.0) (temp 0.0) (j4 0) (j4p2 0)) (declare (type (double-float) d emin safmin temp) (type (f2cl-lib:integer4) j4 j4p2)) (if (<= (f2cl-lib:int-sub n0 i0 1) 0) (go end_label)) (setf safmin (dlamch "Safe minimum")) (setf j4 (f2cl-lib:int-sub (f2cl-lib:int-add (f2cl-lib:int-mul 4 i0) pp) 3)) (setf emin (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 4)) ((1 *)) z-%offset%)) (setf d (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%)) (setf dmin d) (cond ((= pp 0) (f2cl-lib:fdo (j4 (f2cl-lib:int-mul 4 i0) (f2cl-lib:int-add j4 4)) ((> j4 (f2cl-lib:int-mul 4 (f2cl-lib:int-add n0 (f2cl-lib:int-sub 3)))) nil) (tagbody (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%) (+ d (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) zero) (setf d (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%)) (setf dmin d) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 1)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 1)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) temp)) (setf d (* d temp))) (t (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))) (setf d (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%) (/ d (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin d)) (setf emin (min emin (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%))) label10))) (t (f2cl-lib:fdo (j4 (f2cl-lib:int-mul 4 i0) (f2cl-lib:int-add j4 4)) ((> j4 (f2cl-lib:int-mul 4 (f2cl-lib:int-add n0 (f2cl-lib:int-sub 3)))) nil) (tagbody (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%) (+ d (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 3))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) zero) (setf d (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%)) (setf dmin d) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 2)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 3))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 3))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 2)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) temp)) (setf d (* d temp))) (t (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%)))) (setf d (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) (/ d (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin d)) (setf emin (min emin (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%))) label20)))) (setf dnm2 d) (setf dmin2 dmin) (setf j4 (f2cl-lib:int-sub (f2cl-lib:int-mul 4 (f2cl-lib:int-sub n0 2)) pp)) (setf j4p2 (f2cl-lib:int-sub (f2cl-lib:int-add j4 (f2cl-lib:int-mul 2 pp)) 1)) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%) (+ dnm2 (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) zero) (setf dnm1 (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%)) (setf dmin dnm1) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) temp)) (setf dnm1 (* dnm2 temp))) (t (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))) (setf dnm1 (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ dnm2 (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin dnm1)) (setf dmin1$ dmin) (setf j4 (f2cl-lib:int-add j4 4)) (setf j4p2 (f2cl-lib:int-sub (f2cl-lib:int-add j4 (f2cl-lib:int-mul 2 pp)) 1)) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%) (+ dnm1 (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) zero) (setf dn (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%)) (setf dmin dn) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) temp)) (setf dn (* dnm1 temp))) (t (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))) (setf dn (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ dnm1 (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin dn)) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) dn) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub (f2cl-lib:int-mul 4 n0) pp)) ((1 *)) z-%offset%) emin) (go end_label) end_label (return (values nil nil nil nil dmin dmin1$ dmin2 dn dnm1 dnm2)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dlasq6 fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (double-float) (double-float) (double-float) (double-float) (double-float) (double-float)) :return-values '(nil nil nil nil fortran-to-lisp::dmin fortran-to-lisp::dmin1$ fortran-to-lisp::dmin2 fortran-to-lisp::dn fortran-to-lisp::dnm1 fortran-to-lisp::dnm2) :calls '(fortran-to-lisp::dlamch))))
null
https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/lapack/dlasq6.lisp
lisp
Compiled by f2cl version: Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " $ I d : f2cl1.l , v 1.209 2008/09/11 14:59:55 rtoy Exp $ " " $ I d : f2cl2.l , v 1.37 2008/02/22 22:19:33 " " $ I d : f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Rel $ " " $ I d : f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Rel $ " " $ I d : f2cl5.l , v 1.197 2008/09/11 15:03:25 rtoy Exp $ " " $ I d : f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " $ I d : macros.l , v 1.106 2008/09/15 15:27:36 " ) Using Lisp International Allegro CL Enterprise Edition 8.1 [ 64 - bit Linux ( x86 - 64 ) ] ( Oct 7 , 2008 17:13 ) (in-package "LAPACK") (let* ((zero 0.0)) (declare (type (double-float 0.0 0.0) zero) (ignorable zero)) (defun dlasq6 (i0 n0 z pp dmin dmin1$ dmin2 dn dnm1 dnm2) (declare (type (double-float) dnm2 dnm1 dn dmin2 dmin1$ dmin) (type (array double-float (*)) z) (type (f2cl-lib:integer4) pp n0 i0)) (f2cl-lib:with-multi-array-data ((z double-float z-%data% z-%offset%)) (prog ((d 0.0) (emin 0.0) (safmin 0.0) (temp 0.0) (j4 0) (j4p2 0)) (declare (type (double-float) d emin safmin temp) (type (f2cl-lib:integer4) j4 j4p2)) (if (<= (f2cl-lib:int-sub n0 i0 1) 0) (go end_label)) (setf safmin (dlamch "Safe minimum")) (setf j4 (f2cl-lib:int-sub (f2cl-lib:int-add (f2cl-lib:int-mul 4 i0) pp) 3)) (setf emin (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 4)) ((1 *)) z-%offset%)) (setf d (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%)) (setf dmin d) (cond ((= pp 0) (f2cl-lib:fdo (j4 (f2cl-lib:int-mul 4 i0) (f2cl-lib:int-add j4 4)) ((> j4 (f2cl-lib:int-mul 4 (f2cl-lib:int-add n0 (f2cl-lib:int-sub 3)))) nil) (tagbody (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%) (+ d (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) zero) (setf d (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%)) (setf dmin d) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 1)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 1)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) temp)) (setf d (* d temp))) (t (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))) (setf d (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 1)) ((1 *)) z-%offset%) (/ d (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin d)) (setf emin (min emin (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%))) label10))) (t (f2cl-lib:fdo (j4 (f2cl-lib:int-mul 4 i0) (f2cl-lib:int-add j4 4)) ((> j4 (f2cl-lib:int-mul 4 (f2cl-lib:int-add n0 (f2cl-lib:int-sub 3)))) nil) (tagbody (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%) (+ d (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 3))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) zero) (setf d (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%)) (setf dmin d) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 2)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 3))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 3))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 2)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) temp)) (setf d (* d temp))) (t (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%)))) (setf d (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) (/ d (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 3)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin d)) (setf emin (min emin (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 1)) ((1 *)) z-%offset%))) label20)))) (setf dnm2 d) (setf dmin2 dmin) (setf j4 (f2cl-lib:int-sub (f2cl-lib:int-mul 4 (f2cl-lib:int-sub n0 2)) pp)) (setf j4p2 (f2cl-lib:int-sub (f2cl-lib:int-add j4 (f2cl-lib:int-mul 2 pp)) 1)) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%) (+ dnm2 (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) zero) (setf dnm1 (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%)) (setf dmin dnm1) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) temp)) (setf dnm1 (* dnm2 temp))) (t (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))) (setf dnm1 (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ dnm2 (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin dnm1)) (setf dmin1$ dmin) (setf j4 (f2cl-lib:int-add j4 4)) (setf j4p2 (f2cl-lib:int-sub (f2cl-lib:int-add j4 (f2cl-lib:int-mul 2 pp)) 1)) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%) (+ dnm1 (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%))) (cond ((= (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *))) zero) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) zero) (setf dn (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%)) (setf dmin dn) (setf emin zero)) ((and (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (< (* safmin (f2cl-lib:fref z ((f2cl-lib:int-add j4 (f2cl-lib:int-sub 2))) ((1 *)))) (f2cl-lib:fref z ((f2cl-lib:int-add j4p2 2)) ((1 *))))) (setf temp (/ (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%))) (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) temp)) (setf dn (* dnm1 temp))) (t (setf (f2cl-lib:fref z-%data% (j4) ((1 *)) z-%offset%) (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ (f2cl-lib:fref z-%data% (j4p2) ((1 *)) z-%offset%) (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))) (setf dn (* (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4p2 2)) ((1 *)) z-%offset%) (/ dnm1 (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub j4 2)) ((1 *)) z-%offset%)))))) (setf dmin (min dmin dn)) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-add j4 2)) ((1 *)) z-%offset%) dn) (setf (f2cl-lib:fref z-%data% ((f2cl-lib:int-sub (f2cl-lib:int-mul 4 n0) pp)) ((1 *)) z-%offset%) emin) (go end_label) end_label (return (values nil nil nil nil dmin dmin1$ dmin2 dn dnm1 dnm2)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dlasq6 fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (double-float) (double-float) (double-float) (double-float) (double-float) (double-float)) :return-values '(nil nil nil nil fortran-to-lisp::dmin fortran-to-lisp::dmin1$ fortran-to-lisp::dmin2 fortran-to-lisp::dn fortran-to-lisp::dnm1 fortran-to-lisp::dnm2) :calls '(fortran-to-lisp::dlamch))))
01ae310e0536c168add5f529381a0d21fb9512f3f3336fc3f2c104e08ea5784d
soegaard/metapict
parametric-plot.rkt
#lang racket/base ;;; ;;; Parametric Plot ;;; (require racket/math racket/draw metapict) (provide parametric-plot) ; draw the graph of a function (define graph-join --) (define (parametric-plot fx fy tmin tmax #:samples [n 50] #:diffx [df/dx #f] #:diffy [df/dy #f]) (def ε 1.0e-10) (define (ndiff f t) (def t-ε (max tmin (- t ε))) (def t+ε (min tmax (+ t ε))) (/ (- (f t+ε) (f t-ε)) (- t+ε t-ε))) (unless df/dx (set! df/dx (λ (t) (ndiff fx t)))) (unless df/dy (set! df/dy (λ (t) (ndiff fy t)))) (def (φ t) (pt (fx t) (fy t))) ; t -> (fx(t),fy(t)) (def (τ t) (vec (df/dx t) (df/dy t))) ; vector along tangent (def Δt (/ (- tmax tmin) n)) (def t0 tmin) (def (ti i) (+ t0 (* i Δt))) (def (xi i) (fx (ti i))) (def (yi i) (fy (ti i))) (curve* (append (if (equal? graph-join --) (list (φ t0)) (list (φ t0) (τ t0))) (for/list ([t (in-range (ti 1) (ti (+ n 1)) Δt)]) (if (equal? graph-join --) (list -- (φ t)) (list .. (φ t) (τ t))))))) ;; (define (window-outline win) ;; (defv (p q) (window-opposite-corners win)) ;; (rectangle p q)) ;; (define (clip-to-window c [win (curve-pict-window)]) ;; (clipped (window-outline win) c)) (module+ test (require metapict) (require metapict/grid) (set-curve-pict-size 301 301) (let () (defv (xmin xmax ymin ymax) (values -10 10 -10 10)) (def win (window xmin xmax ymin ymax)) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax))) (color "red" (draw (parametric-plot (λ (t) (expt t 2)) (λ (t) (expt t 3)) -5 5)))))) (let () (defv (xmin xmax ymin ymax) (values -16 16 -16 16)) (def win (window xmin xmax ymin ymax)) (def (fx t) (+ (* 10 (cos t)) (* 5 (cos (* -3 t))))) (def (fy t) (+ (* 10 (sin t)) (* 5 (sin (* -3 t))))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 2)) (color "red" (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200)))))) (let () (defv (xmin xmax ymin ymax) (values -1.1 1.1 -1.1 1.1)) (def win (window xmin xmax ymin ymax)) (def (fx t) (sin t)) (def (fy t) (sin (* 2 t))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 2)) (color "red" (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200)))))) (let () (defv (xmin xmax ymin ymax) (values -2.1 2.1 -2.1 2.1)) (def win (window xmin xmax ymin ymax)) (def fxs (list (λ (t) (* 2 (cos t))) (λ (t) (* 2 (cos t))) (λ (t) (cos t)) (λ (t) (cos t)))) (def fys (list (λ (t) (* 2 (sin t))) (λ (t) (sin t)) (λ (t) (* 2 (sin t))) (λ (t) (sin t)))) (def cols (list "blue" "yellow" "green" "red")) (def (fy t) (sin (* 2 t))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 1.)) (color "red" (draw* (for/list ([fx fxs] [fy fys] [col cols]) (color col (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200))))))))) (require racket/format) (let () (defv (xmin xmax ymin ymax) (values -1.5 1.5 -1.5 1.5)) (def win (window xmin xmax ymin ymax)) (def (fx t) (sin t)) (def (fy t) (sin (* 2 t))) (defv (tmin tmax) (values 0 (* 2 3.14))) (def ε 1.0e-10) (define (ndiff f t) (def t-ε (max tmin (- t ε))) (def t+ε (min tmax (+ t ε))) (/ (- (f t+ε) (f t-ε)) (- t+ε t-ε))) (def t0 0.5) (def (P t) (pt (fx t) (fy t))) (def P0 (P t0)) (def (lab t [dir (cnt)]) (draw (label (~a "t=" (~r t)) (pt+ (P t) (vec 0.05 0)) (rt)))) (def (dP/dt t) (vec (ndiff fx t) (ndiff fy t))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 2)) (color "red" (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200))) (draw (label (~a "t = " t0) (pt 0 1.3) (cnt))) (draw* (for/list ([t (in-range 0 (* 2 3.14) 0.5)]) (list (penscale 4 (color "blue" (draw (P t)))) (lab t (rot-90 (unit-vec (dP/dt t)))))))))) )
null
https://raw.githubusercontent.com/soegaard/metapict/5712a0fa6ad6671d17726c4221396d6ffac5cbd3/metapict/parametric-plot.rkt
racket
Parametric Plot draw the graph of a function t -> (fx(t),fy(t)) vector along tangent (define (window-outline win) (defv (p q) (window-opposite-corners win)) (rectangle p q)) (define (clip-to-window c [win (curve-pict-window)]) (clipped (window-outline win) c))
#lang racket/base (require racket/math racket/draw metapict) (define graph-join --) (define (parametric-plot fx fy tmin tmax #:samples [n 50] #:diffx [df/dx #f] #:diffy [df/dy #f]) (def ε 1.0e-10) (define (ndiff f t) (def t-ε (max tmin (- t ε))) (def t+ε (min tmax (+ t ε))) (/ (- (f t+ε) (f t-ε)) (- t+ε t-ε))) (unless df/dx (set! df/dx (λ (t) (ndiff fx t)))) (unless df/dy (set! df/dy (λ (t) (ndiff fy t)))) (def Δt (/ (- tmax tmin) n)) (def t0 tmin) (def (ti i) (+ t0 (* i Δt))) (def (xi i) (fx (ti i))) (def (yi i) (fy (ti i))) (curve* (append (if (equal? graph-join --) (list (φ t0)) (list (φ t0) (τ t0))) (for/list ([t (in-range (ti 1) (ti (+ n 1)) Δt)]) (if (equal? graph-join --) (list -- (φ t)) (list .. (φ t) (τ t))))))) (module+ test (require metapict) (require metapict/grid) (set-curve-pict-size 301 301) (let () (defv (xmin xmax ymin ymax) (values -10 10 -10 10)) (def win (window xmin xmax ymin ymax)) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax))) (color "red" (draw (parametric-plot (λ (t) (expt t 2)) (λ (t) (expt t 3)) -5 5)))))) (let () (defv (xmin xmax ymin ymax) (values -16 16 -16 16)) (def win (window xmin xmax ymin ymax)) (def (fx t) (+ (* 10 (cos t)) (* 5 (cos (* -3 t))))) (def (fy t) (+ (* 10 (sin t)) (* 5 (sin (* -3 t))))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 2)) (color "red" (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200)))))) (let () (defv (xmin xmax ymin ymax) (values -1.1 1.1 -1.1 1.1)) (def win (window xmin xmax ymin ymax)) (def (fx t) (sin t)) (def (fy t) (sin (* 2 t))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 2)) (color "red" (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200)))))) (let () (defv (xmin xmax ymin ymax) (values -2.1 2.1 -2.1 2.1)) (def win (window xmin xmax ymin ymax)) (def fxs (list (λ (t) (* 2 (cos t))) (λ (t) (* 2 (cos t))) (λ (t) (cos t)) (λ (t) (cos t)))) (def fys (list (λ (t) (* 2 (sin t))) (λ (t) (sin t)) (λ (t) (* 2 (sin t))) (λ (t) (sin t)))) (def cols (list "blue" "yellow" "green" "red")) (def (fy t) (sin (* 2 t))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 1.)) (color "red" (draw* (for/list ([fx fxs] [fy fys] [col cols]) (color col (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200))))))))) (require racket/format) (let () (defv (xmin xmax ymin ymax) (values -1.5 1.5 -1.5 1.5)) (def win (window xmin xmax ymin ymax)) (def (fx t) (sin t)) (def (fy t) (sin (* 2 t))) (defv (tmin tmax) (values 0 (* 2 3.14))) (def ε 1.0e-10) (define (ndiff f t) (def t-ε (max tmin (- t ε))) (def t+ε (min tmax (+ t ε))) (/ (- (f t+ε) (f t-ε)) (- t+ε t-ε))) (def t0 0.5) (def (P t) (pt (fx t) (fy t))) (def P0 (P t0)) (def (lab t [dir (cnt)]) (draw (label (~a "t=" (~r t)) (pt+ (P t) (vec 0.05 0)) (rt)))) (def (dP/dt t) (vec (ndiff fx t) (ndiff fy t))) (with-window win (draw (color "gray" (grid (pt xmin ymin) (pt xmax ymax) #:step 2)) (color "red" (draw (parametric-plot fx fy 0 (* 2 3.14) #:samples 200))) (draw (label (~a "t = " t0) (pt 0 1.3) (cnt))) (draw* (for/list ([t (in-range 0 (* 2 3.14) 0.5)]) (list (penscale 4 (color "blue" (draw (P t)))) (lab t (rot-90 (unit-vec (dP/dt t)))))))))) )
c7e1b8bf04e2e7644662287312e2d02cec3767dfbff3946c2b5743dd2d89a5f4
gilith/hol-light
friendship.ml
(* ========================================================================= *) (* The friendship theorem. *) (* *) Proof from " Combinatorics Tutorial 2 : Friendship Theorem " , copyright MathOlymp.com , 2001 . Apparently due to and . (* ========================================================================= *) needs "Library/prime.ml";; needs "Library/pocklington.ml";; (* ------------------------------------------------------------------------- *) Useful inductive breakdown principle ending at gcd . (* ------------------------------------------------------------------------- *) let GCD_INDUCT = prove (`!P. (!m n. P m /\ P (m + n) ==> P n) ==> !m n. P m /\ P n ==> P (gcd(m,n))`, GEN_TAC THEN STRIP_TAC THEN REPEAT GEN_TAC THEN WF_INDUCT_TAC `m + n:num` THEN REPEAT(POP_ASSUM MP_TAC) THEN MAP_EVERY (fun t -> SPEC_TAC(t,t)) [`n:num`; `m:num`] THEN MATCH_MP_TAC WLOG_LE THEN CONJ_TAC THENL [REWRITE_TAC[CONJ_ACI; GCD_SYM; ADD_SYM]; REPEAT STRIP_TAC] THEN ASM_CASES_TAC `m = 0` THENL [ASM_MESON_TAC[GCD_0]; ALL_TAC] THEN UNDISCH_TAC `!m n:num. P m /\ P (m + n) ==> P n` THEN DISCH_THEN(MP_TAC o SPECL [`m:num`; `n - m:num`]) THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ASM_SIMP_TAC[SUB_ADD; LT_IMP_LE] THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPECL [`m:num`; `n - m:num`]) THEN REWRITE_TAC[IMP_IMP] THEN ANTS_TAC THENL [ASM_REWRITE_TAC[] THEN ASM_ARITH_TAC; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [LE_EXISTS]) THEN DISCH_THEN(X_CHOOSE_THEN `d:num` SUBST_ALL_TAC) THEN REWRITE_TAC[ADD_SUB2; GCD_ADD]);; (* ------------------------------------------------------------------------- *) (* General theorems about loops in a sequence. *) (* ------------------------------------------------------------------------- *) let LOOP_GCD = prove (`!x m n. (!i. x(i + m) = x(i)) /\ (!i. x(i + n) = x(i)) ==> !i. x(i + gcd(m,n)) = x(i)`, GEN_TAC THEN MATCH_MP_TAC GCD_INDUCT THEN MESON_TAC[ADD_AC]);; let LOOP_COPRIME = prove (`!x m n. (!i. x(i + m) = x(i)) /\ (!i. x(i + n) = x(i)) /\ coprime(m,n) ==> !i. x i = x 0`, REPEAT GEN_TAC THEN STRIP_TAC THEN INDUCT_TAC THEN REWRITE_TAC[ADD1] THEN ASM_MESON_TAC[LOOP_GCD; COPRIME_GCD]);; (* ------------------------------------------------------------------------- *) (* General theorem about partition into equally-sized eqv classes. *) (* ------------------------------------------------------------------------- *) let EQUIVALENCE_UNIFORM_PARTITION = prove (`!R s k. FINITE s /\ (!x. x IN s ==> R x x) /\ (!x y. R x y ==> R y x) /\ (!x y z. R x y /\ R y z ==> R x z) /\ (!x:A. x IN s ==> CARD {y | y IN s /\ R x y} = k) ==> k divides (CARD s)`, REPEAT GEN_TAC THEN WF_INDUCT_TAC `CARD(s:A->bool)` THEN ASM_CASES_TAC `s:A->bool = {}` THENL [ASM_MESON_TAC[CARD_CLAUSES; DIVIDES_0]; REPEAT STRIP_TAC] THEN FIRST_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM MEMBER_NOT_EMPTY]) THEN DISCH_THEN(X_CHOOSE_TAC `a:A`) THEN FIRST_X_ASSUM(MP_TAC o SPEC `{y:A | y IN s /\ ~(R (a:A) y)}`) THEN REWRITE_TAC[IMP_IMP] THEN ANTS_TAC THENL [ASM_SIMP_TAC[IN_ELIM_THM; FINITE_RESTRICT] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [MATCH_MP_TAC CARD_PSUBSET THEN ASM_SIMP_TAC[PSUBSET; SUBSET; EXTENSION; IN_ELIM_THM] THEN ASM_MESON_TAC[]; GEN_TAC THEN REWRITE_TAC[IN_ELIM_THM] THEN DISCH_THEN(CONJUNCTS_THEN2 (ANTE_RES_THEN MP_TAC) ASSUME_TAC) THEN DISCH_TAC THEN MATCH_MP_TAC EQ_IMP THEN AP_THM_TAC THEN AP_TERM_TAC THEN AP_TERM_TAC THEN ASM SET_TAC[]]; ALL_TAC] THEN DISCH_TAC THEN SUBGOAL_THEN `CARD(s) = CARD {y | y IN s /\ (R:A->A->bool) a y} + CARD {y | y IN s /\ ~(R a y)}` (fun th -> ASM_SIMP_TAC[th; DIVIDES_ADD; DIVIDES_REFL]) THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC CARD_UNION_EQ THEN ASM SET_TAC[]);; (* ------------------------------------------------------------------------- *) (* With explicit restricted quantification. *) (* ------------------------------------------------------------------------- *) let EQUIVALENCE_UNIFORM_PARTITION_RESTRICT = prove (`!R s k. FINITE s /\ (!x. x IN s ==> R x x) /\ (!x y. x IN s /\ y IN s /\ R x y ==> R y x) /\ (!x y z. x IN s /\ y IN s /\ z IN s /\ R x y /\ R y z ==> R x z) /\ (!x:A. x IN s ==> CARD {y | y IN s /\ R x y} = k) ==> k divides (CARD s)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC EQUIVALENCE_UNIFORM_PARTITION THEN EXISTS_TAC `\x y:A. x IN s /\ y IN s /\ R x y` THEN SIMP_TAC[] THEN ASM_REWRITE_TAC[CONJ_ASSOC] THEN ASM_MESON_TAC[]);; (* ------------------------------------------------------------------------- *) (* General theorem about pairing up elements of a set. *) (* ------------------------------------------------------------------------- *) let ELEMENTS_PAIR_UP = prove (`!s r. FINITE s /\ (!x. x IN s ==> ~(r x x)) /\ (!x y. x IN s /\ y IN s /\ r x y ==> r y x) /\ (!x:A. x IN s ==> ?!y. y IN s /\ r x y) ==> EVEN(CARD s)`, REPEAT GEN_TAC THEN WF_INDUCT_TAC `CARD(s:A->bool)` THEN STRIP_TAC THEN ASM_CASES_TAC `s:A->bool = {}` THEN ASM_REWRITE_TAC[CARD_CLAUSES; ARITH] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM MEMBER_NOT_EMPTY]) THEN DISCH_THEN(X_CHOOSE_TAC `a:A`) THEN MP_TAC(ASSUME `!x:A. x IN s ==> (?!y:A. y IN s /\ r x y)`) THEN DISCH_THEN(MP_TAC o SPEC `a:A`) THEN REWRITE_TAC[ASSUME `a:A IN s`] THEN DISCH_THEN(MP_TAC o EXISTENCE) THEN DISCH_THEN(X_CHOOSE_THEN `b:A` STRIP_ASSUME_TAC) THEN FIRST_X_ASSUM(MP_TAC o SPEC `s DELETE (a:A) DELETE b`) THEN REWRITE_TAC[IMP_IMP] THEN ANTS_TAC THENL [ALL_TAC; DISCH_TAC THEN SUBGOAL_THEN `s = (a:A) INSERT b INSERT (s DELETE a DELETE b)` SUBST1_TAC THENL [ASM SET_TAC[]; ALL_TAC] THEN ASM_SIMP_TAC[CARD_CLAUSES; FINITE_DELETE; FINITE_INSERT] THEN REWRITE_TAC[IN_INSERT; IN_DELETE] THEN ASM_MESON_TAC[EVEN]] THEN ASM_SIMP_TAC[FINITE_DELETE; IN_DELETE] THEN CONJ_TAC THENL [MATCH_MP_TAC CARD_PSUBSET THEN ASM SET_TAC[]; ALL_TAC] THEN X_GEN_TAC `x:A` THEN STRIP_TAC THEN MP_TAC(ASSUME `!x:A. x IN s ==> (?!y. y IN s /\ r x y)`) THEN DISCH_THEN(MP_TAC o SPEC `x:A`) THEN REWRITE_TAC[ASSUME `x:A IN s`] THEN MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC THEN REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `y:A` THEN EQ_TAC THEN SIMP_TAC[] THEN ASM_MESON_TAC[]);; (* ------------------------------------------------------------------------- *) (* Cycles and paths. *) (* ------------------------------------------------------------------------- *) let cycle = new_definition `cycle r k x <=> (!i. r (x i) (x(i + 1))) /\ (!i. x(i + k) = x(i))`;; let path = new_definition `path r k x <=> (!i. i < k ==> r (x i) (x(i + 1))) /\ (!i. k < i ==> x(i) = @x. T)`;; (* ------------------------------------------------------------------------- *) Lemmas about these concepts . (* ------------------------------------------------------------------------- *) let CYCLE_OFFSET = prove (`!r k x:num->A. cycle r k x ==> !i m. x(m * k + i) = x(i)`, REPEAT GEN_TAC THEN REWRITE_TAC[cycle] THEN STRIP_TAC THEN GEN_TAC THEN INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN ASM_MESON_TAC[ADD_AC]);; let CYCLE_MOD = prove (`!r k x:num->A. cycle r k x /\ ~(k = 0) ==> !i. x(i MOD k) = x(i)`, MESON_TAC[CYCLE_OFFSET; DIVISION]);; let PATHS_MONO = prove (`(!x y. r x y ==> s x y) ==> {x | path r k x} SUBSET {x | path s k x}`, REWRITE_TAC[path; IN_ELIM_THM; SUBSET] THEN MESON_TAC[]);; let HAS_SIZE_PATHS = prove (`!N m r k. (:A) HAS_SIZE N /\ (!x. {y | r x y} HAS_SIZE m) ==> {x:num->A | path r k x} HAS_SIZE (N * m EXP k)`, REWRITE_TAC[RIGHT_FORALL_IMP_THM] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN INDUCT_TAC THEN REWRITE_TAC[EXP; MULT_CLAUSES] THENL [SUBGOAL_THEN `{x:num->A | path r 0 x} = IMAGE (\a i. if i = 0 then a else @x. T) (:A)` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_ELIM_THM; IN_IMAGE; IN_UNIV; path; LT] THEN REWRITE_TAC[FUN_EQ_THM; LT_NZ] THEN MESON_TAC[]; ALL_TAC] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN ASM_REWRITE_TAC[IN_UNIV] THEN REWRITE_TAC[FUN_EQ_THM] THEN MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `{x:num->A | path r (SUC k) x} = IMAGE (\(x,a) i. if i = SUC k then a else x i) {x,a | x IN {x | path r k x} /\ a IN {u | r (x k) u}}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_ELIM_THM; IN_IMAGE; EXISTS_PAIR_THM] THEN X_GEN_TAC `x:num->A` THEN REWRITE_TAC[PAIR_EQ] THEN ONCE_REWRITE_TAC[TAUT `(a /\ b) /\ c /\ d <=> c /\ d /\ a /\ b`] THEN REWRITE_TAC[RIGHT_EXISTS_AND_THM; UNWIND_THM1] THEN REWRITE_TAC[FUN_EQ_THM; path; LT] THEN EQ_TAC THENL [STRIP_TAC THEN EXISTS_TAC `\i. if i = SUC k then @x. T else x(i):A` THEN EXISTS_TAC `x(SUC k):A` THEN SIMP_TAC[] THEN CONJ_TAC THENL [MESON_TAC[]; ALL_TAC] THEN SIMP_TAC[ARITH_RULE `~(k = SUC k) /\ (i < k ==> ~(i = SUC k))`] THEN ASM_SIMP_TAC[ADD1; ARITH_RULE `i < k ==> ~(i + 1 = SUC k)`] THEN ASM_MESON_TAC[ARITH_RULE `k < i /\ ~(i = k + 1) ==> SUC k < i`]; ALL_TAC] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`z:num->A`; `a:A`] THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN SIMP_TAC[ARITH_RULE `i = k \/ i < k ==> ~(i = SUC k)`] THEN REWRITE_TAC[ARITH_RULE `i + 1 = SUC k <=> i = k`] THEN ASM_MESON_TAC[ARITH_RULE `SUC k < i ==> ~(i = SUC k) /\ k < i`]; ALL_TAC] THEN ONCE_REWRITE_TAC[ARITH_RULE `N * m * m EXP k = (N * m EXP k) * m`] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [REWRITE_TAC[FORALL_PAIR_THM; IN_ELIM_PAIR_THM; IN_ELIM_THM] THEN REWRITE_TAC[FUN_EQ_THM; path; PAIR_EQ] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `i = SUC k` THEN ASM_MESON_TAC[ARITH_RULE `k < SUC k`]; ALL_TAC] THEN ASM_SIMP_TAC[HAS_SIZE_PRODUCT_DEPENDENT]);; let FINITE_PATHS = prove (`!r k. FINITE(:A) ==> FINITE {x:num->A | path r k x}`, REPEAT STRIP_TAC THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path (\a b. T) k x}` THEN SIMP_TAC[PATHS_MONO] THEN MP_TAC(ISPECL [`CARD(:A)`; `CARD(:A)`; `\a:A b:A. T`; `k:num`] HAS_SIZE_PATHS) THEN ANTS_TAC THEN ASM_SIMP_TAC[HAS_SIZE; SET_RULE `{y | T} = (:A)`]);; let HAS_SIZE_CYCLES = prove (`!r k. FINITE(:A) /\ ~(k = 0) ==> {x:num->A | cycle r k x} HAS_SIZE CARD{x:num->A | path r k x /\ x(k) = x(0)}`, REPEAT STRIP_TAC THEN SUBGOAL_THEN `{x:num->A | cycle r k x} = IMAGE (\x i. x(i MOD k)) {x | path r k x /\ x(k) = x(0)}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_IMAGE; IN_ELIM_THM] THEN X_GEN_TAC `x:num->A` THEN EQ_TAC THENL [DISCH_TAC THEN EXISTS_TAC `\i. if i <= k then x(i):A else @x. T` THEN REPEAT CONJ_TAC THENL [ASM_SIMP_TAC[FUN_EQ_THM; LT_IMP_LE; DIVISION] THEN ASM_MESON_TAC[CYCLE_MOD]; SIMP_TAC[path; LT_IMP_LE] THEN REWRITE_TAC[GSYM NOT_LT] THEN SIMP_TAC[ARITH_RULE `i < k ==> ~(k < i + 1)`] THEN ASM_MESON_TAC[cycle]; REWRITE_TAC[LE_0; LE_REFL] THEN ASM_MESON_TAC[cycle; ADD_CLAUSES]]; REWRITE_TAC[LEFT_AND_EXISTS_THM; LEFT_IMP_EXISTS_THM] THEN X_GEN_TAC `y:num->A` THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[cycle] THEN CONJ_TAC THEN X_GEN_TAC `i:num` THENL [ALL_TAC; AP_TERM_TAC THEN MATCH_MP_TAC MOD_EQ THEN EXISTS_TAC `1` THEN REWRITE_TAC[MULT_CLAUSES]] THEN SUBGOAL_THEN `y((i + 1) MOD k):A = y(i MOD k + 1)` SUBST1_TAC THENL [ALL_TAC; ASM_MESON_TAC[path; DIVISION]] THEN SUBGOAL_THEN `(i + 1) MOD k = (i MOD k + 1) MOD k` SUBST1_TAC THENL [MATCH_MP_TAC MOD_EQ THEN EXISTS_TAC `i DIV k` THEN REWRITE_TAC[ARITH_RULE `i + 1 = (m + 1) + ik <=> i = ik + m`] THEN ASM_MESON_TAC[DIVISION]; ALL_TAC] THEN FIRST_ASSUM(MP_TAC o CONJUNCT2 o SPEC `i:num` o MATCH_MP DIVISION) THEN SPEC_TAC(`i MOD k`,`j:num`) THEN GEN_TAC THEN ONCE_REWRITE_TAC[ARITH_RULE `j < k <=> j + 1 < k \/ j + 1 = k`] THEN STRIP_TAC THEN ASM_SIMP_TAC[MOD_LT] THEN AP_TERM_TAC THEN MATCH_MP_TAC MOD_UNIQ THEN EXISTS_TAC `1` THEN UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC]; ALL_TAC] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [ALL_TAC; REWRITE_TAC[HAS_SIZE] THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path r k x}` THEN ASM_SIMP_TAC[FINITE_PATHS] THEN SET_TAC[]] THEN MAP_EVERY X_GEN_TAC [`x:num->A`; `y:num->A`] THEN SIMP_TAC[IN_ELIM_THM] THEN REWRITE_TAC[path; FUN_EQ_THM] THEN STRIP_TAC THEN X_GEN_TAC `i:num` THEN REPEAT_TCL DISJ_CASES_THEN ASSUME_TAC (SPECL [`i:num`; `k:num`] LT_CASES) THENL [ASM_MESON_TAC[MOD_LT]; ASM_MESON_TAC[]; ASM_REWRITE_TAC[]] THEN ASM_MESON_TAC[MOD_0]);; let FINITE_CYCLES = prove (`!r k. FINITE(:A) /\ ~(k = 0) ==> FINITE {x:num->A | cycle r k x}`, MESON_TAC[HAS_SIZE_CYCLES; HAS_SIZE]);; let CARD_PATHCYCLES_STEP = prove (`!N m r k. (:A) HAS_SIZE N /\ ~(k = 0) /\ ~(m = 0) /\ (!x:A. {y | r x y} HAS_SIZE m) /\ (!x y. r x y ==> r y x) /\ (!x y. ~(x = y) ==> ?!z. r x z /\ r z y) ==> {x | path r (k + 2) x /\ x(k + 2) = x(0)} HAS_SIZE (m * CARD {x | path r k x /\ x(k) = x(0)} + CARD {x | path r (k) x /\ ~(x(k) = x(0))})`, REPEAT STRIP_TAC THEN REWRITE_TAC[SET_RULE `{x | path r (k + 2) x /\ x(k + 2) = x(0)} = {x | path r (k + 2) x /\ x k = x 0 /\ x(k + 2) = x(0)} UNION {x | path r (k + 2) x /\ ~(x k = x 0) /\ x(k + 2) = x(0)}`] THEN MATCH_MP_TAC HAS_SIZE_UNION THEN GEN_REWRITE_TAC I [CONJ_ASSOC] THEN CONJ_TAC THENL [ALL_TAC; SET_TAC[]] THEN CONJ_TAC THENL [SUBGOAL_THEN `{x:num->A | path r (k + 2) x /\ x k = x 0 /\ x (k + 2) = x 0} = IMAGE (\(x,a) i. if i = k + 1 then a else if i = k + 2 then x(0) else x(i)) {x,a | x IN {x | path r k x /\ x(k) = x(0)} /\ a IN {u | r (x k) u}}` SUBST1_TAC THENL [ALL_TAC; MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [REWRITE_TAC[FORALL_PAIR_THM; IN_ELIM_PAIR_THM] THEN REWRITE_TAC[IN_ELIM_THM; FUN_EQ_THM; PAIR_EQ] THEN MAP_EVERY X_GEN_TAC [`y:num->A`; `a:A`; `z:num->A`; `b:A`] THEN DISCH_THEN(fun th -> CONJ_TAC THEN MP_TAC th THENL [ALL_TAC; MESON_TAC[]]) THEN REPEAT(DISCH_THEN(CONJUNCTS_THEN2 STRIP_ASSUME_TAC MP_TAC)) THEN DISCH_THEN(fun th -> X_GEN_TAC `i:num` THEN MP_TAC th) THEN DISCH_THEN(fun th -> MP_TAC th THEN MP_TAC(SPEC `0` th)) THEN REWRITE_TAC[ARITH_RULE `~(0 = k + 1) /\ ~(0 = k + 2)`] THEN DISCH_TAC THEN ASM_CASES_TAC `k:num < i` THENL [ASM_MESON_TAC[path]; ALL_TAC] THEN DISCH_THEN(MP_TAC o SPEC `i:num`) THEN ASM_MESON_TAC[ARITH_RULE `k < k + 1 /\ k < k + 2`]; ALL_TAC] THEN ONCE_REWRITE_TAC[MULT_SYM] THEN MATCH_MP_TAC HAS_SIZE_PRODUCT_DEPENDENT THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[HAS_SIZE] THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path r k x}` THEN CONJ_TAC THENL [ALL_TAC; SET_TAC[]] THEN ASM_MESON_TAC[HAS_SIZE; FINITE_PATHS]] THEN REWRITE_TAC[EXTENSION; IN_IMAGE] THEN REWRITE_TAC[EXISTS_PAIR_THM; IN_ELIM_PAIR_THM] THEN REWRITE_TAC[FUN_EQ_THM; IN_ELIM_THM] THEN X_GEN_TAC `x:num->A` THEN EQ_TAC THENL [STRIP_TAC THEN EXISTS_TAC `\i. if i <= k then x(i):A else @x. T` THEN EXISTS_TAC `(x:num->A) (k + 1)` THEN REWRITE_TAC[IN_ELIM_THM; LE_REFL; LE_0] THEN ASM_REWRITE_TAC[CONJ_ASSOC] THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[path; ARITH_RULE `k < k + 2`]] THEN CONJ_TAC THENL [ALL_TAC; UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN SIMP_TAC[path; LT_IMP_LE; ARITH_RULE `i < k ==> i + 1 <= k`] THEN SIMP_TAC[GSYM NOT_LT] THEN MESON_TAC[ARITH_RULE `i < k ==> i < k + 2`]] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THEN ASM_CASES_TAC `i = k + 2` THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [path]) THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN DISCH_THEN(MP_TAC o SPEC `i:num` o CONJUNCT2) THEN ASM_REWRITE_TAC[ARITH_RULE `k + 2 < i <=> ~(i <= k) /\ ~(i = k + 1) /\ ~(i = k + 2)`]; ALL_TAC] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`z:num->A`; `b:A`] THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC STRIP_ASSUME_TAC) THEN DISCH_THEN(fun th -> MP_TAC th THEN MP_TAC(SPEC `0` th)) THEN REWRITE_TAC[COND_ID; ARITH_RULE `~(0 = k + 1)`] THEN DISCH_TAC THEN REWRITE_TAC[CONJ_ASSOC] THEN DISCH_THEN(LABEL_TAC "*") THEN CONJ_TAC THENL [ALL_TAC; REMOVE_THEN "*" (MP_TAC o SPEC `k + 2`) THEN ASM_REWRITE_TAC[ARITH_RULE `~(k + 2 = k + 1)`]] THEN CONJ_TAC THENL [ALL_TAC; REMOVE_THEN "*" (MP_TAC o SPEC `k:num`) THEN ASM_REWRITE_TAC[ARITH_RULE `~(k = k + 2) /\ ~(k = k + 1)`]] THEN UNDISCH_TAC `path r k (z:num->A)` THEN ASM_REWRITE_TAC[path] THEN SIMP_TAC[ARITH_RULE `k + 2 < i ==> k < i /\ ~(i = k + 1) /\ ~(i = k + 2)`] THEN STRIP_TAC THEN X_GEN_TAC `i:num` THEN DISCH_TAC THEN ASM_SIMP_TAC[ARITH_RULE `i < k + 2 ==> ~(i = k + 2)`] THEN REWRITE_TAC[ARITH_RULE `i + 1 = k + 2 <=> i = k + 1`] THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THENL [ASM_MESON_TAC[ARITH_RULE `~(x + 1 = x)`]; ALL_TAC] THEN REWRITE_TAC[EQ_ADD_RCANCEL] THEN COND_CASES_TAC THEN ASM_SIMP_TAC[] THENL [ASM_MESON_TAC[]; ALL_TAC] THEN ASM_MESON_TAC[ARITH_RULE `i < k + 2 /\ ~(i = k) /\ ~(i = k + 1) ==> i < k`]; ALL_TAC] THEN SUBGOAL_THEN `{x:num->A | path r (k + 2) x /\ ~(x k = x 0) /\ x (k + 2) = x 0} = IMAGE (\x i. if i = k + 1 then @z. r (x k) z /\ r z (x 0) else if i = k + 2 then x(0) else x(i)) {x | path r k x /\ ~(x(k) = x(0))}` SUBST1_TAC THENL [ALL_TAC; MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [ALL_TAC; REWRITE_TAC[HAS_SIZE] THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path r k x}` THEN CONJ_TAC THENL [ALL_TAC; SET_TAC[]] THEN ASM_MESON_TAC[HAS_SIZE; FINITE_PATHS]] THEN MAP_EVERY X_GEN_TAC [`x:num->A`; `y:num->A`] THEN REWRITE_TAC[IN_ELIM_THM] THEN STRIP_TAC THEN REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `k:num < i` THENL [ASM_MESON_TAC[path]; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [FUN_EQ_THM]) THEN DISCH_THEN(MP_TAC o SPEC `i:num`) THEN ASM_MESON_TAC[ARITH_RULE `k < k + 1 /\ k < k + 2`]] THEN REWRITE_TAC[EXTENSION; IN_IMAGE; IN_ELIM_THM] THEN X_GEN_TAC `x:num->A` THEN REWRITE_TAC[IN_ELIM_THM] THEN EQ_TAC THENL [STRIP_TAC THEN EXISTS_TAC `\i. if i <= k then x(i):A else @x. T` THEN ASM_REWRITE_TAC[LE_REFL; LE_0] THEN CONJ_TAC THENL [ALL_TAC; UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN SIMP_TAC[path; LT_IMP_LE; ARITH_RULE `i < k ==> i + 1 <= k`] THEN SIMP_TAC[GSYM NOT_LT] THEN MESON_TAC[ARITH_RULE `i < k ==> i < k + 2`]] THEN REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THENL [CONV_TAC SYM_CONV THEN MATCH_MP_TAC SELECT_UNIQUE THEN UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN REWRITE_TAC[path] THEN DISCH_THEN(MP_TAC o CONJUNCT1) THEN DISCH_THEN(fun th -> MP_TAC(SPEC `k:num` th) THEN MP_TAC(SPEC `k + 1` th)) THEN REWRITE_TAC[ARITH_RULE `k < k + 2 /\ k + 1 < k + 2`] THEN REWRITE_TAC[GSYM ADD_ASSOC; ARITH] THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_CASES_TAC `i = k + 2` THEN ASM_REWRITE_TAC[] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN REWRITE_TAC[path] THEN DISCH_THEN(MP_TAC o CONJUNCT2) THEN ASM_MESON_TAC[ARITH_RULE `~(i <= k) /\ ~(i = k + 1) /\ ~(i = k + 2) ==> k + 2 < i`]; ALL_TAC] THEN DISCH_THEN(X_CHOOSE_THEN `y:num->A` STRIP_ASSUME_TAC) THEN ASM_REWRITE_TAC[ARITH_RULE `~(k + 2 = k + 1) /\ ~(0 = k + 1) /\ ~(0 = k + 2) /\ ~(k = k + 1) /\ ~(k = k + 2)`] THEN REWRITE_TAC[path] THEN CONJ_TAC THEN X_GEN_TAC `i:num` THEN DISCH_TAC THENL [REWRITE_TAC[ARITH_RULE `i + 1 = k + 2 <=> i = k + 1`] THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THENL [REWRITE_TAC[ARITH_RULE `(k + 1) + 1 = k + 1 <=> F`] THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_SIMP_TAC[ARITH_RULE `i < k + 2 ==> ~(i = k + 2)`] THEN REWRITE_TAC[EQ_ADD_RCANCEL] THEN COND_CASES_TAC THEN ASM_SIMP_TAC[] THENL [ASM_MESON_TAC[]; ALL_TAC] THEN UNDISCH_TAC `path r k (y:num->A)` THEN REWRITE_TAC[path] THEN DISCH_THEN(MATCH_MP_TAC o CONJUNCT1) THEN MAP_EVERY UNDISCH_TAC [`~(i:num = k)`; `~(i = k + 1)`; `i < k + 2`] THEN ARITH_TAC; ALL_TAC] THEN ASM_SIMP_TAC[ARITH_RULE `k + 2 < i ==> ~(i = k + 1) /\ ~(i = k + 2)`] THEN ASM_MESON_TAC[path; ARITH_RULE `k + 2 < i ==> k < i`]);; (* ------------------------------------------------------------------------- *) The first lemma about the number of cycles . (* ------------------------------------------------------------------------- *) let shiftable = new_definition `shiftable x y <=> ?k. !i. x(i) = y(i + k)`;; let SHIFTABLE_REFL = prove (`!x. shiftable x x`, REWRITE_TAC[shiftable] THEN MESON_TAC[ADD_CLAUSES]);; let SHIFTABLE_TRANS = prove (`!x y z. shiftable x y /\ shiftable y z ==> shiftable x z`, REWRITE_TAC[shiftable] THEN MESON_TAC[ADD_ASSOC]);; let SHIFTABLE_LOCAL = prove (`!x y p r. cycle r p x /\ cycle r p y /\ ~(p = 0) ==> (shiftable x y <=> ?k. k < p /\ !i. x(i) = y(i + k))`, REPEAT STRIP_TAC THEN REWRITE_TAC[shiftable] THEN EQ_TAC THENL [ALL_TAC; MESON_TAC[]] THEN DISCH_THEN(X_CHOOSE_TAC `k:num`) THEN EXISTS_TAC `k MOD p` THEN FIRST_ASSUM(MP_TAC o SPEC `k:num` o MATCH_MP DIVISION) THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN ASM_REWRITE_TAC[] THEN DISCH_THEN(fun th -> GEN_REWRITE_TAC (BINDER_CONV o LAND_CONV o ONCE_DEPTH_CONV) [th]) THEN ASM_MESON_TAC[CYCLE_OFFSET; ADD_AC]);; let SHIFTABLE_SYM = prove (`!x y p r. cycle r p x /\ cycle r p y /\ ~(p = 0) /\ shiftable x y ==> shiftable y x`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[TAUT `a /\ b /\ c /\ d <=> (a /\ b /\ c) /\ d`] THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN FIRST_ASSUM(SUBST1_TAC o MATCH_MP SHIFTABLE_LOCAL) THEN DISCH_THEN(X_CHOOSE_THEN `k:num` STRIP_ASSUME_TAC) THEN REWRITE_TAC[shiftable] THEN EXISTS_TAC `p - k:num` THEN ASM_SIMP_TAC[ARITH_RULE `k < p ==> (i + (p - k)) + k = i + p:num`] THEN ASM_MESON_TAC[cycle]);; let CYCLES_PRIME_LEMMA = prove (`!r p x. FINITE(:A) /\ prime p /\ (!x. ~(r x x)) ==> p divides CARD {x:num->A | cycle r p x}`, REPEAT GEN_TAC THEN ASM_CASES_TAC `p = 0` THEN ASM_REWRITE_TAC[PRIME_0] THEN STRIP_TAC THEN MATCH_MP_TAC EQUIVALENCE_UNIFORM_PARTITION_RESTRICT THEN EXISTS_TAC `shiftable:(num->A)->(num->A)->bool` THEN ASM_SIMP_TAC[IN_ELIM_THM; FINITE_CYCLES] THEN CONJ_TAC THENL [MESON_TAC[SHIFTABLE_REFL]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[SHIFTABLE_SYM]; ALL_TAC] THEN CONJ_TAC THENL [MESON_TAC[SHIFTABLE_TRANS]; ALL_TAC] THEN X_GEN_TAC `x:num->A` THEN DISCH_TAC THEN SUBGOAL_THEN `{y:num->A | cycle r p y /\ shiftable x y} HAS_SIZE p` (fun th -> MESON_TAC[HAS_SIZE; th]) THEN SUBGOAL_THEN `{y:num->A | cycle r p y /\ shiftable x y} = IMAGE (\k i. x(i + k)) {k | k < p}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_IMAGE; IN_ELIM_THM] THEN X_GEN_TAC `y:num->A` THEN REWRITE_TAC[FUN_EQ_THM] THEN EQ_TAC THENL [ASM_MESON_TAC[SHIFTABLE_LOCAL; SHIFTABLE_SYM]; ALL_TAC] THEN REPEAT STRIP_TAC THENL [FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [cycle]) THEN ASM_REWRITE_TAC[cycle] THEN MESON_TAC[ADD_AC]; ALL_TAC] THEN MATCH_MP_TAC SHIFTABLE_SYM THEN MAP_EVERY EXISTS_TAC [`p:num`; `r:A->A->bool`] THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [cycle]) THEN ASM_REWRITE_TAC[cycle; shiftable] THEN MESON_TAC[ADD_AC]; ALL_TAC] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN REWRITE_TAC[HAS_SIZE_NUMSEG_LT] THEN REWRITE_TAC[IN_ELIM_THM] THEN MATCH_MP_TAC WLOG_LE THEN REWRITE_TAC[FUN_EQ_THM] THEN CONJ_TAC THENL [MESON_TAC[]; ALL_TAC] THEN MAP_EVERY X_GEN_TAC [`k:num`; `l:num`] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC(TAUT `(~p ==> F) ==> p`) THEN DISCH_TAC THEN SUBGOAL_THEN `!i. x(i):A = x(0)` MP_TAC THENL [ALL_TAC; ASM_MESON_TAC[cycle]] THEN MATCH_MP_TAC LOOP_COPRIME THEN EXISTS_TAC `p:num` THEN REWRITE_TAC[RIGHT_EXISTS_AND_THM] THEN CONJ_TAC THENL [ASM_MESON_TAC[cycle]; ALL_TAC] THEN EXISTS_TAC `l + (p - k):num` THEN CONJ_TAC THENL [X_GEN_TAC `i:num` THEN ONCE_REWRITE_TAC[ARITH_RULE `i + l + pk = (i + pk) + l:num`] THEN ASSUM_LIST(REWRITE_TAC o map GSYM) THEN SIMP_TAC[ARITH_RULE `k < p ==> (i + p - k) + k = i + p:num`; ASSUME `k < p:num`] THEN ASM_MESON_TAC[cycle]; ALL_TAC] THEN SUBGOAL_THEN `l + p - k = p + l - k:num` SUBST1_TAC THENL [MAP_EVERY UNDISCH_TAC [`k < p:num`; `k <= l:num`] THEN ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[NUMBER_RULE `coprime(p,p + d) <=> coprime(d,p)`] THEN MATCH_MP_TAC PRIME_COPRIME_LT THEN ASM_REWRITE_TAC[] THEN ASM_ARITH_TAC);; (* ------------------------------------------------------------------------- *) (* The theorem itself. *) (* ------------------------------------------------------------------------- *) let FRIENDSHIP = prove (`!friend:person->person->bool. FINITE(:person) /\ (!x. ~(friend x x)) /\ (!x y. friend x y ==> friend y x) /\ (!x y. ~(x = y) ==> ?!z. friend x z /\ friend y z) ==> ?u. !v. ~(v = u) ==> friend u v`, REPEAT STRIP_TAC THEN UNDISCH_TAC `!x y:person. ~(x = y) ==> ?!z:person. friend x z /\ friend y z` THEN REWRITE_TAC[EXISTS_UNIQUE_THM] THEN REWRITE_TAC[TAUT `a ==> b /\ c <=> (a ==> b) /\ (a ==> c)`] THEN REWRITE_TAC[FORALL_AND_THM; RIGHT_IMP_FORALL_THM] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [RIGHT_IMP_EXISTS_THM] THEN REWRITE_TAC[SKOLEM_THM; IMP_IMP; GSYM CONJ_ASSOC] THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC STRIP_ASSUME_TAC) THEN DISCH_THEN(X_CHOOSE_TAC `mutualfriend:person->person->person`) THEN SUBGOAL_THEN `!s:person->bool. FINITE s` ASSUME_TAC THENL [ASM_MESON_TAC[SUBSET_UNIV; FINITE_SUBSET]; ALL_TAC] THEN ABBREV_TAC `degree = \p:person. CARD {q:person | friend p q}` THEN SUBGOAL_THEN `!x y:person. ~(friend x y) ==> degree(x):num <= degree(y)` ASSUME_TAC THENL [REPEAT STRIP_TAC THEN ASM_CASES_TAC `x:person = y` THENL [ASM_MESON_TAC[LE_REFL]; ALL_TAC] THEN EXPAND_TAC "degree" THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `CARD(IMAGE (\u. (mutualfriend:person->person->person) u y) {q | friend (x:person) q})` THEN CONJ_TAC THENL [ALL_TAC; MATCH_MP_TAC CARD_SUBSET THEN ASM SET_TAC[]] THEN MATCH_MP_TAC EQ_IMP_LE THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC CARD_IMAGE_INJ THEN ASM_REWRITE_TAC[IN_ELIM_THM] THEN MAP_EVERY X_GEN_TAC [`u1:person`; `u2:person`] THEN STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o SPECL [`x:person`; `(mutualfriend:person->person->person) u1 y`; `u1:person`; `u2:person`]) THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `!x y:person. ~(friend x y) ==> degree x:num = degree y` ASSUME_TAC THENL [ASM_MESON_TAC[LE_ANTISYM]; ALL_TAC] THEN GEN_REWRITE_TAC I [TAUT `p <=> ~ ~ p`] THEN GEN_REWRITE_TAC RAND_CONV [NOT_EXISTS_THM] THEN DISCH_THEN(ASSUME_TAC o REWRITE_RULE[NOT_FORALL_THM; NOT_IMP]) THEN SUBGOAL_THEN `?m:num. !x:person. degree(x) = m` STRIP_ASSUME_TAC THENL [FIRST_ASSUM(X_CHOOSE_THEN `b:person` STRIP_ASSUME_TAC o SPEC `a:person`) THEN ABBREV_TAC `c = (mutualfriend:person->person->person) a b` THEN ABBREV_TAC `k = (degree:person->num) a` THEN EXISTS_TAC `k:num` THEN SUBGOAL_THEN `(degree:person->num)(b) = k /\ ~(friend a b) /\ friend a c /\ friend b c` STRIP_ASSUME_TAC THENL [ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `!x:person. ~(x = c) ==> degree x = (k:num)` ASSUME_TAC THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `!p:person. {q:person | friend p q} HAS_SIZE m` ASSUME_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN SUBGOAL_THEN `~(m = 0)` ASSUME_TAC THENL [DISCH_TAC THEN UNDISCH_TAC `!p:person. {q:person | friend p q} HAS_SIZE m` THEN ASM_REWRITE_TAC[HAS_SIZE_0; EXTENSION; IN_ELIM_THM; NOT_IN_EMPTY] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `EVEN(m)` ASSUME_TAC THENL [UNDISCH_TAC `!x:person. degree x = (m:num)` THEN DISCH_THEN(SUBST1_TAC o SYM o SPEC `a:person`) THEN EXPAND_TAC "degree" THEN MATCH_MP_TAC ELEMENTS_PAIR_UP THEN EXISTS_TAC `\x y:person. friend a x /\ friend a y /\ friend x y` THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN ABBREV_TAC `N = CARD(:person)` THEN SUBGOAL_THEN `N = m * (m - 1) + 1` ASSUME_TAC THENL [ABBREV_TAC `t = {q:person | friend (a:person) q}` THEN SUBGOAL_THEN `FINITE(t:person->bool) /\ CARD t = m` STRIP_ASSUME_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN ABBREV_TAC `u = \b:person. {c:person | friend b c /\ ~(c IN (a INSERT t))}` THEN EXPAND_TAC "N" THEN SUBGOAL_THEN `(:person) = (a INSERT t) UNION UNIONS {u(b) | b IN t}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_INSERT; IN_UNIV; IN_UNION; IN_UNIONS] THEN MAP_EVERY EXPAND_TAC ["t"; "u"] THEN REWRITE_TAC[IN_ELIM_THM] THEN X_GEN_TAC `x:person` THEN MATCH_MP_TAC(TAUT `(~a /\ ~b ==> c) ==> (a \/ b) \/ c`) THEN STRIP_TAC THEN REWRITE_TAC[LEFT_AND_EXISTS_THM] THEN ONCE_REWRITE_TAC[TAUT `(a /\ b) /\ c <=> b /\ a /\ c`] THEN ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN REWRITE_TAC[UNWIND_THM2] THEN REWRITE_TAC[IN_ELIM_THM; IN_INSERT; DE_MORGAN_THM] THEN EXISTS_TAC `mutualfriend (a:person) (x:person) :person` THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `m * (m - 1) + 1 = (m + 1) + m * (m - 2)` SUBST1_TAC THENL [SIMP_TAC[ARITH_RULE `a + 1 = (m + 1) + m * c <=> a = m * (1 + c)`] THEN AP_TERM_TAC THEN UNDISCH_TAC `EVEN m` THEN ASM_CASES_TAC `m = 1` THEN ASM_REWRITE_TAC[ARITH] THEN DISCH_TAC THEN MAP_EVERY UNDISCH_TAC [`~(m = 0)`; `~(m = 1)`] THEN ARITH_TAC; ALL_TAC] THEN SUBGOAL_THEN `m + 1 = CARD((a:person) INSERT t)` SUBST1_TAC THENL [ASM_SIMP_TAC[CARD_CLAUSES; ADD1] THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `UNIONS {u b :person->bool | (b:person) IN t} HAS_SIZE m * (m - 2)` MP_TAC THENL [MATCH_MP_TAC HAS_SIZE_UNIONS THEN CONJ_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN CONJ_TAC THENL [ALL_TAC; EXPAND_TAC "u" THEN REWRITE_TAC[DISJOINT; EXTENSION; IN_INTER] THEN REWRITE_TAC[NOT_IN_EMPTY; IN_ELIM_THM; IN_INSERT] THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[]] THEN REPEAT STRIP_TAC THEN MP_TAC(ASSUME `(b:person) IN t`) THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN DISCH_TAC THEN SUBGOAL_THEN `u (b:person) = {q:person | friend q b} DELETE a DELETE (mutualfriend a b)` SUBST1_TAC THENL [MAP_EVERY EXPAND_TAC ["u"; "t"] THEN REWRITE_TAC[EXTENSION; IN_INSERT; IN_DELETE; IN_ELIM_THM] THEN X_GEN_TAC `x:person` THEN FIRST_X_ASSUM(MP_TAC o SPECL [`a:person`; `b:person`; `(mutualfriend:person->person->person) a b`; `x:person`]) THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_SIMP_TAC[CARD_DELETE; HAS_SIZE] THEN REWRITE_TAC[IN_ELIM_THM; IN_DELETE] THEN COND_CASES_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN SUBGOAL_THEN `{q:person | friend q (b:person)} = {q | friend b q}` SUBST1_TAC THENL [ASM SET_TAC[]; ALL_TAC] THEN ASM_REWRITE_TAC[ARITH_RULE `m - 1 - 1 = m - 2`] THEN ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN REWRITE_TAC[HAS_SIZE] THEN DISCH_THEN(SUBST1_TAC o SYM o CONJUNCT2) THEN MATCH_MP_TAC CARD_UNION THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[EXTENSION; IN_INSERT; IN_INTER; NOT_IN_EMPTY; IN_UNIONS] THEN REWRITE_TAC[IN_ELIM_THM; LEFT_AND_EXISTS_THM] THEN ONCE_REWRITE_TAC[TAUT `(a /\ b) /\ c <=> b /\ a /\ c`] THEN ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN REWRITE_TAC[UNWIND_THM2] THEN MAP_EVERY EXPAND_TAC ["u"; "t"] THEN REWRITE_TAC[IN_ELIM_THM; IN_INSERT] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `~(m = 2)` ASSUME_TAC THENL [DISCH_THEN SUBST_ALL_TAC THEN RULE_ASSUM_TAC(CONV_RULE NUM_REDUCE_CONV) THEN SUBGOAL_THEN `(:person) HAS_SIZE 3` MP_TAC THENL [ASM_REWRITE_TAC[HAS_SIZE]; ALL_TAC] THEN CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN REWRITE_TAC[NOT_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`a:person`; `b:person`; `c:person`] THEN REWRITE_TAC[EXTENSION; IN_UNIV; IN_INSERT; NOT_IN_EMPTY] THEN STRIP_TAC THEN UNDISCH_TAC `!u:person. ?v:person. ~(v = u) /\ ~friend u v` THEN REWRITE_TAC[NOT_FORALL_THM; NOT_EXISTS_THM] THEN EXISTS_TAC `a:person` THEN UNDISCH_TAC `!p:person. {q:person | friend p q} HAS_SIZE 2` THEN DISCH_THEN(MP_TAC o SPEC `a:person`) THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN REWRITE_TAC[EXTENSION; IN_ELIM_THM; IN_INSERT; NOT_IN_EMPTY] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`x:person`; `y:person`] THEN STRIP_TAC THEN X_GEN_TAC `z:person` THEN UNDISCH_TAC `!x:person. x = a \/ x = b \/ x = c` THEN DISCH_THEN(fun th -> MAP_EVERY (fun x -> MP_TAC(SPEC x th)) [`x:person`; `y:person`; `z:person`]) THEN ASM_MESON_TAC[]; ALL_TAC] THEN MP_TAC(SPEC `m - 1` PRIME_FACTOR) THEN ANTS_TAC THENL [UNDISCH_TAC `~(m = 2)` THEN ARITH_TAC; ALL_TAC] THEN DISCH_THEN(X_CHOOSE_THEN `p:num` STRIP_ASSUME_TAC) THEN SUBGOAL_THEN `~(p divides 1)` MP_TAC THENL [ASM_MESON_TAC[DIVIDES_ONE; PRIME_1]; ALL_TAC] THEN REWRITE_TAC[] THEN MATCH_MP_TAC(NUMBER_RULE `!x. p divides (x + 1) /\ p divides x ==> p divides 1`) THEN EXISTS_TAC `m - 1` THEN ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[ARITH_RULE `~(m = 0) ==> m - 1 + 1 = m`] THEN MATCH_MP_TAC PRIME_DIVEXP THEN EXISTS_TAC `p - 2` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC(NUMBER_RULE `!q c K1 K2. p divides q /\ p divides c /\ c = (q + 1) * K1 + K2 /\ K1 + K2 = ((q + 1) * q + 1) * nep2 ==> p divides nep2`) THEN MAP_EVERY EXISTS_TAC [`m - 1`; `CARD {x:num->person | cycle friend p x}`; `CARD {x:num->person | path friend (p-2) x /\ x (p-2) = x 0}`; `CARD {x:num->person | path friend (p-2) x /\ ~(x (p-2) = x 0)}`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [MATCH_MP_TAC CYCLES_PRIME_LEMMA THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `3 <= p` ASSUME_TAC THENL [MATCH_MP_TAC(ARITH_RULE `2 <= p /\ ~(p = 2) ==> 3 <= p`) THEN ASM_SIMP_TAC[PRIME_GE_2] THEN DISCH_THEN SUBST_ALL_TAC THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM DIVIDES_2]) THEN MP_TAC(DIVIDES_CONV `2 divides 1`) THEN REWRITE_TAC[CONTRAPOS_THM] THEN MATCH_MP_TAC(NUMBER_RULE `!q. t divides q /\ m = q + 1 ==> t divides m ==> t divides w`) THEN EXISTS_TAC `m - 1` THEN ASM_REWRITE_TAC[] THEN UNDISCH_TAC `~(m = 0)` THEN ARITH_TAC; ALL_TAC] THEN ASM_SIMP_TAC[ARITH_RULE `~(m = 0) ==> m - 1 + 1 = m`] THEN CONJ_TAC THENL [MP_TAC(ISPECL[`friend:person->person->bool`; `p:num`] HAS_SIZE_CYCLES) THEN ANTS_TAC THENL [ASM_MESON_TAC[PRIME_0]; ALL_TAC] THEN SIMP_TAC[HAS_SIZE] THEN DISCH_THEN(K ALL_TAC) THEN MATCH_MP_TAC HAS_SIZE_CARD THEN SUBGOAL_THEN `p = (p - 2) + 2` (fun th -> GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [th]) THENL [ASM_MESON_TAC[PRIME_GE_2; SUB_ADD]; ALL_TAC] THEN MATCH_MP_TAC CARD_PATHCYCLES_STEP THEN EXISTS_TAC `N:num` THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN UNDISCH_TAC `3 <= p` THEN ARITH_TAC; ALL_TAC] THEN MP_TAC(ISPECL [`N:num`; `m:num`; `friend:person->person->bool`; `p - 2`] HAS_SIZE_PATHS) THEN ANTS_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN ASM_REWRITE_TAC[HAS_SIZE] THEN DISCH_THEN(SUBST1_TAC o SYM o CONJUNCT2) THEN MATCH_MP_TAC CARD_UNION_EQ THEN ASM_SIMP_TAC[FINITE_PATHS] THEN SET_TAC[]);;
null
https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/100/friendship.ml
ocaml
========================================================================= The friendship theorem. ========================================================================= ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- General theorems about loops in a sequence. ------------------------------------------------------------------------- ------------------------------------------------------------------------- General theorem about partition into equally-sized eqv classes. ------------------------------------------------------------------------- ------------------------------------------------------------------------- With explicit restricted quantification. ------------------------------------------------------------------------- ------------------------------------------------------------------------- General theorem about pairing up elements of a set. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Cycles and paths. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- The theorem itself. -------------------------------------------------------------------------
Proof from " Combinatorics Tutorial 2 : Friendship Theorem " , copyright MathOlymp.com , 2001 . Apparently due to and . needs "Library/prime.ml";; needs "Library/pocklington.ml";; Useful inductive breakdown principle ending at gcd . let GCD_INDUCT = prove (`!P. (!m n. P m /\ P (m + n) ==> P n) ==> !m n. P m /\ P n ==> P (gcd(m,n))`, GEN_TAC THEN STRIP_TAC THEN REPEAT GEN_TAC THEN WF_INDUCT_TAC `m + n:num` THEN REPEAT(POP_ASSUM MP_TAC) THEN MAP_EVERY (fun t -> SPEC_TAC(t,t)) [`n:num`; `m:num`] THEN MATCH_MP_TAC WLOG_LE THEN CONJ_TAC THENL [REWRITE_TAC[CONJ_ACI; GCD_SYM; ADD_SYM]; REPEAT STRIP_TAC] THEN ASM_CASES_TAC `m = 0` THENL [ASM_MESON_TAC[GCD_0]; ALL_TAC] THEN UNDISCH_TAC `!m n:num. P m /\ P (m + n) ==> P n` THEN DISCH_THEN(MP_TAC o SPECL [`m:num`; `n - m:num`]) THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ASM_SIMP_TAC[SUB_ADD; LT_IMP_LE] THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPECL [`m:num`; `n - m:num`]) THEN REWRITE_TAC[IMP_IMP] THEN ANTS_TAC THENL [ASM_REWRITE_TAC[] THEN ASM_ARITH_TAC; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [LE_EXISTS]) THEN DISCH_THEN(X_CHOOSE_THEN `d:num` SUBST_ALL_TAC) THEN REWRITE_TAC[ADD_SUB2; GCD_ADD]);; let LOOP_GCD = prove (`!x m n. (!i. x(i + m) = x(i)) /\ (!i. x(i + n) = x(i)) ==> !i. x(i + gcd(m,n)) = x(i)`, GEN_TAC THEN MATCH_MP_TAC GCD_INDUCT THEN MESON_TAC[ADD_AC]);; let LOOP_COPRIME = prove (`!x m n. (!i. x(i + m) = x(i)) /\ (!i. x(i + n) = x(i)) /\ coprime(m,n) ==> !i. x i = x 0`, REPEAT GEN_TAC THEN STRIP_TAC THEN INDUCT_TAC THEN REWRITE_TAC[ADD1] THEN ASM_MESON_TAC[LOOP_GCD; COPRIME_GCD]);; let EQUIVALENCE_UNIFORM_PARTITION = prove (`!R s k. FINITE s /\ (!x. x IN s ==> R x x) /\ (!x y. R x y ==> R y x) /\ (!x y z. R x y /\ R y z ==> R x z) /\ (!x:A. x IN s ==> CARD {y | y IN s /\ R x y} = k) ==> k divides (CARD s)`, REPEAT GEN_TAC THEN WF_INDUCT_TAC `CARD(s:A->bool)` THEN ASM_CASES_TAC `s:A->bool = {}` THENL [ASM_MESON_TAC[CARD_CLAUSES; DIVIDES_0]; REPEAT STRIP_TAC] THEN FIRST_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM MEMBER_NOT_EMPTY]) THEN DISCH_THEN(X_CHOOSE_TAC `a:A`) THEN FIRST_X_ASSUM(MP_TAC o SPEC `{y:A | y IN s /\ ~(R (a:A) y)}`) THEN REWRITE_TAC[IMP_IMP] THEN ANTS_TAC THENL [ASM_SIMP_TAC[IN_ELIM_THM; FINITE_RESTRICT] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [MATCH_MP_TAC CARD_PSUBSET THEN ASM_SIMP_TAC[PSUBSET; SUBSET; EXTENSION; IN_ELIM_THM] THEN ASM_MESON_TAC[]; GEN_TAC THEN REWRITE_TAC[IN_ELIM_THM] THEN DISCH_THEN(CONJUNCTS_THEN2 (ANTE_RES_THEN MP_TAC) ASSUME_TAC) THEN DISCH_TAC THEN MATCH_MP_TAC EQ_IMP THEN AP_THM_TAC THEN AP_TERM_TAC THEN AP_TERM_TAC THEN ASM SET_TAC[]]; ALL_TAC] THEN DISCH_TAC THEN SUBGOAL_THEN `CARD(s) = CARD {y | y IN s /\ (R:A->A->bool) a y} + CARD {y | y IN s /\ ~(R a y)}` (fun th -> ASM_SIMP_TAC[th; DIVIDES_ADD; DIVIDES_REFL]) THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC CARD_UNION_EQ THEN ASM SET_TAC[]);; let EQUIVALENCE_UNIFORM_PARTITION_RESTRICT = prove (`!R s k. FINITE s /\ (!x. x IN s ==> R x x) /\ (!x y. x IN s /\ y IN s /\ R x y ==> R y x) /\ (!x y z. x IN s /\ y IN s /\ z IN s /\ R x y /\ R y z ==> R x z) /\ (!x:A. x IN s ==> CARD {y | y IN s /\ R x y} = k) ==> k divides (CARD s)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC EQUIVALENCE_UNIFORM_PARTITION THEN EXISTS_TAC `\x y:A. x IN s /\ y IN s /\ R x y` THEN SIMP_TAC[] THEN ASM_REWRITE_TAC[CONJ_ASSOC] THEN ASM_MESON_TAC[]);; let ELEMENTS_PAIR_UP = prove (`!s r. FINITE s /\ (!x. x IN s ==> ~(r x x)) /\ (!x y. x IN s /\ y IN s /\ r x y ==> r y x) /\ (!x:A. x IN s ==> ?!y. y IN s /\ r x y) ==> EVEN(CARD s)`, REPEAT GEN_TAC THEN WF_INDUCT_TAC `CARD(s:A->bool)` THEN STRIP_TAC THEN ASM_CASES_TAC `s:A->bool = {}` THEN ASM_REWRITE_TAC[CARD_CLAUSES; ARITH] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM MEMBER_NOT_EMPTY]) THEN DISCH_THEN(X_CHOOSE_TAC `a:A`) THEN MP_TAC(ASSUME `!x:A. x IN s ==> (?!y:A. y IN s /\ r x y)`) THEN DISCH_THEN(MP_TAC o SPEC `a:A`) THEN REWRITE_TAC[ASSUME `a:A IN s`] THEN DISCH_THEN(MP_TAC o EXISTENCE) THEN DISCH_THEN(X_CHOOSE_THEN `b:A` STRIP_ASSUME_TAC) THEN FIRST_X_ASSUM(MP_TAC o SPEC `s DELETE (a:A) DELETE b`) THEN REWRITE_TAC[IMP_IMP] THEN ANTS_TAC THENL [ALL_TAC; DISCH_TAC THEN SUBGOAL_THEN `s = (a:A) INSERT b INSERT (s DELETE a DELETE b)` SUBST1_TAC THENL [ASM SET_TAC[]; ALL_TAC] THEN ASM_SIMP_TAC[CARD_CLAUSES; FINITE_DELETE; FINITE_INSERT] THEN REWRITE_TAC[IN_INSERT; IN_DELETE] THEN ASM_MESON_TAC[EVEN]] THEN ASM_SIMP_TAC[FINITE_DELETE; IN_DELETE] THEN CONJ_TAC THENL [MATCH_MP_TAC CARD_PSUBSET THEN ASM SET_TAC[]; ALL_TAC] THEN X_GEN_TAC `x:A` THEN STRIP_TAC THEN MP_TAC(ASSUME `!x:A. x IN s ==> (?!y. y IN s /\ r x y)`) THEN DISCH_THEN(MP_TAC o SPEC `x:A`) THEN REWRITE_TAC[ASSUME `x:A IN s`] THEN MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC THEN REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `y:A` THEN EQ_TAC THEN SIMP_TAC[] THEN ASM_MESON_TAC[]);; let cycle = new_definition `cycle r k x <=> (!i. r (x i) (x(i + 1))) /\ (!i. x(i + k) = x(i))`;; let path = new_definition `path r k x <=> (!i. i < k ==> r (x i) (x(i + 1))) /\ (!i. k < i ==> x(i) = @x. T)`;; Lemmas about these concepts . let CYCLE_OFFSET = prove (`!r k x:num->A. cycle r k x ==> !i m. x(m * k + i) = x(i)`, REPEAT GEN_TAC THEN REWRITE_TAC[cycle] THEN STRIP_TAC THEN GEN_TAC THEN INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN ASM_MESON_TAC[ADD_AC]);; let CYCLE_MOD = prove (`!r k x:num->A. cycle r k x /\ ~(k = 0) ==> !i. x(i MOD k) = x(i)`, MESON_TAC[CYCLE_OFFSET; DIVISION]);; let PATHS_MONO = prove (`(!x y. r x y ==> s x y) ==> {x | path r k x} SUBSET {x | path s k x}`, REWRITE_TAC[path; IN_ELIM_THM; SUBSET] THEN MESON_TAC[]);; let HAS_SIZE_PATHS = prove (`!N m r k. (:A) HAS_SIZE N /\ (!x. {y | r x y} HAS_SIZE m) ==> {x:num->A | path r k x} HAS_SIZE (N * m EXP k)`, REWRITE_TAC[RIGHT_FORALL_IMP_THM] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN INDUCT_TAC THEN REWRITE_TAC[EXP; MULT_CLAUSES] THENL [SUBGOAL_THEN `{x:num->A | path r 0 x} = IMAGE (\a i. if i = 0 then a else @x. T) (:A)` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_ELIM_THM; IN_IMAGE; IN_UNIV; path; LT] THEN REWRITE_TAC[FUN_EQ_THM; LT_NZ] THEN MESON_TAC[]; ALL_TAC] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN ASM_REWRITE_TAC[IN_UNIV] THEN REWRITE_TAC[FUN_EQ_THM] THEN MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `{x:num->A | path r (SUC k) x} = IMAGE (\(x,a) i. if i = SUC k then a else x i) {x,a | x IN {x | path r k x} /\ a IN {u | r (x k) u}}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_ELIM_THM; IN_IMAGE; EXISTS_PAIR_THM] THEN X_GEN_TAC `x:num->A` THEN REWRITE_TAC[PAIR_EQ] THEN ONCE_REWRITE_TAC[TAUT `(a /\ b) /\ c /\ d <=> c /\ d /\ a /\ b`] THEN REWRITE_TAC[RIGHT_EXISTS_AND_THM; UNWIND_THM1] THEN REWRITE_TAC[FUN_EQ_THM; path; LT] THEN EQ_TAC THENL [STRIP_TAC THEN EXISTS_TAC `\i. if i = SUC k then @x. T else x(i):A` THEN EXISTS_TAC `x(SUC k):A` THEN SIMP_TAC[] THEN CONJ_TAC THENL [MESON_TAC[]; ALL_TAC] THEN SIMP_TAC[ARITH_RULE `~(k = SUC k) /\ (i < k ==> ~(i = SUC k))`] THEN ASM_SIMP_TAC[ADD1; ARITH_RULE `i < k ==> ~(i + 1 = SUC k)`] THEN ASM_MESON_TAC[ARITH_RULE `k < i /\ ~(i = k + 1) ==> SUC k < i`]; ALL_TAC] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`z:num->A`; `a:A`] THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN SIMP_TAC[ARITH_RULE `i = k \/ i < k ==> ~(i = SUC k)`] THEN REWRITE_TAC[ARITH_RULE `i + 1 = SUC k <=> i = k`] THEN ASM_MESON_TAC[ARITH_RULE `SUC k < i ==> ~(i = SUC k) /\ k < i`]; ALL_TAC] THEN ONCE_REWRITE_TAC[ARITH_RULE `N * m * m EXP k = (N * m EXP k) * m`] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [REWRITE_TAC[FORALL_PAIR_THM; IN_ELIM_PAIR_THM; IN_ELIM_THM] THEN REWRITE_TAC[FUN_EQ_THM; path; PAIR_EQ] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `i = SUC k` THEN ASM_MESON_TAC[ARITH_RULE `k < SUC k`]; ALL_TAC] THEN ASM_SIMP_TAC[HAS_SIZE_PRODUCT_DEPENDENT]);; let FINITE_PATHS = prove (`!r k. FINITE(:A) ==> FINITE {x:num->A | path r k x}`, REPEAT STRIP_TAC THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path (\a b. T) k x}` THEN SIMP_TAC[PATHS_MONO] THEN MP_TAC(ISPECL [`CARD(:A)`; `CARD(:A)`; `\a:A b:A. T`; `k:num`] HAS_SIZE_PATHS) THEN ANTS_TAC THEN ASM_SIMP_TAC[HAS_SIZE; SET_RULE `{y | T} = (:A)`]);; let HAS_SIZE_CYCLES = prove (`!r k. FINITE(:A) /\ ~(k = 0) ==> {x:num->A | cycle r k x} HAS_SIZE CARD{x:num->A | path r k x /\ x(k) = x(0)}`, REPEAT STRIP_TAC THEN SUBGOAL_THEN `{x:num->A | cycle r k x} = IMAGE (\x i. x(i MOD k)) {x | path r k x /\ x(k) = x(0)}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_IMAGE; IN_ELIM_THM] THEN X_GEN_TAC `x:num->A` THEN EQ_TAC THENL [DISCH_TAC THEN EXISTS_TAC `\i. if i <= k then x(i):A else @x. T` THEN REPEAT CONJ_TAC THENL [ASM_SIMP_TAC[FUN_EQ_THM; LT_IMP_LE; DIVISION] THEN ASM_MESON_TAC[CYCLE_MOD]; SIMP_TAC[path; LT_IMP_LE] THEN REWRITE_TAC[GSYM NOT_LT] THEN SIMP_TAC[ARITH_RULE `i < k ==> ~(k < i + 1)`] THEN ASM_MESON_TAC[cycle]; REWRITE_TAC[LE_0; LE_REFL] THEN ASM_MESON_TAC[cycle; ADD_CLAUSES]]; REWRITE_TAC[LEFT_AND_EXISTS_THM; LEFT_IMP_EXISTS_THM] THEN X_GEN_TAC `y:num->A` THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[cycle] THEN CONJ_TAC THEN X_GEN_TAC `i:num` THENL [ALL_TAC; AP_TERM_TAC THEN MATCH_MP_TAC MOD_EQ THEN EXISTS_TAC `1` THEN REWRITE_TAC[MULT_CLAUSES]] THEN SUBGOAL_THEN `y((i + 1) MOD k):A = y(i MOD k + 1)` SUBST1_TAC THENL [ALL_TAC; ASM_MESON_TAC[path; DIVISION]] THEN SUBGOAL_THEN `(i + 1) MOD k = (i MOD k + 1) MOD k` SUBST1_TAC THENL [MATCH_MP_TAC MOD_EQ THEN EXISTS_TAC `i DIV k` THEN REWRITE_TAC[ARITH_RULE `i + 1 = (m + 1) + ik <=> i = ik + m`] THEN ASM_MESON_TAC[DIVISION]; ALL_TAC] THEN FIRST_ASSUM(MP_TAC o CONJUNCT2 o SPEC `i:num` o MATCH_MP DIVISION) THEN SPEC_TAC(`i MOD k`,`j:num`) THEN GEN_TAC THEN ONCE_REWRITE_TAC[ARITH_RULE `j < k <=> j + 1 < k \/ j + 1 = k`] THEN STRIP_TAC THEN ASM_SIMP_TAC[MOD_LT] THEN AP_TERM_TAC THEN MATCH_MP_TAC MOD_UNIQ THEN EXISTS_TAC `1` THEN UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC]; ALL_TAC] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [ALL_TAC; REWRITE_TAC[HAS_SIZE] THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path r k x}` THEN ASM_SIMP_TAC[FINITE_PATHS] THEN SET_TAC[]] THEN MAP_EVERY X_GEN_TAC [`x:num->A`; `y:num->A`] THEN SIMP_TAC[IN_ELIM_THM] THEN REWRITE_TAC[path; FUN_EQ_THM] THEN STRIP_TAC THEN X_GEN_TAC `i:num` THEN REPEAT_TCL DISJ_CASES_THEN ASSUME_TAC (SPECL [`i:num`; `k:num`] LT_CASES) THENL [ASM_MESON_TAC[MOD_LT]; ASM_MESON_TAC[]; ASM_REWRITE_TAC[]] THEN ASM_MESON_TAC[MOD_0]);; let FINITE_CYCLES = prove (`!r k. FINITE(:A) /\ ~(k = 0) ==> FINITE {x:num->A | cycle r k x}`, MESON_TAC[HAS_SIZE_CYCLES; HAS_SIZE]);; let CARD_PATHCYCLES_STEP = prove (`!N m r k. (:A) HAS_SIZE N /\ ~(k = 0) /\ ~(m = 0) /\ (!x:A. {y | r x y} HAS_SIZE m) /\ (!x y. r x y ==> r y x) /\ (!x y. ~(x = y) ==> ?!z. r x z /\ r z y) ==> {x | path r (k + 2) x /\ x(k + 2) = x(0)} HAS_SIZE (m * CARD {x | path r k x /\ x(k) = x(0)} + CARD {x | path r (k) x /\ ~(x(k) = x(0))})`, REPEAT STRIP_TAC THEN REWRITE_TAC[SET_RULE `{x | path r (k + 2) x /\ x(k + 2) = x(0)} = {x | path r (k + 2) x /\ x k = x 0 /\ x(k + 2) = x(0)} UNION {x | path r (k + 2) x /\ ~(x k = x 0) /\ x(k + 2) = x(0)}`] THEN MATCH_MP_TAC HAS_SIZE_UNION THEN GEN_REWRITE_TAC I [CONJ_ASSOC] THEN CONJ_TAC THENL [ALL_TAC; SET_TAC[]] THEN CONJ_TAC THENL [SUBGOAL_THEN `{x:num->A | path r (k + 2) x /\ x k = x 0 /\ x (k + 2) = x 0} = IMAGE (\(x,a) i. if i = k + 1 then a else if i = k + 2 then x(0) else x(i)) {x,a | x IN {x | path r k x /\ x(k) = x(0)} /\ a IN {u | r (x k) u}}` SUBST1_TAC THENL [ALL_TAC; MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [REWRITE_TAC[FORALL_PAIR_THM; IN_ELIM_PAIR_THM] THEN REWRITE_TAC[IN_ELIM_THM; FUN_EQ_THM; PAIR_EQ] THEN MAP_EVERY X_GEN_TAC [`y:num->A`; `a:A`; `z:num->A`; `b:A`] THEN DISCH_THEN(fun th -> CONJ_TAC THEN MP_TAC th THENL [ALL_TAC; MESON_TAC[]]) THEN REPEAT(DISCH_THEN(CONJUNCTS_THEN2 STRIP_ASSUME_TAC MP_TAC)) THEN DISCH_THEN(fun th -> X_GEN_TAC `i:num` THEN MP_TAC th) THEN DISCH_THEN(fun th -> MP_TAC th THEN MP_TAC(SPEC `0` th)) THEN REWRITE_TAC[ARITH_RULE `~(0 = k + 1) /\ ~(0 = k + 2)`] THEN DISCH_TAC THEN ASM_CASES_TAC `k:num < i` THENL [ASM_MESON_TAC[path]; ALL_TAC] THEN DISCH_THEN(MP_TAC o SPEC `i:num`) THEN ASM_MESON_TAC[ARITH_RULE `k < k + 1 /\ k < k + 2`]; ALL_TAC] THEN ONCE_REWRITE_TAC[MULT_SYM] THEN MATCH_MP_TAC HAS_SIZE_PRODUCT_DEPENDENT THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[HAS_SIZE] THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path r k x}` THEN CONJ_TAC THENL [ALL_TAC; SET_TAC[]] THEN ASM_MESON_TAC[HAS_SIZE; FINITE_PATHS]] THEN REWRITE_TAC[EXTENSION; IN_IMAGE] THEN REWRITE_TAC[EXISTS_PAIR_THM; IN_ELIM_PAIR_THM] THEN REWRITE_TAC[FUN_EQ_THM; IN_ELIM_THM] THEN X_GEN_TAC `x:num->A` THEN EQ_TAC THENL [STRIP_TAC THEN EXISTS_TAC `\i. if i <= k then x(i):A else @x. T` THEN EXISTS_TAC `(x:num->A) (k + 1)` THEN REWRITE_TAC[IN_ELIM_THM; LE_REFL; LE_0] THEN ASM_REWRITE_TAC[CONJ_ASSOC] THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[path; ARITH_RULE `k < k + 2`]] THEN CONJ_TAC THENL [ALL_TAC; UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN SIMP_TAC[path; LT_IMP_LE; ARITH_RULE `i < k ==> i + 1 <= k`] THEN SIMP_TAC[GSYM NOT_LT] THEN MESON_TAC[ARITH_RULE `i < k ==> i < k + 2`]] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THEN ASM_CASES_TAC `i = k + 2` THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [path]) THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN DISCH_THEN(MP_TAC o SPEC `i:num` o CONJUNCT2) THEN ASM_REWRITE_TAC[ARITH_RULE `k + 2 < i <=> ~(i <= k) /\ ~(i = k + 1) /\ ~(i = k + 2)`]; ALL_TAC] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`z:num->A`; `b:A`] THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC STRIP_ASSUME_TAC) THEN DISCH_THEN(fun th -> MP_TAC th THEN MP_TAC(SPEC `0` th)) THEN REWRITE_TAC[COND_ID; ARITH_RULE `~(0 = k + 1)`] THEN DISCH_TAC THEN REWRITE_TAC[CONJ_ASSOC] THEN DISCH_THEN(LABEL_TAC "*") THEN CONJ_TAC THENL [ALL_TAC; REMOVE_THEN "*" (MP_TAC o SPEC `k + 2`) THEN ASM_REWRITE_TAC[ARITH_RULE `~(k + 2 = k + 1)`]] THEN CONJ_TAC THENL [ALL_TAC; REMOVE_THEN "*" (MP_TAC o SPEC `k:num`) THEN ASM_REWRITE_TAC[ARITH_RULE `~(k = k + 2) /\ ~(k = k + 1)`]] THEN UNDISCH_TAC `path r k (z:num->A)` THEN ASM_REWRITE_TAC[path] THEN SIMP_TAC[ARITH_RULE `k + 2 < i ==> k < i /\ ~(i = k + 1) /\ ~(i = k + 2)`] THEN STRIP_TAC THEN X_GEN_TAC `i:num` THEN DISCH_TAC THEN ASM_SIMP_TAC[ARITH_RULE `i < k + 2 ==> ~(i = k + 2)`] THEN REWRITE_TAC[ARITH_RULE `i + 1 = k + 2 <=> i = k + 1`] THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THENL [ASM_MESON_TAC[ARITH_RULE `~(x + 1 = x)`]; ALL_TAC] THEN REWRITE_TAC[EQ_ADD_RCANCEL] THEN COND_CASES_TAC THEN ASM_SIMP_TAC[] THENL [ASM_MESON_TAC[]; ALL_TAC] THEN ASM_MESON_TAC[ARITH_RULE `i < k + 2 /\ ~(i = k) /\ ~(i = k + 1) ==> i < k`]; ALL_TAC] THEN SUBGOAL_THEN `{x:num->A | path r (k + 2) x /\ ~(x k = x 0) /\ x (k + 2) = x 0} = IMAGE (\x i. if i = k + 1 then @z. r (x k) z /\ r z (x 0) else if i = k + 2 then x(0) else x(i)) {x | path r k x /\ ~(x(k) = x(0))}` SUBST1_TAC THENL [ALL_TAC; MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN CONJ_TAC THENL [ALL_TAC; REWRITE_TAC[HAS_SIZE] THEN MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{x:num->A | path r k x}` THEN CONJ_TAC THENL [ALL_TAC; SET_TAC[]] THEN ASM_MESON_TAC[HAS_SIZE; FINITE_PATHS]] THEN MAP_EVERY X_GEN_TAC [`x:num->A`; `y:num->A`] THEN REWRITE_TAC[IN_ELIM_THM] THEN STRIP_TAC THEN REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `k:num < i` THENL [ASM_MESON_TAC[path]; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [FUN_EQ_THM]) THEN DISCH_THEN(MP_TAC o SPEC `i:num`) THEN ASM_MESON_TAC[ARITH_RULE `k < k + 1 /\ k < k + 2`]] THEN REWRITE_TAC[EXTENSION; IN_IMAGE; IN_ELIM_THM] THEN X_GEN_TAC `x:num->A` THEN REWRITE_TAC[IN_ELIM_THM] THEN EQ_TAC THENL [STRIP_TAC THEN EXISTS_TAC `\i. if i <= k then x(i):A else @x. T` THEN ASM_REWRITE_TAC[LE_REFL; LE_0] THEN CONJ_TAC THENL [ALL_TAC; UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN SIMP_TAC[path; LT_IMP_LE; ARITH_RULE `i < k ==> i + 1 <= k`] THEN SIMP_TAC[GSYM NOT_LT] THEN MESON_TAC[ARITH_RULE `i < k ==> i < k + 2`]] THEN REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `i:num` THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THENL [CONV_TAC SYM_CONV THEN MATCH_MP_TAC SELECT_UNIQUE THEN UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN REWRITE_TAC[path] THEN DISCH_THEN(MP_TAC o CONJUNCT1) THEN DISCH_THEN(fun th -> MP_TAC(SPEC `k:num` th) THEN MP_TAC(SPEC `k + 1` th)) THEN REWRITE_TAC[ARITH_RULE `k < k + 2 /\ k + 1 < k + 2`] THEN REWRITE_TAC[GSYM ADD_ASSOC; ARITH] THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_CASES_TAC `i = k + 2` THEN ASM_REWRITE_TAC[] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN UNDISCH_TAC `path r (k + 2) (x:num->A)` THEN REWRITE_TAC[path] THEN DISCH_THEN(MP_TAC o CONJUNCT2) THEN ASM_MESON_TAC[ARITH_RULE `~(i <= k) /\ ~(i = k + 1) /\ ~(i = k + 2) ==> k + 2 < i`]; ALL_TAC] THEN DISCH_THEN(X_CHOOSE_THEN `y:num->A` STRIP_ASSUME_TAC) THEN ASM_REWRITE_TAC[ARITH_RULE `~(k + 2 = k + 1) /\ ~(0 = k + 1) /\ ~(0 = k + 2) /\ ~(k = k + 1) /\ ~(k = k + 2)`] THEN REWRITE_TAC[path] THEN CONJ_TAC THEN X_GEN_TAC `i:num` THEN DISCH_TAC THENL [REWRITE_TAC[ARITH_RULE `i + 1 = k + 2 <=> i = k + 1`] THEN ASM_CASES_TAC `i = k + 1` THEN ASM_REWRITE_TAC[] THENL [REWRITE_TAC[ARITH_RULE `(k + 1) + 1 = k + 1 <=> F`] THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_SIMP_TAC[ARITH_RULE `i < k + 2 ==> ~(i = k + 2)`] THEN REWRITE_TAC[EQ_ADD_RCANCEL] THEN COND_CASES_TAC THEN ASM_SIMP_TAC[] THENL [ASM_MESON_TAC[]; ALL_TAC] THEN UNDISCH_TAC `path r k (y:num->A)` THEN REWRITE_TAC[path] THEN DISCH_THEN(MATCH_MP_TAC o CONJUNCT1) THEN MAP_EVERY UNDISCH_TAC [`~(i:num = k)`; `~(i = k + 1)`; `i < k + 2`] THEN ARITH_TAC; ALL_TAC] THEN ASM_SIMP_TAC[ARITH_RULE `k + 2 < i ==> ~(i = k + 1) /\ ~(i = k + 2)`] THEN ASM_MESON_TAC[path; ARITH_RULE `k + 2 < i ==> k < i`]);; The first lemma about the number of cycles . let shiftable = new_definition `shiftable x y <=> ?k. !i. x(i) = y(i + k)`;; let SHIFTABLE_REFL = prove (`!x. shiftable x x`, REWRITE_TAC[shiftable] THEN MESON_TAC[ADD_CLAUSES]);; let SHIFTABLE_TRANS = prove (`!x y z. shiftable x y /\ shiftable y z ==> shiftable x z`, REWRITE_TAC[shiftable] THEN MESON_TAC[ADD_ASSOC]);; let SHIFTABLE_LOCAL = prove (`!x y p r. cycle r p x /\ cycle r p y /\ ~(p = 0) ==> (shiftable x y <=> ?k. k < p /\ !i. x(i) = y(i + k))`, REPEAT STRIP_TAC THEN REWRITE_TAC[shiftable] THEN EQ_TAC THENL [ALL_TAC; MESON_TAC[]] THEN DISCH_THEN(X_CHOOSE_TAC `k:num`) THEN EXISTS_TAC `k MOD p` THEN FIRST_ASSUM(MP_TAC o SPEC `k:num` o MATCH_MP DIVISION) THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN ASM_REWRITE_TAC[] THEN DISCH_THEN(fun th -> GEN_REWRITE_TAC (BINDER_CONV o LAND_CONV o ONCE_DEPTH_CONV) [th]) THEN ASM_MESON_TAC[CYCLE_OFFSET; ADD_AC]);; let SHIFTABLE_SYM = prove (`!x y p r. cycle r p x /\ cycle r p y /\ ~(p = 0) /\ shiftable x y ==> shiftable y x`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[TAUT `a /\ b /\ c /\ d <=> (a /\ b /\ c) /\ d`] THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN FIRST_ASSUM(SUBST1_TAC o MATCH_MP SHIFTABLE_LOCAL) THEN DISCH_THEN(X_CHOOSE_THEN `k:num` STRIP_ASSUME_TAC) THEN REWRITE_TAC[shiftable] THEN EXISTS_TAC `p - k:num` THEN ASM_SIMP_TAC[ARITH_RULE `k < p ==> (i + (p - k)) + k = i + p:num`] THEN ASM_MESON_TAC[cycle]);; let CYCLES_PRIME_LEMMA = prove (`!r p x. FINITE(:A) /\ prime p /\ (!x. ~(r x x)) ==> p divides CARD {x:num->A | cycle r p x}`, REPEAT GEN_TAC THEN ASM_CASES_TAC `p = 0` THEN ASM_REWRITE_TAC[PRIME_0] THEN STRIP_TAC THEN MATCH_MP_TAC EQUIVALENCE_UNIFORM_PARTITION_RESTRICT THEN EXISTS_TAC `shiftable:(num->A)->(num->A)->bool` THEN ASM_SIMP_TAC[IN_ELIM_THM; FINITE_CYCLES] THEN CONJ_TAC THENL [MESON_TAC[SHIFTABLE_REFL]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[SHIFTABLE_SYM]; ALL_TAC] THEN CONJ_TAC THENL [MESON_TAC[SHIFTABLE_TRANS]; ALL_TAC] THEN X_GEN_TAC `x:num->A` THEN DISCH_TAC THEN SUBGOAL_THEN `{y:num->A | cycle r p y /\ shiftable x y} HAS_SIZE p` (fun th -> MESON_TAC[HAS_SIZE; th]) THEN SUBGOAL_THEN `{y:num->A | cycle r p y /\ shiftable x y} = IMAGE (\k i. x(i + k)) {k | k < p}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_IMAGE; IN_ELIM_THM] THEN X_GEN_TAC `y:num->A` THEN REWRITE_TAC[FUN_EQ_THM] THEN EQ_TAC THENL [ASM_MESON_TAC[SHIFTABLE_LOCAL; SHIFTABLE_SYM]; ALL_TAC] THEN REPEAT STRIP_TAC THENL [FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [cycle]) THEN ASM_REWRITE_TAC[cycle] THEN MESON_TAC[ADD_AC]; ALL_TAC] THEN MATCH_MP_TAC SHIFTABLE_SYM THEN MAP_EVERY EXISTS_TAC [`p:num`; `r:A->A->bool`] THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [cycle]) THEN ASM_REWRITE_TAC[cycle; shiftable] THEN MESON_TAC[ADD_AC]; ALL_TAC] THEN MATCH_MP_TAC HAS_SIZE_IMAGE_INJ THEN REWRITE_TAC[HAS_SIZE_NUMSEG_LT] THEN REWRITE_TAC[IN_ELIM_THM] THEN MATCH_MP_TAC WLOG_LE THEN REWRITE_TAC[FUN_EQ_THM] THEN CONJ_TAC THENL [MESON_TAC[]; ALL_TAC] THEN MAP_EVERY X_GEN_TAC [`k:num`; `l:num`] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC(TAUT `(~p ==> F) ==> p`) THEN DISCH_TAC THEN SUBGOAL_THEN `!i. x(i):A = x(0)` MP_TAC THENL [ALL_TAC; ASM_MESON_TAC[cycle]] THEN MATCH_MP_TAC LOOP_COPRIME THEN EXISTS_TAC `p:num` THEN REWRITE_TAC[RIGHT_EXISTS_AND_THM] THEN CONJ_TAC THENL [ASM_MESON_TAC[cycle]; ALL_TAC] THEN EXISTS_TAC `l + (p - k):num` THEN CONJ_TAC THENL [X_GEN_TAC `i:num` THEN ONCE_REWRITE_TAC[ARITH_RULE `i + l + pk = (i + pk) + l:num`] THEN ASSUM_LIST(REWRITE_TAC o map GSYM) THEN SIMP_TAC[ARITH_RULE `k < p ==> (i + p - k) + k = i + p:num`; ASSUME `k < p:num`] THEN ASM_MESON_TAC[cycle]; ALL_TAC] THEN SUBGOAL_THEN `l + p - k = p + l - k:num` SUBST1_TAC THENL [MAP_EVERY UNDISCH_TAC [`k < p:num`; `k <= l:num`] THEN ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[NUMBER_RULE `coprime(p,p + d) <=> coprime(d,p)`] THEN MATCH_MP_TAC PRIME_COPRIME_LT THEN ASM_REWRITE_TAC[] THEN ASM_ARITH_TAC);; let FRIENDSHIP = prove (`!friend:person->person->bool. FINITE(:person) /\ (!x. ~(friend x x)) /\ (!x y. friend x y ==> friend y x) /\ (!x y. ~(x = y) ==> ?!z. friend x z /\ friend y z) ==> ?u. !v. ~(v = u) ==> friend u v`, REPEAT STRIP_TAC THEN UNDISCH_TAC `!x y:person. ~(x = y) ==> ?!z:person. friend x z /\ friend y z` THEN REWRITE_TAC[EXISTS_UNIQUE_THM] THEN REWRITE_TAC[TAUT `a ==> b /\ c <=> (a ==> b) /\ (a ==> c)`] THEN REWRITE_TAC[FORALL_AND_THM; RIGHT_IMP_FORALL_THM] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [RIGHT_IMP_EXISTS_THM] THEN REWRITE_TAC[SKOLEM_THM; IMP_IMP; GSYM CONJ_ASSOC] THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC STRIP_ASSUME_TAC) THEN DISCH_THEN(X_CHOOSE_TAC `mutualfriend:person->person->person`) THEN SUBGOAL_THEN `!s:person->bool. FINITE s` ASSUME_TAC THENL [ASM_MESON_TAC[SUBSET_UNIV; FINITE_SUBSET]; ALL_TAC] THEN ABBREV_TAC `degree = \p:person. CARD {q:person | friend p q}` THEN SUBGOAL_THEN `!x y:person. ~(friend x y) ==> degree(x):num <= degree(y)` ASSUME_TAC THENL [REPEAT STRIP_TAC THEN ASM_CASES_TAC `x:person = y` THENL [ASM_MESON_TAC[LE_REFL]; ALL_TAC] THEN EXPAND_TAC "degree" THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `CARD(IMAGE (\u. (mutualfriend:person->person->person) u y) {q | friend (x:person) q})` THEN CONJ_TAC THENL [ALL_TAC; MATCH_MP_TAC CARD_SUBSET THEN ASM SET_TAC[]] THEN MATCH_MP_TAC EQ_IMP_LE THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC CARD_IMAGE_INJ THEN ASM_REWRITE_TAC[IN_ELIM_THM] THEN MAP_EVERY X_GEN_TAC [`u1:person`; `u2:person`] THEN STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o SPECL [`x:person`; `(mutualfriend:person->person->person) u1 y`; `u1:person`; `u2:person`]) THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `!x y:person. ~(friend x y) ==> degree x:num = degree y` ASSUME_TAC THENL [ASM_MESON_TAC[LE_ANTISYM]; ALL_TAC] THEN GEN_REWRITE_TAC I [TAUT `p <=> ~ ~ p`] THEN GEN_REWRITE_TAC RAND_CONV [NOT_EXISTS_THM] THEN DISCH_THEN(ASSUME_TAC o REWRITE_RULE[NOT_FORALL_THM; NOT_IMP]) THEN SUBGOAL_THEN `?m:num. !x:person. degree(x) = m` STRIP_ASSUME_TAC THENL [FIRST_ASSUM(X_CHOOSE_THEN `b:person` STRIP_ASSUME_TAC o SPEC `a:person`) THEN ABBREV_TAC `c = (mutualfriend:person->person->person) a b` THEN ABBREV_TAC `k = (degree:person->num) a` THEN EXISTS_TAC `k:num` THEN SUBGOAL_THEN `(degree:person->num)(b) = k /\ ~(friend a b) /\ friend a c /\ friend b c` STRIP_ASSUME_TAC THENL [ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `!x:person. ~(x = c) ==> degree x = (k:num)` ASSUME_TAC THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `!p:person. {q:person | friend p q} HAS_SIZE m` ASSUME_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN SUBGOAL_THEN `~(m = 0)` ASSUME_TAC THENL [DISCH_TAC THEN UNDISCH_TAC `!p:person. {q:person | friend p q} HAS_SIZE m` THEN ASM_REWRITE_TAC[HAS_SIZE_0; EXTENSION; IN_ELIM_THM; NOT_IN_EMPTY] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `EVEN(m)` ASSUME_TAC THENL [UNDISCH_TAC `!x:person. degree x = (m:num)` THEN DISCH_THEN(SUBST1_TAC o SYM o SPEC `a:person`) THEN EXPAND_TAC "degree" THEN MATCH_MP_TAC ELEMENTS_PAIR_UP THEN EXISTS_TAC `\x y:person. friend a x /\ friend a y /\ friend x y` THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN ABBREV_TAC `N = CARD(:person)` THEN SUBGOAL_THEN `N = m * (m - 1) + 1` ASSUME_TAC THENL [ABBREV_TAC `t = {q:person | friend (a:person) q}` THEN SUBGOAL_THEN `FINITE(t:person->bool) /\ CARD t = m` STRIP_ASSUME_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN ABBREV_TAC `u = \b:person. {c:person | friend b c /\ ~(c IN (a INSERT t))}` THEN EXPAND_TAC "N" THEN SUBGOAL_THEN `(:person) = (a INSERT t) UNION UNIONS {u(b) | b IN t}` SUBST1_TAC THENL [REWRITE_TAC[EXTENSION; IN_INSERT; IN_UNIV; IN_UNION; IN_UNIONS] THEN MAP_EVERY EXPAND_TAC ["t"; "u"] THEN REWRITE_TAC[IN_ELIM_THM] THEN X_GEN_TAC `x:person` THEN MATCH_MP_TAC(TAUT `(~a /\ ~b ==> c) ==> (a \/ b) \/ c`) THEN STRIP_TAC THEN REWRITE_TAC[LEFT_AND_EXISTS_THM] THEN ONCE_REWRITE_TAC[TAUT `(a /\ b) /\ c <=> b /\ a /\ c`] THEN ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN REWRITE_TAC[UNWIND_THM2] THEN REWRITE_TAC[IN_ELIM_THM; IN_INSERT; DE_MORGAN_THM] THEN EXISTS_TAC `mutualfriend (a:person) (x:person) :person` THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `m * (m - 1) + 1 = (m + 1) + m * (m - 2)` SUBST1_TAC THENL [SIMP_TAC[ARITH_RULE `a + 1 = (m + 1) + m * c <=> a = m * (1 + c)`] THEN AP_TERM_TAC THEN UNDISCH_TAC `EVEN m` THEN ASM_CASES_TAC `m = 1` THEN ASM_REWRITE_TAC[ARITH] THEN DISCH_TAC THEN MAP_EVERY UNDISCH_TAC [`~(m = 0)`; `~(m = 1)`] THEN ARITH_TAC; ALL_TAC] THEN SUBGOAL_THEN `m + 1 = CARD((a:person) INSERT t)` SUBST1_TAC THENL [ASM_SIMP_TAC[CARD_CLAUSES; ADD1] THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `UNIONS {u b :person->bool | (b:person) IN t} HAS_SIZE m * (m - 2)` MP_TAC THENL [MATCH_MP_TAC HAS_SIZE_UNIONS THEN CONJ_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN CONJ_TAC THENL [ALL_TAC; EXPAND_TAC "u" THEN REWRITE_TAC[DISJOINT; EXTENSION; IN_INTER] THEN REWRITE_TAC[NOT_IN_EMPTY; IN_ELIM_THM; IN_INSERT] THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN ASM_MESON_TAC[]] THEN REPEAT STRIP_TAC THEN MP_TAC(ASSUME `(b:person) IN t`) THEN EXPAND_TAC "t" THEN REWRITE_TAC[IN_ELIM_THM] THEN DISCH_TAC THEN SUBGOAL_THEN `u (b:person) = {q:person | friend q b} DELETE a DELETE (mutualfriend a b)` SUBST1_TAC THENL [MAP_EVERY EXPAND_TAC ["u"; "t"] THEN REWRITE_TAC[EXTENSION; IN_INSERT; IN_DELETE; IN_ELIM_THM] THEN X_GEN_TAC `x:person` THEN FIRST_X_ASSUM(MP_TAC o SPECL [`a:person`; `b:person`; `(mutualfriend:person->person->person) a b`; `x:person`]) THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_SIMP_TAC[CARD_DELETE; HAS_SIZE] THEN REWRITE_TAC[IN_ELIM_THM; IN_DELETE] THEN COND_CASES_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN SUBGOAL_THEN `{q:person | friend q (b:person)} = {q | friend b q}` SUBST1_TAC THENL [ASM SET_TAC[]; ALL_TAC] THEN ASM_REWRITE_TAC[ARITH_RULE `m - 1 - 1 = m - 2`] THEN ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN REWRITE_TAC[HAS_SIZE] THEN DISCH_THEN(SUBST1_TAC o SYM o CONJUNCT2) THEN MATCH_MP_TAC CARD_UNION THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[EXTENSION; IN_INSERT; IN_INTER; NOT_IN_EMPTY; IN_UNIONS] THEN REWRITE_TAC[IN_ELIM_THM; LEFT_AND_EXISTS_THM] THEN ONCE_REWRITE_TAC[TAUT `(a /\ b) /\ c <=> b /\ a /\ c`] THEN ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN REWRITE_TAC[UNWIND_THM2] THEN MAP_EVERY EXPAND_TAC ["u"; "t"] THEN REWRITE_TAC[IN_ELIM_THM; IN_INSERT] THEN ASM_MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `~(m = 2)` ASSUME_TAC THENL [DISCH_THEN SUBST_ALL_TAC THEN RULE_ASSUM_TAC(CONV_RULE NUM_REDUCE_CONV) THEN SUBGOAL_THEN `(:person) HAS_SIZE 3` MP_TAC THENL [ASM_REWRITE_TAC[HAS_SIZE]; ALL_TAC] THEN CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN REWRITE_TAC[NOT_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`a:person`; `b:person`; `c:person`] THEN REWRITE_TAC[EXTENSION; IN_UNIV; IN_INSERT; NOT_IN_EMPTY] THEN STRIP_TAC THEN UNDISCH_TAC `!u:person. ?v:person. ~(v = u) /\ ~friend u v` THEN REWRITE_TAC[NOT_FORALL_THM; NOT_EXISTS_THM] THEN EXISTS_TAC `a:person` THEN UNDISCH_TAC `!p:person. {q:person | friend p q} HAS_SIZE 2` THEN DISCH_THEN(MP_TAC o SPEC `a:person`) THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN REWRITE_TAC[EXTENSION; IN_ELIM_THM; IN_INSERT; NOT_IN_EMPTY] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`x:person`; `y:person`] THEN STRIP_TAC THEN X_GEN_TAC `z:person` THEN UNDISCH_TAC `!x:person. x = a \/ x = b \/ x = c` THEN DISCH_THEN(fun th -> MAP_EVERY (fun x -> MP_TAC(SPEC x th)) [`x:person`; `y:person`; `z:person`]) THEN ASM_MESON_TAC[]; ALL_TAC] THEN MP_TAC(SPEC `m - 1` PRIME_FACTOR) THEN ANTS_TAC THENL [UNDISCH_TAC `~(m = 2)` THEN ARITH_TAC; ALL_TAC] THEN DISCH_THEN(X_CHOOSE_THEN `p:num` STRIP_ASSUME_TAC) THEN SUBGOAL_THEN `~(p divides 1)` MP_TAC THENL [ASM_MESON_TAC[DIVIDES_ONE; PRIME_1]; ALL_TAC] THEN REWRITE_TAC[] THEN MATCH_MP_TAC(NUMBER_RULE `!x. p divides (x + 1) /\ p divides x ==> p divides 1`) THEN EXISTS_TAC `m - 1` THEN ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[ARITH_RULE `~(m = 0) ==> m - 1 + 1 = m`] THEN MATCH_MP_TAC PRIME_DIVEXP THEN EXISTS_TAC `p - 2` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC(NUMBER_RULE `!q c K1 K2. p divides q /\ p divides c /\ c = (q + 1) * K1 + K2 /\ K1 + K2 = ((q + 1) * q + 1) * nep2 ==> p divides nep2`) THEN MAP_EVERY EXISTS_TAC [`m - 1`; `CARD {x:num->person | cycle friend p x}`; `CARD {x:num->person | path friend (p-2) x /\ x (p-2) = x 0}`; `CARD {x:num->person | path friend (p-2) x /\ ~(x (p-2) = x 0)}`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [MATCH_MP_TAC CYCLES_PRIME_LEMMA THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `3 <= p` ASSUME_TAC THENL [MATCH_MP_TAC(ARITH_RULE `2 <= p /\ ~(p = 2) ==> 3 <= p`) THEN ASM_SIMP_TAC[PRIME_GE_2] THEN DISCH_THEN SUBST_ALL_TAC THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM DIVIDES_2]) THEN MP_TAC(DIVIDES_CONV `2 divides 1`) THEN REWRITE_TAC[CONTRAPOS_THM] THEN MATCH_MP_TAC(NUMBER_RULE `!q. t divides q /\ m = q + 1 ==> t divides m ==> t divides w`) THEN EXISTS_TAC `m - 1` THEN ASM_REWRITE_TAC[] THEN UNDISCH_TAC `~(m = 0)` THEN ARITH_TAC; ALL_TAC] THEN ASM_SIMP_TAC[ARITH_RULE `~(m = 0) ==> m - 1 + 1 = m`] THEN CONJ_TAC THENL [MP_TAC(ISPECL[`friend:person->person->bool`; `p:num`] HAS_SIZE_CYCLES) THEN ANTS_TAC THENL [ASM_MESON_TAC[PRIME_0]; ALL_TAC] THEN SIMP_TAC[HAS_SIZE] THEN DISCH_THEN(K ALL_TAC) THEN MATCH_MP_TAC HAS_SIZE_CARD THEN SUBGOAL_THEN `p = (p - 2) + 2` (fun th -> GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [th]) THENL [ASM_MESON_TAC[PRIME_GE_2; SUB_ADD]; ALL_TAC] THEN MATCH_MP_TAC CARD_PATHCYCLES_STEP THEN EXISTS_TAC `N:num` THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN UNDISCH_TAC `3 <= p` THEN ARITH_TAC; ALL_TAC] THEN MP_TAC(ISPECL [`N:num`; `m:num`; `friend:person->person->bool`; `p - 2`] HAS_SIZE_PATHS) THEN ANTS_TAC THENL [ASM_MESON_TAC[HAS_SIZE]; ALL_TAC] THEN ASM_REWRITE_TAC[HAS_SIZE] THEN DISCH_THEN(SUBST1_TAC o SYM o CONJUNCT2) THEN MATCH_MP_TAC CARD_UNION_EQ THEN ASM_SIMP_TAC[FINITE_PATHS] THEN SET_TAC[]);;
d838b8ec662a9f510dd63b24636b11047c97c861da18c0f78f7e87fc5d9849a4
let-def/lrgrep
Numbering.mli
(******************************************************************************) (* *) (* Fix *) (* *) , Paris (* *) . All rights reserved . This file is distributed under the terms of the GNU Library General Public License version 2 , with a (* special exception on linking, as described in the file LICENSE. *) (* *) (******************************************************************************) (**This module offers a facility for {b assigning a unique number} to each value in a certain finite set and translating (both ways) between values and their numbers. *) open Sigs * The functor { ! Make } requires an implementation of maps for the type [ ] and offers a two - phase numbering facility . The function [ encode ] is backed by a map , therefore runs in logarithmic time or constant time , depending on the type of map that is used . The function [ decode ] is backed by an array of size [ n ] , therefore runs in constant time . and offers a two-phase numbering facility. The function [encode] is backed by a map, therefore runs in logarithmic time or constant time, depending on the type of map that is used. The function [decode] is backed by an array of size [n], therefore runs in constant time. *) module Make (M : IMPERATIVE_MAPS) : TWO_PHASE_NUMBERING with type t = M.key (**{!ForOrderedType} is a special case of {!Make} where it suffices for keys to be ordered. *) module ForOrderedType (T : OrderedType) : TWO_PHASE_NUMBERING with type t = T.t (**{!ForHashedType} is a special case of {!Make} where it suffices for keys to be hashed. *) module ForHashedType (T : HashedType) : TWO_PHASE_NUMBERING with type t = T.t * { ! } is a special case of { ! Make } where keys can have arbitrary type . OCaml 's built - in generic equality and hash functions are used . OCaml's built-in generic equality and hash functions are used. *) module ForType (T : TYPE) : TWO_PHASE_NUMBERING with type t = T.t
null
https://raw.githubusercontent.com/let-def/lrgrep/29e64174dc9617bcd1871fd2e4fd712269568324/lib/fix/Numbering.mli
ocaml
**************************************************************************** Fix special exception on linking, as described in the file LICENSE. **************************************************************************** *This module offers a facility for {b assigning a unique number} to each value in a certain finite set and translating (both ways) between values and their numbers. *{!ForOrderedType} is a special case of {!Make} where it suffices for keys to be ordered. *{!ForHashedType} is a special case of {!Make} where it suffices for keys to be hashed.
, Paris . All rights reserved . This file is distributed under the terms of the GNU Library General Public License version 2 , with a open Sigs * The functor { ! Make } requires an implementation of maps for the type [ ] and offers a two - phase numbering facility . The function [ encode ] is backed by a map , therefore runs in logarithmic time or constant time , depending on the type of map that is used . The function [ decode ] is backed by an array of size [ n ] , therefore runs in constant time . and offers a two-phase numbering facility. The function [encode] is backed by a map, therefore runs in logarithmic time or constant time, depending on the type of map that is used. The function [decode] is backed by an array of size [n], therefore runs in constant time. *) module Make (M : IMPERATIVE_MAPS) : TWO_PHASE_NUMBERING with type t = M.key module ForOrderedType (T : OrderedType) : TWO_PHASE_NUMBERING with type t = T.t module ForHashedType (T : HashedType) : TWO_PHASE_NUMBERING with type t = T.t * { ! } is a special case of { ! Make } where keys can have arbitrary type . OCaml 's built - in generic equality and hash functions are used . OCaml's built-in generic equality and hash functions are used. *) module ForType (T : TYPE) : TWO_PHASE_NUMBERING with type t = T.t
cb9ca97e58b16efcabd04dcb4a6543d6020ac4efca74f5a1a890bff96b0feae5
stchang/graph
timing-test-scc.rkt
#lang racket (require rackunit racket/unsafe/ops file/gunzip) (require graph/graph-weighted graph/graph-fns-basic graph/gen-graph "test-utils.rkt") times determined from running cmd line racket , on 2.40Ghz quad - core cpu ( Q6600 ) ;; otherwise when indicated, times recorded using i7-2600k ;; unzip file (when (not (file-exists? "SCC.txt")) (gunzip "SCC.txt.gz")) ;; scc timing test ------------------------------------------------------------ large ( 875714 vertices ) directed graph ( unweighted ) to check timing from Coursera Stanford Algorithms course ;; see also -005/forum/thread?thread_id=623 (define g/scc (mk-directed-graph null)) ~1sec to just read the file ~20sec to ( map string->number ( string - split e ) ) every line about ~40sec to create the graph ;; no difference when using with-input-from-file and open-input-file using in - port : ~28sec unsafe - struct - ref : ~28sec ;; on work machine: ~22s custom read - num ( work machine ): ~12.5s read - num with unsafe fx ops : ~12.5s (with-input-from-file "SCC.txt" (λ () SCC.txt file has format : num <space> <space> \n ;; (last line has no \n) (define (read-num [in (current-input-port)]) (let loop ([num 0]) (define b (read-byte in)) (if (eof-object? b) eof (case b # \newline [(32) num] ; #\space [else (loop (+ (* 10 num) (- b 48)))])))) (for ([u (in-port read-num)] [v (in-port read-num)]) (add-directed-edge! g/scc u v)))) ( for ( [ u ( in - port ) ] ) ( add - directed - edge ! g / scc u ( read ) ) ) ) ) ; (for ([e (in-lines)]) ( apply add - directed - edge ! g / scc ( map string->number ( string - split e ) ) ) ) ) ) ( " graph created " ) (check-equal? (length (get-vertices g/scc)) 875714) old get - edges ( using generator ): do nt use generator : ~3sec ( time ( length ( get - edges g / scc ) ) ) (check-equal? (length (get-edges g/scc)) 5105043) TIMING NOTES ( wikipedia scc fn --- do nt use do - dfs ) use in - S ? instead of member : from stuck to ~10s ;; use = instead of vertex=?: ~10s ;; unsafe list ops: ~<10s ;; use < instead of min: ~<10s (less than previous) unsafe fx ops : ~9s #;(define (fast-scc G) (define i 0) (define S null) (define SCC null) (define-vertex-properties G visited? lowlink index in-S?) (define (strong-connect v) (index-set! v i) (lowlink-set! v i) (set! i (unsafe-fx+ i 1)) (set! S (unsafe-cons-list v S)) (in-S?-set! v #t) (for ([w (in-neighbors G v)]) (cond [(not (lowlink-defined? w)) (strong-connect w) (let ([llv (lowlink v)][llw (lowlink w)]) (when (unsafe-fx< llw llv) (lowlink-set! v llw)))] [(in-S? w #:default #f) ;(member w S) (let ([llv (lowlink v)] [iw (index w)]) (when (unsafe-fx< iw llv) (lowlink-set! v iw))) #;(lowlink-set! v (min (lowlink v) (index w)))])) build SCC (define-values (new-scc S-rst) (splitf-at S (λ (w) (in-S?-set! w #f) (not (unsafe-fx= w v))))) (set! SCC (unsafe-cons-list (unsafe-cons-list v new-scc) SCC)) (set! S (unsafe-cdr S-rst)))) (for ([v (in-vertices G)]) (when (not (lowlink-defined? v)) (strong-connect v))) SCC) ;; TIMING NOTES (scc fn -- using do-dfs): ;; regular scc: stuck regular scc with in - S ? instead of member : ~12sec = instead of vertex= ? : ~12sec syntax - rules : ~12sec unsafe list ops : ~12sec unsafe arith ops : ~12sec < instead of min ( saves a hash - set ): ~11.5sec unsafe < : ~11.3sec use acc : ~11.3sec cache llv in epilogue ( saves a lookup : ~11.2sec do nt use broke ? parameter : ~10.2sec duplicate broken ? flag : ~10.3sec unsafe - struct - ref : ~10.3sec use do nt use generator for edges : ~9s expected : 371762 sccs (define SCC-TIME-LIMIT 30000) ; see timing notes above (let-values ([(res cpu real gc) (time-apply scc (list g/scc unsafe-fx=))]) (check-equal? 371762 (length (car res))) (when (> real SCC-TIME-LIMIT) (printf "scc time: ~a sec (LIMIT = ~a)\n" real SCC-TIME-LIMIT)) (check-true (< real SCC-TIME-LIMIT)))
null
https://raw.githubusercontent.com/stchang/graph/0ff9a1934f4421c53ec4b71cb48d54a6ad86c7b9/graph-test/tests/graph/timing-test-scc.rkt
racket
otherwise when indicated, times recorded using i7-2600k unzip file scc timing test ------------------------------------------------------------ see also -005/forum/thread?thread_id=623 no difference when using with-input-from-file and open-input-file on work machine: ~22s (last line has no \n) #\space (for ([e (in-lines)]) use = instead of vertex=?: ~10s unsafe list ops: ~<10s use < instead of min: ~<10s (less than previous) (define (fast-scc G) (member w S) (lowlink-set! v (min (lowlink v) (index w)))])) TIMING NOTES (scc fn -- using do-dfs): regular scc: stuck see timing notes above
#lang racket (require rackunit racket/unsafe/ops file/gunzip) (require graph/graph-weighted graph/graph-fns-basic graph/gen-graph "test-utils.rkt") times determined from running cmd line racket , on 2.40Ghz quad - core cpu ( Q6600 ) (when (not (file-exists? "SCC.txt")) (gunzip "SCC.txt.gz")) large ( 875714 vertices ) directed graph ( unweighted ) to check timing from Coursera Stanford Algorithms course (define g/scc (mk-directed-graph null)) ~1sec to just read the file ~20sec to ( map string->number ( string - split e ) ) every line about ~40sec to create the graph using in - port : ~28sec unsafe - struct - ref : ~28sec custom read - num ( work machine ): ~12.5s read - num with unsafe fx ops : ~12.5s (with-input-from-file "SCC.txt" (λ () SCC.txt file has format : num <space> <space> \n (define (read-num [in (current-input-port)]) (let loop ([num 0]) (define b (read-byte in)) (if (eof-object? b) eof (case b # \newline [else (loop (+ (* 10 num) (- b 48)))])))) (for ([u (in-port read-num)] [v (in-port read-num)]) (add-directed-edge! g/scc u v)))) ( for ( [ u ( in - port ) ] ) ( add - directed - edge ! g / scc u ( read ) ) ) ) ) ( apply add - directed - edge ! g / scc ( map string->number ( string - split e ) ) ) ) ) ) ( " graph created " ) (check-equal? (length (get-vertices g/scc)) 875714) old get - edges ( using generator ): do nt use generator : ~3sec ( time ( length ( get - edges g / scc ) ) ) (check-equal? (length (get-edges g/scc)) 5105043) TIMING NOTES ( wikipedia scc fn --- do nt use do - dfs ) use in - S ? instead of member : from stuck to ~10s unsafe fx ops : ~9s (define i 0) (define S null) (define SCC null) (define-vertex-properties G visited? lowlink index in-S?) (define (strong-connect v) (index-set! v i) (lowlink-set! v i) (set! i (unsafe-fx+ i 1)) (set! S (unsafe-cons-list v S)) (in-S?-set! v #t) (for ([w (in-neighbors G v)]) (cond [(not (lowlink-defined? w)) (strong-connect w) (let ([llv (lowlink v)][llw (lowlink w)]) (when (unsafe-fx< llw llv) (lowlink-set! v llw)))] (let ([llv (lowlink v)] [iw (index w)]) (when (unsafe-fx< iw llv) (lowlink-set! v iw))) build SCC (define-values (new-scc S-rst) (splitf-at S (λ (w) (in-S?-set! w #f) (not (unsafe-fx= w v))))) (set! SCC (unsafe-cons-list (unsafe-cons-list v new-scc) SCC)) (set! S (unsafe-cdr S-rst)))) (for ([v (in-vertices G)]) (when (not (lowlink-defined? v)) (strong-connect v))) SCC) regular scc with in - S ? instead of member : ~12sec = instead of vertex= ? : ~12sec syntax - rules : ~12sec unsafe list ops : ~12sec unsafe arith ops : ~12sec < instead of min ( saves a hash - set ): ~11.5sec unsafe < : ~11.3sec use acc : ~11.3sec cache llv in epilogue ( saves a lookup : ~11.2sec do nt use broke ? parameter : ~10.2sec duplicate broken ? flag : ~10.3sec unsafe - struct - ref : ~10.3sec use do nt use generator for edges : ~9s expected : 371762 sccs (let-values ([(res cpu real gc) (time-apply scc (list g/scc unsafe-fx=))]) (check-equal? 371762 (length (car res))) (when (> real SCC-TIME-LIMIT) (printf "scc time: ~a sec (LIMIT = ~a)\n" real SCC-TIME-LIMIT)) (check-true (< real SCC-TIME-LIMIT)))
9d5c8f4b497b6d374f187dae17df6fca354bada5888f1cd42fcf9a767712fe8c
pirapira/coq2rust
summary.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Pp open Errors open Util type marshallable = [ `Yes | `No | `Shallow ] type 'a summary_declaration = { freeze_function : marshallable -> 'a; unfreeze_function : 'a -> unit; init_function : unit -> unit } let summaries = ref Int.Map.empty let mangle id = id ^ "-SUMMARY" let internal_declare_summary hash sumname sdecl = let (infun, outfun) = Dyn.create (mangle sumname) in let dyn_freeze b = infun (sdecl.freeze_function b) and dyn_unfreeze sum = sdecl.unfreeze_function (outfun sum) and dyn_init = sdecl.init_function in let ddecl = { freeze_function = dyn_freeze; unfreeze_function = dyn_unfreeze; init_function = dyn_init } in summaries := Int.Map.add hash (sumname, ddecl) !summaries let all_declared_summaries = ref Int.Set.empty let summary_names = ref [] let name_of_summary name = try List.assoc name !summary_names with Not_found -> "summary name not found" let declare_summary sumname decl = let hash = String.hash sumname in let () = if Int.Map.mem hash !summaries then let (name, _) = Int.Map.find hash !summaries in anomaly ~label:"Summary.declare_summary" (str "Colliding summary names: " ++ str sumname ++ str " vs. " ++ str name) in all_declared_summaries := Int.Set.add hash !all_declared_summaries; summary_names := (hash, sumname) :: !summary_names; internal_declare_summary hash sumname decl type frozen = { summaries : (int * Dyn.t) list; * Ordered list w.r.t . the first component . ml_module : Dyn.t option; (** Special handling of the ml_module summary. *) } let empty_frozen = { summaries = []; ml_module = None; } let ml_modules = "ML-MODULES" let ml_modules_summary = String.hash ml_modules let freeze_summaries ~marshallable : frozen = let fold id (_, decl) accu = to debug missing Lazy.force if marshallable < > ` No then begin prerr_endline ( " begin marshalling " ^ i d ) ; ignore(Marshal.to_string ( decl.freeze_function marshallable ) [ ] ) ; prerr_endline ( " end marshalling " ^ i d ) ; end ; /debug if marshallable <> `No then begin prerr_endline ("begin marshalling " ^ id); ignore(Marshal.to_string (decl.freeze_function marshallable) []); prerr_endline ("end marshalling " ^ id); end; /debug *) let state = decl.freeze_function marshallable in if Int.equal id ml_modules_summary then { accu with ml_module = Some state } else { accu with summaries = (id, state) :: accu.summaries } in Int.Map.fold_right fold !summaries empty_frozen let unfreeze_summaries fs = The unfreezing of [ ml_modules_summary ] has to be anticipated since it * may modify the content of [ summaries ] ny loading new ML modules * may modify the content of [summaries] ny loading new ML modules *) let (_, decl) = try Int.Map.find ml_modules_summary !summaries with Not_found -> anomaly (str "Undeclared summary " ++ str ml_modules) in let () = match fs.ml_module with | None -> anomaly (str "Undeclared summary " ++ str ml_modules) | Some state -> decl.unfreeze_function state in let fold id (_, decl) states = if Int.equal id ml_modules_summary then states else match states with | [] -> let () = decl.init_function () in [] | (nid, state) :: rstates -> if Int.equal id nid then let () = decl.unfreeze_function state in rstates else let () = decl.init_function () in states in let fold id decl state = try fold id decl state with e when Errors.noncritical e -> let e = Errors.push e in Printf.eprintf "Error unfrezing summay %s\n%s\n%!" (name_of_summary id) (Pp.string_of_ppcmds (Errors.iprint e)); iraise e in (** We rely on the order of the frozen list, and the order of folding *) ignore (Int.Map.fold_left fold !summaries fs.summaries) let init_summaries () = Int.Map.iter (fun _ (_, decl) -> decl.init_function ()) !summaries * For global tables registered statically before the end of coqtop launch , the following empty [ init_function ] could be used . launch, the following empty [init_function] could be used. *) let nop () = () (** Selective freeze *) type frozen_bits = (int * Dyn.t) list let ids_of_string_list complement ids = if not complement then List.map String.hash ids else let fold accu id = let id = String.hash id in Int.Set.remove id accu in let ids = List.fold_left fold !all_declared_summaries ids in Int.Set.elements ids let freeze_summary ~marshallable ?(complement=false) ids = let ids = ids_of_string_list complement ids in List.map (fun id -> let (_, summary) = Int.Map.find id !summaries in id, summary.freeze_function marshallable) ids let unfreeze_summary datas = List.iter (fun (id, data) -> let (name, summary) = Int.Map.find id !summaries in try summary.unfreeze_function data with e -> let e = Errors.push e in prerr_endline ("Exception unfreezing " ^ name); iraise e) datas let surgery_summary { summaries; ml_module } bits = let summaries = List.map (fun (id, _ as orig) -> try id, List.assoc id bits with Not_found -> orig) summaries in { summaries; ml_module } let project_summary { summaries; ml_module } ?(complement=false) ids = let ids = ids_of_string_list complement ids in List.filter (fun (id, _) -> List.mem id ids) summaries let pointer_equal l1 l2 = CList.for_all2eq (fun (id1,v1) (id2,v2) -> id1 = id2 && Dyn.pointer_equal v1 v2) l1 l2 (** All-in-one reference declaration + registration *) let ref ?(freeze=fun _ r -> r) ~name x = let r = ref x in declare_summary name { freeze_function = (fun b -> freeze b !r); unfreeze_function = ((:=) r); init_function = (fun () -> r := x) }; r
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/library/summary.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Special handling of the ml_module summary. * We rely on the order of the frozen list, and the order of folding * Selective freeze * All-in-one reference declaration + registration
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open Errors open Util type marshallable = [ `Yes | `No | `Shallow ] type 'a summary_declaration = { freeze_function : marshallable -> 'a; unfreeze_function : 'a -> unit; init_function : unit -> unit } let summaries = ref Int.Map.empty let mangle id = id ^ "-SUMMARY" let internal_declare_summary hash sumname sdecl = let (infun, outfun) = Dyn.create (mangle sumname) in let dyn_freeze b = infun (sdecl.freeze_function b) and dyn_unfreeze sum = sdecl.unfreeze_function (outfun sum) and dyn_init = sdecl.init_function in let ddecl = { freeze_function = dyn_freeze; unfreeze_function = dyn_unfreeze; init_function = dyn_init } in summaries := Int.Map.add hash (sumname, ddecl) !summaries let all_declared_summaries = ref Int.Set.empty let summary_names = ref [] let name_of_summary name = try List.assoc name !summary_names with Not_found -> "summary name not found" let declare_summary sumname decl = let hash = String.hash sumname in let () = if Int.Map.mem hash !summaries then let (name, _) = Int.Map.find hash !summaries in anomaly ~label:"Summary.declare_summary" (str "Colliding summary names: " ++ str sumname ++ str " vs. " ++ str name) in all_declared_summaries := Int.Set.add hash !all_declared_summaries; summary_names := (hash, sumname) :: !summary_names; internal_declare_summary hash sumname decl type frozen = { summaries : (int * Dyn.t) list; * Ordered list w.r.t . the first component . ml_module : Dyn.t option; } let empty_frozen = { summaries = []; ml_module = None; } let ml_modules = "ML-MODULES" let ml_modules_summary = String.hash ml_modules let freeze_summaries ~marshallable : frozen = let fold id (_, decl) accu = to debug missing Lazy.force if marshallable < > ` No then begin prerr_endline ( " begin marshalling " ^ i d ) ; ignore(Marshal.to_string ( decl.freeze_function marshallable ) [ ] ) ; prerr_endline ( " end marshalling " ^ i d ) ; end ; /debug if marshallable <> `No then begin prerr_endline ("begin marshalling " ^ id); ignore(Marshal.to_string (decl.freeze_function marshallable) []); prerr_endline ("end marshalling " ^ id); end; /debug *) let state = decl.freeze_function marshallable in if Int.equal id ml_modules_summary then { accu with ml_module = Some state } else { accu with summaries = (id, state) :: accu.summaries } in Int.Map.fold_right fold !summaries empty_frozen let unfreeze_summaries fs = The unfreezing of [ ml_modules_summary ] has to be anticipated since it * may modify the content of [ summaries ] ny loading new ML modules * may modify the content of [summaries] ny loading new ML modules *) let (_, decl) = try Int.Map.find ml_modules_summary !summaries with Not_found -> anomaly (str "Undeclared summary " ++ str ml_modules) in let () = match fs.ml_module with | None -> anomaly (str "Undeclared summary " ++ str ml_modules) | Some state -> decl.unfreeze_function state in let fold id (_, decl) states = if Int.equal id ml_modules_summary then states else match states with | [] -> let () = decl.init_function () in [] | (nid, state) :: rstates -> if Int.equal id nid then let () = decl.unfreeze_function state in rstates else let () = decl.init_function () in states in let fold id decl state = try fold id decl state with e when Errors.noncritical e -> let e = Errors.push e in Printf.eprintf "Error unfrezing summay %s\n%s\n%!" (name_of_summary id) (Pp.string_of_ppcmds (Errors.iprint e)); iraise e in ignore (Int.Map.fold_left fold !summaries fs.summaries) let init_summaries () = Int.Map.iter (fun _ (_, decl) -> decl.init_function ()) !summaries * For global tables registered statically before the end of coqtop launch , the following empty [ init_function ] could be used . launch, the following empty [init_function] could be used. *) let nop () = () type frozen_bits = (int * Dyn.t) list let ids_of_string_list complement ids = if not complement then List.map String.hash ids else let fold accu id = let id = String.hash id in Int.Set.remove id accu in let ids = List.fold_left fold !all_declared_summaries ids in Int.Set.elements ids let freeze_summary ~marshallable ?(complement=false) ids = let ids = ids_of_string_list complement ids in List.map (fun id -> let (_, summary) = Int.Map.find id !summaries in id, summary.freeze_function marshallable) ids let unfreeze_summary datas = List.iter (fun (id, data) -> let (name, summary) = Int.Map.find id !summaries in try summary.unfreeze_function data with e -> let e = Errors.push e in prerr_endline ("Exception unfreezing " ^ name); iraise e) datas let surgery_summary { summaries; ml_module } bits = let summaries = List.map (fun (id, _ as orig) -> try id, List.assoc id bits with Not_found -> orig) summaries in { summaries; ml_module } let project_summary { summaries; ml_module } ?(complement=false) ids = let ids = ids_of_string_list complement ids in List.filter (fun (id, _) -> List.mem id ids) summaries let pointer_equal l1 l2 = CList.for_all2eq (fun (id1,v1) (id2,v2) -> id1 = id2 && Dyn.pointer_equal v1 v2) l1 l2 let ref ?(freeze=fun _ r -> r) ~name x = let r = ref x in declare_summary name { freeze_function = (fun b -> freeze b !r); unfreeze_function = ((:=) r); init_function = (fun () -> r := x) }; r
daa23d045cab43f75f5de976906c259d4244a1c375c88f320297dba99ca33af0
AdaCore/why3
alt_ergo.ml
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) (** Alt-ergo printer *) open Format open Pp open Wstdlib open Ident open Ty open Term open Decl open Printer open Cntexmp_printer let meta_ac = Theory.register_meta "AC" [Theory.MTlsymbol] ~desc:"Specify@ that@ a@ symbol@ is@ associative@ and@ commutative." let meta_printer_option = Theory.register_meta "printer_option" [Theory.MTstring] ~desc:"Pass@ additional@ parameters@ to@ the@ pretty-printer." let meta_invalid_trigger = Theory.register_meta "invalid trigger" [Theory.MTlsymbol] ~desc:"Specify@ that@ a@ symbol@ is@ not@ allowed@ in@ a@ trigger." type info = { info_syn : syntax_map; info_ac : Sls.t; info_show_attrs : bool; info_type_casts : bool; mutable info_csm : string list Mls.t; info_inv_trig : Sls.t; info_printer : ident_printer; mutable info_model: S.t; info_vc_term: vc_term_info; info_in_goal: bool; meta_model_projection: Sls.t; info_cntexample: bool } let ident_printer () = let bls = [ "abs_int"; "abs_real"; "ac"; "and"; "array"; "as"; "axiom"; "bitv"; "bool"; "case_split"; "check"; "cut"; "distinct"; "else"; "end"; "exists"; "extends"; "false"; "float"; "float32"; "float32d"; "float64"; "float64d"; "forall"; "fpa_rounding_mode"; "function"; "goal"; "if"; "in"; "include"; "int"; "int_ceil"; "int_floor"; "integer_log2"; "integer_round"; "is_theory_constant"; "inversion"; "let"; "linear_dependency"; "logic"; "max_int"; "max_real"; "min_int"; "min_real"; "not"; "not_theory_constant"; "of"; "or"; "parameter"; "predicate"; "pow_real_int"; "pow_real_real"; "prop"; "real"; "real_of_int"; "rewriting"; "select"; "sqrt_real"; "sqrt_real_default"; "sqrt_real_excess"; "store"; "then"; "theory"; "true"; "type"; "unit"; "void"; "with"; "Aw"; "Down"; "Od"; "NearestTiesToAway"; "NearestTiesToEven"; "Nd"; "No"; "Nu"; "Nz"; "ToZero"; "Up"; ] in let san = sanitizer char_to_alpha char_to_alnumus in create_ident_printer bls ~sanitizer:san let print_ident info fmt id = pp_print_string fmt (id_unique info.info_printer id) let print_attr fmt l = fprintf fmt "\"%s\"" l.attr_string let print_ident_attr info fmt id = if info.info_show_attrs then fprintf fmt "%s %a" (id_unique info.info_printer id) (print_list space print_attr) (Sattr.elements id.id_attrs) else print_ident info fmt id let forget_var info v = forget_id info.info_printer v.vs_name let collect_model_ls info ls = if relevant_for_counterexample ls.ls_name then info.info_model <- add_model_element (ls, ls.ls_name.id_loc, ls.ls_name.id_attrs) info.info_model (* let tv_printer = let san = sanitizer char_to_lalpha char_to_alnumus in create_ident_printer [] ~sanitizer:san let print_tvsymbol fmt tv = fprintf fmt "'%s" (id_unique tv_printer tv.tv_name) let forget_tvs () = forget_all tv_printer *) work around a " duplicate type variable " bug of Alt - Ergo 0.94 let print_tvsymbol, forget_tvs = let htv = Hid.create 5 in (fun info fmt tv -> Hid.replace htv tv.tv_name (); fprintf fmt "'%s" (id_unique info.info_printer tv.tv_name)), (fun info -> Hid.iter (fun id _ -> forget_id info.info_printer id) htv; Hid.clear htv) let rec print_type info fmt ty = match ty.ty_node with | Tyvar id -> print_tvsymbol info fmt id | Tyapp (ts, tl) -> begin match query_syntax info.info_syn ts.ts_name with | Some s -> syntax_arguments s (print_type info) fmt tl | None -> fprintf fmt "%a%a" (print_tyapp info) tl (print_ident info) ts.ts_name end and print_tyapp info fmt = function | [] -> () | [ty] -> fprintf fmt "%a " (print_type info) ty | tl -> fprintf fmt "(%a) " (print_list comma (print_type info)) tl (* can the type of a value be derived from the type of the arguments? *) let unambig_fs fs = let rec lookup v ty = match ty.ty_node with | Tyvar u when tv_equal u v -> true | _ -> ty_any (lookup v) ty in let lookup v = List.exists (lookup v) fs.ls_args in let rec inspect ty = match ty.ty_node with | Tyvar u when not (lookup u) -> false | _ -> ty_all inspect ty in inspect (Opt.get fs.ls_value) let number_format = { Number.long_int_support = `Default; Number.negative_int_support = `Default; Number.dec_int_support = `Default; Number.hex_int_support = `Unsupported; Number.oct_int_support = `Unsupported; Number.bin_int_support = `Unsupported; Number.negative_real_support = `Default; Number.dec_real_support = `Default; Number.hex_real_support = `Default; Number.frac_real_support = `Unsupported (fun _ _ -> assert false); } let rec print_term info fmt t = if check_for_counterexample t then begin match t.t_node with | Tapp (ls,_) -> info.info_model <- add_model_element (ls,t.t_loc,t.t_attrs) info.info_model | _ -> assert false (* cannot happen because check_for_counterexample is true *) end; check_enter_vc_term t info.info_in_goal info.info_vc_term; let () = match t.t_node with | Tconst c -> Constant.(print number_format unsupported_escape) fmt c | Tvar { vs_name = id } -> print_ident info fmt id | Tapp (ls, tl) -> begin match query_syntax info.info_syn ls.ls_name with | Some s -> syntax_arguments s (print_term info) fmt tl | None -> begin if (tl = []) then begin let vc_term_info = info.info_vc_term in if vc_term_info.vc_inside then begin match vc_term_info.vc_loc with | None -> () | Some loc -> let attrs = (*match vc_term_info.vc_func_name with | None ->*) ls.ls_name.id_attrs | Some _ - > model_trace_for_postcondition : model_trace_for_postcondition ~attrs:ls.ls_name.id_attrs info.info_vc_term *) in let _t_check_pos = t_attr_set ~loc attrs t in (* TODO: temporarily disable collecting variables inside the term triggering VC *) info.info_model < - add_model_element t_check_pos info.info_model ; () end end; end; if (Mls.mem ls info.info_csm) then begin let print_field fmt (id,t) = fprintf fmt "%s =@ %a" id (print_term info) t in fprintf fmt "{@ %a@ }" (print_list semi print_field) (List.combine (Mls.find ls info.info_csm) tl) end else if ls.ls_proj then begin fprintf fmt "%a.%a" (print_tapp info) tl (print_ident info) ls.ls_name end else if (unambig_fs ls || not info.info_type_casts) then begin fprintf fmt "%a%a" (print_ident info) ls.ls_name (print_tapp info) tl end else begin fprintf fmt "(%a%a : %a)" (print_ident info) ls.ls_name (print_tapp info) tl (print_type info) (t_type t) end end | Tlet (t1, tb) -> let v, t2 = t_open_bound tb in fprintf fmt "(let %a =@ %a@ : %a in@ %a)" (print_ident info) v.vs_name (print_term info) t1 (* some version of alt-ergo have an inefficient typing of let *) (print_type info) v.vs_ty (print_term info) t2; forget_var info v | Tif(t1,t2,t3) -> fprintf fmt "(if %a then %a else %a)" (print_fmla info) t1 (print_term info) t2 (print_term info) t3 | Tcase _ -> unsupportedTerm t "alt-ergo: you must eliminate match" | Teps _ -> unsupportedTerm t "alt-ergo: you must eliminate epsilon" | Tquant _ | Tbinop _ | Tnot _ | Ttrue | Tfalse -> raise (TermExpected t) in check_exit_vc_term t info.info_in_goal info.info_vc_term; and print_tapp info fmt = function | [] -> () | tl -> fprintf fmt "(%a)" (print_list comma (print_term info)) tl and print_fmla info fmt f = if check_for_counterexample f then begin match f.t_node with | Tapp (ls,_) -> info.info_model <- add_model_element (ls,f.t_loc,f.t_attrs) info.info_model | _ -> assert false (* cannot happen because check_for_counterexample is true *) end; check_enter_vc_term f info.info_in_goal info.info_vc_term; let () = if info.info_show_attrs then match Sattr.elements f.t_attrs with | [] -> print_fmla_node info fmt f | l -> fprintf fmt "(%a : %a)" (print_list colon print_attr) l (print_fmla_node info) f else print_fmla_node info fmt f in check_exit_vc_term f info.info_in_goal info.info_vc_term and print_fmla_node info fmt f = match f.t_node with | Tapp ({ ls_name = id }, []) -> print_ident info fmt id | Tapp (ls, tl) -> begin match query_syntax info.info_syn ls.ls_name with | Some s -> syntax_arguments s (print_term info) fmt tl | None -> fprintf fmt "%a(%a)" (print_ident info) ls.ls_name (print_list comma (print_term info)) tl end | Tquant (q, fq) -> let vl, tl, f = t_open_quant fq in let q, tl = match q with | Tforall -> "forall", tl | Texists -> "exists", [] (* Alt-ergo has no triggers for exists *) in let forall fmt v = fprintf fmt "%s %a:%a" q (print_ident_attr info) v.vs_name (print_type info) v.vs_ty in fprintf fmt "@[(%a%a.@ %a)@]" (print_list dot forall) vl (print_triggers info) tl (print_fmla info) f; List.iter (forget_var info) vl | Tbinop (Tand, f1, f2) -> fprintf fmt "(%a and@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tbinop (Tor, f1, f2) -> fprintf fmt "(%a or@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tbinop (Timplies, f1, f2) -> fprintf fmt "(%a ->@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tbinop (Tiff, f1, f2) -> fprintf fmt "(%a <->@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tnot f -> fprintf fmt "(not %a)" (print_fmla info) f | Ttrue -> pp_print_string fmt "true" | Tfalse -> pp_print_string fmt "false" | Tif(t1,t2,t3) -> fprintf fmt "(if %a then %a else %a)" (print_fmla info) t1 (print_fmla info) t2 (print_fmla info) t3 | Tlet (t1, tb) -> let v, f2 = t_open_bound tb in fprintf fmt "(let %a =@ %a@ : %a in@ %a)" (print_ident info) v.vs_name (print_term info) t1 (* some version of alt-ergo have an inefficient typing of let *) (print_type info) v.vs_ty (print_fmla info) f2; forget_var info v | Tcase _ -> unsupportedTerm f "alt-ergo: you must eliminate match" | Tvar _ | Tconst _ | Teps _ -> raise (FmlaExpected f) and print_expr info fmt = TermTF.t_select (print_term info fmt) (print_fmla info fmt) and print_triggers info fmt tl = let filter = function | { t_ty = Some _ } -> true | { t_node = Tapp (ps,_) } -> not (Sls.mem ps info.info_inv_trig) | _ -> false in let tl = List.map (List.filter filter) tl in let tl = List.filter (function [] -> false | _::_ -> true) tl in if tl = [] then () else fprintf fmt "@ [%a]" (print_list alt (print_list comma (print_expr info))) tl let print_logic_binder info fmt v = fprintf fmt "%a: %a" (print_ident info) v.vs_name (print_type info) v.vs_ty let print_type_decl info fmt ts = match ts.ts_args with | [] -> fprintf fmt "type %a" (print_ident info) ts.ts_name | [tv] -> fprintf fmt "type %a %a" (print_tvsymbol info) tv (print_ident info) ts.ts_name | tl -> fprintf fmt "type (%a) %a" (print_list comma (print_tvsymbol info)) tl (print_ident info) ts.ts_name let print_enum_decl info fmt ts csl = let print_cs fmt (ls,_) = print_ident info fmt ls.ls_name in fprintf fmt "@[<hov 2>type %a =@ %a@]@\n@\n" (print_ident info) ts.ts_name (print_list alt2 print_cs) csl let print_ty_decl info fmt ts = if is_alias_type_def ts.ts_def then () else if Mid.mem ts.ts_name info.info_syn then () else (fprintf fmt "%a@\n@\n" (print_type_decl info) ts; forget_tvs info) let print_data_decl info d fmt = function | ts, csl (* monomorphic enumeration *) when ts.ts_args = [] && List.for_all (fun (_,l) -> l = []) csl -> print_enum_decl info fmt ts csl | ts, [cs,pjl] (* records *) -> if Sid.mem ts.ts_name (get_used_syms_decl d) then unsupported "alt-ergo: recursive records are not supported"; let field_name_ty pj ty = let pj = match pj with | Some pj -> pj.ls_name | None -> let field_name = id_fresh (cs.ls_name.id_string^"_proj") in let field_name = create_vsymbol field_name ty(*dummy*) in field_name.vs_name in let pj = sprintf "%a" (print_ident info) pj in pj,ty in let l = List.map2 field_name_ty pjl cs.ls_args in info.info_csm <- Mls.add cs (List.map fst l) info.info_csm; let print_field fmt (pj,ty) = fprintf fmt "%s@ :@ %a" pj (print_type info) ty in fprintf fmt "%a@ =@ {@ %a@ }@\n@\n" (print_type_decl info) ts (print_list semi print_field) l | _, _ -> unsupported "alt-ergo: algebraic datatype are not supported" let print_data_decl info d fmt ((ts, _csl) as p) = if Mid.mem ts.ts_name info.info_syn then () else print_data_decl info d fmt p let print_param_decl info fmt ls = let sac = if Sls.mem ls info.info_ac then "ac " else "" in fprintf fmt "@[<hov 2>logic %s%a : %a%s%a@]@\n@\n" sac (print_ident info) ls.ls_name (print_list comma (print_type info)) ls.ls_args (if ls.ls_args = [] then "" else " -> ") (print_option_or_default "prop" (print_type info)) ls.ls_value let print_param_decl info fmt ls = if Mid.mem ls.ls_name info.info_syn then () else (print_param_decl info fmt ls; forget_tvs info) let print_logic_decl info fmt ls ld = collect_model_ls info ls; let vl,e = open_ls_defn ld in begin match e.t_ty with | Some _ -> TODO AC ? fprintf fmt "@[<hov 2>function %a(%a) : %a =@ %a@]@\n@\n" (print_ident info) ls.ls_name (print_list comma (print_logic_binder info)) vl (print_type info) (Opt.get ls.ls_value) (print_term info) e | None -> fprintf fmt "@[<hov 2>predicate %a(%a) =@ %a@]@\n@\n" (print_ident info) ls.ls_name (print_list comma (print_logic_binder info)) vl (print_fmla info) e end; List.iter (forget_var info) vl let print_logic_decl info fmt (ls,ld) = if Mid.mem ls.ls_name info.info_syn then () else (print_logic_decl info fmt ls ld; forget_tvs info) let print_info_model info = (* Prints the content of info.info_model *) let info_model = info.info_model in if not (S.is_empty info_model) && info.info_cntexample then begin let model_map = S.fold (fun ((ls,_,_) as el) acc -> let s = asprintf "%a" (print_ident info) ls.ls_name in Mstr.add s el acc) info_model Mstr.empty in (); (* Printing model has modification of info.info_model as undesirable side-effect. Revert it back. *) info.info_model <- info_model; model_map end else Mstr.empty let print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f = match k with | Paxiom -> fprintf fmt "@[<hov 2>axiom %a :@ %a@]@\n@\n" (print_ident info) pr.pr_name (print_fmla info) f | Pgoal -> (match pr.pr_name.id_loc with | None -> () | Some loc -> fprintf fmt " @[(* %a *)@]@\n" Loc.pp_position loc); let model_list = print_info_model info in printing_info := Some { why3_env = env; vc_term_loc = vc_loc; vc_term_attrs = vc_attrs; queried_terms = model_list; type_coercions = Mty.empty; type_fields = Mty.empty; record_fields = Mls.empty; constructors = Mstr.empty; set_str = Mstr.empty; }; fprintf fmt "@[<hov 2>goal %a :@ %a@]@\n" (print_ident info) pr.pr_name (print_fmla info) f | Plemma -> assert false let print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f = if Mid.mem pr.pr_name info.info_syn then () else (print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f; forget_tvs info) let print_decl vc_loc vc_attrs env printing_info info fmt d = match d.d_node with | Dtype ts -> print_ty_decl info fmt ts | Ddata dl -> print_list nothing (print_data_decl info d) fmt dl | Dparam ls -> collect_model_ls info ls; print_param_decl info fmt ls | Dlogic dl -> print_list nothing (print_logic_decl info) fmt dl | Dind _ -> unsupportedDecl d "alt-ergo: inductive definitions are not supported" | Dprop (k,pr,f) -> print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f let check_options ((show,cast) as acc) = function | [Theory.MAstr "show_attrs"] -> true, cast | [Theory.MAstr "no_type_cast"] -> show, false | [Theory.MAstr _] -> acc | _ -> assert false let print_task args ?old:_ fmt task = let inv_trig = Task.on_tagged_ls meta_invalid_trigger task in let show,cast = Task.on_meta meta_printer_option check_options (false,true) task in let cntexample = Driver.get_counterexmp task in let vc_loc = Intro_vc_vars_counterexmp.get_location_of_vc task in let vc_attrs = (Task.task_goal_fmla task).t_attrs in let vc_info = {vc_inside = false; vc_loc; vc_func_name = None} in let info = { info_syn = Discriminate.get_syntax_map task; info_ac = Task.on_tagged_ls meta_ac task; info_show_attrs = show; info_type_casts = cast; info_csm = Mls.empty; info_inv_trig = Sls.add ps_equ inv_trig; info_printer = ident_printer (); info_model = S.empty; info_vc_term = vc_info; info_in_goal = false; meta_model_projection = Task.on_tagged_ls Theory.meta_projection task; info_cntexample = cntexample; } in print_prelude fmt args.prelude; print_th_prelude task fmt args.th_prelude; let rec print_decls = function | Some t -> print_decls t.Task.task_prev; begin match t.Task.task_decl.Theory.td_node with | Theory.Decl d -> begin try print_decl vc_loc vc_attrs args.env args.printing_info info fmt d with Unsupported s -> raise (UnsupportedDecl (d,s)) end | _ -> () end | None -> () in print_decls task; pp_print_flush fmt () let () = register_printer "alt-ergo" print_task ~desc:"Printer for the Alt-Ergo theorem prover."
null
https://raw.githubusercontent.com/AdaCore/why3/03f27e383b7191f9df0c7df84016a6450603f864/src/printer/alt_ergo.ml
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** * Alt-ergo printer let tv_printer = let san = sanitizer char_to_lalpha char_to_alnumus in create_ident_printer [] ~sanitizer:san let print_tvsymbol fmt tv = fprintf fmt "'%s" (id_unique tv_printer tv.tv_name) let forget_tvs () = forget_all tv_printer can the type of a value be derived from the type of the arguments? cannot happen because check_for_counterexample is true match vc_term_info.vc_func_name with | None -> TODO: temporarily disable collecting variables inside the term triggering VC some version of alt-ergo have an inefficient typing of let cannot happen because check_for_counterexample is true Alt-ergo has no triggers for exists some version of alt-ergo have an inefficient typing of let monomorphic enumeration records dummy Prints the content of info.info_model Printing model has modification of info.info_model as undesirable side-effect. Revert it back.
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University General Public License version 2.1 , with the special exception open Format open Pp open Wstdlib open Ident open Ty open Term open Decl open Printer open Cntexmp_printer let meta_ac = Theory.register_meta "AC" [Theory.MTlsymbol] ~desc:"Specify@ that@ a@ symbol@ is@ associative@ and@ commutative." let meta_printer_option = Theory.register_meta "printer_option" [Theory.MTstring] ~desc:"Pass@ additional@ parameters@ to@ the@ pretty-printer." let meta_invalid_trigger = Theory.register_meta "invalid trigger" [Theory.MTlsymbol] ~desc:"Specify@ that@ a@ symbol@ is@ not@ allowed@ in@ a@ trigger." type info = { info_syn : syntax_map; info_ac : Sls.t; info_show_attrs : bool; info_type_casts : bool; mutable info_csm : string list Mls.t; info_inv_trig : Sls.t; info_printer : ident_printer; mutable info_model: S.t; info_vc_term: vc_term_info; info_in_goal: bool; meta_model_projection: Sls.t; info_cntexample: bool } let ident_printer () = let bls = [ "abs_int"; "abs_real"; "ac"; "and"; "array"; "as"; "axiom"; "bitv"; "bool"; "case_split"; "check"; "cut"; "distinct"; "else"; "end"; "exists"; "extends"; "false"; "float"; "float32"; "float32d"; "float64"; "float64d"; "forall"; "fpa_rounding_mode"; "function"; "goal"; "if"; "in"; "include"; "int"; "int_ceil"; "int_floor"; "integer_log2"; "integer_round"; "is_theory_constant"; "inversion"; "let"; "linear_dependency"; "logic"; "max_int"; "max_real"; "min_int"; "min_real"; "not"; "not_theory_constant"; "of"; "or"; "parameter"; "predicate"; "pow_real_int"; "pow_real_real"; "prop"; "real"; "real_of_int"; "rewriting"; "select"; "sqrt_real"; "sqrt_real_default"; "sqrt_real_excess"; "store"; "then"; "theory"; "true"; "type"; "unit"; "void"; "with"; "Aw"; "Down"; "Od"; "NearestTiesToAway"; "NearestTiesToEven"; "Nd"; "No"; "Nu"; "Nz"; "ToZero"; "Up"; ] in let san = sanitizer char_to_alpha char_to_alnumus in create_ident_printer bls ~sanitizer:san let print_ident info fmt id = pp_print_string fmt (id_unique info.info_printer id) let print_attr fmt l = fprintf fmt "\"%s\"" l.attr_string let print_ident_attr info fmt id = if info.info_show_attrs then fprintf fmt "%s %a" (id_unique info.info_printer id) (print_list space print_attr) (Sattr.elements id.id_attrs) else print_ident info fmt id let forget_var info v = forget_id info.info_printer v.vs_name let collect_model_ls info ls = if relevant_for_counterexample ls.ls_name then info.info_model <- add_model_element (ls, ls.ls_name.id_loc, ls.ls_name.id_attrs) info.info_model work around a " duplicate type variable " bug of Alt - Ergo 0.94 let print_tvsymbol, forget_tvs = let htv = Hid.create 5 in (fun info fmt tv -> Hid.replace htv tv.tv_name (); fprintf fmt "'%s" (id_unique info.info_printer tv.tv_name)), (fun info -> Hid.iter (fun id _ -> forget_id info.info_printer id) htv; Hid.clear htv) let rec print_type info fmt ty = match ty.ty_node with | Tyvar id -> print_tvsymbol info fmt id | Tyapp (ts, tl) -> begin match query_syntax info.info_syn ts.ts_name with | Some s -> syntax_arguments s (print_type info) fmt tl | None -> fprintf fmt "%a%a" (print_tyapp info) tl (print_ident info) ts.ts_name end and print_tyapp info fmt = function | [] -> () | [ty] -> fprintf fmt "%a " (print_type info) ty | tl -> fprintf fmt "(%a) " (print_list comma (print_type info)) tl let unambig_fs fs = let rec lookup v ty = match ty.ty_node with | Tyvar u when tv_equal u v -> true | _ -> ty_any (lookup v) ty in let lookup v = List.exists (lookup v) fs.ls_args in let rec inspect ty = match ty.ty_node with | Tyvar u when not (lookup u) -> false | _ -> ty_all inspect ty in inspect (Opt.get fs.ls_value) let number_format = { Number.long_int_support = `Default; Number.negative_int_support = `Default; Number.dec_int_support = `Default; Number.hex_int_support = `Unsupported; Number.oct_int_support = `Unsupported; Number.bin_int_support = `Unsupported; Number.negative_real_support = `Default; Number.dec_real_support = `Default; Number.hex_real_support = `Default; Number.frac_real_support = `Unsupported (fun _ _ -> assert false); } let rec print_term info fmt t = if check_for_counterexample t then begin match t.t_node with | Tapp (ls,_) -> info.info_model <- add_model_element (ls,t.t_loc,t.t_attrs) info.info_model end; check_enter_vc_term t info.info_in_goal info.info_vc_term; let () = match t.t_node with | Tconst c -> Constant.(print number_format unsupported_escape) fmt c | Tvar { vs_name = id } -> print_ident info fmt id | Tapp (ls, tl) -> begin match query_syntax info.info_syn ls.ls_name with | Some s -> syntax_arguments s (print_term info) fmt tl | None -> begin if (tl = []) then begin let vc_term_info = info.info_vc_term in if vc_term_info.vc_inside then begin match vc_term_info.vc_loc with | None -> () | Some loc -> ls.ls_name.id_attrs | Some _ - > model_trace_for_postcondition : model_trace_for_postcondition ~attrs:ls.ls_name.id_attrs info.info_vc_term *) in let _t_check_pos = t_attr_set ~loc attrs t in info.info_model < - add_model_element t_check_pos info.info_model ; () end end; end; if (Mls.mem ls info.info_csm) then begin let print_field fmt (id,t) = fprintf fmt "%s =@ %a" id (print_term info) t in fprintf fmt "{@ %a@ }" (print_list semi print_field) (List.combine (Mls.find ls info.info_csm) tl) end else if ls.ls_proj then begin fprintf fmt "%a.%a" (print_tapp info) tl (print_ident info) ls.ls_name end else if (unambig_fs ls || not info.info_type_casts) then begin fprintf fmt "%a%a" (print_ident info) ls.ls_name (print_tapp info) tl end else begin fprintf fmt "(%a%a : %a)" (print_ident info) ls.ls_name (print_tapp info) tl (print_type info) (t_type t) end end | Tlet (t1, tb) -> let v, t2 = t_open_bound tb in fprintf fmt "(let %a =@ %a@ : %a in@ %a)" (print_ident info) v.vs_name (print_term info) t1 (print_type info) v.vs_ty (print_term info) t2; forget_var info v | Tif(t1,t2,t3) -> fprintf fmt "(if %a then %a else %a)" (print_fmla info) t1 (print_term info) t2 (print_term info) t3 | Tcase _ -> unsupportedTerm t "alt-ergo: you must eliminate match" | Teps _ -> unsupportedTerm t "alt-ergo: you must eliminate epsilon" | Tquant _ | Tbinop _ | Tnot _ | Ttrue | Tfalse -> raise (TermExpected t) in check_exit_vc_term t info.info_in_goal info.info_vc_term; and print_tapp info fmt = function | [] -> () | tl -> fprintf fmt "(%a)" (print_list comma (print_term info)) tl and print_fmla info fmt f = if check_for_counterexample f then begin match f.t_node with | Tapp (ls,_) -> info.info_model <- add_model_element (ls,f.t_loc,f.t_attrs) info.info_model end; check_enter_vc_term f info.info_in_goal info.info_vc_term; let () = if info.info_show_attrs then match Sattr.elements f.t_attrs with | [] -> print_fmla_node info fmt f | l -> fprintf fmt "(%a : %a)" (print_list colon print_attr) l (print_fmla_node info) f else print_fmla_node info fmt f in check_exit_vc_term f info.info_in_goal info.info_vc_term and print_fmla_node info fmt f = match f.t_node with | Tapp ({ ls_name = id }, []) -> print_ident info fmt id | Tapp (ls, tl) -> begin match query_syntax info.info_syn ls.ls_name with | Some s -> syntax_arguments s (print_term info) fmt tl | None -> fprintf fmt "%a(%a)" (print_ident info) ls.ls_name (print_list comma (print_term info)) tl end | Tquant (q, fq) -> let vl, tl, f = t_open_quant fq in let q, tl = match q with | Tforall -> "forall", tl in let forall fmt v = fprintf fmt "%s %a:%a" q (print_ident_attr info) v.vs_name (print_type info) v.vs_ty in fprintf fmt "@[(%a%a.@ %a)@]" (print_list dot forall) vl (print_triggers info) tl (print_fmla info) f; List.iter (forget_var info) vl | Tbinop (Tand, f1, f2) -> fprintf fmt "(%a and@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tbinop (Tor, f1, f2) -> fprintf fmt "(%a or@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tbinop (Timplies, f1, f2) -> fprintf fmt "(%a ->@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tbinop (Tiff, f1, f2) -> fprintf fmt "(%a <->@ %a)" (print_fmla info) f1 (print_fmla info) f2 | Tnot f -> fprintf fmt "(not %a)" (print_fmla info) f | Ttrue -> pp_print_string fmt "true" | Tfalse -> pp_print_string fmt "false" | Tif(t1,t2,t3) -> fprintf fmt "(if %a then %a else %a)" (print_fmla info) t1 (print_fmla info) t2 (print_fmla info) t3 | Tlet (t1, tb) -> let v, f2 = t_open_bound tb in fprintf fmt "(let %a =@ %a@ : %a in@ %a)" (print_ident info) v.vs_name (print_term info) t1 (print_type info) v.vs_ty (print_fmla info) f2; forget_var info v | Tcase _ -> unsupportedTerm f "alt-ergo: you must eliminate match" | Tvar _ | Tconst _ | Teps _ -> raise (FmlaExpected f) and print_expr info fmt = TermTF.t_select (print_term info fmt) (print_fmla info fmt) and print_triggers info fmt tl = let filter = function | { t_ty = Some _ } -> true | { t_node = Tapp (ps,_) } -> not (Sls.mem ps info.info_inv_trig) | _ -> false in let tl = List.map (List.filter filter) tl in let tl = List.filter (function [] -> false | _::_ -> true) tl in if tl = [] then () else fprintf fmt "@ [%a]" (print_list alt (print_list comma (print_expr info))) tl let print_logic_binder info fmt v = fprintf fmt "%a: %a" (print_ident info) v.vs_name (print_type info) v.vs_ty let print_type_decl info fmt ts = match ts.ts_args with | [] -> fprintf fmt "type %a" (print_ident info) ts.ts_name | [tv] -> fprintf fmt "type %a %a" (print_tvsymbol info) tv (print_ident info) ts.ts_name | tl -> fprintf fmt "type (%a) %a" (print_list comma (print_tvsymbol info)) tl (print_ident info) ts.ts_name let print_enum_decl info fmt ts csl = let print_cs fmt (ls,_) = print_ident info fmt ls.ls_name in fprintf fmt "@[<hov 2>type %a =@ %a@]@\n@\n" (print_ident info) ts.ts_name (print_list alt2 print_cs) csl let print_ty_decl info fmt ts = if is_alias_type_def ts.ts_def then () else if Mid.mem ts.ts_name info.info_syn then () else (fprintf fmt "%a@\n@\n" (print_type_decl info) ts; forget_tvs info) let print_data_decl info d fmt = function when ts.ts_args = [] && List.for_all (fun (_,l) -> l = []) csl -> print_enum_decl info fmt ts csl if Sid.mem ts.ts_name (get_used_syms_decl d) then unsupported "alt-ergo: recursive records are not supported"; let field_name_ty pj ty = let pj = match pj with | Some pj -> pj.ls_name | None -> let field_name = id_fresh (cs.ls_name.id_string^"_proj") in field_name.vs_name in let pj = sprintf "%a" (print_ident info) pj in pj,ty in let l = List.map2 field_name_ty pjl cs.ls_args in info.info_csm <- Mls.add cs (List.map fst l) info.info_csm; let print_field fmt (pj,ty) = fprintf fmt "%s@ :@ %a" pj (print_type info) ty in fprintf fmt "%a@ =@ {@ %a@ }@\n@\n" (print_type_decl info) ts (print_list semi print_field) l | _, _ -> unsupported "alt-ergo: algebraic datatype are not supported" let print_data_decl info d fmt ((ts, _csl) as p) = if Mid.mem ts.ts_name info.info_syn then () else print_data_decl info d fmt p let print_param_decl info fmt ls = let sac = if Sls.mem ls info.info_ac then "ac " else "" in fprintf fmt "@[<hov 2>logic %s%a : %a%s%a@]@\n@\n" sac (print_ident info) ls.ls_name (print_list comma (print_type info)) ls.ls_args (if ls.ls_args = [] then "" else " -> ") (print_option_or_default "prop" (print_type info)) ls.ls_value let print_param_decl info fmt ls = if Mid.mem ls.ls_name info.info_syn then () else (print_param_decl info fmt ls; forget_tvs info) let print_logic_decl info fmt ls ld = collect_model_ls info ls; let vl,e = open_ls_defn ld in begin match e.t_ty with | Some _ -> TODO AC ? fprintf fmt "@[<hov 2>function %a(%a) : %a =@ %a@]@\n@\n" (print_ident info) ls.ls_name (print_list comma (print_logic_binder info)) vl (print_type info) (Opt.get ls.ls_value) (print_term info) e | None -> fprintf fmt "@[<hov 2>predicate %a(%a) =@ %a@]@\n@\n" (print_ident info) ls.ls_name (print_list comma (print_logic_binder info)) vl (print_fmla info) e end; List.iter (forget_var info) vl let print_logic_decl info fmt (ls,ld) = if Mid.mem ls.ls_name info.info_syn then () else (print_logic_decl info fmt ls ld; forget_tvs info) let print_info_model info = let info_model = info.info_model in if not (S.is_empty info_model) && info.info_cntexample then begin let model_map = S.fold (fun ((ls,_,_) as el) acc -> let s = asprintf "%a" (print_ident info) ls.ls_name in Mstr.add s el acc) info_model Mstr.empty in (); info.info_model <- info_model; model_map end else Mstr.empty let print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f = match k with | Paxiom -> fprintf fmt "@[<hov 2>axiom %a :@ %a@]@\n@\n" (print_ident info) pr.pr_name (print_fmla info) f | Pgoal -> (match pr.pr_name.id_loc with | None -> () | Some loc -> fprintf fmt " @[(* %a *)@]@\n" Loc.pp_position loc); let model_list = print_info_model info in printing_info := Some { why3_env = env; vc_term_loc = vc_loc; vc_term_attrs = vc_attrs; queried_terms = model_list; type_coercions = Mty.empty; type_fields = Mty.empty; record_fields = Mls.empty; constructors = Mstr.empty; set_str = Mstr.empty; }; fprintf fmt "@[<hov 2>goal %a :@ %a@]@\n" (print_ident info) pr.pr_name (print_fmla info) f | Plemma -> assert false let print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f = if Mid.mem pr.pr_name info.info_syn then () else (print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f; forget_tvs info) let print_decl vc_loc vc_attrs env printing_info info fmt d = match d.d_node with | Dtype ts -> print_ty_decl info fmt ts | Ddata dl -> print_list nothing (print_data_decl info d) fmt dl | Dparam ls -> collect_model_ls info ls; print_param_decl info fmt ls | Dlogic dl -> print_list nothing (print_logic_decl info) fmt dl | Dind _ -> unsupportedDecl d "alt-ergo: inductive definitions are not supported" | Dprop (k,pr,f) -> print_prop_decl vc_loc vc_attrs env printing_info info fmt k pr f let check_options ((show,cast) as acc) = function | [Theory.MAstr "show_attrs"] -> true, cast | [Theory.MAstr "no_type_cast"] -> show, false | [Theory.MAstr _] -> acc | _ -> assert false let print_task args ?old:_ fmt task = let inv_trig = Task.on_tagged_ls meta_invalid_trigger task in let show,cast = Task.on_meta meta_printer_option check_options (false,true) task in let cntexample = Driver.get_counterexmp task in let vc_loc = Intro_vc_vars_counterexmp.get_location_of_vc task in let vc_attrs = (Task.task_goal_fmla task).t_attrs in let vc_info = {vc_inside = false; vc_loc; vc_func_name = None} in let info = { info_syn = Discriminate.get_syntax_map task; info_ac = Task.on_tagged_ls meta_ac task; info_show_attrs = show; info_type_casts = cast; info_csm = Mls.empty; info_inv_trig = Sls.add ps_equ inv_trig; info_printer = ident_printer (); info_model = S.empty; info_vc_term = vc_info; info_in_goal = false; meta_model_projection = Task.on_tagged_ls Theory.meta_projection task; info_cntexample = cntexample; } in print_prelude fmt args.prelude; print_th_prelude task fmt args.th_prelude; let rec print_decls = function | Some t -> print_decls t.Task.task_prev; begin match t.Task.task_decl.Theory.td_node with | Theory.Decl d -> begin try print_decl vc_loc vc_attrs args.env args.printing_info info fmt d with Unsupported s -> raise (UnsupportedDecl (d,s)) end | _ -> () end | None -> () in print_decls task; pp_print_flush fmt () let () = register_printer "alt-ergo" print_task ~desc:"Printer for the Alt-Ergo theorem prover."
853ebf708f12e98b994f5cfb88b7c39adbd4be9cdc3774f4bd607da068d6364f
wedesoft/sfsim25
quaternion.clj
(ns sfsim25.quaternion "Complex algebra implementation." (:refer-clojure :exclude [+ - *]) (:require [clojure.core :as c] [clojure.math :refer (cos sin sqrt) :as m] [clojure.core.matrix :refer (matrix mul)] [clojure.core.matrix.linear :as l] [sfsim25.util :refer (sinc sqr)]) (:import [mikera.vectorz Vector])) (set! *unchecked-math* true) (defrecord Quaternion [^double a ^double b ^double c ^double d]) (set! *warn-on-reflection* true) (defn + "Add two quaternions" ^Quaternion [^Quaternion p ^Quaternion q] (->Quaternion (c/+ (:a p) (:a q)) (c/+ (:b p) (:b q)) (c/+ (:c p) (:c q)) (c/+ (:d p) (:d q)))) (defn - "Subtract two quaternions" ^Quaternion [^Quaternion p ^Quaternion q] (->Quaternion (c/- (:a p) (:a q)) (c/- (:b p) (:b q)) (c/- (:c p) (:c q)) (c/- (:d p) (:d q)))) (defn * "Multiply two quaternions" ^Quaternion [^Quaternion p ^Quaternion q] (->Quaternion (c/- (c/* (:a p) (:a q)) (c/* (:b p) (:b q)) (c/* (:c p) (:c q)) (c/* (:d p) (:d q))) (c/- (c/+ (c/* (:a p) (:b q)) (c/* (:b p) (:a q)) (c/* (:c p) (:d q))) (c/* (:d p) (:c q))) (c/+ (c/- (c/* (:a p) (:c q)) (c/* (:b p) (:d q))) (c/* (:c p) (:a q)) (c/* (:d p) (:b q))) (c/+ (c/- (c/+ (c/* (:a p) (:d q)) (c/* (:b p) (:c q))) (c/* (:c p) (:b q))) (c/* (:d p) (:a q))))) (defn norm2 "Compute square of norm of quaternion" ^double [^Quaternion q] (c/+ (sqr (:a q)) (sqr (:b q)) (sqr (:c q)) (sqr (:d q)))) (defn norm "Compute norm of quaternion" ^double [^Quaternion q] (sqrt (norm2 q))) (defn normalize "Normalize quaternion to create unit quaternion" ^Quaternion [^Quaternion q] (let [factor (/ 1.0 (norm q))] (->Quaternion (c/* (:a q) factor) (c/* (:b q) factor) (c/* (:c q) factor) (c/* (:d q) factor)))) (defn conjugate "Return conjugate of quaternion" ^Quaternion [^Quaternion q] (->Quaternion (:a q) (c/- (:b q)) (c/- (:c q)) (c/- (:d q)))) (defn inverse "Return inverse of quaternion" ^Quaternion [^Quaternion q] (let [factor (/ 1.0 (norm2 q))] (->Quaternion (c/* (:a q) factor) (c/* (c/- (:b q)) factor) (c/* (c/- (:c q)) factor) (c/* (c/- (:d q)) factor)))) (defn vector->quaternion "Convert 3D vector to quaternion" ^Quaternion [^Vector v] (apply ->Quaternion 0.0 v)) (defn quaternion->vector "Convert quaternion to 3D vector" ^Vector [^Quaternion q] (matrix [(:b q) (:c q) (:d q)])) (defn exp "Exponentiation of quaternion" ^Quaternion [^Quaternion q] (let [scale (m/exp (:a q)) rotation (l/norm (quaternion->vector q)) cos-scale (c/* scale (cos rotation)) sinc-scale (c/* scale (sinc rotation))] (->Quaternion cos-scale (c/* sinc-scale (:b q)) (c/* sinc-scale (:c q)) (c/* sinc-scale (:d q))))) (defn rotation "Generate quaternion to represent rotation" ^Quaternion [^double theta ^Vector v] (let [scale (/ theta 2)] (exp (vector->quaternion (mul scale v))))) (defn rotate-vector "Rotate a vector with a rotation represented by a quaternion" ^Vector [^Quaternion q ^Vector v] (quaternion->vector (* (* q (vector->quaternion v)) (conjugate q)))) (set! *warn-on-reflection* false) (set! *unchecked-math* false)
null
https://raw.githubusercontent.com/wedesoft/sfsim25/0d439804cf61ecdea499e9fab6adaee9d91b65d1/src/sfsim25/quaternion.clj
clojure
(ns sfsim25.quaternion "Complex algebra implementation." (:refer-clojure :exclude [+ - *]) (:require [clojure.core :as c] [clojure.math :refer (cos sin sqrt) :as m] [clojure.core.matrix :refer (matrix mul)] [clojure.core.matrix.linear :as l] [sfsim25.util :refer (sinc sqr)]) (:import [mikera.vectorz Vector])) (set! *unchecked-math* true) (defrecord Quaternion [^double a ^double b ^double c ^double d]) (set! *warn-on-reflection* true) (defn + "Add two quaternions" ^Quaternion [^Quaternion p ^Quaternion q] (->Quaternion (c/+ (:a p) (:a q)) (c/+ (:b p) (:b q)) (c/+ (:c p) (:c q)) (c/+ (:d p) (:d q)))) (defn - "Subtract two quaternions" ^Quaternion [^Quaternion p ^Quaternion q] (->Quaternion (c/- (:a p) (:a q)) (c/- (:b p) (:b q)) (c/- (:c p) (:c q)) (c/- (:d p) (:d q)))) (defn * "Multiply two quaternions" ^Quaternion [^Quaternion p ^Quaternion q] (->Quaternion (c/- (c/* (:a p) (:a q)) (c/* (:b p) (:b q)) (c/* (:c p) (:c q)) (c/* (:d p) (:d q))) (c/- (c/+ (c/* (:a p) (:b q)) (c/* (:b p) (:a q)) (c/* (:c p) (:d q))) (c/* (:d p) (:c q))) (c/+ (c/- (c/* (:a p) (:c q)) (c/* (:b p) (:d q))) (c/* (:c p) (:a q)) (c/* (:d p) (:b q))) (c/+ (c/- (c/+ (c/* (:a p) (:d q)) (c/* (:b p) (:c q))) (c/* (:c p) (:b q))) (c/* (:d p) (:a q))))) (defn norm2 "Compute square of norm of quaternion" ^double [^Quaternion q] (c/+ (sqr (:a q)) (sqr (:b q)) (sqr (:c q)) (sqr (:d q)))) (defn norm "Compute norm of quaternion" ^double [^Quaternion q] (sqrt (norm2 q))) (defn normalize "Normalize quaternion to create unit quaternion" ^Quaternion [^Quaternion q] (let [factor (/ 1.0 (norm q))] (->Quaternion (c/* (:a q) factor) (c/* (:b q) factor) (c/* (:c q) factor) (c/* (:d q) factor)))) (defn conjugate "Return conjugate of quaternion" ^Quaternion [^Quaternion q] (->Quaternion (:a q) (c/- (:b q)) (c/- (:c q)) (c/- (:d q)))) (defn inverse "Return inverse of quaternion" ^Quaternion [^Quaternion q] (let [factor (/ 1.0 (norm2 q))] (->Quaternion (c/* (:a q) factor) (c/* (c/- (:b q)) factor) (c/* (c/- (:c q)) factor) (c/* (c/- (:d q)) factor)))) (defn vector->quaternion "Convert 3D vector to quaternion" ^Quaternion [^Vector v] (apply ->Quaternion 0.0 v)) (defn quaternion->vector "Convert quaternion to 3D vector" ^Vector [^Quaternion q] (matrix [(:b q) (:c q) (:d q)])) (defn exp "Exponentiation of quaternion" ^Quaternion [^Quaternion q] (let [scale (m/exp (:a q)) rotation (l/norm (quaternion->vector q)) cos-scale (c/* scale (cos rotation)) sinc-scale (c/* scale (sinc rotation))] (->Quaternion cos-scale (c/* sinc-scale (:b q)) (c/* sinc-scale (:c q)) (c/* sinc-scale (:d q))))) (defn rotation "Generate quaternion to represent rotation" ^Quaternion [^double theta ^Vector v] (let [scale (/ theta 2)] (exp (vector->quaternion (mul scale v))))) (defn rotate-vector "Rotate a vector with a rotation represented by a quaternion" ^Vector [^Quaternion q ^Vector v] (quaternion->vector (* (* q (vector->quaternion v)) (conjugate q)))) (set! *warn-on-reflection* false) (set! *unchecked-math* false)
f8000973aafdde7dec7d79e3990b75b340a004892b03e0e29fa73c61a2d0c9da
bmeurer/ocamljit2
test4.ml
let output_lock = Mutex.create() let rec fib n = if n <= 2 then 1 else fib(n-1) + fib(n-2) let fibtask n = while true do Mutex.lock output_lock; print_int(fib n); print_newline(); Mutex.unlock output_lock done let _ = Thread.create fibtask 28; Thread.delay 1.0; while true do let l = read_line () in Mutex.lock output_lock; print_string ">> "; print_string l; print_newline(); Mutex.unlock output_lock done
null
https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/testsuite/tests/lib-threads/test4.ml
ocaml
let output_lock = Mutex.create() let rec fib n = if n <= 2 then 1 else fib(n-1) + fib(n-2) let fibtask n = while true do Mutex.lock output_lock; print_int(fib n); print_newline(); Mutex.unlock output_lock done let _ = Thread.create fibtask 28; Thread.delay 1.0; while true do let l = read_line () in Mutex.lock output_lock; print_string ">> "; print_string l; print_newline(); Mutex.unlock output_lock done
a9b0cab1b372604b2a897eed7a75d00e1f4b2c47eedaa9a90806e130ba203a9e
sgbj/MaximaSharp
sqfr.lisp
Author University of Nebraska at Kearney Copyright ( C ) 2004 , Brief Description : Maxima code for linear homogeneous second order ;; differential equations. Maxima odelin is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License , ;; . Maxima odelin has NO WARRANTY , not even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ($put '$sqfr 1 '$version) (eval-when #+gcl (load compile eval) #-gcl (:load-toplevel :compile-toplevel :execute) ($load "odeutils")) ;; If x is a symbol for a subvarp, return its general representation. ;; Otherwise signal an error---the argument f is the string name of ;; a function that requires the symbol. (defun require-symbol (x f &optional a) (declare (ignore a)) (setq x ($ratdisrep x)) (if (or (symbolp x) ($subvarp x)) x (merror "Function ~:M requires a symbol; instead found ~:M" f x)) x) (defun $strictmysqfr (p x) (setq p ($expand ($ratdisrep p))) (setq x (require-symbol x "$mysqfr")) (let ((i 1) (lc 1) (r) (ai) (w) (bad) (acc nil) (q) (s) ($gcd '$spmod) ($algebraic t) ($resultant '$red) ($ratfac nil) ($ratprint nil)) (setq lc ($coeff p x ($hipow p x))) (setq p ($expand (div p lc))) (while (not ($freeof x p)) (setq r ($gcd p ($diff p x) x)) (setq q ($first ($divide p r))) (setq ai ($first ($divide q ($gcd q r x) x))) (setq ai (div ai ($coeff ai x ($hipow ai x)))) (push ai acc) (setq p r) (incf i)) (setq acc (reverse acc)) (setq r lc) (setq i 0) (while acc (setq ai (pop acc)) (setq r (mul r (power ai (incf i)))) (setq s ($resultant ai ($diff ai x) x)) (if (not ($constantp s)) (push ($factor s) bad)) (dolist (wi w) (setq s ($resultant ai wi x)) (if (not ($constantp s)) (push ($factor s) bad))) (push ai w)) (setq bad `(($set) ,@bad)) (setq bad (mbag-map #'(lambda (w) `((mnotequal) ,w 0)) bad)) (if (not ($emptyp bad)) (mtell "Proviso: assuming ~:M~%" bad)) (values r bad))) (defun $mysqfr (p x) (setq p ($expand ($ratdisrep p))) (setq x (require-symbol x "$mysqfr")) (let ((i 0) (r) (ai) (acc) (q) ($gcd '$spmod) ($algebraic t)) (cond ((like 0 p) 0) (t (setq p ($expand p)) (setq acc ($coeff p x ($hipow p x))) (setq p (div p acc)) (while (not ($freeof x p)) (setq r ($gcd p ($diff p x) x)) (setq q ($first ($divide p r x))) (setq ai ($first ($divide q ($gcd q r x) x))) (setq ai (div ai ($coeff ai x ($hipow ai x)))) (setq acc (mul acc (power ai (incf i)))) (setq p r)) acc))))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/contrib/diffequations/sqfr.lisp
lisp
differential equations. you can redistribute it and/or . MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. If x is a symbol for a subvarp, return its general representation. Otherwise signal an error---the argument f is the string name of a function that requires the symbol.
Author University of Nebraska at Kearney Copyright ( C ) 2004 , Brief Description : Maxima code for linear homogeneous second order modify it under the terms of the GNU General Public License , Maxima odelin has NO WARRANTY , not even the implied warranty of ($put '$sqfr 1 '$version) (eval-when #+gcl (load compile eval) #-gcl (:load-toplevel :compile-toplevel :execute) ($load "odeutils")) (defun require-symbol (x f &optional a) (declare (ignore a)) (setq x ($ratdisrep x)) (if (or (symbolp x) ($subvarp x)) x (merror "Function ~:M requires a symbol; instead found ~:M" f x)) x) (defun $strictmysqfr (p x) (setq p ($expand ($ratdisrep p))) (setq x (require-symbol x "$mysqfr")) (let ((i 1) (lc 1) (r) (ai) (w) (bad) (acc nil) (q) (s) ($gcd '$spmod) ($algebraic t) ($resultant '$red) ($ratfac nil) ($ratprint nil)) (setq lc ($coeff p x ($hipow p x))) (setq p ($expand (div p lc))) (while (not ($freeof x p)) (setq r ($gcd p ($diff p x) x)) (setq q ($first ($divide p r))) (setq ai ($first ($divide q ($gcd q r x) x))) (setq ai (div ai ($coeff ai x ($hipow ai x)))) (push ai acc) (setq p r) (incf i)) (setq acc (reverse acc)) (setq r lc) (setq i 0) (while acc (setq ai (pop acc)) (setq r (mul r (power ai (incf i)))) (setq s ($resultant ai ($diff ai x) x)) (if (not ($constantp s)) (push ($factor s) bad)) (dolist (wi w) (setq s ($resultant ai wi x)) (if (not ($constantp s)) (push ($factor s) bad))) (push ai w)) (setq bad `(($set) ,@bad)) (setq bad (mbag-map #'(lambda (w) `((mnotequal) ,w 0)) bad)) (if (not ($emptyp bad)) (mtell "Proviso: assuming ~:M~%" bad)) (values r bad))) (defun $mysqfr (p x) (setq p ($expand ($ratdisrep p))) (setq x (require-symbol x "$mysqfr")) (let ((i 0) (r) (ai) (acc) (q) ($gcd '$spmod) ($algebraic t)) (cond ((like 0 p) 0) (t (setq p ($expand p)) (setq acc ($coeff p x ($hipow p x))) (setq p (div p acc)) (while (not ($freeof x p)) (setq r ($gcd p ($diff p x) x)) (setq q ($first ($divide p r x))) (setq ai ($first ($divide q ($gcd q r x) x))) (setq ai (div ai ($coeff ai x ($hipow ai x)))) (setq acc (mul acc (power ai (incf i)))) (setq p r)) acc))))
c58a1c3640c687cf1941d6bf8e6e3e6d192ea87b4e7f1727821c438c136c2a89
flosell/lambdacd-git
ssh_agent_support.clj
(ns lambdacd-git.ssh-agent-support (:require [clojure.tools.logging :as log]) (:import (org.eclipse.jgit.transport SshSessionFactory JschConfigSessionFactory) (com.jcraft.jsch.agentproxy.connector SSHAgentConnector) (org.eclipse.jgit.util FS) (com.jcraft.jsch.agentproxy RemoteIdentityRepository) (com.jcraft.jsch.agentproxy.usocket JNAUSocketFactory) (com.jcraft.jsch JSch))) (defn add-ssh-agent-connector [^JSch jsch] (let [usf (JNAUSocketFactory.) con (SSHAgentConnector. usf) irepo (RemoteIdentityRepository. con)] (.setIdentityRepository jsch irepo))) (defn ssh-agent-customizer [jsch] (try (if (SSHAgentConnector/isConnectorAvailable) (add-ssh-agent-connector jsch) (log/info "No SSH-Agent connector available. SSH-Keys with passphrases will not be supported")) (catch Exception e (log/warn e "Problems with SSH Agent. Falling back to default behavior"))))
null
https://raw.githubusercontent.com/flosell/lambdacd-git/3677c7afc1324bef6eb1c20f66bd83d99a1c54a9/src/lambdacd_git/ssh_agent_support.clj
clojure
(ns lambdacd-git.ssh-agent-support (:require [clojure.tools.logging :as log]) (:import (org.eclipse.jgit.transport SshSessionFactory JschConfigSessionFactory) (com.jcraft.jsch.agentproxy.connector SSHAgentConnector) (org.eclipse.jgit.util FS) (com.jcraft.jsch.agentproxy RemoteIdentityRepository) (com.jcraft.jsch.agentproxy.usocket JNAUSocketFactory) (com.jcraft.jsch JSch))) (defn add-ssh-agent-connector [^JSch jsch] (let [usf (JNAUSocketFactory.) con (SSHAgentConnector. usf) irepo (RemoteIdentityRepository. con)] (.setIdentityRepository jsch irepo))) (defn ssh-agent-customizer [jsch] (try (if (SSHAgentConnector/isConnectorAvailable) (add-ssh-agent-connector jsch) (log/info "No SSH-Agent connector available. SSH-Keys with passphrases will not be supported")) (catch Exception e (log/warn e "Problems with SSH Agent. Falling back to default behavior"))))
ac9f46e76a5fb0a4b1144b26600f7a2929660f6b1a70a6fddee99e66fe45878c
GaloisInc/tower
Common.hs
{-# LANGUAGE Rank2Types #-} Create build script . -- ( c ) 2015 Galois , Inc. -- module Tower.AADL.Build.Common where import Data.Char import Data.Maybe (maybeToList, fromMaybe) import System.FilePath import Text.PrettyPrint.Leijen hiding ((</>)) import Ivory.Artifact import Ivory.Tower import qualified Ivory.Compile.C.CmdlineFrontend as O import Tower.AADL.Config (AADLConfig(..)) import Tower.AADL.Compile data Required = Req | Opt deriving (Read, Show, Eq) data Assign = Equals | ColonEq | QuestionEq | PlusEq deriving (Read, Show, Eq) data Export = NoExport | Export deriving (Read, Show, Eq) data MkStmt = Include Required FilePath | Var Export String Assign String | Target String [String] [String] | IfNDef String [MkStmt] [MkStmt] | Comment String deriving (Read, Show, Eq) -- Combinators to make building make statements easier ------------------------ include :: FilePath -> MkStmt include fname = Include Req fname includeOpt :: FilePath -> MkStmt includeOpt fname = Include Opt fname infixr 4 ?=, =:, +=, === (?=) :: String -> String -> MkStmt var ?= val = Var NoExport var QuestionEq val (=:) :: String -> String -> MkStmt var =: val = Var NoExport var ColonEq val (+=) :: String -> String -> MkStmt var += val = Var NoExport var PlusEq val (===) :: String -> String -> MkStmt var === val = Var NoExport var Equals val export :: MkStmt -> MkStmt export (Var _ var assign val) = Var Export var assign val export s = s ------------------------------------------------------------------------------- -- Makefile pretty printer ---------------------------------------------------- renderExport :: Export -> Doc renderExport NoExport = empty renderExport Export = text "export " renderAssign :: Assign -> Doc renderAssign Equals = char '=' renderAssign ColonEq = text " := " renderAssign QuestionEq = text " ?= " renderAssign PlusEq = text " += " renderMkStmt :: MkStmt -> Doc renderMkStmt (Include Req fp) = text "include" <+> text fp renderMkStmt (Include Opt fp) = text "-include" <+> text fp renderMkStmt (Var expt var assign val) = renderExport expt <> text var <> renderAssign assign <> text val renderMkStmt (Target name deps actions) = text name <> text ":" <+> hsep (map text deps) <> foldr (\str acc -> linebreak <> char '\t' <> text str <> acc) empty actions <> linebreak renderMkStmt (IfNDef var t e) = text "ifndef" <+> text var <$$> vsep (map renderMkStmt t) <$$> text "else" <$$> vsep (map renderMkStmt e) <$$> text "endif" renderMkStmt (Comment msg) = char '#' <+> text msg renderMkStmts :: [MkStmt] -> String renderMkStmts stmts = show $ foldr (\mkstmt acc -> renderMkStmt mkstmt <> linebreak <> linebreak <> acc) empty (autogenComment : stmts) where autogenComment = Comment "This makefile is autogenerated. DO NOT EDIT." ------------------------------------------------------------------------------- ramsesMakefileName :: String ramsesMakefileName = "ramses.mk" aadlFilesMk :: String aadlFilesMk = "AADL_FILES.mk" componentLibsName :: String componentLibsName = "componentlibs.mk" mkLib :: AADLConfig -> [String] -> String mkLib c aadlFileNames = unlines (map go aadlFileNames) ++ [] where go m = m ++ "_LIBS += " ++ configLibDir c makefileName :: String makefileName = "Makefile" aadlDocNames :: CompiledDocs -> [String] aadlDocNames docs = map docName $ maybeToList (tyDoc docs) ++ thdDocs docs -------------------------------------------------------------------------------- -- Helpers shellVar :: String -> String shellVar = map toUpper -------------------------------------------------------------------------------- -- Support for OS Specific Code generation -------------------------------------------------------------------------------- data OSSpecific a = OSSpecific { osSpecificName :: String , osSpecificConfig :: a , osSpecificArtifacts :: String -> AADLConfig -> [String] -> [Located Artifact] , osSpecificSrcDir :: AADLConfig -> Located Artifact -> Located Artifact , osSpecificTower :: forall e. Tower e () , osSpecificOptsApps :: AADLConfig -> O.Opts -> O.Opts , osSpecificOptsLibs :: AADLConfig -> O.Opts -> O.Opts } defaultOptsUpdate :: AADLConfig -> O.Opts -> O.Opts defaultOptsUpdate c copts = copts { O.outDir = Just (dir </> configSrcsDir c) , O.outHdrDir = Just (dir </> configHdrDir c) , O.outArtDir = Just dir } where dir = fromMaybe "." (O.outDir copts)
null
https://raw.githubusercontent.com/GaloisInc/tower/a43f5e36c6443472ea2dc15bbd49faf8643a6f87/tower-aadl/src/Tower/AADL/Build/Common.hs
haskell
# LANGUAGE Rank2Types # Combinators to make building make statements easier ------------------------ ----------------------------------------------------------------------------- Makefile pretty printer ---------------------------------------------------- ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ Helpers ------------------------------------------------------------------------------ Support for OS Specific Code generation ------------------------------------------------------------------------------
Create build script . ( c ) 2015 Galois , Inc. module Tower.AADL.Build.Common where import Data.Char import Data.Maybe (maybeToList, fromMaybe) import System.FilePath import Text.PrettyPrint.Leijen hiding ((</>)) import Ivory.Artifact import Ivory.Tower import qualified Ivory.Compile.C.CmdlineFrontend as O import Tower.AADL.Config (AADLConfig(..)) import Tower.AADL.Compile data Required = Req | Opt deriving (Read, Show, Eq) data Assign = Equals | ColonEq | QuestionEq | PlusEq deriving (Read, Show, Eq) data Export = NoExport | Export deriving (Read, Show, Eq) data MkStmt = Include Required FilePath | Var Export String Assign String | Target String [String] [String] | IfNDef String [MkStmt] [MkStmt] | Comment String deriving (Read, Show, Eq) include :: FilePath -> MkStmt include fname = Include Req fname includeOpt :: FilePath -> MkStmt includeOpt fname = Include Opt fname infixr 4 ?=, =:, +=, === (?=) :: String -> String -> MkStmt var ?= val = Var NoExport var QuestionEq val (=:) :: String -> String -> MkStmt var =: val = Var NoExport var ColonEq val (+=) :: String -> String -> MkStmt var += val = Var NoExport var PlusEq val (===) :: String -> String -> MkStmt var === val = Var NoExport var Equals val export :: MkStmt -> MkStmt export (Var _ var assign val) = Var Export var assign val export s = s renderExport :: Export -> Doc renderExport NoExport = empty renderExport Export = text "export " renderAssign :: Assign -> Doc renderAssign Equals = char '=' renderAssign ColonEq = text " := " renderAssign QuestionEq = text " ?= " renderAssign PlusEq = text " += " renderMkStmt :: MkStmt -> Doc renderMkStmt (Include Req fp) = text "include" <+> text fp renderMkStmt (Include Opt fp) = text "-include" <+> text fp renderMkStmt (Var expt var assign val) = renderExport expt <> text var <> renderAssign assign <> text val renderMkStmt (Target name deps actions) = text name <> text ":" <+> hsep (map text deps) <> foldr (\str acc -> linebreak <> char '\t' <> text str <> acc) empty actions <> linebreak renderMkStmt (IfNDef var t e) = text "ifndef" <+> text var <$$> vsep (map renderMkStmt t) <$$> text "else" <$$> vsep (map renderMkStmt e) <$$> text "endif" renderMkStmt (Comment msg) = char '#' <+> text msg renderMkStmts :: [MkStmt] -> String renderMkStmts stmts = show $ foldr (\mkstmt acc -> renderMkStmt mkstmt <> linebreak <> linebreak <> acc) empty (autogenComment : stmts) where autogenComment = Comment "This makefile is autogenerated. DO NOT EDIT." ramsesMakefileName :: String ramsesMakefileName = "ramses.mk" aadlFilesMk :: String aadlFilesMk = "AADL_FILES.mk" componentLibsName :: String componentLibsName = "componentlibs.mk" mkLib :: AADLConfig -> [String] -> String mkLib c aadlFileNames = unlines (map go aadlFileNames) ++ [] where go m = m ++ "_LIBS += " ++ configLibDir c makefileName :: String makefileName = "Makefile" aadlDocNames :: CompiledDocs -> [String] aadlDocNames docs = map docName $ maybeToList (tyDoc docs) ++ thdDocs docs shellVar :: String -> String shellVar = map toUpper data OSSpecific a = OSSpecific { osSpecificName :: String , osSpecificConfig :: a , osSpecificArtifacts :: String -> AADLConfig -> [String] -> [Located Artifact] , osSpecificSrcDir :: AADLConfig -> Located Artifact -> Located Artifact , osSpecificTower :: forall e. Tower e () , osSpecificOptsApps :: AADLConfig -> O.Opts -> O.Opts , osSpecificOptsLibs :: AADLConfig -> O.Opts -> O.Opts } defaultOptsUpdate :: AADLConfig -> O.Opts -> O.Opts defaultOptsUpdate c copts = copts { O.outDir = Just (dir </> configSrcsDir c) , O.outHdrDir = Just (dir </> configHdrDir c) , O.outArtDir = Just dir } where dir = fromMaybe "." (O.outDir copts)
69a913b21748ae47d06e80d4ffb136bfb8b365682615af93071ddf834f54ea70
haskell/bytestring
RealFloat.hs
-- | -- Module : Data.ByteString.Builder.RealFloat Copyright : ( c ) 2021 -- License : BSD-style -- Maintainer : -- -- Floating point formatting for @Bytestring.Builder@ -- -- This module primarily exposes `floatDec` and `doubleDec` which do the equivalent of converting through @'Data . ByteString . Builder.string7 ' . ' show'@. -- -- It also exposes `formatFloat` and `formatDouble` with a similar API as ` GHC.Float.formatRealFloat ` . -- NB : The float - to - string conversions exposed by this module match ` show ` 's -- output (specifically with respect to default rounding and length). In -- particular, there are boundary cases where the closest and \'shortest\' -- string representations are not used. Mentions of \'shortest\' in the docs -- below are with this caveat. -- For example , for fidelity , we match ` show ` on the output below . -- -- >>> show (1.0e23 :: Float) " 1.0e23 " -- >>> show (1.0e23 :: Double) -- "9.999999999999999e22" > > > floatDec 1.0e23 " 1.0e23 " > > > doubleDec 1.0e23 -- "9.999999999999999e22" -- -- Simplifying, we can build a shorter, lossless representation by just using @"1.0e23"@ since the floating point values that are 1 ULP away are -- -- >>> showHex (castDoubleToWord64 1.0e23) [] " 44b52d02c7e14af6 " > > > castWord64ToDouble 0x44b52d02c7e14af5 -- 9.999999999999997e22 > > > castWord64ToDouble 0x44b52d02c7e14af6 -- 9.999999999999999e22 > > > castWord64ToDouble 0x44b52d02c7e14af7 -- 1.0000000000000001e23 -- -- In particular, we could use the exact boundary if it is the shortest -- representation and the original floating number is even. To experiment with -- the shorter rounding, refer to ` Data . ByteString . Builder . RealFloat . Internal.acceptBounds ` . This will give us -- > > > floatDec 1.0e23 " 1.0e23 " > > > doubleDec 1.0e23 " 1.0e23 " -- -- For more details, please refer to the < paper > . -- @since 0.11.2.0 module Data.ByteString.Builder.RealFloat ( floatDec , doubleDec -- * Custom formatting , formatFloat , formatDouble , FloatFormat , standard , standardDefaultPrecision , scientific , generic ) where import Data.ByteString.Builder.Internal (Builder) import qualified Data.ByteString.Builder.RealFloat.Internal as R import qualified Data.ByteString.Builder.RealFloat.F2S as RF import qualified Data.ByteString.Builder.RealFloat.D2S as RD import qualified Data.ByteString.Builder.Prim as BP import GHC.Float (roundTo) import GHC.Word (Word64) import GHC.Show (intToDigit) -- | Returns a rendered Float. Matches `show` in displaying in standard or -- scientific notation -- -- @ -- floatDec = 'formatFloat' 'generic' -- @ # INLINABLE floatDec # floatDec :: Float -> Builder floatDec = formatFloat generic -- | Returns a rendered Double. Matches `show` in displaying in standard or -- scientific notation -- -- @ -- doubleDec = 'formatDouble' 'generic' -- @ # INLINABLE doubleDec # doubleDec :: Double -> Builder doubleDec = formatDouble generic -- | Format type for use with `formatFloat` and `formatDouble`. -- @since 0.11.2.0 data FloatFormat = MkFloatFormat FormatMode (Maybe Int) -- | Standard notation with `n` decimal places -- @since 0.11.2.0 standard :: Int -> FloatFormat standard n = MkFloatFormat FStandard (Just n) | Standard notation with the \'default precision\ ' ( decimal places matching ` show ` ) -- @since 0.11.2.0 standardDefaultPrecision :: FloatFormat standardDefaultPrecision = MkFloatFormat FStandard Nothing | Scientific notation with \'default precision\ ' ( decimal places matching ` show ` ) -- @since 0.11.2.0 scientific :: FloatFormat scientific = MkFloatFormat FScientific Nothing -- | Standard or scientific notation depending on the exponent. Matches `show` -- @since 0.11.2.0 generic :: FloatFormat generic = MkFloatFormat FGeneric Nothing -- | ByteString float-to-string format data FormatMode = FScientific -- ^ scientific notation | FStandard -- ^ standard notation with `Maybe Int` digits after the decimal | FGeneric -- ^ dispatches to scientific or standard notation based on the exponent deriving Show TODO : support precision argument for FGeneric and -- | Returns a rendered Float. Returns the \'shortest\' representation in -- scientific notation and takes an optional precision argument in standard -- notation. Also see `floatDec`. -- -- With standard notation, the precision argument is used to truncate (or extend with 0s ) the \'shortest\ ' rendered Float . The \'default precision\ ' does -- no such modifications and will return as many decimal places as the -- representation demands. -- -- e.g -- > > > formatFloat ( standard 1 ) 1.2345e-2 " 0.0 " > > > formatFloat ( standard 10 ) 1.2345e-2 " 0.0123450000 " -- >>> formatFloat standardDefaultPrecision 1.2345e-2 " 0.01234 " > > > formatFloat scientific 12.345 " 1.2345e1 " > > > formatFloat generic 12.345 " 12.345 " -- @since 0.11.2.0 # INLINABLE formatFloat # formatFloat :: FloatFormat -> Float -> Builder formatFloat (MkFloatFormat fmt prec) = \f -> let (RF.FloatingDecimal m e) = RF.f2Intermediate f e' = R.int32ToInt e + R.decimalLength9 m in case fmt of FGeneric -> case specialStr f of Just b -> b Nothing -> if e' >= 0 && e' <= 7 then sign f `mappend` showStandard (R.word32ToWord64 m) e' prec else BP.primBounded (R.toCharsScientific (f < 0) m e) () FScientific -> RF.f2s f FStandard -> case specialStr f of Just b -> b Nothing -> sign f `mappend` showStandard (R.word32ToWord64 m) e' prec TODO : support precision argument for FGeneric and -- | Returns a rendered Double. Returns the \'shortest\' representation in -- scientific notation and takes an optional precision argument in standard -- notation. Also see `doubleDec`. -- -- With standard notation, the precision argument is used to truncate (or extend with 0s ) the \'shortest\ ' rendered Float . The \'default precision\ ' -- does no such modifications and will return as many decimal places as the -- representation demands. -- -- e.g -- > > > formatDouble ( standard 1 ) 1.2345e-2 " 0.0 " > > > formatDouble ( standard 10 ) 1.2345e-2 " 0.0123450000 " -- >>> formatDouble standardDefaultPrecision 1.2345e-2 " 0.01234 " > > > formatDouble scientific 12.345 " 1.2345e1 " > > > formatDouble generic 12.345 " 12.345 " -- @since 0.11.2.0 # INLINABLE formatDouble # formatDouble :: FloatFormat -> Double -> Builder formatDouble (MkFloatFormat fmt prec) = \f -> let (RD.FloatingDecimal m e) = RD.d2Intermediate f e' = R.int32ToInt e + R.decimalLength17 m in case fmt of FGeneric -> case specialStr f of Just b -> b Nothing -> if e' >= 0 && e' <= 7 then sign f `mappend` showStandard m e' prec else BP.primBounded (R.toCharsScientific (f < 0) m e) () FScientific -> RD.d2s f FStandard -> case specialStr f of Just b -> b Nothing -> sign f `mappend` showStandard m e' prec | Char7 encode a ' ' . # INLINE char7 # char7 :: Char -> Builder char7 = BP.primFixed BP.char7 -- | Char7 encode a 'String'. # INLINE string7 # string7 :: String -> Builder string7 = BP.primMapListFixed BP.char7 -- | Encodes a `-` if input is negative sign :: RealFloat a => a -> Builder sign f = if f < 0 then char7 '-' else mempty | Special rendering for , Infinity , and 0 . See RealFloat . Internal . NonNumbersAndZero specialStr :: RealFloat a => a -> Maybe Builder specialStr f | isNaN f = Just $ string7 "NaN" | isInfinite f = Just $ sign f `mappend` string7 "Infinity" | isNegativeZero f = Just $ string7 "-0.0" | f == 0 = Just $ string7 "0.0" | otherwise = Nothing -- | Returns a list of decimal digits in a Word64 digits :: Word64 -> [Int] digits w = go [] w where go ds 0 = ds go ds c = let (q, r) = R.dquotRem10 c in go ((R.word64ToInt r) : ds) q | Show a floating point value in standard notation . Based on GHC.Float.showFloat showStandard :: Word64 -> Int -> Maybe Int -> Builder showStandard m e prec = case prec of Nothing | e <= 0 -> char7 '0' `mappend` char7 '.' `mappend` string7 (replicate (-e) '0') `mappend` mconcat (digitsToBuilder ds) | otherwise -> let f 0 s rs = mk0 (reverse s) `mappend` char7 '.' `mappend` mk0 rs f n s [] = f (n-1) (char7 '0':s) [] f n s (r:rs) = f (n-1) (r:s) rs in f e [] (digitsToBuilder ds) Just p | e >= 0 -> let (ei, is') = roundTo 10 (p' + e) ds (ls, rs) = splitAt (e + ei) (digitsToBuilder is') in mk0 ls `mappend` mkDot rs | otherwise -> let (ei, is') = roundTo 10 p' (replicate (-e) 0 ++ ds) -- ds' should always be non-empty but use redundant pattern -- matching to silence warning ds' = if ei > 0 then is' else 0:is' (ls, rs) = splitAt 1 $ digitsToBuilder ds' in mk0 ls `mappend` mkDot rs where p' = max p 0 where mk0 ls = case ls of [] -> char7 '0'; _ -> mconcat ls mkDot rs = if null rs then mempty else char7 '.' `mappend` mconcat rs ds = digits m digitsToBuilder = fmap (char7 . intToDigit)
null
https://raw.githubusercontent.com/haskell/bytestring/f6065faed6347893beb1b6db88b6788ca15280c1/Data/ByteString/Builder/RealFloat.hs
haskell
| Module : Data.ByteString.Builder.RealFloat License : BSD-style Maintainer : Floating point formatting for @Bytestring.Builder@ This module primarily exposes `floatDec` and `doubleDec` which do the It also exposes `formatFloat` and `formatDouble` with a similar API as output (specifically with respect to default rounding and length). In particular, there are boundary cases where the closest and \'shortest\' string representations are not used. Mentions of \'shortest\' in the docs below are with this caveat. >>> show (1.0e23 :: Float) >>> show (1.0e23 :: Double) "9.999999999999999e22" "9.999999999999999e22" Simplifying, we can build a shorter, lossless representation by just using >>> showHex (castDoubleToWord64 1.0e23) [] 9.999999999999997e22 9.999999999999999e22 1.0000000000000001e23 In particular, we could use the exact boundary if it is the shortest representation and the original floating number is even. To experiment with the shorter rounding, refer to For more details, please refer to the * Custom formatting | Returns a rendered Float. Matches `show` in displaying in standard or scientific notation @ floatDec = 'formatFloat' 'generic' @ | Returns a rendered Double. Matches `show` in displaying in standard or scientific notation @ doubleDec = 'formatDouble' 'generic' @ | Format type for use with `formatFloat` and `formatDouble`. | Standard notation with `n` decimal places | Standard or scientific notation depending on the exponent. Matches `show` | ByteString float-to-string format ^ scientific notation ^ standard notation with `Maybe Int` digits after the decimal ^ dispatches to scientific or standard notation based on the exponent | Returns a rendered Float. Returns the \'shortest\' representation in scientific notation and takes an optional precision argument in standard notation. Also see `floatDec`. With standard notation, the precision argument is used to truncate (or no such modifications and will return as many decimal places as the representation demands. e.g >>> formatFloat standardDefaultPrecision 1.2345e-2 | Returns a rendered Double. Returns the \'shortest\' representation in scientific notation and takes an optional precision argument in standard notation. Also see `doubleDec`. With standard notation, the precision argument is used to truncate (or does no such modifications and will return as many decimal places as the representation demands. e.g >>> formatDouble standardDefaultPrecision 1.2345e-2 | Char7 encode a 'String'. | Encodes a `-` if input is negative | Returns a list of decimal digits in a Word64 ds' should always be non-empty but use redundant pattern matching to silence warning
Copyright : ( c ) 2021 equivalent of converting through @'Data . ByteString . Builder.string7 ' . ' show'@. ` GHC.Float.formatRealFloat ` . NB : The float - to - string conversions exposed by this module match ` show ` 's For example , for fidelity , we match ` show ` on the output below . " 1.0e23 " > > > floatDec 1.0e23 " 1.0e23 " > > > doubleDec 1.0e23 @"1.0e23"@ since the floating point values that are 1 ULP away are " 44b52d02c7e14af6 " > > > castWord64ToDouble 0x44b52d02c7e14af5 > > > castWord64ToDouble 0x44b52d02c7e14af6 > > > castWord64ToDouble 0x44b52d02c7e14af7 ` Data . ByteString . Builder . RealFloat . Internal.acceptBounds ` . This will give us > > > floatDec 1.0e23 " 1.0e23 " > > > doubleDec 1.0e23 " 1.0e23 " < paper > . @since 0.11.2.0 module Data.ByteString.Builder.RealFloat ( floatDec , doubleDec , formatFloat , formatDouble , FloatFormat , standard , standardDefaultPrecision , scientific , generic ) where import Data.ByteString.Builder.Internal (Builder) import qualified Data.ByteString.Builder.RealFloat.Internal as R import qualified Data.ByteString.Builder.RealFloat.F2S as RF import qualified Data.ByteString.Builder.RealFloat.D2S as RD import qualified Data.ByteString.Builder.Prim as BP import GHC.Float (roundTo) import GHC.Word (Word64) import GHC.Show (intToDigit) # INLINABLE floatDec # floatDec :: Float -> Builder floatDec = formatFloat generic # INLINABLE doubleDec # doubleDec :: Double -> Builder doubleDec = formatDouble generic @since 0.11.2.0 data FloatFormat = MkFloatFormat FormatMode (Maybe Int) @since 0.11.2.0 standard :: Int -> FloatFormat standard n = MkFloatFormat FStandard (Just n) | Standard notation with the \'default precision\ ' ( decimal places matching ` show ` ) @since 0.11.2.0 standardDefaultPrecision :: FloatFormat standardDefaultPrecision = MkFloatFormat FStandard Nothing | Scientific notation with \'default precision\ ' ( decimal places matching ` show ` ) @since 0.11.2.0 scientific :: FloatFormat scientific = MkFloatFormat FScientific Nothing @since 0.11.2.0 generic :: FloatFormat generic = MkFloatFormat FGeneric Nothing data FormatMode deriving Show TODO : support precision argument for FGeneric and extend with 0s ) the \'shortest\ ' rendered Float . The \'default precision\ ' does > > > formatFloat ( standard 1 ) 1.2345e-2 " 0.0 " > > > formatFloat ( standard 10 ) 1.2345e-2 " 0.0123450000 " " 0.01234 " > > > formatFloat scientific 12.345 " 1.2345e1 " > > > formatFloat generic 12.345 " 12.345 " @since 0.11.2.0 # INLINABLE formatFloat # formatFloat :: FloatFormat -> Float -> Builder formatFloat (MkFloatFormat fmt prec) = \f -> let (RF.FloatingDecimal m e) = RF.f2Intermediate f e' = R.int32ToInt e + R.decimalLength9 m in case fmt of FGeneric -> case specialStr f of Just b -> b Nothing -> if e' >= 0 && e' <= 7 then sign f `mappend` showStandard (R.word32ToWord64 m) e' prec else BP.primBounded (R.toCharsScientific (f < 0) m e) () FScientific -> RF.f2s f FStandard -> case specialStr f of Just b -> b Nothing -> sign f `mappend` showStandard (R.word32ToWord64 m) e' prec TODO : support precision argument for FGeneric and extend with 0s ) the \'shortest\ ' rendered Float . The \'default precision\ ' > > > formatDouble ( standard 1 ) 1.2345e-2 " 0.0 " > > > formatDouble ( standard 10 ) 1.2345e-2 " 0.0123450000 " " 0.01234 " > > > formatDouble scientific 12.345 " 1.2345e1 " > > > formatDouble generic 12.345 " 12.345 " @since 0.11.2.0 # INLINABLE formatDouble # formatDouble :: FloatFormat -> Double -> Builder formatDouble (MkFloatFormat fmt prec) = \f -> let (RD.FloatingDecimal m e) = RD.d2Intermediate f e' = R.int32ToInt e + R.decimalLength17 m in case fmt of FGeneric -> case specialStr f of Just b -> b Nothing -> if e' >= 0 && e' <= 7 then sign f `mappend` showStandard m e' prec else BP.primBounded (R.toCharsScientific (f < 0) m e) () FScientific -> RD.d2s f FStandard -> case specialStr f of Just b -> b Nothing -> sign f `mappend` showStandard m e' prec | Char7 encode a ' ' . # INLINE char7 # char7 :: Char -> Builder char7 = BP.primFixed BP.char7 # INLINE string7 # string7 :: String -> Builder string7 = BP.primMapListFixed BP.char7 sign :: RealFloat a => a -> Builder sign f = if f < 0 then char7 '-' else mempty | Special rendering for , Infinity , and 0 . See RealFloat . Internal . NonNumbersAndZero specialStr :: RealFloat a => a -> Maybe Builder specialStr f | isNaN f = Just $ string7 "NaN" | isInfinite f = Just $ sign f `mappend` string7 "Infinity" | isNegativeZero f = Just $ string7 "-0.0" | f == 0 = Just $ string7 "0.0" | otherwise = Nothing digits :: Word64 -> [Int] digits w = go [] w where go ds 0 = ds go ds c = let (q, r) = R.dquotRem10 c in go ((R.word64ToInt r) : ds) q | Show a floating point value in standard notation . Based on GHC.Float.showFloat showStandard :: Word64 -> Int -> Maybe Int -> Builder showStandard m e prec = case prec of Nothing | e <= 0 -> char7 '0' `mappend` char7 '.' `mappend` string7 (replicate (-e) '0') `mappend` mconcat (digitsToBuilder ds) | otherwise -> let f 0 s rs = mk0 (reverse s) `mappend` char7 '.' `mappend` mk0 rs f n s [] = f (n-1) (char7 '0':s) [] f n s (r:rs) = f (n-1) (r:s) rs in f e [] (digitsToBuilder ds) Just p | e >= 0 -> let (ei, is') = roundTo 10 (p' + e) ds (ls, rs) = splitAt (e + ei) (digitsToBuilder is') in mk0 ls `mappend` mkDot rs | otherwise -> let (ei, is') = roundTo 10 p' (replicate (-e) 0 ++ ds) ds' = if ei > 0 then is' else 0:is' (ls, rs) = splitAt 1 $ digitsToBuilder ds' in mk0 ls `mappend` mkDot rs where p' = max p 0 where mk0 ls = case ls of [] -> char7 '0'; _ -> mconcat ls mkDot rs = if null rs then mempty else char7 '.' `mappend` mconcat rs ds = digits m digitsToBuilder = fmap (char7 . intToDigit)
033d6ef4ed23f49f2824234ed83a495f50f28116fc1e566e5abc107eefe8bd74
vvvvalvalval/datofu
uid.clj
(ns datofu.uid "Utilities for generating unique identifiers." (:require [datofu.schema.dsl :as sch] [datomic.api :as d] [clojure.string :as str])) (defn schema-tx [] [;; storing the state in a separate partitions so that it won't pollute the Peers. (sch/part :datofu.parts/uid) (sch/attr :datofu.uid.impl.cell.string/id :string :identity) (sch/attr :datofu.uid.impl.cell.string/count :long) (sch/db-fn ::add-sequential-strings "Given an entity identifier `e`, a string-valued attribute `a`, and a string `base`, generates a unique `a` value for `e` from `base`. The typical use case is to generate a string id from a human-readable root. The strategy for avoiding collisions are avoided consists of appending a dash ('-') and number at the end of `base`; if `base` already has such a suffix, it is escaped by doubling the dash. (Of course, uniqueness is only guaranteed if you generate all the values via this function.). An optional namespace string `ns` may be provided (defaults to \"\"). Collisions are only prevented for call to the same namespace. Caveat: there can only be one call to this transaction fn for given base and namespaces in a given transaction, therefore if there are several calls in a transaction you will need to dedupe the bases upstream." {:lang "clojure" :params '[db ns base e+as] :requires '[[clojure.string :as str] [datomic.api :as d]] :code '(let [normalized-base (if-let [match (re-matches #"(.*)\-(\d+)" base)] (let [[_ prefix digits] match] (str prefix "--" digits)) base) escape (fn [s] (cond-> s (str/includes? s "\\") (str/replace #"\\" "\\\\") (str/includes? s ":") (str/replace #":" "\\\\:"))) id (str (if ns (escape ns) "") ":" (escape normalized-base)) n (-> (d/datoms db :eavt [:datofu.uid.impl.cell.string/id id] :datofu.uid.impl.cell.string/count) first :v (or 0))] (into [{:db/id (d/tempid :datofu.parts/uid) :datofu.uid.impl.cell.string/id id :datofu.uid.impl.cell.string/count (+ n (count e+as))}] (map-indexed (fn [i [e attr]] (let [m (+ n i) generated (cond-> normalized-base (> m 0) (str "-" m))] [:db/add e attr generated]))) e+as))}) (sch/attr :datofu.uid.impl.cell.long/ns :string :identity) (sch/attr :datofu.uid.impl.cell.long/count :long) (sch/db-clj-fn ::add-sequential-longs ;; TODO doc "" '[db ns e+as] '(let [ns (or ns "") n (-> (d/datoms db :eavt [:datofu.uid.impl.cell.long/ns ns] :datofu.uid.impl.cell.long/count) first :v (or 0))] (into [{:db/id (d/tempid :datofu.parts/uid) :datofu.uid.impl.cell.long/ns ns :datofu.uid.impl.cell.long/count (+ n (count e+as))}] (map-indexed (fn [i [e attr]] (let [m (+ n i)] [:db/add e attr m]))) e+as) )) ])
null
https://raw.githubusercontent.com/vvvvalvalval/datofu/c596c3beca92309135d88e338f233163c0e9cf5f/src/datofu/uid.clj
clojure
storing the state in a separate partitions so that it won't pollute the Peers. TODO doc
(ns datofu.uid "Utilities for generating unique identifiers." (:require [datofu.schema.dsl :as sch] [datomic.api :as d] [clojure.string :as str])) (defn schema-tx [] (sch/part :datofu.parts/uid) (sch/attr :datofu.uid.impl.cell.string/id :string :identity) (sch/attr :datofu.uid.impl.cell.string/count :long) (sch/db-fn ::add-sequential-strings "Given an entity identifier `e`, a string-valued attribute `a`, and a string `base`, generates a unique `a` value for `e` from `base`. The typical use case is to generate a string id from a human-readable root. if `base` already has such a suffix, it is escaped by doubling the dash. (Of course, uniqueness is only guaranteed if you generate all the values via this function.). An optional namespace string `ns` may be provided (defaults to \"\"). Collisions are only prevented for call to the same namespace. Caveat: there can only be one call to this transaction fn for given base and namespaces in a given transaction, therefore if there are several calls in a transaction you will need to dedupe the bases upstream." {:lang "clojure" :params '[db ns base e+as] :requires '[[clojure.string :as str] [datomic.api :as d]] :code '(let [normalized-base (if-let [match (re-matches #"(.*)\-(\d+)" base)] (let [[_ prefix digits] match] (str prefix "--" digits)) base) escape (fn [s] (cond-> s (str/includes? s "\\") (str/replace #"\\" "\\\\") (str/includes? s ":") (str/replace #":" "\\\\:"))) id (str (if ns (escape ns) "") ":" (escape normalized-base)) n (-> (d/datoms db :eavt [:datofu.uid.impl.cell.string/id id] :datofu.uid.impl.cell.string/count) first :v (or 0))] (into [{:db/id (d/tempid :datofu.parts/uid) :datofu.uid.impl.cell.string/id id :datofu.uid.impl.cell.string/count (+ n (count e+as))}] (map-indexed (fn [i [e attr]] (let [m (+ n i) generated (cond-> normalized-base (> m 0) (str "-" m))] [:db/add e attr generated]))) e+as))}) (sch/attr :datofu.uid.impl.cell.long/ns :string :identity) (sch/attr :datofu.uid.impl.cell.long/count :long) (sch/db-clj-fn ::add-sequential-longs "" '[db ns e+as] '(let [ns (or ns "") n (-> (d/datoms db :eavt [:datofu.uid.impl.cell.long/ns ns] :datofu.uid.impl.cell.long/count) first :v (or 0))] (into [{:db/id (d/tempid :datofu.parts/uid) :datofu.uid.impl.cell.long/ns ns :datofu.uid.impl.cell.long/count (+ n (count e+as))}] (map-indexed (fn [i [e attr]] (let [m (+ n i)] [:db/add e attr m]))) e+as) )) ])
e8814385fbdeb1bab60d7c4f53390e07d0316c88dbaf47d267b6ee7b3d860753
cojna/iota
GoldenSectionSearchSpec.hs
module Algorithm.GoldenSectionSearchSpec where import Algorithm.GoldenSectionSearch import Data.Semigroup import Test.Prelude main :: IO () main = hspec spec eps :: Double eps = 1e-6 spec :: Spec spec = do describe "phi" $ do it "phi = (1 + sqrt 5) / 2" $ do phi `shouldSatisfy` approx eps ((1 + sqrt 5) / 2) describe "resphi" $ do it "resphi = 2 - phi" $ do resphi `shouldSatisfy` approx eps (2 - phi) it "resphi = 1 / (1 + phi)" $ do resphi `shouldSatisfy` approx eps (1 / (1 + phi)) describe "min1/min2" $ do prop "mid1 (mid1 low high) high == mid2 low high" prop_mid1mid1 prop "mid2 low (mid2 low high) == mid1 low high" prop_mid2mid2 describe "goldenSectionSearchMin" $ do it "search (x - 1) ^ 2 + 2 == Min (Arg 2 1)" $ goldenSectionSearchMin (-10) 10 f `shouldSatisfy` approx eps (Arg 2.0 1.0) . getMin describe "goldenSectionSearchMax" $ do it "search - (x - 1) ^ 2 - 2 == Max (Arg (-2) 1)" $ goldenSectionSearchMax (-10) 10 (negate . f) `shouldSatisfy` approx eps (Arg (-2.0) 1.0) . getMax describe "goldenSectionSearchMin2" $ do it "search (x - 1) ^ 2 + (y - 2) ^ 2 + 3 == Min (Arg 3 (1, 2))" $ goldenSectionSearchMin2 (-10) 10 g `shouldSatisfy` approx eps (Arg 3.0 (1.0, 2.0)) . getMin describe "goldenSectionSearchMax2" $ do it "search -(x - 1) ^ 2 - (y - 2) ^ 2 - 3 == Max (Arg (-3) (1, 2))" $ goldenSectionSearchMax2 (-10) 10 (\x y -> - g x y) `shouldSatisfy` approx eps (Arg (-3.0) (1.0, 2.0)) . getMax f :: Double -> Double f x = (x - 1) ^ (2 :: Int) + 2 g :: Double -> Double -> Double g x y = (x - 1) ^ (2 :: Int) + (y - 2) ^ (2 :: Int) + 3 prop_mid1mid1 :: Double -> Double -> Bool prop_mid1mid1 x y = approx eps (mid1 (mid1 low high) high) (mid2 low high) where low = min x y high = max x y prop_mid2mid2 :: Double -> Double -> Bool prop_mid2mid2 x y = approx eps (mid2 low (mid2 low high)) (mid1 low high) where low = min x y high = max x y
null
https://raw.githubusercontent.com/cojna/iota/6d2ad5b71b1b50bca9136d6ed84f80a0b7713d7c/test/Algorithm/GoldenSectionSearchSpec.hs
haskell
module Algorithm.GoldenSectionSearchSpec where import Algorithm.GoldenSectionSearch import Data.Semigroup import Test.Prelude main :: IO () main = hspec spec eps :: Double eps = 1e-6 spec :: Spec spec = do describe "phi" $ do it "phi = (1 + sqrt 5) / 2" $ do phi `shouldSatisfy` approx eps ((1 + sqrt 5) / 2) describe "resphi" $ do it "resphi = 2 - phi" $ do resphi `shouldSatisfy` approx eps (2 - phi) it "resphi = 1 / (1 + phi)" $ do resphi `shouldSatisfy` approx eps (1 / (1 + phi)) describe "min1/min2" $ do prop "mid1 (mid1 low high) high == mid2 low high" prop_mid1mid1 prop "mid2 low (mid2 low high) == mid1 low high" prop_mid2mid2 describe "goldenSectionSearchMin" $ do it "search (x - 1) ^ 2 + 2 == Min (Arg 2 1)" $ goldenSectionSearchMin (-10) 10 f `shouldSatisfy` approx eps (Arg 2.0 1.0) . getMin describe "goldenSectionSearchMax" $ do it "search - (x - 1) ^ 2 - 2 == Max (Arg (-2) 1)" $ goldenSectionSearchMax (-10) 10 (negate . f) `shouldSatisfy` approx eps (Arg (-2.0) 1.0) . getMax describe "goldenSectionSearchMin2" $ do it "search (x - 1) ^ 2 + (y - 2) ^ 2 + 3 == Min (Arg 3 (1, 2))" $ goldenSectionSearchMin2 (-10) 10 g `shouldSatisfy` approx eps (Arg 3.0 (1.0, 2.0)) . getMin describe "goldenSectionSearchMax2" $ do it "search -(x - 1) ^ 2 - (y - 2) ^ 2 - 3 == Max (Arg (-3) (1, 2))" $ goldenSectionSearchMax2 (-10) 10 (\x y -> - g x y) `shouldSatisfy` approx eps (Arg (-3.0) (1.0, 2.0)) . getMax f :: Double -> Double f x = (x - 1) ^ (2 :: Int) + 2 g :: Double -> Double -> Double g x y = (x - 1) ^ (2 :: Int) + (y - 2) ^ (2 :: Int) + 3 prop_mid1mid1 :: Double -> Double -> Bool prop_mid1mid1 x y = approx eps (mid1 (mid1 low high) high) (mid2 low high) where low = min x y high = max x y prop_mid2mid2 :: Double -> Double -> Bool prop_mid2mid2 x y = approx eps (mid2 low (mid2 low high)) (mid1 low high) where low = min x y high = max x y
b9fde582d8ec70c969504a230717c49f6fa23165b47ea98fdfde936b0c54931b
GrammaTech/sel
defmethod-2.lisp
(defmethod m :before (arg) (+ 1 2) (- 2 3) (/ 3 4) (* 4 2))
null
https://raw.githubusercontent.com/GrammaTech/sel/a59174c02a454e8d588614e221cf281260cf12f8/test/etc/lisp-scopes/defmethod-2.lisp
lisp
(defmethod m :before (arg) (+ 1 2) (- 2 3) (/ 3 4) (* 4 2))
a1ea4cd004fa0da96bcd61f66ec8b05c4b839923a33e0f6cbaf7651efc67194b
let-def/ocaml-recovery-parser
pprintast.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro (* Fabrice Le Fessant, INRIA Saclay *) , University of Pennsylvania (* *) Copyright 2007 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) Original Code from Ber - metaocaml , modified for 3.12.0 and fixed (* Printing code expressions *) Authors : , Extensive Rewrite : : University of Pennsylvania TODO more fine - grained precedence pretty - printing [@@@ocaml.warning "-9"];; open Asttypes open Format open Location open Longident open Parsetree open Ast_helper let prefix_symbols = [ '!'; '?'; '~' ] ;; let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%'; '#' ] (* type fixity = Infix| Prefix *) let special_infix_strings = ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ] let letop s = String.length s > 3 && s.[0] = 'l' && s.[1] = 'e' && s.[2] = 't' && List.mem s.[3] infix_symbols let andop s = String.length s > 3 && s.[0] = 'a' && s.[1] = 'n' && s.[2] = 'd' && List.mem s.[3] infix_symbols determines if the string is an infix string . checks backwards , first allowing a renaming postfix ( " _ 102 " ) which may have resulted from - > Texp - > translation , then checking if all the characters in the beginning of the string are valid infix characters . checks backwards, first allowing a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp translation, then checking if all the characters in the beginning of the string are valid infix characters. *) let fixity_of_string = function | "" -> `Normal | s when List.mem s special_infix_strings -> `Infix s | s when List.mem s.[0] infix_symbols -> `Infix s | s when List.mem s.[0] prefix_symbols -> `Prefix s | s when s.[0] = '.' -> `Mixfix s | s when letop s -> `Letop s | s when andop s -> `Andop s | _ -> `Normal let view_fixity_of_exp = function | {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} -> fixity_of_string l | _ -> `Normal let is_infix = function `Infix _ -> true | _ -> false let is_mixfix = function `Mixfix _ -> true | _ -> false let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false let first_is c str = str <> "" && str.[0] = c let last_is c str = str <> "" && str.[String.length str - 1] = c let first_is_in cs str = str <> "" && List.mem str.[0] cs (* which identifiers are in fact operators needing parentheses *) let needs_parens txt = let fix = fixity_of_string txt in is_infix fix || is_mixfix fix || is_kwdop fix || first_is_in prefix_symbols txt (* some infixes need spaces around parens to avoid clashes with comment syntax *) let needs_spaces txt = first_is '*' txt || last_is '*' txt (* add parentheses to binders when they are in fact infix or prefix operators *) let protect_ident ppf txt = let format : (_, _, _) format = if not (needs_parens txt) then "%s" else if needs_spaces txt then "(@;%s@;)" else "(%s)" in fprintf ppf format txt let protect_longident ppf print_longident longprefix txt = let format : (_, _, _) format = if not (needs_parens txt) then "%a.%s" else if needs_spaces txt then "%a.(@;%s@;)" else "%a.(%s)" in fprintf ppf format print_longident longprefix txt type space_formatter = (unit, Format.formatter, unit) format let override = function | Override -> "!" | Fresh -> "" (* variance encoding: need to sync up with the [parser.mly] *) let type_variance = function | Invariant -> "" | Covariant -> "+" | Contravariant -> "-" type construct = [ `cons of expression list | `list of expression list | `nil | `normal | `simple of Longident.t | `tuple ] let view_expr x = match x.pexp_desc with | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil | Pexp_construct ( {txt= Lident"::";_},Some _) -> let rec loop exp acc = match exp with | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_); pexp_attributes = []} -> (List.rev acc,true) | {pexp_desc= Pexp_construct ({txt=Lident "::";_}, Some ({pexp_desc= Pexp_tuple([e1;e2]); pexp_attributes = []})); pexp_attributes = []} -> loop e2 (e1::acc) | e -> (List.rev (e::acc),false) in let (ls,b) = loop x [] in if b then `list ls else `cons ls | Pexp_construct (x,None) -> `simple (x.txt) | _ -> `normal let is_simple_construct :construct -> bool = function | `nil | `tuple | `list _ | `simple _ -> true | `cons _ | `normal -> false let pp = fprintf type ctxt = { pipe : bool; semi : bool; ifthenelse : bool; } let reset_ctxt = { pipe=false; semi=false; ifthenelse=false } let under_pipe ctxt = { ctxt with pipe=true } let under_semi ctxt = { ctxt with semi=true } let under_ifthenelse ctxt = { ctxt with ifthenelse=true } let reset_semi = with semi = false } let reset_ifthenelse = with ifthenelse = false } let = with pipe = false } let reset_semi ctxt = { ctxt with semi=false } let reset_ifthenelse ctxt = { ctxt with ifthenelse=false } let reset_pipe ctxt = { ctxt with pipe=false } *) let list : 'a . ?sep:space_formatter -> ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit = fun ?sep ?first ?last fu f xs -> let first = match first with Some x -> x |None -> ("": _ format6) and last = match last with Some x -> x |None -> ("": _ format6) and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in let aux f = function | [] -> () | [x] -> fu f x | xs -> let rec loop f = function | [x] -> fu f x | x::xs -> fu f x; pp f sep; loop f xs; | _ -> assert false in begin pp f first; loop f xs; pp f last; end in aux f xs let option : 'a. ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit = fun ?first ?last fu f a -> let first = match first with Some x -> x | None -> ("": _ format6) and last = match last with Some x -> x | None -> ("": _ format6) in match a with | None -> () | Some x -> pp f first; fu f x; pp f last let paren: 'a . ?first:space_formatter -> ?last:space_formatter -> bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit = fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x -> if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")") else fu f x let rec longident f = function | Lident s -> protect_ident f s | Ldot(y,s) -> protect_longident f longident y s | Lapply (y,s) -> pp f "%a(%a)" longident y longident s let longident_loc f x = pp f "%a" longident x.txt let constant f = function | Pconst_char i -> pp f "%C" i | Pconst_string (i, None) -> pp f "%S" i | Pconst_string (i, Some delim) -> pp f "{%s|%s|%s}" delim i delim | Pconst_integer (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_integer (i, Some m) -> paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m) | Pconst_float (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_float (i, Some m) -> paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m) (* trailing space*) let mutable_flag f = function | Immutable -> () | Mutable -> pp f "mutable@;" let virtual_flag f = function | Concrete -> () | Virtual -> pp f "virtual@;" (* trailing space added *) let rec_flag f rf = match rf with | Nonrecursive -> () | Recursive -> pp f "rec " let nonrec_flag f rf = match rf with | Nonrecursive -> pp f "nonrec " | Recursive -> () let direction_flag f = function | Upto -> pp f "to@ " | Downto -> pp f "downto@ " let private_flag f = function | Public -> () | Private -> pp f "private@ " let iter_loc f ctxt {txt; loc = _} = f ctxt txt let constant_string f s = pp f "%S" s let tyvar ppf s = if String.length s >= 2 && s.[1] = '\'' then (* without the space, this would be parsed as a character literal *) Format.fprintf ppf "' %s" s else Format.fprintf ppf "'%s" s let tyvar_loc f str = tyvar f str.txt let string_quot f x = pp f "`%s" x (* c ['a,'b] *) let rec class_params_def ctxt f = function | [] -> () | l -> pp f "[%a] " (* space *) (list (type_param ctxt) ~sep:",") l and type_with_label ctxt f (label, c) = match label with | Nolabel -> core_type1 ctxt f c (* otherwise parenthesize *) | Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c | Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c and core_type ctxt f x = if x.ptyp_attributes <> [] then begin pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]} (attributes ctxt) x.ptyp_attributes end else match x.ptyp_desc with | Ptyp_arrow (l, ct1, ct2) -> FIXME remove parens later (type_with_label ctxt) (l,ct1) (core_type ctxt) ct2 | Ptyp_alias (ct, s) -> pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct tyvar s | Ptyp_poly ([], ct) -> core_type ctxt f ct | Ptyp_poly (sl, ct) -> pp f "@[<2>%a%a@]" (fun f l -> pp f "%a" (fun f l -> match l with | [] -> () | _ -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") l) l) sl (core_type ctxt) ct | _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x and core_type1 ctxt f x = if x.ptyp_attributes <> [] then core_type ctxt f x else match x.ptyp_desc with | Ptyp_any -> pp f "_"; | Ptyp_var s -> tyvar f s; | Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l | Ptyp_constr (li, l) -> pp f (* "%a%a@;" *) "%a%a" (fun f l -> match l with |[] -> () |[x]-> pp f "%a@;" (core_type1 ctxt) x | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l) l longident_loc li | Ptyp_variant (l, closed, low) -> let type_variant_helper f x = match x.prf_desc with | Rtag (l, _, ctl) -> pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l (fun f l -> match l with |[] -> () | _ -> pp f "@;of@;%a" (list (core_type ctxt) ~sep:"&") ctl) ctl (attributes ctxt) x.prf_attributes | Rinherit ct -> core_type ctxt f ct in pp f "@[<2>[%a%a]@]" (fun f l -> match l, closed with | [], Closed -> () | [], Open -> pp f ">" (* Cf #7200: print [>] correctly *) | _ -> pp f "%s@;%a" (match (closed,low) with | (Closed,None) -> "" | (Closed,Some _) -> "<" (* FIXME desugar the syntax sugar*) | (Open,_) -> ">") (list type_variant_helper ~sep:"@;<1 -2>| ") l) l (fun f low -> match low with |Some [] |None -> () |Some xs -> pp f ">@ %a" (list string_quot) xs) low | Ptyp_object (l, o) -> let core_field_type f x = match x.pof_desc with | Otag (l, ct) -> Cf # 7200 pp f "@[<hov2>%s: %a@ %a@ @]" l.txt (core_type ctxt) ct (attributes ctxt) x.pof_attributes | Oinherit ct -> pp f "@[<hov2>%a@ @]" (core_type ctxt) ct in let field_var f = function | Asttypes.Closed -> () | Asttypes.Open -> match l with | [] -> pp f ".." | _ -> pp f " ;.." in pp f "@[<hov2><@ %a%a@ > @]" (list core_field_type ~sep:";") l Cf # 7200 FIXME pp f "@[<hov2>%a#%a@]" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l longident_loc li | Ptyp_package (lid, cstrs) -> let aux f (s, ct) = pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in (match cstrs with |[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid |_ -> pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid (list aux ~sep:"@ and@ ") cstrs) | Ptyp_extension e -> extension ctxt f e | _ -> paren true (core_type ctxt) f x (********************pattern********************) be cautious when use [ pattern ] , [ ] is preferred and pattern ctxt f x = only consider ( ( A|B)|C ) | {ppat_desc= Ppat_or (p1,p2); ppat_attributes = []} -> list_of_pattern (p2::acc) p1 | x -> x::acc in if x.ppat_attributes <> [] then begin pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]} (attributes ctxt) x.ppat_attributes end else match x.ppat_desc with | Ppat_alias (p, s) -> pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p protect_ident s.txt (* RA*) | Ppat_or _ -> (* *) pp f "@[<hov0>%a@]" (list ~sep:"@,|" (pattern ctxt)) (list_of_pattern [] x) | _ -> pattern1 ctxt f x and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit = let rec pattern_list_helper f = function | {ppat_desc = Ppat_construct ({ txt = Lident("::") ;_}, Some ({ppat_desc = Ppat_tuple([pat1; pat2]);_})); ppat_attributes = []} -> pp f "%a::%a" (simple_pattern ctxt) pat1 pattern_list_helper pat2 (*RA*) | p -> pattern1 ctxt f p in if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> simple_pattern ctxt f x | Ppat_construct (({txt;_} as li), po) -> FIXME The third field always false if txt = Lident "::" then pp f "%a" pattern_list_helper x else (match po with | Some x -> pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x | None -> pp f "%a" longident_loc li) | _ -> simple_pattern ctxt f x and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit = if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), _) -> pp f "%s" x | Ppat_any -> pp f "_"; | Ppat_var ({txt = txt;_}) -> protect_ident f txt | Ppat_array l -> pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l | Ppat_unpack { txt = None } -> pp f "(module@ _)@ " | Ppat_unpack { txt = Some s } -> pp f "(module@ %s)@ " s | Ppat_type li -> pp f "#%a" longident_loc li | Ppat_record (l, closed) -> let longident_x_pattern f (li, p) = match (li,p) with | ({txt=Lident s;_ }, {ppat_desc=Ppat_var {txt;_}; ppat_attributes=[]; _}) when s = txt -> pp f "@[<2>%a@]" longident_loc li | _ -> pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p in begin match closed with | Closed -> pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l | _ -> pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l end | Ppat_tuple l -> | Ppat_constant (c) -> pp f "%a" constant c | Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2 | Ppat_variant (l,None) -> pp f "`%s" l | Ppat_constraint (p, ct) -> pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct | Ppat_lazy p -> pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p | Ppat_exception p -> pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p | Ppat_extension e -> extension ctxt f e | Ppat_open (lid, p) -> let with_paren = match p.ppat_desc with | Ppat_array _ | Ppat_record _ | Ppat_construct (({txt=Lident ("()"|"[]");_}), _) -> false | _ -> true in pp f "@[<2>%a.%a @]" longident_loc lid (paren with_paren @@ pattern1 ctxt) p | _ -> paren true (pattern ctxt) f x and label_exp ctxt f (l,opt,p) = match l with | Nolabel -> (* single case pattern parens needed here *) pp f "%a@ " (simple_pattern ctxt) p | Optional rest -> begin match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = rest -> (match opt with | Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o | None -> pp f "?%s@ " rest) | _ -> (match opt with | Some o -> pp f "?%s:(%a=@;%a)@;" rest (pattern1 ctxt) p (expression ctxt) o | None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p) end | Labelled l -> match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = l -> pp f "~%s@;" l | _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p and sugar_expr ctxt f e = if e.pexp_attributes <> [] then false else match e.pexp_desc with | Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _}; pexp_attributes=[]; _}, args) when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin let print_indexop a path_prefix assign left sep right print_index indices rem_args = let print_path ppf = function | None -> () | Some m -> pp ppf ".%a" longident m in match assign, rem_args with | false, [] -> pp f "@[%a%a%s%a%s@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right; true | true, [v] -> pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right (simple_expr ctxt) v; true | _ -> false in match id, List.map snd args with | Lident "!", [e] -> pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true | Ldot (path, ("get"|"set" as func)), a :: other_args -> begin let assign = func = "set" in let print = print_indexop a None assign in match path, other_args with | Lident "Array", i :: rest -> print ".(" "" ")" (expression ctxt) [i] rest | Lident "String", i :: rest -> print ".[" "" "]" (expression ctxt) [i] rest | Ldot (Lident "Bigarray", "Array1"), i1 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1] rest | Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest | Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest | Ldot (Lident "Bigarray", "Genarray"), {pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest -> print ".{" "," "}" (simple_expr ctxt) indexes rest | _ -> false end | (Lident s | Ldot(_,s)) , a :: i :: rest when first_is '.' s -> (* extract operator: assignment operators end with [right_bracket ^ "<-"], access operators end with [right_bracket] directly *) let multi_indices = String.contains s ';' in let i = match i.pexp_desc with | Pexp_array l when multi_indices -> l | _ -> [ i ] in let assign = last_is '-' s in let kind = (* extract the right end bracket *) let n = String.length s in if assign then s.[n - 3] else s.[n - 1] in let left, right = match kind with | ')' -> '(', ")" | ']' -> '[', "]" | '}' -> '{', "}" | _ -> assert false in let path_prefix = match id with | Ldot(m,_) -> Some m | _ -> None in let left = String.sub s 0 (1+String.index s left) in print_indexop a path_prefix assign left ";" right (if multi_indices then expression ctxt else simple_expr ctxt) i rest | _ -> false end | _ -> false and expression ctxt f x = if x.pexp_attributes <> [] then pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes else match x.pexp_desc with | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _ | Pexp_newtype _ when ctxt.pipe || ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse -> paren true (expression reset_ctxt) f x | Pexp_let _ | Pexp_letmodule _ | Pexp_open _ | Pexp_letexception _ | Pexp_letop _ when ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_fun (l, e0, p, e) -> pp f "@[<2>fun@;%a->@;%a@]" (label_exp ctxt) (l, e0, p) (expression ctxt) e | Pexp_newtype (lid, e) -> pp f "@[<2>fun@;(type@;%s)@;->@;%a@]" lid.txt (expression ctxt) e | Pexp_function l -> pp f "@[<hv>function%a@]" (case_list ctxt) l | Pexp_match (e, l) -> pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]" (expression reset_ctxt) e (case_list ctxt) l | Pexp_try (e, l) -> pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]" (* "try@;@[<2>%a@]@\nwith@\n%a"*) (expression reset_ctxt) e (case_list ctxt) l | Pexp_let (rf, l, e) -> (* pp f "@[<2>let %a%a in@;<1 -2>%a@]" (*no indentation here, a new line*) *) rec_flag rf pp f "@[<2>%a in@;<1 -2>%a@]" (bindings reset_ctxt) (rf,l) (expression ctxt) e | Pexp_apply (e, l) -> begin if not (sugar_expr ctxt f x) then match view_fixity_of_exp e with | `Infix s -> begin match l with | [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] -> FIXME associativity label_x_expression_param pp f "@[<2>%a@;%s@;%a@]" (label_x_expression_param reset_ctxt) arg1 s (label_x_expression_param ctxt) arg2 | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | `Prefix s -> let s = if List.mem s ["~+";"~-";"~+.";"~-."] && (match l with (* See #7200: avoid turning (~- 1) into (- 1) which is parsed as an int literal *) |[(_,{pexp_desc=Pexp_constant _})] -> false | _ -> true) then String.sub s 1 (String.length s -1) else s in begin match l with | [(Nolabel, x)] -> pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | _ -> pp f "@[<hov2>%a@]" begin fun f (e,l) -> pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l (* reset here only because [function,match,try,sequence] are lower priority *) end (e,l) end | Pexp_construct (li, Some eo) when not (is_simple_construct (view_expr x))-> (* Not efficient FIXME*) (match view_expr x with | `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;" | `normal -> pp f "@[<2>%a@;%a@]" longident_loc li (simple_expr ctxt) eo | _ -> assert false) | Pexp_setfield (e1, li, e2) -> pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 | Pexp_ifthenelse (e1, e2, eo) -> (* @;@[<2>else@ %a@]@] *) let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2 (fun f eo -> match eo with | Some x -> pp f "@;@[<2>else@;%a@]" (expression (under_semi ctxt)) x | None -> () (* pp f "()" *)) eo | Pexp_sequence _ -> let rec sequence_helper acc = function | {pexp_desc=Pexp_sequence(e1,e2); pexp_attributes = []} -> sequence_helper (e1::acc) e2 | v -> List.rev (v::acc) in let lst = sequence_helper [] x in pp f "@[<hv>%a@]" (list (expression (under_semi ctxt)) ~sep:";@;") lst | Pexp_new (li) -> pp f "@[<hov2>new@ %a@]" longident_loc li; | Pexp_setinstvar (s, e) -> pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e FIXME let string_x_expression f (s, e) = pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in pp f "@[<hov2>{<%a>}@]" (list string_x_expression ~sep:";" ) l; | Pexp_letmodule (s, me, e) -> pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]" (Option.value s.txt ~default:"_") (module_expr reset_ctxt) me (expression ctxt) e | Pexp_letexception (cd, e) -> pp f "@[<hov2>let@ exception@ %a@ in@ %a@]" (extension_constructor ctxt) cd (expression ctxt) e | Pexp_assert e -> pp f "@[<hov2>assert@ %a@]" (simple_expr ctxt) e | Pexp_lazy (e) -> pp f "@[<hov2>lazy@ %a@]" (simple_expr ctxt) e (* Pexp_poly: impossible but we should print it anyway, rather than assert false *) | Pexp_poly (e, None) -> pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, Some ct) -> pp f "@[<hov2>(!poly!@ %a@ : %a)@]" (simple_expr ctxt) e (core_type ctxt) ct | Pexp_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) (module_expr ctxt) o.popen_expr (expression ctxt) e | Pexp_variant (l,Some eo) -> pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo | Pexp_letop {let_; ands; body} -> pp f "@[<2>@[<v>%a@,%a@] in@;<1 -2>%a@]" (binding_op ctxt) let_ (list ~sep:"@," (binding_op ctxt)) ands (expression ctxt) body | Pexp_extension e -> extension ctxt f e | Pexp_unreachable -> pp f "." | _ -> expression1 ctxt f x and expression1 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_object cs -> pp f "%a" (class_structure ctxt) cs | _ -> expression2 ctxt f x (* used in [Pexp_apply] *) and expression2 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_field (e, li) -> pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt | _ -> simple_expr ctxt f x and simple_expr ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_construct _ when is_simple_construct (view_expr x) -> (match view_expr x with | `nil -> pp f "[]" | `tuple -> pp f "()" | `list xs -> pp f "@[<hv0>[%a]@]" (list (expression (under_semi ctxt)) ~sep:";@;") xs | `simple x -> longident f x | _ -> assert false) | Pexp_ident li -> longident_loc f li (* (match view_fixity_of_exp x with *) (* |`Normal -> longident_loc f li *) (* | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) *) | Pexp_constant c -> constant f c; | Pexp_pack me -> pp f "(module@;%a)" (module_expr ctxt) me | Pexp_tuple l -> pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l | Pexp_constraint (e, ct) -> pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_coerce (e, cto1, ct) -> pp f "(%a%a :> %a)" (expression ctxt) e (option (core_type ctxt) ~first:" : " ~last:" ") cto1 (* no sep hint*) (core_type ctxt) ct | Pexp_variant (l, None) -> pp f "`%s" l | Pexp_record (l, eo) -> let longident_x_expression f ( li, e) = match e with | {pexp_desc=Pexp_ident {txt;_}; pexp_attributes=[]; _} when li.txt = txt -> pp f "@[<hov2>%a@]" longident_loc li | _ -> pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e in pp f "@[<hv0>@[<hv2>{@;%a%a@]@;}@]"(* "@[<hov2>{%a%a}@]" *) (option ~last:" with@;" (simple_expr ctxt)) eo (list longident_x_expression ~sep:";@;") l | Pexp_array (l) -> pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l | Pexp_while (e1, e2) -> let fmt : (_,_,_) format = "@[<2>while@;%a@;do@;%a@;done@]" in pp f fmt (expression ctxt) e1 (expression ctxt) e2 | Pexp_for (s, e1, e2, df, e3) -> let fmt:(_,_,_)format = "@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in let expression = expression ctxt in pp f fmt (pattern ctxt) s expression e1 direction_flag df expression e2 expression e3 | _ -> paren true (expression ctxt) f x and attributes ctxt f l = List.iter (attribute ctxt f) l and item_attributes ctxt f l = List.iter (item_attribute ctxt f) l and attribute ctxt f a = pp f "@[<2>[@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and item_attribute ctxt f a = pp f "@[<2>[@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and floating_attribute ctxt f a = pp f "@[<2>[@@@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and value_description ctxt f x = (* note: value_description has an attribute field, but they're already printed by the callers this method *) pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type (fun f x -> if x.pval_prim <> [] then pp f "@ =@ %a" (list constant_string) x.pval_prim ) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e and item_extension ctxt f (s, e) = pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e and exception_declaration ctxt f x = pp f "@[<hov2>exception@ %a@]%a" (extension_constructor ctxt) x.ptyexn_constructor (item_attributes ctxt) x.ptyexn_attributes and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} = let class_type_field f x = match x.pctf_desc with | Pctf_inherit (ct) -> pp f "@[<2>inherit@ %a@]%a" (class_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_val (s, mf, vf, ct) -> pp f "@[<2>val @ %a%a%s@ :@ %a@]%a" mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_method (s, pf, vf, ct) -> pp f "@[<2>method %a %a%s :@;%a@]%a" private_flag pf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_constraint (ct1, ct2) -> pp f "@[<2>constraint@ %a@ =@ %a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pctf_attributes | Pctf_attribute a -> floating_attribute ctxt f a | Pctf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pctf_attributes in pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]" (fun f -> function {ptyp_desc=Ptyp_any; ptyp_attributes=[]; _} -> () | ct -> pp f " (%a)" (core_type ctxt) ct) ct (list class_type_field ~sep:"@;") l (* call [class_signature] called by [class_signature] *) and class_type ctxt f x = match x.pcty_desc with | Pcty_signature cs -> class_signature ctxt f cs; attributes ctxt f x.pcty_attributes | Pcty_constr (li, l) -> pp f "%a%a%a" (fun f l -> match l with | [] -> () | _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l longident_loc li (attributes ctxt) x.pcty_attributes | Pcty_arrow (l, co, cl) -> FIXME remove parens later (type_with_label ctxt) (l,co) (class_type ctxt) cl | Pcty_extension e -> extension ctxt f e; attributes ctxt f x.pcty_attributes | Pcty_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_type ctxt) e (* [class type a = object end] *) and class_type_declaration_list ctxt f l = let class_type_declaration kwd f x = let { pci_params=ls; pci_name={ txt; _ }; _ } = x in pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in match l with | [] -> () | [x] -> class_type_declaration "class type" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_type_declaration "class type") x (list ~sep:"@," (class_type_declaration "and")) xs and class_field ctxt f x = match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf) (class_expr ctxt) ce (fun f so -> match so with | None -> (); | Some (s) -> pp f "@ as %s" s.txt ) so (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_concrete (ovf, e)) -> pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf) mutable_flag mf s.txt (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_virtual ct) -> pp f "@[<2>method virtual %a %s :@;%a@]%a" private_flag pf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_virtual ct) -> pp f "@[<2>val virtual %a%s :@ %a@]%a" mutable_flag mf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_concrete (ovf, e)) -> let bind e = binding ctxt f {pvb_pat= {ppat_desc=Ppat_var s; ppat_loc=Location.none; ppat_loc_stack=[]; ppat_attributes=[]}; pvb_expr=e; pvb_attributes=[]; pvb_loc=Location.none; } in pp f "@[<2>method%s %a%a@]%a" (override ovf) private_flag pf (fun f -> function | {pexp_desc=Pexp_poly (e, Some ct); pexp_attributes=[]; _} -> pp f "%s :@;%a=@;%a" s.txt (core_type ctxt) ct (expression ctxt) e | {pexp_desc=Pexp_poly (e, None); pexp_attributes=[]; _} -> bind e | _ -> bind e) e (item_attributes ctxt) x.pcf_attributes | Pcf_constraint (ct1, ct2) -> pp f "@[<2>constraint %a =@;%a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pcf_attributes | Pcf_initializer (e) -> pp f "@[<2>initializer@ %a@]%a" (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_attribute a -> floating_attribute ctxt f a | Pcf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pcf_attributes and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } = pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]" (fun f p -> match p.ppat_desc with | Ppat_any -> () | Ppat_constraint _ -> pp f " %a" (pattern ctxt) p | _ -> pp f " (%a)" (pattern ctxt) p) p (list (class_field ctxt)) l and class_expr ctxt f x = if x.pcl_attributes <> [] then begin pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]} (attributes ctxt) x.pcl_attributes end else match x.pcl_desc with | Pcl_structure (cs) -> class_structure ctxt f cs | Pcl_fun (l, eo, p, e) -> pp f "fun@ %a@ ->@ %a" (label_exp ctxt) (l,eo,p) (class_expr ctxt) e | Pcl_let (rf, l, ce) -> pp f "%a@ in@ %a" (bindings ctxt) (rf,l) (class_expr ctxt) ce | Pcl_apply (ce, l) -> Cf : # 7200 (class_expr ctxt) ce (list (label_x_expression_param ctxt)) l | Pcl_constr (li, l) -> pp f "%a%a" (fun f l-> if l <>[] then pp f "[%a]@ " (list (core_type ctxt) ~sep:",") l) l longident_loc li | Pcl_constraint (ce, ct) -> pp f "(%a@ :@ %a)" (class_expr ctxt) ce (class_type ctxt) ct | Pcl_extension e -> extension ctxt f e | Pcl_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_expr ctxt) e and module_type ctxt f x = if x.pmty_attributes <> [] then begin pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]} (attributes ctxt) x.pmty_attributes end else match x.pmty_desc with | Pmty_functor (Unit, mt2) -> pp f "@[<hov2>functor () ->@ %a@]" (module_type ctxt) mt2 | Pmty_functor (Named (s, mt1), mt2) -> begin match s.txt with | None -> pp f "@[<hov2>%a@ ->@ %a@]" (module_type1 ctxt) mt1 (module_type ctxt) mt2 | Some name -> pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" name (module_type ctxt) mt1 (module_type ctxt) mt2 end | Pmty_with (mt, []) -> module_type ctxt f mt | Pmty_with (mt, l) -> let with_constraint f = function | Pwith_type (li, ({ptype_params= ls ;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a =@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_module (li, li2) -> pp f "module %a =@ %a" longident_loc li longident_loc li2; | Pwith_typesubst (li, ({ptype_params=ls;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a :=@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_modsubst (li, li2) -> pp f "module %a :=@ %a" longident_loc li longident_loc li2 in pp f "@[<hov2>%a@ with@ %a@]" (module_type1 ctxt) mt (list with_constraint ~sep:"@ and@ ") l | _ -> module_type1 ctxt f x and module_type1 ctxt f x = if x.pmty_attributes <> [] then module_type ctxt f x else match x.pmty_desc with | Pmty_ident li -> pp f "%a" longident_loc li; | Pmty_alias li -> pp f "(module %a)" longident_loc li; | Pmty_signature (s) -> pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *) (list (signature_item ctxt)) s (* FIXME wrong indentation*) | Pmty_typeof me -> pp f "@[<hov2>module@ type@ of@ %a@]" (module_expr ctxt) me | Pmty_extension e -> extension ctxt f e | _ -> paren true (module_type ctxt) f x and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x and signature_item ctxt f x : unit = match x.psig_desc with | Psig_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Psig_typesubst l -> type_def_list ctxt f (Nonrecursive, false, l) | Psig_value vd -> let intro = if vd.pval_prim = [] then "val" else "external" in pp f "@[<2>%s@ %a@ :@ %a@]%a" intro protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Psig_typext te -> type_extension ctxt f te | Psig_exception ed -> exception_declaration ctxt f ed | Psig_class l -> let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) = pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_description "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_description "class") x (list ~sep:"@," (class_description "and")) xs end | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias; pmty_attributes=[]; _};_} as pmd) -> pp f "@[<hov>module@ %s@ =@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") longident_loc alias (item_attributes ctxt) pmd.pmd_attributes | Psig_module pmd -> pp f "@[<hov>module@ %s@ :@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes | Psig_modsubst pms -> pp f "@[<hov>module@ %s@ :=@ %a@]%a" pms.pms_name.txt longident_loc pms.pms_manifest (item_attributes ctxt) pms.pms_attributes | Psig_open od -> pp f "@[<hov2>open%s@ %a@]%a" (override od.popen_override) longident_loc od.popen_expr (item_attributes ctxt) od.popen_attributes | Psig_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_type ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Psig_class_type (l) -> class_type_declaration_list ctxt f l | Psig_recmodule decls -> let rec string_x_module_type_list f ?(first=true) l = match l with | [] -> () ; | pmd :: tl -> if not first then pp f "@ @[<hov2>and@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes else pp f "@[<hov2>module@ rec@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes; string_x_module_type_list f ~first:false tl in string_x_module_type_list f decls | Psig_attribute a -> floating_attribute ctxt f a | Psig_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and module_expr ctxt f x = if x.pmod_attributes <> [] then pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]} (attributes ctxt) x.pmod_attributes else match x.pmod_desc with | Pmod_structure (s) -> pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]" (list (structure_item ctxt) ~sep:"@\n") s; | Pmod_constraint (me, mt) -> pp f "@[<hov2>(%a@ :@ %a)@]" (module_expr ctxt) me (module_type ctxt) mt | Pmod_ident (li) -> pp f "%a" longident_loc li; | Pmod_functor (Unit, me) -> pp f "functor ()@;->@;%a" (module_expr ctxt) me | Pmod_functor (Named (s, mt), me) -> pp f "functor@ (%s@ :@ %a)@;->@;%a" (Option.value s.txt ~default:"_") (module_type ctxt) mt (module_expr ctxt) me | Pmod_apply (me1, me2) -> pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2 Cf : # 7200 | Pmod_unpack e -> pp f "(val@ %a)" (expression ctxt) e | Pmod_extension e -> extension ctxt f e and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x and payload ctxt f = function | PStr [{pstr_desc = Pstr_eval (e, attrs)}] -> pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | PStr x -> structure ctxt f x | PTyp x -> pp f ":"; core_type ctxt f x | PSig x -> pp f ":"; signature ctxt f x | PPat (x, None) -> pp f "?"; pattern ctxt f x | PPat (x, Some e) -> pp f "?"; pattern ctxt f x; pp f " when "; expression ctxt f e (* transform [f = fun g h -> ..] to [f g h = ... ] could be improved *) and binding ctxt f {pvb_pat=p; pvb_expr=x; _} = (* .pvb_attributes have already been printed by the caller, #bindings *) let rec pp_print_pexp_function f x = if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x else match x.pexp_desc with | Pexp_fun (label, eo, p, e) -> if label=Nolabel then pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e else pp f "%a@ %a" (label_exp ctxt) (label,eo,p) pp_print_pexp_function e | Pexp_newtype (str,e) -> pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e | _ -> pp f "=@;%a" (expression ctxt) x in let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in let is_desugared_gadt p e = let gadt_pattern = match p with | {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _} as pat, {ptyp_desc=Ptyp_poly (args_tyvars, rt)}); ppat_attributes=[]}-> Some (pat, args_tyvars, rt) | _ -> None in let rec gadt_exp tyvars e = match e with | {pexp_desc=Pexp_newtype (tyvar, e); pexp_attributes=[]} -> gadt_exp (tyvar :: tyvars) e | {pexp_desc=Pexp_constraint (e, ct); pexp_attributes=[]} -> Some (List.rev tyvars, e, ct) | _ -> None in let gadt_exp = gadt_exp [] e in match gadt_pattern, gadt_exp with | Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct) when tyvars_str pt_tyvars = tyvars_str e_tyvars -> let ety = Typ.varify_constructors e_tyvars e_ct in if ety = pt_ct then Some (p, pt_tyvars, e_ct, e) else None | _ -> None in if x.pexp_attributes <> [] then pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x else match is_desugared_gadt p x with | Some (p, [], ct, e) -> pp f "%a@;: %a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ct (expression ctxt) e | Some (p, tyvars, ct, e) -> begin pp f "%a@;: type@;%a.@;%a@;=@;%a" (simple_pattern ctxt) p (list pp_print_string ~sep:"@;") (tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e end | None -> begin match p with | {ppat_desc=Ppat_constraint(p ,ty); special case for the first begin match ty with | {ptyp_desc=Ptyp_poly _; ptyp_attributes=[]} -> pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x | _ -> pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x end | {ppat_desc=Ppat_var _; ppat_attributes=[]} -> pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x end (* [in] is not printed *) and bindings ctxt f (rf,l) = let binding kwd rf f x = pp f "@[<2>%s %a%a@]%a" kwd rec_flag rf (binding ctxt) x (item_attributes ctxt) x.pvb_attributes in match l with | [] -> () | [x] -> binding "let" rf f x | x::xs -> pp f "@[<v>%a@,%a@]" (binding "let" rf) x (list ~sep:"@," (binding "and" Nonrecursive)) xs and binding_op ctxt f x = pp f "@[<2>%s %a@;=@;%a@]" x.pbop_op.txt (pattern ctxt) x.pbop_pat (expression ctxt) x.pbop_exp and structure_item ctxt f x = match x.pstr_desc with | Pstr_eval (e, attrs) -> pp f "@[<hov2>;;%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | Pstr_type (_, []) -> assert false | Pstr_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Pstr_value (rf, l) -> pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l pp f "@[<2>%a@]" (bindings ctxt) (rf,l) | Pstr_typext te -> type_extension ctxt f te | Pstr_exception ed -> exception_declaration ctxt f ed | Pstr_module x -> let rec module_helper = function | {pmod_desc=Pmod_functor(arg_opt,me'); pmod_attributes = []} -> begin match arg_opt with | Unit -> pp f "()" | Named (s, mt) -> pp f "(%s:%a)" (Option.value s.txt ~default:"_") (module_type ctxt) mt end; module_helper me' | me -> me in pp f "@[<hov2>module %s%a@]%a" (Option.value x.pmb_name.txt ~default:"_") (fun f me -> let me = module_helper me in match me with | {pmod_desc= Pmod_constraint (me', ({pmty_desc=(Pmty_ident (_) | Pmty_signature (_));_} as mt)); pmod_attributes = []} -> pp f " :@;%a@;=@;%a@;" (module_type ctxt) mt (module_expr ctxt) me' | _ -> pp f " =@ %a" (module_expr ctxt) me ) x.pmb_expr (item_attributes ctxt) x.pmb_attributes | Pstr_open od -> pp f "@[<2>open%s@;%a@]%a" (override od.popen_override) (module_expr ctxt) od.popen_expr (item_attributes ctxt) od.popen_attributes | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Pstr_class l -> let extract_class_args cl = let rec loop acc = function | {pcl_desc=Pcl_fun (l, eo, p, cl'); pcl_attributes = []} -> loop ((l,eo,p) :: acc) cl' | cl -> List.rev acc, cl in let args, cl = loop [] cl in let constr, cl = match cl with | {pcl_desc=Pcl_constraint (cl', ct); pcl_attributes = []} -> Some ct, cl' | _ -> None, cl in args, constr, cl in let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in let class_declaration kwd f ({pci_params=ls; pci_name={txt;_}; _} as x) = let args, constr, cl = extract_class_args x.pci_expr in pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (list (label_exp ctxt)) args (option class_constraint) constr (class_expr ctxt) cl (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_declaration "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_declaration "class") x (list ~sep:"@," (class_declaration "and")) xs end | Pstr_class_type l -> class_type_declaration_list ctxt f l | Pstr_primitive vd -> pp f "@[<hov2>external@ %a@ :@ %a@]%a" protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Pstr_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_expr ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes 3.07 let aux f = function | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) -> pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes | pmb -> pp f "@[<hov2>@ and@ %s@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes in begin match decls with | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | pmb :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | _ -> assert false end | Pstr_attribute a -> floating_attribute ctxt f a | Pstr_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and type_param ctxt f (ct, a) = pp f "%s%a" (type_variance a) (core_type ctxt) ct and type_params ctxt f = function | [] -> () | l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",@;") l and type_def_list ctxt f (rf, exported, l) = let type_decl kwd rf f x = let eq = if (x.ptype_kind = Ptype_abstract) && (x.ptype_manifest = None) then "" else if exported then " =" else " :=" in pp f "@[<2>%s %a%a%s%s%a@]%a" kwd nonrec_flag rf (type_params ctxt) x.ptype_params x.ptype_name.txt eq (type_declaration ctxt) x (item_attributes ctxt) x.ptype_attributes in match l with | [] -> assert false | [x] -> type_decl "type" rf f x | x :: xs -> pp f "@[<v>%a@,%a@]" (type_decl "type" rf) x (list ~sep:"@," (type_decl "and" Recursive)) xs and record_declaration ctxt f lbls = let type_record_field f pld = pp f "@[<2>%a%s:@;%a@;%a@]" mutable_flag pld.pld_mutable pld.pld_name.txt (core_type ctxt) pld.pld_type (attributes ctxt) pld.pld_attributes in pp f "{@\n%a}" (list type_record_field ~sep:";@\n" ) lbls and type_declaration ctxt f x = (* type_declaration has an attribute field, but it's been printed by the caller of this method *) let priv f = match x.ptype_private with | Public -> () | Private -> pp f "@;private" in let manifest f = match x.ptype_manifest with | None -> () | Some y -> if x.ptype_kind = Ptype_abstract then pp f "%t@;%a" priv (core_type ctxt) y else pp f "@;%a" (core_type ctxt) y in let constructor_declaration f pcd = pp f "|@;"; constructor_declaration ctxt f (pcd.pcd_name.txt, pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes) in let repr f = let intro f = if x.ptype_manifest = None then () else pp f "@;=" in match x.ptype_kind with | Ptype_variant xs -> let variants fmt xs = if xs = [] then pp fmt " |" else pp fmt "@\n%a" (list ~sep:"@\n" constructor_declaration) xs in pp f "%t%t%a" intro priv variants xs | Ptype_abstract -> () | Ptype_record l -> pp f "%t%t@;%a" intro priv (record_declaration ctxt) l | Ptype_open -> pp f "%t%t@;.." intro priv in let constraints f = List.iter (fun (ct1,ct2,_) -> pp f "@[<hov2>@ constraint@ %a@ =@ %a@]" (core_type ctxt) ct1 (core_type ctxt) ct2) x.ptype_cstrs in pp f "%t%t%t" manifest repr constraints and type_extension ctxt f x = let extension_constructor f x = pp f "@\n|@;%a" (extension_constructor ctxt) x in pp f "@[<2>type %a%a += %a@ %a@]%a" (fun f -> function | [] -> () | l -> pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l) x.ptyext_params longident_loc x.ptyext_path Cf : # 7200 (list ~sep:"" extension_constructor) x.ptyext_constructors (item_attributes ctxt) x.ptyext_attributes and constructor_declaration ctxt f (name, args, res, attrs) = let name = match name with | "::" -> "(::)" | s -> s in match res with | None -> pp f "%s%a@;%a" name (fun f -> function | Pcstr_tuple [] -> () | Pcstr_tuple l -> pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l | Pcstr_record l -> pp f "@;of@;%a" (record_declaration ctxt) l ) args (attributes ctxt) attrs | Some r -> pp f "%s:@;%a@;%a" name (fun f -> function | Pcstr_tuple [] -> core_type1 ctxt f r | Pcstr_tuple l -> pp f "%a@;->@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l (core_type1 ctxt) r | Pcstr_record l -> pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r ) args (attributes ctxt) attrs and extension_constructor ctxt f x = Cf : # 7200 match x.pext_kind with | Pext_decl(l, r) -> constructor_declaration ctxt f (x.pext_name.txt, l, r, x.pext_attributes) | Pext_rebind li -> pp f "%s%a@;=@;%a" x.pext_name.txt (attributes ctxt) x.pext_attributes longident_loc li and case_list ctxt f l : unit = let aux f {pc_lhs; pc_guard; pc_rhs} = pp f "@;| @[<2>%a%a@;->@;%a@]" (pattern ctxt) pc_lhs (option (expression ctxt) ~first:"@;when@;") pc_guard (expression (under_pipe ctxt)) pc_rhs in list aux f l ~sep:"" and label_x_expression_param ctxt f (l,e) = let simple_name = match e with | {pexp_desc=Pexp_ident {txt=Lident l;_}; pexp_attributes=[]} -> Some l | _ -> None in match l with level 2 | Optional str -> if Some str = simple_name then pp f "?%s" str else pp f "?%s:%a" str (simple_expr ctxt) e | Labelled lbl -> if Some lbl = simple_name then pp f "~%s" lbl else pp f "~%s:%a" lbl (simple_expr ctxt) e and directive_argument f x = match x.pdira_desc with | Pdir_string (s) -> pp f "@ %S" s | Pdir_int (n, None) -> pp f "@ %s" n | Pdir_int (n, Some m) -> pp f "@ %s%c" n m | Pdir_ident (li) -> pp f "@ %a" longident li | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b) let toplevel_phrase f x = match x with | Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s (* pp_open_hvbox f 0; *) (* pp_print_list structure_item f s ; *) pp_close_box f ( ) ; | Ptop_dir {pdir_name; pdir_arg = None; _} -> pp f "@[<hov2>#%s@]" pdir_name.txt | Ptop_dir {pdir_name; pdir_arg = Some pdir_arg; _} -> pp f "@[<hov2>#%s@ %a@]" pdir_name.txt directive_argument pdir_arg let expression f x = pp f "@[%a@]" (expression reset_ctxt) x let string_of_expression x = ignore (flush_str_formatter ()) ; let f = str_formatter in expression f x; flush_str_formatter () let string_of_structure x = ignore (flush_str_formatter ()); let f = str_formatter in structure reset_ctxt f x; flush_str_formatter () let top_phrase f x = pp_print_newline f (); toplevel_phrase f x; pp f ";;"; pp_print_newline f () let core_type = core_type reset_ctxt let pattern = pattern reset_ctxt let signature = signature reset_ctxt let structure = structure reset_ctxt
null
https://raw.githubusercontent.com/let-def/ocaml-recovery-parser/87a87a25c9436f2e3187b82ec59a5f75c0e2446b/lib/pprintast.ml
ocaml
************************************************************************ OCaml Fabrice Le Fessant, INRIA Saclay en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Printing code expressions type fixity = Infix| Prefix which identifiers are in fact operators needing parentheses some infixes need spaces around parens to avoid clashes with comment syntax add parentheses to binders when they are in fact infix or prefix operators variance encoding: need to sync up with the [parser.mly] trailing space trailing space added without the space, this would be parsed as a character literal c ['a,'b] space otherwise parenthesize "%a%a@;" Cf #7200: print [>] correctly FIXME desugar the syntax sugar *******************pattern******************* RA RA single case pattern parens needed here extract operator: assignment operators end with [right_bracket ^ "<-"], access operators end with [right_bracket] directly extract the right end bracket "try@;@[<2>%a@]@\nwith@\n%a" pp f "@[<2>let %a%a in@;<1 -2>%a@]" (*no indentation here, a new line See #7200: avoid turning (~- 1) into (- 1) which is parsed as an int literal reset here only because [function,match,try,sequence] are lower priority Not efficient FIXME @;@[<2>else@ %a@]@] pp f "()" Pexp_poly: impossible but we should print it anyway, rather than assert false used in [Pexp_apply] (match view_fixity_of_exp x with |`Normal -> longident_loc f li | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) no sep hint "@[<hov2>{%a%a}@]" note: value_description has an attribute field, but they're already printed by the callers this method call [class_signature] called by [class_signature] [class type a = object end] "@[<hov>sig@ %a@ end@]" FIXME wrong indentation transform [f = fun g h -> ..] to [f g h = ... ] could be improved .pvb_attributes have already been printed by the caller, #bindings [in] is not printed type_declaration has an attribute field, but it's been printed by the caller of this method pp_open_hvbox f 0; pp_print_list structure_item f s ;
, OCamlPro , University of Pennsylvania Copyright 2007 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the Original Code from Ber - metaocaml , modified for 3.12.0 and fixed Authors : , Extensive Rewrite : : University of Pennsylvania TODO more fine - grained precedence pretty - printing [@@@ocaml.warning "-9"];; open Asttypes open Format open Location open Longident open Parsetree open Ast_helper let prefix_symbols = [ '!'; '?'; '~' ] ;; let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%'; '#' ] let special_infix_strings = ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ] let letop s = String.length s > 3 && s.[0] = 'l' && s.[1] = 'e' && s.[2] = 't' && List.mem s.[3] infix_symbols let andop s = String.length s > 3 && s.[0] = 'a' && s.[1] = 'n' && s.[2] = 'd' && List.mem s.[3] infix_symbols determines if the string is an infix string . checks backwards , first allowing a renaming postfix ( " _ 102 " ) which may have resulted from - > Texp - > translation , then checking if all the characters in the beginning of the string are valid infix characters . checks backwards, first allowing a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp translation, then checking if all the characters in the beginning of the string are valid infix characters. *) let fixity_of_string = function | "" -> `Normal | s when List.mem s special_infix_strings -> `Infix s | s when List.mem s.[0] infix_symbols -> `Infix s | s when List.mem s.[0] prefix_symbols -> `Prefix s | s when s.[0] = '.' -> `Mixfix s | s when letop s -> `Letop s | s when andop s -> `Andop s | _ -> `Normal let view_fixity_of_exp = function | {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} -> fixity_of_string l | _ -> `Normal let is_infix = function `Infix _ -> true | _ -> false let is_mixfix = function `Mixfix _ -> true | _ -> false let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false let first_is c str = str <> "" && str.[0] = c let last_is c str = str <> "" && str.[String.length str - 1] = c let first_is_in cs str = str <> "" && List.mem str.[0] cs let needs_parens txt = let fix = fixity_of_string txt in is_infix fix || is_mixfix fix || is_kwdop fix || first_is_in prefix_symbols txt let needs_spaces txt = first_is '*' txt || last_is '*' txt let protect_ident ppf txt = let format : (_, _, _) format = if not (needs_parens txt) then "%s" else if needs_spaces txt then "(@;%s@;)" else "(%s)" in fprintf ppf format txt let protect_longident ppf print_longident longprefix txt = let format : (_, _, _) format = if not (needs_parens txt) then "%a.%s" else if needs_spaces txt then "%a.(@;%s@;)" else "%a.(%s)" in fprintf ppf format print_longident longprefix txt type space_formatter = (unit, Format.formatter, unit) format let override = function | Override -> "!" | Fresh -> "" let type_variance = function | Invariant -> "" | Covariant -> "+" | Contravariant -> "-" type construct = [ `cons of expression list | `list of expression list | `nil | `normal | `simple of Longident.t | `tuple ] let view_expr x = match x.pexp_desc with | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil | Pexp_construct ( {txt= Lident"::";_},Some _) -> let rec loop exp acc = match exp with | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_); pexp_attributes = []} -> (List.rev acc,true) | {pexp_desc= Pexp_construct ({txt=Lident "::";_}, Some ({pexp_desc= Pexp_tuple([e1;e2]); pexp_attributes = []})); pexp_attributes = []} -> loop e2 (e1::acc) | e -> (List.rev (e::acc),false) in let (ls,b) = loop x [] in if b then `list ls else `cons ls | Pexp_construct (x,None) -> `simple (x.txt) | _ -> `normal let is_simple_construct :construct -> bool = function | `nil | `tuple | `list _ | `simple _ -> true | `cons _ | `normal -> false let pp = fprintf type ctxt = { pipe : bool; semi : bool; ifthenelse : bool; } let reset_ctxt = { pipe=false; semi=false; ifthenelse=false } let under_pipe ctxt = { ctxt with pipe=true } let under_semi ctxt = { ctxt with semi=true } let under_ifthenelse ctxt = { ctxt with ifthenelse=true } let reset_semi = with semi = false } let reset_ifthenelse = with ifthenelse = false } let = with pipe = false } let reset_semi ctxt = { ctxt with semi=false } let reset_ifthenelse ctxt = { ctxt with ifthenelse=false } let reset_pipe ctxt = { ctxt with pipe=false } *) let list : 'a . ?sep:space_formatter -> ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit = fun ?sep ?first ?last fu f xs -> let first = match first with Some x -> x |None -> ("": _ format6) and last = match last with Some x -> x |None -> ("": _ format6) and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in let aux f = function | [] -> () | [x] -> fu f x | xs -> let rec loop f = function | [x] -> fu f x | x::xs -> fu f x; pp f sep; loop f xs; | _ -> assert false in begin pp f first; loop f xs; pp f last; end in aux f xs let option : 'a. ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit = fun ?first ?last fu f a -> let first = match first with Some x -> x | None -> ("": _ format6) and last = match last with Some x -> x | None -> ("": _ format6) in match a with | None -> () | Some x -> pp f first; fu f x; pp f last let paren: 'a . ?first:space_formatter -> ?last:space_formatter -> bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit = fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x -> if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")") else fu f x let rec longident f = function | Lident s -> protect_ident f s | Ldot(y,s) -> protect_longident f longident y s | Lapply (y,s) -> pp f "%a(%a)" longident y longident s let longident_loc f x = pp f "%a" longident x.txt let constant f = function | Pconst_char i -> pp f "%C" i | Pconst_string (i, None) -> pp f "%S" i | Pconst_string (i, Some delim) -> pp f "{%s|%s|%s}" delim i delim | Pconst_integer (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_integer (i, Some m) -> paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m) | Pconst_float (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_float (i, Some m) -> paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m) let mutable_flag f = function | Immutable -> () | Mutable -> pp f "mutable@;" let virtual_flag f = function | Concrete -> () | Virtual -> pp f "virtual@;" let rec_flag f rf = match rf with | Nonrecursive -> () | Recursive -> pp f "rec " let nonrec_flag f rf = match rf with | Nonrecursive -> pp f "nonrec " | Recursive -> () let direction_flag f = function | Upto -> pp f "to@ " | Downto -> pp f "downto@ " let private_flag f = function | Public -> () | Private -> pp f "private@ " let iter_loc f ctxt {txt; loc = _} = f ctxt txt let constant_string f s = pp f "%S" s let tyvar ppf s = if String.length s >= 2 && s.[1] = '\'' then Format.fprintf ppf "' %s" s else Format.fprintf ppf "'%s" s let tyvar_loc f str = tyvar f str.txt let string_quot f x = pp f "`%s" x let rec class_params_def ctxt f = function | [] -> () | l -> (list (type_param ctxt) ~sep:",") l and type_with_label ctxt f (label, c) = match label with | Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c | Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c and core_type ctxt f x = if x.ptyp_attributes <> [] then begin pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]} (attributes ctxt) x.ptyp_attributes end else match x.ptyp_desc with | Ptyp_arrow (l, ct1, ct2) -> FIXME remove parens later (type_with_label ctxt) (l,ct1) (core_type ctxt) ct2 | Ptyp_alias (ct, s) -> pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct tyvar s | Ptyp_poly ([], ct) -> core_type ctxt f ct | Ptyp_poly (sl, ct) -> pp f "@[<2>%a%a@]" (fun f l -> pp f "%a" (fun f l -> match l with | [] -> () | _ -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") l) l) sl (core_type ctxt) ct | _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x and core_type1 ctxt f x = if x.ptyp_attributes <> [] then core_type ctxt f x else match x.ptyp_desc with | Ptyp_any -> pp f "_"; | Ptyp_var s -> tyvar f s; | Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l | Ptyp_constr (li, l) -> (fun f l -> match l with |[] -> () |[x]-> pp f "%a@;" (core_type1 ctxt) x | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l) l longident_loc li | Ptyp_variant (l, closed, low) -> let type_variant_helper f x = match x.prf_desc with | Rtag (l, _, ctl) -> pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l (fun f l -> match l with |[] -> () | _ -> pp f "@;of@;%a" (list (core_type ctxt) ~sep:"&") ctl) ctl (attributes ctxt) x.prf_attributes | Rinherit ct -> core_type ctxt f ct in pp f "@[<2>[%a%a]@]" (fun f l -> match l, closed with | [], Closed -> () | _ -> pp f "%s@;%a" (match (closed,low) with | (Closed,None) -> "" | (Open,_) -> ">") (list type_variant_helper ~sep:"@;<1 -2>| ") l) l (fun f low -> match low with |Some [] |None -> () |Some xs -> pp f ">@ %a" (list string_quot) xs) low | Ptyp_object (l, o) -> let core_field_type f x = match x.pof_desc with | Otag (l, ct) -> Cf # 7200 pp f "@[<hov2>%s: %a@ %a@ @]" l.txt (core_type ctxt) ct (attributes ctxt) x.pof_attributes | Oinherit ct -> pp f "@[<hov2>%a@ @]" (core_type ctxt) ct in let field_var f = function | Asttypes.Closed -> () | Asttypes.Open -> match l with | [] -> pp f ".." | _ -> pp f " ;.." in pp f "@[<hov2><@ %a%a@ > @]" (list core_field_type ~sep:";") l Cf # 7200 FIXME pp f "@[<hov2>%a#%a@]" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l longident_loc li | Ptyp_package (lid, cstrs) -> let aux f (s, ct) = pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in (match cstrs with |[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid |_ -> pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid (list aux ~sep:"@ and@ ") cstrs) | Ptyp_extension e -> extension ctxt f e | _ -> paren true (core_type ctxt) f x be cautious when use [ pattern ] , [ ] is preferred and pattern ctxt f x = only consider ( ( A|B)|C ) | {ppat_desc= Ppat_or (p1,p2); ppat_attributes = []} -> list_of_pattern (p2::acc) p1 | x -> x::acc in if x.ppat_attributes <> [] then begin pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]} (attributes ctxt) x.ppat_attributes end else match x.ppat_desc with | Ppat_alias (p, s) -> pp f "@[<hov0>%a@]" (list ~sep:"@,|" (pattern ctxt)) (list_of_pattern [] x) | _ -> pattern1 ctxt f x and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit = let rec pattern_list_helper f = function | {ppat_desc = Ppat_construct ({ txt = Lident("::") ;_}, Some ({ppat_desc = Ppat_tuple([pat1; pat2]);_})); ppat_attributes = []} -> | p -> pattern1 ctxt f p in if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> simple_pattern ctxt f x | Ppat_construct (({txt;_} as li), po) -> FIXME The third field always false if txt = Lident "::" then pp f "%a" pattern_list_helper x else (match po with | Some x -> pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x | None -> pp f "%a" longident_loc li) | _ -> simple_pattern ctxt f x and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit = if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), _) -> pp f "%s" x | Ppat_any -> pp f "_"; | Ppat_var ({txt = txt;_}) -> protect_ident f txt | Ppat_array l -> pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l | Ppat_unpack { txt = None } -> pp f "(module@ _)@ " | Ppat_unpack { txt = Some s } -> pp f "(module@ %s)@ " s | Ppat_type li -> pp f "#%a" longident_loc li | Ppat_record (l, closed) -> let longident_x_pattern f (li, p) = match (li,p) with | ({txt=Lident s;_ }, {ppat_desc=Ppat_var {txt;_}; ppat_attributes=[]; _}) when s = txt -> pp f "@[<2>%a@]" longident_loc li | _ -> pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p in begin match closed with | Closed -> pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l | _ -> pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l end | Ppat_tuple l -> | Ppat_constant (c) -> pp f "%a" constant c | Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2 | Ppat_variant (l,None) -> pp f "`%s" l | Ppat_constraint (p, ct) -> pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct | Ppat_lazy p -> pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p | Ppat_exception p -> pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p | Ppat_extension e -> extension ctxt f e | Ppat_open (lid, p) -> let with_paren = match p.ppat_desc with | Ppat_array _ | Ppat_record _ | Ppat_construct (({txt=Lident ("()"|"[]");_}), _) -> false | _ -> true in pp f "@[<2>%a.%a @]" longident_loc lid (paren with_paren @@ pattern1 ctxt) p | _ -> paren true (pattern ctxt) f x and label_exp ctxt f (l,opt,p) = match l with | Nolabel -> pp f "%a@ " (simple_pattern ctxt) p | Optional rest -> begin match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = rest -> (match opt with | Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o | None -> pp f "?%s@ " rest) | _ -> (match opt with | Some o -> pp f "?%s:(%a=@;%a)@;" rest (pattern1 ctxt) p (expression ctxt) o | None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p) end | Labelled l -> match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = l -> pp f "~%s@;" l | _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p and sugar_expr ctxt f e = if e.pexp_attributes <> [] then false else match e.pexp_desc with | Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _}; pexp_attributes=[]; _}, args) when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin let print_indexop a path_prefix assign left sep right print_index indices rem_args = let print_path ppf = function | None -> () | Some m -> pp ppf ".%a" longident m in match assign, rem_args with | false, [] -> pp f "@[%a%a%s%a%s@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right; true | true, [v] -> pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right (simple_expr ctxt) v; true | _ -> false in match id, List.map snd args with | Lident "!", [e] -> pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true | Ldot (path, ("get"|"set" as func)), a :: other_args -> begin let assign = func = "set" in let print = print_indexop a None assign in match path, other_args with | Lident "Array", i :: rest -> print ".(" "" ")" (expression ctxt) [i] rest | Lident "String", i :: rest -> print ".[" "" "]" (expression ctxt) [i] rest | Ldot (Lident "Bigarray", "Array1"), i1 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1] rest | Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest | Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest | Ldot (Lident "Bigarray", "Genarray"), {pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest -> print ".{" "," "}" (simple_expr ctxt) indexes rest | _ -> false end | (Lident s | Ldot(_,s)) , a :: i :: rest when first_is '.' s -> let multi_indices = String.contains s ';' in let i = match i.pexp_desc with | Pexp_array l when multi_indices -> l | _ -> [ i ] in let assign = last_is '-' s in let kind = let n = String.length s in if assign then s.[n - 3] else s.[n - 1] in let left, right = match kind with | ')' -> '(', ")" | ']' -> '[', "]" | '}' -> '{', "}" | _ -> assert false in let path_prefix = match id with | Ldot(m,_) -> Some m | _ -> None in let left = String.sub s 0 (1+String.index s left) in print_indexop a path_prefix assign left ";" right (if multi_indices then expression ctxt else simple_expr ctxt) i rest | _ -> false end | _ -> false and expression ctxt f x = if x.pexp_attributes <> [] then pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes else match x.pexp_desc with | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _ | Pexp_newtype _ when ctxt.pipe || ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse -> paren true (expression reset_ctxt) f x | Pexp_let _ | Pexp_letmodule _ | Pexp_open _ | Pexp_letexception _ | Pexp_letop _ when ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_fun (l, e0, p, e) -> pp f "@[<2>fun@;%a->@;%a@]" (label_exp ctxt) (l, e0, p) (expression ctxt) e | Pexp_newtype (lid, e) -> pp f "@[<2>fun@;(type@;%s)@;->@;%a@]" lid.txt (expression ctxt) e | Pexp_function l -> pp f "@[<hv>function%a@]" (case_list ctxt) l | Pexp_match (e, l) -> pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]" (expression reset_ctxt) e (case_list ctxt) l | Pexp_try (e, l) -> pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]" (expression reset_ctxt) e (case_list ctxt) l | Pexp_let (rf, l, e) -> rec_flag rf pp f "@[<2>%a in@;<1 -2>%a@]" (bindings reset_ctxt) (rf,l) (expression ctxt) e | Pexp_apply (e, l) -> begin if not (sugar_expr ctxt f x) then match view_fixity_of_exp e with | `Infix s -> begin match l with | [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] -> FIXME associativity label_x_expression_param pp f "@[<2>%a@;%s@;%a@]" (label_x_expression_param reset_ctxt) arg1 s (label_x_expression_param ctxt) arg2 | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | `Prefix s -> let s = if List.mem s ["~+";"~-";"~+.";"~-."] && (match l with |[(_,{pexp_desc=Pexp_constant _})] -> false | _ -> true) then String.sub s 1 (String.length s -1) else s in begin match l with | [(Nolabel, x)] -> pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | _ -> pp f "@[<hov2>%a@]" begin fun f (e,l) -> pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l end (e,l) end | Pexp_construct (li, Some eo) (match view_expr x with | `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;" | `normal -> pp f "@[<2>%a@;%a@]" longident_loc li (simple_expr ctxt) eo | _ -> assert false) | Pexp_setfield (e1, li, e2) -> pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 | Pexp_ifthenelse (e1, e2, eo) -> let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2 (fun f eo -> match eo with | Some x -> pp f "@;@[<2>else@;%a@]" (expression (under_semi ctxt)) x | Pexp_sequence _ -> let rec sequence_helper acc = function | {pexp_desc=Pexp_sequence(e1,e2); pexp_attributes = []} -> sequence_helper (e1::acc) e2 | v -> List.rev (v::acc) in let lst = sequence_helper [] x in pp f "@[<hv>%a@]" (list (expression (under_semi ctxt)) ~sep:";@;") lst | Pexp_new (li) -> pp f "@[<hov2>new@ %a@]" longident_loc li; | Pexp_setinstvar (s, e) -> pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e FIXME let string_x_expression f (s, e) = pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in pp f "@[<hov2>{<%a>}@]" (list string_x_expression ~sep:";" ) l; | Pexp_letmodule (s, me, e) -> pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]" (Option.value s.txt ~default:"_") (module_expr reset_ctxt) me (expression ctxt) e | Pexp_letexception (cd, e) -> pp f "@[<hov2>let@ exception@ %a@ in@ %a@]" (extension_constructor ctxt) cd (expression ctxt) e | Pexp_assert e -> pp f "@[<hov2>assert@ %a@]" (simple_expr ctxt) e | Pexp_lazy (e) -> pp f "@[<hov2>lazy@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, None) -> pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, Some ct) -> pp f "@[<hov2>(!poly!@ %a@ : %a)@]" (simple_expr ctxt) e (core_type ctxt) ct | Pexp_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) (module_expr ctxt) o.popen_expr (expression ctxt) e | Pexp_variant (l,Some eo) -> pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo | Pexp_letop {let_; ands; body} -> pp f "@[<2>@[<v>%a@,%a@] in@;<1 -2>%a@]" (binding_op ctxt) let_ (list ~sep:"@," (binding_op ctxt)) ands (expression ctxt) body | Pexp_extension e -> extension ctxt f e | Pexp_unreachable -> pp f "." | _ -> expression1 ctxt f x and expression1 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_object cs -> pp f "%a" (class_structure ctxt) cs | _ -> expression2 ctxt f x and expression2 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_field (e, li) -> pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt | _ -> simple_expr ctxt f x and simple_expr ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_construct _ when is_simple_construct (view_expr x) -> (match view_expr x with | `nil -> pp f "[]" | `tuple -> pp f "()" | `list xs -> pp f "@[<hv0>[%a]@]" (list (expression (under_semi ctxt)) ~sep:";@;") xs | `simple x -> longident f x | _ -> assert false) | Pexp_ident li -> longident_loc f li | Pexp_constant c -> constant f c; | Pexp_pack me -> pp f "(module@;%a)" (module_expr ctxt) me | Pexp_tuple l -> pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l | Pexp_constraint (e, ct) -> pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_coerce (e, cto1, ct) -> pp f "(%a%a :> %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_variant (l, None) -> pp f "`%s" l | Pexp_record (l, eo) -> let longident_x_expression f ( li, e) = match e with | {pexp_desc=Pexp_ident {txt;_}; pexp_attributes=[]; _} when li.txt = txt -> pp f "@[<hov2>%a@]" longident_loc li | _ -> pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e in (option ~last:" with@;" (simple_expr ctxt)) eo (list longident_x_expression ~sep:";@;") l | Pexp_array (l) -> pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l | Pexp_while (e1, e2) -> let fmt : (_,_,_) format = "@[<2>while@;%a@;do@;%a@;done@]" in pp f fmt (expression ctxt) e1 (expression ctxt) e2 | Pexp_for (s, e1, e2, df, e3) -> let fmt:(_,_,_)format = "@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in let expression = expression ctxt in pp f fmt (pattern ctxt) s expression e1 direction_flag df expression e2 expression e3 | _ -> paren true (expression ctxt) f x and attributes ctxt f l = List.iter (attribute ctxt f) l and item_attributes ctxt f l = List.iter (item_attribute ctxt f) l and attribute ctxt f a = pp f "@[<2>[@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and item_attribute ctxt f a = pp f "@[<2>[@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and floating_attribute ctxt f a = pp f "@[<2>[@@@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and value_description ctxt f x = pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type (fun f x -> if x.pval_prim <> [] then pp f "@ =@ %a" (list constant_string) x.pval_prim ) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e and item_extension ctxt f (s, e) = pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e and exception_declaration ctxt f x = pp f "@[<hov2>exception@ %a@]%a" (extension_constructor ctxt) x.ptyexn_constructor (item_attributes ctxt) x.ptyexn_attributes and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} = let class_type_field f x = match x.pctf_desc with | Pctf_inherit (ct) -> pp f "@[<2>inherit@ %a@]%a" (class_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_val (s, mf, vf, ct) -> pp f "@[<2>val @ %a%a%s@ :@ %a@]%a" mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_method (s, pf, vf, ct) -> pp f "@[<2>method %a %a%s :@;%a@]%a" private_flag pf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_constraint (ct1, ct2) -> pp f "@[<2>constraint@ %a@ =@ %a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pctf_attributes | Pctf_attribute a -> floating_attribute ctxt f a | Pctf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pctf_attributes in pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]" (fun f -> function {ptyp_desc=Ptyp_any; ptyp_attributes=[]; _} -> () | ct -> pp f " (%a)" (core_type ctxt) ct) ct (list class_type_field ~sep:"@;") l and class_type ctxt f x = match x.pcty_desc with | Pcty_signature cs -> class_signature ctxt f cs; attributes ctxt f x.pcty_attributes | Pcty_constr (li, l) -> pp f "%a%a%a" (fun f l -> match l with | [] -> () | _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l longident_loc li (attributes ctxt) x.pcty_attributes | Pcty_arrow (l, co, cl) -> FIXME remove parens later (type_with_label ctxt) (l,co) (class_type ctxt) cl | Pcty_extension e -> extension ctxt f e; attributes ctxt f x.pcty_attributes | Pcty_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_type ctxt) e and class_type_declaration_list ctxt f l = let class_type_declaration kwd f x = let { pci_params=ls; pci_name={ txt; _ }; _ } = x in pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in match l with | [] -> () | [x] -> class_type_declaration "class type" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_type_declaration "class type") x (list ~sep:"@," (class_type_declaration "and")) xs and class_field ctxt f x = match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf) (class_expr ctxt) ce (fun f so -> match so with | None -> (); | Some (s) -> pp f "@ as %s" s.txt ) so (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_concrete (ovf, e)) -> pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf) mutable_flag mf s.txt (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_virtual ct) -> pp f "@[<2>method virtual %a %s :@;%a@]%a" private_flag pf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_virtual ct) -> pp f "@[<2>val virtual %a%s :@ %a@]%a" mutable_flag mf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_concrete (ovf, e)) -> let bind e = binding ctxt f {pvb_pat= {ppat_desc=Ppat_var s; ppat_loc=Location.none; ppat_loc_stack=[]; ppat_attributes=[]}; pvb_expr=e; pvb_attributes=[]; pvb_loc=Location.none; } in pp f "@[<2>method%s %a%a@]%a" (override ovf) private_flag pf (fun f -> function | {pexp_desc=Pexp_poly (e, Some ct); pexp_attributes=[]; _} -> pp f "%s :@;%a=@;%a" s.txt (core_type ctxt) ct (expression ctxt) e | {pexp_desc=Pexp_poly (e, None); pexp_attributes=[]; _} -> bind e | _ -> bind e) e (item_attributes ctxt) x.pcf_attributes | Pcf_constraint (ct1, ct2) -> pp f "@[<2>constraint %a =@;%a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pcf_attributes | Pcf_initializer (e) -> pp f "@[<2>initializer@ %a@]%a" (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_attribute a -> floating_attribute ctxt f a | Pcf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pcf_attributes and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } = pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]" (fun f p -> match p.ppat_desc with | Ppat_any -> () | Ppat_constraint _ -> pp f " %a" (pattern ctxt) p | _ -> pp f " (%a)" (pattern ctxt) p) p (list (class_field ctxt)) l and class_expr ctxt f x = if x.pcl_attributes <> [] then begin pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]} (attributes ctxt) x.pcl_attributes end else match x.pcl_desc with | Pcl_structure (cs) -> class_structure ctxt f cs | Pcl_fun (l, eo, p, e) -> pp f "fun@ %a@ ->@ %a" (label_exp ctxt) (l,eo,p) (class_expr ctxt) e | Pcl_let (rf, l, ce) -> pp f "%a@ in@ %a" (bindings ctxt) (rf,l) (class_expr ctxt) ce | Pcl_apply (ce, l) -> Cf : # 7200 (class_expr ctxt) ce (list (label_x_expression_param ctxt)) l | Pcl_constr (li, l) -> pp f "%a%a" (fun f l-> if l <>[] then pp f "[%a]@ " (list (core_type ctxt) ~sep:",") l) l longident_loc li | Pcl_constraint (ce, ct) -> pp f "(%a@ :@ %a)" (class_expr ctxt) ce (class_type ctxt) ct | Pcl_extension e -> extension ctxt f e | Pcl_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_expr ctxt) e and module_type ctxt f x = if x.pmty_attributes <> [] then begin pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]} (attributes ctxt) x.pmty_attributes end else match x.pmty_desc with | Pmty_functor (Unit, mt2) -> pp f "@[<hov2>functor () ->@ %a@]" (module_type ctxt) mt2 | Pmty_functor (Named (s, mt1), mt2) -> begin match s.txt with | None -> pp f "@[<hov2>%a@ ->@ %a@]" (module_type1 ctxt) mt1 (module_type ctxt) mt2 | Some name -> pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" name (module_type ctxt) mt1 (module_type ctxt) mt2 end | Pmty_with (mt, []) -> module_type ctxt f mt | Pmty_with (mt, l) -> let with_constraint f = function | Pwith_type (li, ({ptype_params= ls ;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a =@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_module (li, li2) -> pp f "module %a =@ %a" longident_loc li longident_loc li2; | Pwith_typesubst (li, ({ptype_params=ls;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a :=@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_modsubst (li, li2) -> pp f "module %a :=@ %a" longident_loc li longident_loc li2 in pp f "@[<hov2>%a@ with@ %a@]" (module_type1 ctxt) mt (list with_constraint ~sep:"@ and@ ") l | _ -> module_type1 ctxt f x and module_type1 ctxt f x = if x.pmty_attributes <> [] then module_type ctxt f x else match x.pmty_desc with | Pmty_ident li -> pp f "%a" longident_loc li; | Pmty_alias li -> pp f "(module %a)" longident_loc li; | Pmty_signature (s) -> | Pmty_typeof me -> pp f "@[<hov2>module@ type@ of@ %a@]" (module_expr ctxt) me | Pmty_extension e -> extension ctxt f e | _ -> paren true (module_type ctxt) f x and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x and signature_item ctxt f x : unit = match x.psig_desc with | Psig_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Psig_typesubst l -> type_def_list ctxt f (Nonrecursive, false, l) | Psig_value vd -> let intro = if vd.pval_prim = [] then "val" else "external" in pp f "@[<2>%s@ %a@ :@ %a@]%a" intro protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Psig_typext te -> type_extension ctxt f te | Psig_exception ed -> exception_declaration ctxt f ed | Psig_class l -> let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) = pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_description "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_description "class") x (list ~sep:"@," (class_description "and")) xs end | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias; pmty_attributes=[]; _};_} as pmd) -> pp f "@[<hov>module@ %s@ =@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") longident_loc alias (item_attributes ctxt) pmd.pmd_attributes | Psig_module pmd -> pp f "@[<hov>module@ %s@ :@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes | Psig_modsubst pms -> pp f "@[<hov>module@ %s@ :=@ %a@]%a" pms.pms_name.txt longident_loc pms.pms_manifest (item_attributes ctxt) pms.pms_attributes | Psig_open od -> pp f "@[<hov2>open%s@ %a@]%a" (override od.popen_override) longident_loc od.popen_expr (item_attributes ctxt) od.popen_attributes | Psig_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_type ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Psig_class_type (l) -> class_type_declaration_list ctxt f l | Psig_recmodule decls -> let rec string_x_module_type_list f ?(first=true) l = match l with | [] -> () ; | pmd :: tl -> if not first then pp f "@ @[<hov2>and@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes else pp f "@[<hov2>module@ rec@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes; string_x_module_type_list f ~first:false tl in string_x_module_type_list f decls | Psig_attribute a -> floating_attribute ctxt f a | Psig_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and module_expr ctxt f x = if x.pmod_attributes <> [] then pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]} (attributes ctxt) x.pmod_attributes else match x.pmod_desc with | Pmod_structure (s) -> pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]" (list (structure_item ctxt) ~sep:"@\n") s; | Pmod_constraint (me, mt) -> pp f "@[<hov2>(%a@ :@ %a)@]" (module_expr ctxt) me (module_type ctxt) mt | Pmod_ident (li) -> pp f "%a" longident_loc li; | Pmod_functor (Unit, me) -> pp f "functor ()@;->@;%a" (module_expr ctxt) me | Pmod_functor (Named (s, mt), me) -> pp f "functor@ (%s@ :@ %a)@;->@;%a" (Option.value s.txt ~default:"_") (module_type ctxt) mt (module_expr ctxt) me | Pmod_apply (me1, me2) -> pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2 Cf : # 7200 | Pmod_unpack e -> pp f "(val@ %a)" (expression ctxt) e | Pmod_extension e -> extension ctxt f e and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x and payload ctxt f = function | PStr [{pstr_desc = Pstr_eval (e, attrs)}] -> pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | PStr x -> structure ctxt f x | PTyp x -> pp f ":"; core_type ctxt f x | PSig x -> pp f ":"; signature ctxt f x | PPat (x, None) -> pp f "?"; pattern ctxt f x | PPat (x, Some e) -> pp f "?"; pattern ctxt f x; pp f " when "; expression ctxt f e and binding ctxt f {pvb_pat=p; pvb_expr=x; _} = let rec pp_print_pexp_function f x = if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x else match x.pexp_desc with | Pexp_fun (label, eo, p, e) -> if label=Nolabel then pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e else pp f "%a@ %a" (label_exp ctxt) (label,eo,p) pp_print_pexp_function e | Pexp_newtype (str,e) -> pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e | _ -> pp f "=@;%a" (expression ctxt) x in let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in let is_desugared_gadt p e = let gadt_pattern = match p with | {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _} as pat, {ptyp_desc=Ptyp_poly (args_tyvars, rt)}); ppat_attributes=[]}-> Some (pat, args_tyvars, rt) | _ -> None in let rec gadt_exp tyvars e = match e with | {pexp_desc=Pexp_newtype (tyvar, e); pexp_attributes=[]} -> gadt_exp (tyvar :: tyvars) e | {pexp_desc=Pexp_constraint (e, ct); pexp_attributes=[]} -> Some (List.rev tyvars, e, ct) | _ -> None in let gadt_exp = gadt_exp [] e in match gadt_pattern, gadt_exp with | Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct) when tyvars_str pt_tyvars = tyvars_str e_tyvars -> let ety = Typ.varify_constructors e_tyvars e_ct in if ety = pt_ct then Some (p, pt_tyvars, e_ct, e) else None | _ -> None in if x.pexp_attributes <> [] then pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x else match is_desugared_gadt p x with | Some (p, [], ct, e) -> pp f "%a@;: %a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ct (expression ctxt) e | Some (p, tyvars, ct, e) -> begin pp f "%a@;: type@;%a.@;%a@;=@;%a" (simple_pattern ctxt) p (list pp_print_string ~sep:"@;") (tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e end | None -> begin match p with | {ppat_desc=Ppat_constraint(p ,ty); special case for the first begin match ty with | {ptyp_desc=Ptyp_poly _; ptyp_attributes=[]} -> pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x | _ -> pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x end | {ppat_desc=Ppat_var _; ppat_attributes=[]} -> pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x end and bindings ctxt f (rf,l) = let binding kwd rf f x = pp f "@[<2>%s %a%a@]%a" kwd rec_flag rf (binding ctxt) x (item_attributes ctxt) x.pvb_attributes in match l with | [] -> () | [x] -> binding "let" rf f x | x::xs -> pp f "@[<v>%a@,%a@]" (binding "let" rf) x (list ~sep:"@," (binding "and" Nonrecursive)) xs and binding_op ctxt f x = pp f "@[<2>%s %a@;=@;%a@]" x.pbop_op.txt (pattern ctxt) x.pbop_pat (expression ctxt) x.pbop_exp and structure_item ctxt f x = match x.pstr_desc with | Pstr_eval (e, attrs) -> pp f "@[<hov2>;;%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | Pstr_type (_, []) -> assert false | Pstr_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Pstr_value (rf, l) -> pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l pp f "@[<2>%a@]" (bindings ctxt) (rf,l) | Pstr_typext te -> type_extension ctxt f te | Pstr_exception ed -> exception_declaration ctxt f ed | Pstr_module x -> let rec module_helper = function | {pmod_desc=Pmod_functor(arg_opt,me'); pmod_attributes = []} -> begin match arg_opt with | Unit -> pp f "()" | Named (s, mt) -> pp f "(%s:%a)" (Option.value s.txt ~default:"_") (module_type ctxt) mt end; module_helper me' | me -> me in pp f "@[<hov2>module %s%a@]%a" (Option.value x.pmb_name.txt ~default:"_") (fun f me -> let me = module_helper me in match me with | {pmod_desc= Pmod_constraint (me', ({pmty_desc=(Pmty_ident (_) | Pmty_signature (_));_} as mt)); pmod_attributes = []} -> pp f " :@;%a@;=@;%a@;" (module_type ctxt) mt (module_expr ctxt) me' | _ -> pp f " =@ %a" (module_expr ctxt) me ) x.pmb_expr (item_attributes ctxt) x.pmb_attributes | Pstr_open od -> pp f "@[<2>open%s@;%a@]%a" (override od.popen_override) (module_expr ctxt) od.popen_expr (item_attributes ctxt) od.popen_attributes | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Pstr_class l -> let extract_class_args cl = let rec loop acc = function | {pcl_desc=Pcl_fun (l, eo, p, cl'); pcl_attributes = []} -> loop ((l,eo,p) :: acc) cl' | cl -> List.rev acc, cl in let args, cl = loop [] cl in let constr, cl = match cl with | {pcl_desc=Pcl_constraint (cl', ct); pcl_attributes = []} -> Some ct, cl' | _ -> None, cl in args, constr, cl in let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in let class_declaration kwd f ({pci_params=ls; pci_name={txt;_}; _} as x) = let args, constr, cl = extract_class_args x.pci_expr in pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (list (label_exp ctxt)) args (option class_constraint) constr (class_expr ctxt) cl (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_declaration "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_declaration "class") x (list ~sep:"@," (class_declaration "and")) xs end | Pstr_class_type l -> class_type_declaration_list ctxt f l | Pstr_primitive vd -> pp f "@[<hov2>external@ %a@ :@ %a@]%a" protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Pstr_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_expr ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes 3.07 let aux f = function | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) -> pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes | pmb -> pp f "@[<hov2>@ and@ %s@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes in begin match decls with | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | pmb :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | _ -> assert false end | Pstr_attribute a -> floating_attribute ctxt f a | Pstr_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and type_param ctxt f (ct, a) = pp f "%s%a" (type_variance a) (core_type ctxt) ct and type_params ctxt f = function | [] -> () | l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",@;") l and type_def_list ctxt f (rf, exported, l) = let type_decl kwd rf f x = let eq = if (x.ptype_kind = Ptype_abstract) && (x.ptype_manifest = None) then "" else if exported then " =" else " :=" in pp f "@[<2>%s %a%a%s%s%a@]%a" kwd nonrec_flag rf (type_params ctxt) x.ptype_params x.ptype_name.txt eq (type_declaration ctxt) x (item_attributes ctxt) x.ptype_attributes in match l with | [] -> assert false | [x] -> type_decl "type" rf f x | x :: xs -> pp f "@[<v>%a@,%a@]" (type_decl "type" rf) x (list ~sep:"@," (type_decl "and" Recursive)) xs and record_declaration ctxt f lbls = let type_record_field f pld = pp f "@[<2>%a%s:@;%a@;%a@]" mutable_flag pld.pld_mutable pld.pld_name.txt (core_type ctxt) pld.pld_type (attributes ctxt) pld.pld_attributes in pp f "{@\n%a}" (list type_record_field ~sep:";@\n" ) lbls and type_declaration ctxt f x = let priv f = match x.ptype_private with | Public -> () | Private -> pp f "@;private" in let manifest f = match x.ptype_manifest with | None -> () | Some y -> if x.ptype_kind = Ptype_abstract then pp f "%t@;%a" priv (core_type ctxt) y else pp f "@;%a" (core_type ctxt) y in let constructor_declaration f pcd = pp f "|@;"; constructor_declaration ctxt f (pcd.pcd_name.txt, pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes) in let repr f = let intro f = if x.ptype_manifest = None then () else pp f "@;=" in match x.ptype_kind with | Ptype_variant xs -> let variants fmt xs = if xs = [] then pp fmt " |" else pp fmt "@\n%a" (list ~sep:"@\n" constructor_declaration) xs in pp f "%t%t%a" intro priv variants xs | Ptype_abstract -> () | Ptype_record l -> pp f "%t%t@;%a" intro priv (record_declaration ctxt) l | Ptype_open -> pp f "%t%t@;.." intro priv in let constraints f = List.iter (fun (ct1,ct2,_) -> pp f "@[<hov2>@ constraint@ %a@ =@ %a@]" (core_type ctxt) ct1 (core_type ctxt) ct2) x.ptype_cstrs in pp f "%t%t%t" manifest repr constraints and type_extension ctxt f x = let extension_constructor f x = pp f "@\n|@;%a" (extension_constructor ctxt) x in pp f "@[<2>type %a%a += %a@ %a@]%a" (fun f -> function | [] -> () | l -> pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l) x.ptyext_params longident_loc x.ptyext_path Cf : # 7200 (list ~sep:"" extension_constructor) x.ptyext_constructors (item_attributes ctxt) x.ptyext_attributes and constructor_declaration ctxt f (name, args, res, attrs) = let name = match name with | "::" -> "(::)" | s -> s in match res with | None -> pp f "%s%a@;%a" name (fun f -> function | Pcstr_tuple [] -> () | Pcstr_tuple l -> pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l | Pcstr_record l -> pp f "@;of@;%a" (record_declaration ctxt) l ) args (attributes ctxt) attrs | Some r -> pp f "%s:@;%a@;%a" name (fun f -> function | Pcstr_tuple [] -> core_type1 ctxt f r | Pcstr_tuple l -> pp f "%a@;->@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l (core_type1 ctxt) r | Pcstr_record l -> pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r ) args (attributes ctxt) attrs and extension_constructor ctxt f x = Cf : # 7200 match x.pext_kind with | Pext_decl(l, r) -> constructor_declaration ctxt f (x.pext_name.txt, l, r, x.pext_attributes) | Pext_rebind li -> pp f "%s%a@;=@;%a" x.pext_name.txt (attributes ctxt) x.pext_attributes longident_loc li and case_list ctxt f l : unit = let aux f {pc_lhs; pc_guard; pc_rhs} = pp f "@;| @[<2>%a%a@;->@;%a@]" (pattern ctxt) pc_lhs (option (expression ctxt) ~first:"@;when@;") pc_guard (expression (under_pipe ctxt)) pc_rhs in list aux f l ~sep:"" and label_x_expression_param ctxt f (l,e) = let simple_name = match e with | {pexp_desc=Pexp_ident {txt=Lident l;_}; pexp_attributes=[]} -> Some l | _ -> None in match l with level 2 | Optional str -> if Some str = simple_name then pp f "?%s" str else pp f "?%s:%a" str (simple_expr ctxt) e | Labelled lbl -> if Some lbl = simple_name then pp f "~%s" lbl else pp f "~%s:%a" lbl (simple_expr ctxt) e and directive_argument f x = match x.pdira_desc with | Pdir_string (s) -> pp f "@ %S" s | Pdir_int (n, None) -> pp f "@ %s" n | Pdir_int (n, Some m) -> pp f "@ %s%c" n m | Pdir_ident (li) -> pp f "@ %a" longident li | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b) let toplevel_phrase f x = match x with | Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s pp_close_box f ( ) ; | Ptop_dir {pdir_name; pdir_arg = None; _} -> pp f "@[<hov2>#%s@]" pdir_name.txt | Ptop_dir {pdir_name; pdir_arg = Some pdir_arg; _} -> pp f "@[<hov2>#%s@ %a@]" pdir_name.txt directive_argument pdir_arg let expression f x = pp f "@[%a@]" (expression reset_ctxt) x let string_of_expression x = ignore (flush_str_formatter ()) ; let f = str_formatter in expression f x; flush_str_formatter () let string_of_structure x = ignore (flush_str_formatter ()); let f = str_formatter in structure reset_ctxt f x; flush_str_formatter () let top_phrase f x = pp_print_newline f (); toplevel_phrase f x; pp f ";;"; pp_print_newline f () let core_type = core_type reset_ctxt let pattern = pattern reset_ctxt let signature = signature reset_ctxt let structure = structure reset_ctxt
d2f84354ff1b205aa0ad792ec4209b6488606f19cca847b033a7b90e0c69fc29
FlowerWrong/mblog
bertie.erl
%% --- Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit for more book information. %%--- -module(bertie). -export([start/0]). start() -> Handle = bitcask:open("bertie_database", [read_write]), N = fetch(Handle), store(Handle, N+1), io:format("Bertie has been run ~p times~n",[N]), bitcask:close(Handle), init:stop(). store(Handle, N) -> bitcask:put(Handle, <<"bertie_executions">>, term_to_binary(N)). fetch(Handle) -> case bitcask:get(Handle, <<"bertie_executions">>) of not_found -> 1; {ok, Bin} -> binary_to_term(Bin) end.
null
https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/bertie/bertie.erl
erlang
--- Copyrights apply to this code. It may not be used to create training material, courses, books, articles, and the like. Contact us if you are in doubt. We make no guarantees that this code is fit for any purpose. Visit for more book information. ---
Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . -module(bertie). -export([start/0]). start() -> Handle = bitcask:open("bertie_database", [read_write]), N = fetch(Handle), store(Handle, N+1), io:format("Bertie has been run ~p times~n",[N]), bitcask:close(Handle), init:stop(). store(Handle, N) -> bitcask:put(Handle, <<"bertie_executions">>, term_to_binary(N)). fetch(Handle) -> case bitcask:get(Handle, <<"bertie_executions">>) of not_found -> 1; {ok, Bin} -> binary_to_term(Bin) end.
19d03aeab337da01f0b82566333cb3144d7d2951eb72fd8faaea9eb8c4156d78
vikram/lisplibraries
stefil.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; Copyright ( c ) 2006 by the authors . ;;; ;;; See LICENCE for details. (in-package :stefil) #.(file-header) Warning : setf - ing these variables in not a smart idea because other systems may rely on their default value . It 's smarter to rebind them in an : around method from your .asd or shadow stefil : deftest with your own that sets ;; their keyword counterparts. (defvar *suite*) (defvar *root-suite*) (defvar *print-test-run-progress* #t) (defvar *compile-tests-before-run* #f) (defvar *compile-tests-with-debug-level* nil) (defvar *test-progress-print-right-margin* 80) (defvar *debug-on-unexpected-error* #t) (defvar *debug-on-assertion-failure* #t) (defvar *test-result-history* '()) (defvar *last-test-result* nil) (defvar *failures-and-errors-are-expected* #f) (defvar *tests* (make-hash-table :test 'eql)) ; this is not thread-safe, but... (defmacro without-debugging (&body body) `(bind ((*debug-on-unexpected-error* #f) (*debug-on-assertion-failure* #f)) ,@body)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; conditions (define-condition test-related-condition () ((test :initform nil :accessor test-of :initarg :test))) (define-condition test-style-warning (style-warning test-related-condition simple-warning) ()) (define-condition assertion-failed (test-related-condition error) ((failure-description :accessor failure-description-of :initarg :failure-description)) (:report (lambda (c stream) (format stream "Test assertion failed:~%~%") (describe (failure-description-of c) stream)))) (define-condition error-in-teardown (error) ((condition :accessor condition-of :initarg :condition) (fixture :accessor fixture-of :initarg :fixture)) (:report (lambda (c stream) (format stream "Error while running teardown of fixture ~A:~%~%~A" (fixture-of c) (condition-of c))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; some classes #+nil (defclass-star:defclass* testable () ((name :type symbol) (parent nil :initarg nil :type (or null testable)) (children (make-hash-table) :documentation "A mapping from testable names to testables") (auto-call #t :type boolean :documentation "Controls whether to automatically call this test when its parent suite is invoked. Enabled by default."))) (defclass testable () ((name :accessor name-of :initarg :name :type symbol) (parent :initform nil :accessor parent-of :type (or null testable)) (children :initform (make-hash-table) :accessor children-of :initarg :children :documentation "A mapping from testable names to testables") (auto-call :initform t :accessor auto-call-p :initarg :auto-call :type boolean :documentation "Controls whether to automatically call this test when its parent suite is invoked. Enabled by default."))) (defprint-object (self testable :identity #f :type #f) (format t "test ~S" (name-of self)) (bind ((children (count-tests self))) (unless (zerop children) (format t " :tests ~S" children)))) (defmethod shared-initialize :after ((self testable) slot-names &key (in (or (parent-of self) (and (boundp '*suite*) *suite*)))) (assert (name-of self)) (setf (find-test (name-of self)) self) ;; make sure the specialized writer below is triggered (setf (parent-of self) in)) (defmethod (setf parent-of) :around (new-parent (self testable)) (assert (typep new-parent '(or null testable))) (when (and new-parent leave alone tests named by uninterned symbols (not (eq new-parent *root-suite*)) (not (eq (symbol-package (name-of new-parent)) (symbol-package (name-of self))))) (warn 'test-style-warning :test self :format-control "Adding test under parent ~S which is in a different package (parent: ~A, child: ~A). Maybe a missing (in-root-suite)?" :format-arguments (list new-parent (symbol-package (name-of new-parent)) (symbol-package (name-of self))))) (bind ((old-parent (parent-of self))) (when old-parent (remhash (name-of self) (children-of old-parent))) (prog1 (call-next-method) (when new-parent (setf (gethash (name-of self) (children-of new-parent)) self))))) (defgeneric count-tests (testable) (:method ((self testable)) (+ (hash-table-count (children-of self)) (iter (for (nil child) :in-hashtable (children-of self)) (summing (count-tests child)))))) #+nil(defclass-star:defclass* test (testable) ((package nil) (lambda-list nil) (compile-before-run #t :type boolean) (declarations nil) (documentation nil) (body nil))) (defclass test (testable) ((package :initform nil :accessor package-of :initarg :package) (lambda-list :initform nil :accessor lambda-list-of :initarg :lambda-list) (compile-before-run :initform t :accessor compile-before-run-p :initarg :compile-before-run :type boolean) (declarations :initform nil :accessor declarations-of :initarg :declarations) (documentation :initform nil :accessor documentation-of :initarg :documentation) (body :initform nil :accessor body-of :initarg :body))) (defun make-test (name &rest args &key &allow-other-keys) (apply #'make-instance 'test :name name args)) (defun make-suite (name &rest args &key &allow-other-keys) (apply #'make-instance 'test :name name args)) #+nil (defclass-star:defclass* failure-description () ((test-context-backtrace) (progress-char #\X :allocation :class) (expected *failures-and-errors-are-expected* :type boolean))) (defclass failure-description () ((test-context-backtrace :accessor test-context-backtrace-of :initarg :test-context-backtrace) (progress-char :initform #\X :accessor progress-char-of :initarg :progress-char :allocation :class) (expected :initform *failures-and-errors-are-expected* :accessor expected-p :initarg :expected :type boolean))) #+nil (defclass-star:defclass* failed-assertion (failure-description) ((form) (format-control) (format-arguments))) (defclass failed-assertion (failure-description) ((form :accessor form-of :initarg :form) (format-control :accessor format-control-of :initarg :format-control) (format-arguments :accessor format-arguments-of :initarg :format-arguments))) (defmethod describe-object ((self failed-assertion) stream) (let ((*print-circle* nil)) (apply #'format stream (format-control-of self) (format-arguments-of self)))) (defprint-object (self failed-assertion :identity #f :type #f) (format t "failure ~S backtrace: ~{~A~^,~}" (form-of self) (mapcar (compose #'name-of #'test-of) (test-context-backtrace-of self)))) #+nil (defclass-star:defclass* missing-condition (failure-description) ((form) (condition))) (defclass missing-condition (failure-description) ((form :accessor form-of :initarg :form) (condition :accessor condition-of :initarg :condition))) (defmethod describe-object ((self missing-condition) stream) (let ((*print-circle* nil)) (format stream "~S failed to signal condition ~S" (form-of self) (condition-of self)))) #+nil (defclass-star:defclass* unexpected-error (failure-description) ((condition) (progress-char #\E :allocation :class))) (defclass unexpected-error (failure-description) ((condition :accessor condition-of :initarg :condition) (progress-char :initform #\E :accessor progress-char-of :initarg :progress-char :allocation :class))) (defprint-object (self unexpected-error :identity #f :type #f) (format t "error ~{~A~^,~}: ~S" (mapcar (compose #'name-of #'test-of) (reverse (test-context-backtrace-of self))) (condition-of self))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; test repository (defun find-test (name &key (otherwise :error)) (bind (((:values test found-p) (if (typep name 'testable) (values name t) (gethash name *tests*)))) (when (and (not found-p) otherwise) (etypecase otherwise (symbol (ecase otherwise (:error (error "Testable called ~A was not found" name)))) (function (funcall otherwise)) (t (setf test otherwise)))) (values test found-p))) (defun (setf find-test) (new-value key) (if new-value (progn (when (gethash key *tests*) (warn 'test-style-warning :format-control "redefining test ~A" :format-arguments (list (let ((*package* #.(find-package "KEYWORD"))) (format nil "~S" key))))) (setf (gethash key *tests*) new-value)) (rem-test key))) (defun rem-test (name &rest args) (bind ((test (apply #'find-test name args)) (parent (when test (parent-of test)))) (when test (assert (or (not (eq *suite* test)) (parent-of test)) () "You can not remove a test which is the current suite and has no parent") (remhash name *tests*) (setf (parent-of test) nil) (fmakunbound (name-of test)) (iter (for (nil subtest) :in-hashtable (children-of test)) (rem-test (name-of subtest))) (when (eq *suite* test) (setf *suite* parent))) test)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; the real thing #+nil (define-dynamic-context* global-context ((failure-descriptions (make-array 8 :adjustable #t :fill-pointer 0)) (assertion-count 0) (progress-char-count 0) (print-test-run-progress-p *print-test-run-progress* :type boolean) (debug-on-unexpected-error-p *debug-on-unexpected-error* :type boolean) (debug-on-assertion-failure-p *debug-on-assertion-failure* :type boolean) (toplevel-context nil) (current-test nil) (run-tests (make-hash-table) :documentation "test -> context mapping") (run-fixtures (make-hash-table)) (test-lambdas (make-hash-table) :documentation "test -> compiled test lambda mapping for this test run"))) (define-dynamic-context global-context ((failure-descriptions :initform (make-array 8 :adjustable t :fill-pointer 0) :accessor failure-descriptions-of :initarg :failure-descriptions) (assertion-count :initform 0 :accessor assertion-count-of :initarg :assertion-count) (progress-char-count :initform 0 :accessor progress-char-count-of :initarg :progress-char-count) (print-test-run-progress-p :initform *print-test-run-progress* :accessor print-test-run-progress-p :initarg :print-test-run-progress-p :type boolean) (debug-on-unexpected-error-p :initform *debug-on-unexpected-error* :accessor debug-on-unexpected-error-p :initarg :debug-on-unexpected-error-p :type boolean) (debug-on-assertion-failure-p :initform *debug-on-assertion-failure* :accessor debug-on-assertion-failure-p :initarg :debug-on-assertion-failure-p :type boolean) (toplevel-context :initform nil :accessor toplevel-context-of :initarg :toplevel-context) (current-test :initform nil :accessor current-test-of :initarg :current-test) (run-tests :initform (make-hash-table) :accessor run-tests-of :initarg :run-tests :documentation "test -> context mapping") (run-fixtures :initform (make-hash-table) :accessor run-fixtures-of :initarg :run-fixtures) (test-lambdas :initform (make-hash-table) :accessor test-lambdas-of :initarg :test-lambdas :documentation "test -> compiled test lambda mapping for this test run"))) (defprint-object (self global-context :identity #f :type #f) (format t "test-run: ~A tests, ~A assertions, ~A failures (~A expected) in ~A sec" (hash-table-count (run-tests-of self)) (assertion-count-of self) (length (failure-descriptions-of self)) (count-if 'expected-p (failure-descriptions-of self)) (bind ((toplevel-context (toplevel-context-of self)) (real-time-spent-in-seconds (when toplevel-context (real-time-spent-in-seconds toplevel-context)))) (if (and toplevel-context real-time-spent-in-seconds) real-time-spent-in-seconds "?")))) (defmacro without-test-progress-printing (&body body) (with-unique-names (old-state) `(let ((,old-state (print-test-run-progress-p *global-context*))) (unwind-protect (progn (setf (print-test-run-progress-p *global-context*) #f) ,@body) (setf (print-test-run-progress-p *global-context*) ,old-state))))) (defmacro with-toplevel-restarts (&body body) `(block restart-wrapper (restart-bind ((continue-without-debugging (lambda () (setf (debug-on-unexpected-error-p *global-context*) #f) (setf (debug-on-assertion-failure-p *global-context*) #f) (continue)) :report-function (lambda (stream) (format stream "~@<Turn off debugging for this test session and invoke the first CONTINUE restart~@:>"))) (abort-testing (lambda () (return-from restart-wrapper)) :report-function (lambda (stream) (format stream "~@<Abort the entire test session~@:>")))) (bind ((swank::*sldb-quit-restart* 'abort-testing)) ,@body)))) (defun test-was-run-p (test) (declare (type testable test)) (and (gethash test (run-tests-of *global-context*)) (not (eq (current-test-of *global-context*) test)))) (defun register-test-being-run (test) (declare (type testable test)) (setf (gethash test (run-tests-of *global-context*)) (current-context)) (setf (current-test-of *global-context*) test)) (defgeneric get-test-lambda (test global-context) (:method ((test test) (context global-context)) (bind (((:values test-lambda found-p) (gethash test (test-lambdas-of context)))) (unless found-p (setf test-lambda (bind ((*package* (package-of test)) (*readtable* (copy-readtable))) (compile nil `(lambda ,(lambda-list-of test) ,@(body-of test))))) (setf (gethash test (test-lambdas-of context)) test-lambda)) test-lambda))) #+nil (define-dynamic-context* context ((test) (internal-realtime-spent-with-test nil) (test-arguments) (number-of-added-failure-descriptions 0)) :chain-parents #t) (define-dynamic-context context ((test :accessor test-of :initarg :test) (internal-realtime-spent-with-test :initform nil :accessor internal-realtime-spent-with-test-of :initarg :internal-realtime-spent-with-test) (test-arguments :accessor test-arguments-of :initarg :test-arguments) (number-of-added-failure-descriptions :initform 0 :accessor number-of-added-failure-descriptions-of :initarg :number-of-added-failure-descriptions)) :chain-parents #t) (defprint-object (self context :identity #f :type #f) (format t "test-run ~@<(~S~{~^ ~S~})~@:>" (name-of (test-of self)) (bind ((result (lambda-list-to-funcall-list (lambda-list-of (test-of self))))) (mapcar (lambda (arg-cell) (setf result (substitute (cdr arg-cell) (car arg-cell) result :test #'eq))) (test-arguments-of self)) result))) (defgeneric real-time-spent-in-seconds (context) (:method ((self context)) (awhen (internal-realtime-spent-with-test-of self) (coerce (/ it internal-time-units-per-second) 'float)))) (defmacro run-failed-tests (&optional (test-result-place '*last-test-result*)) `(with-new-global-context () (if (> (length (failure-descriptions-of ,test-result-place)) 0) (progn (%run-failed-tests ,test-result-place) (push *global-context* *test-result-history*) (setf *last-test-result* *global-context*) (setf ,test-result-place *global-context*)) (progn (warn "There are no failed tests in ~S" ',test-result-place) (values))))) (defun %run-failed-tests (global-context-to-be-processed) (warn "Re-running failed tests without considering their dynamic environment, which may affect their behaviour!") (with-toplevel-restarts (iter (for failure :in-sequence (failure-descriptions-of global-context-to-be-processed)) (for context = (elt (test-context-backtrace-of failure) 0)) (apply (name-of (test-of context)) (mapcar #'cdr (test-arguments-of context)))) (when (print-test-run-progress-p *global-context*) (terpri *debug-io*)))) (defun run-test-body-in-handlers (test function) (declare (type test test) (type function function)) (register-test-being-run test) (labels ((prune-failure-descriptions () ;; drop failures recorded by the previous run of this test (loop repeat (number-of-added-failure-descriptions-of *context*) do (vector-pop (failure-descriptions-of *global-context*))) (setf (number-of-added-failure-descriptions-of *context*) 0)) (run-test-body () (handler-bind ((assertion-failed (lambda (c) (declare (ignore c)) (unless (debug-on-assertion-failure-p *global-context*) (continue)))) (error (lambda (c) (unless (typep c 'assertion-failed) (record-failure* 'unexpected-error :description-initargs (list :condition c) :signal-assertion-failed #f) (when (debug-on-unexpected-error-p *global-context*) (invoke-debugger c)) (return-from run-test-body))))) (restart-case (bind ((*package* (package-of test)) (*readtable* (copy-readtable)) (start-time (get-internal-run-time))) (multiple-value-prog1 (funcall function) (setf (internal-realtime-spent-with-test-of *context*) (- (get-internal-run-time) start-time)))) (continue () :report (lambda (stream) (format stream "~@<Skip the rest of the test ~S and continue by returning (values)~@:>" (name-of test))) (values)) (retest () :report (lambda (stream) (format stream "~@<Rerun the test ~S~@:>" (name-of test))) ;; TODO: this will only prune the failures that were recorded in the current context. ;; in case of nesting it will leave alone the failures recorded in deeper levels. (prune-failure-descriptions) (return-from run-test-body (run-test-body))))))) (run-test-body))) (defun run-test-body (test function arguments toplevel-p) (declare (type test test)) (bind ((result-values '())) (flet ((body () (with-new-context (:test test :test-arguments arguments) (when toplevel-p (setf (toplevel-context-of *global-context*) (current-context))) (setf result-values (multiple-value-list (run-test-body-in-handlers test function)))))) (if toplevel-p (with-toplevel-restarts (body)) (body)) (if toplevel-p (progn (when (print-test-run-progress-p *global-context*) (terpri *debug-io*)) (if result-values (values-list (append result-values (list *global-context*))) *global-context*)) (values-list result-values))))) (defmacro deftest (&whole whole name args &body body) (bind (((:values remaining-forms declarations documentation) (parse-body body :documentation #t :whole whole)) ((name &rest test-args &key (compile-before-run *compile-tests-before-run*) in &allow-other-keys) (ensure-list name)) (in-p (get-properties test-args '(:in)))) (remove-from-plistf test-args :in) (unless (or (not (symbol-package name)) (eq (symbol-package name) *package*)) (warn 'test-style-warning :test name :format-control "Defining test on symbol ~S whose home package is not *package* which is ~A" :format-arguments (list name *package*))) (with-unique-names (test test-lambda global-context toplevel-p body) `(progn (eval-when (:load-toplevel :execute) (make-test ',name :package ,*package* :lambda-list ',args :declarations ',declarations :documentation ',documentation :body ',remaining-forms ,@(when in-p (if in `(:in (find-test ',in)) '(:in nil))) ,@test-args)) (defun ,name ,args ,@(when documentation (list documentation)) ,@declarations ,@(awhen *compile-tests-with-debug-level* `((declare (optimize (debug ,it))))) (bind ((,test (find-test ',name)) (,toplevel-p (not (has-global-context))) (,global-context (unless ,toplevel-p (current-global-context)))) ;; for convenience we define a function in a LABELS with the test name, so the debugger shows it in the backtrace (labels (,@(unless compile-before-run `((,name () ,@remaining-forms))) (,body () ,(if compile-before-run `(bind ((,test-lambda (get-test-lambda ,test ,global-context))) (run-test-body ,test (lambda () TODO install a labels entry with the test name ? to avoid compile at each recursion ... ,(lambda-list-to-funcall-expression test-lambda args)) ,(lambda-list-to-value-list-expression args) ,toplevel-p)) `(run-test-body ,test #',name ,(lambda-list-to-value-list-expression args) ,toplevel-p)))) (declare (dynamic-extent ,@(unless compile-before-run `(#',name)) #',body)) (if ,toplevel-p (with-new-global-context () (setf ,global-context (current-global-context)) (push ,global-context *test-result-history*) (setf *last-test-result* ,global-context) (,body)) (,body))))))))) (defmacro defixture (name &body body) "Fixtures are defun's that only execute the :setup part of their body once per test session if there is any at the time of calling." (with-unique-names (global-context nesting-count phase) (bind (setup-body teardown-body) (iter (for entry :in body) (if (and (consp body) (member (first entry) '(:setup :teardown))) (ecase (first entry) (:setup (assert (not setup-body) () "Multiple :setup's for fixture ~S" name) (setf setup-body (rest entry))) (:teardown (assert (not teardown-body) () "Multiple :teardown's for fixture ~S" name) (setf teardown-body (rest entry)))) (progn (assert (and (not setup-body) (not teardown-body)) () "Error parsing body of fixture ~A" name) (setf setup-body body) (leave)))) `(defun ,name (&optional (,phase :setup)) (declare (optimize (debug 3))) (bind ((,global-context (and (has-global-context) (current-global-context))) (,nesting-count (or (and ,global-context (gethash ',name (run-fixtures-of ,global-context))) 0))) (assert (>= ,nesting-count 0)) (ecase ,phase (:setup (incf ,nesting-count) (prog1 (if (and ,global-context (> ,nesting-count 1)) #f (progn ,@setup-body #t)) (when ,global-context (setf (gethash ',name (run-fixtures-of ,global-context)) ,nesting-count)))) (:teardown (decf ,nesting-count) (prog1 (if (and ,global-context (> ,nesting-count 0)) #f (progn (setf ,nesting-count 0) ,@teardown-body #t)) (when ,global-context (setf (gethash ',name (run-fixtures-of ,global-context)) ,nesting-count)))))))))) (defmacro with-fixture (name &body body) (with-unique-names (whole-fixture-body) `(flet ((,whole-fixture-body () (,name :setup) (unwind-protect (progn ,@body) (block teardown-block (handler-bind ((serious-condition (lambda (c) (with-simple-restart (continue ,(let ((*package* (find-package :common-lisp))) (format nil "Skip teardown of ~S and continue" name))) (error 'error-in-teardown :condition c :fixture ',name)) (return-from teardown-block)))) (,name :teardown)))))) (declare (dynamic-extent ,whole-fixture-body)) (if (has-global-context) (,whole-fixture-body) (with-new-global-context () (,whole-fixture-body)))))) (defmacro with-fixtures (fixtures &body body) (if fixtures `(with-fixture ,(first fixtures) (with-fixtures ,(rest fixtures) ,@body)) `(progn ,@body))) (defun record-failure (description-type &rest args) (record-failure* description-type :description-initargs args)) (defun record-failure* (type &key (signal-assertion-failed #t) description-initargs) (bind ((description (apply #'make-instance type :test-context-backtrace (when (has-context) (iter (for context :first (current-context) :then (parent-context-of context)) (while context) (collect context))) description-initargs))) (if (and (has-global-context) (has-context)) (progn (vector-push-extend description (failure-descriptions-of *global-context*)) (incf (number-of-added-failure-descriptions-of *context*)) (write-progress-char (progress-char-of description)) (when signal-assertion-failed (restart-case (error 'assertion-failed :test (test-of *context*) :failure-description description) (continue () :report (lambda (stream) (format stream "~@<Roger, go on testing...~@:>")))))) (progn (describe description *debug-io*) (when *debug-on-assertion-failure* ; we have no *global-context* (restart-case (error 'assertion-failed :failure-description description) (continue () :report (lambda (stream) (format stream "~@<Ignore the failure and continue~@:>"))))))))) (defun extract-assert-expression-and-message (input-form) (bind ((negatedp #f) (predicate) (arguments '())) (labels ((process (form) (if (consp form) (case (first form) ((not) (assert (= (length form) 2)) (setf negatedp (not negatedp)) (process (second form))) (t (setf predicate (first form)) (setf arguments (rest form)))) (setf predicate form)))) (process input-form) (cond ((ignore-errors (macro-function predicate)) (values '() input-form "Macro expression ~A evaluated to false." (list `(quote ,input-form)))) ((ignore-errors (fdefinition predicate)) (cond ((= (length arguments) 0) (values '() input-form "Expression ~A evaluated to false." (list `(quote ,input-form)))) ((= (length arguments) 2) (with-unique-names (x y) (values `((,x ,(first arguments)) (,y ,(second arguments))) (if negatedp `(not (,predicate ,x ,y)) `(,predicate ,x ,y)) "Binary predicate ~A failed.~%~ x: ~S => ~S~%~ y: ~S => ~S" (list (if negatedp `(quote (not (,predicate x y))) `(quote (,predicate x y))) `(quote ,(first arguments)) x `(quote ,(second arguments)) y)))) (t (bind ((arg-values (mapcar (lambda (el) (unless (keywordp el) (gensym))) arguments)) (bindings (iter (for arg :in arguments) (for arg-value :in arg-values) (when arg-value (collect `(,arg-value ,arg))))) (expression-values (mapcar (lambda (arg-value argument) (or arg-value argument)) arg-values arguments)) (expression (if negatedp `(not (,predicate ,@expression-values)) `(,predicate ,@expression-values))) ((:values message message-args) (iter (with message = "Expression ~A evaluated to ~A") (for arg :in arguments) (for idx :upfrom 0) (for arg-value :in arg-values) (when arg-value (setf message (concatenate 'string message "~%~D: ~A => ~S")) (appending `(,idx (quote ,arg) ,arg-value) :into message-args)) (finally (return (values message message-args)))))) (values bindings expression message (nconc (list `(quote (,predicate ,@arguments)) (if negatedp "true" "false")) message-args)))))) (t (values '() input-form "Expression ~A evaluated to false." (list `(quote ,input-form)))))))) (defun write-progress-char (char) (bind ((global-context (when (boundp '*global-context*) *global-context*))) (when (and global-context (print-test-run-progress-p global-context)) (when (and (not (zerop (progress-char-count-of global-context))) (zerop (mod (progress-char-count-of global-context) *test-progress-print-right-margin*))) (terpri *debug-io*)) (incf (progress-char-count-of global-context))) (when (or (and global-context (print-test-run-progress-p global-context)) (and (not global-context) *print-test-run-progress*)) (write-char char *debug-io*)))) (defun register-assertion-was-successful () (write-progress-char #\.)) (defun register-assertion () (when (boundp '*global-context*) (incf (assertion-count-of *global-context*)))) (defmacro is (&whole whole form &optional (message nil message-p) &rest message-args) (bind (((:values bindings expression message message-args) (if message-p (values nil form message message-args) (extract-assert-expression-and-message form)))) (with-unique-names (result) `(progn (register-assertion) (bind ,bindings (bind ((,result (multiple-value-list ,expression))) (if (first ,result) (register-assertion-was-successful) (record-failure 'failed-assertion :form ',whole :format-control ,message :format-arguments (list ,@message-args))) (values-list ,result))))))) (defmacro signals (what &body body) (bind ((condition-type what)) (unless (symbolp condition-type) (error "SIGNALS expects a symbol as condition-type! (Is there a superfulous quote at ~S?)" condition-type)) `(progn (register-assertion) (block test-block (handler-bind ((,condition-type (lambda (c) (register-assertion-was-successful) (return-from test-block c)))) ,@body) (record-failure 'missing-condition :form (list* 'progn ',body) :condition ',condition-type) (values))))) (defmacro finishes (&body body) `(progn (register-assertion) (multiple-value-prog1 (progn ,@body) (register-assertion-was-successful)))) (defmacro runs-without-failure? (&body body) (with-unique-names (old-failure-count) `(bind ((,old-failure-count (length (failure-descriptions-of *global-context*)))) ,@body (= ,old-failure-count (length (failure-descriptions-of *global-context*)))))) (defmacro with-expected-failures (&body body) "Any failure inside the dynamic extent of this block is registered as an expected failure." `(bind ((*failures-and-errors-are-expected* #t)) ,@body)) ;;;;;;;;;;;;;;;;;;;;;;;; ;;; some utils (define-condition illegal-lambda-list (error) ((lambda-list :accessor lambda-list-of :initarg :lambda-list))) (defun illegal-lambda-list (lambda-list) (error 'illegal-lambda-list :lambda-list lambda-list)) (defun parse-lambda-list (lambda-list visitor &key macro) TODO finish macro lambda list parsing (declare (optimize (speed 3)) (type list lambda-list) (type (or symbol function) visitor)) (let ((args lambda-list)) (labels ((fail () (illegal-lambda-list lambda-list)) (ensure-list (list) (if (listp list) list (list list))) (process-&whole () (assert (eq (first args) '&whole)) (pop args) (unless macro (fail)) (let ((whole (pop args))) (unless whole (fail)) (funcall visitor '&whole whole whole)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&optional (entering-&optional)) (&body (process-&body)) (&environment (process-&environment)) ((&whole &aux &allow-other-keys) (fail)) (t (process-required)))) (process-&body () (assert (eq (first args) '&body)) (pop args) (unless macro (fail)) (let ((body (pop args))) (unless (null args) (fail)) (unless body (fail)) (funcall visitor '&body body body))) (process-&environment () (assert (eq (first args) '&environment)) (pop args) (unless macro (fail)) (let ((env (pop args))) (unless env (fail)) (funcall visitor '&environment env env)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&optional (entering-&optional)) (&body (process-&body)) (&aux (process-&aux)) ((&whole &environment &allow-other-keys) (fail)) (t (process-required)))) (process-required () (unless args (done)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&optional (entering-&optional)) (&body (process-&body)) (&environment (process-&environment)) ((&whole &allow-other-keys) (fail)) (&aux (entering-&aux)) (t (let ((arg (pop args))) (funcall visitor nil arg arg)) (process-required)))) (process-&rest () (assert (eq (first args) '&rest)) (pop args) (let ((rest (pop args))) (unless rest (fail)) (funcall visitor '&rest rest rest)) (unless args (done)) (case (first args) (&key (entering-&key)) (&environment (process-&environment)) ((&whole &optional &rest &body &allow-other-keys) (fail)) (&aux (entering-&aux)) (t (fail)))) (entering-&optional () (assert (eq (first args) '&optional)) (pop args) (process-&optional)) (process-&optional () (unless args (done)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&body (process-&body)) ((&whole &optional &environment &allow-other-keys) (fail)) (&aux (entering-&aux)) (t (let* ((arg (ensure-list (pop args))) (name (first arg)) (default (second arg))) (funcall visitor '&optional name arg nil default)) (process-&optional)))) (entering-&key () (assert (eq (first args) '&key)) (pop args) (process-&key)) (process-&key () (unless args (done)) (case (first args) (&allow-other-keys (funcall visitor '&allow-other-keys nil nil)) ((&key &optional &whole &environment &body) (fail)) (&aux (entering-&aux)) (t (let* ((arg (ensure-list (pop args))) (name-part (first arg)) (default (second arg)) (external-name (if (consp name-part) (progn (unless (= (length name-part) 2) (illegal-lambda-list lambda-list)) (first name-part)) (intern (symbol-name name-part) #.(find-package "KEYWORD")))) (local-name (if (consp name-part) (second name-part) name-part))) (funcall visitor '&key local-name arg external-name default)) (process-&key)))) (entering-&aux () (assert (eq (first args) '&aux)) (pop args) (process-&aux)) (process-&aux () (unless args (done)) (case (first args) ((&whole &optional &key &environment &allow-other-keys &aux &body) (fail)) (t (let ((arg (ensure-list (pop args)))) (funcall visitor '&aux (first arg) arg)) (process-&aux)))) (done () (return-from parse-lambda-list (values)))) (when args (case (first args) (&whole (process-&whole)) (t (process-required))))))) (defun lambda-list-to-funcall-list (args) (let ((result (list)) (rest-variable-name nil)) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry default)) (case kind (&key (push external-name result) (push name result)) (&allow-other-keys) (&rest (setf rest-variable-name name)) (t (push name result))))) (values (nreverse result) rest-variable-name))) (defun lambda-list-to-lambda-list-with-quoted-defaults (args) (let ((primaries (list)) (keywords (list)) (optionals (list)) (rest-variable-name nil) (allow-other-keys? nil)) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry)) (ecase kind (&key (push `((,external-name ,name) (quote ,default)) keywords)) (&optional (push `(,name ,default) optionals)) (&allow-other-keys (setf allow-other-keys? t)) (&rest (setf rest-variable-name name)) ((nil) (push name primaries))))) (values `(,@(nreverse primaries) ,@(when optionals (cons '&optional (nreverse optionals))) ,@(when keywords (cons '&key (nreverse keywords))) ,@(when allow-other-keys? (list '&allow-other-keys))) rest-variable-name))) (defun lambda-list-to-funcall-expression (function args) (multiple-value-bind (arg-list rest-variable) (lambda-list-to-funcall-list args) (if rest-variable `(apply ,function ,@arg-list ,rest-variable) `(funcall ,function ,@arg-list)))) (defun lambda-list-to-value-list-expression (args) `(list ,@(let ((result (list))) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry external-name default)) (case kind (&allow-other-keys) (t (push `(cons ',name ,name) result))))) (nreverse result)))) (defun lambda-list-to-variable-name-list (args &key macro include-specials) (let ((result (list)) (rest-variable-name nil) (whole-variable-name nil) (env-variable-name nil)) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry external-name default)) (case kind (&allow-other-keys ) (&environment (setf env-variable-name name) (when include-specials (push name result))) (&whole (setf whole-variable-name name) (when include-specials (push name result))) ((&rest &body) (setf rest-variable-name name) (when include-specials (push name result))) (t (push name result)))) :macro macro) (values (nreverse result) rest-variable-name whole-variable-name env-variable-name))) (defun funcall-test-with-feedback-message (test-function &rest args) "Run the given test non-interactively and print the results to *standard-output*. This function is ideal for ASDF:TEST-OP's." (aprog1 (without-debugging (apply test-function args)) (let ((*package* (find-package :common-lisp))) (format *standard-output* "The result of ~S is: ~A For more details run it from the REPL and use the customized Slime inspector to inspect the results (ASDF eats up the return values). Some inspector features may only be available when using the Slime branch at darcs get --lazy -lisp.net/project/cl-dwim/darcs/slime but the official Slime should also work fine.~%" test-function it))))
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/stefil/stefil.lisp
lisp
-*- mode: Lisp; Syntax: Common-Lisp; -*- See LICENCE for details. their keyword counterparts. this is not thread-safe, but... conditions some classes make sure the specialized writer below is triggered test repository the real thing drop failures recorded by the previous run of this test TODO: this will only prune the failures that were recorded in the current context. in case of nesting it will leave alone the failures recorded in deeper levels. for convenience we define a function in a LABELS with the test name, so the debugger shows it in the backtrace we have no *global-context* some utils
Copyright ( c ) 2006 by the authors . (in-package :stefil) #.(file-header) Warning : setf - ing these variables in not a smart idea because other systems may rely on their default value . It 's smarter to rebind them in an : around method from your .asd or shadow stefil : deftest with your own that sets (defvar *suite*) (defvar *root-suite*) (defvar *print-test-run-progress* #t) (defvar *compile-tests-before-run* #f) (defvar *compile-tests-with-debug-level* nil) (defvar *test-progress-print-right-margin* 80) (defvar *debug-on-unexpected-error* #t) (defvar *debug-on-assertion-failure* #t) (defvar *test-result-history* '()) (defvar *last-test-result* nil) (defvar *failures-and-errors-are-expected* #f) (defmacro without-debugging (&body body) `(bind ((*debug-on-unexpected-error* #f) (*debug-on-assertion-failure* #f)) ,@body)) (define-condition test-related-condition () ((test :initform nil :accessor test-of :initarg :test))) (define-condition test-style-warning (style-warning test-related-condition simple-warning) ()) (define-condition assertion-failed (test-related-condition error) ((failure-description :accessor failure-description-of :initarg :failure-description)) (:report (lambda (c stream) (format stream "Test assertion failed:~%~%") (describe (failure-description-of c) stream)))) (define-condition error-in-teardown (error) ((condition :accessor condition-of :initarg :condition) (fixture :accessor fixture-of :initarg :fixture)) (:report (lambda (c stream) (format stream "Error while running teardown of fixture ~A:~%~%~A" (fixture-of c) (condition-of c))))) #+nil (defclass-star:defclass* testable () ((name :type symbol) (parent nil :initarg nil :type (or null testable)) (children (make-hash-table) :documentation "A mapping from testable names to testables") (auto-call #t :type boolean :documentation "Controls whether to automatically call this test when its parent suite is invoked. Enabled by default."))) (defclass testable () ((name :accessor name-of :initarg :name :type symbol) (parent :initform nil :accessor parent-of :type (or null testable)) (children :initform (make-hash-table) :accessor children-of :initarg :children :documentation "A mapping from testable names to testables") (auto-call :initform t :accessor auto-call-p :initarg :auto-call :type boolean :documentation "Controls whether to automatically call this test when its parent suite is invoked. Enabled by default."))) (defprint-object (self testable :identity #f :type #f) (format t "test ~S" (name-of self)) (bind ((children (count-tests self))) (unless (zerop children) (format t " :tests ~S" children)))) (defmethod shared-initialize :after ((self testable) slot-names &key (in (or (parent-of self) (and (boundp '*suite*) *suite*)))) (assert (name-of self)) (setf (find-test (name-of self)) self) (setf (parent-of self) in)) (defmethod (setf parent-of) :around (new-parent (self testable)) (assert (typep new-parent '(or null testable))) (when (and new-parent leave alone tests named by uninterned symbols (not (eq new-parent *root-suite*)) (not (eq (symbol-package (name-of new-parent)) (symbol-package (name-of self))))) (warn 'test-style-warning :test self :format-control "Adding test under parent ~S which is in a different package (parent: ~A, child: ~A). Maybe a missing (in-root-suite)?" :format-arguments (list new-parent (symbol-package (name-of new-parent)) (symbol-package (name-of self))))) (bind ((old-parent (parent-of self))) (when old-parent (remhash (name-of self) (children-of old-parent))) (prog1 (call-next-method) (when new-parent (setf (gethash (name-of self) (children-of new-parent)) self))))) (defgeneric count-tests (testable) (:method ((self testable)) (+ (hash-table-count (children-of self)) (iter (for (nil child) :in-hashtable (children-of self)) (summing (count-tests child)))))) #+nil(defclass-star:defclass* test (testable) ((package nil) (lambda-list nil) (compile-before-run #t :type boolean) (declarations nil) (documentation nil) (body nil))) (defclass test (testable) ((package :initform nil :accessor package-of :initarg :package) (lambda-list :initform nil :accessor lambda-list-of :initarg :lambda-list) (compile-before-run :initform t :accessor compile-before-run-p :initarg :compile-before-run :type boolean) (declarations :initform nil :accessor declarations-of :initarg :declarations) (documentation :initform nil :accessor documentation-of :initarg :documentation) (body :initform nil :accessor body-of :initarg :body))) (defun make-test (name &rest args &key &allow-other-keys) (apply #'make-instance 'test :name name args)) (defun make-suite (name &rest args &key &allow-other-keys) (apply #'make-instance 'test :name name args)) #+nil (defclass-star:defclass* failure-description () ((test-context-backtrace) (progress-char #\X :allocation :class) (expected *failures-and-errors-are-expected* :type boolean))) (defclass failure-description () ((test-context-backtrace :accessor test-context-backtrace-of :initarg :test-context-backtrace) (progress-char :initform #\X :accessor progress-char-of :initarg :progress-char :allocation :class) (expected :initform *failures-and-errors-are-expected* :accessor expected-p :initarg :expected :type boolean))) #+nil (defclass-star:defclass* failed-assertion (failure-description) ((form) (format-control) (format-arguments))) (defclass failed-assertion (failure-description) ((form :accessor form-of :initarg :form) (format-control :accessor format-control-of :initarg :format-control) (format-arguments :accessor format-arguments-of :initarg :format-arguments))) (defmethod describe-object ((self failed-assertion) stream) (let ((*print-circle* nil)) (apply #'format stream (format-control-of self) (format-arguments-of self)))) (defprint-object (self failed-assertion :identity #f :type #f) (format t "failure ~S backtrace: ~{~A~^,~}" (form-of self) (mapcar (compose #'name-of #'test-of) (test-context-backtrace-of self)))) #+nil (defclass-star:defclass* missing-condition (failure-description) ((form) (condition))) (defclass missing-condition (failure-description) ((form :accessor form-of :initarg :form) (condition :accessor condition-of :initarg :condition))) (defmethod describe-object ((self missing-condition) stream) (let ((*print-circle* nil)) (format stream "~S failed to signal condition ~S" (form-of self) (condition-of self)))) #+nil (defclass-star:defclass* unexpected-error (failure-description) ((condition) (progress-char #\E :allocation :class))) (defclass unexpected-error (failure-description) ((condition :accessor condition-of :initarg :condition) (progress-char :initform #\E :accessor progress-char-of :initarg :progress-char :allocation :class))) (defprint-object (self unexpected-error :identity #f :type #f) (format t "error ~{~A~^,~}: ~S" (mapcar (compose #'name-of #'test-of) (reverse (test-context-backtrace-of self))) (condition-of self))) (defun find-test (name &key (otherwise :error)) (bind (((:values test found-p) (if (typep name 'testable) (values name t) (gethash name *tests*)))) (when (and (not found-p) otherwise) (etypecase otherwise (symbol (ecase otherwise (:error (error "Testable called ~A was not found" name)))) (function (funcall otherwise)) (t (setf test otherwise)))) (values test found-p))) (defun (setf find-test) (new-value key) (if new-value (progn (when (gethash key *tests*) (warn 'test-style-warning :format-control "redefining test ~A" :format-arguments (list (let ((*package* #.(find-package "KEYWORD"))) (format nil "~S" key))))) (setf (gethash key *tests*) new-value)) (rem-test key))) (defun rem-test (name &rest args) (bind ((test (apply #'find-test name args)) (parent (when test (parent-of test)))) (when test (assert (or (not (eq *suite* test)) (parent-of test)) () "You can not remove a test which is the current suite and has no parent") (remhash name *tests*) (setf (parent-of test) nil) (fmakunbound (name-of test)) (iter (for (nil subtest) :in-hashtable (children-of test)) (rem-test (name-of subtest))) (when (eq *suite* test) (setf *suite* parent))) test)) #+nil (define-dynamic-context* global-context ((failure-descriptions (make-array 8 :adjustable #t :fill-pointer 0)) (assertion-count 0) (progress-char-count 0) (print-test-run-progress-p *print-test-run-progress* :type boolean) (debug-on-unexpected-error-p *debug-on-unexpected-error* :type boolean) (debug-on-assertion-failure-p *debug-on-assertion-failure* :type boolean) (toplevel-context nil) (current-test nil) (run-tests (make-hash-table) :documentation "test -> context mapping") (run-fixtures (make-hash-table)) (test-lambdas (make-hash-table) :documentation "test -> compiled test lambda mapping for this test run"))) (define-dynamic-context global-context ((failure-descriptions :initform (make-array 8 :adjustable t :fill-pointer 0) :accessor failure-descriptions-of :initarg :failure-descriptions) (assertion-count :initform 0 :accessor assertion-count-of :initarg :assertion-count) (progress-char-count :initform 0 :accessor progress-char-count-of :initarg :progress-char-count) (print-test-run-progress-p :initform *print-test-run-progress* :accessor print-test-run-progress-p :initarg :print-test-run-progress-p :type boolean) (debug-on-unexpected-error-p :initform *debug-on-unexpected-error* :accessor debug-on-unexpected-error-p :initarg :debug-on-unexpected-error-p :type boolean) (debug-on-assertion-failure-p :initform *debug-on-assertion-failure* :accessor debug-on-assertion-failure-p :initarg :debug-on-assertion-failure-p :type boolean) (toplevel-context :initform nil :accessor toplevel-context-of :initarg :toplevel-context) (current-test :initform nil :accessor current-test-of :initarg :current-test) (run-tests :initform (make-hash-table) :accessor run-tests-of :initarg :run-tests :documentation "test -> context mapping") (run-fixtures :initform (make-hash-table) :accessor run-fixtures-of :initarg :run-fixtures) (test-lambdas :initform (make-hash-table) :accessor test-lambdas-of :initarg :test-lambdas :documentation "test -> compiled test lambda mapping for this test run"))) (defprint-object (self global-context :identity #f :type #f) (format t "test-run: ~A tests, ~A assertions, ~A failures (~A expected) in ~A sec" (hash-table-count (run-tests-of self)) (assertion-count-of self) (length (failure-descriptions-of self)) (count-if 'expected-p (failure-descriptions-of self)) (bind ((toplevel-context (toplevel-context-of self)) (real-time-spent-in-seconds (when toplevel-context (real-time-spent-in-seconds toplevel-context)))) (if (and toplevel-context real-time-spent-in-seconds) real-time-spent-in-seconds "?")))) (defmacro without-test-progress-printing (&body body) (with-unique-names (old-state) `(let ((,old-state (print-test-run-progress-p *global-context*))) (unwind-protect (progn (setf (print-test-run-progress-p *global-context*) #f) ,@body) (setf (print-test-run-progress-p *global-context*) ,old-state))))) (defmacro with-toplevel-restarts (&body body) `(block restart-wrapper (restart-bind ((continue-without-debugging (lambda () (setf (debug-on-unexpected-error-p *global-context*) #f) (setf (debug-on-assertion-failure-p *global-context*) #f) (continue)) :report-function (lambda (stream) (format stream "~@<Turn off debugging for this test session and invoke the first CONTINUE restart~@:>"))) (abort-testing (lambda () (return-from restart-wrapper)) :report-function (lambda (stream) (format stream "~@<Abort the entire test session~@:>")))) (bind ((swank::*sldb-quit-restart* 'abort-testing)) ,@body)))) (defun test-was-run-p (test) (declare (type testable test)) (and (gethash test (run-tests-of *global-context*)) (not (eq (current-test-of *global-context*) test)))) (defun register-test-being-run (test) (declare (type testable test)) (setf (gethash test (run-tests-of *global-context*)) (current-context)) (setf (current-test-of *global-context*) test)) (defgeneric get-test-lambda (test global-context) (:method ((test test) (context global-context)) (bind (((:values test-lambda found-p) (gethash test (test-lambdas-of context)))) (unless found-p (setf test-lambda (bind ((*package* (package-of test)) (*readtable* (copy-readtable))) (compile nil `(lambda ,(lambda-list-of test) ,@(body-of test))))) (setf (gethash test (test-lambdas-of context)) test-lambda)) test-lambda))) #+nil (define-dynamic-context* context ((test) (internal-realtime-spent-with-test nil) (test-arguments) (number-of-added-failure-descriptions 0)) :chain-parents #t) (define-dynamic-context context ((test :accessor test-of :initarg :test) (internal-realtime-spent-with-test :initform nil :accessor internal-realtime-spent-with-test-of :initarg :internal-realtime-spent-with-test) (test-arguments :accessor test-arguments-of :initarg :test-arguments) (number-of-added-failure-descriptions :initform 0 :accessor number-of-added-failure-descriptions-of :initarg :number-of-added-failure-descriptions)) :chain-parents #t) (defprint-object (self context :identity #f :type #f) (format t "test-run ~@<(~S~{~^ ~S~})~@:>" (name-of (test-of self)) (bind ((result (lambda-list-to-funcall-list (lambda-list-of (test-of self))))) (mapcar (lambda (arg-cell) (setf result (substitute (cdr arg-cell) (car arg-cell) result :test #'eq))) (test-arguments-of self)) result))) (defgeneric real-time-spent-in-seconds (context) (:method ((self context)) (awhen (internal-realtime-spent-with-test-of self) (coerce (/ it internal-time-units-per-second) 'float)))) (defmacro run-failed-tests (&optional (test-result-place '*last-test-result*)) `(with-new-global-context () (if (> (length (failure-descriptions-of ,test-result-place)) 0) (progn (%run-failed-tests ,test-result-place) (push *global-context* *test-result-history*) (setf *last-test-result* *global-context*) (setf ,test-result-place *global-context*)) (progn (warn "There are no failed tests in ~S" ',test-result-place) (values))))) (defun %run-failed-tests (global-context-to-be-processed) (warn "Re-running failed tests without considering their dynamic environment, which may affect their behaviour!") (with-toplevel-restarts (iter (for failure :in-sequence (failure-descriptions-of global-context-to-be-processed)) (for context = (elt (test-context-backtrace-of failure) 0)) (apply (name-of (test-of context)) (mapcar #'cdr (test-arguments-of context)))) (when (print-test-run-progress-p *global-context*) (terpri *debug-io*)))) (defun run-test-body-in-handlers (test function) (declare (type test test) (type function function)) (register-test-being-run test) (labels ((prune-failure-descriptions () (loop repeat (number-of-added-failure-descriptions-of *context*) do (vector-pop (failure-descriptions-of *global-context*))) (setf (number-of-added-failure-descriptions-of *context*) 0)) (run-test-body () (handler-bind ((assertion-failed (lambda (c) (declare (ignore c)) (unless (debug-on-assertion-failure-p *global-context*) (continue)))) (error (lambda (c) (unless (typep c 'assertion-failed) (record-failure* 'unexpected-error :description-initargs (list :condition c) :signal-assertion-failed #f) (when (debug-on-unexpected-error-p *global-context*) (invoke-debugger c)) (return-from run-test-body))))) (restart-case (bind ((*package* (package-of test)) (*readtable* (copy-readtable)) (start-time (get-internal-run-time))) (multiple-value-prog1 (funcall function) (setf (internal-realtime-spent-with-test-of *context*) (- (get-internal-run-time) start-time)))) (continue () :report (lambda (stream) (format stream "~@<Skip the rest of the test ~S and continue by returning (values)~@:>" (name-of test))) (values)) (retest () :report (lambda (stream) (format stream "~@<Rerun the test ~S~@:>" (name-of test))) (prune-failure-descriptions) (return-from run-test-body (run-test-body))))))) (run-test-body))) (defun run-test-body (test function arguments toplevel-p) (declare (type test test)) (bind ((result-values '())) (flet ((body () (with-new-context (:test test :test-arguments arguments) (when toplevel-p (setf (toplevel-context-of *global-context*) (current-context))) (setf result-values (multiple-value-list (run-test-body-in-handlers test function)))))) (if toplevel-p (with-toplevel-restarts (body)) (body)) (if toplevel-p (progn (when (print-test-run-progress-p *global-context*) (terpri *debug-io*)) (if result-values (values-list (append result-values (list *global-context*))) *global-context*)) (values-list result-values))))) (defmacro deftest (&whole whole name args &body body) (bind (((:values remaining-forms declarations documentation) (parse-body body :documentation #t :whole whole)) ((name &rest test-args &key (compile-before-run *compile-tests-before-run*) in &allow-other-keys) (ensure-list name)) (in-p (get-properties test-args '(:in)))) (remove-from-plistf test-args :in) (unless (or (not (symbol-package name)) (eq (symbol-package name) *package*)) (warn 'test-style-warning :test name :format-control "Defining test on symbol ~S whose home package is not *package* which is ~A" :format-arguments (list name *package*))) (with-unique-names (test test-lambda global-context toplevel-p body) `(progn (eval-when (:load-toplevel :execute) (make-test ',name :package ,*package* :lambda-list ',args :declarations ',declarations :documentation ',documentation :body ',remaining-forms ,@(when in-p (if in `(:in (find-test ',in)) '(:in nil))) ,@test-args)) (defun ,name ,args ,@(when documentation (list documentation)) ,@declarations ,@(awhen *compile-tests-with-debug-level* `((declare (optimize (debug ,it))))) (bind ((,test (find-test ',name)) (,toplevel-p (not (has-global-context))) (,global-context (unless ,toplevel-p (current-global-context)))) (labels (,@(unless compile-before-run `((,name () ,@remaining-forms))) (,body () ,(if compile-before-run `(bind ((,test-lambda (get-test-lambda ,test ,global-context))) (run-test-body ,test (lambda () TODO install a labels entry with the test name ? to avoid compile at each recursion ... ,(lambda-list-to-funcall-expression test-lambda args)) ,(lambda-list-to-value-list-expression args) ,toplevel-p)) `(run-test-body ,test #',name ,(lambda-list-to-value-list-expression args) ,toplevel-p)))) (declare (dynamic-extent ,@(unless compile-before-run `(#',name)) #',body)) (if ,toplevel-p (with-new-global-context () (setf ,global-context (current-global-context)) (push ,global-context *test-result-history*) (setf *last-test-result* ,global-context) (,body)) (,body))))))))) (defmacro defixture (name &body body) "Fixtures are defun's that only execute the :setup part of their body once per test session if there is any at the time of calling." (with-unique-names (global-context nesting-count phase) (bind (setup-body teardown-body) (iter (for entry :in body) (if (and (consp body) (member (first entry) '(:setup :teardown))) (ecase (first entry) (:setup (assert (not setup-body) () "Multiple :setup's for fixture ~S" name) (setf setup-body (rest entry))) (:teardown (assert (not teardown-body) () "Multiple :teardown's for fixture ~S" name) (setf teardown-body (rest entry)))) (progn (assert (and (not setup-body) (not teardown-body)) () "Error parsing body of fixture ~A" name) (setf setup-body body) (leave)))) `(defun ,name (&optional (,phase :setup)) (declare (optimize (debug 3))) (bind ((,global-context (and (has-global-context) (current-global-context))) (,nesting-count (or (and ,global-context (gethash ',name (run-fixtures-of ,global-context))) 0))) (assert (>= ,nesting-count 0)) (ecase ,phase (:setup (incf ,nesting-count) (prog1 (if (and ,global-context (> ,nesting-count 1)) #f (progn ,@setup-body #t)) (when ,global-context (setf (gethash ',name (run-fixtures-of ,global-context)) ,nesting-count)))) (:teardown (decf ,nesting-count) (prog1 (if (and ,global-context (> ,nesting-count 0)) #f (progn (setf ,nesting-count 0) ,@teardown-body #t)) (when ,global-context (setf (gethash ',name (run-fixtures-of ,global-context)) ,nesting-count)))))))))) (defmacro with-fixture (name &body body) (with-unique-names (whole-fixture-body) `(flet ((,whole-fixture-body () (,name :setup) (unwind-protect (progn ,@body) (block teardown-block (handler-bind ((serious-condition (lambda (c) (with-simple-restart (continue ,(let ((*package* (find-package :common-lisp))) (format nil "Skip teardown of ~S and continue" name))) (error 'error-in-teardown :condition c :fixture ',name)) (return-from teardown-block)))) (,name :teardown)))))) (declare (dynamic-extent ,whole-fixture-body)) (if (has-global-context) (,whole-fixture-body) (with-new-global-context () (,whole-fixture-body)))))) (defmacro with-fixtures (fixtures &body body) (if fixtures `(with-fixture ,(first fixtures) (with-fixtures ,(rest fixtures) ,@body)) `(progn ,@body))) (defun record-failure (description-type &rest args) (record-failure* description-type :description-initargs args)) (defun record-failure* (type &key (signal-assertion-failed #t) description-initargs) (bind ((description (apply #'make-instance type :test-context-backtrace (when (has-context) (iter (for context :first (current-context) :then (parent-context-of context)) (while context) (collect context))) description-initargs))) (if (and (has-global-context) (has-context)) (progn (vector-push-extend description (failure-descriptions-of *global-context*)) (incf (number-of-added-failure-descriptions-of *context*)) (write-progress-char (progress-char-of description)) (when signal-assertion-failed (restart-case (error 'assertion-failed :test (test-of *context*) :failure-description description) (continue () :report (lambda (stream) (format stream "~@<Roger, go on testing...~@:>")))))) (progn (describe description *debug-io*) (restart-case (error 'assertion-failed :failure-description description) (continue () :report (lambda (stream) (format stream "~@<Ignore the failure and continue~@:>"))))))))) (defun extract-assert-expression-and-message (input-form) (bind ((negatedp #f) (predicate) (arguments '())) (labels ((process (form) (if (consp form) (case (first form) ((not) (assert (= (length form) 2)) (setf negatedp (not negatedp)) (process (second form))) (t (setf predicate (first form)) (setf arguments (rest form)))) (setf predicate form)))) (process input-form) (cond ((ignore-errors (macro-function predicate)) (values '() input-form "Macro expression ~A evaluated to false." (list `(quote ,input-form)))) ((ignore-errors (fdefinition predicate)) (cond ((= (length arguments) 0) (values '() input-form "Expression ~A evaluated to false." (list `(quote ,input-form)))) ((= (length arguments) 2) (with-unique-names (x y) (values `((,x ,(first arguments)) (,y ,(second arguments))) (if negatedp `(not (,predicate ,x ,y)) `(,predicate ,x ,y)) "Binary predicate ~A failed.~%~ x: ~S => ~S~%~ y: ~S => ~S" (list (if negatedp `(quote (not (,predicate x y))) `(quote (,predicate x y))) `(quote ,(first arguments)) x `(quote ,(second arguments)) y)))) (t (bind ((arg-values (mapcar (lambda (el) (unless (keywordp el) (gensym))) arguments)) (bindings (iter (for arg :in arguments) (for arg-value :in arg-values) (when arg-value (collect `(,arg-value ,arg))))) (expression-values (mapcar (lambda (arg-value argument) (or arg-value argument)) arg-values arguments)) (expression (if negatedp `(not (,predicate ,@expression-values)) `(,predicate ,@expression-values))) ((:values message message-args) (iter (with message = "Expression ~A evaluated to ~A") (for arg :in arguments) (for idx :upfrom 0) (for arg-value :in arg-values) (when arg-value (setf message (concatenate 'string message "~%~D: ~A => ~S")) (appending `(,idx (quote ,arg) ,arg-value) :into message-args)) (finally (return (values message message-args)))))) (values bindings expression message (nconc (list `(quote (,predicate ,@arguments)) (if negatedp "true" "false")) message-args)))))) (t (values '() input-form "Expression ~A evaluated to false." (list `(quote ,input-form)))))))) (defun write-progress-char (char) (bind ((global-context (when (boundp '*global-context*) *global-context*))) (when (and global-context (print-test-run-progress-p global-context)) (when (and (not (zerop (progress-char-count-of global-context))) (zerop (mod (progress-char-count-of global-context) *test-progress-print-right-margin*))) (terpri *debug-io*)) (incf (progress-char-count-of global-context))) (when (or (and global-context (print-test-run-progress-p global-context)) (and (not global-context) *print-test-run-progress*)) (write-char char *debug-io*)))) (defun register-assertion-was-successful () (write-progress-char #\.)) (defun register-assertion () (when (boundp '*global-context*) (incf (assertion-count-of *global-context*)))) (defmacro is (&whole whole form &optional (message nil message-p) &rest message-args) (bind (((:values bindings expression message message-args) (if message-p (values nil form message message-args) (extract-assert-expression-and-message form)))) (with-unique-names (result) `(progn (register-assertion) (bind ,bindings (bind ((,result (multiple-value-list ,expression))) (if (first ,result) (register-assertion-was-successful) (record-failure 'failed-assertion :form ',whole :format-control ,message :format-arguments (list ,@message-args))) (values-list ,result))))))) (defmacro signals (what &body body) (bind ((condition-type what)) (unless (symbolp condition-type) (error "SIGNALS expects a symbol as condition-type! (Is there a superfulous quote at ~S?)" condition-type)) `(progn (register-assertion) (block test-block (handler-bind ((,condition-type (lambda (c) (register-assertion-was-successful) (return-from test-block c)))) ,@body) (record-failure 'missing-condition :form (list* 'progn ',body) :condition ',condition-type) (values))))) (defmacro finishes (&body body) `(progn (register-assertion) (multiple-value-prog1 (progn ,@body) (register-assertion-was-successful)))) (defmacro runs-without-failure? (&body body) (with-unique-names (old-failure-count) `(bind ((,old-failure-count (length (failure-descriptions-of *global-context*)))) ,@body (= ,old-failure-count (length (failure-descriptions-of *global-context*)))))) (defmacro with-expected-failures (&body body) "Any failure inside the dynamic extent of this block is registered as an expected failure." `(bind ((*failures-and-errors-are-expected* #t)) ,@body)) (define-condition illegal-lambda-list (error) ((lambda-list :accessor lambda-list-of :initarg :lambda-list))) (defun illegal-lambda-list (lambda-list) (error 'illegal-lambda-list :lambda-list lambda-list)) (defun parse-lambda-list (lambda-list visitor &key macro) TODO finish macro lambda list parsing (declare (optimize (speed 3)) (type list lambda-list) (type (or symbol function) visitor)) (let ((args lambda-list)) (labels ((fail () (illegal-lambda-list lambda-list)) (ensure-list (list) (if (listp list) list (list list))) (process-&whole () (assert (eq (first args) '&whole)) (pop args) (unless macro (fail)) (let ((whole (pop args))) (unless whole (fail)) (funcall visitor '&whole whole whole)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&optional (entering-&optional)) (&body (process-&body)) (&environment (process-&environment)) ((&whole &aux &allow-other-keys) (fail)) (t (process-required)))) (process-&body () (assert (eq (first args) '&body)) (pop args) (unless macro (fail)) (let ((body (pop args))) (unless (null args) (fail)) (unless body (fail)) (funcall visitor '&body body body))) (process-&environment () (assert (eq (first args) '&environment)) (pop args) (unless macro (fail)) (let ((env (pop args))) (unless env (fail)) (funcall visitor '&environment env env)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&optional (entering-&optional)) (&body (process-&body)) (&aux (process-&aux)) ((&whole &environment &allow-other-keys) (fail)) (t (process-required)))) (process-required () (unless args (done)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&optional (entering-&optional)) (&body (process-&body)) (&environment (process-&environment)) ((&whole &allow-other-keys) (fail)) (&aux (entering-&aux)) (t (let ((arg (pop args))) (funcall visitor nil arg arg)) (process-required)))) (process-&rest () (assert (eq (first args) '&rest)) (pop args) (let ((rest (pop args))) (unless rest (fail)) (funcall visitor '&rest rest rest)) (unless args (done)) (case (first args) (&key (entering-&key)) (&environment (process-&environment)) ((&whole &optional &rest &body &allow-other-keys) (fail)) (&aux (entering-&aux)) (t (fail)))) (entering-&optional () (assert (eq (first args) '&optional)) (pop args) (process-&optional)) (process-&optional () (unless args (done)) (case (first args) (&key (entering-&key)) (&rest (process-&rest)) (&body (process-&body)) ((&whole &optional &environment &allow-other-keys) (fail)) (&aux (entering-&aux)) (t (let* ((arg (ensure-list (pop args))) (name (first arg)) (default (second arg))) (funcall visitor '&optional name arg nil default)) (process-&optional)))) (entering-&key () (assert (eq (first args) '&key)) (pop args) (process-&key)) (process-&key () (unless args (done)) (case (first args) (&allow-other-keys (funcall visitor '&allow-other-keys nil nil)) ((&key &optional &whole &environment &body) (fail)) (&aux (entering-&aux)) (t (let* ((arg (ensure-list (pop args))) (name-part (first arg)) (default (second arg)) (external-name (if (consp name-part) (progn (unless (= (length name-part) 2) (illegal-lambda-list lambda-list)) (first name-part)) (intern (symbol-name name-part) #.(find-package "KEYWORD")))) (local-name (if (consp name-part) (second name-part) name-part))) (funcall visitor '&key local-name arg external-name default)) (process-&key)))) (entering-&aux () (assert (eq (first args) '&aux)) (pop args) (process-&aux)) (process-&aux () (unless args (done)) (case (first args) ((&whole &optional &key &environment &allow-other-keys &aux &body) (fail)) (t (let ((arg (ensure-list (pop args)))) (funcall visitor '&aux (first arg) arg)) (process-&aux)))) (done () (return-from parse-lambda-list (values)))) (when args (case (first args) (&whole (process-&whole)) (t (process-required))))))) (defun lambda-list-to-funcall-list (args) (let ((result (list)) (rest-variable-name nil)) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry default)) (case kind (&key (push external-name result) (push name result)) (&allow-other-keys) (&rest (setf rest-variable-name name)) (t (push name result))))) (values (nreverse result) rest-variable-name))) (defun lambda-list-to-lambda-list-with-quoted-defaults (args) (let ((primaries (list)) (keywords (list)) (optionals (list)) (rest-variable-name nil) (allow-other-keys? nil)) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry)) (ecase kind (&key (push `((,external-name ,name) (quote ,default)) keywords)) (&optional (push `(,name ,default) optionals)) (&allow-other-keys (setf allow-other-keys? t)) (&rest (setf rest-variable-name name)) ((nil) (push name primaries))))) (values `(,@(nreverse primaries) ,@(when optionals (cons '&optional (nreverse optionals))) ,@(when keywords (cons '&key (nreverse keywords))) ,@(when allow-other-keys? (list '&allow-other-keys))) rest-variable-name))) (defun lambda-list-to-funcall-expression (function args) (multiple-value-bind (arg-list rest-variable) (lambda-list-to-funcall-list args) (if rest-variable `(apply ,function ,@arg-list ,rest-variable) `(funcall ,function ,@arg-list)))) (defun lambda-list-to-value-list-expression (args) `(list ,@(let ((result (list))) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry external-name default)) (case kind (&allow-other-keys) (t (push `(cons ',name ,name) result))))) (nreverse result)))) (defun lambda-list-to-variable-name-list (args &key macro include-specials) (let ((result (list)) (rest-variable-name nil) (whole-variable-name nil) (env-variable-name nil)) (parse-lambda-list args (lambda (kind name entry &optional external-name default) (declare (ignore entry external-name default)) (case kind (&allow-other-keys ) (&environment (setf env-variable-name name) (when include-specials (push name result))) (&whole (setf whole-variable-name name) (when include-specials (push name result))) ((&rest &body) (setf rest-variable-name name) (when include-specials (push name result))) (t (push name result)))) :macro macro) (values (nreverse result) rest-variable-name whole-variable-name env-variable-name))) (defun funcall-test-with-feedback-message (test-function &rest args) "Run the given test non-interactively and print the results to *standard-output*. This function is ideal for ASDF:TEST-OP's." (aprog1 (without-debugging (apply test-function args)) (let ((*package* (find-package :common-lisp))) (format *standard-output* "The result of ~S is: ~A For more details run it from the REPL and use the customized Slime inspector to inspect the results (ASDF eats up the return values). Some inspector features may only be available when using the Slime branch at darcs get --lazy -lisp.net/project/cl-dwim/darcs/slime but the official Slime should also work fine.~%" test-function it))))
1e79adf7defdd05b31087a5675317fca64bdd60b3c362cdf415fd42ed8f18a24
ku-fpg/kansas-lava
Stream.hs
{-# LANGUAGE DeriveDataTypeable #-} -- | This implementation of the Stream data type. It's defined similarly to -- other implementation of infinite streams found on hackage, except the -- elements of the stream are strict to prevent some space leaks. module Language.KansasLava.Stream where import Data.Traversable import qualified Data.Foldable as F import Control.Applicative import Control.Monad import Prelude hiding (zipWith,zipWith3, repeat) import Data.Monoid import qualified Data.List as List import Data.Dynamic import Debug.Trace -- | Set the precedence of infix `Cons`. infixr 5 `Cons` -- | A stream is an infinite sequence of values. data Stream a = Cons !a (Maybe (Stream a)) -- ^ Cons takes a head and an optional tail. -- If the tail is empty, then the last value is repeated. deriving (Typeable) instance Show a => Show (Stream a) where show (Cons a opt_as) = show a ++ " " ++ maybe "" show opt_as instance Applicative Stream where pure a = a `Cons` Nothing (h1 `Cons` t1) <*> (h2 `Cons` t2) = h1 h2 `Cons` (t1 `opt_ap` t2) where Nothing `opt_ap` Nothing = Nothing Nothing `opt_ap` (Just x) = Just (pure h1 <*> x) (Just f) `opt_ap` Nothing = Just (f <*> pure h2) (Just f) `opt_ap` (Just x) = Just (f <*> x) instance Functor Stream where fmap f (a `Cons` opt_as) = f a `Cons` maybe Nothing (Just . fmap f) opt_as -- | Lift a value to be a constant stream. --repeat :: a -> Stream a --repeat a = a `Cons` repeat a | Zip two streams together . zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c zipWith f xs ys = f <$> xs <*> ys | Zip three streams together . zipWith3 :: (a -> b -> c -> d) -> Stream a -> Stream b -> Stream c -> Stream d zipWith3 f xs ys zs = f <$> xs <*> ys <*> zs -- | Convert a list to a stream. If the list is finite, then the last element of -- the stream will be an error. fromFiniteList :: [a] -> a -> Stream a fromFiniteList (x : xs) end = x `Cons` (Just (fromFiniteList xs end)) fromFiniteList [] end = end `Cons` Nothing fromList :: [a] -> Stream a fromList xs = fromFiniteList xs (error "found end of infinite list") head :: Stream a -> a head (Cons a _) = a tail :: Stream a -> Stream a tail (Cons a Nothing) = Cons a Nothing tail (Cons _ (Just xs)) = xs cons :: a -> Stream a -> Stream a cons x xs = Cons x (Just xs) uncons :: Stream a -> (a,Stream a) uncons (Cons x xs) = (x,case xs of Nothing -> Cons x xs Just v -> v) unzip :: Stream (a,b) -> (Stream a, Stream b) unzip ss = (fmap fst ss,fmap snd ss) -- | Convert a Stream to a lazy list. toList :: Stream a -> [a] toList (x `Cons` opt_xs) = x : maybe (List.repeat x) toList opt_xs instance F.Foldable Stream where foldMap f (a `Cons` opt_as) = f a `mappend` maybe (F.foldMap f (a `Cons` opt_as)) (F.foldMap f) opt_as instance Traversable Stream where traverse f (a `Cons` opt_as) = Cons <$> f a <*> maybe (pure Nothing) (\ as -> Just <$> traverse f as) opt_as observeStream :: (Show a) => String -> Stream a -> Stream a observeStream nm (Cons a rest) = trace (show (nm,a)) $ Cons a $ case rest of Nothing -> trace (show (nm,".")) $ Nothing Just xs -> Just $ observeStream nm xs
null
https://raw.githubusercontent.com/ku-fpg/kansas-lava/cc0be29bd8392b57060c3c11e7f3b799a6d437e1/Language/KansasLava/Stream.hs
haskell
# LANGUAGE DeriveDataTypeable # | This implementation of the Stream data type. It's defined similarly to other implementation of infinite streams found on hackage, except the elements of the stream are strict to prevent some space leaks. | Set the precedence of infix `Cons`. | A stream is an infinite sequence of values. ^ Cons takes a head and an optional tail. If the tail is empty, then the last value is repeated. | Lift a value to be a constant stream. repeat :: a -> Stream a repeat a = a `Cons` repeat a | Convert a list to a stream. If the list is finite, then the last element of the stream will be an error. | Convert a Stream to a lazy list.
module Language.KansasLava.Stream where import Data.Traversable import qualified Data.Foldable as F import Control.Applicative import Control.Monad import Prelude hiding (zipWith,zipWith3, repeat) import Data.Monoid import qualified Data.List as List import Data.Dynamic import Debug.Trace infixr 5 `Cons` data Stream a = Cons !a (Maybe (Stream a)) deriving (Typeable) instance Show a => Show (Stream a) where show (Cons a opt_as) = show a ++ " " ++ maybe "" show opt_as instance Applicative Stream where pure a = a `Cons` Nothing (h1 `Cons` t1) <*> (h2 `Cons` t2) = h1 h2 `Cons` (t1 `opt_ap` t2) where Nothing `opt_ap` Nothing = Nothing Nothing `opt_ap` (Just x) = Just (pure h1 <*> x) (Just f) `opt_ap` Nothing = Just (f <*> pure h2) (Just f) `opt_ap` (Just x) = Just (f <*> x) instance Functor Stream where fmap f (a `Cons` opt_as) = f a `Cons` maybe Nothing (Just . fmap f) opt_as | Zip two streams together . zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c zipWith f xs ys = f <$> xs <*> ys | Zip three streams together . zipWith3 :: (a -> b -> c -> d) -> Stream a -> Stream b -> Stream c -> Stream d zipWith3 f xs ys zs = f <$> xs <*> ys <*> zs fromFiniteList :: [a] -> a -> Stream a fromFiniteList (x : xs) end = x `Cons` (Just (fromFiniteList xs end)) fromFiniteList [] end = end `Cons` Nothing fromList :: [a] -> Stream a fromList xs = fromFiniteList xs (error "found end of infinite list") head :: Stream a -> a head (Cons a _) = a tail :: Stream a -> Stream a tail (Cons a Nothing) = Cons a Nothing tail (Cons _ (Just xs)) = xs cons :: a -> Stream a -> Stream a cons x xs = Cons x (Just xs) uncons :: Stream a -> (a,Stream a) uncons (Cons x xs) = (x,case xs of Nothing -> Cons x xs Just v -> v) unzip :: Stream (a,b) -> (Stream a, Stream b) unzip ss = (fmap fst ss,fmap snd ss) toList :: Stream a -> [a] toList (x `Cons` opt_xs) = x : maybe (List.repeat x) toList opt_xs instance F.Foldable Stream where foldMap f (a `Cons` opt_as) = f a `mappend` maybe (F.foldMap f (a `Cons` opt_as)) (F.foldMap f) opt_as instance Traversable Stream where traverse f (a `Cons` opt_as) = Cons <$> f a <*> maybe (pure Nothing) (\ as -> Just <$> traverse f as) opt_as observeStream :: (Show a) => String -> Stream a -> Stream a observeStream nm (Cons a rest) = trace (show (nm,a)) $ Cons a $ case rest of Nothing -> trace (show (nm,".")) $ Nothing Just xs -> Just $ observeStream nm xs
9e7524985dae9f68fa8580c494c1f92c2b15f2bf2a45cead871f2cdd4f6e493b
stumpwm/stumpwm-contrib
numpad-layouts.lisp
;;;; numpad-layouts.lisp (in-package #:numpad-layouts) (export '(set-numpad-layout)) (defparameter *layouts* '((us . ((87 10 . 16) (88 11 . 16) (89 12 . 16) (106 61 . 16) (83 13 . 16) (84 14 . 16) (85 15 . 16) (86 21 . 17) (79 16 . 16) (80 17 . 16) (81 18 . 16) (63 17 . 17) (82 20 . 16) (104 36 . 16) (91 60 . 16) (90 19 . 17))) (fr . ((87 10 . 17) (88 11 . 17) (89 12 . 17) (106 60 . 17) (83 13 . 17) (84 14 . 17) (85 15 . 17) (86 21 . 17) (79 16 . 17) (80 17 . 17) (81 18 . 17) (63 51 . 16) (82 15 . 16) (104 36 . 16) (91 59 . 17) (90 19 . 17))) (se . ((87 10 . 16) (88 11 . 16) (89 12 . 16) (106 61 . 16) (83 13 . 16) (84 14 . 16) (85 15 . 16) (86 21 . 17) (79 16 . 16) (80 17 . 16) (81 18 . 16) (63 17 . 17) (82 20 . 16) (104 36 . 16) (91 60 . 16) (90 19 . 17)))) "An alist of numpad layouts for non-standard keyboards that move the locations of 0-9 and the symbols on a numpad (typically -,*,+ and =).") (defun set-numpad-layout (layout-name) "Sets the `*numpad-map*' that StumpWM uses to map numpad keys to the main keyboard when the NumLock key is active." (if (symbolp layout-name) (let ((layout (rest (assoc layout-name *layouts* :test #'string=)))) (if layout (setf stumpwm:*numpad-map* layout) (error "~a is not a supported layout" layout-name))) (error "~a is not of type symbol" layout-name)))
null
https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/a7dc1c663d04e6c73a4772c8a6ad56a34381096a/util/numpad-layouts/numpad-layouts.lisp
lisp
numpad-layouts.lisp
(in-package #:numpad-layouts) (export '(set-numpad-layout)) (defparameter *layouts* '((us . ((87 10 . 16) (88 11 . 16) (89 12 . 16) (106 61 . 16) (83 13 . 16) (84 14 . 16) (85 15 . 16) (86 21 . 17) (79 16 . 16) (80 17 . 16) (81 18 . 16) (63 17 . 17) (82 20 . 16) (104 36 . 16) (91 60 . 16) (90 19 . 17))) (fr . ((87 10 . 17) (88 11 . 17) (89 12 . 17) (106 60 . 17) (83 13 . 17) (84 14 . 17) (85 15 . 17) (86 21 . 17) (79 16 . 17) (80 17 . 17) (81 18 . 17) (63 51 . 16) (82 15 . 16) (104 36 . 16) (91 59 . 17) (90 19 . 17))) (se . ((87 10 . 16) (88 11 . 16) (89 12 . 16) (106 61 . 16) (83 13 . 16) (84 14 . 16) (85 15 . 16) (86 21 . 17) (79 16 . 16) (80 17 . 16) (81 18 . 16) (63 17 . 17) (82 20 . 16) (104 36 . 16) (91 60 . 16) (90 19 . 17)))) "An alist of numpad layouts for non-standard keyboards that move the locations of 0-9 and the symbols on a numpad (typically -,*,+ and =).") (defun set-numpad-layout (layout-name) "Sets the `*numpad-map*' that StumpWM uses to map numpad keys to the main keyboard when the NumLock key is active." (if (symbolp layout-name) (let ((layout (rest (assoc layout-name *layouts* :test #'string=)))) (if layout (setf stumpwm:*numpad-map* layout) (error "~a is not a supported layout" layout-name))) (error "~a is not of type symbol" layout-name)))
5e4d73056dec48329e64ac1703adc1f7855ccb9424a96d29beec2fc4aef564fc
loganallen/CmlControl
branch.ml
open Unix open Universal (****************************** Branch Module *********************************) (******************************************************************************) (* validate the branch name *) let validate_branch (branch : string) : unit = if branch.[0] = '.' || branch.[0] = '-' then raise (Fatal "invalid branch name") else () (* returns a list of all branches in alphabetical order*) let get_branches () : string list = let rec branch_loop acc q = match q with | [] -> acc | h::t -> begin let temp = ".cml/heads/"^h in if Sys.is_directory temp then let subs = temp |> Sys.readdir |> Array.to_list |> List.map (fun f -> h^"/"^f) in branch_loop acc t@subs else branch_loop (h::acc) t end in ".cml/heads" |> Sys.readdir |> Array.to_list |> branch_loop [] |> List.sort (Pervasives.compare) (* returns string of name of the current branch *) let get_current_branch () : string = try let ic = open_in ".cml/HEAD" in let raw = input_line ic in let _ = close_in ic in let split = (String.index raw '/') + 1 in String.sub raw split (String.length raw - split) with | Sys_error _ -> raise (Fatal "HEAD not found") | End_of_file -> raise (Fatal "HEAD not initialized") (* returns the head ptr of the given branch *) let get_branch_ptr (branch_name : string) : string = try let ic = open_in (".cml/heads/" ^ branch_name) in let ptr = input_line ic in close_in ic; ptr with | Sys_error _ -> raise (Fatal ("branch "^branch_name^" not found")) | End_of_file -> raise (Fatal (branch_name^" ptr not set")) (* initializes a given commit to a given branch name *) let set_branch_ptr (branch_name : string) (commit_hash : string) : unit = try let oc = open_out (".cml/heads/" ^ branch_name) in output_string oc commit_hash; close_out oc with | Sys_error _ -> raise (Fatal "write error") (* recursively creates branch sub-directories as needed *) let rec branch_help (path : string) (branch : string) : out_channel = try let slash = String.index branch '/' in let dir = String.sub branch 0 slash in let prefix = path^dir in if not (Sys.file_exists prefix) then mkdir prefix 0o777; (String.length branch - (slash+1)) |> String.sub branch (slash+1) |> branch_help (prefix^"/") with | Not_found -> open_out (path^"/"^branch) (* create a new branch if it doesn't exist *) let create_branch (branch : string) (ptr : string) : unit = if (get_branches () |> List.mem branch) then raise (Fatal ("a branch named "^branch^" already exists")) else let _ = validate_branch branch in let oc = begin if String.contains branch '/' then branch_help ".cml/heads/" branch else open_out (".cml/heads/"^branch) end in output_string oc ptr; close_out oc (* delete a branch if it exists *) let delete_branch (branch : string) : unit = if branch = get_current_branch () then raise (Fatal ("cannot delete branch '"^branch^"'")) else try if (get_branches () |> List.mem branch) then let _ = Sys.remove (".cml/heads/"^branch) in Print.print ("Deleted branch "^branch^"") else raise (Fatal ("branch '"^branch^"' not found")) with | Sys_error _ -> raise (Fatal "cannot perform such an operation") (* switch current working branch *) (* precondition: [branch] exists *) let switch_branch (branch : string) (isdetached : bool) : unit = let cur = if isdetached then "" else get_current_branch () in if cur = branch then Print.print ("Already on branch '"^branch^"'") else let oc = open_out ".cml/HEAD" in output_string oc ("heads/"^branch); close_out oc; Print.print ("Switched to branch '"^branch^"'")
null
https://raw.githubusercontent.com/loganallen/CmlControl/24bf4616b36672bc12225b9bd93b1ae662733663/modules/branch.ml
ocaml
***************************** Branch Module ******************************** **************************************************************************** validate the branch name returns a list of all branches in alphabetical order returns string of name of the current branch returns the head ptr of the given branch initializes a given commit to a given branch name recursively creates branch sub-directories as needed create a new branch if it doesn't exist delete a branch if it exists switch current working branch precondition: [branch] exists
open Unix open Universal let validate_branch (branch : string) : unit = if branch.[0] = '.' || branch.[0] = '-' then raise (Fatal "invalid branch name") else () let get_branches () : string list = let rec branch_loop acc q = match q with | [] -> acc | h::t -> begin let temp = ".cml/heads/"^h in if Sys.is_directory temp then let subs = temp |> Sys.readdir |> Array.to_list |> List.map (fun f -> h^"/"^f) in branch_loop acc t@subs else branch_loop (h::acc) t end in ".cml/heads" |> Sys.readdir |> Array.to_list |> branch_loop [] |> List.sort (Pervasives.compare) let get_current_branch () : string = try let ic = open_in ".cml/HEAD" in let raw = input_line ic in let _ = close_in ic in let split = (String.index raw '/') + 1 in String.sub raw split (String.length raw - split) with | Sys_error _ -> raise (Fatal "HEAD not found") | End_of_file -> raise (Fatal "HEAD not initialized") let get_branch_ptr (branch_name : string) : string = try let ic = open_in (".cml/heads/" ^ branch_name) in let ptr = input_line ic in close_in ic; ptr with | Sys_error _ -> raise (Fatal ("branch "^branch_name^" not found")) | End_of_file -> raise (Fatal (branch_name^" ptr not set")) let set_branch_ptr (branch_name : string) (commit_hash : string) : unit = try let oc = open_out (".cml/heads/" ^ branch_name) in output_string oc commit_hash; close_out oc with | Sys_error _ -> raise (Fatal "write error") let rec branch_help (path : string) (branch : string) : out_channel = try let slash = String.index branch '/' in let dir = String.sub branch 0 slash in let prefix = path^dir in if not (Sys.file_exists prefix) then mkdir prefix 0o777; (String.length branch - (slash+1)) |> String.sub branch (slash+1) |> branch_help (prefix^"/") with | Not_found -> open_out (path^"/"^branch) let create_branch (branch : string) (ptr : string) : unit = if (get_branches () |> List.mem branch) then raise (Fatal ("a branch named "^branch^" already exists")) else let _ = validate_branch branch in let oc = begin if String.contains branch '/' then branch_help ".cml/heads/" branch else open_out (".cml/heads/"^branch) end in output_string oc ptr; close_out oc let delete_branch (branch : string) : unit = if branch = get_current_branch () then raise (Fatal ("cannot delete branch '"^branch^"'")) else try if (get_branches () |> List.mem branch) then let _ = Sys.remove (".cml/heads/"^branch) in Print.print ("Deleted branch "^branch^"") else raise (Fatal ("branch '"^branch^"' not found")) with | Sys_error _ -> raise (Fatal "cannot perform such an operation") let switch_branch (branch : string) (isdetached : bool) : unit = let cur = if isdetached then "" else get_current_branch () in if cur = branch then Print.print ("Already on branch '"^branch^"'") else let oc = open_out ".cml/HEAD" in output_string oc ("heads/"^branch); close_out oc; Print.print ("Switched to branch '"^branch^"'")
9577acab680743e577028559d99c681b704384e56b860b088963ac4a5fe63a2e
dsorokin/aivika
MachRep3.hs
It corresponds to model MachRep3 described in document -- Introduction to Discrete-Event Simulation and the SimPy Language -- [/~matloff/156/PLN/DESimIntro.pdf]. SimPy is available on [ / ] . -- -- The model description is as follows. -- Variation of models MachRep1 , MachRep2 . Two machines , but -- sometimes break down. Up time is exponentially distributed with mean 1.0 , and repair time is exponentially distributed with mean 0.5 . In this example , there is only one repairperson , and she is not summoned -- until both machines are down. We find the proportion of up time. It should come out to about 0.45 . import Control.Monad import Control.Monad.Trans import Simulation.Aivika meanUpTime = 1.0 meanRepairTime = 0.5 specs = Specs { spcStartTime = 0.0, spcStopTime = 1000.0, spcDT = 1.0, spcMethod = RungeKutta4, spcGeneratorType = SimpleGenerator } model :: Simulation Results model = do -- number of machines currently up nUp <- newRef 2 -- total up time for all machines totalUpTime <- newRef 0.0 repairPerson <- newResource FCFS 1 pid1 <- newProcessId pid2 <- newProcessId let machine :: ProcessId -> Process () machine pid = do upTime <- randomExponentialProcess meanUpTime liftEvent $ modifyRef totalUpTime (+ upTime) liftEvent $ modifyRef nUp (+ (-1)) nUp' <- liftEvent $ readRef nUp if nUp' == 1 then passivateProcess else liftEvent $ do n <- resourceCount repairPerson when (n == 1) $ reactivateProcess pid requestResource repairPerson repairTime <- randomExponentialProcess meanRepairTime liftEvent $ modifyRef nUp (+ 1) releaseResource repairPerson machine pid runProcessInStartTimeUsingId pid1 (machine pid2) runProcessInStartTimeUsingId pid2 (machine pid1) let upTimeProp = do x <- readRef totalUpTime y <- liftDynamics time return $ x / (2 * y) return $ results [resultSource "upTimeProp" "The long-run proportion of up time (~ 0.45)" upTimeProp] main = printSimulationResultsInStopTime printResultSourceInEnglish model specs
null
https://raw.githubusercontent.com/dsorokin/aivika/7a14f460ab114b0f8cdfcd05d5cc889fdc2db0a4/examples/MachRep3.hs
haskell
Introduction to Discrete-Event Simulation and the SimPy Language [/~matloff/156/PLN/DESimIntro.pdf]. The model description is as follows. sometimes break down. Up time is exponentially distributed with mean until both machines are down. We find the proportion of up time. It number of machines currently up total up time for all machines
It corresponds to model MachRep3 described in document SimPy is available on [ / ] . Variation of models MachRep1 , MachRep2 . Two machines , but 1.0 , and repair time is exponentially distributed with mean 0.5 . In this example , there is only one repairperson , and she is not summoned should come out to about 0.45 . import Control.Monad import Control.Monad.Trans import Simulation.Aivika meanUpTime = 1.0 meanRepairTime = 0.5 specs = Specs { spcStartTime = 0.0, spcStopTime = 1000.0, spcDT = 1.0, spcMethod = RungeKutta4, spcGeneratorType = SimpleGenerator } model :: Simulation Results model = nUp <- newRef 2 totalUpTime <- newRef 0.0 repairPerson <- newResource FCFS 1 pid1 <- newProcessId pid2 <- newProcessId let machine :: ProcessId -> Process () machine pid = do upTime <- randomExponentialProcess meanUpTime liftEvent $ modifyRef totalUpTime (+ upTime) liftEvent $ modifyRef nUp (+ (-1)) nUp' <- liftEvent $ readRef nUp if nUp' == 1 then passivateProcess else liftEvent $ do n <- resourceCount repairPerson when (n == 1) $ reactivateProcess pid requestResource repairPerson repairTime <- randomExponentialProcess meanRepairTime liftEvent $ modifyRef nUp (+ 1) releaseResource repairPerson machine pid runProcessInStartTimeUsingId pid1 (machine pid2) runProcessInStartTimeUsingId pid2 (machine pid1) let upTimeProp = do x <- readRef totalUpTime y <- liftDynamics time return $ x / (2 * y) return $ results [resultSource "upTimeProp" "The long-run proportion of up time (~ 0.45)" upTimeProp] main = printSimulationResultsInStopTime printResultSourceInEnglish model specs
d0cc1a12e3f172a4ee8661db5051acfb2abf41ef2d5829790c04b90b22181329
Clozure/ccl-tests
load-pathnames.lsp
;-*- Mode: Lisp -*- Author : Created : Sat Nov 29 04:33:05 2003 ;;;; Contains: Load tests for pathnames and logical pathnames (in-package :cl-test) (compile-and-load "pathnames-aux.lsp") (load "pathnames.lsp") (load "pathname.lsp") (load "pathnamep.lsp") (load "make-pathname.lsp") (load "pathname-host.lsp") (load "pathname-device.lsp") (load "pathname-directory.lsp") (load "pathname-name.lsp") (load "pathname-type.lsp") (load "pathname-version.lsp") (load "load-logical-pathname-translations.lsp") (load "logical-pathname.lsp") (load "logical-pathname-translations.lsp") (load "translate-logical-pathname.lsp") (load "namestring.lsp") (load "file-namestring.lsp") (load "directory-namestring.lsp") (load "host-namestring.lsp") (load "enough-namestring.lsp") (load "wild-pathname-p.lsp") (load "merge-pathnames.lsp") (load "pathname-match-p.lsp") (load "parse-namestring.lsp")
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/load-pathnames.lsp
lisp
-*- Mode: Lisp -*- Contains: Load tests for pathnames and logical pathnames
Author : Created : Sat Nov 29 04:33:05 2003 (in-package :cl-test) (compile-and-load "pathnames-aux.lsp") (load "pathnames.lsp") (load "pathname.lsp") (load "pathnamep.lsp") (load "make-pathname.lsp") (load "pathname-host.lsp") (load "pathname-device.lsp") (load "pathname-directory.lsp") (load "pathname-name.lsp") (load "pathname-type.lsp") (load "pathname-version.lsp") (load "load-logical-pathname-translations.lsp") (load "logical-pathname.lsp") (load "logical-pathname-translations.lsp") (load "translate-logical-pathname.lsp") (load "namestring.lsp") (load "file-namestring.lsp") (load "directory-namestring.lsp") (load "host-namestring.lsp") (load "enough-namestring.lsp") (load "wild-pathname-p.lsp") (load "merge-pathnames.lsp") (load "pathname-match-p.lsp") (load "parse-namestring.lsp")
c61a2d7f0d74dca670688bb2a5293301df8b3f13df5932800913d537b344ff34
db48x/xe2
tutorial.lisp
(in-package :xong) ;;; Text labels (defcell balloon (categories :initform '(:drawn :actor)) text stroke-color background-color timeout) (define-method initialize balloon (&key text (stroke-color ".white") (background-color ".blue") (style :balloon) (timeout nil)) (setf <text> text) (setf <stroke-color> stroke-color) (setf <background-color> background-color) (setf <style> style) (setf <timeout> (if (floatp timeout) specify in ( roughly ) seconds if floating (truncate (* 15 timeout)) ;; leave as frames if integer timeout))) (define-method draw balloon (x y image) (clon:with-field-values (text style) self (let* ((offset (ecase style (:balloon 16) (:flat 0))) (x0 (+ x offset)) (y0 (+ y offset)) (x1 (+ x0 offset)) (y1 (+ y0 offset)) (margin 4) (height (+ (* 2 margin) (apply #'+ (mapcar #'formatted-line-height text)))) (width (+ (* 2 margin) (apply #'max (mapcar #'formatted-line-width text))))) (draw-box x1 y1 width height :stroke-color <stroke-color> :color <background-color> :destination image) (when (eq style :balloon) (draw-line x0 y0 x1 y1 :destination image)) (let ((x2 (+ margin x1)) (y2 (+ margin y1))) (dolist (line text) (render-formatted-line line x2 y2 :destination image) (incf y2 (formatted-line-height line))))))) (define-method run balloon () [expend-default-action-points self] (when (integerp <timeout>) (when (minusp (decf <timeout>)) [die self]))) Tutorial NPC : Beckoner (defparameter *greeting-text* '((("Hello there!")))) (defparameter *beckon-text* '((("Use the arrow keys")) (("to approach me.")))) (defparameter *success-text* '((("Good job. You've mastered the use")) (("of the arrow keys.")))) (defparameter *bye-text* '((("You can exit through one")) (("of the portals.")) (("Portals look like this: ") (nil :image "portal")))) (defcell beckoner (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 40)) (define-method emote beckoner (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run beckoner () (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *greeting-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *beckon-text*] (setf timeout 100)) (2 [emote self *success-text*] (incf state) (setf timeout 50)) (3 [emote self *bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (< [distance-to-player self] 5)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) Tutorial level 1 : (defvar *bricks* 0) (defcell brick (tile :initform "wall-red") (categories :initform '(:obstacle :paint-source :wall :brick)) (color :initform :red)) (define-method initialize brick () (incf *bricks*)) (define-method die brick () (decf *bricks*) [parent>>die self]) (defparameter *puck-welcome-text* '((("Hello and welcome to the tutorial!")))) (defparameter *puck-instruction-text* '((("Use CONTROL with an arrow-key to")) (("fire your puck at the bricks.")) (("See if you can break them all.")))) (defparameter *puck-success-text* '((("Good job. You've mastered the use")) (("of the puck.")))) (defparameter *puck-bye-text* '((("You can exit through the")) (("portal to the southeast.")))) (defcell puckman (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 10)) (define-method emote puckman (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run puckman () (message "BRICKS ~S" *bricks*) (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *puck-welcome-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *puck-instruction-text*] (setf timeout 200)) (2 [emote self *puck-success-text*] (incf state) (setf timeout 60)) (3 [emote self *puck-bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (zerop *bricks*)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) (define-prototype puckman-world (:parent xe2:=world=) (height :initform *xong-level-height*) (width :initform *xong-level-width*) (edge-condition :initform :block) (ambient-light :initform :total)) (define-method generate puckman-world (&rest args) [create-default-grid self] (setf <level> 0 *bricks* 0) (clon:with-fields (height width grid player) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =floor=) i j])) (dotimes (i 3) (dotimes (j 3) [drop-cell self (clone =brick=) (+ 10 i) (+ 10 j)])) (let ((puckman (clone =puckman=))) [drop-cell self puckman 3 5] [drop-cell self (clone =portal= :address '(=chevronman-world=) :text '((("To part 2")))) 18 30 :loadout t]))) (define-method begin-ambient-loop puckman-world () (play-music "sparqq" :loop t)) Tutorial level 2 : Chevrons (defvar *chevron-enemies* 0) (defcell enemy (tile :initform "enemy") (categories :initform '(:actor :target :obstacle :enemy :puck)) (direction :initform :east) (stepping :initform t)) (define-method kick enemy (direction) (setf <direction> direction)) (define-method run enemy () (clon:with-field-values (row column) self (when [obstacle-in-direction-p *world* row column <direction>] (setf <direction> (random-direction))) [move self <direction>]) [expend-action-points self 25]) (define-method loadout enemy () (incf *chevron-enemies*)) (define-method die enemy () (decf *chevron-enemies*) [parent>>die self]) (defparameter *chevron-welcome-text* '((("Now you'll learn about chevrons.")))) (defparameter *chevron-instruction-text* '((("Use ALT (or OPTION on the Mac)")) (("with an arrow-key to drop a chevron.")) (("The chevron directs enemies toward the")) (("direction it points in. See if you can")) (("defeat the enemy ") (nil :image "enemy") (" by directing it")) (("into the Black hole, i.e. ") (nil :image "hole") (" .")))) (defparameter *chevron-success-text* '((("Good job. You've mastered the use")) (("of the chevron.")))) (defparameter *chevron-bye-text* '((("You can exit through the")) (("portal to the northeast.")))) (defcell chevronman (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 10)) (define-method emote chevronman (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run chevronman () (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *chevron-welcome-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *chevron-instruction-text* 4.0] (setf timeout 300)) (2 [emote self *chevron-success-text*] (incf state) (setf timeout 50)) (3 [emote self *chevron-bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (zerop *chevron-enemies*)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) (define-prototype chevronman-world (:parent xe2:=world=) (height :initform *xong-level-height*) (width :initform *xong-level-width*) (edge-condition :initform :block) (ambient-light :initform :total)) (define-method generate chevronman-world (&rest args) [create-default-grid self] (setf <level> 0 *chevron-enemies* 0) (clon:with-fields (height width grid player) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =floor=) i j])) (let ((chevron-1 (clone =chevron=)) (chevron-2 (clone =chevron=)) (chevronman (clone =chevronman=)) (enemy (clone =enemy=))) [orient chevron-1 :east] [orient chevron-2 :west] [drop-cell self chevron-1 10 10] [drop-cell self chevron-2 10 20] (dotimes (n 9) [drop-cell self (clone =hole= :nospew t) 20 (+ n 11)]) (dotimes (n 9) [drop-cell self (clone =hole= :nospew t) 5 (+ n 11)]) (dotimes (n 5) (let ((diamond (clone =diamond=))) [drop-cell self diamond (+ 20 (random 5)) (+ 30 (random 10))] (when (= n 0) [drop diamond (clone =balloon= :text '((("Extra chevrons."))))]))) [drop-cell self enemy 10 15] [loadout enemy] [drop-cell self chevronman 20 5] [drop-cell self (clone =portal= :address '(=multiman-world=) :text '((("To part 3")))) 6 30 :loadout t]))) (define-method begin-ambient-loop chevronman-world () (play-music "phong" :loop t)) MULTIMAN : use multiple skills (defparameter *multi-welcome-text* '((("Now combine your skills")) (("to defeat multiple enemies.")))) (defparameter *multi-instruction-text* '((("Use multiple chevrons to direct")) (("enemies around the obstacles and")) (("into the black holes. Use the puck")) (("to break any bricks blocking your path.")))) (defparameter *multi-success-text* '((("Great! You've combined")) (("your skills and learned")) (("the basics of XONG.")))) (defparameter *multi-bye-text* '((("Exit through the portal to")) (("the northeast to begin")) (("playing Level 1 of XONG.")))) (defcell multiman (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 10)) (define-method emote multiman (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run multiman () (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *multi-welcome-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *multi-instruction-text* 4.0] (setf timeout 300)) (2 [emote self *multi-success-text*] (incf state) (setf timeout 35)) (3 [emote self *multi-bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (zerop *chevron-enemies*)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) (define-prototype multiman-world (:parent xe2:=world=) (height :initform *xong-level-height*) (width :initform *xong-level-width*) (edge-condition :initform :block) (ambient-light :initform :total)) (define-method generate multiman-world (&rest args) [create-default-grid self] (setf <level> 0 *chevron-enemies* 0) (labels ((drop-bulkhead (r c) (prog1 nil [drop-cell self (clone =bulkhead=) r c])) (drop-brick (r c) (prog1 nil [drop-cell self (clone =brick=) r c]))) (clon:with-fields (height width grid player) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =floor=) i j])) (let ((chevron-1 (clone =chevron=)) (chevron-2 (clone =chevron=)) (chevron-3 (clone =chevron=)) (chevron-4 (clone =chevron=)) (multiman (clone =multiman=)) (enemy-1 (clone =enemy=)) (enemy-2 (clone =enemy=))) [orient chevron-1 :east] [orient chevron-2 :west] [drop-cell self chevron-1 15 10] [drop-cell self chevron-2 15 20] [orient chevron-3 :east] [orient chevron-4 :west] [drop-cell self chevron-3 8 10] [drop-cell self chevron-4 8 20] (trace-row #'drop-bulkhead 5 8 22) (trace-row #'drop-bulkhead 17 8 22) (dotimes (n 8) [drop-cell self (clone =hole= :nospew t) 2 (+ n 11)]) (dotimes (n 8) [drop-cell self (clone =hole= :nospew t) 20 (+ n 11)]) (trace-rectangle #'drop-brick 1 10 3 10) (trace-rectangle #'drop-brick 19 10 3 10) (dotimes (n 5) (let ((diamond (clone =diamond=))) [drop-cell self diamond (+ 20 (random 5)) (+ 30 (random 10))] (when (= n 0) [drop diamond (clone =balloon= :text '((("Extra chevrons."))))]))) (dotimes (n 2) (let ((puckup (clone =puckup=))) [drop-cell self puckup (+ 20 (random 5)) (+ 3 (random 5))] (when (= n 0) [drop puckup (clone =balloon= :text '((("Extra pucks."))))]))) [drop-cell self enemy-1 15 18] [drop-cell self enemy-2 8 15] [loadout enemy-1] [loadout enemy-2] [drop-cell self multiman 15 25] [drop-cell self (clone =portal= :address (generate-level-address 1) :text '((("Exit to Level 1")))) 6 30 :loadout t])))) (define-method begin-ambient-loop multiman-world () (play-music "neon" :loop t))
null
https://raw.githubusercontent.com/db48x/xe2/7896fcc69f5c6e28eaf6f6abb7966d6663370a66/xong/tutorial.lisp
lisp
Text labels leave as frames if integer
(in-package :xong) (defcell balloon (categories :initform '(:drawn :actor)) text stroke-color background-color timeout) (define-method initialize balloon (&key text (stroke-color ".white") (background-color ".blue") (style :balloon) (timeout nil)) (setf <text> text) (setf <stroke-color> stroke-color) (setf <background-color> background-color) (setf <style> style) (setf <timeout> (if (floatp timeout) specify in ( roughly ) seconds if floating (truncate (* 15 timeout)) timeout))) (define-method draw balloon (x y image) (clon:with-field-values (text style) self (let* ((offset (ecase style (:balloon 16) (:flat 0))) (x0 (+ x offset)) (y0 (+ y offset)) (x1 (+ x0 offset)) (y1 (+ y0 offset)) (margin 4) (height (+ (* 2 margin) (apply #'+ (mapcar #'formatted-line-height text)))) (width (+ (* 2 margin) (apply #'max (mapcar #'formatted-line-width text))))) (draw-box x1 y1 width height :stroke-color <stroke-color> :color <background-color> :destination image) (when (eq style :balloon) (draw-line x0 y0 x1 y1 :destination image)) (let ((x2 (+ margin x1)) (y2 (+ margin y1))) (dolist (line text) (render-formatted-line line x2 y2 :destination image) (incf y2 (formatted-line-height line))))))) (define-method run balloon () [expend-default-action-points self] (when (integerp <timeout>) (when (minusp (decf <timeout>)) [die self]))) Tutorial NPC : Beckoner (defparameter *greeting-text* '((("Hello there!")))) (defparameter *beckon-text* '((("Use the arrow keys")) (("to approach me.")))) (defparameter *success-text* '((("Good job. You've mastered the use")) (("of the arrow keys.")))) (defparameter *bye-text* '((("You can exit through one")) (("of the portals.")) (("Portals look like this: ") (nil :image "portal")))) (defcell beckoner (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 40)) (define-method emote beckoner (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run beckoner () (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *greeting-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *beckon-text*] (setf timeout 100)) (2 [emote self *success-text*] (incf state) (setf timeout 50)) (3 [emote self *bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (< [distance-to-player self] 5)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) Tutorial level 1 : (defvar *bricks* 0) (defcell brick (tile :initform "wall-red") (categories :initform '(:obstacle :paint-source :wall :brick)) (color :initform :red)) (define-method initialize brick () (incf *bricks*)) (define-method die brick () (decf *bricks*) [parent>>die self]) (defparameter *puck-welcome-text* '((("Hello and welcome to the tutorial!")))) (defparameter *puck-instruction-text* '((("Use CONTROL with an arrow-key to")) (("fire your puck at the bricks.")) (("See if you can break them all.")))) (defparameter *puck-success-text* '((("Good job. You've mastered the use")) (("of the puck.")))) (defparameter *puck-bye-text* '((("You can exit through the")) (("portal to the southeast.")))) (defcell puckman (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 10)) (define-method emote puckman (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run puckman () (message "BRICKS ~S" *bricks*) (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *puck-welcome-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *puck-instruction-text*] (setf timeout 200)) (2 [emote self *puck-success-text*] (incf state) (setf timeout 60)) (3 [emote self *puck-bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (zerop *bricks*)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) (define-prototype puckman-world (:parent xe2:=world=) (height :initform *xong-level-height*) (width :initform *xong-level-width*) (edge-condition :initform :block) (ambient-light :initform :total)) (define-method generate puckman-world (&rest args) [create-default-grid self] (setf <level> 0 *bricks* 0) (clon:with-fields (height width grid player) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =floor=) i j])) (dotimes (i 3) (dotimes (j 3) [drop-cell self (clone =brick=) (+ 10 i) (+ 10 j)])) (let ((puckman (clone =puckman=))) [drop-cell self puckman 3 5] [drop-cell self (clone =portal= :address '(=chevronman-world=) :text '((("To part 2")))) 18 30 :loadout t]))) (define-method begin-ambient-loop puckman-world () (play-music "sparqq" :loop t)) Tutorial level 2 : Chevrons (defvar *chevron-enemies* 0) (defcell enemy (tile :initform "enemy") (categories :initform '(:actor :target :obstacle :enemy :puck)) (direction :initform :east) (stepping :initform t)) (define-method kick enemy (direction) (setf <direction> direction)) (define-method run enemy () (clon:with-field-values (row column) self (when [obstacle-in-direction-p *world* row column <direction>] (setf <direction> (random-direction))) [move self <direction>]) [expend-action-points self 25]) (define-method loadout enemy () (incf *chevron-enemies*)) (define-method die enemy () (decf *chevron-enemies*) [parent>>die self]) (defparameter *chevron-welcome-text* '((("Now you'll learn about chevrons.")))) (defparameter *chevron-instruction-text* '((("Use ALT (or OPTION on the Mac)")) (("with an arrow-key to drop a chevron.")) (("The chevron directs enemies toward the")) (("direction it points in. See if you can")) (("defeat the enemy ") (nil :image "enemy") (" by directing it")) (("into the Black hole, i.e. ") (nil :image "hole") (" .")))) (defparameter *chevron-success-text* '((("Good job. You've mastered the use")) (("of the chevron.")))) (defparameter *chevron-bye-text* '((("You can exit through the")) (("portal to the northeast.")))) (defcell chevronman (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 10)) (define-method emote chevronman (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run chevronman () (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *chevron-welcome-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *chevron-instruction-text* 4.0] (setf timeout 300)) (2 [emote self *chevron-success-text*] (incf state) (setf timeout 50)) (3 [emote self *chevron-bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (zerop *chevron-enemies*)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) (define-prototype chevronman-world (:parent xe2:=world=) (height :initform *xong-level-height*) (width :initform *xong-level-width*) (edge-condition :initform :block) (ambient-light :initform :total)) (define-method generate chevronman-world (&rest args) [create-default-grid self] (setf <level> 0 *chevron-enemies* 0) (clon:with-fields (height width grid player) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =floor=) i j])) (let ((chevron-1 (clone =chevron=)) (chevron-2 (clone =chevron=)) (chevronman (clone =chevronman=)) (enemy (clone =enemy=))) [orient chevron-1 :east] [orient chevron-2 :west] [drop-cell self chevron-1 10 10] [drop-cell self chevron-2 10 20] (dotimes (n 9) [drop-cell self (clone =hole= :nospew t) 20 (+ n 11)]) (dotimes (n 9) [drop-cell self (clone =hole= :nospew t) 5 (+ n 11)]) (dotimes (n 5) (let ((diamond (clone =diamond=))) [drop-cell self diamond (+ 20 (random 5)) (+ 30 (random 10))] (when (= n 0) [drop diamond (clone =balloon= :text '((("Extra chevrons."))))]))) [drop-cell self enemy 10 15] [loadout enemy] [drop-cell self chevronman 20 5] [drop-cell self (clone =portal= :address '(=multiman-world=) :text '((("To part 3")))) 6 30 :loadout t]))) (define-method begin-ambient-loop chevronman-world () (play-music "phong" :loop t)) MULTIMAN : use multiple skills (defparameter *multi-welcome-text* '((("Now combine your skills")) (("to defeat multiple enemies.")))) (defparameter *multi-instruction-text* '((("Use multiple chevrons to direct")) (("enemies around the obstacles and")) (("into the black holes. Use the puck")) (("to break any bricks blocking your path.")))) (defparameter *multi-success-text* '((("Great! You've combined")) (("your skills and learned")) (("the basics of XONG.")))) (defparameter *multi-bye-text* '((("Exit through the portal to")) (("the northeast to begin")) (("playing Level 1 of XONG.")))) (defcell multiman (tile :initform "npc") (state :initform 0) (categories :initform '(:obstacle :actor :npc)) (timeout :initform 10)) (define-method emote multiman (text &optional (timeout 3.0)) (let ((balloon (clone =balloon= :text text :timeout timeout))) [play-sample self "talk"] [drop self balloon])) (define-method run multiman () (clon:with-fields (state timeout) self [expend-default-action-points self] (labels ((act () (ecase state (0 [emote self *multi-welcome-text* 1.0] (incf state) (setf timeout 20)) (1 [emote self *multi-instruction-text* 4.0] (setf timeout 300)) (2 [emote self *multi-success-text*] (incf state) (setf timeout 35)) (3 [emote self *multi-bye-text*] (setf timeout 200))))) (if (and (not (= 3 state)) (zerop *chevron-enemies*)) (progn (setf state 2) (act)) (if (null timeout) (act) (when (minusp (decf timeout)) (setf timeout nil) (act))))))) (define-prototype multiman-world (:parent xe2:=world=) (height :initform *xong-level-height*) (width :initform *xong-level-width*) (edge-condition :initform :block) (ambient-light :initform :total)) (define-method generate multiman-world (&rest args) [create-default-grid self] (setf <level> 0 *chevron-enemies* 0) (labels ((drop-bulkhead (r c) (prog1 nil [drop-cell self (clone =bulkhead=) r c])) (drop-brick (r c) (prog1 nil [drop-cell self (clone =brick=) r c]))) (clon:with-fields (height width grid player) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =floor=) i j])) (let ((chevron-1 (clone =chevron=)) (chevron-2 (clone =chevron=)) (chevron-3 (clone =chevron=)) (chevron-4 (clone =chevron=)) (multiman (clone =multiman=)) (enemy-1 (clone =enemy=)) (enemy-2 (clone =enemy=))) [orient chevron-1 :east] [orient chevron-2 :west] [drop-cell self chevron-1 15 10] [drop-cell self chevron-2 15 20] [orient chevron-3 :east] [orient chevron-4 :west] [drop-cell self chevron-3 8 10] [drop-cell self chevron-4 8 20] (trace-row #'drop-bulkhead 5 8 22) (trace-row #'drop-bulkhead 17 8 22) (dotimes (n 8) [drop-cell self (clone =hole= :nospew t) 2 (+ n 11)]) (dotimes (n 8) [drop-cell self (clone =hole= :nospew t) 20 (+ n 11)]) (trace-rectangle #'drop-brick 1 10 3 10) (trace-rectangle #'drop-brick 19 10 3 10) (dotimes (n 5) (let ((diamond (clone =diamond=))) [drop-cell self diamond (+ 20 (random 5)) (+ 30 (random 10))] (when (= n 0) [drop diamond (clone =balloon= :text '((("Extra chevrons."))))]))) (dotimes (n 2) (let ((puckup (clone =puckup=))) [drop-cell self puckup (+ 20 (random 5)) (+ 3 (random 5))] (when (= n 0) [drop puckup (clone =balloon= :text '((("Extra pucks."))))]))) [drop-cell self enemy-1 15 18] [drop-cell self enemy-2 8 15] [loadout enemy-1] [loadout enemy-2] [drop-cell self multiman 15 25] [drop-cell self (clone =portal= :address (generate-level-address 1) :text '((("Exit to Level 1")))) 6 30 :loadout t])))) (define-method begin-ambient-loop multiman-world () (play-music "neon" :loop t))
2700473678a52c15ca5f17a9a9ee1d4bdc752e4ffdb122197f424bd95935e88c
bdeket/rktsicm
quad.rkt
#lang racket/base (require "quad/quad-flo.rkt" ) (provide (all-from-out "quad/quad-flo.rkt" ))
null
https://raw.githubusercontent.com/bdeket/rktsicm/588acaf709a0e652b6474921f85524926d0f218d/rktsicm/sicm/numerics/quad.rkt
racket
#lang racket/base (require "quad/quad-flo.rkt" ) (provide (all-from-out "quad/quad-flo.rkt" ))
57c86361accb3cfa133238b926406e72ced29fa650b96d797f0dc229fce2b5ae
dinosaure/cri
nickname.ml
type t = string module BNF = struct open Angstrom let nickname = peek_char >>= function | Some ('a' .. 'z' | 'A' .. 'Z' | '\x5b' .. '\x60' | '\x7b' .. '\x7d') -> ( take_while1 @@ function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '\x5b' .. '\x60' | '\x7b' .. '\x7d' | '-' -> true | _ -> false ) | _ -> fail "nickname" end let for_all p str = let res = ref true in for i = 0 to String.length str - 1 do res := !res && p str.[i] done ; !res let is = function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '-' | '\x5b' .. '\x60' | '\x7b' .. '\x7d' -> true | _ -> false let of_string ?(strict= false) str = if str = "" then Rresult.R.error_msgf "A nickname can not be empty" else if String.length str > 9 && strict then Rresult.R.error_msgf "A nickname can not be larger than 9 bytes" else match str.[0] with | 'a' .. 'z' | 'A' .. 'Z' | '\x5b' .. '\x60' | '\x7b' .. '\x7d' -> if for_all is str then Ok str else Rresult.R.error_msgf "Invalid nickname: %S" str | _ -> Rresult.R.error_msgf "Invalid nickname: %S" str ): according to RFC 2812 but be resilient * with larger nickname ( <3 @kit_ty_kate ) . * with larger nickname (<3 @kit_ty_kate). *) let is str = match of_string str with | Ok _ -> true | _ -> false let to_string x = x let of_string_exn ?strict str = match of_string ?strict str with | Ok v -> v | Error (`Msg err) -> invalid_arg err let pp = Fmt.string
null
https://raw.githubusercontent.com/dinosaure/cri/ef0a05a9d8c18a0cd35b9ad4984d8ea01ee64f03/lib/nickname.ml
ocaml
type t = string module BNF = struct open Angstrom let nickname = peek_char >>= function | Some ('a' .. 'z' | 'A' .. 'Z' | '\x5b' .. '\x60' | '\x7b' .. '\x7d') -> ( take_while1 @@ function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '\x5b' .. '\x60' | '\x7b' .. '\x7d' | '-' -> true | _ -> false ) | _ -> fail "nickname" end let for_all p str = let res = ref true in for i = 0 to String.length str - 1 do res := !res && p str.[i] done ; !res let is = function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '-' | '\x5b' .. '\x60' | '\x7b' .. '\x7d' -> true | _ -> false let of_string ?(strict= false) str = if str = "" then Rresult.R.error_msgf "A nickname can not be empty" else if String.length str > 9 && strict then Rresult.R.error_msgf "A nickname can not be larger than 9 bytes" else match str.[0] with | 'a' .. 'z' | 'A' .. 'Z' | '\x5b' .. '\x60' | '\x7b' .. '\x7d' -> if for_all is str then Ok str else Rresult.R.error_msgf "Invalid nickname: %S" str | _ -> Rresult.R.error_msgf "Invalid nickname: %S" str ): according to RFC 2812 but be resilient * with larger nickname ( <3 @kit_ty_kate ) . * with larger nickname (<3 @kit_ty_kate). *) let is str = match of_string str with | Ok _ -> true | _ -> false let to_string x = x let of_string_exn ?strict str = match of_string ?strict str with | Ok v -> v | Error (`Msg err) -> invalid_arg err let pp = Fmt.string
ca45a366430ba79ef8630f503122264df4fdb6d927060d8dad229afbc25fad76
transient-haskell/transient-stack
test5.hs
#!/usr/bin/env execthirdlinedocker.sh info : use sed -i ' s/\r//g ' file if report " /usr / bin / env : ‘ execthirdlinedocker.sh\r ’ : No such file or directory " LIB="./ " & & runghc -DDEBUG -i${LIB}/transient / src -i${LIB}/transient - universe / src -i${LIB}/axiom / src $ 1 $ { 2 } $ { 3 } {-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-} module Main where --import Transient.Move --import Transient.Move.Utils --import Transient.Logged import Transient.Internals import Transient.Indeterminism --import Transient.EVars import Network import Control.Applicative import Control.Concurrent import Control.Monad.IO.Class import System.Environment import System.IO.Unsafe import Data.Monoid import System.IO import Control.Monad import Data.Maybe import Control.Exception hiding (onException) import Data.Typeable import Data.IORef import Data.List((\\)) import Transient.Logged import Transient.Move import Data.Aeson import Transient.Parse import qualified Data.ByteString.Lazy.Char8 as BS -- async exceptions main1 = keep $ job <|> killer job= do abduce labelState "JOB" onException $ \(e :: SomeException) -> do th <- liftIO myThreadId liftIO $ print ("JOB", e,th) empty tmask $ liftIO $ print (sum [0..10000000 :: Int]) liftIO $ Main.loop [0..] "JOB" loop [] _ = return() loop xs msg = do threadDelay 1000000 print msg Main.loop (tail xs) msg killer = do abduce liftIO $ threadDelay 1000000 th <- threadState "JOB" liftIO $ throwTo th $ ErrorCall "sent async exception to JOB" killer2 = do abduce labelState "KILLER" onException $ \(e :: SomeException) -> do th <- liftIO myThreadId liftIO $ print ("KILLER", e,th) empty liftIO $ threadDelay 1000000 st <- getCont liftIO $ killChildren $ children $ fromJust $ parent st liftIO $ Main.loop [0..] "KILLER" return () tmask :: TransIO a -> TransIO a tmask proc = do (mr,_) <- liftIO $ mask_ $ runTransient proc if isJust mr then return $ fromJust mr else empty --------------------------------------------------------- withResource adquire release f= do r <- mask_ adquire f r release r tbracket adquire release = react (bracket adquire release) (return ()) < | > liftIO ( forever ( threadDelay maxBound ) ) main2= keep $ job1 job1= do onException $ \(e :: SomeException) -> do th <- liftIO myThreadId liftIO $ print ("JOB", e,th) empty r <- tbracket adquire release --labelState "JOB" w <- useResources $ do i <- choose[1,2] liftIO $ print "after adquire, managing resource" return $ r ++ " processed " ++ show i liftIO $ print w where adquire = do print "adquire" return "Resource" release _ = print "release" main= keep $ do setParseString "{\"username\":\"xyz\",\"password\":\"xyz\"}" r <- param liftIO $ print ("value=",r :: Value) where string= do d <- isDone if d then empty !> "empty" else tTakeWhile (\c -> c /= '}' && c /= ']' )
null
https://raw.githubusercontent.com/transient-haskell/transient-stack/dde6f6613a946d57bb70879a5c0e7e5a73a91dbe/transient/tests/test5.hs
haskell
# LANGUAGE ScopedTypeVariables, OverloadedStrings # import Transient.Move import Transient.Move.Utils import Transient.Logged import Transient.EVars async exceptions ------------------------------------------------------- labelState "JOB"
#!/usr/bin/env execthirdlinedocker.sh info : use sed -i ' s/\r//g ' file if report " /usr / bin / env : ‘ execthirdlinedocker.sh\r ’ : No such file or directory " LIB="./ " & & runghc -DDEBUG -i${LIB}/transient / src -i${LIB}/transient - universe / src -i${LIB}/axiom / src $ 1 $ { 2 } $ { 3 } module Main where import Transient.Internals import Transient.Indeterminism import Network import Control.Applicative import Control.Concurrent import Control.Monad.IO.Class import System.Environment import System.IO.Unsafe import Data.Monoid import System.IO import Control.Monad import Data.Maybe import Control.Exception hiding (onException) import Data.Typeable import Data.IORef import Data.List((\\)) import Transient.Logged import Transient.Move import Data.Aeson import Transient.Parse import qualified Data.ByteString.Lazy.Char8 as BS main1 = keep $ job <|> killer job= do abduce labelState "JOB" onException $ \(e :: SomeException) -> do th <- liftIO myThreadId liftIO $ print ("JOB", e,th) empty tmask $ liftIO $ print (sum [0..10000000 :: Int]) liftIO $ Main.loop [0..] "JOB" loop [] _ = return() loop xs msg = do threadDelay 1000000 print msg Main.loop (tail xs) msg killer = do abduce liftIO $ threadDelay 1000000 th <- threadState "JOB" liftIO $ throwTo th $ ErrorCall "sent async exception to JOB" killer2 = do abduce labelState "KILLER" onException $ \(e :: SomeException) -> do th <- liftIO myThreadId liftIO $ print ("KILLER", e,th) empty liftIO $ threadDelay 1000000 st <- getCont liftIO $ killChildren $ children $ fromJust $ parent st liftIO $ Main.loop [0..] "KILLER" return () tmask :: TransIO a -> TransIO a tmask proc = do (mr,_) <- liftIO $ mask_ $ runTransient proc if isJust mr then return $ fromJust mr else empty withResource adquire release f= do r <- mask_ adquire f r release r tbracket adquire release = react (bracket adquire release) (return ()) < | > liftIO ( forever ( threadDelay maxBound ) ) main2= keep $ job1 job1= do onException $ \(e :: SomeException) -> do th <- liftIO myThreadId liftIO $ print ("JOB", e,th) empty r <- tbracket adquire release w <- useResources $ do i <- choose[1,2] liftIO $ print "after adquire, managing resource" return $ r ++ " processed " ++ show i liftIO $ print w where adquire = do print "adquire" return "Resource" release _ = print "release" main= keep $ do setParseString "{\"username\":\"xyz\",\"password\":\"xyz\"}" r <- param liftIO $ print ("value=",r :: Value) where string= do d <- isDone if d then empty !> "empty" else tTakeWhile (\c -> c /= '}' && c /= ']' )
d28b91baaa873c2b9f75b5893c003e2597b6ce1a0930ed613e237b2268393584
klarna/jesse
jesse_schema_validator.erl
%%%============================================================================= Copyright 2014 Klarna AB %% 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. %% @doc Json schema validation module . %% This module is the core of jesse , it implements the validation functionality %% according to the standard. %% @end %%%============================================================================= -module(jesse_schema_validator). %% API -export([ validate/3 , validate_with_state/3 ]). %% Includes -include("jesse_schema_validator.hrl"). %%% API @doc against ` JsonSchema ' with ` Options ' . %% If the given json is valid, then it is returned to the caller as is, %% otherwise an exception will be thrown. -spec validate( JsonSchema :: jesse:json_term() , Data :: jesse:json_term() , Options :: [{Key :: atom(), Data :: any()}] ) -> {ok, jesse:json_term()} | no_return(). validate(JsonSchema, Value, Options) -> State = jesse_state:new(JsonSchema, Options), NewState = validate_with_state(JsonSchema, Value, State), {result(NewState), Value}. @doc against ` JsonSchema ' with ` State ' . %% If the given json is valid, then the latest state is returned to the caller, %% otherwise an exception will be thrown. -spec validate_with_state( JsonSchema :: jesse:json_term() , Data :: jesse:json_term() , State :: jesse_state:state() ) -> jesse_state:state() | no_return(). validate_with_state(JsonSchema, Value, State) -> SchemaVer = get_schema_ver(JsonSchema, State), select_and_run_validator(SchemaVer, JsonSchema, Value, State). Internal functions @doc Returns " $ schema " property from ` JsonSchema ' if it is present , otherwise the default schema version from ` State ' is returned . @private get_schema_ver(JsonSchema, State) -> case jesse_json_path:value(?_SCHEMA, JsonSchema, ?not_found) of ?not_found -> jesse_state:get_default_schema_ver(State); SchemaVer -> SchemaVer end. @doc Returns a result depending on ` State ' . @private result(State) -> ErrorList = jesse_state:get_error_list(State), case ErrorList of [] -> ok; _ -> throw(ErrorList) end. %% @doc Runs appropriate validator depending on schema version %% it is called with. @private select_and_run_validator(?json_schema_draft3, JsonSchema, Value, State) -> jesse_validator_draft3:check_value( Value , jesse_json_path:unwrap_value(JsonSchema) , State ); select_and_run_validator(SchemaURI, _JsonSchema, _Value, State) -> jesse_error:handle_schema_invalid({?schema_unsupported, SchemaURI}, State). %%% Local Variables: erlang - indent - level : 2 %%% End:
null
https://raw.githubusercontent.com/klarna/jesse/830738e8a03413851cc48a55a5e70f459391cc00/src/jesse_schema_validator.erl
erlang
============================================================================= 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. according to the standard. @end ============================================================================= API Includes API If the given json is valid, then it is returned to the caller as is, otherwise an exception will be thrown. If the given json is valid, then the latest state is returned to the caller, otherwise an exception will be thrown. @doc Runs appropriate validator depending on schema version it is called with. Local Variables: End:
Copyright 2014 Klarna AB Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @doc Json schema validation module . This module is the core of jesse , it implements the validation functionality -module(jesse_schema_validator). -export([ validate/3 , validate_with_state/3 ]). -include("jesse_schema_validator.hrl"). @doc against ` JsonSchema ' with ` Options ' . -spec validate( JsonSchema :: jesse:json_term() , Data :: jesse:json_term() , Options :: [{Key :: atom(), Data :: any()}] ) -> {ok, jesse:json_term()} | no_return(). validate(JsonSchema, Value, Options) -> State = jesse_state:new(JsonSchema, Options), NewState = validate_with_state(JsonSchema, Value, State), {result(NewState), Value}. @doc against ` JsonSchema ' with ` State ' . -spec validate_with_state( JsonSchema :: jesse:json_term() , Data :: jesse:json_term() , State :: jesse_state:state() ) -> jesse_state:state() | no_return(). validate_with_state(JsonSchema, Value, State) -> SchemaVer = get_schema_ver(JsonSchema, State), select_and_run_validator(SchemaVer, JsonSchema, Value, State). Internal functions @doc Returns " $ schema " property from ` JsonSchema ' if it is present , otherwise the default schema version from ` State ' is returned . @private get_schema_ver(JsonSchema, State) -> case jesse_json_path:value(?_SCHEMA, JsonSchema, ?not_found) of ?not_found -> jesse_state:get_default_schema_ver(State); SchemaVer -> SchemaVer end. @doc Returns a result depending on ` State ' . @private result(State) -> ErrorList = jesse_state:get_error_list(State), case ErrorList of [] -> ok; _ -> throw(ErrorList) end. @private select_and_run_validator(?json_schema_draft3, JsonSchema, Value, State) -> jesse_validator_draft3:check_value( Value , jesse_json_path:unwrap_value(JsonSchema) , State ); select_and_run_validator(SchemaURI, _JsonSchema, _Value, State) -> jesse_error:handle_schema_invalid({?schema_unsupported, SchemaURI}, State). erlang - indent - level : 2
e819dd9038e4c314080fe15674a3f399e19084eec6af730e508687e5a752e6bd
danieljharvey/mimsa
Shared.hs
module Calc.Parser.Shared ( inBrackets, myLexeme, withLocation, stringLiteral, addLocation, addTypeLocation, ) where import Calc.ExprUtils import Calc.Parser.Types import Calc.TypeUtils import Calc.Types.Annotation import Data.Functor (($>)) import Data.Text (Text) import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L between2 :: Char -> Char -> Parser a -> Parser a between2 a b parser = do _ <- myLexeme (char a) val <- parser _ <- myLexeme (char b) pure val withLocation :: (Annotation -> a -> b) -> Parser a -> Parser b withLocation withP p = do start <- getOffset value <- p end <- getOffset pure (withP (Location start end) value) | wraps any parser of Exprs and adds location information addLocation :: Parser ParserExpr -> Parser ParserExpr addLocation = withLocation (mapOuterExprAnnotation . const) -- | wraps any parser of Type and adds location information addTypeLocation :: Parser ParserType -> Parser ParserType addTypeLocation = withLocation (mapOuterTypeAnnotation . const) inBrackets :: Parser a -> Parser a inBrackets = between2 '(' ')' myLexeme :: Parser a -> Parser a myLexeme = L.lexeme (L.space space1 empty empty) stringLiteral :: Text -> Parser () stringLiteral s = myLexeme (string s) $> ()
null
https://raw.githubusercontent.com/danieljharvey/mimsa/c5bcab3e9f961216cea540edb95a8a66db773980/llvm-calc2/src/Calc/Parser/Shared.hs
haskell
| wraps any parser of Type and adds location information
module Calc.Parser.Shared ( inBrackets, myLexeme, withLocation, stringLiteral, addLocation, addTypeLocation, ) where import Calc.ExprUtils import Calc.Parser.Types import Calc.TypeUtils import Calc.Types.Annotation import Data.Functor (($>)) import Data.Text (Text) import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L between2 :: Char -> Char -> Parser a -> Parser a between2 a b parser = do _ <- myLexeme (char a) val <- parser _ <- myLexeme (char b) pure val withLocation :: (Annotation -> a -> b) -> Parser a -> Parser b withLocation withP p = do start <- getOffset value <- p end <- getOffset pure (withP (Location start end) value) | wraps any parser of Exprs and adds location information addLocation :: Parser ParserExpr -> Parser ParserExpr addLocation = withLocation (mapOuterExprAnnotation . const) addTypeLocation :: Parser ParserType -> Parser ParserType addTypeLocation = withLocation (mapOuterTypeAnnotation . const) inBrackets :: Parser a -> Parser a inBrackets = between2 '(' ')' myLexeme :: Parser a -> Parser a myLexeme = L.lexeme (L.space space1 empty empty) stringLiteral :: Text -> Parser () stringLiteral s = myLexeme (string s) $> ()
b1b6b01acc17c05a150432b79b369ddc1e71180ba377e93d14a24b29df3b7ed5
alanz/ghc-exactprint
CommentPlacement5.hs
module CommentPlacement5 where bar :: Foo -> () bar a = case a of GInt -> () -- GBool -> () bar _ = ()
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/3b36f5d0a498e31d882fe111304b2cf5ca6cad22/tests/examples/ghc92/CommentPlacement5.hs
haskell
GBool -> ()
module CommentPlacement5 where bar :: Foo -> () bar a = case a of GInt -> () bar _ = ()
c8581d50ba8da33d2993cc3931cb99f97b31ec2dfca3c1ae74000d8c8fed6db3
jackfirth/racket-expect
rackunit.rkt
#lang reprovide "private/rackunit/main.rkt"
null
https://raw.githubusercontent.com/jackfirth/racket-expect/9530df30537ae05400b6a3add9619e5f697dca52/rackunit.rkt
racket
#lang reprovide "private/rackunit/main.rkt"
706e153742e9dfbccb85a3b6b936a755c820b052cdeed2b1345a8c20765b1e13
Kakadu/fp2022
utils.mli
* Copyright 2021 - 2022 , * SPDX - License - Identifier : LGPL-3.0 - or - later val explode : string -> char list val implode : char list -> Stdlib.String.t val isChar : char -> bool val isDigit : char -> bool
null
https://raw.githubusercontent.com/Kakadu/fp2022/47f471ccdb86713930e4aa518a96bf4ce0b3e53f/Lua/lib/utils.mli
ocaml
* Copyright 2021 - 2022 , * SPDX - License - Identifier : LGPL-3.0 - or - later val explode : string -> char list val implode : char list -> Stdlib.String.t val isChar : char -> bool val isDigit : char -> bool
525c518d385311238c85e374b8acae66d293d04b7c814466321b1e9e37cfd083
vikram/lisplibraries
examples.lisp
Copyright ( c ) 2007 , 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. ;;; $ I d : examples.lisp , v 1.4 2007/10/01 19:57:15 xach Exp $ (defpackage #:vecto-examples (:use #:cl #:vecto)) (in-package #:vecto-examples) (defun radiant-lambda (file) (with-canvas (:width 90 :height 90) (let ((font (get-font "times.ttf")) (step (/ pi 7))) (set-font font 40) (translate 45 45) (draw-centered-string 0 -10 #(#x3BB)) (set-rgb-stroke 1 0 0) (centered-circle-path 0 0 35) (stroke) (set-rgba-stroke 0 0 1.0 0.5) (set-line-width 4) (dotimes (i 14) (with-graphics-state (rotate (* i step)) (move-to 30 0) (line-to 40 0) (stroke))) (save-png file)))) (defun feedlike-icon (file) (with-canvas (:width 100 :height 100) (set-rgb-fill 1.0 0.65 0.3) (rounded-rectangle 0 0 100 100 10 10) (fill-path) (set-rgb-fill 1.0 1.0 1.0) (centered-circle-path 20 20 10) (fill-path) (flet ((quarter-circle (x y radius) (let ((kappa (* +kappa+ radius))) (move-to (+ x radius) y) (curve-to (+ x radius) (+ y kappa) (+ x kappa) (+ y radius) x (+ y radius))))) (set-rgb-stroke 1.0 1.0 1.0) (set-line-width 15) (quarter-circle 20 20 30) (stroke) (quarter-circle 20 20 60) (stroke)) (save-png file))) (defun star-clipping (file) (with-canvas (:width 200 :height 200) (let ((size 100) (angle 0) (step (* 2 (/ (* pi 2) 5)))) (translate size size) (move-to 0 size) (dotimes (i 5) (setf angle (+ angle step)) (line-to (* (sin angle) size) (* (cos angle) size))) (even-odd-clip-path) (end-path-no-op) (flet ((circle (distance) (set-rgba-fill distance 0 0 (- 1.0 distance)) (centered-circle-path 0 0 (* size distance)) (fill-path))) (loop for i downfrom 1.0 by 0.05 repeat 20 do (circle i))) (save-png file))))
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/vecto-1.1/doc/examples.lisp
lisp
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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.
Copyright ( c ) 2007 , All Rights Reserved DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , $ I d : examples.lisp , v 1.4 2007/10/01 19:57:15 xach Exp $ (defpackage #:vecto-examples (:use #:cl #:vecto)) (in-package #:vecto-examples) (defun radiant-lambda (file) (with-canvas (:width 90 :height 90) (let ((font (get-font "times.ttf")) (step (/ pi 7))) (set-font font 40) (translate 45 45) (draw-centered-string 0 -10 #(#x3BB)) (set-rgb-stroke 1 0 0) (centered-circle-path 0 0 35) (stroke) (set-rgba-stroke 0 0 1.0 0.5) (set-line-width 4) (dotimes (i 14) (with-graphics-state (rotate (* i step)) (move-to 30 0) (line-to 40 0) (stroke))) (save-png file)))) (defun feedlike-icon (file) (with-canvas (:width 100 :height 100) (set-rgb-fill 1.0 0.65 0.3) (rounded-rectangle 0 0 100 100 10 10) (fill-path) (set-rgb-fill 1.0 1.0 1.0) (centered-circle-path 20 20 10) (fill-path) (flet ((quarter-circle (x y radius) (let ((kappa (* +kappa+ radius))) (move-to (+ x radius) y) (curve-to (+ x radius) (+ y kappa) (+ x kappa) (+ y radius) x (+ y radius))))) (set-rgb-stroke 1.0 1.0 1.0) (set-line-width 15) (quarter-circle 20 20 30) (stroke) (quarter-circle 20 20 60) (stroke)) (save-png file))) (defun star-clipping (file) (with-canvas (:width 200 :height 200) (let ((size 100) (angle 0) (step (* 2 (/ (* pi 2) 5)))) (translate size size) (move-to 0 size) (dotimes (i 5) (setf angle (+ angle step)) (line-to (* (sin angle) size) (* (cos angle) size))) (even-odd-clip-path) (end-path-no-op) (flet ((circle (distance) (set-rgba-fill distance 0 0 (- 1.0 distance)) (centered-circle-path 0 0 (* size distance)) (fill-path))) (loop for i downfrom 1.0 by 0.05 repeat 20 do (circle i))) (save-png file))))
5268483d17112f33f223ed9bd6da06e99cbcb09d13052f4eb8942a056e81f18a
tek/proteome
PersistLoadTest.hs
module Proteome.Test.PersistLoadTest where import qualified Data.Text.IO as Text import Exon (exon) import Path (absdir, reldir, relfile, toFilePath, (</>)) import Path.IO (createDirIfMissing) import qualified Polysemy.Test as Test import Polysemy.Test (UnitTest, assertJust, (===)) import Ribosome (pathText) import Ribosome.Api (bufferGetName, currentBufferPath, vimGetBuffers, vimSetOption) import Ribosome.Effect.Persist (Persist) import Ribosome.Effect.PersistPath (PersistPath) import qualified Ribosome.Persist as Persist import Ribosome.Test (resumeTestError) import qualified Proteome.Data.Env as Env import Proteome.Data.ProjectMetadata (ProjectMetadata (DirProject)) import Proteome.Data.ProjectName (ProjectName (ProjectName)) import Proteome.Data.ProjectRoot (ProjectRoot (ProjectRoot)) import Proteome.Data.ProjectType (ProjectType (ProjectType)) import qualified Proteome.PersistBuffers as PersistBuffers import Proteome.PersistBuffers (loadBuffers) import Proteome.Test.Run (interpretPersistTest, proteomeTest) main :: ProjectMetadata main = DirProject (ProjectName "flagellum") (ProjectRoot [absdir|/|]) (Just (ProjectType "haskell")) buffersJson :: Text -> Text buffersJson base = [exon|{"current":"#{base}/file2","buffers":["#{base}/file1","#{base}/file2","#{base}/file3"]}|] test_loadPersistedBuffers :: UnitTest test_loadPersistedBuffers = proteomeTest $ interpretPersistTest do vimSetOption "swapfile" False atomicModify' (#mainProject . #meta .~ main) persistBase <- resumeTestError @PersistPath Persist.persistRoot let persistDir = persistBase </> [reldir|buffers/haskell/flagellum|] createDirIfMissing True persistDir fixDir <- Test.fixturePath [reldir|persist/store|] embed (Text.writeFile (toFilePath (persistDir </> PersistBuffers.file)) (buffersJson (pathText fixDir))) resumeTestError @(Persist _) loadBuffers buffers <- vimGetBuffers 3 === length buffers active <- currentBufferPath assertJust (fixDir </> [relfile|file2|]) active (target fixDir ===) =<< traverse bufferGetName =<< atomicGets Env.buffers where target fixDir = pathText . (fixDir </>) <$> [[relfile|file1|], [relfile|file2|], [relfile|file3|]]
null
https://raw.githubusercontent.com/tek/proteome/019928432bd5f5ba87d35eab19e341a5c98b1bba/packages/proteome/test/Proteome/Test/PersistLoadTest.hs
haskell
module Proteome.Test.PersistLoadTest where import qualified Data.Text.IO as Text import Exon (exon) import Path (absdir, reldir, relfile, toFilePath, (</>)) import Path.IO (createDirIfMissing) import qualified Polysemy.Test as Test import Polysemy.Test (UnitTest, assertJust, (===)) import Ribosome (pathText) import Ribosome.Api (bufferGetName, currentBufferPath, vimGetBuffers, vimSetOption) import Ribosome.Effect.Persist (Persist) import Ribosome.Effect.PersistPath (PersistPath) import qualified Ribosome.Persist as Persist import Ribosome.Test (resumeTestError) import qualified Proteome.Data.Env as Env import Proteome.Data.ProjectMetadata (ProjectMetadata (DirProject)) import Proteome.Data.ProjectName (ProjectName (ProjectName)) import Proteome.Data.ProjectRoot (ProjectRoot (ProjectRoot)) import Proteome.Data.ProjectType (ProjectType (ProjectType)) import qualified Proteome.PersistBuffers as PersistBuffers import Proteome.PersistBuffers (loadBuffers) import Proteome.Test.Run (interpretPersistTest, proteomeTest) main :: ProjectMetadata main = DirProject (ProjectName "flagellum") (ProjectRoot [absdir|/|]) (Just (ProjectType "haskell")) buffersJson :: Text -> Text buffersJson base = [exon|{"current":"#{base}/file2","buffers":["#{base}/file1","#{base}/file2","#{base}/file3"]}|] test_loadPersistedBuffers :: UnitTest test_loadPersistedBuffers = proteomeTest $ interpretPersistTest do vimSetOption "swapfile" False atomicModify' (#mainProject . #meta .~ main) persistBase <- resumeTestError @PersistPath Persist.persistRoot let persistDir = persistBase </> [reldir|buffers/haskell/flagellum|] createDirIfMissing True persistDir fixDir <- Test.fixturePath [reldir|persist/store|] embed (Text.writeFile (toFilePath (persistDir </> PersistBuffers.file)) (buffersJson (pathText fixDir))) resumeTestError @(Persist _) loadBuffers buffers <- vimGetBuffers 3 === length buffers active <- currentBufferPath assertJust (fixDir </> [relfile|file2|]) active (target fixDir ===) =<< traverse bufferGetName =<< atomicGets Env.buffers where target fixDir = pathText . (fixDir </>) <$> [[relfile|file1|], [relfile|file2|], [relfile|file3|]]
5a8dfabd02ee3bbab145315e36fff3c5bf6e8a4d4b7715c4e16a42bc2bd7746d
pablo-meier/ScrabbleCheat
move.erl
-module(move). -define(SCRABBLE_RACK_SIZE, 7). -define(SCRABBLE_BINGO_BONUS, 50). -include("gameinfo.hrl"). -import(tile, [get_tile_letter/1, is_wildcard/1, get_tile_location/1, is_occupied/1, get_tile_bonus/1, duplicate_tile/2]). -import(board, [place_move_on_board/2, to_beginning/1, orthogonals/1, get_adjacent/3, zoom/3, flip/1]). -import(lists, [foldl/3, filter/2, any/2, map/2]). -export([new_move/0, verify/3, add_to_move/2, score/3, duplicate_moves/2, get_move_tiles/1, from_list/1]). %% The move datatype. Checks structural integrity of moves, not %% responsible for legal placement relative to a board, or dictionary %% checks. Implemented simply as a list of tuples. %% new_move :: () -> Move %% %% The atom prevents move from being flattened. new_move() -> {move, []}. %% add_to_move :: Tile * Move -> Move %% %% Adds to the move, or throws an error. add_to_move(Tile, Move) -> {move, MoveList} = Move, {Row, Col} = get_tile_location(Tile), WithinBounds = check_integrity(Row, Col), case WithinBounds of true -> {move, [Tile|MoveList]}; _False -> throw({out_of_bounds, {Row, Col}}) end. %% get_move_tiles :: Move -> [Tile] %% %% Evaluates to the tiles that compose the move. get_move_tiles({move, MoveList}) -> MoveList. duplicate_moves : : Move * Move - > Bool %% Given 2 moves , checks if they add the same tiles in the same places . %% Note that while it is prefereable to not generate duplicates in the first place , this might be a TODO for later . duplicate_moves({move, MoveList1}, {move, MoveList2}) -> lists:all(fun (X) -> lists:any(fun (Y) -> X =:= Y end, MoveList2) end, MoveList1) andalso lists:all(fun (X) -> lists:any(fun (Y) -> X =:= Y end, MoveList1) end, MoveList2). %% %% check_integrity :: Int * Int -> Bool check_integrity(Row, Col) -> Row =< 15 andalso Row >= 1 andalso Col =< 15 andalso Col >= 1. score : : Move * Board * ( ) - > Int %% %% Scores a move given a move, current board, and Game Name. Used to be implemented as a first - class function , but we move away due to a bug that was purely structural ( the first - class function needed to be recursive ; and dynamic recursive function in Erlang are balls . You 'd have to Y - Combinator that shit up . What I 'd %% do for a letrec. score(Move, Board, GameName) -> GameInfo = gameinfo:get_gameinfo(GameName), ScoreDist = GameInfo#gameinfo.scoredist, ScoreFun = dict_as_function(ScoreDist), Bingos = GameInfo#gameinfo.bingo_bonuses, BingoBonus = get_bingo_bonus_function(dict_as_function(Bingos)), Lst = get_move_tiles(Move), ZoomBackDir = to_beginning(get_move_orientation(Lst)), MockBoard = place_move_on_board(Move, Board), [ATile|_] = Lst, StartTile = zoom(ATile, ZoomBackDir, MockBoard), Forward = flip(ZoomBackDir), %% Calculate the score of the original move Original = score_wordpath(StartTile, Forward, MockBoard, Lst, 0, [], ScoreFun), Calculate the score of any moves Perpendiculars = score_perpendiculars(StartTile, Forward, MockBoard, Lst, 0, ScoreFun), Original + Perpendiculars + BingoBonus(Lst). dict_as_function : : > - > ( Key - > Value ) %% %% A dict is just a poor abstraction of a function. We just make it so ^_^ dict_as_function(Dict) -> fun (X) -> case dict:find(X, Dict) of error -> 0; {ok, Value} -> Value end end. %% get_bingo_bonus_function :: (Int -> Int) -> ([Tile] -> Int) %% %% Given a set of bonuses, produce a function that calculates the bingo bonus %% applicable to a given move. get_bingo_bonus_function(Bonuses) -> fun (Lst) -> Bonuses(length(Lst)) end. %% score_wordpath %% :: (Tile * Direction * Board * [Tile] * Int * [Bonus] * (String -> Int) -> Points) %% %% Given a function with a score distribution for the letters in the game (e.g. A is 1 point , Q is 10 ) , create a function that ' traces ' the score by following %% a path on the board. score_wordpath(Tile, Direction, Board, MoveComponents, Accum, Bonuses, ScoreFun) -> TilePoints = case is_wildcard(Tile) of true -> 0; false -> ScoreFun(get_tile_letter(Tile)) end, %% Adjust points for letter bonuses IsNew = is_part_of_new_move(Tile, MoveComponents), LetterBonus = get_tile_bonus(Tile), WithBonuses = case {LetterBonus, IsNew} of {double_letter_score, true} -> 2 * TilePoints; {triple_letter_score, true} -> 3 * TilePoints; _Else -> TilePoints end, %% Check word bonuses and whether or not they belong in the original move. BonusAcc = check_and_add_bonuses(Tile, MoveComponents, Bonuses), %% See if you can continue case get_adjacent(Tile, Board, Direction) of none -> foldl(fun (X, Y) -> X(Y) end, Accum + WithBonuses, BonusAcc); NewTile -> case is_occupied(NewTile) of true -> score_wordpath(NewTile, Direction, Board, MoveComponents, Accum + WithBonuses, BonusAcc, ScoreFun); false -> foldl(fun (X, Y) -> X(Y) end, Accum + WithBonuses, BonusAcc) end end. %% get_move_orientation :: [Tile] -> horizontal | vertical get_move_orientation([H|T]) -> {Row1, _} = get_tile_location(H), Horizontal = lists:all(fun (X) -> {Row2,_} = get_tile_location(X), Row2 =:= Row1 end, T), case Horizontal of true -> horizontal; _Else -> vertical end. %% from_list :: [Tile] -> Move %% %% Make a Move from a list of Tiles from_list(Lst) -> lists:foldl(fun (T, Acc) -> move:add_to_move(T, Acc) end, move:new_move(), Lst). %% score_perpendiculars :: Tile * Direction * Board * [Tile] * Int * (Char -> Int) -> Points %% %% Follows a path, and if it sees moves in perpendicular directions, scores them. score_perpendiculars(Tile, Direction, Board, MoveComponents, Accum, ScoreFun) -> %% See if you have a perpendicular path. OrthogonalTiles = map(fun (X) -> get_adjacent(Tile, Board, X) end, orthogonals(Direction)), Filtered = filter(fun (X) -> X =/= none end, OrthogonalTiles), Surrounding = filter(fun (ThisTile) -> is_occupied(ThisTile) end, Filtered), %% Ensure it's perpendicular to a tile that's fresh in this move. IsNew = is_part_of_new_move(Tile, MoveComponents), %% Score it as a word if there exists a perpendicular path to a new tile component. Points = case {Surrounding, IsNew} of {[], _} -> 0; {_, false} -> 0; _Else -> ZoomBackDir = to_beginning(hd(orthogonals(Direction))), StartTile = zoom(Tile, ZoomBackDir, Board), Forward = flip(ZoomBackDir), score_wordpath(StartTile, Forward, Board, MoveComponents, 0, [], ScoreFun) end, %% Continue if possible. case get_adjacent(Tile, Board, Direction) of none -> Points + Accum; NextTile -> case is_occupied(NextTile) of false -> Points + Accum; true -> score_perpendiculars(NextTile, Direction, Board, MoveComponents, Points + Accum, ScoreFun) end end. check_and_add_bonuses(Tile, MoveComponents, Bonuses) -> IsNew = is_part_of_new_move(Tile, MoveComponents), case {get_tile_bonus(Tile), IsNew} of {triple_word_score, true} -> [fun(X) -> 3 * X end|Bonuses]; {double_word_score, true} -> [fun(X) -> 2 * X end|Bonuses]; _Else -> Bonuses end. is_part_of_new_move(Tile, MoveComponents) -> any(fun (X) -> duplicate_tile(Tile, X) end, MoveComponents). %% verify :: Move * Board * Gamestate -> () %% %% Throws a BadMoveException if the move isn't valid. This can happen if it's empty, %% or disconnected from other moves on the board. verify(Move, Board, Gamestate) -> Tiles = get_move_tiles(Move), Dict = gamestate:get_gamestate_dict(Gamestate), case Tiles of [] -> throw_badMove("Move is empty!"); _Else -> WithMove = board:place_move_on_board(Move, Board), try Gaddag = scrabblecheat_main:get_master_gaddag(Dict), board:verify(WithMove, Gaddag) catch {badArgsException, _} -> throw_badMove("This move doesn't work with the board supplied in the gamestate.") end end. throw_badMove(Msg) -> Encoded = list_to_binary(Msg), throw({badArgsException, Encoded}).
null
https://raw.githubusercontent.com/pablo-meier/ScrabbleCheat/718cb768a910f2ba7ca6cd1d2aae0e342849bf0a/code/server/src/move.erl
erlang
The move datatype. Checks structural integrity of moves, not responsible for legal placement relative to a board, or dictionary checks. Implemented simply as a list of tuples. new_move :: () -> Move The atom prevents move from being flattened. add_to_move :: Tile * Move -> Move Adds to the move, or throws an error. get_move_tiles :: Move -> [Tile] Evaluates to the tiles that compose the move. Note that while it is prefereable to not generate duplicates in the %% check_integrity :: Int * Int -> Bool Scores a move given a move, current board, and Game Name. Used to be implemented do for a letrec. Calculate the score of the original move A dict is just a poor abstraction of a function. We just make it so ^_^ get_bingo_bonus_function :: (Int -> Int) -> ([Tile] -> Int) Given a set of bonuses, produce a function that calculates the bingo bonus applicable to a given move. score_wordpath :: (Tile * Direction * Board * [Tile] * Int * [Bonus] * (String -> Int) -> Points) Given a function with a score distribution for the letters in the game (e.g. a path on the board. Adjust points for letter bonuses Check word bonuses and whether or not they belong in the original move. See if you can continue get_move_orientation :: [Tile] -> horizontal | vertical from_list :: [Tile] -> Move Make a Move from a list of Tiles score_perpendiculars :: Tile * Direction * Board * [Tile] * Int * (Char -> Int) -> Points Follows a path, and if it sees moves in perpendicular directions, scores them. See if you have a perpendicular path. Ensure it's perpendicular to a tile that's fresh in this move. Score it as a word if there exists a perpendicular path to a new tile component. Continue if possible. verify :: Move * Board * Gamestate -> () Throws a BadMoveException if the move isn't valid. This can happen if it's empty, or disconnected from other moves on the board.
-module(move). -define(SCRABBLE_RACK_SIZE, 7). -define(SCRABBLE_BINGO_BONUS, 50). -include("gameinfo.hrl"). -import(tile, [get_tile_letter/1, is_wildcard/1, get_tile_location/1, is_occupied/1, get_tile_bonus/1, duplicate_tile/2]). -import(board, [place_move_on_board/2, to_beginning/1, orthogonals/1, get_adjacent/3, zoom/3, flip/1]). -import(lists, [foldl/3, filter/2, any/2, map/2]). -export([new_move/0, verify/3, add_to_move/2, score/3, duplicate_moves/2, get_move_tiles/1, from_list/1]). new_move() -> {move, []}. add_to_move(Tile, Move) -> {move, MoveList} = Move, {Row, Col} = get_tile_location(Tile), WithinBounds = check_integrity(Row, Col), case WithinBounds of true -> {move, [Tile|MoveList]}; _False -> throw({out_of_bounds, {Row, Col}}) end. get_move_tiles({move, MoveList}) -> MoveList. duplicate_moves : : Move * Move - > Bool Given 2 moves , checks if they add the same tiles in the same places . first place , this might be a TODO for later . duplicate_moves({move, MoveList1}, {move, MoveList2}) -> lists:all(fun (X) -> lists:any(fun (Y) -> X =:= Y end, MoveList2) end, MoveList1) andalso lists:all(fun (X) -> lists:any(fun (Y) -> X =:= Y end, MoveList1) end, MoveList2). check_integrity(Row, Col) -> Row =< 15 andalso Row >= 1 andalso Col =< 15 andalso Col >= 1. score : : Move * Board * ( ) - > Int as a first - class function , but we move away due to a bug that was purely structural ( the first - class function needed to be recursive ; and dynamic recursive function in Erlang are balls . You 'd have to Y - Combinator that shit up . What I 'd score(Move, Board, GameName) -> GameInfo = gameinfo:get_gameinfo(GameName), ScoreDist = GameInfo#gameinfo.scoredist, ScoreFun = dict_as_function(ScoreDist), Bingos = GameInfo#gameinfo.bingo_bonuses, BingoBonus = get_bingo_bonus_function(dict_as_function(Bingos)), Lst = get_move_tiles(Move), ZoomBackDir = to_beginning(get_move_orientation(Lst)), MockBoard = place_move_on_board(Move, Board), [ATile|_] = Lst, StartTile = zoom(ATile, ZoomBackDir, MockBoard), Forward = flip(ZoomBackDir), Original = score_wordpath(StartTile, Forward, MockBoard, Lst, 0, [], ScoreFun), Calculate the score of any moves Perpendiculars = score_perpendiculars(StartTile, Forward, MockBoard, Lst, 0, ScoreFun), Original + Perpendiculars + BingoBonus(Lst). dict_as_function : : > - > ( Key - > Value ) dict_as_function(Dict) -> fun (X) -> case dict:find(X, Dict) of error -> 0; {ok, Value} -> Value end end. get_bingo_bonus_function(Bonuses) -> fun (Lst) -> Bonuses(length(Lst)) end. A is 1 point , Q is 10 ) , create a function that ' traces ' the score by following score_wordpath(Tile, Direction, Board, MoveComponents, Accum, Bonuses, ScoreFun) -> TilePoints = case is_wildcard(Tile) of true -> 0; false -> ScoreFun(get_tile_letter(Tile)) end, IsNew = is_part_of_new_move(Tile, MoveComponents), LetterBonus = get_tile_bonus(Tile), WithBonuses = case {LetterBonus, IsNew} of {double_letter_score, true} -> 2 * TilePoints; {triple_letter_score, true} -> 3 * TilePoints; _Else -> TilePoints end, BonusAcc = check_and_add_bonuses(Tile, MoveComponents, Bonuses), case get_adjacent(Tile, Board, Direction) of none -> foldl(fun (X, Y) -> X(Y) end, Accum + WithBonuses, BonusAcc); NewTile -> case is_occupied(NewTile) of true -> score_wordpath(NewTile, Direction, Board, MoveComponents, Accum + WithBonuses, BonusAcc, ScoreFun); false -> foldl(fun (X, Y) -> X(Y) end, Accum + WithBonuses, BonusAcc) end end. get_move_orientation([H|T]) -> {Row1, _} = get_tile_location(H), Horizontal = lists:all(fun (X) -> {Row2,_} = get_tile_location(X), Row2 =:= Row1 end, T), case Horizontal of true -> horizontal; _Else -> vertical end. from_list(Lst) -> lists:foldl(fun (T, Acc) -> move:add_to_move(T, Acc) end, move:new_move(), Lst). score_perpendiculars(Tile, Direction, Board, MoveComponents, Accum, ScoreFun) -> OrthogonalTiles = map(fun (X) -> get_adjacent(Tile, Board, X) end, orthogonals(Direction)), Filtered = filter(fun (X) -> X =/= none end, OrthogonalTiles), Surrounding = filter(fun (ThisTile) -> is_occupied(ThisTile) end, Filtered), IsNew = is_part_of_new_move(Tile, MoveComponents), Points = case {Surrounding, IsNew} of {[], _} -> 0; {_, false} -> 0; _Else -> ZoomBackDir = to_beginning(hd(orthogonals(Direction))), StartTile = zoom(Tile, ZoomBackDir, Board), Forward = flip(ZoomBackDir), score_wordpath(StartTile, Forward, Board, MoveComponents, 0, [], ScoreFun) end, case get_adjacent(Tile, Board, Direction) of none -> Points + Accum; NextTile -> case is_occupied(NextTile) of false -> Points + Accum; true -> score_perpendiculars(NextTile, Direction, Board, MoveComponents, Points + Accum, ScoreFun) end end. check_and_add_bonuses(Tile, MoveComponents, Bonuses) -> IsNew = is_part_of_new_move(Tile, MoveComponents), case {get_tile_bonus(Tile), IsNew} of {triple_word_score, true} -> [fun(X) -> 3 * X end|Bonuses]; {double_word_score, true} -> [fun(X) -> 2 * X end|Bonuses]; _Else -> Bonuses end. is_part_of_new_move(Tile, MoveComponents) -> any(fun (X) -> duplicate_tile(Tile, X) end, MoveComponents). verify(Move, Board, Gamestate) -> Tiles = get_move_tiles(Move), Dict = gamestate:get_gamestate_dict(Gamestate), case Tiles of [] -> throw_badMove("Move is empty!"); _Else -> WithMove = board:place_move_on_board(Move, Board), try Gaddag = scrabblecheat_main:get_master_gaddag(Dict), board:verify(WithMove, Gaddag) catch {badArgsException, _} -> throw_badMove("This move doesn't work with the board supplied in the gamestate.") end end. throw_badMove(Msg) -> Encoded = list_to_binary(Msg), throw({badArgsException, Encoded}).
fb33f4680c1aac5f014cb51170d889aa00806708fbfd0cc8b5351dcb01977e8d
DogLooksGood/holdem
player_avatar_cards.cljs
(ns poker.components.player-avatar-cards (:require [nubank.workspaces.core :as ws] [nubank.workspaces.card-types.react :as ct.react] [poker.components.player-avatar :refer [player-avatar]] [reagent.core :as reagent])) (ws/defcard player-at-showdown (ct.react/react-card (reagent/as-element [player-avatar {:name "dog", :avatar "🐂", :status :player-status/acted, :stack 500, :showdown-cards [[:c :a] [:c :k]], :position "CO", :local/game-status :game-status/showdown}]))) (ws/defcard player-at-runner-prepare (ct.react/react-card (reagent/as-element [player-avatar {:name "dog", :avatar "🐂", :status :player-status/acted, :stack 500, :showdown-cards [[:c :a] [:c :k]], :position "CO", :local/game-status :game-status/runner-prepare}])))
null
https://raw.githubusercontent.com/DogLooksGood/holdem/bc0f93ed65cab54890c91f78bb95fe3ba020a41f/test/cljs/poker/components/player_avatar_cards.cljs
clojure
(ns poker.components.player-avatar-cards (:require [nubank.workspaces.core :as ws] [nubank.workspaces.card-types.react :as ct.react] [poker.components.player-avatar :refer [player-avatar]] [reagent.core :as reagent])) (ws/defcard player-at-showdown (ct.react/react-card (reagent/as-element [player-avatar {:name "dog", :avatar "🐂", :status :player-status/acted, :stack 500, :showdown-cards [[:c :a] [:c :k]], :position "CO", :local/game-status :game-status/showdown}]))) (ws/defcard player-at-runner-prepare (ct.react/react-card (reagent/as-element [player-avatar {:name "dog", :avatar "🐂", :status :player-status/acted, :stack 500, :showdown-cards [[:c :a] [:c :k]], :position "CO", :local/game-status :game-status/runner-prepare}])))
68720f712263ddd8e7467c2d0e6f849c12c28428c244526a720ffc29b00436f6
yzhs/ocamlllvm
asmpackager.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2002 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 . (* *) (***********************************************************************) $ Id$ " Package " a set of .cmx/.o files into one .cmx/.o file having the original compilation units as sub - modules . original compilation units as sub-modules. *) open Printf open Misc open Lambda open Clambda open Cmx_format type error = Illegal_renaming of string * string | Forward_reference of string * string | Wrong_for_pack of string * string | Linking_error | Assembler_error of string | File_not_found of string exception Error of error (* Read the unit information from a .cmx file. *) type pack_member_kind = PM_intf | PM_impl of unit_infos type pack_member = { pm_file: string; pm_name: string; pm_kind: pack_member_kind } let read_member_info pack_path file = let name = String.capitalize(Filename.basename(chop_extensions file)) in let kind = if Filename.check_suffix file ".cmx" then begin let (info, crc) = Compilenv.read_unit_info file in if info.ui_name <> name then raise(Error(Illegal_renaming(file, info.ui_name))); if info.ui_symbol <> (Compilenv.current_unit_infos()).ui_symbol ^ "__" ^ info.ui_name then raise(Error(Wrong_for_pack(file, pack_path))); Asmlink.check_consistency file info crc; Compilenv.cache_unit_info info; PM_impl info end else PM_intf in { pm_file = file; pm_name = name; pm_kind = kind } (* Check absence of forward references *) let check_units members = let rec check forbidden = function [] -> () | mb :: tl -> begin match mb.pm_kind with | PM_intf -> () | PM_impl infos -> List.iter (fun (unit, _) -> if List.mem unit forbidden then raise(Error(Forward_reference(mb.pm_file, unit)))) infos.ui_imports_cmx end; check (list_remove mb.pm_name forbidden) tl in check (List.map (fun mb -> mb.pm_name) members) members (* Make the .o file for the package *) let make_package_object ppf members targetobj targetname coercion = let objtemp = if !Clflags.keep_asm_file then chop_extension_if_any targetobj ^ ".pack" ^ Config.ext_obj else Put the full name of the module in the temporary file name to avoid collisions with MSVC 's link /lib in case of successive packs to avoid collisions with MSVC's link /lib in case of successive packs *) Filename.temp_file (Compilenv.make_symbol (Some "")) Config.ext_obj in let components = List.map (fun m -> match m.pm_kind with | PM_intf -> None | PM_impl _ -> Some(Ident.create_persistent m.pm_name)) members in Asmgen.compile_implementation (chop_extension_if_any objtemp) ppf (Translmod.transl_store_package components (Ident.create_persistent targetname) coercion); let objfiles = List.map (fun m -> chop_extension_if_any m.pm_file ^ Config.ext_obj) (List.filter (fun m -> m.pm_kind <> PM_intf) members) in let ok = Ccomp.call_linker Ccomp.Partial targetobj (objtemp :: objfiles) "" in remove_file objtemp; if not ok then raise(Error Linking_error) (* Make the .cmx file for the package *) let build_package_cmx members cmxfile = let unit_names = List.map (fun m -> m.pm_name) members in let filter lst = List.filter (fun (name, crc) -> not (List.mem name unit_names)) lst in let union lst = List.fold_left (List.fold_left (fun accu n -> if List.mem n accu then accu else n :: accu)) [] lst in let units = List.fold_right (fun m accu -> match m.pm_kind with PM_intf -> accu | PM_impl info -> info :: accu) members [] in let ui = Compilenv.current_unit_infos() in let pkg_infos = { ui_name = ui.ui_name; ui_symbol = ui.ui_symbol; ui_defines = List.flatten (List.map (fun info -> info.ui_defines) units) @ [ui.ui_symbol]; ui_imports_cmi = (ui.ui_name, Env.crc_of_unit ui.ui_name) :: filter(Asmlink.extract_crc_interfaces()); ui_imports_cmx = filter(Asmlink.extract_crc_implementations()); ui_approx = ui.ui_approx; ui_curry_fun = union(List.map (fun info -> info.ui_curry_fun) units); ui_apply_fun = union(List.map (fun info -> info.ui_apply_fun) units); ui_send_fun = union(List.map (fun info -> info.ui_send_fun) units); ui_force_link = List.exists (fun info -> info.ui_force_link) units; } in Compilenv.write_unit_info pkg_infos cmxfile (* Make the .cmx and the .o for the package *) let package_object_files ppf files targetcmx targetobj targetname coercion = let pack_path = match !Clflags.for_package with | None -> targetname | Some p -> p ^ "." ^ targetname in let members = map_left_right (read_member_info pack_path) files in check_units members; make_package_object ppf members targetobj targetname coercion; build_package_cmx members targetcmx (* The entry point *) let package_files ppf files targetcmx = let files = List.map (fun f -> try find_in_path !Config.load_path f with Not_found -> raise(Error(File_not_found f))) files in let prefix = chop_extensions targetcmx in let targetcmi = prefix ^ ".cmi" in let targetobj = chop_extension_if_any targetcmx ^ Config.ext_obj in let targetname = String.capitalize(Filename.basename prefix) in (* Set the name of the current "input" *) Location.input_name := targetcmx; (* Set the name of the current compunit *) Compilenv.reset ?packname:!Clflags.for_package targetname; try let coercion = Typemod.package_units files targetcmi targetname in package_object_files ppf files targetcmx targetobj targetname coercion with x -> remove_file targetcmx; remove_file targetobj; raise x (* Error report *) open Format let report_error ppf = function Illegal_renaming(file, id) -> fprintf ppf "Wrong file naming: %s@ contains the code for@ %s" file id | Forward_reference(file, ident) -> fprintf ppf "Forward reference to %s in file %s" ident file | Wrong_for_pack(file, path) -> fprintf ppf "File %s@ was not compiled with the `-for-pack %s' option" file path | File_not_found file -> fprintf ppf "File %s not found" file | Assembler_error file -> fprintf ppf "Error while assembling %s" file | Linking_error -> fprintf ppf "Error during partial linking"
null
https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/asmcomp/asmpackager.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* Read the unit information from a .cmx file. Check absence of forward references Make the .o file for the package Make the .cmx file for the package Make the .cmx and the .o for the package The entry point Set the name of the current "input" Set the name of the current compunit Error report
, projet Cristal , INRIA Rocquencourt Copyright 2002 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 . $ Id$ " Package " a set of .cmx/.o files into one .cmx/.o file having the original compilation units as sub - modules . original compilation units as sub-modules. *) open Printf open Misc open Lambda open Clambda open Cmx_format type error = Illegal_renaming of string * string | Forward_reference of string * string | Wrong_for_pack of string * string | Linking_error | Assembler_error of string | File_not_found of string exception Error of error type pack_member_kind = PM_intf | PM_impl of unit_infos type pack_member = { pm_file: string; pm_name: string; pm_kind: pack_member_kind } let read_member_info pack_path file = let name = String.capitalize(Filename.basename(chop_extensions file)) in let kind = if Filename.check_suffix file ".cmx" then begin let (info, crc) = Compilenv.read_unit_info file in if info.ui_name <> name then raise(Error(Illegal_renaming(file, info.ui_name))); if info.ui_symbol <> (Compilenv.current_unit_infos()).ui_symbol ^ "__" ^ info.ui_name then raise(Error(Wrong_for_pack(file, pack_path))); Asmlink.check_consistency file info crc; Compilenv.cache_unit_info info; PM_impl info end else PM_intf in { pm_file = file; pm_name = name; pm_kind = kind } let check_units members = let rec check forbidden = function [] -> () | mb :: tl -> begin match mb.pm_kind with | PM_intf -> () | PM_impl infos -> List.iter (fun (unit, _) -> if List.mem unit forbidden then raise(Error(Forward_reference(mb.pm_file, unit)))) infos.ui_imports_cmx end; check (list_remove mb.pm_name forbidden) tl in check (List.map (fun mb -> mb.pm_name) members) members let make_package_object ppf members targetobj targetname coercion = let objtemp = if !Clflags.keep_asm_file then chop_extension_if_any targetobj ^ ".pack" ^ Config.ext_obj else Put the full name of the module in the temporary file name to avoid collisions with MSVC 's link /lib in case of successive packs to avoid collisions with MSVC's link /lib in case of successive packs *) Filename.temp_file (Compilenv.make_symbol (Some "")) Config.ext_obj in let components = List.map (fun m -> match m.pm_kind with | PM_intf -> None | PM_impl _ -> Some(Ident.create_persistent m.pm_name)) members in Asmgen.compile_implementation (chop_extension_if_any objtemp) ppf (Translmod.transl_store_package components (Ident.create_persistent targetname) coercion); let objfiles = List.map (fun m -> chop_extension_if_any m.pm_file ^ Config.ext_obj) (List.filter (fun m -> m.pm_kind <> PM_intf) members) in let ok = Ccomp.call_linker Ccomp.Partial targetobj (objtemp :: objfiles) "" in remove_file objtemp; if not ok then raise(Error Linking_error) let build_package_cmx members cmxfile = let unit_names = List.map (fun m -> m.pm_name) members in let filter lst = List.filter (fun (name, crc) -> not (List.mem name unit_names)) lst in let union lst = List.fold_left (List.fold_left (fun accu n -> if List.mem n accu then accu else n :: accu)) [] lst in let units = List.fold_right (fun m accu -> match m.pm_kind with PM_intf -> accu | PM_impl info -> info :: accu) members [] in let ui = Compilenv.current_unit_infos() in let pkg_infos = { ui_name = ui.ui_name; ui_symbol = ui.ui_symbol; ui_defines = List.flatten (List.map (fun info -> info.ui_defines) units) @ [ui.ui_symbol]; ui_imports_cmi = (ui.ui_name, Env.crc_of_unit ui.ui_name) :: filter(Asmlink.extract_crc_interfaces()); ui_imports_cmx = filter(Asmlink.extract_crc_implementations()); ui_approx = ui.ui_approx; ui_curry_fun = union(List.map (fun info -> info.ui_curry_fun) units); ui_apply_fun = union(List.map (fun info -> info.ui_apply_fun) units); ui_send_fun = union(List.map (fun info -> info.ui_send_fun) units); ui_force_link = List.exists (fun info -> info.ui_force_link) units; } in Compilenv.write_unit_info pkg_infos cmxfile let package_object_files ppf files targetcmx targetobj targetname coercion = let pack_path = match !Clflags.for_package with | None -> targetname | Some p -> p ^ "." ^ targetname in let members = map_left_right (read_member_info pack_path) files in check_units members; make_package_object ppf members targetobj targetname coercion; build_package_cmx members targetcmx let package_files ppf files targetcmx = let files = List.map (fun f -> try find_in_path !Config.load_path f with Not_found -> raise(Error(File_not_found f))) files in let prefix = chop_extensions targetcmx in let targetcmi = prefix ^ ".cmi" in let targetobj = chop_extension_if_any targetcmx ^ Config.ext_obj in let targetname = String.capitalize(Filename.basename prefix) in Location.input_name := targetcmx; Compilenv.reset ?packname:!Clflags.for_package targetname; try let coercion = Typemod.package_units files targetcmi targetname in package_object_files ppf files targetcmx targetobj targetname coercion with x -> remove_file targetcmx; remove_file targetobj; raise x open Format let report_error ppf = function Illegal_renaming(file, id) -> fprintf ppf "Wrong file naming: %s@ contains the code for@ %s" file id | Forward_reference(file, ident) -> fprintf ppf "Forward reference to %s in file %s" ident file | Wrong_for_pack(file, path) -> fprintf ppf "File %s@ was not compiled with the `-for-pack %s' option" file path | File_not_found file -> fprintf ppf "File %s not found" file | Assembler_error file -> fprintf ppf "Error while assembling %s" file | Linking_error -> fprintf ppf "Error during partial linking"
c03904f459ec875d075044e0401cd8aed9faddd3dc3d6a4310ad955860bb5913
nervous-systems/kvlt
chan.cljc
(ns kvlt.test.chan (:require [kvlt.chan :as chan] #? (:clj [clojure.core.async :as async :refer [go]]) #? (:cljs [cljs.core.async :as async]) [kvlt.test.util :as util #?(:clj :refer :cljs :refer-macros) [deftest is=]]) #? (:cljs (:require-macros [cljs.core.async.macros :refer [go]]))) (deftest request! (let [chan (async/chan 1 (map (fn [{{x :body} :body}] [x "World"])))] (util/with-result (util/channel-promise (chan/request! {:url (str ":" util/local-port "/echo") :body "Hello" :as :edn} {:chan chan})) #(is= ['Hello "World"] %)))) (deftest websocket! (util/with-result (util/channel-promise (chan/websocket! (str "ws:" util/local-port "/ws-echo"))) (fn [ch] (util/channel-promise (go (async/>! ch "OK") (is= "OK" (async/<! ch)))))))
null
https://raw.githubusercontent.com/nervous-systems/kvlt/26fe43eb9de6d7cc7ad8a466953fa0ffe09889ca/test/kvlt/test/chan.cljc
clojure
(ns kvlt.test.chan (:require [kvlt.chan :as chan] #? (:clj [clojure.core.async :as async :refer [go]]) #? (:cljs [cljs.core.async :as async]) [kvlt.test.util :as util #?(:clj :refer :cljs :refer-macros) [deftest is=]]) #? (:cljs (:require-macros [cljs.core.async.macros :refer [go]]))) (deftest request! (let [chan (async/chan 1 (map (fn [{{x :body} :body}] [x "World"])))] (util/with-result (util/channel-promise (chan/request! {:url (str ":" util/local-port "/echo") :body "Hello" :as :edn} {:chan chan})) #(is= ['Hello "World"] %)))) (deftest websocket! (util/with-result (util/channel-promise (chan/websocket! (str "ws:" util/local-port "/ws-echo"))) (fn [ch] (util/channel-promise (go (async/>! ch "OK") (is= "OK" (async/<! ch)))))))
aecfc1832226b7f6a7beda41d19733db6a769f0ae1e775a8230b8d6cc548dadb
clojure-interop/aws-api
AWSServiceCatalogAsyncClientBuilder.clj
(ns com.amazonaws.services.servicecatalog.AWSServiceCatalogAsyncClientBuilder "Fluent builder for AWSServiceCatalogAsync. Use of the builder is preferred over using constructors of the client class." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.servicecatalog AWSServiceCatalogAsyncClientBuilder])) (defn *standard "returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.servicecatalog.AWSServiceCatalogAsyncClientBuilder`" (^com.amazonaws.services.servicecatalog.AWSServiceCatalogAsyncClientBuilder [] (AWSServiceCatalogAsyncClientBuilder/standard ))) (defn *default-client "returns: Default async client using the DefaultAWSCredentialsProviderChain and DefaultAwsRegionProviderChain chain - `com.amazonaws.services.servicecatalog.AWSServiceCatalogAsync`" (^com.amazonaws.services.servicecatalog.AWSServiceCatalogAsync [] (AWSServiceCatalogAsyncClientBuilder/defaultClient )))
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.servicecatalog/src/com/amazonaws/services/servicecatalog/AWSServiceCatalogAsyncClientBuilder.clj
clojure
(ns com.amazonaws.services.servicecatalog.AWSServiceCatalogAsyncClientBuilder "Fluent builder for AWSServiceCatalogAsync. Use of the builder is preferred over using constructors of the client class." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.servicecatalog AWSServiceCatalogAsyncClientBuilder])) (defn *standard "returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.servicecatalog.AWSServiceCatalogAsyncClientBuilder`" (^com.amazonaws.services.servicecatalog.AWSServiceCatalogAsyncClientBuilder [] (AWSServiceCatalogAsyncClientBuilder/standard ))) (defn *default-client "returns: Default async client using the DefaultAWSCredentialsProviderChain and DefaultAwsRegionProviderChain chain - `com.amazonaws.services.servicecatalog.AWSServiceCatalogAsync`" (^com.amazonaws.services.servicecatalog.AWSServiceCatalogAsync [] (AWSServiceCatalogAsyncClientBuilder/defaultClient )))
d9f88d01003efa13b2e870a2c13838d2c7b9d71d11de0d0a928cb5f6933bd5b7
sinahab/shamir-secret-sharing
UtilSpec.hs
module UtilSpec (main, spec) where import Test.Hspec import Util (combinations) -- `main` is here so that this module can be run from GHCi on its own. It is -- not needed for automatic spec discovery. main :: IO () main = hspec spec spec :: Spec spec = do describe "combinations" $ do it "Returns all possible combinations of n elements." $ do let myList = [1,2,3,4] combinations 1 myList `shouldBe` [[1], [2], [3], [4]] combinations 2 myList `shouldBe` [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]] combinations 3 myList `shouldBe` [[1,2,3], [1,2,4], [1,3,4], [2,3,4]] combinations 4 myList `shouldBe` [[1,2,3,4]]
null
https://raw.githubusercontent.com/sinahab/shamir-secret-sharing/9c39190f52f2316962d597fc5307819d68c7c790/test/UtilSpec.hs
haskell
`main` is here so that this module can be run from GHCi on its own. It is not needed for automatic spec discovery.
module UtilSpec (main, spec) where import Test.Hspec import Util (combinations) main :: IO () main = hspec spec spec :: Spec spec = do describe "combinations" $ do it "Returns all possible combinations of n elements." $ do let myList = [1,2,3,4] combinations 1 myList `shouldBe` [[1], [2], [3], [4]] combinations 2 myList `shouldBe` [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]] combinations 3 myList `shouldBe` [[1,2,3], [1,2,4], [1,3,4], [2,3,4]] combinations 4 myList `shouldBe` [[1,2,3,4]]
4307c48600638c6f2752bece8290a7f7547390e5109fd024a5cbc53a3e675353
mcorbin/tour-of-clojure
functions.clj
(defn add-five "Add 5 to the number `n`" [n] (+ 5 n)) (println (add-five 5)) (println (add-five 10.5) "\n") (def multiply "multiply the 2 parameters" (fn [n m] (+ n m) ;; do nothing (str "Hello " "world" "!") ;; do nothing (println "Side effects") ;; i/o (* m n))) ;;returned value (println (multiply 2 4) "\n") ;; you can define functions using #(...) (def add-three #(+ % 3)) (println (add-three 10) "\n") (def add #(+ %1 %2)) (println (add 10 5))
null
https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/resources/public/pages/code/functions.clj
clojure
do nothing do nothing i/o returned value you can define functions using #(...)
(defn add-five "Add 5 to the number `n`" [n] (+ 5 n)) (println (add-five 5)) (println (add-five 10.5) "\n") (def multiply "multiply the 2 parameters" (fn [n m] (println (multiply 2 4) "\n") (def add-three #(+ % 3)) (println (add-three 10) "\n") (def add #(+ %1 %2)) (println (add 10 5))
faaafbe88c5b8c64bbde2aaf1906f074a18b944ca12b89d9998be230ae144f74
nboldi/c-parser-in-haskell
PrettyPrint.hs
# LANGUAGE FlexibleInstances , FlexibleContexts , UndecidableInstances , NamedFieldPuns # -- | Adds source templates to a source tree and uses them -- to pretty print it with the original format. module MiniC.PrettyPrint where import SourceCode.SourceTree import SourceCode.ToSourceTree import MiniC.SourceNotation import MiniC.Representation import MiniC.RangeTree import Data.Maybe import Data.List import Data.Function import Text.Parsec.Pos import Text.Parsec.PosOps import Control.Lens import Control.Monad import Control.Applicative -- | Pretty prints an AST by using source templates stored as node info prettyPrint :: (Functor node, ToSourceRose node TemplateInfo) => node (NodeInfo TemplateInfo si) -> String prettyPrint = printRose . toRose . fmap (view sourceInfo) | Pretty prints a rose tree according to the source templates remainig from the original AST printRose :: SourceRose TemplateInfo -> String printRose r = printRose' [r] where printRose' :: [SourceRose TemplateInfo] -> String printRose' path = concatMap (printElem path) . nodeTemplate . roseInfo . head $ path printElem :: [SourceRose TemplateInfo] -> SourceTemplateElem -> String printElem _ (TextElem str) = str printElem path ni@(NodeElem i) = case resolveRoseInd i path of Right path -> printRose' path -- When only a part of the source tree is printed, -- linked nodes can be missing. -- Left err -> error ("Error while pretty printing: " -- ++ err ++ " in " ++ show (head path) -- ++ "\n\ninside\n" ++ show (head (tail path))) Left err -> "<???>"
null
https://raw.githubusercontent.com/nboldi/c-parser-in-haskell/1a92132e7d1b984cf93ec89d6836cc804257b57d/MiniC/PrettyPrint.hs
haskell
| Adds source templates to a source tree and uses them to pretty print it with the original format. | Pretty prints an AST by using source templates stored as node info When only a part of the source tree is printed, linked nodes can be missing. Left err -> error ("Error while pretty printing: " ++ err ++ " in " ++ show (head path) ++ "\n\ninside\n" ++ show (head (tail path)))
# LANGUAGE FlexibleInstances , FlexibleContexts , UndecidableInstances , NamedFieldPuns # module MiniC.PrettyPrint where import SourceCode.SourceTree import SourceCode.ToSourceTree import MiniC.SourceNotation import MiniC.Representation import MiniC.RangeTree import Data.Maybe import Data.List import Data.Function import Text.Parsec.Pos import Text.Parsec.PosOps import Control.Lens import Control.Monad import Control.Applicative prettyPrint :: (Functor node, ToSourceRose node TemplateInfo) => node (NodeInfo TemplateInfo si) -> String prettyPrint = printRose . toRose . fmap (view sourceInfo) | Pretty prints a rose tree according to the source templates remainig from the original AST printRose :: SourceRose TemplateInfo -> String printRose r = printRose' [r] where printRose' :: [SourceRose TemplateInfo] -> String printRose' path = concatMap (printElem path) . nodeTemplate . roseInfo . head $ path printElem :: [SourceRose TemplateInfo] -> SourceTemplateElem -> String printElem _ (TextElem str) = str printElem path ni@(NodeElem i) = case resolveRoseInd i path of Right path -> printRose' path Left err -> "<???>"
e5edd2366885295fe84e7e585ae982c8ea859e0e18e9220aedb923cbb17450d3
alanz/ghc-exactprint
T11077.hs
module T11077 (module X, foo) where import Data.List as X foo = undefined
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/T11077.hs
haskell
module T11077 (module X, foo) where import Data.List as X foo = undefined
d7cde20d7b825b5534f775b312966a52c8d4ae705a81e145b57807e023950a5e
sebashack/servantRestfulAPI
Interpreter.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # # LANGUAGE ScopedTypeVariables # module Domains.BookingDomain.Bookable.Interpreter ( bookableServer ) where import Data.ByteString.Char8 (pack) import Control.Monad.Except import Network.Wai import Servant import Servant.JuicyPixels import Data.Aeson import Data.Aeson.Types import Codec.Picture import Codec.Picture.Extra import Codec.Picture.Types import Domains.BookingDomain.Bookable.API import Configs.ConfigTypes import HelperLibs.MySQL.ActionRunner import Control.Monad.Trans.Reader import Control.Monad.IO.Class import Control.Monad (mapM) import Servant.JuicyPixels import HelperLibs.ElasticSearch.ResponseParser import HelperLibs.Interpreters.Bookable import HelperLibs.Interpreters.BookingDomain import qualified Data.ByteString.Base64 as B64 import qualified Database.Persist.MySQL as MySQL import qualified Data.CountryCodes as CC import qualified Schemas.SQL.DbTypes as DbT import qualified Repositories.BookableRepo.Operations as BR import qualified Repositories.ReservationRepo.Operations as RR (getBklReservedPrisInPeriod_, getBklReservedPrisAfter) import qualified Repositories.CancellationRepo.Operations as CR (getBklCancInfoInPeriod) import qualified Domains.BookingDomain.Bookable.DataTypes as BT import qualified Schemas.SQL.Reservation as RSC import qualified Data.ByteString.Lazy as LB (toStrict, fromStrict) import qualified Data.ByteString as SB (length, ByteString) import qualified Data.ByteString.Lazy.Char8 as L8 import qualified Data.Map.Strict as Map import qualified Data.Text as T import qualified Data.Time as TM import qualified Data.Text.Encoding as TE import qualified Data.Set as S import qualified HelperLibs.SCalendar.Operations as SC Given a BasicBookableData data type , this function indexes a Bookable , related to a Property , in DB . Note that the user who wants to create a Bookable must match the Property whose ID he 's providing . -- Also note that we are using sets for roomIds so that we avoid repetition. postBookable :: ConfigMySQL -> ConfigES -> Maybe T.Text -> BT.BasicBookableData -> ExceptT ServantErr IO BT.Bookable postBookable _ _ Nothing _ = throwError _noToken postBookable coMysql coEs (Just token) bookData = do bookCreation <- liftIO $ runMySQL coMysql $ do let propId = BT.propId bookData adminCreds <- validateAdminAndMatchProperty coEs token propId case adminCreds of Left error -> return $ Left error Right (userId, _, _, propType, facs, cCode, region, city) -> do case validateBasicBookData bookData of Left error -> return $ Left error Right validatedData -> do let (BT.BasicBookableData propId bklSpecs esDesc enDesc maxOccu roomIds) = validatedData (BT.BookableSpecs name roomSize bedType bedNum amenities) = bklSpecs jsonRes <- liftIO $ runExceptT $ BR.indexBookable coEs propId (name, roomSize, bedType, bedNum, amenities) esDesc enDesc maxOccu (S.toList roomIds) (cCode, region, city) propType facs case jsonRes of Left error -> return indexBookErr Right (Object object) -> return $ maybe bookParsingErr (\(String bookId) -> Right (bookId, cCode, validatedData)) (parseMaybe (object .:) "_id") case getCustomError bookCreation of Left error -> throwError error Right (bookId, cCode, validatedData) -> return $ BT.Bookable bookId (CC.fromText cCode) BT.Unlisted validatedData S.empty -- Given a bookableId, get that bookable. getBookable :: ConfigES -> T.Text -> ExceptT ServantErr IO BT.Bookable getBookable config bookId = do jsonRes <- liftIO $ runExceptT $ BR.queryBookableById config bookId case jsonRes of Left _ -> throwError _bookNotFound Right (Object object) -> maybe (throwError _bookParsingErr) (\bookable -> return bookable) (parseBookable object) -- Given a bookableId change the state of that bookable to Listed if possible. Note that if a Bookable has no images , it can not be listed . listBookable :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () listBookable _ _ _ Nothing = throwError _noToken listBookable coMysql coEs bookId (Just token) = do update <- liftIO $ runMySQL coMysql $ do imgCount <- BR.bookableImageCount bookId if imgCount < 1 then return bklNoImgs else updateBookable coEs bookId token True isListable (\v -> Right v) (\a b -> b) BR.updateBookableState either (\err -> throwError err) (\v -> return ()) (getCustomError update) -- Given a bookableId change the state of that bookable to Unlisted if possible. unlistBookable :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () unlistBookable _ _ _ Nothing = throwError _noToken unlistBookable coMysql coEs bookId (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token False isUnlistable (\v -> Right v) (\a b -> b) BR.updateBookableState either (\err -> throwError err) (\v -> return ()) (getCustomError update) Given a bookableId and a description , update that bookable 's spanish description . updateBookableEsDesc :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> T.Text -> ExceptT ServantErr IO () updateBookableEsDesc _ _ _ Nothing _ = throwError _noToken updateBookableEsDesc coMysql coEs bookId (Just token) desc = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token desc (\x -> Right ()) (\x -> (either (\e -> Left e) (\v -> Right v) (validateDescription x))) (\a b -> b) BR.updateBookableEsDesc either (\err -> throwError err) (\v -> return ()) (getCustomError update) Given a bookableId and a description , update that bookable 's english description . updateBookableEnDesc :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> T.Text -> ExceptT ServantErr IO () updateBookableEnDesc _ _ _ Nothing _ = throwError _noToken updateBookableEnDesc coMysql coEs bookId (Just token) desc = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token desc (\x -> Right ()) (\x -> (either (\e -> Left e) (\v -> Right v) (validateDescription x))) (\a b -> b) BR.updateBookableEnDesc either (\err -> throwError err) (\v -> return ()) (getCustomError update) -- Given a BookableSpecs data type and a bookableId, update that bookable's specs. Note that as -- roomSize and bedType are optional fields, if invalid values are provided, a null will be stored in DB. updateBookableSpecs :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> BT.BookableSpecs -> ExceptT ServantErr IO () updateBookableSpecs _ _ _ Nothing _ = throwError _noToken updateBookableSpecs coMysql coEs bookId (Just token) specs = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token specs (\x -> Right ()) validation (\a b -> b) BR.updateBookableSpecs either (\err -> throwError err) (\v -> return ()) (getCustomError update) where validation bklSpecs = case validateBookSpecs bklSpecs of Left error -> Left error Right (BT.BookableSpecs name roomSize bedType bedNum amenities) -> Right (name, roomSize, bedType, bedNum, amenities) -- Given a maximum occupancy and a bookableId, update that bookable's maximum occupancy if it is valid. Note that if -- the given maxOccu is less than the occupancy of any of that bookable's pricings, an error is thrown. updateBookableMaxOccu :: ConfigMySQL -> ConfigES -> T.Text -> Int -> Maybe T.Text -> ExceptT ServantErr IO () updateBookableMaxOccu _ _ _ _ Nothing = throwError _noToken updateBookableMaxOccu coMysql coEs bookId maxOccu (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token maxOccu (checkMaxOccuAndPricings maxOccu) validateMaxOccupancy (\a b -> b) BR.updateBookableMaxOccu either (\err -> throwError err) (\v -> return ()) (getCustomError update) where checkMaxOccuAndPricings n (BT.Bookable bookId cCode status bookData pricings) | all (\pri -> if n >= BT.occupancy (BT.priData pri) then True else False) pricings = Right () | otherwise = maxOccuPriErr -- Given a list of roomIds and a bookable's id, add that list into that bookable's set of identifiers, if they're valid. -- Note that as the API internally uses sets, if the list of rooms has duplicates, they will be eliminated. Also, -- if you try to add a room aidentifier which was already a member of the set, it won't generate a duplicate. The list of room identifiers can not be greater than 100 elements . addBookableRoomIds :: ConfigMySQL -> ConfigES -> T.Text -> [T.Text] -> Maybe T.Text -> ExceptT ServantErr IO () addBookableRoomIds _ _ _ _ Nothing = throwError _noToken addBookableRoomIds coMysql coEs bookId roomIds (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token (S.fromList roomIds) takeRoomIds validateRoomIds (\a b -> S.toList $ S.union a b) BR.updateBookableRoomIds either (\err -> throwError err) (\v -> return ()) (getCustomError update) -- Given a list of roomIds and a bookable's id, delete that list from that bookable's set of identifiers, if they're valid. -- Note that as the API internally uses sets, if the list of rooms has duplicates, they will be eliminated. Also, -- if you try to delete a room identifier which wasn't a member of the set it won't have any effect. -- If the list of roomIds becomes empty, the bookable will be automatically unlisted. removeBookableRoomIds :: ConfigMySQL -> ConfigES -> T.Text -> [T.Text] -> Maybe T.Text -> ExceptT ServantErr IO () removeBookableRoomIds _ _ _ _ Nothing = throwError _noToken removeBookableRoomIds coMysql coEs bookId roomIds (Just token) = do update <- liftIO $ runMySQL coMysql $ do roomIds <- updateBookable coEs bookId token (S.fromList roomIds) takeRoomIds validateRoomIds (\a b -> S.toList $ S.difference a b) BR.updateBookableRoomIds case roomIds of Left error -> return $ Left error Right [] -> do jsonRes <-liftIO $ runExceptT $ BR.updateBookableState coEs bookId False return $ either (\err -> updateBookErr) (\v -> return ()) jsonRes _ -> return $ Right () either (\err -> throwError err) (\v -> return ()) (getCustomError update) Given a PricingData data type , and a bookableId , add new pricing into that bookable 's set of pricings , if the data is valid . Note that a Bookable can not have more than 15 pricings . Also , a pricing can not have an occupancy greater than the maximum occupancy of the Bookable . addBookablePricing :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> BT.PricingData -> ExceptT ServantErr IO () addBookablePricing _ _ _ Nothing _ = throwError _noToken addBookablePricing coMysql coEs bookId (Just token) priData = do update <- liftIO $ runMySQL coMysql $ do currentDate <- liftIO TM.getCurrentTime let priId = genPricingId bookId currentDate updateBookable coEs bookId token priData (takePricings occu) (validatePricingData priId) (\set val -> fmap pricingToTuple (S.toList $ S.insert val set)) BR.updateBookablePricings either (\err -> throwError err) (\v -> return ()) (getCustomError update) where (BT.PricingData occu conds price disc) = priData takePricings :: Int -> BT.Bookable -> Either String (S.Set BT.Pricing) takePricings n bkl | n > maxOccu = priOccuTooLarge | n < 1 = badPriOccupancy | S.size (BT.pricings bkl) >= 16 = tooManyPricings | otherwise = Right $ BT.pricings bkl where maxOccu = BT.maxOccu (BT.basicData bkl) Given a PrcingData data type , a bookableId and a PricingId , update the information concerning that Pricing , if the -- data is valid. Again, a pricing cannot have an occupancy greater than the maximum occupancy of the bookable. updateBookablePricing :: ConfigMySQL -> ConfigES -> T.Text -> T.Text -> Maybe T.Text -> BT.PricingData -> ExceptT ServantErr IO () updateBookablePricing _ _ _ _ Nothing _ = throwError _noToken updateBookablePricing coMysql coEs bookId priId (Just token) priData = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token priData (takePricings occu priId) (validatePricingData priId) (\set val -> fmap pricingToTuple (S.toList $ S.insert val set)) BR.updateBookablePricings either (\err -> throwError err) (\v -> return ()) (getCustomError update) where (BT.PricingData occu conds price disc) = priData takePricings :: Int -> T.Text -> BT.Bookable -> Either String (S.Set BT.Pricing) takePricings n priId bkl | n > maxOccu = priOccuTooLarge | n < 1 = badPriOccupancy | S.notMember dummyPricing (BT.pricings bkl) = priNotFound | otherwise = Right $ BT.pricings bkl where maxOccu = BT.maxOccu (BT.basicData bkl) dummyPricing = (BT.Pricing priId (BT.PricingData 0 [] 0 0)) -- Given a bookableId and a pricingId, remove that pricing from that bookable's set of pricings. If the given pricingId -- does not point to pricing in the that bookable's set, this operation has no effect. Also note that if the list of -- pricings becomes empty, that bookable will be automatically unlisted. removeBookablePricing :: ConfigMySQL -> ConfigES -> T.Text -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () removeBookablePricing _ _ _ _ Nothing = throwError _noToken removeBookablePricing coMysql coEs bookId priId (Just token) = do update <- liftIO $ runMySQL coMysql $ do pricings <- updateBookable coEs bookId token (BT.Pricing priId (BT.PricingData 0 [] 0 0)) takePricings (\v -> Right v) (\set val -> fmap pricingToTuple (S.toList $ S.delete val set)) BR.updateBookablePricings case pricings of Left error -> return $ Left error Right [] -> do jsonRes <-liftIO $ runExceptT $ BR.updateBookableState coEs bookId False return $ either (\err -> updateBookErr) (\v -> return ()) jsonRes _ -> return $ Right () either (\err -> throwError err) (\v -> return ()) (getCustomError update) where takePricings bkl = Right $ BT.pricings bkl -- Given a propertyId, get all the bookables related to that property. getPropBookables :: ConfigES -> T.Text -> ExceptT ServantErr IO [BT.Bookable] getPropBookables config propId = do jsonRes <- liftIO $ runExceptT $ BR.queryBookablesByProp config propId case jsonRes of Left _ -> throwError _searchBookErr Right (Object object) -> maybe (throwError _bookParsingErr) (\bookables -> return bookables) (parseBookables object) Given a bookableId and a jpeg DynamicImage , store that image in DB . This function returns the i d of -- that image. postBookableImg :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> DynamicImage -> ExceptT ServantErr IO T.Text postBookableImg _ _ _ Nothing _ = throwError _noToken postBookableImg coMysql coEs bookId (Just token) (ImageYCbCr8 imgJPEG) = do postImg <- liftIO $ runMySQL coMysql $ do adminCreds <- validateAdminPropBkl coEs bookId token case adminCreds of Left error -> return $ Left error Right (userId, propId) -> do imgCount <- BR.bookableImageCount bookId if imgCount > 15 then return tooMuchImgs else do let encodedImg = LB.toStrict (encodeJpegAtQuality 100 imgJPEG) numBytes = SB.length encodedImg case checkImgBound numBytes of LT -> return tooSmallImage GT -> return tooLargeImage EQ -> do imgId <- BR.storeBookableImg bookId encodedImg return $ Right imgId either (\err -> throwError err) (\v -> return v) (getCustomError postImg) -- Given a bookableId, get all the imageIds related to that bookable. getBookableImageIds :: ConfigMySQL -> T.Text -> ExceptT ServantErr IO [T.Text] getBookableImageIds coMysql bookId = do imgIds <- liftIO $ runMySQL coMysql $ BR.bookableImageIds bookId return imgIds -- Given a bokableId and an imageId, delete that bookable's image. If the bookable happens to have no images at all, -- it will be automatically unlisted. deleteBookableImg :: ConfigMySQL -> ConfigES -> T.Text -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () deleteBookableImg _ _ _ _ Nothing = throwError _noToken deleteBookableImg coMysql coEs bookId imgId (Just token) = do postImg <- liftIO $ runMySQL coMysql $ do adminCreds <- validateAdminPropBkl coEs bookId token case adminCreds of Left error -> return $ Left error Right (userId, propId) -> do BR.deleteBookableImg bookId imgId imgCount <- BR.bookableImageCount bookId if imgCount > 0 then return $ Right () else do jsonRes <-liftIO $ runExceptT $ BR.updateBookableState coEs bookId False return $ either (\err -> updateBookErr) (\v -> return ()) jsonRes either (\err -> throwError err) (\v -> return ()) (getCustomError postImg) -- Given a bookableId and a period of time (Period from to) this function returns a EconomicReport -- of all reservedPricings and cancellations of that bookable and whose (checkIn, checkOut) is -- included in the provided period of time. getBookableIncome :: ConfigMySQL -> ConfigES -> T.Text -> BT.Period -> Maybe T.Text -> ExceptT ServantErr IO BT.EconomicReport getBookableIncome _ _ _ _ Nothing = throwError _noToken getBookableIncome coMysql coEs bookId (BT.Period from to) (Just token) = do eReport <- liftIO $ runMySQL coMysql $ do eitherBookable <- liftIO $ runExceptT $ queryAndParseBookable coEs bookId case eitherBookable of Left error -> return $ Left error Right bookable -> do let propId = BT.propId $ BT.basicData bookable adminValidation <- validateAdminAndMatchProperty coEs token propId case adminValidation of Left error -> return $ Left error Right _ -> do repoResPris <- RR.getBklReservedPrisInPeriod_ bookId DbT.Accepted (from, to) repoCancs <- CR.getBklCancInfoInPeriod bookId (from, to) let resPrisInfo = fmap repoResPriToTuple repoResPris cancsInfo = fmap cancInfoToTupleWithList repoCancs reservedRooms = sum $ fmap toNumRooms resPrisInfo cancelledRooms = sum $ fmap toNumRooms cancsInfo reservationIncome = sum $ fmap getTotalPrice resPrisInfo cancellationLoss = sum $ fmap getTotalPrice cancsInfo return $ Right (BT.EconomicReport (BT.Period from to) reservedRooms cancelledRooms reservationIncome cancellationLoss) either (\err -> throwError err) (\v -> return v) (getCustomError eReport) where repoResPriToTuple (_, (RSC.ReservedPricing _ _ _ cIn cOut _ _ _ price disc text)) = (maybe [] (\t -> read (T.unpack t)) text, cIn, cOut, fromIntegral price, disc) cancInfoToTupleWithList (text, cIn, cOut, price, disc) = (read (T.unpack text), cIn, cOut, fromIntegral price, disc) toNumRooms (ls, _, _, _, _) = fromIntegral $ length ls -- Note that we have to round the total result because we represent currencies as Integers. getTotalPrice :: ([T.Text], TM.UTCTime, TM.UTCTime, Integer, Int) -> Integer getTotalPrice (ls, cIn, cOut, price, disc) = let numNights = round $ (TM.diffUTCTime cOut cIn) / 86400 in round $ (fromIntegral numNights) * (fromIntegral $ length ls) * (fromIntegral price) * ((fromIntegral $ 100 - disc) / 100) -- Given a bookableId and a discount, apply that discount to all the pricings belonging to that bookable, if it is valid. applyBookableDiscount :: ConfigMySQL -> ConfigES -> T.Text -> Int -> Maybe T.Text -> ExceptT ServantErr IO () applyBookableDiscount _ _ _ _ Nothing = throwError _noToken applyBookableDiscount coMysql coEs bookId disc (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token disc takePricings validateDiscount (\set d -> fmap pricingToTuple $ fmap (applyDisc d) (S.toList set)) BR.updateBookablePricings either (\err -> throwError err) (\v -> return ()) (getCustomError update) where takePricings bkl = Right $ BT.pricings bkl validateDiscount d | d < 0 || d > 100 = badPriDisc | otherwise = Right d applyDisc d (BT.Pricing priId priData) = (BT.Pricing priId (priData { BT.roomDiscount = d })) -- Given a propertyId and a CheckInOut data type, this function returns a list of -- searchResults of the availability of that property's bookables. getPropBookableAvailability :: ConfigMySQL -> ConfigES -> T.Text -> BT.CheckInOut -> ExceptT ServantErr IO [BT.SearchResultWithImgIds] getPropBookableAvailability coMysql coEs propId (BT.CheckInOut cIn cOut) = do search <- liftIO $ runMySQL coMysql $ do jsonRes <- liftIO $ runExceptT $ BR.queryBookablesByProp coEs propId case jsonRes of Left _ -> return searchBookErr Right (Object object) -> do We are using here getSearchResults with numRooms = = 0 to get results from all bookables and with size = = 1000 so that we get a list of all bookables . eitherResults <- getSearchResults coEs object cIn cOut 0 0 1000 case eitherResults of Left error -> return $ Left error Right results -> do resultsWithImgs <- mapM getSearchResultImgIds results return $ Right resultsWithImgs either (\err -> throwError err) (\v -> return v) (getCustomError search) Given a BasicSearch data type this function returns a list of searchResults which match the given BasicSearch . makeBasicSearch :: ConfigMySQL -> ConfigES -> Maybe Int -> Maybe Int -> BT.BasicSearch -> ExceptT ServantErr IO [BT.SearchResult] makeBasicSearch coMysql coEs from size basicSearch = do search <- liftIO $ runMySQL coMysql $ do We are only concerned with the first 600 bookables found by ElasticSearch . jsonRes <- liftIO $ runExceptT $ BR.basicBookableQuery coEs cCode' guestNum' locStr' 0 600 case jsonRes of Left _ -> return searchBookErr Right (Object object) -> do getSearchResults coEs object cIn cOut numRooms' from' size' either (\err -> throwError err) (\v -> return v) (getCustomError search) where (BT.BasicSearch cCode guestNum locStr (BT.CheckInOut cIn cOut) numRooms) = basicSearch from' = maybe 0 (setBound 0) from size' = maybe 15 (setBound 15) size guestNum' = setBound 1 guestNum numRooms' = setBound 1 numRooms locStr' = maybe "" id locStr cCode' = CC.toText cCode Given a AdvancedSearch data type this function returns a list of searchResults which match the given AdvancedSearch . makeAdvancedSearch :: ConfigMySQL -> ConfigES -> Maybe Int -> Maybe Int -> BT.AdvancedSearch -> ExceptT ServantErr IO [BT.SearchResult] makeAdvancedSearch coMysql coEs from size advancedSearch = do search <- liftIO $ runMySQL coMysql $ do We are only concerned with the first 600 bookables found by ElasticSearch . jsonRes <- liftIO $ runExceptT $ BR.advancedBookableQuery coEs cCode' guestNum' locStr' propType facs amens numBeds priRange' disc' 0 600 case jsonRes of Left _ -> return searchBookErr Right (Object object) -> do getSearchResults coEs object cIn cOut numRooms' from' size' either (\err -> throwError err) (\v -> return v) (getCustomError search) where (BT.AdvancedSearch basicSearch priRange disc propType facs amens numBeds) = advancedSearch (BT.BasicSearch cCode guestNum locStr (BT.CheckInOut cIn cOut) numRooms) = basicSearch from' = maybe 0 (setBound 0) from size' = maybe 15 (setBound 15) size guestNum' = setBound 1 guestNum numRooms' = setBound 1 numRooms locStr' = maybe "" id locStr cCode' = CC.toText cCode numBeds' = fmap (setBound 1) numBeds disc' = fmap (\v -> if v >= 0 && v <= 100 then v else 0) disc priRange' = do (BT.PriceRange l u) <- priRange if l < u && l >= 0 then Just (l, u) else Nothing -- Given a bookableId and a Period (from, to) data type this function returns a report about -- the availability of that bookable in that period of time. getBookablePeriodReport :: ConfigMySQL -> ConfigES -> T.Text -> BT.Period -> Maybe T.Text -> ExceptT ServantErr IO BT.Report getBookablePeriodReport _ _ _ _ Nothing = throwError _noToken getBookablePeriodReport coMysql coEs bookId (BT.Period from to) (Just token) = do report <- liftIO $ runMySQL coMysql $ do eitherBookable <- liftIO $ runExceptT $ queryAndParseBookable coEs bookId case eitherBookable of Left error -> return $ Left error Right bookable -> do let propId = BT.propId $ BT.basicData bookable start = TM.addUTCTime (-2764800) from end = TM.addUTCTime (2764800) to create report up to the last night of the period roomIds = BT.roomIds $ BT.basicData bookable adminValidation <- validateAdminAndMatchProperty coEs token propId maybeCalendar <- createBookableCalendar bookId start end 128 roomIds case (adminValidation, maybeCalendar) of (Left error, _) -> return $ Left error (_, Nothing) -> return calendarCreationErr (Right _, Just calendar) -> do let maybeReport = fmap toDomainReport (SC.periodReport (from, lastNight) calendar) return $ maybe reportCreationErr (\v -> Right v) maybeReport either (\err -> throwError err) (\v -> return v) (getCustomError report) -- Given a propertyId and a Period (from, to) data type this function returns a list of -- periodReports about the availability of that property's bookables in that period of time. getPropertyPeriodReport :: ConfigMySQL -> ConfigES -> T.Text -> BT.Period -> Maybe T.Text -> ExceptT ServantErr IO [BT.PeriodReport] getPropertyPeriodReport _ _ _ _ Nothing = throwError _noToken getPropertyPeriodReport coMysql coEs propId (BT.Period from to) (Just token) = do search <- liftIO $ runMySQL coMysql $ do eitherBookables <- liftIO $ runExceptT $ queryAndParsePropBookables coEs propId adminValidation <- validateAdminAndMatchProperty coEs token propId case (adminValidation, eitherBookables) of (Left error, _) -> return $ Left error (_, Left error) -> return $ Left error (Right _, Right bookables) -> do let start = TM.addUTCTime (-2764800) from end = TM.addUTCTime (2764800) to create reports up to the last night of the period reports <- mapM (createBookPeriodReport (start, end) (from, lastNight)) bookables return $ sequence reports either (\err -> throwError err) (\v -> return v) (getCustomError search) where createBookPeriodReport (start, end) (up, lo) bkl = do let roomIds = BT.roomIds $ BT.basicData bkl bookId = BT.bklId bkl maybeCalendar <- createBookableCalendar bookId start end 128 roomIds case maybeCalendar of Nothing -> return calendarCreationErr Just calendar -> do let maybeReport = fmap toDomainReport (SC.periodReport (up, lo) calendar) return $ maybe (reportCreationErr) (\r -> Right (BT.PeriodReport bkl r)) maybeReport deleteBookable :: ConfigMySQL -> ConfigES -> T.Text -> BT.UserCredentials -> Maybe T.Text -> ExceptT ServantErr IO () deleteBookable _ _ _ _ Nothing = throwError _noToken deleteBookable coMysql coEs bookId (BT.UserCredentials identifier password) (Just token) = do deletion <- liftIO $ runMySQL coMysql $ do userValidation <- matchUserTokenAndCredentials identifier password token adminValidation <- validateAdminAndMatchBookable coEs token bookId case (userValidation, adminValidation) of (Left error, _) -> return $ Left error (_, Left error) -> return $ Left error (Right _, Right _) -> do (TM.UTCTime day time) <- liftIO $ TM.getCurrentTime resPris <- RR.getBklReservedPrisAfter bookId DbT.Accepted (TM.UTCTime day 0) if null resPris then do jsonRes <- liftIO $ runExceptT $ BR.deleteBookable coEs bookId either (\err -> return bklDeletionErr)(\v -> return $ Right ()) jsonRes else return cannotDeleteBkl either (\err -> throwError err) (\v -> return v) (getCustomError deletion) bookableServer :: ConfigMySQL -> ConfigES -> Server BookableAPI bookableServer coMysql coEs = (getBookable coEs) :<|> (postBookable coMysql coEs) :<|> (listBookable coMysql coEs) :<|> (unlistBookable coMysql coEs) :<|> (deleteBookable coMysql coEs) :<|> (updateBookableEsDesc coMysql coEs) :<|> (updateBookableEnDesc coMysql coEs) :<|> (updateBookableSpecs coMysql coEs) :<|> (updateBookableMaxOccu coMysql coEs) :<|> (addBookableRoomIds coMysql coEs) :<|> (removeBookableRoomIds coMysql coEs) :<|> (addBookablePricing coMysql coEs) :<|> (updateBookablePricing coMysql coEs) :<|> (removeBookablePricing coMysql coEs) :<|> (getPropBookables coEs) :<|> (getPropBookableAvailability coMysql coEs) :<|> (makeBasicSearch coMysql coEs) :<|> (makeAdvancedSearch coMysql coEs) :<|> (postBookableImg coMysql coEs) :<|> (getBookableImageIds coMysql) :<|> (deleteBookableImg coMysql coEs) :<|> (getBookablePeriodReport coMysql coEs) :<|> (getBookableIncome coMysql coEs) :<|> (applyBookableDiscount coMysql coEs) :<|> (getPropertyPeriodReport coMysql coEs)
null
https://raw.githubusercontent.com/sebashack/servantRestfulAPI/e625535d196acefaff4f5bf03108816be668fe4d/libs/Domains/BookingDomain/Bookable/Interpreter.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeOperators # Also note that we are using sets for roomIds so that we avoid repetition. Given a bookableId, get that bookable. Given a bookableId change the state of that bookable to Listed if possible. Given a bookableId change the state of that bookable to Unlisted if possible. Given a BookableSpecs data type and a bookableId, update that bookable's specs. Note that as roomSize and bedType are optional fields, if invalid values are provided, a null will be stored in DB. Given a maximum occupancy and a bookableId, update that bookable's maximum occupancy if it is valid. Note that if the given maxOccu is less than the occupancy of any of that bookable's pricings, an error is thrown. Given a list of roomIds and a bookable's id, add that list into that bookable's set of identifiers, if they're valid. Note that as the API internally uses sets, if the list of rooms has duplicates, they will be eliminated. Also, if you try to add a room aidentifier which was already a member of the set, it won't generate a duplicate. Given a list of roomIds and a bookable's id, delete that list from that bookable's set of identifiers, if they're valid. Note that as the API internally uses sets, if the list of rooms has duplicates, they will be eliminated. Also, if you try to delete a room identifier which wasn't a member of the set it won't have any effect. If the list of roomIds becomes empty, the bookable will be automatically unlisted. data is valid. Again, a pricing cannot have an occupancy greater than the maximum occupancy of the bookable. Given a bookableId and a pricingId, remove that pricing from that bookable's set of pricings. If the given pricingId does not point to pricing in the that bookable's set, this operation has no effect. Also note that if the list of pricings becomes empty, that bookable will be automatically unlisted. Given a propertyId, get all the bookables related to that property. that image. Given a bookableId, get all the imageIds related to that bookable. Given a bokableId and an imageId, delete that bookable's image. If the bookable happens to have no images at all, it will be automatically unlisted. Given a bookableId and a period of time (Period from to) this function returns a EconomicReport of all reservedPricings and cancellations of that bookable and whose (checkIn, checkOut) is included in the provided period of time. Note that we have to round the total result because we represent currencies as Integers. Given a bookableId and a discount, apply that discount to all the pricings belonging to that bookable, if it is valid. Given a propertyId and a CheckInOut data type, this function returns a list of searchResults of the availability of that property's bookables. Given a bookableId and a Period (from, to) data type this function returns a report about the availability of that bookable in that period of time. Given a propertyId and a Period (from, to) data type this function returns a list of periodReports about the availability of that property's bookables in that period of time.
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # LANGUAGE ScopedTypeVariables # module Domains.BookingDomain.Bookable.Interpreter ( bookableServer ) where import Data.ByteString.Char8 (pack) import Control.Monad.Except import Network.Wai import Servant import Servant.JuicyPixels import Data.Aeson import Data.Aeson.Types import Codec.Picture import Codec.Picture.Extra import Codec.Picture.Types import Domains.BookingDomain.Bookable.API import Configs.ConfigTypes import HelperLibs.MySQL.ActionRunner import Control.Monad.Trans.Reader import Control.Monad.IO.Class import Control.Monad (mapM) import Servant.JuicyPixels import HelperLibs.ElasticSearch.ResponseParser import HelperLibs.Interpreters.Bookable import HelperLibs.Interpreters.BookingDomain import qualified Data.ByteString.Base64 as B64 import qualified Database.Persist.MySQL as MySQL import qualified Data.CountryCodes as CC import qualified Schemas.SQL.DbTypes as DbT import qualified Repositories.BookableRepo.Operations as BR import qualified Repositories.ReservationRepo.Operations as RR (getBklReservedPrisInPeriod_, getBklReservedPrisAfter) import qualified Repositories.CancellationRepo.Operations as CR (getBklCancInfoInPeriod) import qualified Domains.BookingDomain.Bookable.DataTypes as BT import qualified Schemas.SQL.Reservation as RSC import qualified Data.ByteString.Lazy as LB (toStrict, fromStrict) import qualified Data.ByteString as SB (length, ByteString) import qualified Data.ByteString.Lazy.Char8 as L8 import qualified Data.Map.Strict as Map import qualified Data.Text as T import qualified Data.Time as TM import qualified Data.Text.Encoding as TE import qualified Data.Set as S import qualified HelperLibs.SCalendar.Operations as SC Given a BasicBookableData data type , this function indexes a Bookable , related to a Property , in DB . Note that the user who wants to create a Bookable must match the Property whose ID he 's providing . postBookable :: ConfigMySQL -> ConfigES -> Maybe T.Text -> BT.BasicBookableData -> ExceptT ServantErr IO BT.Bookable postBookable _ _ Nothing _ = throwError _noToken postBookable coMysql coEs (Just token) bookData = do bookCreation <- liftIO $ runMySQL coMysql $ do let propId = BT.propId bookData adminCreds <- validateAdminAndMatchProperty coEs token propId case adminCreds of Left error -> return $ Left error Right (userId, _, _, propType, facs, cCode, region, city) -> do case validateBasicBookData bookData of Left error -> return $ Left error Right validatedData -> do let (BT.BasicBookableData propId bklSpecs esDesc enDesc maxOccu roomIds) = validatedData (BT.BookableSpecs name roomSize bedType bedNum amenities) = bklSpecs jsonRes <- liftIO $ runExceptT $ BR.indexBookable coEs propId (name, roomSize, bedType, bedNum, amenities) esDesc enDesc maxOccu (S.toList roomIds) (cCode, region, city) propType facs case jsonRes of Left error -> return indexBookErr Right (Object object) -> return $ maybe bookParsingErr (\(String bookId) -> Right (bookId, cCode, validatedData)) (parseMaybe (object .:) "_id") case getCustomError bookCreation of Left error -> throwError error Right (bookId, cCode, validatedData) -> return $ BT.Bookable bookId (CC.fromText cCode) BT.Unlisted validatedData S.empty getBookable :: ConfigES -> T.Text -> ExceptT ServantErr IO BT.Bookable getBookable config bookId = do jsonRes <- liftIO $ runExceptT $ BR.queryBookableById config bookId case jsonRes of Left _ -> throwError _bookNotFound Right (Object object) -> maybe (throwError _bookParsingErr) (\bookable -> return bookable) (parseBookable object) Note that if a Bookable has no images , it can not be listed . listBookable :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () listBookable _ _ _ Nothing = throwError _noToken listBookable coMysql coEs bookId (Just token) = do update <- liftIO $ runMySQL coMysql $ do imgCount <- BR.bookableImageCount bookId if imgCount < 1 then return bklNoImgs else updateBookable coEs bookId token True isListable (\v -> Right v) (\a b -> b) BR.updateBookableState either (\err -> throwError err) (\v -> return ()) (getCustomError update) unlistBookable :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () unlistBookable _ _ _ Nothing = throwError _noToken unlistBookable coMysql coEs bookId (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token False isUnlistable (\v -> Right v) (\a b -> b) BR.updateBookableState either (\err -> throwError err) (\v -> return ()) (getCustomError update) Given a bookableId and a description , update that bookable 's spanish description . updateBookableEsDesc :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> T.Text -> ExceptT ServantErr IO () updateBookableEsDesc _ _ _ Nothing _ = throwError _noToken updateBookableEsDesc coMysql coEs bookId (Just token) desc = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token desc (\x -> Right ()) (\x -> (either (\e -> Left e) (\v -> Right v) (validateDescription x))) (\a b -> b) BR.updateBookableEsDesc either (\err -> throwError err) (\v -> return ()) (getCustomError update) Given a bookableId and a description , update that bookable 's english description . updateBookableEnDesc :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> T.Text -> ExceptT ServantErr IO () updateBookableEnDesc _ _ _ Nothing _ = throwError _noToken updateBookableEnDesc coMysql coEs bookId (Just token) desc = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token desc (\x -> Right ()) (\x -> (either (\e -> Left e) (\v -> Right v) (validateDescription x))) (\a b -> b) BR.updateBookableEnDesc either (\err -> throwError err) (\v -> return ()) (getCustomError update) updateBookableSpecs :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> BT.BookableSpecs -> ExceptT ServantErr IO () updateBookableSpecs _ _ _ Nothing _ = throwError _noToken updateBookableSpecs coMysql coEs bookId (Just token) specs = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token specs (\x -> Right ()) validation (\a b -> b) BR.updateBookableSpecs either (\err -> throwError err) (\v -> return ()) (getCustomError update) where validation bklSpecs = case validateBookSpecs bklSpecs of Left error -> Left error Right (BT.BookableSpecs name roomSize bedType bedNum amenities) -> Right (name, roomSize, bedType, bedNum, amenities) updateBookableMaxOccu :: ConfigMySQL -> ConfigES -> T.Text -> Int -> Maybe T.Text -> ExceptT ServantErr IO () updateBookableMaxOccu _ _ _ _ Nothing = throwError _noToken updateBookableMaxOccu coMysql coEs bookId maxOccu (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token maxOccu (checkMaxOccuAndPricings maxOccu) validateMaxOccupancy (\a b -> b) BR.updateBookableMaxOccu either (\err -> throwError err) (\v -> return ()) (getCustomError update) where checkMaxOccuAndPricings n (BT.Bookable bookId cCode status bookData pricings) | all (\pri -> if n >= BT.occupancy (BT.priData pri) then True else False) pricings = Right () | otherwise = maxOccuPriErr The list of room identifiers can not be greater than 100 elements . addBookableRoomIds :: ConfigMySQL -> ConfigES -> T.Text -> [T.Text] -> Maybe T.Text -> ExceptT ServantErr IO () addBookableRoomIds _ _ _ _ Nothing = throwError _noToken addBookableRoomIds coMysql coEs bookId roomIds (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token (S.fromList roomIds) takeRoomIds validateRoomIds (\a b -> S.toList $ S.union a b) BR.updateBookableRoomIds either (\err -> throwError err) (\v -> return ()) (getCustomError update) removeBookableRoomIds :: ConfigMySQL -> ConfigES -> T.Text -> [T.Text] -> Maybe T.Text -> ExceptT ServantErr IO () removeBookableRoomIds _ _ _ _ Nothing = throwError _noToken removeBookableRoomIds coMysql coEs bookId roomIds (Just token) = do update <- liftIO $ runMySQL coMysql $ do roomIds <- updateBookable coEs bookId token (S.fromList roomIds) takeRoomIds validateRoomIds (\a b -> S.toList $ S.difference a b) BR.updateBookableRoomIds case roomIds of Left error -> return $ Left error Right [] -> do jsonRes <-liftIO $ runExceptT $ BR.updateBookableState coEs bookId False return $ either (\err -> updateBookErr) (\v -> return ()) jsonRes _ -> return $ Right () either (\err -> throwError err) (\v -> return ()) (getCustomError update) Given a PricingData data type , and a bookableId , add new pricing into that bookable 's set of pricings , if the data is valid . Note that a Bookable can not have more than 15 pricings . Also , a pricing can not have an occupancy greater than the maximum occupancy of the Bookable . addBookablePricing :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> BT.PricingData -> ExceptT ServantErr IO () addBookablePricing _ _ _ Nothing _ = throwError _noToken addBookablePricing coMysql coEs bookId (Just token) priData = do update <- liftIO $ runMySQL coMysql $ do currentDate <- liftIO TM.getCurrentTime let priId = genPricingId bookId currentDate updateBookable coEs bookId token priData (takePricings occu) (validatePricingData priId) (\set val -> fmap pricingToTuple (S.toList $ S.insert val set)) BR.updateBookablePricings either (\err -> throwError err) (\v -> return ()) (getCustomError update) where (BT.PricingData occu conds price disc) = priData takePricings :: Int -> BT.Bookable -> Either String (S.Set BT.Pricing) takePricings n bkl | n > maxOccu = priOccuTooLarge | n < 1 = badPriOccupancy | S.size (BT.pricings bkl) >= 16 = tooManyPricings | otherwise = Right $ BT.pricings bkl where maxOccu = BT.maxOccu (BT.basicData bkl) Given a PrcingData data type , a bookableId and a PricingId , update the information concerning that Pricing , if the updateBookablePricing :: ConfigMySQL -> ConfigES -> T.Text -> T.Text -> Maybe T.Text -> BT.PricingData -> ExceptT ServantErr IO () updateBookablePricing _ _ _ _ Nothing _ = throwError _noToken updateBookablePricing coMysql coEs bookId priId (Just token) priData = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token priData (takePricings occu priId) (validatePricingData priId) (\set val -> fmap pricingToTuple (S.toList $ S.insert val set)) BR.updateBookablePricings either (\err -> throwError err) (\v -> return ()) (getCustomError update) where (BT.PricingData occu conds price disc) = priData takePricings :: Int -> T.Text -> BT.Bookable -> Either String (S.Set BT.Pricing) takePricings n priId bkl | n > maxOccu = priOccuTooLarge | n < 1 = badPriOccupancy | S.notMember dummyPricing (BT.pricings bkl) = priNotFound | otherwise = Right $ BT.pricings bkl where maxOccu = BT.maxOccu (BT.basicData bkl) dummyPricing = (BT.Pricing priId (BT.PricingData 0 [] 0 0)) removeBookablePricing :: ConfigMySQL -> ConfigES -> T.Text -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () removeBookablePricing _ _ _ _ Nothing = throwError _noToken removeBookablePricing coMysql coEs bookId priId (Just token) = do update <- liftIO $ runMySQL coMysql $ do pricings <- updateBookable coEs bookId token (BT.Pricing priId (BT.PricingData 0 [] 0 0)) takePricings (\v -> Right v) (\set val -> fmap pricingToTuple (S.toList $ S.delete val set)) BR.updateBookablePricings case pricings of Left error -> return $ Left error Right [] -> do jsonRes <-liftIO $ runExceptT $ BR.updateBookableState coEs bookId False return $ either (\err -> updateBookErr) (\v -> return ()) jsonRes _ -> return $ Right () either (\err -> throwError err) (\v -> return ()) (getCustomError update) where takePricings bkl = Right $ BT.pricings bkl getPropBookables :: ConfigES -> T.Text -> ExceptT ServantErr IO [BT.Bookable] getPropBookables config propId = do jsonRes <- liftIO $ runExceptT $ BR.queryBookablesByProp config propId case jsonRes of Left _ -> throwError _searchBookErr Right (Object object) -> maybe (throwError _bookParsingErr) (\bookables -> return bookables) (parseBookables object) Given a bookableId and a jpeg DynamicImage , store that image in DB . This function returns the i d of postBookableImg :: ConfigMySQL -> ConfigES -> T.Text -> Maybe T.Text -> DynamicImage -> ExceptT ServantErr IO T.Text postBookableImg _ _ _ Nothing _ = throwError _noToken postBookableImg coMysql coEs bookId (Just token) (ImageYCbCr8 imgJPEG) = do postImg <- liftIO $ runMySQL coMysql $ do adminCreds <- validateAdminPropBkl coEs bookId token case adminCreds of Left error -> return $ Left error Right (userId, propId) -> do imgCount <- BR.bookableImageCount bookId if imgCount > 15 then return tooMuchImgs else do let encodedImg = LB.toStrict (encodeJpegAtQuality 100 imgJPEG) numBytes = SB.length encodedImg case checkImgBound numBytes of LT -> return tooSmallImage GT -> return tooLargeImage EQ -> do imgId <- BR.storeBookableImg bookId encodedImg return $ Right imgId either (\err -> throwError err) (\v -> return v) (getCustomError postImg) getBookableImageIds :: ConfigMySQL -> T.Text -> ExceptT ServantErr IO [T.Text] getBookableImageIds coMysql bookId = do imgIds <- liftIO $ runMySQL coMysql $ BR.bookableImageIds bookId return imgIds deleteBookableImg :: ConfigMySQL -> ConfigES -> T.Text -> T.Text -> Maybe T.Text -> ExceptT ServantErr IO () deleteBookableImg _ _ _ _ Nothing = throwError _noToken deleteBookableImg coMysql coEs bookId imgId (Just token) = do postImg <- liftIO $ runMySQL coMysql $ do adminCreds <- validateAdminPropBkl coEs bookId token case adminCreds of Left error -> return $ Left error Right (userId, propId) -> do BR.deleteBookableImg bookId imgId imgCount <- BR.bookableImageCount bookId if imgCount > 0 then return $ Right () else do jsonRes <-liftIO $ runExceptT $ BR.updateBookableState coEs bookId False return $ either (\err -> updateBookErr) (\v -> return ()) jsonRes either (\err -> throwError err) (\v -> return ()) (getCustomError postImg) getBookableIncome :: ConfigMySQL -> ConfigES -> T.Text -> BT.Period -> Maybe T.Text -> ExceptT ServantErr IO BT.EconomicReport getBookableIncome _ _ _ _ Nothing = throwError _noToken getBookableIncome coMysql coEs bookId (BT.Period from to) (Just token) = do eReport <- liftIO $ runMySQL coMysql $ do eitherBookable <- liftIO $ runExceptT $ queryAndParseBookable coEs bookId case eitherBookable of Left error -> return $ Left error Right bookable -> do let propId = BT.propId $ BT.basicData bookable adminValidation <- validateAdminAndMatchProperty coEs token propId case adminValidation of Left error -> return $ Left error Right _ -> do repoResPris <- RR.getBklReservedPrisInPeriod_ bookId DbT.Accepted (from, to) repoCancs <- CR.getBklCancInfoInPeriod bookId (from, to) let resPrisInfo = fmap repoResPriToTuple repoResPris cancsInfo = fmap cancInfoToTupleWithList repoCancs reservedRooms = sum $ fmap toNumRooms resPrisInfo cancelledRooms = sum $ fmap toNumRooms cancsInfo reservationIncome = sum $ fmap getTotalPrice resPrisInfo cancellationLoss = sum $ fmap getTotalPrice cancsInfo return $ Right (BT.EconomicReport (BT.Period from to) reservedRooms cancelledRooms reservationIncome cancellationLoss) either (\err -> throwError err) (\v -> return v) (getCustomError eReport) where repoResPriToTuple (_, (RSC.ReservedPricing _ _ _ cIn cOut _ _ _ price disc text)) = (maybe [] (\t -> read (T.unpack t)) text, cIn, cOut, fromIntegral price, disc) cancInfoToTupleWithList (text, cIn, cOut, price, disc) = (read (T.unpack text), cIn, cOut, fromIntegral price, disc) toNumRooms (ls, _, _, _, _) = fromIntegral $ length ls getTotalPrice :: ([T.Text], TM.UTCTime, TM.UTCTime, Integer, Int) -> Integer getTotalPrice (ls, cIn, cOut, price, disc) = let numNights = round $ (TM.diffUTCTime cOut cIn) / 86400 in round $ (fromIntegral numNights) * (fromIntegral $ length ls) * (fromIntegral price) * ((fromIntegral $ 100 - disc) / 100) applyBookableDiscount :: ConfigMySQL -> ConfigES -> T.Text -> Int -> Maybe T.Text -> ExceptT ServantErr IO () applyBookableDiscount _ _ _ _ Nothing = throwError _noToken applyBookableDiscount coMysql coEs bookId disc (Just token) = do update <- liftIO $ runMySQL coMysql $ do updateBookable coEs bookId token disc takePricings validateDiscount (\set d -> fmap pricingToTuple $ fmap (applyDisc d) (S.toList set)) BR.updateBookablePricings either (\err -> throwError err) (\v -> return ()) (getCustomError update) where takePricings bkl = Right $ BT.pricings bkl validateDiscount d | d < 0 || d > 100 = badPriDisc | otherwise = Right d applyDisc d (BT.Pricing priId priData) = (BT.Pricing priId (priData { BT.roomDiscount = d })) getPropBookableAvailability :: ConfigMySQL -> ConfigES -> T.Text -> BT.CheckInOut -> ExceptT ServantErr IO [BT.SearchResultWithImgIds] getPropBookableAvailability coMysql coEs propId (BT.CheckInOut cIn cOut) = do search <- liftIO $ runMySQL coMysql $ do jsonRes <- liftIO $ runExceptT $ BR.queryBookablesByProp coEs propId case jsonRes of Left _ -> return searchBookErr Right (Object object) -> do We are using here getSearchResults with numRooms = = 0 to get results from all bookables and with size = = 1000 so that we get a list of all bookables . eitherResults <- getSearchResults coEs object cIn cOut 0 0 1000 case eitherResults of Left error -> return $ Left error Right results -> do resultsWithImgs <- mapM getSearchResultImgIds results return $ Right resultsWithImgs either (\err -> throwError err) (\v -> return v) (getCustomError search) Given a BasicSearch data type this function returns a list of searchResults which match the given BasicSearch . makeBasicSearch :: ConfigMySQL -> ConfigES -> Maybe Int -> Maybe Int -> BT.BasicSearch -> ExceptT ServantErr IO [BT.SearchResult] makeBasicSearch coMysql coEs from size basicSearch = do search <- liftIO $ runMySQL coMysql $ do We are only concerned with the first 600 bookables found by ElasticSearch . jsonRes <- liftIO $ runExceptT $ BR.basicBookableQuery coEs cCode' guestNum' locStr' 0 600 case jsonRes of Left _ -> return searchBookErr Right (Object object) -> do getSearchResults coEs object cIn cOut numRooms' from' size' either (\err -> throwError err) (\v -> return v) (getCustomError search) where (BT.BasicSearch cCode guestNum locStr (BT.CheckInOut cIn cOut) numRooms) = basicSearch from' = maybe 0 (setBound 0) from size' = maybe 15 (setBound 15) size guestNum' = setBound 1 guestNum numRooms' = setBound 1 numRooms locStr' = maybe "" id locStr cCode' = CC.toText cCode Given a AdvancedSearch data type this function returns a list of searchResults which match the given AdvancedSearch . makeAdvancedSearch :: ConfigMySQL -> ConfigES -> Maybe Int -> Maybe Int -> BT.AdvancedSearch -> ExceptT ServantErr IO [BT.SearchResult] makeAdvancedSearch coMysql coEs from size advancedSearch = do search <- liftIO $ runMySQL coMysql $ do We are only concerned with the first 600 bookables found by ElasticSearch . jsonRes <- liftIO $ runExceptT $ BR.advancedBookableQuery coEs cCode' guestNum' locStr' propType facs amens numBeds priRange' disc' 0 600 case jsonRes of Left _ -> return searchBookErr Right (Object object) -> do getSearchResults coEs object cIn cOut numRooms' from' size' either (\err -> throwError err) (\v -> return v) (getCustomError search) where (BT.AdvancedSearch basicSearch priRange disc propType facs amens numBeds) = advancedSearch (BT.BasicSearch cCode guestNum locStr (BT.CheckInOut cIn cOut) numRooms) = basicSearch from' = maybe 0 (setBound 0) from size' = maybe 15 (setBound 15) size guestNum' = setBound 1 guestNum numRooms' = setBound 1 numRooms locStr' = maybe "" id locStr cCode' = CC.toText cCode numBeds' = fmap (setBound 1) numBeds disc' = fmap (\v -> if v >= 0 && v <= 100 then v else 0) disc priRange' = do (BT.PriceRange l u) <- priRange if l < u && l >= 0 then Just (l, u) else Nothing getBookablePeriodReport :: ConfigMySQL -> ConfigES -> T.Text -> BT.Period -> Maybe T.Text -> ExceptT ServantErr IO BT.Report getBookablePeriodReport _ _ _ _ Nothing = throwError _noToken getBookablePeriodReport coMysql coEs bookId (BT.Period from to) (Just token) = do report <- liftIO $ runMySQL coMysql $ do eitherBookable <- liftIO $ runExceptT $ queryAndParseBookable coEs bookId case eitherBookable of Left error -> return $ Left error Right bookable -> do let propId = BT.propId $ BT.basicData bookable start = TM.addUTCTime (-2764800) from end = TM.addUTCTime (2764800) to create report up to the last night of the period roomIds = BT.roomIds $ BT.basicData bookable adminValidation <- validateAdminAndMatchProperty coEs token propId maybeCalendar <- createBookableCalendar bookId start end 128 roomIds case (adminValidation, maybeCalendar) of (Left error, _) -> return $ Left error (_, Nothing) -> return calendarCreationErr (Right _, Just calendar) -> do let maybeReport = fmap toDomainReport (SC.periodReport (from, lastNight) calendar) return $ maybe reportCreationErr (\v -> Right v) maybeReport either (\err -> throwError err) (\v -> return v) (getCustomError report) getPropertyPeriodReport :: ConfigMySQL -> ConfigES -> T.Text -> BT.Period -> Maybe T.Text -> ExceptT ServantErr IO [BT.PeriodReport] getPropertyPeriodReport _ _ _ _ Nothing = throwError _noToken getPropertyPeriodReport coMysql coEs propId (BT.Period from to) (Just token) = do search <- liftIO $ runMySQL coMysql $ do eitherBookables <- liftIO $ runExceptT $ queryAndParsePropBookables coEs propId adminValidation <- validateAdminAndMatchProperty coEs token propId case (adminValidation, eitherBookables) of (Left error, _) -> return $ Left error (_, Left error) -> return $ Left error (Right _, Right bookables) -> do let start = TM.addUTCTime (-2764800) from end = TM.addUTCTime (2764800) to create reports up to the last night of the period reports <- mapM (createBookPeriodReport (start, end) (from, lastNight)) bookables return $ sequence reports either (\err -> throwError err) (\v -> return v) (getCustomError search) where createBookPeriodReport (start, end) (up, lo) bkl = do let roomIds = BT.roomIds $ BT.basicData bkl bookId = BT.bklId bkl maybeCalendar <- createBookableCalendar bookId start end 128 roomIds case maybeCalendar of Nothing -> return calendarCreationErr Just calendar -> do let maybeReport = fmap toDomainReport (SC.periodReport (up, lo) calendar) return $ maybe (reportCreationErr) (\r -> Right (BT.PeriodReport bkl r)) maybeReport deleteBookable :: ConfigMySQL -> ConfigES -> T.Text -> BT.UserCredentials -> Maybe T.Text -> ExceptT ServantErr IO () deleteBookable _ _ _ _ Nothing = throwError _noToken deleteBookable coMysql coEs bookId (BT.UserCredentials identifier password) (Just token) = do deletion <- liftIO $ runMySQL coMysql $ do userValidation <- matchUserTokenAndCredentials identifier password token adminValidation <- validateAdminAndMatchBookable coEs token bookId case (userValidation, adminValidation) of (Left error, _) -> return $ Left error (_, Left error) -> return $ Left error (Right _, Right _) -> do (TM.UTCTime day time) <- liftIO $ TM.getCurrentTime resPris <- RR.getBklReservedPrisAfter bookId DbT.Accepted (TM.UTCTime day 0) if null resPris then do jsonRes <- liftIO $ runExceptT $ BR.deleteBookable coEs bookId either (\err -> return bklDeletionErr)(\v -> return $ Right ()) jsonRes else return cannotDeleteBkl either (\err -> throwError err) (\v -> return v) (getCustomError deletion) bookableServer :: ConfigMySQL -> ConfigES -> Server BookableAPI bookableServer coMysql coEs = (getBookable coEs) :<|> (postBookable coMysql coEs) :<|> (listBookable coMysql coEs) :<|> (unlistBookable coMysql coEs) :<|> (deleteBookable coMysql coEs) :<|> (updateBookableEsDesc coMysql coEs) :<|> (updateBookableEnDesc coMysql coEs) :<|> (updateBookableSpecs coMysql coEs) :<|> (updateBookableMaxOccu coMysql coEs) :<|> (addBookableRoomIds coMysql coEs) :<|> (removeBookableRoomIds coMysql coEs) :<|> (addBookablePricing coMysql coEs) :<|> (updateBookablePricing coMysql coEs) :<|> (removeBookablePricing coMysql coEs) :<|> (getPropBookables coEs) :<|> (getPropBookableAvailability coMysql coEs) :<|> (makeBasicSearch coMysql coEs) :<|> (makeAdvancedSearch coMysql coEs) :<|> (postBookableImg coMysql coEs) :<|> (getBookableImageIds coMysql) :<|> (deleteBookableImg coMysql coEs) :<|> (getBookablePeriodReport coMysql coEs) :<|> (getBookableIncome coMysql coEs) :<|> (applyBookableDiscount coMysql coEs) :<|> (getPropertyPeriodReport coMysql coEs)
4f31c433e150da3021f670ab523c552bd35c8fe2cbbeeb66fa3c490239d254ed
clojure/core.typed
method.clj
Copyright ( c ) , contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.core.typed.checker.check.jvm.method (:require [clojure.core.typed.checker.type-rep :as r] [clojure.core.typed.util-vars :as vs] [clojure.core.typed.errors :as err] [clojure.core.typed.checker.check.jvm.type-hints :as type-hints] [clojure.core.typed.checker.utils :as u] [clojure.core.typed.ast-utils :as ast-u] [clojure.core.typed.checker.jvm.subtype :as sub] [clojure.core.typed.checker.type-ctors :as c] [clojure.core.typed.checker.jvm.parse-unparse :as prs] [clojure.core.typed.checker.check.funapp :as funapp] [clojure.core.typed.checker.check.utils :as cu] [clojure.core.typed.checker.jvm.method-override-env :as mth-override])) [ MethodExpr Type Any - > Expr ] (defn check-invoke-method [{method-name :method :keys [args env] :as expr} expected & {:keys [method-override] :as opt}] {:pre [(#{:static-call :instance-call} (:op expr)) (not (:ctarget opt)) ;not supported (not (:cargs opt)) ;not supported ((some-fn nil? r/TCResult?) expected) ((some-fn nil? r/Type?) method-override)] :post [(-> % u/expr-type r/TCResult?) (vector? (:args %))]} (binding [vs/*current-env* env vs/*current-expr* expr] (let [inst? (= :instance-call (:op expr)) method (cu/MethodExpr->Method expr) msym (cu/MethodExpr->qualsym expr) rfin-type (or method-override (when msym (mth-override/get-method-override msym)) (when method (cu/Method->Type method))) _ (assert ((some-fn nil? r/Type?) rfin-type)) ctarget (:instance expr)] (if-not rfin-type (err/tc-delayed-error (str "Unresolved " (if inst? "instance" "static") " method invocation " method-name "." (type-hints/suggest-type-hints method-name (some-> ctarget u/expr-type r/ret-t) (map (comp r/ret-t u/expr-type) args)) "\n\nHint: use *warn-on-reflection* to identify reflective calls") :form (ast-u/emit-form-fn expr) :return (merge (assoc expr u/expr-type (cu/error-ret expected)) (when ctarget {:instance ctarget}))) (let [_ (when inst? (let [target-class (resolve (:declaring-class method)) _ (assert (class? target-class))] ; (prn "check target" (prs/unparse-type (r/ret-t (u/expr-type ctarget))) ( prs / unparse - type ( c / RClass - of ( coerce / Class->symbol ( resolve (: declaring - class method ) ) ) nil ) ) ) (when-not (sub/subtype? (r/ret-t (u/expr-type ctarget)) (c/RClass-of-with-unknown-params target-class)) (err/tc-delayed-error (str "Cannot call instance method " (cu/Method->symbol method) " on type " (pr-str (prs/unparse-type (r/ret-t (u/expr-type ctarget))))) :form (ast-u/emit-form-fn expr))))) result-type (funapp/check-funapp expr args (r/ret rfin-type) (map u/expr-type args) expected) _ (when expected FIXME check filters and object (when-not (sub/subtype? (r/ret-t result-type) (r/ret-t expected)) (err/tc-delayed-error (str "Return type of " (if inst? "instance" "static") " method " (cu/Method->symbol method) " is " (prs/unparse-type (r/ret-t result-type)) ", expected " (prs/unparse-type (r/ret-t expected)) "." (when (sub/subtype? r/-nil (r/ret-t result-type)) (str "\n\nHint: Use `non-nil-return` and `nilable-param` to configure " "where `nil` is allowed in a Java method call. `method-type` " "prints the current type of a method."))) :form (ast-u/emit-form-fn expr))))] (assoc expr u/expr-type result-type))))))
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/check/jvm/method.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. not supported not supported (prn "check target" (prs/unparse-type (r/ret-t (u/expr-type ctarget)))
Copyright ( c ) , contributors . (ns clojure.core.typed.checker.check.jvm.method (:require [clojure.core.typed.checker.type-rep :as r] [clojure.core.typed.util-vars :as vs] [clojure.core.typed.errors :as err] [clojure.core.typed.checker.check.jvm.type-hints :as type-hints] [clojure.core.typed.checker.utils :as u] [clojure.core.typed.ast-utils :as ast-u] [clojure.core.typed.checker.jvm.subtype :as sub] [clojure.core.typed.checker.type-ctors :as c] [clojure.core.typed.checker.jvm.parse-unparse :as prs] [clojure.core.typed.checker.check.funapp :as funapp] [clojure.core.typed.checker.check.utils :as cu] [clojure.core.typed.checker.jvm.method-override-env :as mth-override])) [ MethodExpr Type Any - > Expr ] (defn check-invoke-method [{method-name :method :keys [args env] :as expr} expected & {:keys [method-override] :as opt}] {:pre [(#{:static-call :instance-call} (:op expr)) ((some-fn nil? r/TCResult?) expected) ((some-fn nil? r/Type?) method-override)] :post [(-> % u/expr-type r/TCResult?) (vector? (:args %))]} (binding [vs/*current-env* env vs/*current-expr* expr] (let [inst? (= :instance-call (:op expr)) method (cu/MethodExpr->Method expr) msym (cu/MethodExpr->qualsym expr) rfin-type (or method-override (when msym (mth-override/get-method-override msym)) (when method (cu/Method->Type method))) _ (assert ((some-fn nil? r/Type?) rfin-type)) ctarget (:instance expr)] (if-not rfin-type (err/tc-delayed-error (str "Unresolved " (if inst? "instance" "static") " method invocation " method-name "." (type-hints/suggest-type-hints method-name (some-> ctarget u/expr-type r/ret-t) (map (comp r/ret-t u/expr-type) args)) "\n\nHint: use *warn-on-reflection* to identify reflective calls") :form (ast-u/emit-form-fn expr) :return (merge (assoc expr u/expr-type (cu/error-ret expected)) (when ctarget {:instance ctarget}))) (let [_ (when inst? (let [target-class (resolve (:declaring-class method)) _ (assert (class? target-class))] ( prs / unparse - type ( c / RClass - of ( coerce / Class->symbol ( resolve (: declaring - class method ) ) ) nil ) ) ) (when-not (sub/subtype? (r/ret-t (u/expr-type ctarget)) (c/RClass-of-with-unknown-params target-class)) (err/tc-delayed-error (str "Cannot call instance method " (cu/Method->symbol method) " on type " (pr-str (prs/unparse-type (r/ret-t (u/expr-type ctarget))))) :form (ast-u/emit-form-fn expr))))) result-type (funapp/check-funapp expr args (r/ret rfin-type) (map u/expr-type args) expected) _ (when expected FIXME check filters and object (when-not (sub/subtype? (r/ret-t result-type) (r/ret-t expected)) (err/tc-delayed-error (str "Return type of " (if inst? "instance" "static") " method " (cu/Method->symbol method) " is " (prs/unparse-type (r/ret-t result-type)) ", expected " (prs/unparse-type (r/ret-t expected)) "." (when (sub/subtype? r/-nil (r/ret-t result-type)) (str "\n\nHint: Use `non-nil-return` and `nilable-param` to configure " "where `nil` is allowed in a Java method call. `method-type` " "prints the current type of a method."))) :form (ast-u/emit-form-fn expr))))] (assoc expr u/expr-type result-type))))))
ee7acfb83dfeea974279216cdc0a62ccc7f61f58ee0122334b1ad386fb0e528b
duo-lang/duo-lang
Options.hs
module Options ( Options(..) , DebugFlags(..) , parseOptions ) where import Data.Foldable (fold) import Options.Applicative data Options where OptLSP :: Options OptRun :: FilePath -> DebugFlags -> Options OptTypecheck :: FilePath -> DebugFlags -> Options OptDeps :: FilePath -> Options OptVersion :: Options --------------------------------------------------------------------------------- -- Debug flags --------------------------------------------------------------------------------- data DebugFlags = DebugFlags { df_debug :: Bool, df_printGraphs :: Bool } debugFlagParser :: Parser DebugFlags debugFlagParser = DebugFlags <$> switch modsDebug <*> switch modsGraph where modsDebug = fold [ long "XDebug" , help "Print debug info." ] modsGraph = fold [ long "XPrintGraph" , help "Print simplification automata graphs." ] --------------------------------------------------------------------------------- Commandline options for starting a LSP session --------------------------------------------------------------------------------- lspParserInfo :: ParserInfo Options lspParserInfo = info (helper <*> pure OptLSP) mods where mods = fold [ fullDesc , header "duo lsp - Start a LSP session" , progDesc "Start a LSP session. This command should only be invoked by editors or for debugging purposes." ] --------------------------------------------------------------------------------- Commandline options for typechecking source files --------------------------------------------------------------------------------- typecheckParser :: Parser Options typecheckParser = OptTypecheck <$> argument str mods <*> debugFlagParser where mods = fold [ metavar "TARGET" , help "Filepath of the source file." ] typecheckParserInfo :: ParserInfo Options typecheckParserInfo = info (helper <*> typecheckParser) mods where mods = fold [ fullDesc , header "duo check - Typecheck Duo source files" , progDesc "Typecheck Duo source files." ] --------------------------------------------------------------------------------- Commandline options for running source files --------------------------------------------------------------------------------- runParser :: Parser Options runParser = OptRun <$> argument str mods <*> debugFlagParser where mods = fold [ metavar "TARGET" , help "Filepath of the source file." ] runParserInfo :: ParserInfo Options runParserInfo = info (helper <*> runParser) mods where mods = fold [ fullDesc , header "duo run - Run Duo source files" , progDesc "Run Duo source files." ] --------------------------------------------------------------------------------- Commandline options for computing a dependency graph --------------------------------------------------------------------------------- depsParser :: Parser Options depsParser = OptDeps <$> argument str mods where mods = fold [ metavar "TARGET" , help "Filepath of the source file." ] depsParserInfo :: ParserInfo Options depsParserInfo = info (helper <*> depsParser) mods where mods = fold [ fullDesc , header "duo deps - Compute dependency graphs" , progDesc "Compute the dependency graph for a Duo module." ] --------------------------------------------------------------------------------- Commandline option for showing the current version --------------------------------------------------------------------------------- versionParser :: Parser Options versionParser = OptVersion <$ flag' () (long "version" <> short 'v' <> help "Show version") --------------------------------------------------------------------------------- -- Combined commandline parser --------------------------------------------------------------------------------- commandParser :: Parser Options commandParser = subparser $ fold [ command "run" runParserInfo , command "deps" depsParserInfo , command "lsp" lspParserInfo , command "check" typecheckParserInfo ] optParser :: Parser Options optParser = commandParser <|> versionParser optParserInfo :: ParserInfo Options optParserInfo = info (helper <*> optParser) mods where mods = fold [ fullDesc , progDesc "Duo is a research programming language focused on the study of dualities and subtyping." , header "duo - Typecheck, run and compile Duo programs" ] --------------------------------------------------------------------------------- -- Exported Parser --------------------------------------------------------------------------------- parseOptions :: IO Options parseOptions = customExecParser p optParserInfo where p = prefs showHelpOnError
null
https://raw.githubusercontent.com/duo-lang/duo-lang/09bc7abc451049e1aadd9b4e7ba8019ff14b8953/app/Options.hs
haskell
------------------------------------------------------------------------------- Debug flags ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- Combined commandline parser ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- Exported Parser -------------------------------------------------------------------------------
module Options ( Options(..) , DebugFlags(..) , parseOptions ) where import Data.Foldable (fold) import Options.Applicative data Options where OptLSP :: Options OptRun :: FilePath -> DebugFlags -> Options OptTypecheck :: FilePath -> DebugFlags -> Options OptDeps :: FilePath -> Options OptVersion :: Options data DebugFlags = DebugFlags { df_debug :: Bool, df_printGraphs :: Bool } debugFlagParser :: Parser DebugFlags debugFlagParser = DebugFlags <$> switch modsDebug <*> switch modsGraph where modsDebug = fold [ long "XDebug" , help "Print debug info." ] modsGraph = fold [ long "XPrintGraph" , help "Print simplification automata graphs." ] Commandline options for starting a LSP session lspParserInfo :: ParserInfo Options lspParserInfo = info (helper <*> pure OptLSP) mods where mods = fold [ fullDesc , header "duo lsp - Start a LSP session" , progDesc "Start a LSP session. This command should only be invoked by editors or for debugging purposes." ] Commandline options for typechecking source files typecheckParser :: Parser Options typecheckParser = OptTypecheck <$> argument str mods <*> debugFlagParser where mods = fold [ metavar "TARGET" , help "Filepath of the source file." ] typecheckParserInfo :: ParserInfo Options typecheckParserInfo = info (helper <*> typecheckParser) mods where mods = fold [ fullDesc , header "duo check - Typecheck Duo source files" , progDesc "Typecheck Duo source files." ] Commandline options for running source files runParser :: Parser Options runParser = OptRun <$> argument str mods <*> debugFlagParser where mods = fold [ metavar "TARGET" , help "Filepath of the source file." ] runParserInfo :: ParserInfo Options runParserInfo = info (helper <*> runParser) mods where mods = fold [ fullDesc , header "duo run - Run Duo source files" , progDesc "Run Duo source files." ] Commandline options for computing a dependency graph depsParser :: Parser Options depsParser = OptDeps <$> argument str mods where mods = fold [ metavar "TARGET" , help "Filepath of the source file." ] depsParserInfo :: ParserInfo Options depsParserInfo = info (helper <*> depsParser) mods where mods = fold [ fullDesc , header "duo deps - Compute dependency graphs" , progDesc "Compute the dependency graph for a Duo module." ] Commandline option for showing the current version versionParser :: Parser Options versionParser = OptVersion <$ flag' () (long "version" <> short 'v' <> help "Show version") commandParser :: Parser Options commandParser = subparser $ fold [ command "run" runParserInfo , command "deps" depsParserInfo , command "lsp" lspParserInfo , command "check" typecheckParserInfo ] optParser :: Parser Options optParser = commandParser <|> versionParser optParserInfo :: ParserInfo Options optParserInfo = info (helper <*> optParser) mods where mods = fold [ fullDesc , progDesc "Duo is a research programming language focused on the study of dualities and subtyping." , header "duo - Typecheck, run and compile Duo programs" ] parseOptions :: IO Options parseOptions = customExecParser p optParserInfo where p = prefs showHelpOnError
d88d4fce07e50696873f9e10ae15797336f57827887292eea75b4b56700a3d73
jeromesimeon/Galax
namespace_symbols.ml
(***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : namespace_symbols.ml , v 1.12 2007/08/20 13:12:40 simeon Exp $ (* Module: Namespace_symbols Description: This module implements symbol tables for QNames. *) open Error open Pool open Namespace_names open Namespace_builtin open Namespace_context (****************) (* Symbol pools *) (****************) (* Pool for namespace prefixes *) module Prefix = struct type t = prefix let equal = (=) let hash = prefix_hash end module PrefixPool = MakeNamePool (Prefix) type prefix_symbol = PrefixPool.symbol let prefix_pool = PrefixPool.create_pool () (* Pool for namespace URIs *) module Uri = struct type t = uri let equal = (=) let hash = uri_hash end module UriPool = MakeNamePool (Uri) type uri_symbol = UriPool.symbol let uri_pool = UriPool.create_pool () Namepool for local names module Ncname = struct type t = ncname let equal = (=) let hash = ncname_hash end module NcnamePool = MakeNamePool (Ncname) type ncname_symbol = NcnamePool.symbol let ncname_pool = NcnamePool.create_pool () (***********) (* Symbols *) (***********) (* Note: Symbols are triples now. - Jerome *) type symbol = (prefix_symbol * uri_symbol * ncname_symbol) (* Symbol creation *) let symbol_create (prefix,uri,ncname) = (PrefixPool.add_name prefix_pool prefix, UriPool.add_name uri_pool uri, NcnamePool.add_name ncname_pool ncname) let wildcard_symbol = symbol_create Namespace_builtin.wild_rqname let (wildcard_prefix_symbol,wildcard_uri_symbol,wildcard_ncname_symbol) = wildcard_symbol (* Symbol lookup *) Note : Those look - ups are expensive and should be avoided - let symbol_name (ps,uris,ncnames) = (PrefixPool.get_name prefix_pool ps, UriPool.get_name uri_pool uris, NcnamePool.get_name ncname_pool ncnames) let symbol_prefix (ps,_,_) = PrefixPool.get_name prefix_pool ps let symbol_string s = let rs = symbol_name s in quoted_uri_string_of_rqname rs let symbol_prefix_string s = let rqname = symbol_name s in prefixed_string_of_rqname rqname (* Equality between symbols *) let symbol_equal (_,uris1,ncnames1) (_,uris2,ncnames2) = (uris1 = uris2) && (ncnames1 = ncnames2) let symbol_hash (_,uris1,ncnames1) = Hashtbl.hash (uris1,ncnames1) Subtagging let symbol_subtag (_,uris1,ncnames1) (_,uris2,ncnames2) = if (uris2 = wildcard_uri_symbol) then if (ncnames2 = wildcard_ncname_symbol) then true else (ncnames2 = ncnames1) else if (ncnames2 = wildcard_ncname_symbol) then (uris2 = uris1) else (ncnames2 = ncnames1) && (uris2 = uris1) (*********************************) (* Operations on element symbols *) (*********************************) type relem_symbol = symbol (* Creates a new symbol *) let relem_symbol rqname = symbol_create rqname let relem_equal = symbol_equal let relem_subtag = symbol_subtag (* Note: Those look-ups are expensive *) let relem_name s = symbol_name s let relem_name_with_binding nsenv s = let rqname = relem_name s in make_binding nsenv rqname let relem_uname nsenv s = let rqname = relem_name s in let (uqname,_,_) = make_binding nsenv rqname in uqname let relem_prefix s = symbol_prefix s let relem_string s = symbol_string s let relem_prefix_string s = symbol_prefix_string s (* Special symbols *) let anyrelem = wildcard_symbol (************************************) Operations on attributes symbols (************************************) type rattr_symbol = symbol (* Creates/accesses symbols *) let rattr_symbol rqname = symbol_create rqname let rattr_equal = symbol_equal let rattr_subtag = symbol_subtag let rattr_name s = symbol_name s let rattr_name_with_binding nsenv s = let rqname = symbol_name s in make_attribute_binding nsenv rqname let rattr_uname nsenv s = let rqname = symbol_name s in let (uqname,_,_) = make_attribute_binding nsenv rqname in uqname let rattr_prefix s = let (prefix,uri,_) = rattr_name s in match uri with | NSUri "" -> NSDefaultElementPrefix | _ -> prefix (* Converts a symbol to a string *) let rattr_string s = symbol_string s let rattr_prefix_string s = symbol_prefix_string s (* Special symbols *) let anyrattr = wildcard_symbol (******************************) (* Operations on type symbols *) (******************************) type rtype_symbol = symbol (* Creates/accesses symbols *) let rtype_symbol rqname = symbol_create rqname let rtype_name s = symbol_name s let rtype_prefix s = symbol_prefix s let rtype_equal = symbol_equal let rtype_subtag = symbol_subtag let rtype_string s = symbol_string s let rtype_prefix_string s = symbol_prefix_string s (* Special formal semantics symbols *) let anysimpletype = rtype_symbol xs_anySimpleType let anytype = rtype_symbol xs_anyType (* Special symbols *) let stringsym = rtype_symbol xs_string let booleansym = rtype_symbol xs_boolean let decimalsym = rtype_symbol xs_decimal let floatsym = rtype_symbol xs_float let doublesym = rtype_symbol xs_double let durationsym = rtype_symbol xs_duration let dateTimesym = rtype_symbol xs_dateTime let timesym = rtype_symbol xs_time let datesym = rtype_symbol xs_date let gYearMonthsym = rtype_symbol xs_gYearMonth let gYearsym = rtype_symbol xs_gYear let gMonthDaysym = rtype_symbol xs_gMonthDay let gDaysym = rtype_symbol xs_gDay let gMonthsym = rtype_symbol xs_gMonth let hexBinarysym = rtype_symbol xs_hexBinary let base64Binarysym = rtype_symbol xs_base64Binary let anyURIsym = rtype_symbol xs_anyURI let qnamesym = rtype_symbol xs_QName let notationsym = rtype_symbol xs_NOTATION let integersym = rtype_symbol xs_integer let intsym = rtype_symbol xs_int (* Predefined types in xs namespace: *) let dayTimeDurationsym = rtype_symbol xs_dayTimeDuration let yearMonthDurationsym = rtype_symbol xs_yearMonthDuration let untypedAtomicsym = rtype_symbol xs_untypedAtomic let untypedsym = rtype_symbol xs_untyped let anyAtomicTypesym = rtype_symbol xs_anyAtomicType (* Attribute symbols *) let idsym = rattr_symbol empty_ID let idrefsym = rattr_symbol empty_IDREF (***********************************) (* Operations on anonymous symbols *) (***********************************) Operations on resolved anonymous symbols type anon_symbol = symbol (* Creates/accesses symbols *) let anon_symbol rqname = symbol_create rqname let anon_equal = symbol_equal let anon_subtag = symbol_subtag let anon_name s = symbol_name s let anon_prefix s = symbol_prefix s (* Converts a symbol to a string *) let anon_string s = symbol_string s let anon_prefix_string s = symbol_prefix_string s (************************) Generic symbol types (************************) Generic resolved symbols type resolved_unit_symbol = | RUnitTupleSymbol (* for tuples *) | RUnitDocSymbol (* for documents *) | RUnitElemSymbol of relem_symbol (* for elements *) | RUnitAttrSymbol of rattr_symbol (* for attributes *) | RUnitTextSymbol (* for text nodes *) | RUnitSimpleSymbol of rtype_symbol (* for simple types *) | RUnitAnonSymbol of anon_symbol (* for anonymous symbols *) let equaltag s1 s2 = match (s1,s2) with | (RUnitDocSymbol, RUnitDocSymbol) -> true | (RUnitElemSymbol es1, RUnitElemSymbol es2) -> symbol_equal es1 es2 | (RUnitAttrSymbol as1, RUnitAttrSymbol as2) -> symbol_equal as1 as2 | (RUnitSimpleSymbol ss1, RUnitSimpleSymbol ss2) -> symbol_equal ss1 ss2 | (RUnitAnonSymbol ss1, RUnitAnonSymbol ss2) -> symbol_equal ss1 ss2 | (RUnitTextSymbol, RUnitTextSymbol) -> true | _ -> false let subtag s1 s2 = match (s1,s2) with | (RUnitDocSymbol, RUnitDocSymbol) -> true | (RUnitElemSymbol es1, RUnitElemSymbol es2) -> symbol_subtag es1 es2 | (RUnitAttrSymbol as1, RUnitAttrSymbol as2) -> symbol_subtag as1 as2 | (RUnitTextSymbol, RUnitTextSymbol) -> true | (RUnitSimpleSymbol ss1, RUnitSimpleSymbol ss2) -> (symbol_equal ss1 ss2) (* || (symbol_equal ss2 anyatomic) ??? *) | (RUnitAnonSymbol ss1, RUnitAnonSymbol ss2) -> symbol_equal ss1 ss2 | _ -> false
null
https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/namespace/namespace_symbols.ml
ocaml
********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* Module: Namespace_symbols Description: This module implements symbol tables for QNames. ************** Symbol pools ************** Pool for namespace prefixes Pool for namespace URIs ********* Symbols ********* Note: Symbols are triples now. - Jerome Symbol creation Symbol lookup Equality between symbols ******************************* Operations on element symbols ******************************* Creates a new symbol Note: Those look-ups are expensive Special symbols ********************************** ********************************** Creates/accesses symbols Converts a symbol to a string Special symbols **************************** Operations on type symbols **************************** Creates/accesses symbols Special formal semantics symbols Special symbols Predefined types in xs namespace: Attribute symbols ********************************* Operations on anonymous symbols ********************************* Creates/accesses symbols Converts a symbol to a string ********************** ********************** for tuples for documents for elements for attributes for text nodes for simple types for anonymous symbols || (symbol_equal ss2 anyatomic) ???
Copyright 2001 - 2007 . $ I d : namespace_symbols.ml , v 1.12 2007/08/20 13:12:40 simeon Exp $ open Error open Pool open Namespace_names open Namespace_builtin open Namespace_context module Prefix = struct type t = prefix let equal = (=) let hash = prefix_hash end module PrefixPool = MakeNamePool (Prefix) type prefix_symbol = PrefixPool.symbol let prefix_pool = PrefixPool.create_pool () module Uri = struct type t = uri let equal = (=) let hash = uri_hash end module UriPool = MakeNamePool (Uri) type uri_symbol = UriPool.symbol let uri_pool = UriPool.create_pool () Namepool for local names module Ncname = struct type t = ncname let equal = (=) let hash = ncname_hash end module NcnamePool = MakeNamePool (Ncname) type ncname_symbol = NcnamePool.symbol let ncname_pool = NcnamePool.create_pool () type symbol = (prefix_symbol * uri_symbol * ncname_symbol) let symbol_create (prefix,uri,ncname) = (PrefixPool.add_name prefix_pool prefix, UriPool.add_name uri_pool uri, NcnamePool.add_name ncname_pool ncname) let wildcard_symbol = symbol_create Namespace_builtin.wild_rqname let (wildcard_prefix_symbol,wildcard_uri_symbol,wildcard_ncname_symbol) = wildcard_symbol Note : Those look - ups are expensive and should be avoided - let symbol_name (ps,uris,ncnames) = (PrefixPool.get_name prefix_pool ps, UriPool.get_name uri_pool uris, NcnamePool.get_name ncname_pool ncnames) let symbol_prefix (ps,_,_) = PrefixPool.get_name prefix_pool ps let symbol_string s = let rs = symbol_name s in quoted_uri_string_of_rqname rs let symbol_prefix_string s = let rqname = symbol_name s in prefixed_string_of_rqname rqname let symbol_equal (_,uris1,ncnames1) (_,uris2,ncnames2) = (uris1 = uris2) && (ncnames1 = ncnames2) let symbol_hash (_,uris1,ncnames1) = Hashtbl.hash (uris1,ncnames1) Subtagging let symbol_subtag (_,uris1,ncnames1) (_,uris2,ncnames2) = if (uris2 = wildcard_uri_symbol) then if (ncnames2 = wildcard_ncname_symbol) then true else (ncnames2 = ncnames1) else if (ncnames2 = wildcard_ncname_symbol) then (uris2 = uris1) else (ncnames2 = ncnames1) && (uris2 = uris1) type relem_symbol = symbol let relem_symbol rqname = symbol_create rqname let relem_equal = symbol_equal let relem_subtag = symbol_subtag let relem_name s = symbol_name s let relem_name_with_binding nsenv s = let rqname = relem_name s in make_binding nsenv rqname let relem_uname nsenv s = let rqname = relem_name s in let (uqname,_,_) = make_binding nsenv rqname in uqname let relem_prefix s = symbol_prefix s let relem_string s = symbol_string s let relem_prefix_string s = symbol_prefix_string s let anyrelem = wildcard_symbol Operations on attributes symbols type rattr_symbol = symbol let rattr_symbol rqname = symbol_create rqname let rattr_equal = symbol_equal let rattr_subtag = symbol_subtag let rattr_name s = symbol_name s let rattr_name_with_binding nsenv s = let rqname = symbol_name s in make_attribute_binding nsenv rqname let rattr_uname nsenv s = let rqname = symbol_name s in let (uqname,_,_) = make_attribute_binding nsenv rqname in uqname let rattr_prefix s = let (prefix,uri,_) = rattr_name s in match uri with | NSUri "" -> NSDefaultElementPrefix | _ -> prefix let rattr_string s = symbol_string s let rattr_prefix_string s = symbol_prefix_string s let anyrattr = wildcard_symbol type rtype_symbol = symbol let rtype_symbol rqname = symbol_create rqname let rtype_name s = symbol_name s let rtype_prefix s = symbol_prefix s let rtype_equal = symbol_equal let rtype_subtag = symbol_subtag let rtype_string s = symbol_string s let rtype_prefix_string s = symbol_prefix_string s let anysimpletype = rtype_symbol xs_anySimpleType let anytype = rtype_symbol xs_anyType let stringsym = rtype_symbol xs_string let booleansym = rtype_symbol xs_boolean let decimalsym = rtype_symbol xs_decimal let floatsym = rtype_symbol xs_float let doublesym = rtype_symbol xs_double let durationsym = rtype_symbol xs_duration let dateTimesym = rtype_symbol xs_dateTime let timesym = rtype_symbol xs_time let datesym = rtype_symbol xs_date let gYearMonthsym = rtype_symbol xs_gYearMonth let gYearsym = rtype_symbol xs_gYear let gMonthDaysym = rtype_symbol xs_gMonthDay let gDaysym = rtype_symbol xs_gDay let gMonthsym = rtype_symbol xs_gMonth let hexBinarysym = rtype_symbol xs_hexBinary let base64Binarysym = rtype_symbol xs_base64Binary let anyURIsym = rtype_symbol xs_anyURI let qnamesym = rtype_symbol xs_QName let notationsym = rtype_symbol xs_NOTATION let integersym = rtype_symbol xs_integer let intsym = rtype_symbol xs_int let dayTimeDurationsym = rtype_symbol xs_dayTimeDuration let yearMonthDurationsym = rtype_symbol xs_yearMonthDuration let untypedAtomicsym = rtype_symbol xs_untypedAtomic let untypedsym = rtype_symbol xs_untyped let anyAtomicTypesym = rtype_symbol xs_anyAtomicType let idsym = rattr_symbol empty_ID let idrefsym = rattr_symbol empty_IDREF Operations on resolved anonymous symbols type anon_symbol = symbol let anon_symbol rqname = symbol_create rqname let anon_equal = symbol_equal let anon_subtag = symbol_subtag let anon_name s = symbol_name s let anon_prefix s = symbol_prefix s let anon_string s = symbol_string s let anon_prefix_string s = symbol_prefix_string s Generic symbol types Generic resolved symbols type resolved_unit_symbol = let equaltag s1 s2 = match (s1,s2) with | (RUnitDocSymbol, RUnitDocSymbol) -> true | (RUnitElemSymbol es1, RUnitElemSymbol es2) -> symbol_equal es1 es2 | (RUnitAttrSymbol as1, RUnitAttrSymbol as2) -> symbol_equal as1 as2 | (RUnitSimpleSymbol ss1, RUnitSimpleSymbol ss2) -> symbol_equal ss1 ss2 | (RUnitAnonSymbol ss1, RUnitAnonSymbol ss2) -> symbol_equal ss1 ss2 | (RUnitTextSymbol, RUnitTextSymbol) -> true | _ -> false let subtag s1 s2 = match (s1,s2) with | (RUnitDocSymbol, RUnitDocSymbol) -> true | (RUnitElemSymbol es1, RUnitElemSymbol es2) -> symbol_subtag es1 es2 | (RUnitAttrSymbol as1, RUnitAttrSymbol as2) -> symbol_subtag as1 as2 | (RUnitTextSymbol, RUnitTextSymbol) -> true | (RUnitSimpleSymbol ss1, RUnitSimpleSymbol ss2) -> | (RUnitAnonSymbol ss1, RUnitAnonSymbol ss2) -> symbol_equal ss1 ss2 | _ -> false
6b51adc583f9223390c9abaef9d732db2001b50d50aeb9c18b179db57b79b8ef
jarohen/yoyo
yoyo_api.clj
(ns leiningen.new.yoyo-api (:require [leiningen.new.templates :refer [renderer name-to-path ->files]])) (def render (renderer "yoyo-api")) (defn yoyo-api "Create a new Yo-yo API" [app-name] (println "Creating a new Yo-yo API...") (let [data {:name app-name :sanitized (name-to-path app-name)}] (->files data ["project.clj" (render "project.clj" data)] [".gitignore" (render "gitignore" data)] ["resources/log4j2.json" (render "resources/log4j2.json" data)] ["src/{{sanitized}}/service/main.clj" (render "clj/main.clj" data)] ["src/{{sanitized}}/service/handler.clj" (render "clj/handler.clj" data)])) (println "Created!") (println "To start the application, run `lein dev`, and then go to :3000"))
null
https://raw.githubusercontent.com/jarohen/yoyo/b579d21becd06b5330dee9f5963708db03ce1e25/templates/yoyo-api/src/leiningen/new/yoyo_api.clj
clojure
(ns leiningen.new.yoyo-api (:require [leiningen.new.templates :refer [renderer name-to-path ->files]])) (def render (renderer "yoyo-api")) (defn yoyo-api "Create a new Yo-yo API" [app-name] (println "Creating a new Yo-yo API...") (let [data {:name app-name :sanitized (name-to-path app-name)}] (->files data ["project.clj" (render "project.clj" data)] [".gitignore" (render "gitignore" data)] ["resources/log4j2.json" (render "resources/log4j2.json" data)] ["src/{{sanitized}}/service/main.clj" (render "clj/main.clj" data)] ["src/{{sanitized}}/service/handler.clj" (render "clj/handler.clj" data)])) (println "Created!") (println "To start the application, run `lein dev`, and then go to :3000"))
1bbc0dd70e0febc35accc4b8385167d48396ea4eceee8cd5ffcaa20f9a0ae17e
janestreet/core_bench
benchmark.ml
open Core open Core_bench_internals module Unix = Core_unix let stabilize_gc () = let rec loop failsafe last_heap_live_words = if failsafe <= 0 then failwith "unable to stabilize the number of live words in the major heap"; Gc.compact (); let stat = Gc.stat () in if stat.Gc.Stat.live_words <> last_heap_live_words then loop (failsafe - 1) stat.Gc.Stat.live_words in loop 10 0 ;; (* The main benchmarking function *) let measure = let module RC = Run_config in let module M = Measurement_sample in fun run_config test -> (* test function *) let (Test.Basic_test.T f) = test.Test.Basic_test.f in let f = f `init in (* the samples *) let max_samples = 3_000 in let results = Array.init max_samples ~f:(fun _ -> M.create ()) in (* counters *) let index = ref 0 in let runs = ref 0 in let total_runs = ref 0 in get the old Gc settings let old_gc = Gc.get () in (* THE MAIN TEST LOOP *) let init_t1 = Time_float.now () in let quota = RC.quota run_config in let quota_max_count = Quota.max_count quota in while (not (Quota.fulfilled quota ~start:init_t1 ~num_calls:!total_runs)) && !index < Array.length results do let current_runs = !runs in let current_index = !index in Stabilize gc if required . We stabilize the gc through the first pass through this loop anyway . If we do n't do this the incoming GC state ( some data may be on the minor heap that is partly full ) will cause an early collection or two which will not happen subsequently . These early collections are just noise . When benchmarking functions that do not allocate any memory , this early noise is the only significant input . In these cases , these spurious early collections will give the allocation stats ( major and promoted words ) a slight negative value . We stabilize the gc through the first pass through this loop anyway. If we don't do this the incoming GC state (some data may be on the minor heap that is partly full) will cause an early collection or two which will not happen subsequently. These early collections are just noise. When benchmarking functions that do not allocate any memory, this early noise is the only significant input. In these cases, these spurious early collections will give the allocation stats (major and promoted words) a slight negative value. *) if RC.stabilize_gc_between_runs run_config || current_runs = 0 then stabilize_gc (); make any Gc changes required . if RC.no_compactions run_config then Gc.set { (Gc.get ()) with Gc.Control.max_overhead = 1_000_000 }; (* pre-run measurements *) let gc1 = Gc.quick_stat () in let t1 = Time_float.now () in let c1 = Time_stamp_counter.now () in (* MEASURE A SINGLE SAMPLE *) for _ = 1 to current_runs do existential type from GADT done; (* END OF MEASUREMENT *) (* post-run measurements *) let c2 = Time_stamp_counter.now () in let t2 = Time_float.now () in let gc2 = Gc.quick_stat () in total_runs := !total_runs + current_runs; reset the old Gc now that we are done with measurements Gc.set old_gc; (* save measurements *) let s = results.(current_index) in s.M.runs <- current_runs; s.M.cycles <- (Time_stamp_counter.diff c2 c1 :> Int63.t); s.M.nanos <- Float.int63_round_down_exn (Time_float.Span.to_ns (Time_float.diff t2 t1)); s.M.minor_allocated <- Float.iround_towards_zero_exn (gc2.Gc.Stat.minor_words -. gc1.Gc.Stat.minor_words); s.M.major_allocated <- Float.iround_towards_zero_exn (gc2.Gc.Stat.major_words -. gc1.Gc.Stat.major_words); s.M.promoted <- Float.iround_towards_zero_exn (gc2.Gc.Stat.promoted_words -. gc1.Gc.Stat.promoted_words); s.M.compactions <- gc2.Gc.Stat.compactions - gc1.Gc.Stat.compactions; s.M.major_collections <- gc2.Gc.Stat.major_collections - gc1.Gc.Stat.major_collections; s.M.minor_collections <- gc2.Gc.Stat.minor_collections - gc1.Gc.Stat.minor_collections; incr index; (* determine the next number of runs *) let next = match RC.sampling_type run_config with | `Linear k -> current_runs + k | `Geometric scale -> let next_geometric = Float.iround_towards_zero_exn (Float.of_int current_runs *. scale) in Int.max next_geometric (current_runs + 1) in (* if [next] would put us over the quota, we decrease as necessary *) let next = Int.min next (quota_max_count - !total_runs) in assert (next >= 0); (* otherwise the loop guard is broken *) runs := next done; let end_time = Time_float.now () in (* END OF MAIN TEST LOOP *) let total_samples = !index in let largest_run = !runs in let measurement = Measurement.create ~name:(Test.Basic_test.name test) ~test_name:(Test.Basic_test.test_name test) ~file_name:(Test.Basic_test.file_name test) ~module_name:(Test.Basic_test.module_name test) ~largest_run ~sample_count:total_samples ~samples:results in Verbosity.print_high "%s: Total time taken %s (%d samples, max runs %d).\n%!" (Test.Basic_test.name test) (Time_float.Span.to_string (Time_float.diff end_time init_t1)) total_samples largest_run; (* if (RC.save_sample_data run_config) * then M.save test ~results total_samples; *) measurement ;; (* Run multiple benchmarks and aggregate the results. If forking is enabled then this function will fork and run each benchmark in a new child process. *) let measure_all run_config tests = Random.self_init (); let module RC = Run_config in Verbosity.set_verbosity (RC.verbosity run_config); (match RC.quota run_config with | Num_calls trials -> Verbosity.print_low "Estimated testing time unknown (%d benchmarks x %d trials). Change using '-quota'.\n\ %!" (List.length tests) trials | Span span -> let est_time = Time_float.Span.scale span (Float.of_int (List.length tests)) in Verbosity.print_low "Estimated testing time %s (%d benchmarks x %s). Change using '-quota'.\n%!" (Time_float.Span.to_string est_time) (List.length tests) (Time_float.Span.to_string span)); if RC.fork_each_benchmark run_config then ( let fds = List.map tests ~f:(fun _ -> Unix.pipe ()) in let () = Stdlib.List.iter2 (fun test (_fdr, fdw) -> match Caml_unix.fork () with | 0 -> let x = measure run_config test in let open Stdlib in let oc = Caml_unix.out_channel_of_descr fdw in Marshal.to_channel oc x []; exit 0 | pid -> ignore (Caml_unix.waitpid [] pid : int * Caml_unix.process_status)) tests fds in List.map fds ~f:(fun (fdr, _fdw) -> let open Stdlib in let ic = Caml_unix.in_channel_of_descr fdr in Marshal.from_channel ic)) else List.map tests ~f:(measure run_config) ;;
null
https://raw.githubusercontent.com/janestreet/core_bench/d3bf745cdaf8a0b169c5e464584a35aeb5b08291/src/benchmark.ml
ocaml
The main benchmarking function test function the samples counters THE MAIN TEST LOOP pre-run measurements MEASURE A SINGLE SAMPLE END OF MEASUREMENT post-run measurements save measurements determine the next number of runs if [next] would put us over the quota, we decrease as necessary otherwise the loop guard is broken END OF MAIN TEST LOOP if (RC.save_sample_data run_config) * then M.save test ~results total_samples; Run multiple benchmarks and aggregate the results. If forking is enabled then this function will fork and run each benchmark in a new child process.
open Core open Core_bench_internals module Unix = Core_unix let stabilize_gc () = let rec loop failsafe last_heap_live_words = if failsafe <= 0 then failwith "unable to stabilize the number of live words in the major heap"; Gc.compact (); let stat = Gc.stat () in if stat.Gc.Stat.live_words <> last_heap_live_words then loop (failsafe - 1) stat.Gc.Stat.live_words in loop 10 0 ;; let measure = let module RC = Run_config in let module M = Measurement_sample in fun run_config test -> let (Test.Basic_test.T f) = test.Test.Basic_test.f in let f = f `init in let max_samples = 3_000 in let results = Array.init max_samples ~f:(fun _ -> M.create ()) in let index = ref 0 in let runs = ref 0 in let total_runs = ref 0 in get the old Gc settings let old_gc = Gc.get () in let init_t1 = Time_float.now () in let quota = RC.quota run_config in let quota_max_count = Quota.max_count quota in while (not (Quota.fulfilled quota ~start:init_t1 ~num_calls:!total_runs)) && !index < Array.length results do let current_runs = !runs in let current_index = !index in Stabilize gc if required . We stabilize the gc through the first pass through this loop anyway . If we do n't do this the incoming GC state ( some data may be on the minor heap that is partly full ) will cause an early collection or two which will not happen subsequently . These early collections are just noise . When benchmarking functions that do not allocate any memory , this early noise is the only significant input . In these cases , these spurious early collections will give the allocation stats ( major and promoted words ) a slight negative value . We stabilize the gc through the first pass through this loop anyway. If we don't do this the incoming GC state (some data may be on the minor heap that is partly full) will cause an early collection or two which will not happen subsequently. These early collections are just noise. When benchmarking functions that do not allocate any memory, this early noise is the only significant input. In these cases, these spurious early collections will give the allocation stats (major and promoted words) a slight negative value. *) if RC.stabilize_gc_between_runs run_config || current_runs = 0 then stabilize_gc (); make any Gc changes required . if RC.no_compactions run_config then Gc.set { (Gc.get ()) with Gc.Control.max_overhead = 1_000_000 }; let gc1 = Gc.quick_stat () in let t1 = Time_float.now () in let c1 = Time_stamp_counter.now () in for _ = 1 to current_runs do existential type from GADT done; let c2 = Time_stamp_counter.now () in let t2 = Time_float.now () in let gc2 = Gc.quick_stat () in total_runs := !total_runs + current_runs; reset the old Gc now that we are done with measurements Gc.set old_gc; let s = results.(current_index) in s.M.runs <- current_runs; s.M.cycles <- (Time_stamp_counter.diff c2 c1 :> Int63.t); s.M.nanos <- Float.int63_round_down_exn (Time_float.Span.to_ns (Time_float.diff t2 t1)); s.M.minor_allocated <- Float.iround_towards_zero_exn (gc2.Gc.Stat.minor_words -. gc1.Gc.Stat.minor_words); s.M.major_allocated <- Float.iround_towards_zero_exn (gc2.Gc.Stat.major_words -. gc1.Gc.Stat.major_words); s.M.promoted <- Float.iround_towards_zero_exn (gc2.Gc.Stat.promoted_words -. gc1.Gc.Stat.promoted_words); s.M.compactions <- gc2.Gc.Stat.compactions - gc1.Gc.Stat.compactions; s.M.major_collections <- gc2.Gc.Stat.major_collections - gc1.Gc.Stat.major_collections; s.M.minor_collections <- gc2.Gc.Stat.minor_collections - gc1.Gc.Stat.minor_collections; incr index; let next = match RC.sampling_type run_config with | `Linear k -> current_runs + k | `Geometric scale -> let next_geometric = Float.iround_towards_zero_exn (Float.of_int current_runs *. scale) in Int.max next_geometric (current_runs + 1) in let next = Int.min next (quota_max_count - !total_runs) in assert (next >= 0); runs := next done; let end_time = Time_float.now () in let total_samples = !index in let largest_run = !runs in let measurement = Measurement.create ~name:(Test.Basic_test.name test) ~test_name:(Test.Basic_test.test_name test) ~file_name:(Test.Basic_test.file_name test) ~module_name:(Test.Basic_test.module_name test) ~largest_run ~sample_count:total_samples ~samples:results in Verbosity.print_high "%s: Total time taken %s (%d samples, max runs %d).\n%!" (Test.Basic_test.name test) (Time_float.Span.to_string (Time_float.diff end_time init_t1)) total_samples largest_run; measurement ;; let measure_all run_config tests = Random.self_init (); let module RC = Run_config in Verbosity.set_verbosity (RC.verbosity run_config); (match RC.quota run_config with | Num_calls trials -> Verbosity.print_low "Estimated testing time unknown (%d benchmarks x %d trials). Change using '-quota'.\n\ %!" (List.length tests) trials | Span span -> let est_time = Time_float.Span.scale span (Float.of_int (List.length tests)) in Verbosity.print_low "Estimated testing time %s (%d benchmarks x %s). Change using '-quota'.\n%!" (Time_float.Span.to_string est_time) (List.length tests) (Time_float.Span.to_string span)); if RC.fork_each_benchmark run_config then ( let fds = List.map tests ~f:(fun _ -> Unix.pipe ()) in let () = Stdlib.List.iter2 (fun test (_fdr, fdw) -> match Caml_unix.fork () with | 0 -> let x = measure run_config test in let open Stdlib in let oc = Caml_unix.out_channel_of_descr fdw in Marshal.to_channel oc x []; exit 0 | pid -> ignore (Caml_unix.waitpid [] pid : int * Caml_unix.process_status)) tests fds in List.map fds ~f:(fun (fdr, _fdw) -> let open Stdlib in let ic = Caml_unix.in_channel_of_descr fdr in Marshal.from_channel ic)) else List.map tests ~f:(measure run_config) ;;
48bc56b7369b1aabba4ac7b5602308a155575ef9b660988db46c0b0a03402de2
Vaguery/klapaucius
set_able_test.clj
(ns push.instructions.aspects.set-able-test (:require [push.interpreter.core :as i]) (:require [push.core :as push]) (:use midje.sweet) (:use push.util.stack-manipulation) (:use push.type.core) (:use push.instructions.aspects) (:use push.instructions.aspects.set-able) ) ;; set-able instructions (fact "conj-set-instruction returns an Instruction with the correct stuff" (let [foo-conj-set (conj-set-instruction (make-type :foo))] (class foo-conj-set) => push.instructions.core.Instruction (:needs foo-conj-set) => {:foo 1, :set 1} (:token foo-conj-set) => :foo-conj-set (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{99})}) foo-conj-set) :foo-conj-set) :exec) => '(#{99 11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3]) :set '(#{99})}) foo-conj-set) :foo-conj-set) :exec) => '(#{99 1 2 3}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '({1 2 3 4}) :set '(#{99})}) foo-conj-set) :foo-conj-set) :exec) => '(#{99 {1 2 3 4}}) )) (fact "intoset-instruction returns an Instruction with the correct stuff" (let [foo-intoset (intoset-instruction (make-type :foo))] (class foo-intoset) => push.instructions.core.Instruction (:needs foo-intoset) => {:foo 1, :set 1} (:token foo-intoset) => :foo-intoset (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{99})}) foo-intoset) :foo-intoset) :exec) => '(#{99 11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3]) :set '(#{99})}) foo-intoset) :foo-intoset) :exec) => '(#{99 [1 2 3]}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '({1 2 3 4}) :set '(#{99})}) foo-intoset) :foo-intoset) :exec) => '(#{99 {1 2 3 4}}) )) (fact "as-set-instruction returns an Instruction with the correct stuff" (let [foo-as-set (as-set-instruction (make-type :foo))] (class foo-as-set) => push.instructions.core.Instruction (:needs foo-as-set) => {:foo 1} (:token foo-as-set) => :foo-as-set (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11)}) foo-as-set) :foo-as-set) :exec) => '(#{11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3])}) foo-as-set) :foo-as-set) :exec) => '(#{1 2 3}) )) (fact "toset-instruction returns an Instruction with the correct stuff" (let [foo-toset (toset-instruction (make-type :foo))] (class foo-toset) => push.instructions.core.Instruction (:needs foo-toset) => {:foo 1} (:token foo-toset) => :foo->set (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11)}) foo-toset) :foo->set) :exec) => '(#{11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3])}) foo-toset) :foo->set) :exec) => '(#{[1 2 3]}) )) (fact "in-set?-instruction returns an Instruction with the correct stuff" (let [foo-in-set? (in-set?-instruction (make-type :foo))] (class foo-in-set?) => push.instructions.core.Instruction (:needs foo-in-set?) => {:foo 1, :set 1} (:token foo-in-set?) => :foo-in-set? (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{22})}) foo-in-set?) :foo-in-set?) :exec) => '(false) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{11 22 33})}) foo-in-set?) :foo-in-set?) :exec) => '(true) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([11]) :set '(#{[11] 22 33})}) foo-in-set?) :foo-in-set?) :exec) => '(true) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{[11] 22 33})}) foo-in-set?) :foo-in-set?) :exec) => '(false) )) (fact "`make-set-able` takes adds the :set-able attribute to a PushType record" (:attributes (make-set-able (make-type :foo))) => #{:set-able}) (fact "`make-set-able` takes adds appropriate instructions to a PushType record" (keys (:instructions (make-set-able (make-type :foo)))) => (contains [:foo->set :foo-as-set] :in-any-order :gaps-ok))
null
https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/test/push/instructions/aspects/set_able_test.clj
clojure
set-able instructions
(ns push.instructions.aspects.set-able-test (:require [push.interpreter.core :as i]) (:require [push.core :as push]) (:use midje.sweet) (:use push.util.stack-manipulation) (:use push.type.core) (:use push.instructions.aspects) (:use push.instructions.aspects.set-able) ) (fact "conj-set-instruction returns an Instruction with the correct stuff" (let [foo-conj-set (conj-set-instruction (make-type :foo))] (class foo-conj-set) => push.instructions.core.Instruction (:needs foo-conj-set) => {:foo 1, :set 1} (:token foo-conj-set) => :foo-conj-set (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{99})}) foo-conj-set) :foo-conj-set) :exec) => '(#{99 11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3]) :set '(#{99})}) foo-conj-set) :foo-conj-set) :exec) => '(#{99 1 2 3}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '({1 2 3 4}) :set '(#{99})}) foo-conj-set) :foo-conj-set) :exec) => '(#{99 {1 2 3 4}}) )) (fact "intoset-instruction returns an Instruction with the correct stuff" (let [foo-intoset (intoset-instruction (make-type :foo))] (class foo-intoset) => push.instructions.core.Instruction (:needs foo-intoset) => {:foo 1, :set 1} (:token foo-intoset) => :foo-intoset (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{99})}) foo-intoset) :foo-intoset) :exec) => '(#{99 11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3]) :set '(#{99})}) foo-intoset) :foo-intoset) :exec) => '(#{99 [1 2 3]}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '({1 2 3 4}) :set '(#{99})}) foo-intoset) :foo-intoset) :exec) => '(#{99 {1 2 3 4}}) )) (fact "as-set-instruction returns an Instruction with the correct stuff" (let [foo-as-set (as-set-instruction (make-type :foo))] (class foo-as-set) => push.instructions.core.Instruction (:needs foo-as-set) => {:foo 1} (:token foo-as-set) => :foo-as-set (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11)}) foo-as-set) :foo-as-set) :exec) => '(#{11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3])}) foo-as-set) :foo-as-set) :exec) => '(#{1 2 3}) )) (fact "toset-instruction returns an Instruction with the correct stuff" (let [foo-toset (toset-instruction (make-type :foo))] (class foo-toset) => push.instructions.core.Instruction (:needs foo-toset) => {:foo 1} (:token foo-toset) => :foo->set (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11)}) foo-toset) :foo->set) :exec) => '(#{11}) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([1 2 3])}) foo-toset) :foo->set) :exec) => '(#{[1 2 3]}) )) (fact "in-set?-instruction returns an Instruction with the correct stuff" (let [foo-in-set? (in-set?-instruction (make-type :foo))] (class foo-in-set?) => push.instructions.core.Instruction (:needs foo-in-set?) => {:foo 1, :set 1} (:token foo-in-set?) => :foo-in-set? (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{22})}) foo-in-set?) :foo-in-set?) :exec) => '(false) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{11 22 33})}) foo-in-set?) :foo-in-set?) :exec) => '(true) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '([11]) :set '(#{[11] 22 33})}) foo-in-set?) :foo-in-set?) :exec) => '(true) (get-stack (i/execute-instruction (i/register-instruction (push/interpreter :stacks {:foo '(11) :set '(#{[11] 22 33})}) foo-in-set?) :foo-in-set?) :exec) => '(false) )) (fact "`make-set-able` takes adds the :set-able attribute to a PushType record" (:attributes (make-set-able (make-type :foo))) => #{:set-able}) (fact "`make-set-able` takes adds appropriate instructions to a PushType record" (keys (:instructions (make-set-able (make-type :foo)))) => (contains [:foo->set :foo-as-set] :in-any-order :gaps-ok))
26291a48f8a6664ac2818dd26578094caf9a7ce8dd2bc6d350ceff8034b920ba
isovector/ld52
DespawnTrigger.hs
module Game.Objects.DespawnTrigger where import Control.Monad (void) import qualified Data.Map as M import Data.Monoid import Game.Common despawnTrigger :: V2 WorldPos -> OriginRect Double -> Set ObjectId -> Object despawnTrigger pos ore despawns = playerHitRectObj' (proc oi -> do let ev = onHitBy IsPlayer oi hit_change <- onChange -< event Nothing Just ev let is_hit = hit_change >>= maybeToEvent returnA -< mempty { oe_die = void is_hit , oe_omnipotence = despawnAll despawns <$ is_hit } ) ore 0 pos despawnAll :: Set ObjectId -> ObjectMap ObjSF -> ObjectMap ObjSF despawnAll despawns = #objm_map %~ appEndo (foldMap (Endo . M.delete) despawns)
null
https://raw.githubusercontent.com/isovector/ld52/949f6f589672fcaf24e7fffa8f737092993c7b6e/src/Game/Objects/DespawnTrigger.hs
haskell
module Game.Objects.DespawnTrigger where import Control.Monad (void) import qualified Data.Map as M import Data.Monoid import Game.Common despawnTrigger :: V2 WorldPos -> OriginRect Double -> Set ObjectId -> Object despawnTrigger pos ore despawns = playerHitRectObj' (proc oi -> do let ev = onHitBy IsPlayer oi hit_change <- onChange -< event Nothing Just ev let is_hit = hit_change >>= maybeToEvent returnA -< mempty { oe_die = void is_hit , oe_omnipotence = despawnAll despawns <$ is_hit } ) ore 0 pos despawnAll :: Set ObjectId -> ObjectMap ObjSF -> ObjectMap ObjSF despawnAll despawns = #objm_map %~ appEndo (foldMap (Endo . M.delete) despawns)
3246aad80bda4c81ec05aa2dd2c65373873c67ca1cffa5f69ad888c10987fda2
racket/racket-lang-org
docs.rkt
#lang plt-web (require (only-in "../www/resources.rkt" www-site) "../testing.rkt" plt-web/private/image-version) (define docs-site (site "stubs/docs" #:url (rewrite-for-testing "-lang.org/") #:always-abs-url? #t #:page-style? #f #:meta? #t #:share-from www-site)) (provide documentation) (define documentation ;; This is a stub page to get the header for tweaked doc pages (page #:site docs-site #:file "" #:link-title "Documentation" #:window-title "{{{TITLE}}}" "\n{{{BODY}}}\n")) (void (plain #:site docs-site #:file "doc-site.js" @list{ function AddLogoToMainDiv() { var main_div = document.getElementsByClassName("main")[0]; var h = document.createElement('div'); h.setAttribute("class", "docsite-logo"); h.innerHTML = "<a href=\"@(url-of (resource "www/" #f))\"><img src=\"@(url-of (resource "www/" #f))@(format "logo-and-text~a.png" (image-version-suffix))\" alt=\"Racket\" /></a>"; main_div.insertBefore(h, main_div.firstChild); } AddOnLoad(AddLogoToMainDiv); })) (void (plain #:site docs-site #:file "doc-site.css" @list{ .docsite-logo { float: right; position: relative; top: -2.5em; left: 1.3em; } .docsite-logo img { width: 8em; }})) (provide docs-path) (define (docs-path [path ""]) (string-append ((resource "stubs/docs/" #f)) path))
null
https://raw.githubusercontent.com/racket/racket-lang-org/88dada2ee769ada9afaf1e3ec1fb28b8ddf216db/stubs/docs.rkt
racket
This is a stub page to get the header for tweaked doc pages
#lang plt-web (require (only-in "../www/resources.rkt" www-site) "../testing.rkt" plt-web/private/image-version) (define docs-site (site "stubs/docs" #:url (rewrite-for-testing "-lang.org/") #:always-abs-url? #t #:page-style? #f #:meta? #t #:share-from www-site)) (provide documentation) (define documentation (page #:site docs-site #:file "" #:link-title "Documentation" #:window-title "{{{TITLE}}}" "\n{{{BODY}}}\n")) (void (plain #:site docs-site #:file "doc-site.js" @list{ function AddLogoToMainDiv() { } })) (void (plain #:site docs-site #:file "doc-site.css" @list{ .docsite-logo { } .docsite-logo img { }})) (provide docs-path) (define (docs-path [path ""]) (string-append ((resource "stubs/docs/" #f)) path))
d1be86761a8cffdb27cf552d4c032e6e83c0eefc31ed0c76b2d0ff5a1dc8a1f0
juspay/atlas
LocationGps.hs
| Copyright 2022 Juspay Technologies Pvt Ltd 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 . Module : Core . Spec . Search . LocationGps Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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. Module : Core.Spec.Search.LocationGps Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Core.Spec.Search.LocationGps where import Beckn.Types.Core.Migration.Gps import Beckn.Utils.GenericPretty (PrettyShow) import Beckn.Utils.Schema import Data.Aeson import Data.OpenApi (ToSchema (declareNamedSchema), defaultSchemaOptions) import Relude hiding (id) newtype LocationGps = LocationGps {gps :: Gps} deriving (Generic, Show) deriving anyclass (ToJSON, FromJSON, PrettyShow) instance ToSchema LocationGps where declareNamedSchema = genericDeclareUnNamedSchema defaultSchemaOptions
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/public-transport-bap/src/Core/Spec/Search/LocationGps.hs
haskell
| Copyright 2022 Juspay Technologies Pvt Ltd 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 . Module : Core . Spec . Search . LocationGps Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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. Module : Core.Spec.Search.LocationGps Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Core.Spec.Search.LocationGps where import Beckn.Types.Core.Migration.Gps import Beckn.Utils.GenericPretty (PrettyShow) import Beckn.Utils.Schema import Data.Aeson import Data.OpenApi (ToSchema (declareNamedSchema), defaultSchemaOptions) import Relude hiding (id) newtype LocationGps = LocationGps {gps :: Gps} deriving (Generic, Show) deriving anyclass (ToJSON, FromJSON, PrettyShow) instance ToSchema LocationGps where declareNamedSchema = genericDeclareUnNamedSchema defaultSchemaOptions
a3935cbf90610e6f726daae134894899c9915792f962355af6b80a7c6b231168
jjsimpso/magic
reader-tester.rkt
#lang magic #Copyright 2019 Jonathan Simpson # # 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. 0 beshort 0x0206 ALAN game data >2 byte <10 version 2.6%d 0 ubyte >0 0 regex/s \\`(\\r\\n|;|[[]) (80.l) string >\0 SourcePath "%s"
null
https://raw.githubusercontent.com/jjsimpso/magic/d5f6804ee2cf9b927efda07c31355e29d6bbe38b/reader-tester.rkt
racket
|[[])
#lang magic #Copyright 2019 Jonathan Simpson # # 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. 0 beshort 0x0206 ALAN game data >2 byte <10 version 2.6%d 0 ubyte >0 (80.l) string >\0 SourcePath "%s"
8af3c026bc10af6806f5de54fc543eb5bb94b11672145d4ce9aabe0a87e0d024
ghcjs/jsaddle-dom
CommandLineAPIHost.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.CommandLineAPIHost (clearConsoleMessages, copyText, inspect, inspectedObject, inspectedObject_, getEventListeners, getEventListeners_, databaseId, databaseId_, storageId, storageId_, CommandLineAPIHost(..), gTypeCommandLineAPIHost) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/CommandLineAPIHost.clearConsoleMessages Mozilla CommandLineAPIHost.clearConsoleMessages documentation > clearConsoleMessages :: (MonadDOM m) => CommandLineAPIHost -> m () clearConsoleMessages self = liftDOM (void (self ^. jsf "clearConsoleMessages" ())) | < -US/docs/Web/API/CommandLineAPIHost.copyText Mozilla CommandLineAPIHost.copyText documentation > copyText :: (MonadDOM m, ToJSString text) => CommandLineAPIHost -> text -> m () copyText self text = liftDOM (void (self ^. jsf "copyText" [toJSVal text])) | < -US/docs/Web/API/CommandLineAPIHost.inspect Mozilla CommandLineAPIHost.inspect documentation > inspect :: (MonadDOM m, ToJSVal objectId, ToJSVal hints) => CommandLineAPIHost -> objectId -> hints -> m () inspect self objectId hints = liftDOM (void (self ^. jsf "inspect" [toJSVal objectId, toJSVal hints])) | < -US/docs/Web/API/CommandLineAPIHost.inspectedObject Mozilla CommandLineAPIHost.inspectedObject documentation > inspectedObject :: (MonadDOM m) => CommandLineAPIHost -> m JSVal inspectedObject self = liftDOM ((self ^. jsf "inspectedObject" ()) >>= toJSVal) | < -US/docs/Web/API/CommandLineAPIHost.inspectedObject Mozilla CommandLineAPIHost.inspectedObject documentation > inspectedObject_ :: (MonadDOM m) => CommandLineAPIHost -> m () inspectedObject_ self = liftDOM (void (self ^. jsf "inspectedObject" ())) | < -US/docs/Web/API/CommandLineAPIHost.getEventListeners Mozilla CommandLineAPIHost.getEventListeners documentation > getEventListeners :: (MonadDOM m, IsNode node) => CommandLineAPIHost -> node -> m Array getEventListeners self node = liftDOM ((self ^. jsf "getEventListeners" [toJSVal node]) >>= fromJSValUnchecked) | < -US/docs/Web/API/CommandLineAPIHost.getEventListeners Mozilla CommandLineAPIHost.getEventListeners documentation > getEventListeners_ :: (MonadDOM m, IsNode node) => CommandLineAPIHost -> node -> m () getEventListeners_ self node = liftDOM (void (self ^. jsf "getEventListeners" [toJSVal node])) | < -US/docs/Web/API/CommandLineAPIHost.databaseId Mozilla CommandLineAPIHost.databaseId documentation > databaseId :: (MonadDOM m, ToJSVal database, FromJSString result) => CommandLineAPIHost -> database -> m result databaseId self database = liftDOM ((self ^. jsf "databaseId" [toJSVal database]) >>= fromJSValUnchecked) | < -US/docs/Web/API/CommandLineAPIHost.databaseId Mozilla CommandLineAPIHost.databaseId documentation > databaseId_ :: (MonadDOM m, ToJSVal database) => CommandLineAPIHost -> database -> m () databaseId_ self database = liftDOM (void (self ^. jsf "databaseId" [toJSVal database])) | < -US/docs/Web/API/CommandLineAPIHost.storageId Mozilla CommandLineAPIHost.storageId documentation > storageId :: (MonadDOM m, ToJSVal storage, FromJSString result) => CommandLineAPIHost -> storage -> m result storageId self storage = liftDOM ((self ^. jsf "storageId" [toJSVal storage]) >>= fromJSValUnchecked) | < -US/docs/Web/API/CommandLineAPIHost.storageId Mozilla CommandLineAPIHost.storageId documentation > storageId_ :: (MonadDOM m, ToJSVal storage) => CommandLineAPIHost -> storage -> m () storageId_ self storage = liftDOM (void (self ^. jsf "storageId" [toJSVal storage]))
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/CommandLineAPIHost.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.CommandLineAPIHost (clearConsoleMessages, copyText, inspect, inspectedObject, inspectedObject_, getEventListeners, getEventListeners_, databaseId, databaseId_, storageId, storageId_, CommandLineAPIHost(..), gTypeCommandLineAPIHost) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/CommandLineAPIHost.clearConsoleMessages Mozilla CommandLineAPIHost.clearConsoleMessages documentation > clearConsoleMessages :: (MonadDOM m) => CommandLineAPIHost -> m () clearConsoleMessages self = liftDOM (void (self ^. jsf "clearConsoleMessages" ())) | < -US/docs/Web/API/CommandLineAPIHost.copyText Mozilla CommandLineAPIHost.copyText documentation > copyText :: (MonadDOM m, ToJSString text) => CommandLineAPIHost -> text -> m () copyText self text = liftDOM (void (self ^. jsf "copyText" [toJSVal text])) | < -US/docs/Web/API/CommandLineAPIHost.inspect Mozilla CommandLineAPIHost.inspect documentation > inspect :: (MonadDOM m, ToJSVal objectId, ToJSVal hints) => CommandLineAPIHost -> objectId -> hints -> m () inspect self objectId hints = liftDOM (void (self ^. jsf "inspect" [toJSVal objectId, toJSVal hints])) | < -US/docs/Web/API/CommandLineAPIHost.inspectedObject Mozilla CommandLineAPIHost.inspectedObject documentation > inspectedObject :: (MonadDOM m) => CommandLineAPIHost -> m JSVal inspectedObject self = liftDOM ((self ^. jsf "inspectedObject" ()) >>= toJSVal) | < -US/docs/Web/API/CommandLineAPIHost.inspectedObject Mozilla CommandLineAPIHost.inspectedObject documentation > inspectedObject_ :: (MonadDOM m) => CommandLineAPIHost -> m () inspectedObject_ self = liftDOM (void (self ^. jsf "inspectedObject" ())) | < -US/docs/Web/API/CommandLineAPIHost.getEventListeners Mozilla CommandLineAPIHost.getEventListeners documentation > getEventListeners :: (MonadDOM m, IsNode node) => CommandLineAPIHost -> node -> m Array getEventListeners self node = liftDOM ((self ^. jsf "getEventListeners" [toJSVal node]) >>= fromJSValUnchecked) | < -US/docs/Web/API/CommandLineAPIHost.getEventListeners Mozilla CommandLineAPIHost.getEventListeners documentation > getEventListeners_ :: (MonadDOM m, IsNode node) => CommandLineAPIHost -> node -> m () getEventListeners_ self node = liftDOM (void (self ^. jsf "getEventListeners" [toJSVal node])) | < -US/docs/Web/API/CommandLineAPIHost.databaseId Mozilla CommandLineAPIHost.databaseId documentation > databaseId :: (MonadDOM m, ToJSVal database, FromJSString result) => CommandLineAPIHost -> database -> m result databaseId self database = liftDOM ((self ^. jsf "databaseId" [toJSVal database]) >>= fromJSValUnchecked) | < -US/docs/Web/API/CommandLineAPIHost.databaseId Mozilla CommandLineAPIHost.databaseId documentation > databaseId_ :: (MonadDOM m, ToJSVal database) => CommandLineAPIHost -> database -> m () databaseId_ self database = liftDOM (void (self ^. jsf "databaseId" [toJSVal database])) | < -US/docs/Web/API/CommandLineAPIHost.storageId Mozilla CommandLineAPIHost.storageId documentation > storageId :: (MonadDOM m, ToJSVal storage, FromJSString result) => CommandLineAPIHost -> storage -> m result storageId self storage = liftDOM ((self ^. jsf "storageId" [toJSVal storage]) >>= fromJSValUnchecked) | < -US/docs/Web/API/CommandLineAPIHost.storageId Mozilla CommandLineAPIHost.storageId documentation > storageId_ :: (MonadDOM m, ToJSVal storage) => CommandLineAPIHost -> storage -> m () storageId_ self storage = liftDOM (void (self ^. jsf "storageId" [toJSVal storage]))
a0ad4b56369bc200bc7b607943772f6c21d7e6664e19995fb89309aff401026b
asmala/clj-simple-form
i18n.clj
(ns clj-simple-form.i18n "Functions for translating form contents, such as labels." (:require [taoensso.tower :as tower])) (def ^:dynamic *translation-scope* []) (defmacro with-form-translation-scope "Sets up a binding for form element translations. ### Example (with-form-translation-scope :profile (t :labels :email))" [object & content] `(binding [*translation-scope* (conj *translation-scope* ~(name object))] (list ~@content))) (defn- lookup-seq->ns-seq "Converts a sequence of nested field groupings into a sequence of dictionary namespaces. ### Example = > ( \"a.b\ " \"b\ " ) " [lookup-seq] (if (empty? lookup-seq) nil (letfn [(deepen-ns [k ns-s] (str ns-s "." k)) (add-ns-key [ns-seq k] (conj (map (partial deepen-ns k) ns-seq) k))] (reverse (reduce add-ns-key [(first lookup-seq)] (rest lookup-seq)))))) (defn- scoped-keys "Returns the keys to be used with Tower translations." [type field] (let [type (name type) field (name field) ns-seq (concat (lookup-seq->ns-seq *translation-scope*) ["defaults"])] (vec (map #(keyword (str "simple-form." % "." type) field) ns-seq)))) (defn- root-scoped-t "Returns a translation igoring the current Tower translation scope." [k-or-ks] (tower/with-scope nil (tower/t k-or-ks))) (defn t "Returns a translation of the given type for the field. ### Examples (t :labels :email) (t :placeholder :name \"First Last\")" ([type field] (root-scoped-t (scoped-keys type field))) ([type field default] (root-scoped-t (conj (scoped-keys type field) default))))
null
https://raw.githubusercontent.com/asmala/clj-simple-form/b1c566b1f0fe532639b15832b557f1608598a0a2/clj-simple-form-core/src/clj_simple_form/i18n.clj
clojure
(ns clj-simple-form.i18n "Functions for translating form contents, such as labels." (:require [taoensso.tower :as tower])) (def ^:dynamic *translation-scope* []) (defmacro with-form-translation-scope "Sets up a binding for form element translations. ### Example (with-form-translation-scope :profile (t :labels :email))" [object & content] `(binding [*translation-scope* (conj *translation-scope* ~(name object))] (list ~@content))) (defn- lookup-seq->ns-seq "Converts a sequence of nested field groupings into a sequence of dictionary namespaces. ### Example = > ( \"a.b\ " \"b\ " ) " [lookup-seq] (if (empty? lookup-seq) nil (letfn [(deepen-ns [k ns-s] (str ns-s "." k)) (add-ns-key [ns-seq k] (conj (map (partial deepen-ns k) ns-seq) k))] (reverse (reduce add-ns-key [(first lookup-seq)] (rest lookup-seq)))))) (defn- scoped-keys "Returns the keys to be used with Tower translations." [type field] (let [type (name type) field (name field) ns-seq (concat (lookup-seq->ns-seq *translation-scope*) ["defaults"])] (vec (map #(keyword (str "simple-form." % "." type) field) ns-seq)))) (defn- root-scoped-t "Returns a translation igoring the current Tower translation scope." [k-or-ks] (tower/with-scope nil (tower/t k-or-ks))) (defn t "Returns a translation of the given type for the field. ### Examples (t :labels :email) (t :placeholder :name \"First Last\")" ([type field] (root-scoped-t (scoped-keys type field))) ([type field default] (root-scoped-t (conj (scoped-keys type field) default))))
51f5e6048ddec3ade1bc4aa3062d0700fdc672ea6fe278a2a22b7f76eecb7c20
thi-ng/demos
utils.clj
(ns ws-ldn-2.utils) (defn deep-merge "Merge fn to be used with `merge-with`. Recursively merges map values which are maps or seqs (for the latter `into` is used). If the RHS value has the metadata key :replace set, it is used as new value without merging." [l r] (cond (:replace (meta r)) r (or (sequential? l) (set? l)) (into l r) (map? l) (merge-with deep-merge l r) :else r)) (comment ;; example usage (merge-with deep-merge {:a 23 :b {"c" 42} :d ["e"] :f ["f"]} {:a2 42 :b {"c2" 66} :d ["e2"] :f ^:replace ["f2"]}) { : a 23 : b { " c " 42 , " c2 " 66 } ; ; merged ;; :d ["e" "e2"] ;; merged ;; :f ["f2"] ;; replaced : a2 42 } )
null
https://raw.githubusercontent.com/thi-ng/demos/048cd131099a7db29be56b965c053908acad4166/ws-ldn-2/src/clj/ws_ldn_2/utils.clj
clojure
example usage ; merged :d ["e" "e2"] ;; merged :f ["f2"] ;; replaced
(ns ws-ldn-2.utils) (defn deep-merge "Merge fn to be used with `merge-with`. Recursively merges map values which are maps or seqs (for the latter `into` is used). If the RHS value has the metadata key :replace set, it is used as new value without merging." [l r] (cond (:replace (meta r)) r (or (sequential? l) (set? l)) (into l r) (map? l) (merge-with deep-merge l r) :else r)) (comment (merge-with deep-merge {:a 23 :b {"c" 42} :d ["e"] :f ["f"]} {:a2 42 :b {"c2" 66} :d ["e2"] :f ^:replace ["f2"]}) { : a 23 : a2 42 } )
4336dc159d2b213eebf7dfec667f180fc0da5d45c4fe7f73a202ead7a102e2c9
inhabitedtype/ocaml-aws
unassignIpv6Addresses.ml
open Types open Aws type input = UnassignIpv6AddressesRequest.t type output = UnassignIpv6AddressesResult.t type error = Errors_internal.t let service = "ec2" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2016-11-15" ]; "Action", [ "UnassignIpv6Addresses" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (UnassignIpv6AddressesRequest.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Xml.member "UnassignIpv6AddressesResponse" (snd xml) in try Util.or_error (Util.option_bind resp UnassignIpv6AddressesResult.parse) (let open Error in BadResponse { body; message = "Could not find well formed UnassignIpv6AddressesResult." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing UnassignIpv6AddressesResult - missing field in body or \ children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/ec2/lib/unassignIpv6Addresses.ml
ocaml
open Types open Aws type input = UnassignIpv6AddressesRequest.t type output = UnassignIpv6AddressesResult.t type error = Errors_internal.t let service = "ec2" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2016-11-15" ]; "Action", [ "UnassignIpv6Addresses" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (UnassignIpv6AddressesRequest.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Xml.member "UnassignIpv6AddressesResponse" (snd xml) in try Util.or_error (Util.option_bind resp UnassignIpv6AddressesResult.parse) (let open Error in BadResponse { body; message = "Could not find well formed UnassignIpv6AddressesResult." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing UnassignIpv6AddressesResult - missing field in body or \ children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
e811076e1a98c9bde5727b489ac7d73c9f3e06c405aafc8cae4563779893b710
DomainDrivenArchitecture/dda-git-crate
app.clj
Licensed to the Apache Software Foundation ( ASF ) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file to you 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. (ns dda.pallet.dda-git-crate.app (:require [schema.core :as s] [dda.pallet.commons.secret :as secret] [dda.pallet.core.app :as core-app] [dda.pallet.dda-config-crate.infra :as config-crate] [dda.pallet.dda-serverspec-crate.app :as serverspec] [dda.pallet.dda-git-crate.infra :as infra] [dda.pallet.dda-git-crate.convention :as convention])) (def with-git infra/with-git) (def InfraResult convention/InfraResult) (def GitConvention convention/GitConvention) (def GitConventionResolved (secret/create-resolved-schema GitConvention)) (def GitAppConfig {:group-specific-config {s/Keyword InfraResult}}) (s/defn ^:always-validate app-configuration-resolved :- GitAppConfig [convention-config :- GitConventionResolved & options] (let [{:keys [group-key] :or {group-key infra/facility}} options] {:group-specific-config {group-key (convention/infra-configuration convention-config)}})) (s/defn ^:always-validate app-configuration :- GitAppConfig [convention-config :- GitConvention & options] (let [resolved-convention-config (secret/resolve-secrets convention-config GitConvention)] (apply app-configuration-resolved resolved-convention-config options))) (s/defmethod ^:always-validate core-app/group-spec infra/facility [crate-app convention-config :- GitConventionResolved] (let [app-config (app-configuration-resolved convention-config)] (core-app/pallet-group-spec app-config [(config-crate/with-config app-config) serverspec/with-serverspec with-git]))) (def crate-app (core-app/make-dda-crate-app :facility infra/facility :convention-schema GitConvention :convention-schema-resolved GitConventionResolved :default-convention-file "git.edn"))
null
https://raw.githubusercontent.com/DomainDrivenArchitecture/dda-git-crate/3c6ea47931bc4566692f3fbf70ef2ecda1ec750b/main/src/dda/pallet/dda_git_crate/app.clj
clojure
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file "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 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.
Licensed to the Apache Software Foundation ( ASF ) under one to you under the Apache License , Version 2.0 ( the distributed under the License is distributed on an " AS IS " BASIS , (ns dda.pallet.dda-git-crate.app (:require [schema.core :as s] [dda.pallet.commons.secret :as secret] [dda.pallet.core.app :as core-app] [dda.pallet.dda-config-crate.infra :as config-crate] [dda.pallet.dda-serverspec-crate.app :as serverspec] [dda.pallet.dda-git-crate.infra :as infra] [dda.pallet.dda-git-crate.convention :as convention])) (def with-git infra/with-git) (def InfraResult convention/InfraResult) (def GitConvention convention/GitConvention) (def GitConventionResolved (secret/create-resolved-schema GitConvention)) (def GitAppConfig {:group-specific-config {s/Keyword InfraResult}}) (s/defn ^:always-validate app-configuration-resolved :- GitAppConfig [convention-config :- GitConventionResolved & options] (let [{:keys [group-key] :or {group-key infra/facility}} options] {:group-specific-config {group-key (convention/infra-configuration convention-config)}})) (s/defn ^:always-validate app-configuration :- GitAppConfig [convention-config :- GitConvention & options] (let [resolved-convention-config (secret/resolve-secrets convention-config GitConvention)] (apply app-configuration-resolved resolved-convention-config options))) (s/defmethod ^:always-validate core-app/group-spec infra/facility [crate-app convention-config :- GitConventionResolved] (let [app-config (app-configuration-resolved convention-config)] (core-app/pallet-group-spec app-config [(config-crate/with-config app-config) serverspec/with-serverspec with-git]))) (def crate-app (core-app/make-dda-crate-app :facility infra/facility :convention-schema GitConvention :convention-schema-resolved GitConventionResolved :default-convention-file "git.edn"))
d5e240dae4a0dd2dfea0b600b2d119d12f1791417afcfc55a6de4d357bf7e5c4
logicmoo/wam_common_lisp
package.lsp
-*- Mode : LISP ; Syntax : Common - lisp ; Base : 10 ; Lowercase : Yes ; -*- Copyright ( c ) 1990 X Consortium ;;; ;;; 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 X CONSORTIUM 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. ;;; Except as contained in this notice , the name of the X Consortium shall ;;; not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium . ;;; The CLtL way #-clx-ansi-common-lisp (lisp:in-package :xlib :use '(:lisp)) #+(and (or kcl ibcl) (not clx-ansi-common-lisp)) (shadow '( rational )) #+(and lispm (not clx-ansi-common-lisp)) (import '( sys:arglist sys:with-stack-list sys:with-stack-list* )) #+(and Genera (not clx-ansi-common-lisp)) (import '( future-common-lisp:print-unreadable-object future-common-lisp:with-standard-io-syntax sys:array-register zwei:indentation )) #+(and lcl3.0 (not clx-ansi-common-lisp)) (import '( lcl:arglist lcl:dynamic-extent lcl:type-error lucid::type-error-datum lucid::type-error-expected-type )) #+(and excl (not clx-ansi-common-lisp)) (import '( excl::arglist excl::dynamic-extent excl::type-error excl::type-error-datum excl::type-error-expected-type )) #+(and allegro (not clx-ansi-common-lisp)) (import '( excl::without-interrupts )) #-clx-ansi-common-lisp (export '( *version* access-control access-error access-hosts activate-screen-saver add-access-host add-resource add-to-save-set alist alloc-color alloc-color-cells alloc-color-planes alloc-error allow-events angle arc-seq array-index atom-error atom-name bell bit-gravity bitmap bitmap-format bitmap-format-lsb-first-p bitmap-format-p bitmap-format-pad bitmap-format-unit bitmap-image boole-constant boolean card16 card29 card32 card8 card8->char change-active-pointer-grab change-keyboard-control change-keyboard-mapping change-pointer-control change-property char->card8 char-ascent char-attributes char-descent char-left-bearing char-right-bearing char-width character->keysyms character-in-map-p circulate-window-down circulate-window-up clear-area close-display close-down-mode close-font closed-display color color-blue color-green color-p color-red color-rgb colormap colormap-display colormap-equal colormap-error colormap-id colormap-p colormap-plist colormap-visual-info connection-failure convert-selection copy-area copy-colormap-and-free copy-gcontext copy-gcontext-components copy-image copy-plane create-colormap create-cursor create-gcontext create-glyph-cursor create-image create-pixmap create-window cursor cursor-display cursor-equal cursor-error cursor-id cursor-p cursor-plist cut-buffer declare-event decode-core-error default-error-handler default-keysym-index default-keysym-translate define-error define-extension define-gcontext-accessor define-keysym define-keysym-set delete-property delete-resource destroy-subwindows destroy-window device-busy device-event-mask device-event-mask-class discard-current-event discard-font-info display display-after-function display-authorization-data display-authorization-name display-bitmap-format display-byte-order display-default-screen display-display display-error-handler display-finish-output display-force-output display-host display-image-lsb-first-p display-invoke-after-function display-keycode-range display-max-keycode display-max-request-length display-min-keycode display-motion-buffer-size display-nscreens display-p display-pixmap-formats display-plist display-protocol-major-version display-protocol-minor-version display-protocol-version display-release-number display-report-asynchronous-errors display-resource-id-base display-resource-id-mask display-roots display-vendor display-vendor-name display-xdefaults display-xid draw-arc draw-arcs draw-direction draw-glyph draw-glyphs draw-image-glyph draw-image-glyphs draw-line draw-lines draw-point draw-points draw-rectangle draw-rectangles draw-segments drawable drawable-border-width drawable-depth drawable-display drawable-equal drawable-error drawable-height drawable-id drawable-p drawable-plist drawable-root drawable-width drawable-x drawable-y error-key event-case event-cond event-handler event-key event-listen event-mask event-mask-class extension-opcode find-atom font font-all-chars-exist-p font-ascent font-default-char font-descent font-direction font-display font-equal font-error font-id font-max-byte1 font-max-byte2 font-max-char font-min-byte1 font-min-byte2 font-min-char font-name font-p font-path font-plist font-properties font-property fontable force-gcontext-changes free-colormap free-colors free-cursor free-gcontext free-pixmap gcontext gcontext-arc-mode gcontext-background gcontext-cache-p gcontext-cap-style gcontext-clip-mask gcontext-clip-ordering gcontext-clip-x gcontext-clip-y gcontext-dash-offset gcontext-dashes gcontext-display gcontext-equal gcontext-error gcontext-exposures gcontext-fill-rule gcontext-fill-style gcontext-font gcontext-foreground gcontext-function gcontext-id gcontext-join-style gcontext-key gcontext-line-style gcontext-line-width gcontext-p gcontext-plane-mask gcontext-plist gcontext-stipple gcontext-subwindow-mode gcontext-tile gcontext-ts-x gcontext-ts-y get-external-event-code get-image get-property get-raw-image get-resource get-search-resource get-search-table get-standard-colormap get-wm-class global-pointer-position grab-button grab-key grab-keyboard grab-pointer grab-server grab-status icon-sizes iconify-window id-choice-error illegal-request-error image image-blue-mask image-depth image-green-mask image-height image-name image-pixmap image-plist image-red-mask image-width image-x image-x-hot image-x-p image-xy image-xy-bitmap-list image-xy-p image-y-hot image-z image-z-bits-per-pixel image-z-p image-z-pixarray implementation-error input-focus install-colormap installed-colormaps int16 int32 int8 intern-atom invalid-font keyboard-control keyboard-mapping keycode->character keycode->keysym keysym keysym->character keysym->keycodes keysym-in-map-p keysym-set kill-client kill-temporary-clients length-error list-extensions list-font-names list-fonts list-properties lookup-color lookup-error make-color make-event-handlers make-event-keys make-event-mask make-resource-database make-state-keys make-state-mask make-wm-hints make-wm-size-hints map-resource map-subwindows map-window mapping-notify mask16 mask32 match-error max-char-ascent max-char-attributes max-char-descent max-char-left-bearing max-char-right-bearing max-char-width merge-resources min-char-ascent min-char-attributes min-char-descent min-char-left-bearing min-char-right-bearing min-char-width missing-parameter modifier-key modifier-mapping modifier-mask motion-events name-error no-operation open-display open-font pixarray pixel pixmap pixmap-display pixmap-equal pixmap-error pixmap-format pixmap-format-bits-per-pixel pixmap-format-depth pixmap-format-p pixmap-format-scanline-pad pixmap-id pixmap-p pixmap-plist point-seq pointer-control pointer-event-mask pointer-event-mask-class pointer-mapping pointer-position process-event put-image put-raw-image query-best-cursor query-best-stipple query-best-tile query-colors query-extension query-keymap query-pointer query-tree queue-event read-bitmap-file read-resources recolor-cursor rect-seq remove-access-host remove-from-save-set reparent-window repeat-seq reply-length-error reply-timeout request-error reset-screen-saver resource-database resource-database-timestamp resource-error resource-id resource-key rgb-colormaps rgb-val root-resources rotate-cut-buffers rotate-properties screen screen-backing-stores screen-black-pixel screen-default-colormap screen-depths screen-event-mask-at-open screen-height screen-height-in-millimeters screen-max-installed-maps screen-min-installed-maps screen-p screen-plist screen-root screen-root-depth screen-root-visual screen-root-visual-info screen-save-unders-p screen-saver screen-white-pixel screen-width screen-width-in-millimeters seg-seq selection-owner send-event sequence-error set-access-control set-close-down-mode set-input-focus set-modifier-mapping set-pointer-mapping set-screen-saver set-selection-owner set-standard-colormap set-standard-properties set-wm-class set-wm-properties set-wm-resources state-keysym-p state-mask-key store-color store-colors stringable text-extents text-width timestamp transient-for translate-coordinates translate-default translation-function type-error undefine-keysym unexpected-reply ungrab-button ungrab-key ungrab-keyboard ungrab-pointer ungrab-server uninstall-colormap unknown-error unmap-subwindows unmap-window value-error visual-info visual-info-bits-per-rgb visual-info-blue-mask visual-info-class visual-info-colormap-entries visual-info-display visual-info-green-mask visual-info-id visual-info-p visual-info-plist visual-info-red-mask warp-pointer warp-pointer-if-inside warp-pointer-relative warp-pointer-relative-if-inside win-gravity window window-all-event-masks window-background window-backing-pixel window-backing-planes window-backing-store window-bit-gravity window-border window-class window-colormap window-colormap-installed-p window-cursor window-display window-do-not-propagate-mask window-equal window-error window-event-mask window-gravity window-id window-map-state window-override-redirect window-p window-plist window-priority window-save-under window-visual window-visual-info with-display with-event-queue with-gcontext with-server-grabbed with-state withdraw-window wm-client-machine wm-colormap-windows wm-command wm-hints wm-hints-flags wm-hints-icon-mask wm-hints-icon-pixmap wm-hints-icon-window wm-hints-icon-x wm-hints-icon-y wm-hints-initial-state wm-hints-input wm-hints-p wm-hints-window-group wm-icon-name wm-name wm-normal-hints wm-protocols wm-resources wm-size-hints wm-size-hints-base-height wm-size-hints-base-width wm-size-hints-height wm-size-hints-height-inc wm-size-hints-max-aspect wm-size-hints-max-height wm-size-hints-max-width wm-size-hints-min-aspect wm-size-hints-min-height wm-size-hints-min-width wm-size-hints-p wm-size-hints-user-specified-position-p wm-size-hints-user-specified-size-p wm-size-hints-width wm-size-hints-width-inc wm-size-hints-win-gravity wm-size-hints-x wm-size-hints-y wm-zoom-hints write-bitmap-file write-resources xatom )) ;;; The ANSI Common Lisp way #+(and Genera clx-ansi-common-lisp) (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* si:*ansi-common-lisp-readtable*)) #+clx-ansi-common-lisp (common-lisp:in-package :common-lisp-user) #+clx-ansi-common-lisp (defpackage xlib (:use common-lisp) (:size 3000) #+(or kcl ibcl) (:shadow rational) #+allegro (:use cltl1) #+allegro (:import-from excl without-interrupts) #+excl (:import-from excl arglist) #+Genera (:import-from sys array-register) #+Genera (:import-from zwei indentation) #+lcl3.0 (:import-from lcl arglist) #+lispm (:import-from lisp char-bit) #+lispm (:import-from sys arglist with-stack-list with-stack-list*) (:export *version* access-control access-error access-hosts activate-screen-saver add-access-host add-resource add-to-save-set alist alloc-color alloc-color-cells alloc-color-planes alloc-error allow-events angle arc-seq array-index atom-error atom-name bell bit-gravity bitmap bitmap-format bitmap-format-lsb-first-p bitmap-format-p bitmap-format-pad bitmap-format-unit bitmap-image boole-constant boolean card16 card29 card32 card8 card8->char change-active-pointer-grab change-keyboard-control change-keyboard-mapping change-pointer-control change-property char->card8 char-ascent char-attributes char-descent char-left-bearing char-right-bearing char-width character->keysyms character-in-map-p circulate-window-down circulate-window-up clear-area close-display close-down-mode close-font closed-display color color-blue color-green color-p color-red color-rgb colormap colormap-display colormap-equal colormap-error colormap-id colormap-p colormap-plist colormap-visual-info connection-failure convert-selection copy-area copy-colormap-and-free copy-gcontext copy-gcontext-components copy-image copy-plane create-colormap create-cursor create-gcontext create-glyph-cursor create-image create-pixmap create-window cursor cursor-display cursor-equal cursor-error cursor-id cursor-p cursor-plist cut-buffer declare-event decode-core-error default-error-handler default-keysym-index default-keysym-translate define-error define-extension define-gcontext-accessor define-keysym define-keysym-set delete-property delete-resource destroy-subwindows destroy-window device-busy device-event-mask device-event-mask-class discard-current-event discard-font-info display display-after-function display-authorization-data display-authorization-name display-bitmap-format display-byte-order display-default-screen display-display display-error-handler display-finish-output display-force-output display-host display-image-lsb-first-p display-invoke-after-function display-keycode-range display-max-keycode display-max-request-length display-min-keycode display-motion-buffer-size display-nscreens display-p display-pixmap-formats display-plist display-protocol-major-version display-protocol-minor-version display-protocol-version display-release-number display-report-asynchronous-errors display-resource-id-base display-resource-id-mask display-roots display-vendor display-vendor-name display-xdefaults display-xid draw-arc draw-arcs draw-direction draw-glyph draw-glyphs draw-image-glyph draw-image-glyphs draw-line draw-lines draw-point draw-points draw-rectangle draw-rectangles draw-segments drawable drawable-border-width drawable-depth drawable-display drawable-equal drawable-error drawable-height drawable-id drawable-p drawable-plist drawable-root drawable-width drawable-x drawable-y error-key event-case event-cond event-handler event-key event-listen event-mask event-mask-class extension-opcode find-atom font font-all-chars-exist-p font-ascent font-default-char font-descent font-direction font-display font-equal font-error font-id font-max-byte1 font-max-byte2 font-max-char font-min-byte1 font-min-byte2 font-min-char font-name font-p font-path font-plist font-properties font-property fontable force-gcontext-changes free-colormap free-colors free-cursor free-gcontext free-pixmap gcontext gcontext-arc-mode gcontext-background gcontext-cache-p gcontext-cap-style gcontext-clip-mask gcontext-clip-ordering gcontext-clip-x gcontext-clip-y gcontext-dash-offset gcontext-dashes gcontext-display gcontext-equal gcontext-error gcontext-exposures gcontext-fill-rule gcontext-fill-style gcontext-font gcontext-foreground gcontext-function gcontext-id gcontext-join-style gcontext-key gcontext-line-style gcontext-line-width gcontext-p gcontext-plane-mask gcontext-plist gcontext-stipple gcontext-subwindow-mode gcontext-tile gcontext-ts-x gcontext-ts-y get-external-event-code get-image get-property get-raw-image get-resource get-search-resource get-search-table get-standard-colormap get-wm-class global-pointer-position grab-button grab-key grab-keyboard grab-pointer grab-server grab-status icon-sizes iconify-window id-choice-error illegal-request-error image image-blue-mask image-depth image-green-mask image-height image-name image-pixmap image-plist image-red-mask image-width image-x image-x-hot image-x-p image-xy image-xy-bitmap-list image-xy-p image-y-hot image-z image-z-bits-per-pixel image-z-p image-z-pixarray implementation-error input-focus install-colormap installed-colormaps int16 int32 int8 intern-atom invalid-font keyboard-control keyboard-mapping keycode->character keycode->keysym keysym keysym->character keysym->keycodes keysym-in-map-p keysym-set kill-client kill-temporary-clients length-error list-extensions list-font-names list-fonts list-properties lookup-color lookup-error make-color make-event-handlers make-event-keys make-event-mask make-resource-database make-state-keys make-state-mask make-wm-hints make-wm-size-hints map-resource map-subwindows map-window mapping-notify mask16 mask32 match-error max-char-ascent max-char-attributes max-char-descent max-char-left-bearing max-char-right-bearing max-char-width merge-resources min-char-ascent min-char-attributes min-char-descent min-char-left-bearing min-char-right-bearing min-char-width missing-parameter modifier-key modifier-mapping modifier-mask motion-events name-error no-operation open-display open-font pixarray pixel pixmap pixmap-display pixmap-equal pixmap-error pixmap-format pixmap-format-bits-per-pixel pixmap-format-depth pixmap-format-p pixmap-format-scanline-pad pixmap-id pixmap-p pixmap-plist point-seq pointer-control pointer-event-mask pointer-event-mask-class pointer-mapping pointer-position process-event put-image put-raw-image query-best-cursor query-best-stipple query-best-tile query-colors query-extension query-keymap query-pointer query-tree queue-event read-bitmap-file read-resources recolor-cursor rect-seq remove-access-host remove-from-save-set reparent-window repeat-seq reply-length-error reply-timeout request-error reset-screen-saver resource-database resource-database-timestamp resource-error resource-id resource-key rgb-colormaps rgb-val root-resources rotate-cut-buffers rotate-properties screen screen-backing-stores screen-black-pixel screen-default-colormap screen-depths screen-event-mask-at-open screen-height screen-height-in-millimeters screen-max-installed-maps screen-min-installed-maps screen-p screen-plist screen-root screen-root-depth screen-root-visual screen-root-visual-info screen-save-unders-p screen-saver screen-white-pixel screen-width screen-width-in-millimeters seg-seq selection-owner send-event sequence-error set-access-control set-close-down-mode set-input-focus set-modifier-mapping set-pointer-mapping set-screen-saver set-selection-owner set-standard-colormap set-standard-properties set-wm-class set-wm-properties set-wm-resources state-keysym-p state-mask-key store-color store-colors stringable text-extents text-width timestamp transient-for translate-coordinates translate-default translation-function undefine-keysym unexpected-reply ungrab-button ungrab-key ungrab-keyboard ungrab-pointer ungrab-server uninstall-colormap unknown-error unmap-subwindows unmap-window value-error visual-info visual-info-bits-per-rgb visual-info-blue-mask visual-info-class visual-info-colormap-entries visual-info-display visual-info-green-mask visual-info-id visual-info-p visual-info-plist visual-info-red-mask warp-pointer warp-pointer-if-inside warp-pointer-relative warp-pointer-relative-if-inside win-gravity window window-all-event-masks window-background window-backing-pixel window-backing-planes window-backing-store window-bit-gravity window-border window-class window-colormap window-colormap-installed-p window-cursor window-display window-do-not-propagate-mask window-equal window-error window-event-mask window-gravity window-id window-map-state window-override-redirect window-p window-plist window-priority window-save-under window-visual window-visual-info with-display with-event-queue with-gcontext with-server-grabbed with-state withdraw-window wm-client-machine wm-colormap-windows wm-command wm-hints wm-hints-flags wm-hints-icon-mask wm-hints-icon-pixmap wm-hints-icon-window wm-hints-icon-x wm-hints-icon-y wm-hints-initial-state wm-hints-input wm-hints-p wm-hints-window-group wm-icon-name wm-name wm-normal-hints wm-protocols wm-resources wm-size-hints wm-size-hints-base-height wm-size-hints-base-width wm-size-hints-height wm-size-hints-height-inc wm-size-hints-max-aspect wm-size-hints-max-height wm-size-hints-max-width wm-size-hints-min-aspect wm-size-hints-min-height wm-size-hints-min-width wm-size-hints-p wm-size-hints-user-specified-position-p wm-size-hints-user-specified-size-p wm-size-hints-width wm-size-hints-width-inc wm-size-hints-win-gravity wm-size-hints-x wm-size-hints-y wm-zoom-hints write-bitmap-file write-resources xatom))
null
https://raw.githubusercontent.com/logicmoo/wam_common_lisp/4396d9e26b050f68182d65c9a2d5a939557616dd/prolog/wam_cl/src/clx/package.lsp
lisp
Syntax : Common - lisp ; Base : 10 ; Lowercase : Yes ; -*- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: The above copyright notice and this permission notice shall be included OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. not be used in advertising or otherwise to promote the sale, use or The CLtL way The ANSI Common Lisp way
Copyright ( c ) 1990 X Consortium " Software " ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , Except as contained in this notice , the name of the X Consortium shall other dealings in this Software without prior written authorization from the X Consortium . #-clx-ansi-common-lisp (lisp:in-package :xlib :use '(:lisp)) #+(and (or kcl ibcl) (not clx-ansi-common-lisp)) (shadow '( rational )) #+(and lispm (not clx-ansi-common-lisp)) (import '( sys:arglist sys:with-stack-list sys:with-stack-list* )) #+(and Genera (not clx-ansi-common-lisp)) (import '( future-common-lisp:print-unreadable-object future-common-lisp:with-standard-io-syntax sys:array-register zwei:indentation )) #+(and lcl3.0 (not clx-ansi-common-lisp)) (import '( lcl:arglist lcl:dynamic-extent lcl:type-error lucid::type-error-datum lucid::type-error-expected-type )) #+(and excl (not clx-ansi-common-lisp)) (import '( excl::arglist excl::dynamic-extent excl::type-error excl::type-error-datum excl::type-error-expected-type )) #+(and allegro (not clx-ansi-common-lisp)) (import '( excl::without-interrupts )) #-clx-ansi-common-lisp (export '( *version* access-control access-error access-hosts activate-screen-saver add-access-host add-resource add-to-save-set alist alloc-color alloc-color-cells alloc-color-planes alloc-error allow-events angle arc-seq array-index atom-error atom-name bell bit-gravity bitmap bitmap-format bitmap-format-lsb-first-p bitmap-format-p bitmap-format-pad bitmap-format-unit bitmap-image boole-constant boolean card16 card29 card32 card8 card8->char change-active-pointer-grab change-keyboard-control change-keyboard-mapping change-pointer-control change-property char->card8 char-ascent char-attributes char-descent char-left-bearing char-right-bearing char-width character->keysyms character-in-map-p circulate-window-down circulate-window-up clear-area close-display close-down-mode close-font closed-display color color-blue color-green color-p color-red color-rgb colormap colormap-display colormap-equal colormap-error colormap-id colormap-p colormap-plist colormap-visual-info connection-failure convert-selection copy-area copy-colormap-and-free copy-gcontext copy-gcontext-components copy-image copy-plane create-colormap create-cursor create-gcontext create-glyph-cursor create-image create-pixmap create-window cursor cursor-display cursor-equal cursor-error cursor-id cursor-p cursor-plist cut-buffer declare-event decode-core-error default-error-handler default-keysym-index default-keysym-translate define-error define-extension define-gcontext-accessor define-keysym define-keysym-set delete-property delete-resource destroy-subwindows destroy-window device-busy device-event-mask device-event-mask-class discard-current-event discard-font-info display display-after-function display-authorization-data display-authorization-name display-bitmap-format display-byte-order display-default-screen display-display display-error-handler display-finish-output display-force-output display-host display-image-lsb-first-p display-invoke-after-function display-keycode-range display-max-keycode display-max-request-length display-min-keycode display-motion-buffer-size display-nscreens display-p display-pixmap-formats display-plist display-protocol-major-version display-protocol-minor-version display-protocol-version display-release-number display-report-asynchronous-errors display-resource-id-base display-resource-id-mask display-roots display-vendor display-vendor-name display-xdefaults display-xid draw-arc draw-arcs draw-direction draw-glyph draw-glyphs draw-image-glyph draw-image-glyphs draw-line draw-lines draw-point draw-points draw-rectangle draw-rectangles draw-segments drawable drawable-border-width drawable-depth drawable-display drawable-equal drawable-error drawable-height drawable-id drawable-p drawable-plist drawable-root drawable-width drawable-x drawable-y error-key event-case event-cond event-handler event-key event-listen event-mask event-mask-class extension-opcode find-atom font font-all-chars-exist-p font-ascent font-default-char font-descent font-direction font-display font-equal font-error font-id font-max-byte1 font-max-byte2 font-max-char font-min-byte1 font-min-byte2 font-min-char font-name font-p font-path font-plist font-properties font-property fontable force-gcontext-changes free-colormap free-colors free-cursor free-gcontext free-pixmap gcontext gcontext-arc-mode gcontext-background gcontext-cache-p gcontext-cap-style gcontext-clip-mask gcontext-clip-ordering gcontext-clip-x gcontext-clip-y gcontext-dash-offset gcontext-dashes gcontext-display gcontext-equal gcontext-error gcontext-exposures gcontext-fill-rule gcontext-fill-style gcontext-font gcontext-foreground gcontext-function gcontext-id gcontext-join-style gcontext-key gcontext-line-style gcontext-line-width gcontext-p gcontext-plane-mask gcontext-plist gcontext-stipple gcontext-subwindow-mode gcontext-tile gcontext-ts-x gcontext-ts-y get-external-event-code get-image get-property get-raw-image get-resource get-search-resource get-search-table get-standard-colormap get-wm-class global-pointer-position grab-button grab-key grab-keyboard grab-pointer grab-server grab-status icon-sizes iconify-window id-choice-error illegal-request-error image image-blue-mask image-depth image-green-mask image-height image-name image-pixmap image-plist image-red-mask image-width image-x image-x-hot image-x-p image-xy image-xy-bitmap-list image-xy-p image-y-hot image-z image-z-bits-per-pixel image-z-p image-z-pixarray implementation-error input-focus install-colormap installed-colormaps int16 int32 int8 intern-atom invalid-font keyboard-control keyboard-mapping keycode->character keycode->keysym keysym keysym->character keysym->keycodes keysym-in-map-p keysym-set kill-client kill-temporary-clients length-error list-extensions list-font-names list-fonts list-properties lookup-color lookup-error make-color make-event-handlers make-event-keys make-event-mask make-resource-database make-state-keys make-state-mask make-wm-hints make-wm-size-hints map-resource map-subwindows map-window mapping-notify mask16 mask32 match-error max-char-ascent max-char-attributes max-char-descent max-char-left-bearing max-char-right-bearing max-char-width merge-resources min-char-ascent min-char-attributes min-char-descent min-char-left-bearing min-char-right-bearing min-char-width missing-parameter modifier-key modifier-mapping modifier-mask motion-events name-error no-operation open-display open-font pixarray pixel pixmap pixmap-display pixmap-equal pixmap-error pixmap-format pixmap-format-bits-per-pixel pixmap-format-depth pixmap-format-p pixmap-format-scanline-pad pixmap-id pixmap-p pixmap-plist point-seq pointer-control pointer-event-mask pointer-event-mask-class pointer-mapping pointer-position process-event put-image put-raw-image query-best-cursor query-best-stipple query-best-tile query-colors query-extension query-keymap query-pointer query-tree queue-event read-bitmap-file read-resources recolor-cursor rect-seq remove-access-host remove-from-save-set reparent-window repeat-seq reply-length-error reply-timeout request-error reset-screen-saver resource-database resource-database-timestamp resource-error resource-id resource-key rgb-colormaps rgb-val root-resources rotate-cut-buffers rotate-properties screen screen-backing-stores screen-black-pixel screen-default-colormap screen-depths screen-event-mask-at-open screen-height screen-height-in-millimeters screen-max-installed-maps screen-min-installed-maps screen-p screen-plist screen-root screen-root-depth screen-root-visual screen-root-visual-info screen-save-unders-p screen-saver screen-white-pixel screen-width screen-width-in-millimeters seg-seq selection-owner send-event sequence-error set-access-control set-close-down-mode set-input-focus set-modifier-mapping set-pointer-mapping set-screen-saver set-selection-owner set-standard-colormap set-standard-properties set-wm-class set-wm-properties set-wm-resources state-keysym-p state-mask-key store-color store-colors stringable text-extents text-width timestamp transient-for translate-coordinates translate-default translation-function type-error undefine-keysym unexpected-reply ungrab-button ungrab-key ungrab-keyboard ungrab-pointer ungrab-server uninstall-colormap unknown-error unmap-subwindows unmap-window value-error visual-info visual-info-bits-per-rgb visual-info-blue-mask visual-info-class visual-info-colormap-entries visual-info-display visual-info-green-mask visual-info-id visual-info-p visual-info-plist visual-info-red-mask warp-pointer warp-pointer-if-inside warp-pointer-relative warp-pointer-relative-if-inside win-gravity window window-all-event-masks window-background window-backing-pixel window-backing-planes window-backing-store window-bit-gravity window-border window-class window-colormap window-colormap-installed-p window-cursor window-display window-do-not-propagate-mask window-equal window-error window-event-mask window-gravity window-id window-map-state window-override-redirect window-p window-plist window-priority window-save-under window-visual window-visual-info with-display with-event-queue with-gcontext with-server-grabbed with-state withdraw-window wm-client-machine wm-colormap-windows wm-command wm-hints wm-hints-flags wm-hints-icon-mask wm-hints-icon-pixmap wm-hints-icon-window wm-hints-icon-x wm-hints-icon-y wm-hints-initial-state wm-hints-input wm-hints-p wm-hints-window-group wm-icon-name wm-name wm-normal-hints wm-protocols wm-resources wm-size-hints wm-size-hints-base-height wm-size-hints-base-width wm-size-hints-height wm-size-hints-height-inc wm-size-hints-max-aspect wm-size-hints-max-height wm-size-hints-max-width wm-size-hints-min-aspect wm-size-hints-min-height wm-size-hints-min-width wm-size-hints-p wm-size-hints-user-specified-position-p wm-size-hints-user-specified-size-p wm-size-hints-width wm-size-hints-width-inc wm-size-hints-win-gravity wm-size-hints-x wm-size-hints-y wm-zoom-hints write-bitmap-file write-resources xatom )) #+(and Genera clx-ansi-common-lisp) (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* si:*ansi-common-lisp-readtable*)) #+clx-ansi-common-lisp (common-lisp:in-package :common-lisp-user) #+clx-ansi-common-lisp (defpackage xlib (:use common-lisp) (:size 3000) #+(or kcl ibcl) (:shadow rational) #+allegro (:use cltl1) #+allegro (:import-from excl without-interrupts) #+excl (:import-from excl arglist) #+Genera (:import-from sys array-register) #+Genera (:import-from zwei indentation) #+lcl3.0 (:import-from lcl arglist) #+lispm (:import-from lisp char-bit) #+lispm (:import-from sys arglist with-stack-list with-stack-list*) (:export *version* access-control access-error access-hosts activate-screen-saver add-access-host add-resource add-to-save-set alist alloc-color alloc-color-cells alloc-color-planes alloc-error allow-events angle arc-seq array-index atom-error atom-name bell bit-gravity bitmap bitmap-format bitmap-format-lsb-first-p bitmap-format-p bitmap-format-pad bitmap-format-unit bitmap-image boole-constant boolean card16 card29 card32 card8 card8->char change-active-pointer-grab change-keyboard-control change-keyboard-mapping change-pointer-control change-property char->card8 char-ascent char-attributes char-descent char-left-bearing char-right-bearing char-width character->keysyms character-in-map-p circulate-window-down circulate-window-up clear-area close-display close-down-mode close-font closed-display color color-blue color-green color-p color-red color-rgb colormap colormap-display colormap-equal colormap-error colormap-id colormap-p colormap-plist colormap-visual-info connection-failure convert-selection copy-area copy-colormap-and-free copy-gcontext copy-gcontext-components copy-image copy-plane create-colormap create-cursor create-gcontext create-glyph-cursor create-image create-pixmap create-window cursor cursor-display cursor-equal cursor-error cursor-id cursor-p cursor-plist cut-buffer declare-event decode-core-error default-error-handler default-keysym-index default-keysym-translate define-error define-extension define-gcontext-accessor define-keysym define-keysym-set delete-property delete-resource destroy-subwindows destroy-window device-busy device-event-mask device-event-mask-class discard-current-event discard-font-info display display-after-function display-authorization-data display-authorization-name display-bitmap-format display-byte-order display-default-screen display-display display-error-handler display-finish-output display-force-output display-host display-image-lsb-first-p display-invoke-after-function display-keycode-range display-max-keycode display-max-request-length display-min-keycode display-motion-buffer-size display-nscreens display-p display-pixmap-formats display-plist display-protocol-major-version display-protocol-minor-version display-protocol-version display-release-number display-report-asynchronous-errors display-resource-id-base display-resource-id-mask display-roots display-vendor display-vendor-name display-xdefaults display-xid draw-arc draw-arcs draw-direction draw-glyph draw-glyphs draw-image-glyph draw-image-glyphs draw-line draw-lines draw-point draw-points draw-rectangle draw-rectangles draw-segments drawable drawable-border-width drawable-depth drawable-display drawable-equal drawable-error drawable-height drawable-id drawable-p drawable-plist drawable-root drawable-width drawable-x drawable-y error-key event-case event-cond event-handler event-key event-listen event-mask event-mask-class extension-opcode find-atom font font-all-chars-exist-p font-ascent font-default-char font-descent font-direction font-display font-equal font-error font-id font-max-byte1 font-max-byte2 font-max-char font-min-byte1 font-min-byte2 font-min-char font-name font-p font-path font-plist font-properties font-property fontable force-gcontext-changes free-colormap free-colors free-cursor free-gcontext free-pixmap gcontext gcontext-arc-mode gcontext-background gcontext-cache-p gcontext-cap-style gcontext-clip-mask gcontext-clip-ordering gcontext-clip-x gcontext-clip-y gcontext-dash-offset gcontext-dashes gcontext-display gcontext-equal gcontext-error gcontext-exposures gcontext-fill-rule gcontext-fill-style gcontext-font gcontext-foreground gcontext-function gcontext-id gcontext-join-style gcontext-key gcontext-line-style gcontext-line-width gcontext-p gcontext-plane-mask gcontext-plist gcontext-stipple gcontext-subwindow-mode gcontext-tile gcontext-ts-x gcontext-ts-y get-external-event-code get-image get-property get-raw-image get-resource get-search-resource get-search-table get-standard-colormap get-wm-class global-pointer-position grab-button grab-key grab-keyboard grab-pointer grab-server grab-status icon-sizes iconify-window id-choice-error illegal-request-error image image-blue-mask image-depth image-green-mask image-height image-name image-pixmap image-plist image-red-mask image-width image-x image-x-hot image-x-p image-xy image-xy-bitmap-list image-xy-p image-y-hot image-z image-z-bits-per-pixel image-z-p image-z-pixarray implementation-error input-focus install-colormap installed-colormaps int16 int32 int8 intern-atom invalid-font keyboard-control keyboard-mapping keycode->character keycode->keysym keysym keysym->character keysym->keycodes keysym-in-map-p keysym-set kill-client kill-temporary-clients length-error list-extensions list-font-names list-fonts list-properties lookup-color lookup-error make-color make-event-handlers make-event-keys make-event-mask make-resource-database make-state-keys make-state-mask make-wm-hints make-wm-size-hints map-resource map-subwindows map-window mapping-notify mask16 mask32 match-error max-char-ascent max-char-attributes max-char-descent max-char-left-bearing max-char-right-bearing max-char-width merge-resources min-char-ascent min-char-attributes min-char-descent min-char-left-bearing min-char-right-bearing min-char-width missing-parameter modifier-key modifier-mapping modifier-mask motion-events name-error no-operation open-display open-font pixarray pixel pixmap pixmap-display pixmap-equal pixmap-error pixmap-format pixmap-format-bits-per-pixel pixmap-format-depth pixmap-format-p pixmap-format-scanline-pad pixmap-id pixmap-p pixmap-plist point-seq pointer-control pointer-event-mask pointer-event-mask-class pointer-mapping pointer-position process-event put-image put-raw-image query-best-cursor query-best-stipple query-best-tile query-colors query-extension query-keymap query-pointer query-tree queue-event read-bitmap-file read-resources recolor-cursor rect-seq remove-access-host remove-from-save-set reparent-window repeat-seq reply-length-error reply-timeout request-error reset-screen-saver resource-database resource-database-timestamp resource-error resource-id resource-key rgb-colormaps rgb-val root-resources rotate-cut-buffers rotate-properties screen screen-backing-stores screen-black-pixel screen-default-colormap screen-depths screen-event-mask-at-open screen-height screen-height-in-millimeters screen-max-installed-maps screen-min-installed-maps screen-p screen-plist screen-root screen-root-depth screen-root-visual screen-root-visual-info screen-save-unders-p screen-saver screen-white-pixel screen-width screen-width-in-millimeters seg-seq selection-owner send-event sequence-error set-access-control set-close-down-mode set-input-focus set-modifier-mapping set-pointer-mapping set-screen-saver set-selection-owner set-standard-colormap set-standard-properties set-wm-class set-wm-properties set-wm-resources state-keysym-p state-mask-key store-color store-colors stringable text-extents text-width timestamp transient-for translate-coordinates translate-default translation-function undefine-keysym unexpected-reply ungrab-button ungrab-key ungrab-keyboard ungrab-pointer ungrab-server uninstall-colormap unknown-error unmap-subwindows unmap-window value-error visual-info visual-info-bits-per-rgb visual-info-blue-mask visual-info-class visual-info-colormap-entries visual-info-display visual-info-green-mask visual-info-id visual-info-p visual-info-plist visual-info-red-mask warp-pointer warp-pointer-if-inside warp-pointer-relative warp-pointer-relative-if-inside win-gravity window window-all-event-masks window-background window-backing-pixel window-backing-planes window-backing-store window-bit-gravity window-border window-class window-colormap window-colormap-installed-p window-cursor window-display window-do-not-propagate-mask window-equal window-error window-event-mask window-gravity window-id window-map-state window-override-redirect window-p window-plist window-priority window-save-under window-visual window-visual-info with-display with-event-queue with-gcontext with-server-grabbed with-state withdraw-window wm-client-machine wm-colormap-windows wm-command wm-hints wm-hints-flags wm-hints-icon-mask wm-hints-icon-pixmap wm-hints-icon-window wm-hints-icon-x wm-hints-icon-y wm-hints-initial-state wm-hints-input wm-hints-p wm-hints-window-group wm-icon-name wm-name wm-normal-hints wm-protocols wm-resources wm-size-hints wm-size-hints-base-height wm-size-hints-base-width wm-size-hints-height wm-size-hints-height-inc wm-size-hints-max-aspect wm-size-hints-max-height wm-size-hints-max-width wm-size-hints-min-aspect wm-size-hints-min-height wm-size-hints-min-width wm-size-hints-p wm-size-hints-user-specified-position-p wm-size-hints-user-specified-size-p wm-size-hints-width wm-size-hints-width-inc wm-size-hints-win-gravity wm-size-hints-x wm-size-hints-y wm-zoom-hints write-bitmap-file write-resources xatom))
a133cac353979c6f74eb26334eba0737acfb1880e51279269dfefbd30f28d630
why-not-try-calmer/feedo
Mongo.hs
# LANGUAGE RecordWildCards # module Mongo (saveToLog, HasMongo (..), checkDbMapper) where import Control.Concurrent (writeChan) import Control.Exception import Control.Monad (unless, when) import Control.Monad.IO.Class (MonadIO (liftIO)) import Crypto.Hash (SHA256 (SHA256), hashWith) import Data.Aeson (eitherDecodeStrict') import qualified Data.ByteString.Char8 as B import Data.Functor ((<&>)) import qualified Data.HashMap.Strict as HMS import qualified Data.List as List import Data.Maybe (fromJust, fromMaybe, isNothing) import Data.Ord import qualified Data.Set as S import qualified Data.Text as T import Data.Time (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) import Database.MongoDB import qualified Database.MongoDB as M import qualified Database.MongoDB.Transport.Tls as Tls import GHC.IORef (atomicModifyIORef', readIORef) import Network.HTTP.Req (BsResponse, responseBody) import Requests (fetchApi) import Text.Read (readMaybe) import TgramOutJson (ChatId) import Types import Utils (defaultChatSettings) Interface class MongoDoc v where readDoc :: Document -> v writeDoc :: v -> Document checks :: v -> Bool instance MongoDoc SubChat where readDoc = bsonToChat writeDoc = chatToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc Feed where readDoc = bsonToFeed writeDoc = feedToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc Item where readDoc = bsonToItem writeDoc = itemToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc Digest where readDoc = bsonToDigest writeDoc = digestToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc LogItem where readDoc = bsonToLog writeDoc = logToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc AdminUser where readDoc = bsonToAdmin writeDoc = adminToBson checks v = v == (readDoc . writeDoc $ v) class HasMongo m where evalDb :: AppConfig -> DbAction -> m DbRes loginDb :: MongoCreds -> Pipe -> m (Either DbError Pipe) setupDb :: String -> m (Either DbError (Pipe, MongoCreds)) fetch :: APIKey -> APIReq -> m (Either T.Text BsResponse) instance MonadIO m => HasMongo (App m) where evalDb = evalMongo loginDb = authWith setupDb = setupMongo fetch = fetchApi instance HasMongo IO where evalDb = evalMongo loginDb = authWith setupDb = setupMongo fetch = fetchApi Connection primaryOrSecondary :: ReplicaSet -> IO (Maybe Pipe) primaryOrSecondary rep = try (primary rep) >>= \case Left (SomeException err) -> do print $ "Failed to acquire primary replica, reason:" ++ show err ++ ". Moving to second." try (secondaryOk rep) >>= \case Left (SomeException _) -> pure Nothing Right pipe -> pure $ Just pipe Right pipe -> pure $ Just pipe authWith :: MonadIO m => MongoCreds -> Pipe -> m (Either DbError Pipe) authWith creds pipe = do isAuth <- access pipe master "admin" $ auth (user_name creds) (password creds) if isAuth then liftIO (putStrLn "Authenticated now.") >> pure (Right pipe) else liftIO (putStrLn "Authentication failed.") >> pure (Left PipeNotAcquired) initConnectionMongo :: MonadIO m => MongoCreds -> m (Either DbError Pipe) initConnectionMongo creds@MongoCredsTls{..} = liftIO $ do pipe <- Tls.connect host_name db_port verdict <- isClosed pipe if verdict then pure . Left $ PipeNotAcquired else loginDb creds pipe initConnectionMongo creds@MongoCredsReplicaTls{..} = liftIO $ do repset <- openReplicaSetTLS (replicateset, hosts) mb_pipe <- primaryOrSecondary repset maybe (pure . Left $ PipeNotAcquired) (\p -> isClosed p >>= \v -> if v then pure . Left $ PipeNotAcquired else loginDb creds p) mb_pipe initConnectionMongo creds@MongoCredsReplicaSrv{..} = liftIO $ do repset <- openReplicaSetSRV' host_name mb_pipe <- primaryOrSecondary repset maybe (pure . Left $ PipeNotAcquired) (\p -> isClosed p >>= \v -> if v then pure . Left $ PipeNotAcquired else loginDb creds p) mb_pipe setupMongo :: MonadIO m => String -> m (Either DbError (Pipe, MongoCreds)) setupMongo connection_string = let [h, db, user, passwd] = T.splitOn ":" . T.pack $ connection_string creds = MongoCredsReplicaSrv (T.unpack h) db user passwd in initConnectionMongo creds >>= \case Left err -> pure $ Left err Right pipe -> pure $ Right (pipe, creds) {- Evaluation -} withMongo :: (HasMongo m, MonadIO m) => AppConfig -> Action IO a -> m (Either () a) withMongo AppConfig{..} action = liftIO $ do pipe <- acquire attempt <- attemptWith pipe case attempt of Left (ConnectionFailure failure) -> do alert failure initConnectionMongo mongo_creds >>= \case Left e -> alertGiveUp $ "Giving up after first_pass failed and re-authentication failed on: " ++ show e Right fresh_pipe -> finishWith fresh_pipe Left err -> alertGiveUp err Right r -> pure $ Right r where ref = snd connectors acquire = readIORef ref finishWith fresh_pipe = do atomicModifyIORef' ref (const (fresh_pipe, ())) attemptGiveup fresh_pipe attemptWith pipe = try $ runMongo pipe action attemptGiveup pipe = attemptWith pipe >>= \case Left (SomeException e) -> alertGiveUp $ "Giving up after successful re-authentication and despite replacing the broken Pipe, on: " ++ show e Right r -> pure $ Right r runMongo :: MonadIO m => Pipe -> Action m a -> m a runMongo pipe = access pipe master (database_name mongo_creds) alertGiveUp err = alert err >> pure (Left ()) alert err = liftIO $ writeChan postjobs . JobTgAlert $ "withMongo failed with " `T.append` (T.pack . show $ err) `T.append` " If the connector timed out, one retry will be carried out, using the same Connection." {- Actions -} buildSearchQuery :: S.Set T.Text -> Maybe UTCTime -> [Document] buildSearchQuery ws mb_last_time = let search = [ "$search" =: [ "index" =: ("default" :: T.Text) , "text" =: [ "query" =: S.toList ws , "fuzzy" =: ([] :: Document) , "path" =: (["i_desc", "i_title"] :: [T.Text]) ] ] ] match t = ["$match" =: ["i_pubdate" =: ["$gt" =: (t :: UTCTime)]]] project = [ "$project" =: [ "_id" =: (0 :: Int) , "i_title" =: (1 :: Int) , "i_feed_link" =: (1 :: Int) , "i_link" =: (1 :: Int) , "i_pubdate" =: (1 :: Int) , "score" =: ["$meta" =: ("searchScore" :: T.Text)] ] ] in case mb_last_time of Nothing -> [search, project] Just t -> [search, match t, project] evalMongo :: (HasMongo m, MonadIO m) => AppConfig -> DbAction -> m DbRes evalMongo env (DbAskForLogin uid cid) = do -- FIX ME -- -- This should be adapted to the Data API let f = " { ' admin_uid ' : ' " ` T.append ` uid ` T.append ` " ' , } " q = FindOne " admins " " feedfarer " " Cluster0 " f fetchApi ( api_key env ) q > > = \case Left _ - > pure . Right resp - > let b = responseBody resp : : APIReq in if null $ let f = "{'admin_uid': '" `T.append` uid `T.append` "', }" q = FindOne "admins" "feedfarer" "Cluster0" f fetchApi (api_key env) q >>= \case Left _ -> pure . DbErr $ FaultyToken Right resp -> let b = responseBody resp :: APIReq in if null $ -} let selector = ["admin_uid" =: uid, "admin_chatid" =: cid] get_doc = findOne $ select selector "admins" write_doc h n = insert_ "admins" . writeDoc $ AdminUser uid h cid n delete_doc = deleteOne $ select selector "admins" in liftIO getCurrentTime >>= \now -> withMongo env get_doc >>= \case Left _ -> pure . DbErr $ FaultyToken Right Nothing -> do h <- mkSafeHash _ <- withMongo env (write_doc h now) pure $ DbToken h Right (Just doc) -> do when (diffUTCTime now (admin_created . readDoc $ doc) > 2592000) (withMongo env delete_doc >> pure ()) pure $ DbToken . admin_token . readDoc $ doc where mkSafeHash = liftIO getSystemTime <&> T.pack . show . hashWith SHA256 . B.pack . show evalMongo env (CheckLogin h) = let r = findOne (select ["admin_token" =: h] "admins") del = deleteOne (select ["admin_token" =: h] "admins") in liftIO getCurrentTime >>= \now -> withMongo env r >>= \case Left _ -> nope Right Nothing -> nope Right (Just doc) -> if diffUTCTime now (admin_created . readDoc $ doc) < 2592000 then pure $ DbLoggedIn (admin_chatid $ readDoc doc) else withMongo env del >> nope where nope = pure . DbErr $ FaultyToken evalMongo env (ArchiveItems feeds) = let selector = foldMap (map (\i -> (["i_link" =: i_link i], writeDoc i, [Upsert])) . f_items) feeds action = withMongo env $ updateAll "items" selector in action >>= \case Left _ -> pure . DbErr $ FailedToUpdate "ArchiveItems" "Action failed during connection." Right res -> if failed res then pure . DbErr $ FailedToUpdate "ArchiveItems failed to write feeds" (T.pack . show $ res) else pure DbOk evalMongo env (DbSearch keywords scope last_time) = let action = aggregate "items" $ buildSearchQuery keywords last_time in withMongo env action >>= \case Left _ -> pure . DbErr $ FailedToUpdate mempty "DbSearch failed" Right res -> let mkSearchRes doc = let title = M.lookup "i_title" doc link = M.lookup "i_link" doc pubdate = M.lookup "i_pubdate" doc :: Maybe UTCTime f_link = M.lookup "i_feed_link" doc score = M.lookup "score" doc :: Maybe Double nothings = [isNothing title, isNothing link, isNothing pubdate, isNothing f_link, isNothing score] in if or nothings then Nothing else Just $ SearchResult { sr_title = fromJust title , sr_link = fromJust link , sr_pubdate = fromJust pubdate , sr_feedlink = fromJust f_link , sr_score = fromJust score } sort_limit = take 10 . List.sortOn (Down . sr_score) rescind = filter (\sr -> sr_feedlink sr `elem` scope) payload r = if null scope then sort_limit r else sort_limit . rescind $ r in case mapM mkSearchRes res of Nothing -> pure $ DbSearchRes S.empty [] Just r -> pure . DbSearchRes keywords . payload $ r evalMongo env (DeleteChat cid) = let action = withMongo env $ deleteOne (select ["sub_chatid" =: cid] "chats") in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate mempty "DeleteChat failed" Right _ -> pure DbOk evalMongo env GetAllChats = let q = APIReq CChats Nothing in fetchApi (api_key env) q >>= \case Left err -> pure . DbErr $ FailedToUpdate "GetAllChats failed" err Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIChats of Left err -> pure $ DbErr . NotFound $ T.pack err Right docs -> pure . DbChats . chats_documents $ docs evalMongo env GetAllFeeds = let q = APIReq CFeeds Nothing in fetchApi (api_key env) q >>= \case Left err -> pure . DbErr $ FailedToUpdate "GetAllFeeds failed" err Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIFeeds of Left err -> pure $ DbErr . NotFound $ T.pack err Right docs -> pure . DbFeeds . map fromAPIFeed . feeds_documents $ docs evalMongo env (GetPages cid mid) = let f = APIFilter Nothing (Just mid) Nothing q = APIReq CPages (Just f) in fetchApi (api_key env) q >>= \case Left _ -> pure $ DbNoPage cid mid Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIPages of Left err -> pure $ DbErr . NotFound $ T.pack err Right docs -> case List.find (\p -> pages_chat_id p == cid) $ pages_documents docs of Nothing -> pure $ DbErr . NotFound $ mempty Just found -> pure $ DbPages (pages_pages found) (pages_url found) let action = withMongo env $ findOne ( select [ " chat_id " = : cid , " message_id " = : mid ] " pages " ) in action > > = \case Right ( Just doc ) - > case M.lookup " pages " doc of Just pages - > pure $ DbPages pages ( M.lookup " url " doc ) _ - > pure $ DbNoPage cid mid _ - > pure $ DbNoPage cid mid let action = withMongo env $ findOne (select ["chat_id" =: cid, "message_id" =: mid] "pages") in action >>= \case Right (Just doc) -> case M.lookup "pages" doc of Just pages -> pure $ DbPages pages (M.lookup "url" doc) _ -> pure $ DbNoPage cid mid _ -> pure $ DbNoPage cid mid -} evalMongo env (IncReads links) = let action l = withMongo env $ modify (select ["f_link" =: l] "feeds") ["$inc" =: ["f_reads" =: (1 :: Int)]] in mapM_ action links >> pure DbOk evalMongo env (InsertPages cid mid pages mb_link) = let base_payload = ["chat_id" =: cid, "message_id" =: mid, "pages" =: pages] payload = case mb_link of Nothing -> base_payload Just l -> base_payload ++ ["url" =: l] action = withMongo env $ insert "pages" payload in action >>= \case Left () -> pure . DbErr $ FailedToInsertPage _ -> pure DbOk evalMongo env (PruneOld t) = let del_items = deleteAll "items" [(["i_pubdate" =: ["$lt" =: (t :: UTCTime)]], [])] del_digests = deleteAll "digests" [(["digest_created" =: ["$lt" =: t]], [])] in withMongo env (del_items >> del_digests) >> pure DbOk evalMongo env (ReadDigest _id) = case readMaybe . T.unpack $ _id :: Maybe ObjectId of Nothing -> pure DbBadOID oid -> let f = APIFilter Nothing Nothing oid q = APIReq CDigests (Just f) in fetchApi (api_key env) q >>= \case Left err -> pure . DbErr $ FailedToUpdate "digest" err Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIDigest of Left err -> pure $ DbErr . NotFound $ T.pack err Right doc -> pure . DbDigest $ digest_document doc action s = findOne $ select s " digests " in case mkSelector of Left err - > pure $ DbErr err Right selector - > withMongo env ( action selector ) > > = \case Left ( ) - > pure . DbErr $ FailedToUpdate " digest " " Read digest refused to read from the database . " Right doc - > maybe ( pure DbNoDigest ) ( pure . . readDoc ) doc action s = findOne $ select s "digests" in case mkSelector of Left err -> pure $ DbErr err Right selector -> withMongo env (action selector) >>= \case Left () -> pure . DbErr $ FailedToUpdate "digest" "Read digest refused to read from the database." Right doc -> maybe (pure DbNoDigest) (pure . DbDigest . readDoc) doc -} evalMongo env (UpsertChat chat) = let action = withMongo env $ upsert (select ["sub_chatid" =: sub_chatid chat] "chats") $ writeDoc chat in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate (T.pack . show . sub_chatid $ chat) "UpsertChat failed" Right _ -> pure DbOk evalMongo env (UpsertChats chatshmap) = let chats = HMS.elems chatshmap selector = map (\c -> (["sub_chatid" =: sub_chatid c], writeDoc c, [Upsert])) chats action = withMongo env $ updateAll "chats" selector in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate (T.intercalate ", " (map (T.pack . show . sub_chatid) chats)) "UpsertChats failed" Right res -> if failed res then pure . DbErr $ FailedToUpdate "Failed to write feeds" (T.pack . show $ res) else pure DbOk evalMongo env (UpsertFeeds feeds) = let selector = map (\f -> (["f_link" =: f_link f], writeDoc f, [Upsert])) feeds action = withMongo env $ updateAll "feeds" selector in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate (T.intercalate ", " (map f_link feeds)) mempty Right res -> if failed res then pure . DbErr $ FailedToUpdate "Failed to write feeds" (T.pack . show $ res) else pure DbOk evalMongo env (View flinks start end) = let query = find (select ["i_feed_link" =: ["$in" =: (flinks :: [T.Text])], "i_pubdate" =: ["$gt" =: (start :: UTCTime), "$lt" =: (end :: UTCTime)]] "items") >>= rest in withMongo env query >>= \case Left _ -> pure $ DbErr FailedToLoadFeeds Right is -> pure $ DbView (map readDoc is) start end evalMongo env (WriteDigest digest) = let action = insert "digests" $ writeDoc digest in withMongo env action >>= \case Left _ -> pure . DbErr $ FailedToUpdate "digest" "HasMongo refused to insert digest items" Right res -> case res of ObjId _id -> pure $ DbDigestId . T.pack . show $ _id _ -> pure . DbErr $ FailedToProduceValidId {- Items -} itemToBson :: Item -> Document itemToBson i = [ "i_title" =: i_title i , "i_desc" =: i_desc i , "i_feed_link" =: i_feed_link i , "i_link" =: i_link i , "i_pubdate" =: i_pubdate i ] bsonToItem :: Document -> Item bsonToItem doc = Item (fromJust $ M.lookup "i_title" doc) (fromJust $ M.lookup "i_desc" doc) (fromJust $ M.lookup "i_link" doc) (fromJust $ M.lookup "i_feed_link" doc) (fromJust $ M.lookup "i_pubdate" doc) {- Feeds -} feedToBson :: Feed -> Document feedToBson Feed{..} = [ "f_avg_interval" =: (realToFrac <$> f_avg_interval :: Maybe NominalDiffTime) , "f_desc" =: f_desc , "f_items" =: map writeDoc (take 30 . List.sortOn (Down . i_pubdate) $ f_items) , "f_last_refresh" =: f_last_refresh , "f_link" =: f_link , "f_reads" =: f_reads , "f_title" =: f_title , "f_type" =: (T.pack . show $ f_type) ] bsonToFeed :: Document -> Feed bsonToFeed doc = let raw_items = fromJust $ M.lookup "f_items" doc items = map readDoc raw_items in Feed { f_avg_interval = M.lookup "f_avg_interval" doc , f_desc = fromJust $ M.lookup "f_desc" doc , f_items = items , f_last_refresh = M.lookup "f_last_refresh" doc , f_link = fromJust $ M.lookup "f_link" doc , f_reads = fromJust $ M.lookup "f_reads" doc , f_title = fromJust $ M.lookup "f_title" doc , f_type = if fromJust (M.lookup "f_type" doc) == (T.pack . show $ Rss) then Rss else Atom } {- Chats, Settings -} bsonToChat :: Document -> SubChat bsonToChat doc = let feeds_links = fromJust $ M.lookup "sub_feeds_links" doc :: [T.Text] linked_to_chats = M.lookup "sub_linked_to_chats" doc :: Maybe ChatId settings_doc = fromJust $ M.lookup "sub_settings" doc :: Document feeds_settings_docs = Settings { settings_word_matches = WordMatches (maybe S.empty S.fromList $ M.lookup "settings_blacklist" settings_doc) (maybe S.empty S.fromList $ M.lookup "settings_searchset" settings_doc) (maybe S.empty S.fromList $ M.lookup "settings_only_search_results" settings_doc) , settings_digest_interval = let every = M.lookup "settings_digest_every_secs" settings_doc :: Maybe NominalDiffTime hm_docs = M.lookup "settings_digest_at" settings_doc :: Maybe [Document] adjust n | n < 6 && n > 0 = n * 10 | otherwise = n extract mds = case mds of Nothing -> [] Just docs -> foldr ( \d acc -> let h = M.lookup "hour" d :: Maybe Int m = M.lookup "minute" d :: Maybe Int in case sequence [h, m] of Nothing -> [] Just hm -> acc ++ [(head hm, adjust $ last hm)] ) [] docs in DigestInterval every (if null $ extract hm_docs then Nothing else Just $ extract hm_docs) , settings_digest_collapse = fromMaybe (settings_digest_collapse defaultChatSettings) $ M.lookup "settings_digest_collapse" settings_doc , settings_digest_size = fromMaybe (settings_digest_size defaultChatSettings) $ M.lookup "settings_digest_size" settings_doc :: Int , settings_digest_title = fromMaybe (settings_digest_title defaultChatSettings) $ M.lookup "settings_digest_title" settings_doc , settings_digest_start = fromMaybe (settings_digest_start defaultChatSettings) $ M.lookup "settings_digest_start" settings_doc :: Maybe UTCTime , settings_paused = Just True == M.lookup "settings_paused" settings_doc , settings_disable_web_view = fromMaybe (settings_disable_web_view defaultChatSettings) $ M.lookup "settings_disable_web_view" settings_doc , settings_pin = fromMaybe (settings_pin defaultChatSettings) $ M.lookup "settings_pin" settings_doc , settings_share_link = fromMaybe (settings_share_link defaultChatSettings) $ M.lookup "settings_share_link" settings_doc , settings_follow = fromMaybe (settings_follow defaultChatSettings) $ M.lookup "settings_follow" settings_doc , settings_pagination = fromMaybe (settings_pagination defaultChatSettings) $ M.lookup "settings_pagination" settings_doc , settings_digest_no_collapse = maybe S.empty S.fromList $ M.lookup "settings_digest_no_collapse" settings_doc } in SubChat { sub_chatid = fromJust $ M.lookup "sub_chatid" doc , sub_last_digest = M.lookup "sub_last_digest" doc , sub_next_digest = M.lookup "sub_next_digest" doc , sub_feeds_links = S.fromList feeds_links , sub_linked_to = linked_to_chats , sub_settings = feeds_settings_docs } chatToBson :: SubChat -> Document chatToBson (SubChat chat_id last_digest next_digest flinks linked_to settings) = let blacklist = S.toList . match_blacklist . settings_word_matches $ settings searchset = S.toList . match_searchset . settings_word_matches $ settings only_search_results = S.toList . match_only_search_results . settings_word_matches $ settings settings' = [ "settings_blacklist" =: blacklist , "settings_digest_collapse" =: settings_digest_collapse settings , "settings_disable_web_view" =: settings_disable_web_view settings , "settings_digest_size" =: settings_digest_size settings , "settings_digest_title" =: settings_digest_title settings , "settings_digest_start" =: settings_digest_start settings , "settings_follow" =: settings_follow settings , "settings_only_search_results" =: only_search_results , "settings_paused" =: settings_paused settings , "settings_pin" =: settings_pin settings , "settings_searchset" =: searchset , "settings_share_link" =: settings_share_link settings , "settings_pagination" =: settings_pagination settings , "settings_digest_no_collapse" =: S.toList (settings_digest_no_collapse settings) ] with_secs = maybe [] (\secs -> ["settings_digest_every_secs" =: secs]) (digest_every_secs . settings_digest_interval $ settings) with_at = maybe [] (\hm -> ["settings_digest_at" =: map (\(h, m) -> ["hour" =: h, "minute" =: m]) hm]) (digest_at . settings_digest_interval $ settings) in [ "sub_chatid" =: chat_id , "sub_last_digest" =: last_digest , "sub_next_digest" =: next_digest , "sub_feeds_links" =: S.toList flinks , "sub_linked_to_chats" =: linked_to , "sub_settings" =: settings' ++ with_secs ++ with_at ] Digests bsonToDigest :: Document -> Digest bsonToDigest doc = let items = map readDoc . fromJust $ M.lookup "digest_items" doc created = fromJust $ M.lookup "digest_created" doc _id = M.lookup "_id" doc :: Maybe T.Text flinks = fromJust $ M.lookup "digest_flinks" doc ftitles = fromMaybe [] $ M.lookup "digest_ftitles" doc in Digest _id created items flinks ftitles digestToBson :: Digest -> Document digestToBson Digest{..} = [ "digest_created" =: (digest_created :: UTCTime) , "digest_items" =: map writeDoc digest_items , "digest_flinks" =: digest_links , "digest_ftitles" =: digest_titles ] {- Logs -} bsonToLog :: Document -> LogItem bsonToLog doc = case M.lookup "log_refresh" doc of Just log_refresh -> LogPerf { log_refresh = fromMaybe 0 log_refresh , log_message = fromMaybe mempty $ M.lookup "log_message" doc , log_at = fromMaybe undefined $ M.lookup "log_at" doc , log_sending_notif = fromMaybe 0 $ M.lookup "log_sending_notif" doc , log_updating = fromMaybe 0 $ M.lookup "log_update" doc , log_total = fromMaybe 0 $ M.lookup "log_total" doc } Nothing -> case M.lookup "log_discarded_duplicates" doc of Just docs -> LogMissing { log_feeds_with_missing = docs , log_at = fromMaybe undefined $ M.lookup "log_at" doc , log_total_missed = fromMaybe 0 $ M.lookup "log_total_dicarded" doc } Nothing -> case M.lookup "log_updated_feeds" doc of Just updated_feeds -> LogDigest { log_updated_feeds = updated_feeds , log_not_updated = fromMaybe mempty $ M.lookup "log_not_updated" doc , log_at = fromMaybe undefined $ M.lookup "log_at" doc } Nothing -> case M.lookup "long_due_chats_with_no_digest" doc of Just l -> LogNoDigest { log_due_chats_with_no_digest = l , log_at = fromMaybe undefined $ M.lookup "log_at" doc } Nothing -> undefined logToBson :: LogItem -> Document logToBson LogPerf{..} = [ "log_message" =: log_message , "log_at" =: log_at , "log_refresh" =: log_refresh , "log_sending_notif" =: log_sending_notif , "log_update" =: log_updating , "log_total" =: log_total , "log_type" =: ("performance" :: T.Text) ] logToBson (LogMissing missing total t) = [ "log_discarded_duplicates" =: missing , "log_total_discarded" =: total , "log_at" =: t , "log_type" =: ("discarded_duplicates" :: T.Text) ] logToBson (LogNoDigest chat_ids t) = [ "log_at" =: t , "log_due_chats_with_no_digest" =: chat_ids , "log_type" =: ("chats_without_digest" :: T.Text) ] logToBson (LogDiscardedToRefreshRecipes to_refresh discarded recipes) = [ "log_refresh" =: to_refresh , "log_discarded" =: discarded , "log_recipes" =: recipes ] logToBson (LogDigest updated not_updated t) = [ "log_at" =: t , "log_updated_feeds" =: updated , "log_not_updated" =: not_updated , "log_type" =: ("feeds_updated_or_not" :: T.Text) ] logToBson (LogCouldNotArchive feeds t err) = let flinks = map f_link feeds items = foldMap f_items feeds in ["log_at " =: t, "log_error" =: err, "log_flinks" =: flinks, "log_items" =: map (T.pack . show) items] saveToLog :: (HasMongo m, MonadIO m) => AppConfig -> LogItem -> m () saveToLog env logitem = withMongo env (insert "logs" $ writeDoc logitem) >> pure () cleanLogs : : ( HasMongo m , MonadIO m ) = > AppConfig - > m ( Either ( ) ) cleanLogs env = do now < - liftIO getCurrentTime res < - withMongo env $ do void $ deleteAll " logs " [ ( [ " log_at " = : [ " $ lt " = : ( one_week_from now : : UTCTime ) ] ] , [ ] ) ] res_delete < - deleteAll " logs " [ ( [ " log_at " = : [ " $ exists " = : False ] ] , [ ] ) ] res_found < - find ( select [ " log_at " = : [ " $ exists " = : False ] ] " logs " ) > > = rest pure ( res_delete , res_found ) case res of Left _ - > pure . Left $ " Failed to cleanLogs " Right ( del , found ) - > if failed del then pure . Left . show $ del else if not $ null found then pure . Left . show $ found else pure $ Right ( ) where one_week_from = addUTCTime ( -604800 ) collectLogStats : : ( HasMongo m , MonadIO m ) = > AppConfig - > m T.Text collectLogStats env = do res < - withMongo env $ do logs < - rest = < < find ( select [ " log_total " = : [ " $ gte " = : ( 0.5 : : Double ) ] ] " logs " ) counts < - rest = < < find ( select [ ] " feeds"){sort = [ " f_reads " = : ( -1 : : Int ) ] , limit = 100 } pure ( logs , counts ) case res of Left _ - > pure " Failed to collectLogStats " Right ( docs_logs , feeds_docs ) - > let logs = List.sortOn log_at . filter ( not . T.null . log_message ) . map readDoc $ docs_logs feeds_counts = map ( \d - > let f = readDoc d in ( f_link f , T.pack . show $ f_reads f ) ) feeds_docs in pure $ foldl ' ( \acc ( ! k , ! v ) - > acc ` T.append ` " " ` T.append ` k ` T.append ` " : " ` T.append ` v ) T.empty feeds_counts ` T.append ` mkStats logs where mkStats logs = let values = let ( a , b , c , d ) = foldl ' ( \(!r , ! s , ! u , ! t ) ( LogPerf _ _ r ' s ' u ' t ' ) - > ( r ' + r , s + s ' , u + u ' , t + t ' ) ) ( 0 , 0 , 0 , 0 ) logs in [ a , b , c , d ] keys = [ " refreshing " , " sending " , " updating " , " total " ] in showLength logs ` T.append ` " logs . Averages for : " ` T.append ` T.intercalate " , " ( zipWith ( \k v - > k ` T.append ` " : " ` T.append ` showAvgLength v logs ) keys values ) showLength = T.pack . show . length showAvgLength a l = T.pack . show $ fromIntegral a ` div ` length l cleanLogs :: (HasMongo m, MonadIO m) => AppConfig -> m (Either String ()) cleanLogs env = do now <- liftIO getCurrentTime res <- withMongo env $ do void $ deleteAll "logs" [(["log_at" =: ["$lt" =: (one_week_from now :: UTCTime)]], [])] res_delete <- deleteAll "logs" [(["log_at" =: ["$exists" =: False]], [])] res_found <- find (select ["log_at" =: ["$exists" =: False]] "logs") >>= rest pure (res_delete, res_found) case res of Left _ -> pure . Left $ "Failed to cleanLogs" Right (del, found) -> if failed del then pure . Left . show $ del else if not $ null found then pure . Left . show $ found else pure $ Right () where one_week_from = addUTCTime (-604800) collectLogStats :: (HasMongo m, MonadIO m) => AppConfig -> m T.Text collectLogStats env = do res <- withMongo env $ do logs <- rest =<< find (select ["log_total" =: ["$gte" =: (0.5 :: Double)]] "logs") counts <- rest =<< find (select [] "feeds"){sort = ["f_reads" =: (-1 :: Int)], limit = 100} pure (logs, counts) case res of Left _ -> pure "Failed to collectLogStats" Right (docs_logs, feeds_docs) -> let logs = List.sortOn log_at . filter (not . T.null . log_message) . map readDoc $ docs_logs feeds_counts = map (\d -> let f = readDoc d in (f_link f, T.pack . show $ f_reads f)) feeds_docs in pure $ foldl' (\acc (!k, !v) -> acc `T.append` " " `T.append` k `T.append` ": " `T.append` v) T.empty feeds_counts `T.append` mkStats logs where mkStats logs = let values = let (a, b, c, d) = foldl' ( \(!r, !s, !u, !t) (LogPerf _ _ r' s' u' t') -> (r' + r, s + s', u + u', t + t') ) (0, 0, 0, 0) logs in [a, b, c, d] keys = ["refreshing", "sending", "updating", "total"] in showLength logs `T.append` " logs. Averages for: " `T.append` T.intercalate ", " ( zipWith ( \k v -> k `T.append` ": " `T.append` showAvgLength v logs ) keys values ) showLength = T.pack . show . length showAvgLength a l = T.pack . show $ fromIntegral a `div` length l -} {- Admins -} bsonToAdmin :: Document -> AdminUser bsonToAdmin doc = let uid = fromJust $ M.lookup "admin_uid" doc token = fromJust $ M.lookup "admin_token" doc cid = fromJust $ M.lookup "admin_chatid" doc created = fromJust $ M.lookup "admin_created" doc in AdminUser uid token cid created adminToBson :: AdminUser -> Document adminToBson AdminUser{..} = [ "admin_uid" =: admin_uid , "admin_chatid" =: admin_chatid , "admin_token" =: admin_token , "admin_created" =: admin_created ] {- Pages -} bsonToPage : : Document - > Maybe PageOne bsonToPage doc = let cid = M.lookup " chat_id " doc mid = M.lookup " message_id " doc pages = M.lookup " pages " doc one = head < $ > pages n = length < $ > pages mb_url = M.lookup " url " doc in PageOne < $ > one < * > cid < * > mid < * > n < * > mb_url bsonToPage :: Document -> Maybe PageOne bsonToPage doc = let cid = M.lookup "chat_id" doc mid = M.lookup "message_id" doc pages = M.lookup "pages" doc one = head <$> pages n = length <$> pages mb_url = M.lookup "url" doc in PageOne <$> one <*> cid <*> mid <*> n <*> mb_url -} {- Cleanup -} purgeCollections : : ( HasMongo m , MonadIO m ) = > AppConfig - > [ T.Text ] - > m ( Either ( ) ) purgeCollections _ [ ] = pure . Left $ " Empty list of collection names ! " purgeCollections env colls = let action = withMongo env $ mapM ( ` deleteAll ` [ ( [ ] , [ ] ) ] ) colls in action > > = \case Left _ - > pure . Left $ " Failed to purgeCollections . " Right res - > if any failed res then pure . Left $ " Failed to purge collections " + + show colls else pure $ Right ( ) { - Mapping purgeCollections :: (HasMongo m, MonadIO m) => AppConfig -> [T.Text] -> m (Either String ()) purgeCollections _ [] = pure . Left $ "Empty list of collection names!" purgeCollections env colls = let action = withMongo env $ mapM (`deleteAll` [([], [])]) colls in action >>= \case Left _ -> pure . Left $ "Failed to purgeCollections." Right res -> if any failed res then pure . Left $ "Failed to purge collections " ++ show colls else pure $ Right () {- Mapping -} remapChats :: (MonadIO m, HasMongo m) => AppConfig -> SubChats -> m (Either String ()) remapChats env chats = let selector = map (\c -> (["sub_chatid" =: sub_chatid c], writeDoc c, [Upsert])) $ HMS.elems chats action = updateAll "chats" selector in withMongo env action >>= \case Left _ -> pure $ Left "Failed"; Right _ -> pure $ Right () -} checkDbMapper :: MonadIO m => m () checkDbMapper = do now <- liftIO getCurrentTime let item = Item mempty mempty mempty mempty now digest_interval = DigestInterval (Just 0) (Just [(1, 20)]) word_matches = WordMatches S.empty S.empty (S.fromList ["1", "2", "3"]) settings = Settings (Just 3) digest_interval 0 Nothing "title" True False True True False False word_matches mempty chat = SubChat 0 (Just now) (Just now) S.empty Nothing settings feed = Feed Rss "1" "2" "3" [item] (Just 0) (Just now) 0 log' = LogPerf mempty now 0 0 0 0 digest = Digest Nothing now [item] [mempty] [mempty] admin_user = AdminUser 123 "just user" 456 now equalities = [ ("item", checks item) , ("digest", checks digest) , ("feed", checks feed) , ("chat", checks chat) , ("log", checks log') , ("admin", checks admin_user) ] :: [(T.Text, Bool)] unless (all snd equalities) . liftIO $ do print digest print (readDoc . writeDoc $ digest :: Digest) throwIO . userError $ "Mapper failed. " ++ (show . filter (not . snd) $ equalities)
null
https://raw.githubusercontent.com/why-not-try-calmer/feedo/15d9bbc0551894a1d3d04cd4711e4e956d213554/src/Mongo.hs
haskell
Evaluation Actions FIX ME -- This should be adapted to the Data API Items Feeds Chats, Settings Logs Admins Pages Cleanup Mapping
# LANGUAGE RecordWildCards # module Mongo (saveToLog, HasMongo (..), checkDbMapper) where import Control.Concurrent (writeChan) import Control.Exception import Control.Monad (unless, when) import Control.Monad.IO.Class (MonadIO (liftIO)) import Crypto.Hash (SHA256 (SHA256), hashWith) import Data.Aeson (eitherDecodeStrict') import qualified Data.ByteString.Char8 as B import Data.Functor ((<&>)) import qualified Data.HashMap.Strict as HMS import qualified Data.List as List import Data.Maybe (fromJust, fromMaybe, isNothing) import Data.Ord import qualified Data.Set as S import qualified Data.Text as T import Data.Time (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime) import Data.Time.Clock.System (getSystemTime) import Database.MongoDB import qualified Database.MongoDB as M import qualified Database.MongoDB.Transport.Tls as Tls import GHC.IORef (atomicModifyIORef', readIORef) import Network.HTTP.Req (BsResponse, responseBody) import Requests (fetchApi) import Text.Read (readMaybe) import TgramOutJson (ChatId) import Types import Utils (defaultChatSettings) Interface class MongoDoc v where readDoc :: Document -> v writeDoc :: v -> Document checks :: v -> Bool instance MongoDoc SubChat where readDoc = bsonToChat writeDoc = chatToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc Feed where readDoc = bsonToFeed writeDoc = feedToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc Item where readDoc = bsonToItem writeDoc = itemToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc Digest where readDoc = bsonToDigest writeDoc = digestToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc LogItem where readDoc = bsonToLog writeDoc = logToBson checks v = v == (readDoc . writeDoc $ v) instance MongoDoc AdminUser where readDoc = bsonToAdmin writeDoc = adminToBson checks v = v == (readDoc . writeDoc $ v) class HasMongo m where evalDb :: AppConfig -> DbAction -> m DbRes loginDb :: MongoCreds -> Pipe -> m (Either DbError Pipe) setupDb :: String -> m (Either DbError (Pipe, MongoCreds)) fetch :: APIKey -> APIReq -> m (Either T.Text BsResponse) instance MonadIO m => HasMongo (App m) where evalDb = evalMongo loginDb = authWith setupDb = setupMongo fetch = fetchApi instance HasMongo IO where evalDb = evalMongo loginDb = authWith setupDb = setupMongo fetch = fetchApi Connection primaryOrSecondary :: ReplicaSet -> IO (Maybe Pipe) primaryOrSecondary rep = try (primary rep) >>= \case Left (SomeException err) -> do print $ "Failed to acquire primary replica, reason:" ++ show err ++ ". Moving to second." try (secondaryOk rep) >>= \case Left (SomeException _) -> pure Nothing Right pipe -> pure $ Just pipe Right pipe -> pure $ Just pipe authWith :: MonadIO m => MongoCreds -> Pipe -> m (Either DbError Pipe) authWith creds pipe = do isAuth <- access pipe master "admin" $ auth (user_name creds) (password creds) if isAuth then liftIO (putStrLn "Authenticated now.") >> pure (Right pipe) else liftIO (putStrLn "Authentication failed.") >> pure (Left PipeNotAcquired) initConnectionMongo :: MonadIO m => MongoCreds -> m (Either DbError Pipe) initConnectionMongo creds@MongoCredsTls{..} = liftIO $ do pipe <- Tls.connect host_name db_port verdict <- isClosed pipe if verdict then pure . Left $ PipeNotAcquired else loginDb creds pipe initConnectionMongo creds@MongoCredsReplicaTls{..} = liftIO $ do repset <- openReplicaSetTLS (replicateset, hosts) mb_pipe <- primaryOrSecondary repset maybe (pure . Left $ PipeNotAcquired) (\p -> isClosed p >>= \v -> if v then pure . Left $ PipeNotAcquired else loginDb creds p) mb_pipe initConnectionMongo creds@MongoCredsReplicaSrv{..} = liftIO $ do repset <- openReplicaSetSRV' host_name mb_pipe <- primaryOrSecondary repset maybe (pure . Left $ PipeNotAcquired) (\p -> isClosed p >>= \v -> if v then pure . Left $ PipeNotAcquired else loginDb creds p) mb_pipe setupMongo :: MonadIO m => String -> m (Either DbError (Pipe, MongoCreds)) setupMongo connection_string = let [h, db, user, passwd] = T.splitOn ":" . T.pack $ connection_string creds = MongoCredsReplicaSrv (T.unpack h) db user passwd in initConnectionMongo creds >>= \case Left err -> pure $ Left err Right pipe -> pure $ Right (pipe, creds) withMongo :: (HasMongo m, MonadIO m) => AppConfig -> Action IO a -> m (Either () a) withMongo AppConfig{..} action = liftIO $ do pipe <- acquire attempt <- attemptWith pipe case attempt of Left (ConnectionFailure failure) -> do alert failure initConnectionMongo mongo_creds >>= \case Left e -> alertGiveUp $ "Giving up after first_pass failed and re-authentication failed on: " ++ show e Right fresh_pipe -> finishWith fresh_pipe Left err -> alertGiveUp err Right r -> pure $ Right r where ref = snd connectors acquire = readIORef ref finishWith fresh_pipe = do atomicModifyIORef' ref (const (fresh_pipe, ())) attemptGiveup fresh_pipe attemptWith pipe = try $ runMongo pipe action attemptGiveup pipe = attemptWith pipe >>= \case Left (SomeException e) -> alertGiveUp $ "Giving up after successful re-authentication and despite replacing the broken Pipe, on: " ++ show e Right r -> pure $ Right r runMongo :: MonadIO m => Pipe -> Action m a -> m a runMongo pipe = access pipe master (database_name mongo_creds) alertGiveUp err = alert err >> pure (Left ()) alert err = liftIO $ writeChan postjobs . JobTgAlert $ "withMongo failed with " `T.append` (T.pack . show $ err) `T.append` " If the connector timed out, one retry will be carried out, using the same Connection." buildSearchQuery :: S.Set T.Text -> Maybe UTCTime -> [Document] buildSearchQuery ws mb_last_time = let search = [ "$search" =: [ "index" =: ("default" :: T.Text) , "text" =: [ "query" =: S.toList ws , "fuzzy" =: ([] :: Document) , "path" =: (["i_desc", "i_title"] :: [T.Text]) ] ] ] match t = ["$match" =: ["i_pubdate" =: ["$gt" =: (t :: UTCTime)]]] project = [ "$project" =: [ "_id" =: (0 :: Int) , "i_title" =: (1 :: Int) , "i_feed_link" =: (1 :: Int) , "i_link" =: (1 :: Int) , "i_pubdate" =: (1 :: Int) , "score" =: ["$meta" =: ("searchScore" :: T.Text)] ] ] in case mb_last_time of Nothing -> [search, project] Just t -> [search, match t, project] evalMongo :: (HasMongo m, MonadIO m) => AppConfig -> DbAction -> m DbRes evalMongo env (DbAskForLogin uid cid) = do let f = " { ' admin_uid ' : ' " ` T.append ` uid ` T.append ` " ' , } " q = FindOne " admins " " feedfarer " " Cluster0 " f fetchApi ( api_key env ) q > > = \case Left _ - > pure . Right resp - > let b = responseBody resp : : APIReq in if null $ let f = "{'admin_uid': '" `T.append` uid `T.append` "', }" q = FindOne "admins" "feedfarer" "Cluster0" f fetchApi (api_key env) q >>= \case Left _ -> pure . DbErr $ FaultyToken Right resp -> let b = responseBody resp :: APIReq in if null $ -} let selector = ["admin_uid" =: uid, "admin_chatid" =: cid] get_doc = findOne $ select selector "admins" write_doc h n = insert_ "admins" . writeDoc $ AdminUser uid h cid n delete_doc = deleteOne $ select selector "admins" in liftIO getCurrentTime >>= \now -> withMongo env get_doc >>= \case Left _ -> pure . DbErr $ FaultyToken Right Nothing -> do h <- mkSafeHash _ <- withMongo env (write_doc h now) pure $ DbToken h Right (Just doc) -> do when (diffUTCTime now (admin_created . readDoc $ doc) > 2592000) (withMongo env delete_doc >> pure ()) pure $ DbToken . admin_token . readDoc $ doc where mkSafeHash = liftIO getSystemTime <&> T.pack . show . hashWith SHA256 . B.pack . show evalMongo env (CheckLogin h) = let r = findOne (select ["admin_token" =: h] "admins") del = deleteOne (select ["admin_token" =: h] "admins") in liftIO getCurrentTime >>= \now -> withMongo env r >>= \case Left _ -> nope Right Nothing -> nope Right (Just doc) -> if diffUTCTime now (admin_created . readDoc $ doc) < 2592000 then pure $ DbLoggedIn (admin_chatid $ readDoc doc) else withMongo env del >> nope where nope = pure . DbErr $ FaultyToken evalMongo env (ArchiveItems feeds) = let selector = foldMap (map (\i -> (["i_link" =: i_link i], writeDoc i, [Upsert])) . f_items) feeds action = withMongo env $ updateAll "items" selector in action >>= \case Left _ -> pure . DbErr $ FailedToUpdate "ArchiveItems" "Action failed during connection." Right res -> if failed res then pure . DbErr $ FailedToUpdate "ArchiveItems failed to write feeds" (T.pack . show $ res) else pure DbOk evalMongo env (DbSearch keywords scope last_time) = let action = aggregate "items" $ buildSearchQuery keywords last_time in withMongo env action >>= \case Left _ -> pure . DbErr $ FailedToUpdate mempty "DbSearch failed" Right res -> let mkSearchRes doc = let title = M.lookup "i_title" doc link = M.lookup "i_link" doc pubdate = M.lookup "i_pubdate" doc :: Maybe UTCTime f_link = M.lookup "i_feed_link" doc score = M.lookup "score" doc :: Maybe Double nothings = [isNothing title, isNothing link, isNothing pubdate, isNothing f_link, isNothing score] in if or nothings then Nothing else Just $ SearchResult { sr_title = fromJust title , sr_link = fromJust link , sr_pubdate = fromJust pubdate , sr_feedlink = fromJust f_link , sr_score = fromJust score } sort_limit = take 10 . List.sortOn (Down . sr_score) rescind = filter (\sr -> sr_feedlink sr `elem` scope) payload r = if null scope then sort_limit r else sort_limit . rescind $ r in case mapM mkSearchRes res of Nothing -> pure $ DbSearchRes S.empty [] Just r -> pure . DbSearchRes keywords . payload $ r evalMongo env (DeleteChat cid) = let action = withMongo env $ deleteOne (select ["sub_chatid" =: cid] "chats") in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate mempty "DeleteChat failed" Right _ -> pure DbOk evalMongo env GetAllChats = let q = APIReq CChats Nothing in fetchApi (api_key env) q >>= \case Left err -> pure . DbErr $ FailedToUpdate "GetAllChats failed" err Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIChats of Left err -> pure $ DbErr . NotFound $ T.pack err Right docs -> pure . DbChats . chats_documents $ docs evalMongo env GetAllFeeds = let q = APIReq CFeeds Nothing in fetchApi (api_key env) q >>= \case Left err -> pure . DbErr $ FailedToUpdate "GetAllFeeds failed" err Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIFeeds of Left err -> pure $ DbErr . NotFound $ T.pack err Right docs -> pure . DbFeeds . map fromAPIFeed . feeds_documents $ docs evalMongo env (GetPages cid mid) = let f = APIFilter Nothing (Just mid) Nothing q = APIReq CPages (Just f) in fetchApi (api_key env) q >>= \case Left _ -> pure $ DbNoPage cid mid Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIPages of Left err -> pure $ DbErr . NotFound $ T.pack err Right docs -> case List.find (\p -> pages_chat_id p == cid) $ pages_documents docs of Nothing -> pure $ DbErr . NotFound $ mempty Just found -> pure $ DbPages (pages_pages found) (pages_url found) let action = withMongo env $ findOne ( select [ " chat_id " = : cid , " message_id " = : mid ] " pages " ) in action > > = \case Right ( Just doc ) - > case M.lookup " pages " doc of Just pages - > pure $ DbPages pages ( M.lookup " url " doc ) _ - > pure $ DbNoPage cid mid _ - > pure $ DbNoPage cid mid let action = withMongo env $ findOne (select ["chat_id" =: cid, "message_id" =: mid] "pages") in action >>= \case Right (Just doc) -> case M.lookup "pages" doc of Just pages -> pure $ DbPages pages (M.lookup "url" doc) _ -> pure $ DbNoPage cid mid _ -> pure $ DbNoPage cid mid -} evalMongo env (IncReads links) = let action l = withMongo env $ modify (select ["f_link" =: l] "feeds") ["$inc" =: ["f_reads" =: (1 :: Int)]] in mapM_ action links >> pure DbOk evalMongo env (InsertPages cid mid pages mb_link) = let base_payload = ["chat_id" =: cid, "message_id" =: mid, "pages" =: pages] payload = case mb_link of Nothing -> base_payload Just l -> base_payload ++ ["url" =: l] action = withMongo env $ insert "pages" payload in action >>= \case Left () -> pure . DbErr $ FailedToInsertPage _ -> pure DbOk evalMongo env (PruneOld t) = let del_items = deleteAll "items" [(["i_pubdate" =: ["$lt" =: (t :: UTCTime)]], [])] del_digests = deleteAll "digests" [(["digest_created" =: ["$lt" =: t]], [])] in withMongo env (del_items >> del_digests) >> pure DbOk evalMongo env (ReadDigest _id) = case readMaybe . T.unpack $ _id :: Maybe ObjectId of Nothing -> pure DbBadOID oid -> let f = APIFilter Nothing Nothing oid q = APIReq CDigests (Just f) in fetchApi (api_key env) q >>= \case Left err -> pure . DbErr $ FailedToUpdate "digest" err Right resp -> let b = responseBody resp in case eitherDecodeStrict' b :: Either String APIDigest of Left err -> pure $ DbErr . NotFound $ T.pack err Right doc -> pure . DbDigest $ digest_document doc action s = findOne $ select s " digests " in case mkSelector of Left err - > pure $ DbErr err Right selector - > withMongo env ( action selector ) > > = \case Left ( ) - > pure . DbErr $ FailedToUpdate " digest " " Read digest refused to read from the database . " Right doc - > maybe ( pure DbNoDigest ) ( pure . . readDoc ) doc action s = findOne $ select s "digests" in case mkSelector of Left err -> pure $ DbErr err Right selector -> withMongo env (action selector) >>= \case Left () -> pure . DbErr $ FailedToUpdate "digest" "Read digest refused to read from the database." Right doc -> maybe (pure DbNoDigest) (pure . DbDigest . readDoc) doc -} evalMongo env (UpsertChat chat) = let action = withMongo env $ upsert (select ["sub_chatid" =: sub_chatid chat] "chats") $ writeDoc chat in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate (T.pack . show . sub_chatid $ chat) "UpsertChat failed" Right _ -> pure DbOk evalMongo env (UpsertChats chatshmap) = let chats = HMS.elems chatshmap selector = map (\c -> (["sub_chatid" =: sub_chatid c], writeDoc c, [Upsert])) chats action = withMongo env $ updateAll "chats" selector in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate (T.intercalate ", " (map (T.pack . show . sub_chatid) chats)) "UpsertChats failed" Right res -> if failed res then pure . DbErr $ FailedToUpdate "Failed to write feeds" (T.pack . show $ res) else pure DbOk evalMongo env (UpsertFeeds feeds) = let selector = map (\f -> (["f_link" =: f_link f], writeDoc f, [Upsert])) feeds action = withMongo env $ updateAll "feeds" selector in action >>= \case Left _ -> pure $ DbErr $ FailedToUpdate (T.intercalate ", " (map f_link feeds)) mempty Right res -> if failed res then pure . DbErr $ FailedToUpdate "Failed to write feeds" (T.pack . show $ res) else pure DbOk evalMongo env (View flinks start end) = let query = find (select ["i_feed_link" =: ["$in" =: (flinks :: [T.Text])], "i_pubdate" =: ["$gt" =: (start :: UTCTime), "$lt" =: (end :: UTCTime)]] "items") >>= rest in withMongo env query >>= \case Left _ -> pure $ DbErr FailedToLoadFeeds Right is -> pure $ DbView (map readDoc is) start end evalMongo env (WriteDigest digest) = let action = insert "digests" $ writeDoc digest in withMongo env action >>= \case Left _ -> pure . DbErr $ FailedToUpdate "digest" "HasMongo refused to insert digest items" Right res -> case res of ObjId _id -> pure $ DbDigestId . T.pack . show $ _id _ -> pure . DbErr $ FailedToProduceValidId itemToBson :: Item -> Document itemToBson i = [ "i_title" =: i_title i , "i_desc" =: i_desc i , "i_feed_link" =: i_feed_link i , "i_link" =: i_link i , "i_pubdate" =: i_pubdate i ] bsonToItem :: Document -> Item bsonToItem doc = Item (fromJust $ M.lookup "i_title" doc) (fromJust $ M.lookup "i_desc" doc) (fromJust $ M.lookup "i_link" doc) (fromJust $ M.lookup "i_feed_link" doc) (fromJust $ M.lookup "i_pubdate" doc) feedToBson :: Feed -> Document feedToBson Feed{..} = [ "f_avg_interval" =: (realToFrac <$> f_avg_interval :: Maybe NominalDiffTime) , "f_desc" =: f_desc , "f_items" =: map writeDoc (take 30 . List.sortOn (Down . i_pubdate) $ f_items) , "f_last_refresh" =: f_last_refresh , "f_link" =: f_link , "f_reads" =: f_reads , "f_title" =: f_title , "f_type" =: (T.pack . show $ f_type) ] bsonToFeed :: Document -> Feed bsonToFeed doc = let raw_items = fromJust $ M.lookup "f_items" doc items = map readDoc raw_items in Feed { f_avg_interval = M.lookup "f_avg_interval" doc , f_desc = fromJust $ M.lookup "f_desc" doc , f_items = items , f_last_refresh = M.lookup "f_last_refresh" doc , f_link = fromJust $ M.lookup "f_link" doc , f_reads = fromJust $ M.lookup "f_reads" doc , f_title = fromJust $ M.lookup "f_title" doc , f_type = if fromJust (M.lookup "f_type" doc) == (T.pack . show $ Rss) then Rss else Atom } bsonToChat :: Document -> SubChat bsonToChat doc = let feeds_links = fromJust $ M.lookup "sub_feeds_links" doc :: [T.Text] linked_to_chats = M.lookup "sub_linked_to_chats" doc :: Maybe ChatId settings_doc = fromJust $ M.lookup "sub_settings" doc :: Document feeds_settings_docs = Settings { settings_word_matches = WordMatches (maybe S.empty S.fromList $ M.lookup "settings_blacklist" settings_doc) (maybe S.empty S.fromList $ M.lookup "settings_searchset" settings_doc) (maybe S.empty S.fromList $ M.lookup "settings_only_search_results" settings_doc) , settings_digest_interval = let every = M.lookup "settings_digest_every_secs" settings_doc :: Maybe NominalDiffTime hm_docs = M.lookup "settings_digest_at" settings_doc :: Maybe [Document] adjust n | n < 6 && n > 0 = n * 10 | otherwise = n extract mds = case mds of Nothing -> [] Just docs -> foldr ( \d acc -> let h = M.lookup "hour" d :: Maybe Int m = M.lookup "minute" d :: Maybe Int in case sequence [h, m] of Nothing -> [] Just hm -> acc ++ [(head hm, adjust $ last hm)] ) [] docs in DigestInterval every (if null $ extract hm_docs then Nothing else Just $ extract hm_docs) , settings_digest_collapse = fromMaybe (settings_digest_collapse defaultChatSettings) $ M.lookup "settings_digest_collapse" settings_doc , settings_digest_size = fromMaybe (settings_digest_size defaultChatSettings) $ M.lookup "settings_digest_size" settings_doc :: Int , settings_digest_title = fromMaybe (settings_digest_title defaultChatSettings) $ M.lookup "settings_digest_title" settings_doc , settings_digest_start = fromMaybe (settings_digest_start defaultChatSettings) $ M.lookup "settings_digest_start" settings_doc :: Maybe UTCTime , settings_paused = Just True == M.lookup "settings_paused" settings_doc , settings_disable_web_view = fromMaybe (settings_disable_web_view defaultChatSettings) $ M.lookup "settings_disable_web_view" settings_doc , settings_pin = fromMaybe (settings_pin defaultChatSettings) $ M.lookup "settings_pin" settings_doc , settings_share_link = fromMaybe (settings_share_link defaultChatSettings) $ M.lookup "settings_share_link" settings_doc , settings_follow = fromMaybe (settings_follow defaultChatSettings) $ M.lookup "settings_follow" settings_doc , settings_pagination = fromMaybe (settings_pagination defaultChatSettings) $ M.lookup "settings_pagination" settings_doc , settings_digest_no_collapse = maybe S.empty S.fromList $ M.lookup "settings_digest_no_collapse" settings_doc } in SubChat { sub_chatid = fromJust $ M.lookup "sub_chatid" doc , sub_last_digest = M.lookup "sub_last_digest" doc , sub_next_digest = M.lookup "sub_next_digest" doc , sub_feeds_links = S.fromList feeds_links , sub_linked_to = linked_to_chats , sub_settings = feeds_settings_docs } chatToBson :: SubChat -> Document chatToBson (SubChat chat_id last_digest next_digest flinks linked_to settings) = let blacklist = S.toList . match_blacklist . settings_word_matches $ settings searchset = S.toList . match_searchset . settings_word_matches $ settings only_search_results = S.toList . match_only_search_results . settings_word_matches $ settings settings' = [ "settings_blacklist" =: blacklist , "settings_digest_collapse" =: settings_digest_collapse settings , "settings_disable_web_view" =: settings_disable_web_view settings , "settings_digest_size" =: settings_digest_size settings , "settings_digest_title" =: settings_digest_title settings , "settings_digest_start" =: settings_digest_start settings , "settings_follow" =: settings_follow settings , "settings_only_search_results" =: only_search_results , "settings_paused" =: settings_paused settings , "settings_pin" =: settings_pin settings , "settings_searchset" =: searchset , "settings_share_link" =: settings_share_link settings , "settings_pagination" =: settings_pagination settings , "settings_digest_no_collapse" =: S.toList (settings_digest_no_collapse settings) ] with_secs = maybe [] (\secs -> ["settings_digest_every_secs" =: secs]) (digest_every_secs . settings_digest_interval $ settings) with_at = maybe [] (\hm -> ["settings_digest_at" =: map (\(h, m) -> ["hour" =: h, "minute" =: m]) hm]) (digest_at . settings_digest_interval $ settings) in [ "sub_chatid" =: chat_id , "sub_last_digest" =: last_digest , "sub_next_digest" =: next_digest , "sub_feeds_links" =: S.toList flinks , "sub_linked_to_chats" =: linked_to , "sub_settings" =: settings' ++ with_secs ++ with_at ] Digests bsonToDigest :: Document -> Digest bsonToDigest doc = let items = map readDoc . fromJust $ M.lookup "digest_items" doc created = fromJust $ M.lookup "digest_created" doc _id = M.lookup "_id" doc :: Maybe T.Text flinks = fromJust $ M.lookup "digest_flinks" doc ftitles = fromMaybe [] $ M.lookup "digest_ftitles" doc in Digest _id created items flinks ftitles digestToBson :: Digest -> Document digestToBson Digest{..} = [ "digest_created" =: (digest_created :: UTCTime) , "digest_items" =: map writeDoc digest_items , "digest_flinks" =: digest_links , "digest_ftitles" =: digest_titles ] bsonToLog :: Document -> LogItem bsonToLog doc = case M.lookup "log_refresh" doc of Just log_refresh -> LogPerf { log_refresh = fromMaybe 0 log_refresh , log_message = fromMaybe mempty $ M.lookup "log_message" doc , log_at = fromMaybe undefined $ M.lookup "log_at" doc , log_sending_notif = fromMaybe 0 $ M.lookup "log_sending_notif" doc , log_updating = fromMaybe 0 $ M.lookup "log_update" doc , log_total = fromMaybe 0 $ M.lookup "log_total" doc } Nothing -> case M.lookup "log_discarded_duplicates" doc of Just docs -> LogMissing { log_feeds_with_missing = docs , log_at = fromMaybe undefined $ M.lookup "log_at" doc , log_total_missed = fromMaybe 0 $ M.lookup "log_total_dicarded" doc } Nothing -> case M.lookup "log_updated_feeds" doc of Just updated_feeds -> LogDigest { log_updated_feeds = updated_feeds , log_not_updated = fromMaybe mempty $ M.lookup "log_not_updated" doc , log_at = fromMaybe undefined $ M.lookup "log_at" doc } Nothing -> case M.lookup "long_due_chats_with_no_digest" doc of Just l -> LogNoDigest { log_due_chats_with_no_digest = l , log_at = fromMaybe undefined $ M.lookup "log_at" doc } Nothing -> undefined logToBson :: LogItem -> Document logToBson LogPerf{..} = [ "log_message" =: log_message , "log_at" =: log_at , "log_refresh" =: log_refresh , "log_sending_notif" =: log_sending_notif , "log_update" =: log_updating , "log_total" =: log_total , "log_type" =: ("performance" :: T.Text) ] logToBson (LogMissing missing total t) = [ "log_discarded_duplicates" =: missing , "log_total_discarded" =: total , "log_at" =: t , "log_type" =: ("discarded_duplicates" :: T.Text) ] logToBson (LogNoDigest chat_ids t) = [ "log_at" =: t , "log_due_chats_with_no_digest" =: chat_ids , "log_type" =: ("chats_without_digest" :: T.Text) ] logToBson (LogDiscardedToRefreshRecipes to_refresh discarded recipes) = [ "log_refresh" =: to_refresh , "log_discarded" =: discarded , "log_recipes" =: recipes ] logToBson (LogDigest updated not_updated t) = [ "log_at" =: t , "log_updated_feeds" =: updated , "log_not_updated" =: not_updated , "log_type" =: ("feeds_updated_or_not" :: T.Text) ] logToBson (LogCouldNotArchive feeds t err) = let flinks = map f_link feeds items = foldMap f_items feeds in ["log_at " =: t, "log_error" =: err, "log_flinks" =: flinks, "log_items" =: map (T.pack . show) items] saveToLog :: (HasMongo m, MonadIO m) => AppConfig -> LogItem -> m () saveToLog env logitem = withMongo env (insert "logs" $ writeDoc logitem) >> pure () cleanLogs : : ( HasMongo m , MonadIO m ) = > AppConfig - > m ( Either ( ) ) cleanLogs env = do now < - liftIO getCurrentTime res < - withMongo env $ do void $ deleteAll " logs " [ ( [ " log_at " = : [ " $ lt " = : ( one_week_from now : : UTCTime ) ] ] , [ ] ) ] res_delete < - deleteAll " logs " [ ( [ " log_at " = : [ " $ exists " = : False ] ] , [ ] ) ] res_found < - find ( select [ " log_at " = : [ " $ exists " = : False ] ] " logs " ) > > = rest pure ( res_delete , res_found ) case res of Left _ - > pure . Left $ " Failed to cleanLogs " Right ( del , found ) - > if failed del then pure . Left . show $ del else if not $ null found then pure . Left . show $ found else pure $ Right ( ) where one_week_from = addUTCTime ( -604800 ) collectLogStats : : ( HasMongo m , MonadIO m ) = > AppConfig - > m T.Text collectLogStats env = do res < - withMongo env $ do logs < - rest = < < find ( select [ " log_total " = : [ " $ gte " = : ( 0.5 : : Double ) ] ] " logs " ) counts < - rest = < < find ( select [ ] " feeds"){sort = [ " f_reads " = : ( -1 : : Int ) ] , limit = 100 } pure ( logs , counts ) case res of Left _ - > pure " Failed to collectLogStats " Right ( docs_logs , feeds_docs ) - > let logs = List.sortOn log_at . filter ( not . T.null . log_message ) . map readDoc $ docs_logs feeds_counts = map ( \d - > let f = readDoc d in ( f_link f , T.pack . show $ f_reads f ) ) feeds_docs in pure $ foldl ' ( \acc ( ! k , ! v ) - > acc ` T.append ` " " ` T.append ` k ` T.append ` " : " ` T.append ` v ) T.empty feeds_counts ` T.append ` mkStats logs where mkStats logs = let values = let ( a , b , c , d ) = foldl ' ( \(!r , ! s , ! u , ! t ) ( LogPerf _ _ r ' s ' u ' t ' ) - > ( r ' + r , s + s ' , u + u ' , t + t ' ) ) ( 0 , 0 , 0 , 0 ) logs in [ a , b , c , d ] keys = [ " refreshing " , " sending " , " updating " , " total " ] in showLength logs ` T.append ` " logs . Averages for : " ` T.append ` T.intercalate " , " ( zipWith ( \k v - > k ` T.append ` " : " ` T.append ` showAvgLength v logs ) keys values ) showLength = T.pack . show . length showAvgLength a l = T.pack . show $ fromIntegral a ` div ` length l cleanLogs :: (HasMongo m, MonadIO m) => AppConfig -> m (Either String ()) cleanLogs env = do now <- liftIO getCurrentTime res <- withMongo env $ do void $ deleteAll "logs" [(["log_at" =: ["$lt" =: (one_week_from now :: UTCTime)]], [])] res_delete <- deleteAll "logs" [(["log_at" =: ["$exists" =: False]], [])] res_found <- find (select ["log_at" =: ["$exists" =: False]] "logs") >>= rest pure (res_delete, res_found) case res of Left _ -> pure . Left $ "Failed to cleanLogs" Right (del, found) -> if failed del then pure . Left . show $ del else if not $ null found then pure . Left . show $ found else pure $ Right () where one_week_from = addUTCTime (-604800) collectLogStats :: (HasMongo m, MonadIO m) => AppConfig -> m T.Text collectLogStats env = do res <- withMongo env $ do logs <- rest =<< find (select ["log_total" =: ["$gte" =: (0.5 :: Double)]] "logs") counts <- rest =<< find (select [] "feeds"){sort = ["f_reads" =: (-1 :: Int)], limit = 100} pure (logs, counts) case res of Left _ -> pure "Failed to collectLogStats" Right (docs_logs, feeds_docs) -> let logs = List.sortOn log_at . filter (not . T.null . log_message) . map readDoc $ docs_logs feeds_counts = map (\d -> let f = readDoc d in (f_link f, T.pack . show $ f_reads f)) feeds_docs in pure $ foldl' (\acc (!k, !v) -> acc `T.append` " " `T.append` k `T.append` ": " `T.append` v) T.empty feeds_counts `T.append` mkStats logs where mkStats logs = let values = let (a, b, c, d) = foldl' ( \(!r, !s, !u, !t) (LogPerf _ _ r' s' u' t') -> (r' + r, s + s', u + u', t + t') ) (0, 0, 0, 0) logs in [a, b, c, d] keys = ["refreshing", "sending", "updating", "total"] in showLength logs `T.append` " logs. Averages for: " `T.append` T.intercalate ", " ( zipWith ( \k v -> k `T.append` ": " `T.append` showAvgLength v logs ) keys values ) showLength = T.pack . show . length showAvgLength a l = T.pack . show $ fromIntegral a `div` length l -} bsonToAdmin :: Document -> AdminUser bsonToAdmin doc = let uid = fromJust $ M.lookup "admin_uid" doc token = fromJust $ M.lookup "admin_token" doc cid = fromJust $ M.lookup "admin_chatid" doc created = fromJust $ M.lookup "admin_created" doc in AdminUser uid token cid created adminToBson :: AdminUser -> Document adminToBson AdminUser{..} = [ "admin_uid" =: admin_uid , "admin_chatid" =: admin_chatid , "admin_token" =: admin_token , "admin_created" =: admin_created ] bsonToPage : : Document - > Maybe PageOne bsonToPage doc = let cid = M.lookup " chat_id " doc mid = M.lookup " message_id " doc pages = M.lookup " pages " doc one = head < $ > pages n = length < $ > pages mb_url = M.lookup " url " doc in PageOne < $ > one < * > cid < * > mid < * > n < * > mb_url bsonToPage :: Document -> Maybe PageOne bsonToPage doc = let cid = M.lookup "chat_id" doc mid = M.lookup "message_id" doc pages = M.lookup "pages" doc one = head <$> pages n = length <$> pages mb_url = M.lookup "url" doc in PageOne <$> one <*> cid <*> mid <*> n <*> mb_url -} purgeCollections : : ( HasMongo m , MonadIO m ) = > AppConfig - > [ T.Text ] - > m ( Either ( ) ) purgeCollections _ [ ] = pure . Left $ " Empty list of collection names ! " purgeCollections env colls = let action = withMongo env $ mapM ( ` deleteAll ` [ ( [ ] , [ ] ) ] ) colls in action > > = \case Left _ - > pure . Left $ " Failed to purgeCollections . " Right res - > if any failed res then pure . Left $ " Failed to purge collections " + + show colls else pure $ Right ( ) { - Mapping purgeCollections :: (HasMongo m, MonadIO m) => AppConfig -> [T.Text] -> m (Either String ()) purgeCollections _ [] = pure . Left $ "Empty list of collection names!" purgeCollections env colls = let action = withMongo env $ mapM (`deleteAll` [([], [])]) colls in action >>= \case Left _ -> pure . Left $ "Failed to purgeCollections." Right res -> if any failed res then pure . Left $ "Failed to purge collections " ++ show colls else pure $ Right () remapChats :: (MonadIO m, HasMongo m) => AppConfig -> SubChats -> m (Either String ()) remapChats env chats = let selector = map (\c -> (["sub_chatid" =: sub_chatid c], writeDoc c, [Upsert])) $ HMS.elems chats action = updateAll "chats" selector in withMongo env action >>= \case Left _ -> pure $ Left "Failed"; Right _ -> pure $ Right () -} checkDbMapper :: MonadIO m => m () checkDbMapper = do now <- liftIO getCurrentTime let item = Item mempty mempty mempty mempty now digest_interval = DigestInterval (Just 0) (Just [(1, 20)]) word_matches = WordMatches S.empty S.empty (S.fromList ["1", "2", "3"]) settings = Settings (Just 3) digest_interval 0 Nothing "title" True False True True False False word_matches mempty chat = SubChat 0 (Just now) (Just now) S.empty Nothing settings feed = Feed Rss "1" "2" "3" [item] (Just 0) (Just now) 0 log' = LogPerf mempty now 0 0 0 0 digest = Digest Nothing now [item] [mempty] [mempty] admin_user = AdminUser 123 "just user" 456 now equalities = [ ("item", checks item) , ("digest", checks digest) , ("feed", checks feed) , ("chat", checks chat) , ("log", checks log') , ("admin", checks admin_user) ] :: [(T.Text, Bool)] unless (all snd equalities) . liftIO $ do print digest print (readDoc . writeDoc $ digest :: Digest) throwIO . userError $ "Mapper failed. " ++ (show . filter (not . snd) $ equalities)
528de2b6cce354768480479be4253d41831bf9dbe1043f4b828592f04ddcea6e
codedownio/sandwich
HasMainFunction.hs
{-# LANGUAGE MultiWayIf #-} # LANGUAGE TemplateHaskell # module Test.Sandwich.TH.HasMainFunction ( fileHasMainFunction , ShouldWarnOnParseError(..) ) where import Control.Monad import Data.String.Interpolate import Language.Haskell.Exts import Language.Haskell.TH (runIO, reportWarning) -- import Debug.Trace data ShouldWarnOnParseError = WarnOnParseError | NoWarnOnParseError deriving (Eq) | Use haskell - src - exts to determine if a give Haskell file has an exported main function Parse with all extensions enabled , which will hopefully parse anything fileHasMainFunction path shouldWarnOnParseError = runIO (parseFileWithExts [x | x@(EnableExtension _) <- knownExtensions] path) >>= \case x@(ParseFailed {}) -> do when (shouldWarnOnParseError == WarnOnParseError) $ reportWarning [i|Failed to parse #{path}: #{x}|] return False ParseOk (Module _ (Just moduleHead) _ _ decls) -> do -- traceM [i|Sucessfully parsed #{path}: #{moduleHead}|] case moduleHead of ModuleHead _ _ _ (Just (ExportSpecList _ (any isMainFunction -> True))) -> do -- traceM [i|FOUND MAIN FUNCTION FOR #{path}|] return True ModuleHead _ _ _ Nothing -> do traceM [ i|LOOKING FOR DECLS : # { decls}| ] return $ any isMainDecl decls _ -> return False ParseOk _ -> do reportWarning [i|Successfully parsed #{path} but no module head found|] return False isMainFunction :: ExportSpec l -> Bool isMainFunction (EVar _ name) = isMainFunctionQName name isMainFunction _ = False isMainFunctionQName :: QName l -> Bool isMainFunctionQName (Qual _ _ name) = isMainFunctionName name isMainFunctionQName (UnQual _ name) = isMainFunctionName name isMainFunctionQName _ = False isMainFunctionName :: Name l -> Bool isMainFunctionName (Ident _ "main") = True isMainFunctionName (Symbol _ "main") = True isMainFunctionName _ = False isMainDecl :: (Show l) => Decl l -> Bool isMainDecl (PatBind _ (PVar _ (Ident _ "main")) _ _) = True = trace [ i|Looking at : # { decl}| ] False isMainDecl _ = False
null
https://raw.githubusercontent.com/codedownio/sandwich/9c8f56b5aee94ba65c70b3e52bde8959010aecc1/sandwich/src/Test/Sandwich/TH/HasMainFunction.hs
haskell
# LANGUAGE MultiWayIf # import Debug.Trace traceM [i|Sucessfully parsed #{path}: #{moduleHead}|] traceM [i|FOUND MAIN FUNCTION FOR #{path}|]
# LANGUAGE TemplateHaskell # module Test.Sandwich.TH.HasMainFunction ( fileHasMainFunction , ShouldWarnOnParseError(..) ) where import Control.Monad import Data.String.Interpolate import Language.Haskell.Exts import Language.Haskell.TH (runIO, reportWarning) data ShouldWarnOnParseError = WarnOnParseError | NoWarnOnParseError deriving (Eq) | Use haskell - src - exts to determine if a give Haskell file has an exported main function Parse with all extensions enabled , which will hopefully parse anything fileHasMainFunction path shouldWarnOnParseError = runIO (parseFileWithExts [x | x@(EnableExtension _) <- knownExtensions] path) >>= \case x@(ParseFailed {}) -> do when (shouldWarnOnParseError == WarnOnParseError) $ reportWarning [i|Failed to parse #{path}: #{x}|] return False ParseOk (Module _ (Just moduleHead) _ _ decls) -> do case moduleHead of ModuleHead _ _ _ (Just (ExportSpecList _ (any isMainFunction -> True))) -> do return True ModuleHead _ _ _ Nothing -> do traceM [ i|LOOKING FOR DECLS : # { decls}| ] return $ any isMainDecl decls _ -> return False ParseOk _ -> do reportWarning [i|Successfully parsed #{path} but no module head found|] return False isMainFunction :: ExportSpec l -> Bool isMainFunction (EVar _ name) = isMainFunctionQName name isMainFunction _ = False isMainFunctionQName :: QName l -> Bool isMainFunctionQName (Qual _ _ name) = isMainFunctionName name isMainFunctionQName (UnQual _ name) = isMainFunctionName name isMainFunctionQName _ = False isMainFunctionName :: Name l -> Bool isMainFunctionName (Ident _ "main") = True isMainFunctionName (Symbol _ "main") = True isMainFunctionName _ = False isMainDecl :: (Show l) => Decl l -> Bool isMainDecl (PatBind _ (PVar _ (Ident _ "main")) _ _) = True = trace [ i|Looking at : # { decl}| ] False isMainDecl _ = False
a412e4049ff79e752437b7a24f6701f5fae616928bf70a5a9c406590691a8425
yomimono/stitchcraft
ingest.ml
open Lwt.Infix let p_name = let doc = "name to associate with the pattern" in Cmdliner.Arg.(value & pos 0 string "My Very Excellent Mother Just Served Us Nine Patterns!" & info [] ~doc ~docv:"NAME") let input = let doc = "file to read for pattern ingestion. -, the default, is stdin" in Cmdliner.Arg.(value & opt string "-" & info ["i"; "input"] ~doc ~docv:"INPUT") let tags = let doc = "tags to associate with the pattern" in Cmdliner.Arg.(value & opt_all string [] & info ["t"; "tag"] ~doc ~docv:"TAG") let search_patterns (module Caqti_db : Caqti_lwt.CONNECTION) (tags : string list) = Caqti_db.collect_list Db.ORM.Patterns.find tags >>= function | Ok ((id, name, _w, _h)::[]) -> Format.eprintf "pattern %d (%s) matches\n%!" id name; Lwt.return (Ok ()) | Ok [] -> Format.eprintf "no matches\n%!"; Lwt.return (Ok ()) | Ok l -> Format.eprintf "lots of matches: %d\n%!" (List.length l); Lwt.return (Ok ()) | Error _ as e -> Lwt.return e let go db file name tags = match Stitchy.Files.stdin_or_file file with | Error s -> Error s | Ok json -> match Stitchy.Types.pattern_of_yojson json with | Error s -> Error s | Ok pattern -> let open Lwt.Infix in Lwt_main.run ( let uri = Db.CLI.uri_of_db db in Caqti_lwt.connect uri >>= function | Error _ as e -> Lwt.return e | Ok m -> let open Lwt_result.Infix in let module Caqti_db = (val m) in Caqti_db.exec Db.ORM.Patterns.create () >>= fun () -> Caqti_db.exec Db.ORM.Tags.create () >>= fun () -> Caqti_db.exec Db.ORM.Tags.insert tags >>= fun () -> let normalized_json = Stitchy.Types.pattern_to_yojson pattern |> Yojson.Safe.to_string in Caqti_db.find Db.ORM.Patterns.insert_with_tags (name, normalized_json, tags) >>= fun id -> Format.printf "pattern inserted with id %d\n%!" id; search_patterns m tags >>= fun () -> Lwt.return @@ Ok () ) |> function | Ok () -> Ok () | Error (`Msg s) -> Error s | Error (#Caqti_error.t as e)-> Error (Format.asprintf "%a" Caqti_error.pp e) let go_t = Cmdliner.Term.(const go $ Db.CLI.db_t $ input $ p_name $ tags) let info = Cmdliner.Cmd.info "ingest" let () = exit @@ Cmdliner.Cmd.eval_result @@ Cmdliner.Cmd.v info go_t
null
https://raw.githubusercontent.com/yomimono/stitchcraft/6b57efa8a145541e976c9cb1f04ffde984b318bd/ingest_pattern/ingest.ml
ocaml
open Lwt.Infix let p_name = let doc = "name to associate with the pattern" in Cmdliner.Arg.(value & pos 0 string "My Very Excellent Mother Just Served Us Nine Patterns!" & info [] ~doc ~docv:"NAME") let input = let doc = "file to read for pattern ingestion. -, the default, is stdin" in Cmdliner.Arg.(value & opt string "-" & info ["i"; "input"] ~doc ~docv:"INPUT") let tags = let doc = "tags to associate with the pattern" in Cmdliner.Arg.(value & opt_all string [] & info ["t"; "tag"] ~doc ~docv:"TAG") let search_patterns (module Caqti_db : Caqti_lwt.CONNECTION) (tags : string list) = Caqti_db.collect_list Db.ORM.Patterns.find tags >>= function | Ok ((id, name, _w, _h)::[]) -> Format.eprintf "pattern %d (%s) matches\n%!" id name; Lwt.return (Ok ()) | Ok [] -> Format.eprintf "no matches\n%!"; Lwt.return (Ok ()) | Ok l -> Format.eprintf "lots of matches: %d\n%!" (List.length l); Lwt.return (Ok ()) | Error _ as e -> Lwt.return e let go db file name tags = match Stitchy.Files.stdin_or_file file with | Error s -> Error s | Ok json -> match Stitchy.Types.pattern_of_yojson json with | Error s -> Error s | Ok pattern -> let open Lwt.Infix in Lwt_main.run ( let uri = Db.CLI.uri_of_db db in Caqti_lwt.connect uri >>= function | Error _ as e -> Lwt.return e | Ok m -> let open Lwt_result.Infix in let module Caqti_db = (val m) in Caqti_db.exec Db.ORM.Patterns.create () >>= fun () -> Caqti_db.exec Db.ORM.Tags.create () >>= fun () -> Caqti_db.exec Db.ORM.Tags.insert tags >>= fun () -> let normalized_json = Stitchy.Types.pattern_to_yojson pattern |> Yojson.Safe.to_string in Caqti_db.find Db.ORM.Patterns.insert_with_tags (name, normalized_json, tags) >>= fun id -> Format.printf "pattern inserted with id %d\n%!" id; search_patterns m tags >>= fun () -> Lwt.return @@ Ok () ) |> function | Ok () -> Ok () | Error (`Msg s) -> Error s | Error (#Caqti_error.t as e)-> Error (Format.asprintf "%a" Caqti_error.pp e) let go_t = Cmdliner.Term.(const go $ Db.CLI.db_t $ input $ p_name $ tags) let info = Cmdliner.Cmd.info "ingest" let () = exit @@ Cmdliner.Cmd.eval_result @@ Cmdliner.Cmd.v info go_t
2115a9928bc9f764517d1ebe38f373f1bd64b7d8fce6b3342ce6dff7f446769b
haskell-works/hw-prim
Container.hs
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # module HaskellWorks.Data.Container ( Container(..) ) where import Data.Int import Data.Word import qualified Data.ByteString as BS import qualified Data.Vector as DV import qualified Data.Vector.Storable as DVS class Container a where type Elem a instance Container [a] where type Elem [a] = a instance Container BS.ByteString where type Elem BS.ByteString = Word8 instance Container (DV.Vector Word8) where type Elem (DV.Vector Word8) = Word8 instance Container (DV.Vector Word16) where type Elem (DV.Vector Word16) = Word16 instance Container (DV.Vector Word32) where type Elem (DV.Vector Word32) = Word32 instance Container (DV.Vector Word64) where type Elem (DV.Vector Word64) = Word64 instance Container (DVS.Vector Word8) where type Elem (DVS.Vector Word8) = Word8 instance Container (DVS.Vector Word16) where type Elem (DVS.Vector Word16) = Word16 instance Container (DVS.Vector Word32) where type Elem (DVS.Vector Word32) = Word32 instance Container (DVS.Vector Word64) where type Elem (DVS.Vector Word64) = Word64 instance Container (DV.Vector Int8) where type Elem (DV.Vector Int8) = Int8 instance Container (DV.Vector Int16) where type Elem (DV.Vector Int16) = Int16 instance Container (DV.Vector Int32) where type Elem (DV.Vector Int32) = Int32 instance Container (DV.Vector Int64) where type Elem (DV.Vector Int64) = Int64 instance Container (DVS.Vector Int8) where type Elem (DVS.Vector Int8) = Int8 instance Container (DVS.Vector Int16) where type Elem (DVS.Vector Int16) = Int16 instance Container (DVS.Vector Int32) where type Elem (DVS.Vector Int32) = Int32 instance Container (DVS.Vector Int64) where type Elem (DVS.Vector Int64) = Int64 instance Container (DVS.Vector Int) where type Elem (DVS.Vector Int) = Int
null
https://raw.githubusercontent.com/haskell-works/hw-prim/aff74834cd2d3fb0eb4994b24b2d1cdef1e3e673/src/HaskellWorks/Data/Container.hs
haskell
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # module HaskellWorks.Data.Container ( Container(..) ) where import Data.Int import Data.Word import qualified Data.ByteString as BS import qualified Data.Vector as DV import qualified Data.Vector.Storable as DVS class Container a where type Elem a instance Container [a] where type Elem [a] = a instance Container BS.ByteString where type Elem BS.ByteString = Word8 instance Container (DV.Vector Word8) where type Elem (DV.Vector Word8) = Word8 instance Container (DV.Vector Word16) where type Elem (DV.Vector Word16) = Word16 instance Container (DV.Vector Word32) where type Elem (DV.Vector Word32) = Word32 instance Container (DV.Vector Word64) where type Elem (DV.Vector Word64) = Word64 instance Container (DVS.Vector Word8) where type Elem (DVS.Vector Word8) = Word8 instance Container (DVS.Vector Word16) where type Elem (DVS.Vector Word16) = Word16 instance Container (DVS.Vector Word32) where type Elem (DVS.Vector Word32) = Word32 instance Container (DVS.Vector Word64) where type Elem (DVS.Vector Word64) = Word64 instance Container (DV.Vector Int8) where type Elem (DV.Vector Int8) = Int8 instance Container (DV.Vector Int16) where type Elem (DV.Vector Int16) = Int16 instance Container (DV.Vector Int32) where type Elem (DV.Vector Int32) = Int32 instance Container (DV.Vector Int64) where type Elem (DV.Vector Int64) = Int64 instance Container (DVS.Vector Int8) where type Elem (DVS.Vector Int8) = Int8 instance Container (DVS.Vector Int16) where type Elem (DVS.Vector Int16) = Int16 instance Container (DVS.Vector Int32) where type Elem (DVS.Vector Int32) = Int32 instance Container (DVS.Vector Int64) where type Elem (DVS.Vector Int64) = Int64 instance Container (DVS.Vector Int) where type Elem (DVS.Vector Int) = Int
bfd8817fd97665c2c4f2d9a55f369c1d962d373bb8c4a5ab7fcf56f653753041
Jell/euroclojure-2016
project.clj
(defproject euroclojure "0.1.0-SNAPSHOT" :description "FIXME: write this!" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.6.1" :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.9.89"] [org.clojure/core.async "0.2.385" :exclusions [org.clojure/tools.reader]] [reagent "0.6.0-rc" :exclusions [cljsjs/react]] [cljsjs/react-with-addons "15.3.1-0"] [kioo "0.4.2" :exclusions [cljsjs/react om]] [org.clojure/data.codec "0.1.0"] [enfocus "2.1.1"] [com.taoensso/tower "3.0.2"]] :plugins [[lein-figwheel "0.5.4-7"] [lein-cljsbuild "1.1.3" :exclusions [[org.clojure/clojure]]]] :source-paths ["src"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target"] :resource-paths ["resources" "resources/webpack" "resources/private"] :cljsbuild {:builds [{:id "dev" :source-paths ["src"] ;; the presence of a :figwheel configuration here ;; will cause figwheel to inject the figwheel client ;; into your build :figwheel {:on-jsload "euroclojure.core/on-js-reload" ;; :open-urls will pop open your application in the default browser once Figwheel has ;; started and complied your application. ;; Comment this out once it no longer serves you. :open-urls [":3449/index.html"]} :compiler {:main euroclojure.core :asset-path "js/compiled/out" :closure-defines {"euroclojure.demo.href" ":3000/demo.html"} :output-to "resources/public/js/compiled/euroclojure.js" :output-dir "resources/public/js/compiled/out" :foreign-libs [{:file "resources/webpack/bundle.js" :requires ["cljsjs/react"] :provides ["webpack-bundle"]}] :source-map-timestamp true To console.log CLJS data - structures make sure you enable devtools in Chrome ;; -devtools :preloads [devtools.preload]}} ;; This next build is an compressed minified build for ;; production. You can build this with: once min {:id "min" :source-paths ["src"] :compiler {:output-to "resources/public/js/compiled/euroclojure.js" :main euroclojure.core :optimizations :advanced :foreign-libs [{:file "resources/webpack/bundle.js" :requires ["cljsjs/react"] :provides ["webpack-bundle"]}] :closure-defines {"euroclojure.demo.href" "-checkout.zimpler.net/demo.html"} :pretty-print false}}]} :figwheel {;; :http-server-root "public" ;; default and assumes "resources" : server - port 3449 ; ; default : server - ip " 127.0.0.1 " :css-dirs ["resources/public/css"] ;; watch and update CSS Start an nREPL server into the running figwheel process :nrepl-port 7888 Server Ring Handler ( optional ) ;; if you want to embed a ring handler into the figwheel http-kit ;; server, this is for simple ring servers, if this does n't work for you just run your own server :) ( see ) ;; :ring-handler hello_world.server/handler ;; To be able to open files in your editor from the heads up display ;; you will need to put a script on your path. ;; that script will have to take a file path and a line number ;; ie. in ~/bin/myfile-opener ;; #! /bin/sh emacsclient -n + $ 2 $ 1 ;; ;; :open-file-command "myfile-opener" ;; if you are using emacsclient you can just use ;; :open-file-command "emacsclient" ;; if you want to disable the REPL :repl false ;; to configure a different figwheel logfile path ;; :server-logfile "tmp/logs/figwheel-logfile.log" } setting up nREPL for Figwheel and ClojureScript dev ;; Please see: ;; -figwheel/wiki/Using-the-Figwheel-REPL-within-NRepl :profiles {:dev {:dependencies [[binaryage/devtools "0.7.2"] [figwheel-sidecar "0.5.4-7"] [com.cemerick/piggieback "0.2.1"]] ;; need to add dev source path here to get user.clj loaded :source-paths ["src" "dev"] for CIDER ;; :plugins [[cider/cider-nrepl "0.12.0"]] for nREPL dev you really need to limit output :init (set! *print-length* 50) :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}}} )
null
https://raw.githubusercontent.com/Jell/euroclojure-2016/a8ca883e8480a4616ede19995aaacd4a495608af/project.clj
clojure
the presence of a :figwheel configuration here will cause figwheel to inject the figwheel client into your build :open-urls will pop open your application started and complied your application. Comment this out once it no longer serves you. -devtools This next build is an compressed minified build for production. You can build this with: :http-server-root "public" ;; default and assumes "resources" ; default watch and update CSS if you want to embed a ring handler into the figwheel http-kit server, this is for simple ring servers, if this :ring-handler hello_world.server/handler To be able to open files in your editor from the heads up display you will need to put a script on your path. that script will have to take a file path and a line number ie. in ~/bin/myfile-opener #! /bin/sh :open-file-command "myfile-opener" if you are using emacsclient you can just use :open-file-command "emacsclient" if you want to disable the REPL to configure a different figwheel logfile path :server-logfile "tmp/logs/figwheel-logfile.log" Please see: -figwheel/wiki/Using-the-Figwheel-REPL-within-NRepl need to add dev source path here to get user.clj loaded :plugins [[cider/cider-nrepl "0.12.0"]]
(defproject euroclojure "0.1.0-SNAPSHOT" :description "FIXME: write this!" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.6.1" :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.9.89"] [org.clojure/core.async "0.2.385" :exclusions [org.clojure/tools.reader]] [reagent "0.6.0-rc" :exclusions [cljsjs/react]] [cljsjs/react-with-addons "15.3.1-0"] [kioo "0.4.2" :exclusions [cljsjs/react om]] [org.clojure/data.codec "0.1.0"] [enfocus "2.1.1"] [com.taoensso/tower "3.0.2"]] :plugins [[lein-figwheel "0.5.4-7"] [lein-cljsbuild "1.1.3" :exclusions [[org.clojure/clojure]]]] :source-paths ["src"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target"] :resource-paths ["resources" "resources/webpack" "resources/private"] :cljsbuild {:builds [{:id "dev" :source-paths ["src"] :figwheel {:on-jsload "euroclojure.core/on-js-reload" in the default browser once Figwheel has :open-urls [":3449/index.html"]} :compiler {:main euroclojure.core :asset-path "js/compiled/out" :closure-defines {"euroclojure.demo.href" ":3000/demo.html"} :output-to "resources/public/js/compiled/euroclojure.js" :output-dir "resources/public/js/compiled/out" :foreign-libs [{:file "resources/webpack/bundle.js" :requires ["cljsjs/react"] :provides ["webpack-bundle"]}] :source-map-timestamp true To console.log CLJS data - structures make sure you enable devtools in Chrome :preloads [devtools.preload]}} once min {:id "min" :source-paths ["src"] :compiler {:output-to "resources/public/js/compiled/euroclojure.js" :main euroclojure.core :optimizations :advanced :foreign-libs [{:file "resources/webpack/bundle.js" :requires ["cljsjs/react"] :provides ["webpack-bundle"]}] :closure-defines {"euroclojure.demo.href" "-checkout.zimpler.net/demo.html"} :pretty-print false}}]} : server - ip " 127.0.0.1 " Start an nREPL server into the running figwheel process :nrepl-port 7888 Server Ring Handler ( optional ) does n't work for you just run your own server :) ( see ) emacsclient -n + $ 2 $ 1 :repl false } setting up nREPL for Figwheel and ClojureScript dev :profiles {:dev {:dependencies [[binaryage/devtools "0.7.2"] [figwheel-sidecar "0.5.4-7"] [com.cemerick/piggieback "0.2.1"]] :source-paths ["src" "dev"] for CIDER for nREPL dev you really need to limit output :init (set! *print-length* 50) :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}}} )
635025a29ee67301fcc1afe24b48c7ae0b44b1d787aec38b477c1783688c8cc3
hakaru-dev/hakaru
Summary.hs
# LANGUAGE CPP , OverloadedStrings , PatternGuards , DataKinds , KindSignatures , GADTs , FlexibleContexts , TypeOperators # OverloadedStrings, PatternGuards, DataKinds, KindSignatures, GADTs, FlexibleContexts, TypeOperators #-} module Main where import qualified Language.Hakaru.Syntax.AST as T import Language.Hakaru.Syntax.AST.Transforms import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.TypeCheck import Language.Hakaru.Types.Sing (Sing) import Language.Hakaru.Pretty.Haskell import Language.Hakaru.Command import Language.Hakaru.Summary #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif import Data.Text as TxT import qualified Data.Text.IO as IO import Data.Monoid ((<>)) import System.IO (stderr) import Text.PrettyPrint hiding ((<>)) import qualified Options.Applicative as O import System.FilePath data Options = Options { fileIn :: String , fileOut :: Maybe String , asModule :: Maybe String , logFloatPrelude :: Bool , optimize :: Bool } deriving Show main :: IO () main = do opts <- parseOpts compileHakaru opts parseOpts :: IO Options parseOpts = O.execParser $ O.info (O.helper <*> options) $ O.fullDesc <> O.progDesc "Compile Hakaru to Haskell" There is some redundancy in Compile.hs , Hakaru.hs , and HKC.hs in how we decide what to run given which arguments . There may be a way to unify these . There is some redundancy in Compile.hs, Hakaru.hs, and HKC.hs in how we decide what to run given which arguments. There may be a way to unify these. -} options :: O.Parser Options options = Options <$> O.strArgument (O.metavar "INPUT" <> O.help "Program to be compiled" ) <*> (O.optional $ O.strOption (O.short 'o' <> O.help "Optional output file name")) <*> (O.optional $ O.strOption (O.long "as-module" <> O.short 'M' <> O.help "creates a haskell module with this name")) <*> O.switch (O.long "logfloat-prelude" <> O.help "use logfloat prelude for numeric stability") <*> O.switch (O.short 'O' <> O.help "perform Hakaru AST optimizations") prettyProg :: (ABT T.Term abt) => String -> Sing a -> abt '[] a -> String prettyProg name typ ast = renderStyle style ( sep [text (name ++ " ::"), nest 2 (prettyType typ)] $+$ sep [text (name ++ " =") , nest 2 (pretty ast)] ) compileHakaru :: Options -> IO () compileHakaru opts = do let infile = fileIn opts prog <- readFromFile infile case parseAndInfer prog of Left err -> IO.hPutStrLn stderr err Right (TypedAST typ ast) -> do ast' <- (if optimize opts then optimizations else id) <$> summary (et ast) writeHkHsToFile infile (fileOut opts) . TxT.unlines $ header (logFloatPrelude opts) (asModule opts) ++ [ pack $ prettyProg "prog" typ ast' ] ++ (case asModule opts of Nothing -> footer Just _ -> []) where et = expandTransformations writeHkHsToFile :: String -> Maybe String -> Text -> IO () writeHkHsToFile inFile moutFile content = let outFile = case moutFile of Nothing -> replaceFileName inFile (takeBaseName inFile) ++ ".hs" Just x -> x in writeToFile outFile content header :: Bool -> Maybe String -> [Text] header logfloats mmodule = [ "{-# LANGUAGE DataKinds, NegativeLiterals #-}" , TxT.unwords [ "module" , case mmodule of Just m -> pack m Nothing -> "Main" , "where" ] , "" , if logfloats then TxT.unlines [ "import Data.Number.LogFloat (LogFloat)" , "import Prelude hiding (product, exp, log, (**), pi)" , "import Language.Hakaru.Runtime.LogFloatPrelude" ] else TxT.unlines [ "import Prelude hiding (product)" , "import Language.Hakaru.Runtime.Prelude" ] , "import Language.Hakaru.Runtime.CmdLine" , "import Language.Hakaru.Types.Sing" , "import qualified System.Random.MWC as MWC" , "import Control.Monad" , "import System.Environment (getArgs)" , "" ] footer :: [Text] footer = ["","main :: IO ()" , TxT.concat ["main = makeMain prog =<< getArgs"]] footerWalk :: [Text] footerWalk = [ "" , "main :: IO ()" , "main = do" , " g <- MWC.createSystemRandom" , " x <- prog2 g" , " iterateM_ (withPrint $ flip prog1 g) x" ]
null
https://raw.githubusercontent.com/hakaru-dev/hakaru/94157c89ea136c3b654a85cce51f19351245a490/commands/Summary.hs
haskell
# LANGUAGE CPP , OverloadedStrings , PatternGuards , DataKinds , KindSignatures , GADTs , FlexibleContexts , TypeOperators # OverloadedStrings, PatternGuards, DataKinds, KindSignatures, GADTs, FlexibleContexts, TypeOperators #-} module Main where import qualified Language.Hakaru.Syntax.AST as T import Language.Hakaru.Syntax.AST.Transforms import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.TypeCheck import Language.Hakaru.Types.Sing (Sing) import Language.Hakaru.Pretty.Haskell import Language.Hakaru.Command import Language.Hakaru.Summary #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif import Data.Text as TxT import qualified Data.Text.IO as IO import Data.Monoid ((<>)) import System.IO (stderr) import Text.PrettyPrint hiding ((<>)) import qualified Options.Applicative as O import System.FilePath data Options = Options { fileIn :: String , fileOut :: Maybe String , asModule :: Maybe String , logFloatPrelude :: Bool , optimize :: Bool } deriving Show main :: IO () main = do opts <- parseOpts compileHakaru opts parseOpts :: IO Options parseOpts = O.execParser $ O.info (O.helper <*> options) $ O.fullDesc <> O.progDesc "Compile Hakaru to Haskell" There is some redundancy in Compile.hs , Hakaru.hs , and HKC.hs in how we decide what to run given which arguments . There may be a way to unify these . There is some redundancy in Compile.hs, Hakaru.hs, and HKC.hs in how we decide what to run given which arguments. There may be a way to unify these. -} options :: O.Parser Options options = Options <$> O.strArgument (O.metavar "INPUT" <> O.help "Program to be compiled" ) <*> (O.optional $ O.strOption (O.short 'o' <> O.help "Optional output file name")) <*> (O.optional $ O.strOption (O.long "as-module" <> O.short 'M' <> O.help "creates a haskell module with this name")) <*> O.switch (O.long "logfloat-prelude" <> O.help "use logfloat prelude for numeric stability") <*> O.switch (O.short 'O' <> O.help "perform Hakaru AST optimizations") prettyProg :: (ABT T.Term abt) => String -> Sing a -> abt '[] a -> String prettyProg name typ ast = renderStyle style ( sep [text (name ++ " ::"), nest 2 (prettyType typ)] $+$ sep [text (name ++ " =") , nest 2 (pretty ast)] ) compileHakaru :: Options -> IO () compileHakaru opts = do let infile = fileIn opts prog <- readFromFile infile case parseAndInfer prog of Left err -> IO.hPutStrLn stderr err Right (TypedAST typ ast) -> do ast' <- (if optimize opts then optimizations else id) <$> summary (et ast) writeHkHsToFile infile (fileOut opts) . TxT.unlines $ header (logFloatPrelude opts) (asModule opts) ++ [ pack $ prettyProg "prog" typ ast' ] ++ (case asModule opts of Nothing -> footer Just _ -> []) where et = expandTransformations writeHkHsToFile :: String -> Maybe String -> Text -> IO () writeHkHsToFile inFile moutFile content = let outFile = case moutFile of Nothing -> replaceFileName inFile (takeBaseName inFile) ++ ".hs" Just x -> x in writeToFile outFile content header :: Bool -> Maybe String -> [Text] header logfloats mmodule = [ "{-# LANGUAGE DataKinds, NegativeLiterals #-}" , TxT.unwords [ "module" , case mmodule of Just m -> pack m Nothing -> "Main" , "where" ] , "" , if logfloats then TxT.unlines [ "import Data.Number.LogFloat (LogFloat)" , "import Prelude hiding (product, exp, log, (**), pi)" , "import Language.Hakaru.Runtime.LogFloatPrelude" ] else TxT.unlines [ "import Prelude hiding (product)" , "import Language.Hakaru.Runtime.Prelude" ] , "import Language.Hakaru.Runtime.CmdLine" , "import Language.Hakaru.Types.Sing" , "import qualified System.Random.MWC as MWC" , "import Control.Monad" , "import System.Environment (getArgs)" , "" ] footer :: [Text] footer = ["","main :: IO ()" , TxT.concat ["main = makeMain prog =<< getArgs"]] footerWalk :: [Text] footerWalk = [ "" , "main :: IO ()" , "main = do" , " g <- MWC.createSystemRandom" , " x <- prog2 g" , " iterateM_ (withPrint $ flip prog1 g) x" ]
ddd2332d3781df7d34d9e578b7ca9a9d7fb0b186d3cfc4bbf8f0b318b55f6b04
nasa/Common-Metadata-Repository
core_test.clj
(ns cmr.graph.core-test (:require [clojure.test :refer :all] [cmr.graph.core :as core])) (deftest a-test (is (= 1 1)))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/graph/test/cmr/graph/core_test.clj
clojure
(ns cmr.graph.core-test (:require [clojure.test :refer :all] [cmr.graph.core :as core])) (deftest a-test (is (= 1 1)))
8d21cd902e7b1cf76f03f889991c5a39e65b75b3df9b51259cecad49ef1fc283
mwand/eopl3
interp.scm
(module interp (lib "eopl.ss" "eopl") ;; interpreter for the PROC language, using the procedural ;; representation of procedures. The \commentboxes are the latex code for inserting the rules into ;; the code in the book. These are too complicated to put here, see ;; the text, sorry. (require "drscheme-init.scm") (require "lang.scm") (require "data-structures.scm") (require "environments.scm") (provide value-of-program value-of) ;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;; value - of - program : Program - > ExpVal (define value-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) value - of : Exp * Env - > ExpVal (define value-of (lambda (exp env) (cases expression exp ;\commentbox{ (value-of (const-exp \n{}) \r) = \n{}} (const-exp (num) (num-val num)) ;\commentbox{ (value-of (var-exp \x{}) \r) = (apply-env \r \x{})} (var-exp (var) (apply-env env var)) ;\commentbox{\diffspec} (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) ;\commentbox{\zerotestspec} (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) ;\commentbox{\ma{\theifspec}} (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) ;\commentbox{\ma{\theletspecsplit}} (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) ))) ;; procedure : Var * Exp * Env -> Proc Page : 79 (define procedure (lambda (var body env) (lambda (val) (value-of body (extend-env var val env))))) apply - procedure : Proc * ExpVal - > ExpVal Page : 79 (define apply-procedure (lambda (proc val) (proc val))) )
null
https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter3/proc-lang/proc-rep/interp.scm
scheme
interpreter for the PROC language, using the procedural representation of procedures. the code in the book. These are too complicated to put here, see the text, sorry. the interpreter ;;;;;;;;;;;;;;;; \commentbox{ (value-of (const-exp \n{}) \r) = \n{}} \commentbox{ (value-of (var-exp \x{}) \r) = (apply-env \r \x{})} \commentbox{\diffspec} \commentbox{\zerotestspec} \commentbox{\ma{\theifspec}} \commentbox{\ma{\theletspecsplit}} procedure : Var * Exp * Env -> Proc
(module interp (lib "eopl.ss" "eopl") The \commentboxes are the latex code for inserting the rules into (require "drscheme-init.scm") (require "lang.scm") (require "data-structures.scm") (require "environments.scm") (provide value-of-program value-of) value - of - program : Program - > ExpVal (define value-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) value - of : Exp * Env - > ExpVal (define value-of (lambda (exp env) (cases expression exp (const-exp (num) (num-val num)) (var-exp (var) (apply-env env var)) (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) ))) Page : 79 (define procedure (lambda (var body env) (lambda (val) (value-of body (extend-env var val env))))) apply - procedure : Proc * ExpVal - > ExpVal Page : 79 (define apply-procedure (lambda (proc val) (proc val))) )
027d9c69606dc090994c585fd7ebab0d06b7e2688afa6c66dfe6ab6568a5d25f
input-output-hk/ouroboros-network
RateLimiting.hs
# LANGUAGE NamedFieldPuns # -- | Rage limiting of accepted connections -- module Ouroboros.Network.Server.RateLimiting ( AcceptedConnectionsLimit (..) , runConnectionRateLimits -- * Tracing , AcceptConnectionsPolicyTrace (..) ) where import Control.Monad (when) import Control.Monad.Class.MonadSTM import Control.Monad.Class.MonadTime import Control.Monad.Class.MonadTimer import Control.Tracer (Tracer, traceWith) import Data.Typeable (Typeable) import Data.Word import Text.Printf -- | Policy which governs how to limit the number of accepted connections. -- data AcceptedConnectionsLimit = AcceptedConnectionsLimit { -- | Hard limit of accepted connections. -- acceptedConnectionsHardLimit :: !Word32, -- | Soft limit of accepted connections. If we are above this threshold, -- we will start rate limiting. -- acceptedConnectionsSoftLimit :: !Word32, | delay for limiting accepted connections . We use linear -- regression starting from 0 at the soft limit up to -- `acceptedConnectionDelay` at the hard limit. -- acceptedConnectionsDelay :: !DiffTime } deriving (Eq, Ord, Show) -- | Rate limiting instruction. -- data RateLimitDelay = -- | no rate limiting -- NoRateLimiting -- | We are above the soft limit, we delay accepting the next connection> | SoftDelay DiffTime -- | We are above the hard limit, wait until the number of connections -- drops below the given threshold (currently this is the hard limit, -- which means we keep `acceptedConnectionsHardLimit` number of -- connections, later we c could be configured to something between -- `acceptedConnesiontSoftLimit` and `acceptedConnectionsHardLimit`). -- | HardLimit Word32 -- | Interpretation of the 'AcceptedConnectionsLimit' policy. -- getRateLimitDecision :: Int -- ^ number of served concurrent connections -> AcceptedConnectionsLimit -- ^ limits -> RateLimitDelay getRateLimitDecision numberOfConnections AcceptedConnectionsLimit { acceptedConnectionsHardLimit , acceptedConnectionsSoftLimit , acceptedConnectionsDelay } -- below the soft limit we accept connections without any delay | numberOfConnections < softLimit = NoRateLimiting -- above the hard limit will will wait until the number of connections drops -- below the soft limit | numberOfConnections >= hardLimit = HardLimit acceptedConnectionsHardLimit -- in between we scale the delay using linear regression. | otherwise = SoftDelay $ fromIntegral (numberOfConnections - softLimit) * acceptedConnectionsDelay / fromIntegral ((hardLimit - softLimit) `max` 1) where hardLimit, softLimit :: Int hardLimit = fromIntegral acceptedConnectionsHardLimit softLimit = fromIntegral acceptedConnectionsSoftLimit -- | Get the number of current connections, make decision based on ' AcceptedConnectionsLimit ' and execute it . -- runConnectionRateLimits :: ( MonadSTM m , MonadDelay m , MonadTime m ) => Tracer m AcceptConnectionsPolicyTrace -> STM m Int -> AcceptedConnectionsLimit -> m () runConnectionRateLimits tracer numberOfConnectionsSTM acceptedConnectionsLimit@AcceptedConnectionsLimit { acceptedConnectionsDelay } = do numberOfConnections <- atomically numberOfConnectionsSTM case getRateLimitDecision numberOfConnections acceptedConnectionsLimit of NoRateLimiting -> pure () SoftDelay delay -> do traceWith tracer (ServerTraceAcceptConnectionRateLimiting delay numberOfConnections) threadDelay delay -- wait until the current number of connection drops below the limit, and -- wait at least 'acceptedConnectionsDelay'. This is to avoid accepting -- the last connection to frequently if it fails almost immediately . HardLimit limit -> do traceWith tracer (ServerTraceAcceptConnectionHardLimit limit) start <- getMonotonicTime atomically $ do numberOfConnections' <- numberOfConnectionsSTM check (numberOfConnections' < fromIntegral limit) end <- getMonotonicTime let remainingDelay = acceptedConnectionsDelay - end `diffTime` start when (remainingDelay > 0) $ threadDelay remainingDelay numberOfConnections' <- atomically numberOfConnectionsSTM traceWith tracer $ ServerTraceAcceptConnectionResume numberOfConnections' -- -- trace -- -- | Trace for the 'AcceptConnectionsLimit' policy. -- data AcceptConnectionsPolicyTrace = ServerTraceAcceptConnectionRateLimiting DiffTime Int | ServerTraceAcceptConnectionHardLimit Word32 | ServerTraceAcceptConnectionResume Int deriving (Eq, Ord, Typeable) instance Show AcceptConnectionsPolicyTrace where show (ServerTraceAcceptConnectionRateLimiting delay numberOfConnections) = printf "rate limiting accepting connections, delaying next accept for %s, currently serving %s connections" (show delay) (show numberOfConnections) show (ServerTraceAcceptConnectionHardLimit limit) = printf "hard rate limit reached, waiting until the number of connections drops below %s" (show limit) show (ServerTraceAcceptConnectionResume numberOfConnections) = printf "hard rate limit over, accepting connections again, currently serving %d connections" numberOfConnections
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/6c15a8093bac34091ad96af2b8b0d1f7fe54b732/ouroboros-network-framework/src/Ouroboros/Network/Server/RateLimiting.hs
haskell
| Rage limiting of accepted connections * Tracing | Policy which governs how to limit the number of accepted connections. | Hard limit of accepted connections. | Soft limit of accepted connections. If we are above this threshold, we will start rate limiting. regression starting from 0 at the soft limit up to `acceptedConnectionDelay` at the hard limit. | Rate limiting instruction. | no rate limiting | We are above the soft limit, we delay accepting the next connection> | We are above the hard limit, wait until the number of connections drops below the given threshold (currently this is the hard limit, which means we keep `acceptedConnectionsHardLimit` number of connections, later we c could be configured to something between `acceptedConnesiontSoftLimit` and `acceptedConnectionsHardLimit`). | Interpretation of the 'AcceptedConnectionsLimit' policy. ^ number of served concurrent connections ^ limits below the soft limit we accept connections without any delay above the hard limit will will wait until the number of connections drops below the soft limit in between we scale the delay using linear regression. | Get the number of current connections, make decision based on wait until the current number of connection drops below the limit, and wait at least 'acceptedConnectionsDelay'. This is to avoid accepting the last connection to frequently if it fails almost immediately . trace | Trace for the 'AcceptConnectionsLimit' policy.
# LANGUAGE NamedFieldPuns # module Ouroboros.Network.Server.RateLimiting ( AcceptedConnectionsLimit (..) , runConnectionRateLimits , AcceptConnectionsPolicyTrace (..) ) where import Control.Monad (when) import Control.Monad.Class.MonadSTM import Control.Monad.Class.MonadTime import Control.Monad.Class.MonadTimer import Control.Tracer (Tracer, traceWith) import Data.Typeable (Typeable) import Data.Word import Text.Printf data AcceptedConnectionsLimit = AcceptedConnectionsLimit { acceptedConnectionsHardLimit :: !Word32, acceptedConnectionsSoftLimit :: !Word32, | delay for limiting accepted connections . We use linear acceptedConnectionsDelay :: !DiffTime } deriving (Eq, Ord, Show) data RateLimitDelay = NoRateLimiting | SoftDelay DiffTime | HardLimit Word32 getRateLimitDecision :: Int -> AcceptedConnectionsLimit -> RateLimitDelay getRateLimitDecision numberOfConnections AcceptedConnectionsLimit { acceptedConnectionsHardLimit , acceptedConnectionsSoftLimit , acceptedConnectionsDelay } | numberOfConnections < softLimit = NoRateLimiting | numberOfConnections >= hardLimit = HardLimit acceptedConnectionsHardLimit | otherwise = SoftDelay $ fromIntegral (numberOfConnections - softLimit) * acceptedConnectionsDelay / fromIntegral ((hardLimit - softLimit) `max` 1) where hardLimit, softLimit :: Int hardLimit = fromIntegral acceptedConnectionsHardLimit softLimit = fromIntegral acceptedConnectionsSoftLimit ' AcceptedConnectionsLimit ' and execute it . runConnectionRateLimits :: ( MonadSTM m , MonadDelay m , MonadTime m ) => Tracer m AcceptConnectionsPolicyTrace -> STM m Int -> AcceptedConnectionsLimit -> m () runConnectionRateLimits tracer numberOfConnectionsSTM acceptedConnectionsLimit@AcceptedConnectionsLimit { acceptedConnectionsDelay } = do numberOfConnections <- atomically numberOfConnectionsSTM case getRateLimitDecision numberOfConnections acceptedConnectionsLimit of NoRateLimiting -> pure () SoftDelay delay -> do traceWith tracer (ServerTraceAcceptConnectionRateLimiting delay numberOfConnections) threadDelay delay HardLimit limit -> do traceWith tracer (ServerTraceAcceptConnectionHardLimit limit) start <- getMonotonicTime atomically $ do numberOfConnections' <- numberOfConnectionsSTM check (numberOfConnections' < fromIntegral limit) end <- getMonotonicTime let remainingDelay = acceptedConnectionsDelay - end `diffTime` start when (remainingDelay > 0) $ threadDelay remainingDelay numberOfConnections' <- atomically numberOfConnectionsSTM traceWith tracer $ ServerTraceAcceptConnectionResume numberOfConnections' data AcceptConnectionsPolicyTrace = ServerTraceAcceptConnectionRateLimiting DiffTime Int | ServerTraceAcceptConnectionHardLimit Word32 | ServerTraceAcceptConnectionResume Int deriving (Eq, Ord, Typeable) instance Show AcceptConnectionsPolicyTrace where show (ServerTraceAcceptConnectionRateLimiting delay numberOfConnections) = printf "rate limiting accepting connections, delaying next accept for %s, currently serving %s connections" (show delay) (show numberOfConnections) show (ServerTraceAcceptConnectionHardLimit limit) = printf "hard rate limit reached, waiting until the number of connections drops below %s" (show limit) show (ServerTraceAcceptConnectionResume numberOfConnections) = printf "hard rate limit over, accepting connections again, currently serving %d connections" numberOfConnections
e47f3f4236aa9c10f304fb80c1a9737dc227477840fc7dfc5a68a18a462a1bf9
RefactoringTools/HaRe
WhereIn1_TokOut.hs
module WhereIn1 where --A definition can be lifted from a where or let into the surronding binding group. --Lifting a definition widens the scope of the definition. --In this example, lift 'sq' in 'sumSquares' --This example aims to test add parameters to 'sq'. sumSquares x y = (sq pow) x + (sq pow) y where pow=2 sq pow 0 = 0 sq pow z = z^pow anotherFun 0 y = sq y where sq x = x^2
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/testing/liftOneLevel/WhereIn1_TokOut.hs
haskell
A definition can be lifted from a where or let into the surronding binding group. Lifting a definition widens the scope of the definition. In this example, lift 'sq' in 'sumSquares' This example aims to test add parameters to 'sq'.
module WhereIn1 where sumSquares x y = (sq pow) x + (sq pow) y where pow=2 sq pow 0 = 0 sq pow z = z^pow anotherFun 0 y = sq y where sq x = x^2
1e16863d0a08694a9b6eba38d1f90c7f530f539e1e87501fe0ff1df2e5d31e3e
composewell/streamly
ConcurrentEager.hs
# LANGUAGE FlexibleContexts # -- | -- Module : Main Copyright : ( c ) 2018 Composewell Technologies -- -- License : BSD3 -- Maintainer : import Stream.ConcurrentCommon (allBenchmarks) import Streamly.Benchmark.Common (runWithCLIOpts, defaultStreamSize) import qualified Streamly.Internal.Data.Stream.Concurrent as Async moduleName :: String moduleName = "Data.Stream.ConcurrentEager" ------------------------------------------------------------------------------- -- Main ------------------------------------------------------------------------------- main :: IO () main = runWithCLIOpts defaultStreamSize (allBenchmarks moduleName (Async.eager True))
null
https://raw.githubusercontent.com/composewell/streamly/071745844371ef0abe3b1a51b7ee6eed8e15ccb5/benchmark/Streamly/Benchmark/Data/Stream/ConcurrentEager.hs
haskell
| Module : Main License : BSD3 Maintainer : ----------------------------------------------------------------------------- Main -----------------------------------------------------------------------------
# LANGUAGE FlexibleContexts # Copyright : ( c ) 2018 Composewell Technologies import Stream.ConcurrentCommon (allBenchmarks) import Streamly.Benchmark.Common (runWithCLIOpts, defaultStreamSize) import qualified Streamly.Internal.Data.Stream.Concurrent as Async moduleName :: String moduleName = "Data.Stream.ConcurrentEager" main :: IO () main = runWithCLIOpts defaultStreamSize (allBenchmarks moduleName (Async.eager True))
98c4510ecc5e790c0dbbb7a8c00381b3e61f88b1ad0dc572b075a6bef3b14a31
dyzsr/ocaml-selectml
chi2.ml
(* TEST *) A basic chi - square test to detect simple errors in the Random module . Accumulate [ n ] samples from function [ f ] and check the chi - square . Only the low 8 bits of the result of [ f ] are sampled . Only the low 8 bits of the result of [f] are sampled. *) let chisquare n f = let r = 256 in let freq = Array.make r 0 in for i = 0 to n - 1 do let t = f () land 0xFF in freq.(t) <- freq.(t) + 1 done; let expected = float n /. float r in let t = Array.fold_left (fun s x -> let d = float x -. expected in d *. d +. s) 0.0 freq in let chi2 = t /. expected in let degfree = float r -. 1.0 in The degree of freedom is high , so we approximate as a normal distribution with mean equal to degfree and variance 2 * degfree . Four sigmas correspond to a 99.9968 % confidence interval . ( Without the approximation , the confidence interval seems to be 99.986 % . ) distribution with mean equal to degfree and variance 2 * degfree. Four sigmas correspond to a 99.9968% confidence interval. (Without the approximation, the confidence interval seems to be 99.986%.) *) chi2 <= degfree +. 4.0 *. sqrt (2.0 *. degfree) let test name f = if not (chisquare 100_000 f) then Printf.printf "%s: suspicious result\n%!" name let _ = test "Random.bits (bits 0-7)" Random.bits; test "Random.bits (bits 12-19)" (fun () -> Random.bits() lsr 12); test "Random.bits (bits 22-29)" (fun () -> Random.bits() lsr 22); test "Random.int 2^26 (bits 0-7)" (fun () -> Random.int (1 lsl 26)); test "Random.int 2^26 (bits 18-25)" (fun () -> Random.int (1 lsl 26) lsr 18); test "Random.int (256 * p) / p" (fun () -> Random.int (256 * 853187) / 853187); test "Random.float 1.0 (first 8 bits)" (fun () -> int_of_float (Random.float 1.0 *. 256.0)); test "Random.float 1.0 (next 8 bits)" (fun () -> int_of_float (Random.float 1.0 *. 65536.0)); test "Random.bits32 (bits 0-7)" (fun () -> Int32.to_int (Random.bits32())); test "Random.bits32 (bits 20-27)" (fun () -> Int32.(to_int (shift_right (Random.bits32()) 20))); test "Random.int32 2^30 (bits 0-7)" (fun () -> Int32.to_int (Random.int32 0x40000000l)); test "Random.int32 2^30 (bits 20-27)" (fun () -> Int32.(to_int (shift_right (Random.int32 0x40000000l) 20))); test "Random.int32 (256 * p) / p" (let p = 7048673l in fun () -> Int32.(to_int (div (Random.int32 (mul 256l p)) p))); test "Random.bits64 (bits 0-7)" (fun () -> Int64.to_int (Random.bits64())); test "Random.bits64 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.bits64()) 30))); test "Random.bits64 (bits 52-59)" (fun () -> Int64.(to_int (shift_right (Random.bits64()) 52))); test "Random.int64 2^60 (bits 0-7)" (fun () -> Int64.to_int (Random.int64 0x1000000000000000L)); test "Random.int64 2^60 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.int64 0x1000000000000000L) 30))); test "Random.int64 2^60 (bits 52-59)" (fun () -> Int64.(to_int (shift_right (Random.int64 0x1000000000000000L) 52))); test "Random.int64 (256 * p) / p" (let p = 16430454264262693L in fun () -> Int64.(to_int (div (Random.int64 (mul 256L p)) p))); if Sys.int_size >= 32 then begin test "Random.full_int 2^30 (bits 0-7)" (fun () -> Random.full_int (1 lsl 30)); test "Random.full_int 2^30 (bits 22-29)" (fun () -> Random.full_int (1 lsl 30) lsr 22); test "Random.full_int (256 * p) / p" (let p = 7992689 in fun () -> Random.full_int (256 * p) / p) end; if Sys.int_size >= 63 then begin test "Random.full_int 2^60 (bits 0-7)" (fun () -> Random.full_int (1 lsl 60)); test "Random.full_int 2^60 (bits 30-37)" (fun () -> Random.full_int (1 lsl 60) lsr 30); test "Random.full_int 2^60 (bits 52-59)" (fun () -> Random.full_int (1 lsl 60) lsr 52); test "Random.full_int (256 * P) / P" (let p = Int64.to_int 17766642568158577L in fun () -> Random.full_int (256 * p) / p) end
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/lib-random/chi2.ml
ocaml
TEST
A basic chi - square test to detect simple errors in the Random module . Accumulate [ n ] samples from function [ f ] and check the chi - square . Only the low 8 bits of the result of [ f ] are sampled . Only the low 8 bits of the result of [f] are sampled. *) let chisquare n f = let r = 256 in let freq = Array.make r 0 in for i = 0 to n - 1 do let t = f () land 0xFF in freq.(t) <- freq.(t) + 1 done; let expected = float n /. float r in let t = Array.fold_left (fun s x -> let d = float x -. expected in d *. d +. s) 0.0 freq in let chi2 = t /. expected in let degfree = float r -. 1.0 in The degree of freedom is high , so we approximate as a normal distribution with mean equal to degfree and variance 2 * degfree . Four sigmas correspond to a 99.9968 % confidence interval . ( Without the approximation , the confidence interval seems to be 99.986 % . ) distribution with mean equal to degfree and variance 2 * degfree. Four sigmas correspond to a 99.9968% confidence interval. (Without the approximation, the confidence interval seems to be 99.986%.) *) chi2 <= degfree +. 4.0 *. sqrt (2.0 *. degfree) let test name f = if not (chisquare 100_000 f) then Printf.printf "%s: suspicious result\n%!" name let _ = test "Random.bits (bits 0-7)" Random.bits; test "Random.bits (bits 12-19)" (fun () -> Random.bits() lsr 12); test "Random.bits (bits 22-29)" (fun () -> Random.bits() lsr 22); test "Random.int 2^26 (bits 0-7)" (fun () -> Random.int (1 lsl 26)); test "Random.int 2^26 (bits 18-25)" (fun () -> Random.int (1 lsl 26) lsr 18); test "Random.int (256 * p) / p" (fun () -> Random.int (256 * 853187) / 853187); test "Random.float 1.0 (first 8 bits)" (fun () -> int_of_float (Random.float 1.0 *. 256.0)); test "Random.float 1.0 (next 8 bits)" (fun () -> int_of_float (Random.float 1.0 *. 65536.0)); test "Random.bits32 (bits 0-7)" (fun () -> Int32.to_int (Random.bits32())); test "Random.bits32 (bits 20-27)" (fun () -> Int32.(to_int (shift_right (Random.bits32()) 20))); test "Random.int32 2^30 (bits 0-7)" (fun () -> Int32.to_int (Random.int32 0x40000000l)); test "Random.int32 2^30 (bits 20-27)" (fun () -> Int32.(to_int (shift_right (Random.int32 0x40000000l) 20))); test "Random.int32 (256 * p) / p" (let p = 7048673l in fun () -> Int32.(to_int (div (Random.int32 (mul 256l p)) p))); test "Random.bits64 (bits 0-7)" (fun () -> Int64.to_int (Random.bits64())); test "Random.bits64 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.bits64()) 30))); test "Random.bits64 (bits 52-59)" (fun () -> Int64.(to_int (shift_right (Random.bits64()) 52))); test "Random.int64 2^60 (bits 0-7)" (fun () -> Int64.to_int (Random.int64 0x1000000000000000L)); test "Random.int64 2^60 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.int64 0x1000000000000000L) 30))); test "Random.int64 2^60 (bits 52-59)" (fun () -> Int64.(to_int (shift_right (Random.int64 0x1000000000000000L) 52))); test "Random.int64 (256 * p) / p" (let p = 16430454264262693L in fun () -> Int64.(to_int (div (Random.int64 (mul 256L p)) p))); if Sys.int_size >= 32 then begin test "Random.full_int 2^30 (bits 0-7)" (fun () -> Random.full_int (1 lsl 30)); test "Random.full_int 2^30 (bits 22-29)" (fun () -> Random.full_int (1 lsl 30) lsr 22); test "Random.full_int (256 * p) / p" (let p = 7992689 in fun () -> Random.full_int (256 * p) / p) end; if Sys.int_size >= 63 then begin test "Random.full_int 2^60 (bits 0-7)" (fun () -> Random.full_int (1 lsl 60)); test "Random.full_int 2^60 (bits 30-37)" (fun () -> Random.full_int (1 lsl 60) lsr 30); test "Random.full_int 2^60 (bits 52-59)" (fun () -> Random.full_int (1 lsl 60) lsr 52); test "Random.full_int (256 * P) / P" (let p = Int64.to_int 17766642568158577L in fun () -> Random.full_int (256 * p) / p) end
d173debbd5838e6353515693152705fec1d026f3d515e0db6eabac09561ee2af
polyfy/polylith
diff.clj
(ns polylith.clj.core.help.diff (:require [polylith.clj.core.util.interface.color :as color])) (defn help [color-mode] (str " Shows changed files since the most recent stable point in time.\n" "\n" " poly diff\n" "\n" " Internally, it executes 'git diff SHA --name-only' where SHA is the SHA-1\n" " of the first commit in the repository, or the SHA-1 of the most recent tag\n" " that matches the default pattern 'stable-*'.\n" "\n" " Stable points are normally set by the CI server or by individual developers,\n" " e.g. Lisa, with 'git tag -f stable-lisa'.\n" "\n" " The pattern can be changed in " (color/purple color-mode ":tag-patterns") " in workspace.edn.\n" "\n" " The way the latest tag is found is by taking the first line that matches the 'stable-*'\n" " regular expression, or if no match was found, the first commit in the repository.\n" " git log --pretty=format:'%H %d'\n" "\n" " Here is a compact way of listing all the commits including tags:\n" " git log --pretty=oneline")) (defn print-help [color-mode] (println (help color-mode))) (comment (print-help "dark") #__)
null
https://raw.githubusercontent.com/polyfy/polylith/febea3d8a9b30a60397594dda3cb0f25154b8d8d/components/help/src/polylith/clj/core/help/diff.clj
clojure
(ns polylith.clj.core.help.diff (:require [polylith.clj.core.util.interface.color :as color])) (defn help [color-mode] (str " Shows changed files since the most recent stable point in time.\n" "\n" " poly diff\n" "\n" " Internally, it executes 'git diff SHA --name-only' where SHA is the SHA-1\n" " of the first commit in the repository, or the SHA-1 of the most recent tag\n" " that matches the default pattern 'stable-*'.\n" "\n" " Stable points are normally set by the CI server or by individual developers,\n" " e.g. Lisa, with 'git tag -f stable-lisa'.\n" "\n" " The pattern can be changed in " (color/purple color-mode ":tag-patterns") " in workspace.edn.\n" "\n" " The way the latest tag is found is by taking the first line that matches the 'stable-*'\n" " regular expression, or if no match was found, the first commit in the repository.\n" " git log --pretty=format:'%H %d'\n" "\n" " Here is a compact way of listing all the commits including tags:\n" " git log --pretty=oneline")) (defn print-help [color-mode] (println (help color-mode))) (comment (print-help "dark") #__)
ecee62aa7ff64cb6c4349d9d9e0f2d1ac791c5f82c7a078c75f5bd9e7e8c8fe0
runtimeverification/haskell-backend
Symbol.hs
| Copyright : ( c ) Runtime Verification , 2019 - 2021 License : BSD-3 - Clause Copyright : (c) Runtime Verification, 2019-2021 License : BSD-3-Clause -} module Kore.Internal.Symbol ( Symbol (..), toSymbolOrAlias, isConstructorLike, isConstructor, isSortInjection, isTotal, isFunction, isDeclaredFunction, isNotBottom, isInjective, isMemo, isAnywhere, noEvaluators, symbolHook, constructor, total, function, injective, sortInjection, smthook, hook, klabel, symbolKywd, coerceSortInjection, -- * Re-exports module Kore.Internal.ApplicationSorts, ) where import Control.DeepSeq ( deepseq, ) import Control.Lens qualified as Lens import Data.Generics.Product import Data.Text ( Text, ) import GHC.Generics qualified as GHC import Generics.SOP qualified as SOP import Kore.AST.AstWithLocation import Kore.Attribute.Pattern.FreeVariables import Kore.Attribute.Symbol qualified as Attribute import Kore.Attribute.Synthetic import Kore.Debug import Kore.Internal.ApplicationSorts import Kore.Sort import Kore.Syntax.Application import Kore.Unparser import Prelude.Kore import Pretty qualified import SMT.AST ( SExpr, ) import SQL qualified data Symbol = Symbol { symbolConstructor :: !Id , symbolParams :: ![Sort] , symbolSorts :: !ApplicationSorts , symbolAttributes :: !Attribute.Symbol } deriving stock (Show) deriving stock (GHC.Generic) deriving anyclass (NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) instance Eq Symbol where (==) a b = on (==) symbolConstructor a b && on (==) symbolParams a b # INLINE (= =) # instance Ord Symbol where compare a b = on compare symbolConstructor a b <> on compare symbolParams a b instance Hashable Symbol where hashWithSalt salt Symbol{symbolConstructor, symbolParams} = salt `hashWithSalt` symbolConstructor `hashWithSalt` symbolParams instance Unparse Symbol where unparse Symbol{symbolConstructor, symbolParams} = unparse symbolConstructor <> parameters symbolParams unparse2 Symbol{symbolConstructor} = unparse2 symbolConstructor instance From Symbol SymbolOrAlias where from = toSymbolOrAlias instance Ord variable => Synthetic (FreeVariables variable) (Application Symbol) where synthetic = fold # INLINE synthetic # instance Synthetic Sort (Application Symbol) where synthetic application = resultSort & deepseq (matchSorts operandSorts children) where Application{applicationSymbolOrAlias = symbol} = application Application{applicationChildren = children} = application Symbol{symbolSorts} = symbol resultSort = applicationSortsResult symbolSorts operandSorts = applicationSortsOperands symbolSorts instance SQL.Column Symbol where defineColumn = SQL.defineTextColumn toColumn = SQL.toColumn . Pretty.renderText . Pretty.layoutOneLine . unparse instance AstWithLocation Symbol where locationFromAst = locationFromAst . symbolConstructor toSymbolOrAlias :: Symbol -> SymbolOrAlias toSymbolOrAlias symbol = SymbolOrAlias { symbolOrAliasConstructor = symbolConstructor symbol , symbolOrAliasParams = symbolParams symbol } | Is a symbol constructor - like ? A symbol @sigma@ is constructor - like if whenever we have the following * Context[y ] is not simplifiable to a pattern without y * sigma ( ... , x , ... ) ! = bottom then Context[sigma ( ... , x , ... ) ] can not be simplified to either x or something that does not contain x as a free variable . Note that constructors and sort injection are natural candidates for constructor - like patterns . Builtins like ' element ' ( for sets , lists and maps ) are also good candidates for constructor - like symbols . Builtins like ' concat ' need an additional condition , i.e. that the arguments are not .Map . A symbol @sigma@ is constructor-like if whenever we have the following * Context[y] is not simplifiable to a pattern without y * sigma(..., x, ...) != bottom then Context[sigma(..., x, ...)] cannot be simplified to either x or something that does not contain x as a free variable. Note that constructors and sort injection are natural candidates for constructor-like patterns. Builtins like 'element' (for sets, lists and maps) are also good candidates for constructor-like symbols. Builtins like 'concat' need an additional condition, i.e. that the arguments are not .Map. -} isConstructorLike :: Symbol -> Bool isConstructorLike = Attribute.isConstructorLike . symbolAttributes isConstructor :: Symbol -> Bool isConstructor = Attribute.isConstructor . Attribute.constructor . symbolAttributes isSortInjection :: Symbol -> Bool isSortInjection = Attribute.isSortInjection . Attribute.sortInjection . symbolAttributes isInjective :: Symbol -> Bool isInjective = Attribute.isInjective . symbolAttributes isTotal :: Symbol -> Bool isTotal = Attribute.isTotal . symbolAttributes isFunction :: Symbol -> Bool isFunction = Attribute.isFunction . symbolAttributes isDeclaredFunction :: Symbol -> Bool isDeclaredFunction = Attribute.isDeclaredFunction . Attribute.function . symbolAttributes isNotBottom :: Symbol -> Bool isNotBottom = Attribute.isNotBottom . symbolAttributes isMemo :: Symbol -> Bool isMemo = Attribute.isMemo . Attribute.memo . symbolAttributes isAnywhere :: Symbol -> Bool isAnywhere = Attribute.isAnywhere . Attribute.anywhere . symbolAttributes noEvaluators :: Symbol -> Bool noEvaluators = Attribute.hasNoEvaluators . Attribute.noEvaluators . symbolAttributes symbolHook :: Symbol -> Attribute.Hook symbolHook = Attribute.hook . symbolAttributes constructor :: Symbol -> Symbol constructor = Lens.set (typed @Attribute.Symbol . typed @Attribute.Constructor) Attribute.Constructor{isConstructor = True} total :: Symbol -> Symbol total = Lens.set (typed @Attribute.Symbol . typed @Attribute.Total) Attribute.Total{isDeclaredTotal = True} function :: Symbol -> Symbol function = Lens.set (typed @Attribute.Symbol . typed @Attribute.Function) Attribute.Function{isDeclaredFunction = True} injective :: Symbol -> Symbol injective = Lens.set (typed @Attribute.Symbol . typed @Attribute.Injective) Attribute.Injective{isDeclaredInjective = True} sortInjection :: Symbol -> Symbol sortInjection = Lens.set (typed @Attribute.Symbol . typed @Attribute.SortInjection) Attribute.SortInjection{isSortInjection = True} smthook :: SExpr -> Symbol -> Symbol smthook sExpr = Lens.set (typed @Attribute.Symbol . typed @Attribute.Smthook) Attribute.Smthook{getSmthook = Just sExpr} hook :: Text -> Symbol -> Symbol hook name = Lens.set (typed @Attribute.Symbol . typed @Attribute.Hook) Attribute.Hook{getHook = Just name} klabel :: Text -> Symbol -> Symbol klabel name = Lens.set (typed @Attribute.Symbol . typed @Attribute.Klabel) Attribute.Klabel{getKlabel = Just name} symbolKywd :: Symbol -> Symbol symbolKywd = Lens.set (typed @Attribute.Symbol . typed @Attribute.SymbolKywd) Attribute.SymbolKywd{isSymbolKywd = True} {- | Coerce a sort injection symbol's source and target sorts. Use @coerceSortInjection@ to update the internal representation of a sort injection 'Symbol' when evaluating or simplifying sort injections. -} coerceSortInjection :: -- | Original sort injection symbol Symbol -> -- | New source sort Sort -> -- | New target sort Sort -> Symbol coerceSortInjection injectionSymbol sourceSort targetSort = injectionSymbol { symbolParams = [sourceSort, targetSort] , symbolSorts = applicationSorts [sourceSort] targetSort }
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/93a705112305a2d7e084e98dca93ec33e0d661d5/kore/src/Kore/Internal/Symbol.hs
haskell
* Re-exports | Coerce a sort injection symbol's source and target sorts. Use @coerceSortInjection@ to update the internal representation of a sort injection 'Symbol' when evaluating or simplifying sort injections. | Original sort injection symbol | New source sort | New target sort
| Copyright : ( c ) Runtime Verification , 2019 - 2021 License : BSD-3 - Clause Copyright : (c) Runtime Verification, 2019-2021 License : BSD-3-Clause -} module Kore.Internal.Symbol ( Symbol (..), toSymbolOrAlias, isConstructorLike, isConstructor, isSortInjection, isTotal, isFunction, isDeclaredFunction, isNotBottom, isInjective, isMemo, isAnywhere, noEvaluators, symbolHook, constructor, total, function, injective, sortInjection, smthook, hook, klabel, symbolKywd, coerceSortInjection, module Kore.Internal.ApplicationSorts, ) where import Control.DeepSeq ( deepseq, ) import Control.Lens qualified as Lens import Data.Generics.Product import Data.Text ( Text, ) import GHC.Generics qualified as GHC import Generics.SOP qualified as SOP import Kore.AST.AstWithLocation import Kore.Attribute.Pattern.FreeVariables import Kore.Attribute.Symbol qualified as Attribute import Kore.Attribute.Synthetic import Kore.Debug import Kore.Internal.ApplicationSorts import Kore.Sort import Kore.Syntax.Application import Kore.Unparser import Prelude.Kore import Pretty qualified import SMT.AST ( SExpr, ) import SQL qualified data Symbol = Symbol { symbolConstructor :: !Id , symbolParams :: ![Sort] , symbolSorts :: !ApplicationSorts , symbolAttributes :: !Attribute.Symbol } deriving stock (Show) deriving stock (GHC.Generic) deriving anyclass (NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) instance Eq Symbol where (==) a b = on (==) symbolConstructor a b && on (==) symbolParams a b # INLINE (= =) # instance Ord Symbol where compare a b = on compare symbolConstructor a b <> on compare symbolParams a b instance Hashable Symbol where hashWithSalt salt Symbol{symbolConstructor, symbolParams} = salt `hashWithSalt` symbolConstructor `hashWithSalt` symbolParams instance Unparse Symbol where unparse Symbol{symbolConstructor, symbolParams} = unparse symbolConstructor <> parameters symbolParams unparse2 Symbol{symbolConstructor} = unparse2 symbolConstructor instance From Symbol SymbolOrAlias where from = toSymbolOrAlias instance Ord variable => Synthetic (FreeVariables variable) (Application Symbol) where synthetic = fold # INLINE synthetic # instance Synthetic Sort (Application Symbol) where synthetic application = resultSort & deepseq (matchSorts operandSorts children) where Application{applicationSymbolOrAlias = symbol} = application Application{applicationChildren = children} = application Symbol{symbolSorts} = symbol resultSort = applicationSortsResult symbolSorts operandSorts = applicationSortsOperands symbolSorts instance SQL.Column Symbol where defineColumn = SQL.defineTextColumn toColumn = SQL.toColumn . Pretty.renderText . Pretty.layoutOneLine . unparse instance AstWithLocation Symbol where locationFromAst = locationFromAst . symbolConstructor toSymbolOrAlias :: Symbol -> SymbolOrAlias toSymbolOrAlias symbol = SymbolOrAlias { symbolOrAliasConstructor = symbolConstructor symbol , symbolOrAliasParams = symbolParams symbol } | Is a symbol constructor - like ? A symbol @sigma@ is constructor - like if whenever we have the following * Context[y ] is not simplifiable to a pattern without y * sigma ( ... , x , ... ) ! = bottom then Context[sigma ( ... , x , ... ) ] can not be simplified to either x or something that does not contain x as a free variable . Note that constructors and sort injection are natural candidates for constructor - like patterns . Builtins like ' element ' ( for sets , lists and maps ) are also good candidates for constructor - like symbols . Builtins like ' concat ' need an additional condition , i.e. that the arguments are not .Map . A symbol @sigma@ is constructor-like if whenever we have the following * Context[y] is not simplifiable to a pattern without y * sigma(..., x, ...) != bottom then Context[sigma(..., x, ...)] cannot be simplified to either x or something that does not contain x as a free variable. Note that constructors and sort injection are natural candidates for constructor-like patterns. Builtins like 'element' (for sets, lists and maps) are also good candidates for constructor-like symbols. Builtins like 'concat' need an additional condition, i.e. that the arguments are not .Map. -} isConstructorLike :: Symbol -> Bool isConstructorLike = Attribute.isConstructorLike . symbolAttributes isConstructor :: Symbol -> Bool isConstructor = Attribute.isConstructor . Attribute.constructor . symbolAttributes isSortInjection :: Symbol -> Bool isSortInjection = Attribute.isSortInjection . Attribute.sortInjection . symbolAttributes isInjective :: Symbol -> Bool isInjective = Attribute.isInjective . symbolAttributes isTotal :: Symbol -> Bool isTotal = Attribute.isTotal . symbolAttributes isFunction :: Symbol -> Bool isFunction = Attribute.isFunction . symbolAttributes isDeclaredFunction :: Symbol -> Bool isDeclaredFunction = Attribute.isDeclaredFunction . Attribute.function . symbolAttributes isNotBottom :: Symbol -> Bool isNotBottom = Attribute.isNotBottom . symbolAttributes isMemo :: Symbol -> Bool isMemo = Attribute.isMemo . Attribute.memo . symbolAttributes isAnywhere :: Symbol -> Bool isAnywhere = Attribute.isAnywhere . Attribute.anywhere . symbolAttributes noEvaluators :: Symbol -> Bool noEvaluators = Attribute.hasNoEvaluators . Attribute.noEvaluators . symbolAttributes symbolHook :: Symbol -> Attribute.Hook symbolHook = Attribute.hook . symbolAttributes constructor :: Symbol -> Symbol constructor = Lens.set (typed @Attribute.Symbol . typed @Attribute.Constructor) Attribute.Constructor{isConstructor = True} total :: Symbol -> Symbol total = Lens.set (typed @Attribute.Symbol . typed @Attribute.Total) Attribute.Total{isDeclaredTotal = True} function :: Symbol -> Symbol function = Lens.set (typed @Attribute.Symbol . typed @Attribute.Function) Attribute.Function{isDeclaredFunction = True} injective :: Symbol -> Symbol injective = Lens.set (typed @Attribute.Symbol . typed @Attribute.Injective) Attribute.Injective{isDeclaredInjective = True} sortInjection :: Symbol -> Symbol sortInjection = Lens.set (typed @Attribute.Symbol . typed @Attribute.SortInjection) Attribute.SortInjection{isSortInjection = True} smthook :: SExpr -> Symbol -> Symbol smthook sExpr = Lens.set (typed @Attribute.Symbol . typed @Attribute.Smthook) Attribute.Smthook{getSmthook = Just sExpr} hook :: Text -> Symbol -> Symbol hook name = Lens.set (typed @Attribute.Symbol . typed @Attribute.Hook) Attribute.Hook{getHook = Just name} klabel :: Text -> Symbol -> Symbol klabel name = Lens.set (typed @Attribute.Symbol . typed @Attribute.Klabel) Attribute.Klabel{getKlabel = Just name} symbolKywd :: Symbol -> Symbol symbolKywd = Lens.set (typed @Attribute.Symbol . typed @Attribute.SymbolKywd) Attribute.SymbolKywd{isSymbolKywd = True} coerceSortInjection :: Symbol -> Sort -> Sort -> Symbol coerceSortInjection injectionSymbol sourceSort targetSort = injectionSymbol { symbolParams = [sourceSort, targetSort] , symbolSorts = applicationSorts [sourceSort] targetSort }
ee67a6814b0b4cca39bf74f30423b4bbb6b61e8bc36bcaad19045af522641645
PLTools/GT
plugin_intf.ml
* Base class type that all trait should follow . For single type declaration [ type ( ' a , ' b , ... ) typ = ... ] plugin generate a { i plugin class } called [ traitnname_typ_t ] and a { i transformation function } called [ traitname_t ] . Generated transformation functions can make use of inherited attribute for type parameter ( which is being generated by method { ! method : typ_g#inh_of_param } ) or simply ignore it . For example , transformation function for type parameter [ ' a ] can have types either [ ' a - > ' sa ] ( see plugins { ! Show } and { ! as examples ) or [ ' ia - > ' a - > ' sa ] . For single type declaration [ type ('a, 'b, ...) typ = ... ] plugin generate a {i plugin class} called [traitnname_typ_t] and a {i transformation function} called [traitname_t]. Generated transformation functions can make use of inherited attribute for type parameter (which is being generated by method {!method:typ_g#inh_of_param}) or simply ignore it. For example, transformation function for type parameter ['a] can have types either ['a -> 'sa] (see plugins {!Show} and {!Gmap} as examples) or ['ia -> 'a -> 'sa]. *) (** A type that stores additional arguments passed to each plugin. *) type plugin_args = (Ppxlib.longident * Ppxlib.expression) list (** Base class type for all plugins. Is parametrized by output AST types for convenience. All plugins receive input data as OCaml AST and return pieces specific for backend. *) class virtual ['loc, 'exp, 'typ, 'type_arg, 'ce, 'ctf, 'cf, 'str, 'sign, 'pat] typ_g = object (** {1 Methods that are specific for a concrete plugin implementation } *) (* They are very likely will need to be implemented when new plugin is added. *) (** Name of a trait (and of plugin too). It is used for constructing new classes and * functions related to plugin. *) method virtual trait_name : string (** Inherited attribute for whole type declaration. Is is defined by plugin kind. *) method virtual inh_of_main : loc:'loc -> Ppxlib.type_declaration -> 'typ (** Synthesized attribute for whole type declaration. Is is defined by plugin kind. *) method virtual syn_of_main : loc:'loc -> ?in_class:bool -> Ppxlib.type_declaration -> 'typ (** [syn_of_param ~loc name] constructs synthethized attribute for type paramter [name]. *) method virtual syn_of_param : loc:'loc -> string -> 'typ (** [inh_of_param ~loc tdecl name ] constructs inherited attribute for type parameter [name]. *) method virtual inh_of_param : loc:'loc -> Ppxlib.type_declaration -> string -> 'typ (** The parameters that the plugin class will have in its definition. * Add ['extra] manually if needed. *) method virtual plugin_class_params : loc:'loc -> Ppxlib.core_type list -> typname:string -> 'typ list (** Arguments of inherit class field that will be generated using the types applied in the RHS of type definition. *) method virtual alias_inherit_type_params : loc:'loc -> Ppxlib.type_declaration -> Ppxlib.core_type list -> 'typ list (* These methods will be implemented in plugin.ml *) (** Adds a few extra members to a plugin class. Could be some constraints that are difficult to add in place where type parameters are declared. *) method virtual extra_class_sig_members : Ppxlib.type_declaration -> 'ctf list (** The same as [extra_class_sig_members] but for structures. *) method virtual extra_class_str_members : Ppxlib.type_declaration -> 'cf list (** {1 Methods that are specific for all plugins and unlikely will need to be override } *) (** Generate signature items for single type definition. *) method virtual do_single_sig : loc:'loc -> is_rec:bool -> Ppxlib.type_declaration -> 'sign list (** Generate structure items for single type definition. *) method virtual do_single : loc:'loc -> is_rec:bool -> Ppxlib.type_declaration -> 'str list (** Generate transformation expression from specified core_type. *) method virtual do_typ_gen : loc:'loc -> mutual_decls:Ppxlib.type_declaration list -> is_self_rec:(Ppxlib.core_type -> [ `Nonrecursive | `Nonregular | `Regular ]) -> Ppxlib.type_declaration -> Ppxlib.core_type -> 'exp (** Generate name for transformation function. *) method virtual make_trans_function_name : Ppxlib.type_declaration -> string (** Generate type of a transformation function. *) method virtual make_trans_function_typ : loc:'loc -> Ppxlib.type_declaration -> 'typ (** Generate structure items for mutally recursive type declarations. *) method virtual do_mutuals : loc:'loc -> is_rec:bool -> Ppxlib.type_declaration list -> 'str list method virtual do_mutuals_sigs : loc:'loc -> is_rec:bool -> 'sign list method virtual need_inh_attr : bool method virtual eta_and_exp : center:'exp -> Ppxlib.type_declaration -> 'exp method virtual prepare_fa_args : 'a. loc:'loc -> (loc:'loc -> flg:Ppxlib.rec_flag -> pat:'pat -> expr:'exp -> 'a -> 'a) -> Ppxlib.type_declaration -> 'pat list * ('a -> 'a) method virtual make_final_trans_function_typ : loc:'loc -> Ppxlib.type_declaration -> 'typ end (** Functor that takes AST construction functions for a specific backend and constructs a plugin object. *) module Make (AstHelpers : GTHELPERS_sig.S) = struct open AstHelpers class virtual g = object inherit [loc, Exp.t, Typ.t, type_arg, Cl.t, Ctf.t, Cf.t, Str.t, Sig.t, Pat.t] typ_g end end module type MAKE = functor (AstHelpers : GTHELPERS_sig.S) -> sig open AstHelpers val trait_name : string val create : plugin_args -> bool * Ppxlib.type_declaration list -> (loc, Exp.t, Typ.t, type_arg, Cl.t, Ctf.t, Cf.t, Str.t, Sig.t, Pat.t) typ_g end
null
https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/common/plugin_intf.ml
ocaml
* A type that stores additional arguments passed to each plugin. * Base class type for all plugins. Is parametrized by output AST types for convenience. All plugins receive input data as OCaml AST and return pieces specific for backend. * {1 Methods that are specific for a concrete plugin implementation } They are very likely will need to be implemented when new plugin is added. * Name of a trait (and of plugin too). It is used for constructing new classes and * functions related to plugin. * Inherited attribute for whole type declaration. Is is defined by plugin kind. * Synthesized attribute for whole type declaration. Is is defined by plugin kind. * [syn_of_param ~loc name] constructs synthethized attribute for type paramter [name]. * [inh_of_param ~loc tdecl name ] constructs inherited attribute for type parameter [name]. * The parameters that the plugin class will have in its definition. * Add ['extra] manually if needed. * Arguments of inherit class field that will be generated using the types applied in the RHS of type definition. These methods will be implemented in plugin.ml * Adds a few extra members to a plugin class. Could be some constraints that are difficult to add in place where type parameters are declared. * The same as [extra_class_sig_members] but for structures. * {1 Methods that are specific for all plugins and unlikely will need to be override } * Generate signature items for single type definition. * Generate structure items for single type definition. * Generate transformation expression from specified core_type. * Generate name for transformation function. * Generate type of a transformation function. * Generate structure items for mutally recursive type declarations. * Functor that takes AST construction functions for a specific backend and constructs a plugin object.
* Base class type that all trait should follow . For single type declaration [ type ( ' a , ' b , ... ) typ = ... ] plugin generate a { i plugin class } called [ traitnname_typ_t ] and a { i transformation function } called [ traitname_t ] . Generated transformation functions can make use of inherited attribute for type parameter ( which is being generated by method { ! method : typ_g#inh_of_param } ) or simply ignore it . For example , transformation function for type parameter [ ' a ] can have types either [ ' a - > ' sa ] ( see plugins { ! Show } and { ! as examples ) or [ ' ia - > ' a - > ' sa ] . For single type declaration [ type ('a, 'b, ...) typ = ... ] plugin generate a {i plugin class} called [traitnname_typ_t] and a {i transformation function} called [traitname_t]. Generated transformation functions can make use of inherited attribute for type parameter (which is being generated by method {!method:typ_g#inh_of_param}) or simply ignore it. For example, transformation function for type parameter ['a] can have types either ['a -> 'sa] (see plugins {!Show} and {!Gmap} as examples) or ['ia -> 'a -> 'sa]. *) type plugin_args = (Ppxlib.longident * Ppxlib.expression) list class virtual ['loc, 'exp, 'typ, 'type_arg, 'ce, 'ctf, 'cf, 'str, 'sign, 'pat] typ_g = object method virtual trait_name : string method virtual inh_of_main : loc:'loc -> Ppxlib.type_declaration -> 'typ method virtual syn_of_main : loc:'loc -> ?in_class:bool -> Ppxlib.type_declaration -> 'typ method virtual syn_of_param : loc:'loc -> string -> 'typ method virtual inh_of_param : loc:'loc -> Ppxlib.type_declaration -> string -> 'typ method virtual plugin_class_params : loc:'loc -> Ppxlib.core_type list -> typname:string -> 'typ list method virtual alias_inherit_type_params : loc:'loc -> Ppxlib.type_declaration -> Ppxlib.core_type list -> 'typ list method virtual extra_class_sig_members : Ppxlib.type_declaration -> 'ctf list method virtual extra_class_str_members : Ppxlib.type_declaration -> 'cf list method virtual do_single_sig : loc:'loc -> is_rec:bool -> Ppxlib.type_declaration -> 'sign list method virtual do_single : loc:'loc -> is_rec:bool -> Ppxlib.type_declaration -> 'str list method virtual do_typ_gen : loc:'loc -> mutual_decls:Ppxlib.type_declaration list -> is_self_rec:(Ppxlib.core_type -> [ `Nonrecursive | `Nonregular | `Regular ]) -> Ppxlib.type_declaration -> Ppxlib.core_type -> 'exp method virtual make_trans_function_name : Ppxlib.type_declaration -> string method virtual make_trans_function_typ : loc:'loc -> Ppxlib.type_declaration -> 'typ method virtual do_mutuals : loc:'loc -> is_rec:bool -> Ppxlib.type_declaration list -> 'str list method virtual do_mutuals_sigs : loc:'loc -> is_rec:bool -> 'sign list method virtual need_inh_attr : bool method virtual eta_and_exp : center:'exp -> Ppxlib.type_declaration -> 'exp method virtual prepare_fa_args : 'a. loc:'loc -> (loc:'loc -> flg:Ppxlib.rec_flag -> pat:'pat -> expr:'exp -> 'a -> 'a) -> Ppxlib.type_declaration -> 'pat list * ('a -> 'a) method virtual make_final_trans_function_typ : loc:'loc -> Ppxlib.type_declaration -> 'typ end module Make (AstHelpers : GTHELPERS_sig.S) = struct open AstHelpers class virtual g = object inherit [loc, Exp.t, Typ.t, type_arg, Cl.t, Ctf.t, Cf.t, Str.t, Sig.t, Pat.t] typ_g end end module type MAKE = functor (AstHelpers : GTHELPERS_sig.S) -> sig open AstHelpers val trait_name : string val create : plugin_args -> bool * Ppxlib.type_declaration list -> (loc, Exp.t, Typ.t, type_arg, Cl.t, Ctf.t, Cf.t, Str.t, Sig.t, Pat.t) typ_g end
0d2ca8d72ef13f52d7c3a8ffeaf3ebb0eb4f5ec025f4e4748174e9f339018179
ucsd-progsys/liquidhaskell
BinahUpdateLib.hs
{-@ LIQUID "--expect-any-error" @-} {-@ LIQUID "--no-adt" @-} {-@ LIQUID "--exact-data-con" @-} {-@ LIQUID "--higherorder" @-} {-@ LIQUID "--no-termination" @-} {-@ LIQUID "--ple" @-} # LANGUAGE ExistentialQuantification , KindSignatures , TypeFamilies , GADTs # module BinahUpdateLib where class PersistEntity record where data EntityField record typ :: * instance PersistEntity Blob where @ data EntityField Blob typ where BinahUpdateLib . BlobYVal : : EntityField { v : _ | True } BinahUpdateLib . BlobXVal : : EntityField { v : _ | v > = 10 } @ BinahUpdateLib.BlobYVal :: EntityField Blob {v:_ | True} BinahUpdateLib.BlobXVal :: EntityField Blob {v:_ | v >= 10} @-} data EntityField Blob typ where BlobXVal :: EntityField Blob Int BlobYVal :: EntityField Blob Int @ data = B { xVal : : { v : Int | v > = 0 } , : : Int } @ data Blob = B { xVal :: Int, yVal :: Int } data Update record typ = Update { updateField :: EntityField record typ , updateValue :: typ } createUpdate :: EntityField record a -> a -> Update record a createUpdate field value = Update { updateField = field , updateValue = value } testUpdateQuery :: () -> Update Blob Int toggle to 80 to be SAFE
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/ple/neg/BinahUpdateLib.hs
haskell
@ LIQUID "--expect-any-error" @ @ LIQUID "--no-adt" @ @ LIQUID "--exact-data-con" @ @ LIQUID "--higherorder" @ @ LIQUID "--no-termination" @ @ LIQUID "--ple" @
# LANGUAGE ExistentialQuantification , KindSignatures , TypeFamilies , GADTs # module BinahUpdateLib where class PersistEntity record where data EntityField record typ :: * instance PersistEntity Blob where @ data EntityField Blob typ where BinahUpdateLib . BlobYVal : : EntityField { v : _ | True } BinahUpdateLib . BlobXVal : : EntityField { v : _ | v > = 10 } @ BinahUpdateLib.BlobYVal :: EntityField Blob {v:_ | True} BinahUpdateLib.BlobXVal :: EntityField Blob {v:_ | v >= 10} @-} data EntityField Blob typ where BlobXVal :: EntityField Blob Int BlobYVal :: EntityField Blob Int @ data = B { xVal : : { v : Int | v > = 0 } , : : Int } @ data Blob = B { xVal :: Int, yVal :: Int } data Update record typ = Update { updateField :: EntityField record typ , updateValue :: typ } createUpdate :: EntityField record a -> a -> Update record a createUpdate field value = Update { updateField = field , updateValue = value } testUpdateQuery :: () -> Update Blob Int toggle to 80 to be SAFE
102e77a01db3cb83dea4a68be9f06102ffb72b53ca639d9a0723b2208a128b88
johnlawrenceaspden/hobby-code
scrapcode.clj
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (comment (def starts (map (fn[tile][[tile 0]]) tiles)) (map ptilelist starts) (count starts) (def it1 (mapcat tilelist->longertilelists starts)) (map ptilelist it1) (count it1) (def it2 (mapcat tilelist->longertilelists it1)) (count it2) (map ptilelist it2) (def it3 (mapcat tilelist->longertilelists it2)) (count it3) (map ptilelist it3) (def it4 (mapcat tilelist->longertilelists it3)) (count it4) (map ptilelist it4) (def it5 (mapcat tilelist->longertilelists it4)) (count it5) (map ptilelist it5) (def it6 (mapcat tilelist->longertilelists it5)) (count it6) (map ptilelist it6) (def it7 (mapcat tilelist->longertilelists it6)) (count it7) (map ptilelist it7) (def it8 (mapcat tilelist->longertilelists it7)) (count it8) (map ptilelist it8) (def it9 (mapcat tilelist->longertilelists it8)) (count it9) (map ptilelist it9) (def it10 (mapcat tilelist->longertilelists it9)) (count it10) (map ptilelist it10) (def it11 (mapcat tilelist->longertilelists it10)) (count it11) (map ptilelist it10) (def i0 [[tile0 0]]) (def ic (drop 1 tiles)) (def candidates (for [tile ic rotation (range 6)] [tile rotation])) (def compat (filter (fn [[tile rotation]](check-consistency i0 tile rotation numericadjlist)) candidates)) (count compat) (map (fn [[tile rotation]] [(tile :number) rotation]) compat) (set tiles) (map (fn[tile] (map #(check-consistency i0 tile % numericadjlist) (range 6))) tiles) (check-consistency i0 tile2 3 numericadjlist) (check-consistency i0 tile5 3 numericadjlist) (check-consistency i0 tile7 3 numericadjlist) (check-consistency i0 tile9 3 numericadjlist) (def i1 [[tile0 0][tile2 3]]) (def i2 [[tile0 0][tile5 3]]) (def i3 [[tile0 0][tile7 3]]) (def i4 [[tile0 0][tile9 3]]) (map (fn[tile] (map #(check-consistency i1 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i2 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i3 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i4 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i5 tile % numericadjlist) (range 6))) tiles) )
null
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/scrapcode.clj
clojure
(comment (def starts (map (fn[tile][[tile 0]]) tiles)) (map ptilelist starts) (count starts) (def it1 (mapcat tilelist->longertilelists starts)) (map ptilelist it1) (count it1) (def it2 (mapcat tilelist->longertilelists it1)) (count it2) (map ptilelist it2) (def it3 (mapcat tilelist->longertilelists it2)) (count it3) (map ptilelist it3) (def it4 (mapcat tilelist->longertilelists it3)) (count it4) (map ptilelist it4) (def it5 (mapcat tilelist->longertilelists it4)) (count it5) (map ptilelist it5) (def it6 (mapcat tilelist->longertilelists it5)) (count it6) (map ptilelist it6) (def it7 (mapcat tilelist->longertilelists it6)) (count it7) (map ptilelist it7) (def it8 (mapcat tilelist->longertilelists it7)) (count it8) (map ptilelist it8) (def it9 (mapcat tilelist->longertilelists it8)) (count it9) (map ptilelist it9) (def it10 (mapcat tilelist->longertilelists it9)) (count it10) (map ptilelist it10) (def it11 (mapcat tilelist->longertilelists it10)) (count it11) (map ptilelist it10) (def i0 [[tile0 0]]) (def ic (drop 1 tiles)) (def candidates (for [tile ic rotation (range 6)] [tile rotation])) (def compat (filter (fn [[tile rotation]](check-consistency i0 tile rotation numericadjlist)) candidates)) (count compat) (map (fn [[tile rotation]] [(tile :number) rotation]) compat) (set tiles) (map (fn[tile] (map #(check-consistency i0 tile % numericadjlist) (range 6))) tiles) (check-consistency i0 tile2 3 numericadjlist) (check-consistency i0 tile5 3 numericadjlist) (check-consistency i0 tile7 3 numericadjlist) (check-consistency i0 tile9 3 numericadjlist) (def i1 [[tile0 0][tile2 3]]) (def i2 [[tile0 0][tile5 3]]) (def i3 [[tile0 0][tile7 3]]) (def i4 [[tile0 0][tile9 3]]) (map (fn[tile] (map #(check-consistency i1 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i2 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i3 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i4 tile % numericadjlist) (range 6))) tiles) (map (fn[tile] (map #(check-consistency i5 tile % numericadjlist) (range 6))) tiles) )
8083081ac907b03833f6ed3aeebd8e472527c5af9e0ed20c4ed0a6b5fbec5c7c
ucsd-progsys/liquidhaskell
T2096.hs
# LANGUAGE KindSignatures # # LANGUAGE DataKinds # # LANGUAGE TypeOperators # {-# LANGUAGE GADTs #-} @ embed GHC.Natural . Natural as int @ {-@ LIQUID "--no-totality" @-} module T2096 where import Prelude import GHC.TypeLits import GHC.Natural import Unsafe.Coerce -- See -progsys/liquidhaskell/issues/2095 workaround :: (n1 + 1) ~ (n2 + 1) => Vec n1 a -> Vec n2 a workaround = unsafeCoerce data Vec (n :: Nat) a where Nil :: Vec 0 a Cons :: a -> Vec n a -> Vec (n + 1) a foo :: Vec n a -> Vec n a -> Vec n a foo Nil Nil = Nil foo (Cons x xs) (Cons y ys) = Cons x zs where zs = foo xs $ workaround ys foo _ _ = undefined
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/284c2ad4e9b87bcb4729ae3f228043b22646ae46/tests/pos/T2096.hs
haskell
# LANGUAGE GADTs # @ LIQUID "--no-totality" @ See -progsys/liquidhaskell/issues/2095
# LANGUAGE KindSignatures # # LANGUAGE DataKinds # # LANGUAGE TypeOperators # @ embed GHC.Natural . Natural as int @ module T2096 where import Prelude import GHC.TypeLits import GHC.Natural import Unsafe.Coerce workaround :: (n1 + 1) ~ (n2 + 1) => Vec n1 a -> Vec n2 a workaround = unsafeCoerce data Vec (n :: Nat) a where Nil :: Vec 0 a Cons :: a -> Vec n a -> Vec (n + 1) a foo :: Vec n a -> Vec n a -> Vec n a foo Nil Nil = Nil foo (Cons x xs) (Cons y ys) = Cons x zs where zs = foo xs $ workaround ys foo _ _ = undefined
4177cacac2db9488d8c9d38e83cb5732b8aca81fe5259b91c182e57c4dbd70eb
bevuta/pepa
preloader.cljs
(ns pepa.preloader (:require [cljs.core.async :as async] [clojure.browser.event :as event]) (:require-macros [pepa.resources :as res] [cljs.core.async.macros :refer [go]]) (:import goog.net.ImageLoader)) (def +image-pathnames+ (res/image-resources)) (defn preload [] (go (let [loader (ImageLoader.) complete (async/chan)] (event/listen-once loader "complete" #(async/put! complete loader)) (doseq [img +image-pathnames+] (.addImage loader img img)) (.start loader) (<! complete))))
null
https://raw.githubusercontent.com/bevuta/pepa/0a9991de0fd1714515ca3def645aec30e21cd671/src-cljs/pepa/preloader.cljs
clojure
(ns pepa.preloader (:require [cljs.core.async :as async] [clojure.browser.event :as event]) (:require-macros [pepa.resources :as res] [cljs.core.async.macros :refer [go]]) (:import goog.net.ImageLoader)) (def +image-pathnames+ (res/image-resources)) (defn preload [] (go (let [loader (ImageLoader.) complete (async/chan)] (event/listen-once loader "complete" #(async/put! complete loader)) (doseq [img +image-pathnames+] (.addImage loader img img)) (.start loader) (<! complete))))
e5f44b8b73d4d6ba265871031c6c9d71de71ea201250e722837752ccf258241c
fujita-y/ypsilon
destructuring.scm
#!core Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited . ;;; See LICENSE file for terms and conditions of use. (library (core destructuring) (export destructuring-match destructuring-bind) (import (core primitives) (core lists) (core syntax-case)) (define ca---r (make-core-hashtable)) (define cd---r (make-core-hashtable)) (define car+ (lambda (expr) (cond ((and (pair? expr) (core-hashtable-ref ca---r (car expr) #f)) => (lambda (a) (cons a (cdr expr)))) (else (list 'car expr))))) (define cdr+ (lambda (expr) (cond ((and (pair? expr) (core-hashtable-ref cd---r (car expr) #f)) => (lambda (a) (cons a (cdr expr)))) (else (list 'cdr expr))))) (define duplicates? (lambda (lst) (and (pair? lst) (let loop ((head (car lst)) (rest (cdr lst))) (or (memq head rest) (and (pair? rest) (loop (car rest) (cdr rest)))))))) (define ellipsis-pair? (lambda (pat) (and (pair? pat) (symbol? (car pat)) (pair? (cdr pat)) (eq? (cadr pat) '...)))) (define quoted-pair? (lambda (pat) (and (pair? pat) (eq? (car pat) 'quote) (pair? (cdr pat)) (null? (cddr pat))))) (define predicate-pair? (lambda (pat) (and (pair? pat) (eq? (car pat) '?) (pair? (cdr pat))))) (define choose-pred (lambda (pat) (cond ((or (symbol? pat) (boolean? pat) (null? pat) (char? pat) (fixnum? pat)) 'eq?) ((number? pat) 'eqv?) (else 'equal?)))) (define count-non-dotted-pattern (lambda (lst) (let loop ((lst lst) (n 0)) (cond ((pair? lst) (cond ((predicate-pair? lst) n) (else (loop (cdr lst) (+ n 1))))) (else n))))) (define memoize-ref (lambda (e mem) (cond ((assoc e (vector-ref mem 0)) => cdr) (else (let ((name (generate-temporary-symbol))) (begin (vector-set! mem 0 (cons (cons e name) (vector-ref mem 0))) name)))))) (define compile-match (lambda (ren mem pat ref match bind vars) (cond ((quoted-pair? pat) (values (cons `(,(choose-pred (cadr pat)) ,ref ',(cadr pat)) match) bind vars)) ((ellipsis-pair? pat) (cond ((null? (cddr pat)) (if (eq? (car pat) '_) (values (cons `(list? ,ref) match) bind vars) (values (cons `(list? ,ref) match) (cons ref bind) (cons (car pat) vars)))) ((or (not (pair? (cddr pat))) (predicate-pair? (cddr pat))) (if (eq? (car pat) '_) (compile-match ren mem (cddr pat) `(last-cdr ,ref) match bind vars) (compile-match ren mem (cddr pat) `(last-cdr ,ref) match (cons `(drop-last-cdr ,ref) bind) (cons (car pat) vars)))) ((pair? (cddr pat)) (let ((memoize (generate-temporary-symbol))) (cond ((null? (cdddr pat)) (let ((memoize (memoize-ref `(last-pair ,ref) mem))) (if (eq? (car pat) '_) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-pair ,ref))) match) bind vars) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-pair ,ref))) match) (cons `(drop-last-pair ,ref) bind) (cons (car pat) vars))))) (else (let ((n (- (count-non-dotted-pattern pat) 2))) (let ((memoize (memoize-ref `(last-n-pair ,n ,ref) mem))) (if (eq? (car pat) '_) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-n-pair ,n ,ref))) match) bind vars) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-n-pair ,n ,ref))) match) (cons `(drop-last-n-pair ,n ,ref) bind) (cons (car pat) vars))))))))) (else (values #f #f #f)))) ((predicate-pair? pat) (let ((renamed (or (core-hashtable-ref ren (cadr pat) #f) (generate-temporary-symbol)))) (core-hashtable-set! ren (cadr pat) renamed) (if (null? (cddr pat)) (values (cons `(,renamed ,ref) match) bind vars) (compile-match ren mem (caddr pat) ref (cons `(,renamed ,ref) match) bind vars)))) ((pair? pat) (let-values (((match2 bind2 vars2) (compile-match ren mem (car pat) (car+ ref) (cons `(pair? ,ref) match) bind vars))) (cond (match2 (compile-match ren mem (cdr pat) (cdr+ ref) match2 bind2 vars2)) (else (values #f #f #f))))) ((eq? pat '...) (values #f #f #f)) ((eq? pat '_) (values match bind vars)) ((symbol? pat) (values match (cons ref bind) (cons pat vars))) ((null? pat) (values (cons `(null? ,ref) match) bind vars)) (else (values (cons `(,(choose-pred pat) ,ref ,pat) match) bind vars))))) (define reorder-tests (lambda (lst preds) (let loop ((lst lst) (preds preds) (acc '())) (if (null? preds) (append acc lst) (let-values (((hits rest) (partition (lambda (e) (memq (car e) (car preds))) lst))) (loop rest (cdr preds) (append acc hits))))))) (define reorder (lambda (clauses) (map (lambda (clause) `(,(car clause) ,(reorder-tests (cadr clause) '((pair? and) (null?) (list?))) ,@(cddr clause))) clauses))) (define cse-length (lambda (clause1 clause2) (let loop ((n 0) (e1 (cadr clause1)) (e2 (cadr clause2))) (cond ((or (null? e1) (null? e2) (not (equal? (car e1) (car e2)))) n) (else (loop (+ n 1) (cdr e1) (cdr e2))))))) (define cse-1 (lambda (clauses current) (let* ((cs-lst (map (lambda (clause) (cond ((eq? clause current) -1) (else (cse-length clause current)))) clauses)) (cs-max (let ((lst (filter (lambda (n) (>= n 2)) cs-lst))) (cond ((null? lst) 0) (else (apply min lst)))))) (and (>= cs-max 2) (let* ((cs-tag (generate-temporary-symbol)) (clause1 (list-head (cadr current) cs-max)) (clause2 (map (lambda (clause len) (cond ((or (= len -1) (>= len cs-max)) `(,(car clause) ,(cons cs-tag (list-tail (cadr clause) cs-max)) ,@(cddr clause))) (else clause))) clauses cs-lst))) (if (symbol? (car clause1)) (append clause2 (list (list cs-tag clause1))) (cons (list cs-tag clause1) clause2))))))) (define cse (lambda (clauses) (let loop ((lst clauses)) (if (null? lst) clauses (cond ((cse-1 clauses (car lst)) => cse) (else (loop (cdr lst)))))))) (define-syntax destructuring-bind (lambda (x) (syntax-case x () ((?_ ?pat ?expr ?body ...) (let ((pat (syntax->datum #'?pat)) (datum (generate-temporary-symbol)) (ren (make-core-hashtable)) (mem (vector '()))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((not (null? (vector-ref mem 0))) (syntax-violation 'destructuring-bind "tail match not supported" x pat)) ((duplicates? vars) (syntax-violation 'destructuring-bind "duplicate variables" x pat)) (match (with-syntax ((?datum (datum->syntax #'k datum)) ((?vars ...) (map (lambda (e) (datum->syntax #'?_ e)) vars)) ((?inits ...) (map (lambda (e) (datum->syntax #'k e)) inits)) ((?body ...) (datum->syntax #'?_ (syntax->datum (syntax (?body ...)))))) (syntax (let ((?datum ?expr)) (let ((?vars ?inits) ...) ?body ...))))) (else (syntax-violation 'destructuring-bind "malformed pattern" x pat))))))))) (define-syntax destructuring-match (lambda (x) (syntax-case x () ((?_ ?expr ?clauses ...) (let ((datum (generate-temporary-symbol)) (ren (make-core-hashtable)) (mem (vector '()))) (let ((code (cse (reorder (map (lambda (clause) (syntax-case clause () ((?pat) (let ((pat (syntax->datum #'?pat))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((duplicates? vars) (syntax-violation 'destructuring-match "duplicate variables" x pat)) (match (list #f (reverse match) '() '() (syntax #t) (syntax #t))) (else (syntax-violation 'destructuring-match "malformed pattern" x pat)))))) ((?pat ?body) (let ((pat (syntax->datum #'?pat))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((duplicates? vars) (syntax-violation 'destructuring-match "duplicate variables" x pat)) (match (list #f (reverse match) vars inits (syntax ?body) (syntax #t))) (else (syntax-violation 'destructuring-match "malformed pattern" x pat)))))) ((?pat ?fender ?body) (let ((pat (syntax->datum #'?pat))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((duplicates? vars) (syntax-violation 'destructuring-match "duplicate variables" x pat)) (match (list #f (reverse match) vars inits (syntax ?body) (syntax ?fender))) (else (syntax-violation 'destructuring-match "malformed pattern" x pat)))))) (_ (syntax-violation 'destructuring-match "malformed clause" x clause)))) (syntax (?clauses ...))))))) (let-values (((shares others) (partition car code))) (let ((subexprs (map (lambda (e) `(,(car e) (and ,@(cadr e)))) shares)) (clauses (map cdr others))) (with-syntax ((?datum (datum->syntax #'k datum)) (((?pred-lhs ?pred-rhs) ...) (map (lambda (a) (list (datum->syntax #'k (cdr a)) (datum->syntax #'?_ (car a)))) (core-hashtable->alist ren))) ((?mem ...) (map (lambda (e) (datum->syntax #'k (cdr e))) (vector-ref mem 0))) ((?subexprs ...) (map (lambda (e) (datum->syntax #'k e)) subexprs)) ((?dispatch ...) (map (lambda (clause) (let-values (((tests vars inits body fender) (apply values clause))) (with-syntax (((?vars ...) (map (lambda (e) (datum->syntax #'?_ e)) vars)) ((?inits ...) (map (lambda (e) (datum->syntax #'k e)) inits)) ((?tests ...) (map (lambda (e) (datum->syntax #'k e)) tests)) (?fender (datum->syntax #'?_ (syntax->datum fender))) (?body (datum->syntax #'?_ (syntax->datum body)))) (if (eq? (syntax->datum (syntax ?fender)) #t) (syntax ((and ?tests ...) (let ((?vars ?inits) ...) ?body))) (syntax ((and ?tests ... (let ((?vars ?inits) ...) ?fender)) (let ((?vars ?inits) ...) ?body))))))) clauses))) (syntax (let ((?datum ?expr) (?pred-lhs ?pred-rhs) ... (?mem #f) ...) (let* (?subexprs ...) (cond ?dispatch ... (else #f)))))))))))))) (for-each (lambda (e) (core-hashtable-set! ca---r (car e) (cdr e))) '((car . caar) (cdr . cadr) (caar . caaar) (cadr . caadr) (cdar . cadar) (cddr . caddr) (caaar . caaaar) (caadr . caaadr) (cadar . caadar) (caddr . caaddr) (cdaar . cadaar) (cdadr . cadadr) (cddar . caddar) (cdddr . cadddr))) (for-each (lambda (e) (core-hashtable-set! cd---r (car e) (cdr e))) '((car . cdar) (cdr . cddr) (caar . cdaar) (cadr . cdadr) (cdar . cddar) (cddr . cdddr) (caaar . cdaaar) (caadr . cdaadr) (cadar . cdadar) (caddr . cdaddr) (cdaar . cddaar) (cdadr . cddadr) (cddar . cdddar) (cdddr . cddddr))) ) ;[end]
null
https://raw.githubusercontent.com/fujita-y/ypsilon/f640c9ecf98eb805de268db65316db704fb31831/stdlib/core/destructuring.scm
scheme
See LICENSE file for terms and conditions of use. [end]
#!core Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited . (library (core destructuring) (export destructuring-match destructuring-bind) (import (core primitives) (core lists) (core syntax-case)) (define ca---r (make-core-hashtable)) (define cd---r (make-core-hashtable)) (define car+ (lambda (expr) (cond ((and (pair? expr) (core-hashtable-ref ca---r (car expr) #f)) => (lambda (a) (cons a (cdr expr)))) (else (list 'car expr))))) (define cdr+ (lambda (expr) (cond ((and (pair? expr) (core-hashtable-ref cd---r (car expr) #f)) => (lambda (a) (cons a (cdr expr)))) (else (list 'cdr expr))))) (define duplicates? (lambda (lst) (and (pair? lst) (let loop ((head (car lst)) (rest (cdr lst))) (or (memq head rest) (and (pair? rest) (loop (car rest) (cdr rest)))))))) (define ellipsis-pair? (lambda (pat) (and (pair? pat) (symbol? (car pat)) (pair? (cdr pat)) (eq? (cadr pat) '...)))) (define quoted-pair? (lambda (pat) (and (pair? pat) (eq? (car pat) 'quote) (pair? (cdr pat)) (null? (cddr pat))))) (define predicate-pair? (lambda (pat) (and (pair? pat) (eq? (car pat) '?) (pair? (cdr pat))))) (define choose-pred (lambda (pat) (cond ((or (symbol? pat) (boolean? pat) (null? pat) (char? pat) (fixnum? pat)) 'eq?) ((number? pat) 'eqv?) (else 'equal?)))) (define count-non-dotted-pattern (lambda (lst) (let loop ((lst lst) (n 0)) (cond ((pair? lst) (cond ((predicate-pair? lst) n) (else (loop (cdr lst) (+ n 1))))) (else n))))) (define memoize-ref (lambda (e mem) (cond ((assoc e (vector-ref mem 0)) => cdr) (else (let ((name (generate-temporary-symbol))) (begin (vector-set! mem 0 (cons (cons e name) (vector-ref mem 0))) name)))))) (define compile-match (lambda (ren mem pat ref match bind vars) (cond ((quoted-pair? pat) (values (cons `(,(choose-pred (cadr pat)) ,ref ',(cadr pat)) match) bind vars)) ((ellipsis-pair? pat) (cond ((null? (cddr pat)) (if (eq? (car pat) '_) (values (cons `(list? ,ref) match) bind vars) (values (cons `(list? ,ref) match) (cons ref bind) (cons (car pat) vars)))) ((or (not (pair? (cddr pat))) (predicate-pair? (cddr pat))) (if (eq? (car pat) '_) (compile-match ren mem (cddr pat) `(last-cdr ,ref) match bind vars) (compile-match ren mem (cddr pat) `(last-cdr ,ref) match (cons `(drop-last-cdr ,ref) bind) (cons (car pat) vars)))) ((pair? (cddr pat)) (let ((memoize (generate-temporary-symbol))) (cond ((null? (cdddr pat)) (let ((memoize (memoize-ref `(last-pair ,ref) mem))) (if (eq? (car pat) '_) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-pair ,ref))) match) bind vars) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-pair ,ref))) match) (cons `(drop-last-pair ,ref) bind) (cons (car pat) vars))))) (else (let ((n (- (count-non-dotted-pattern pat) 2))) (let ((memoize (memoize-ref `(last-n-pair ,n ,ref) mem))) (if (eq? (car pat) '_) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-n-pair ,n ,ref))) match) bind vars) (compile-match ren mem (cddr pat) memoize (cons `(and (pair? ,ref) (set! ,memoize (last-n-pair ,n ,ref))) match) (cons `(drop-last-n-pair ,n ,ref) bind) (cons (car pat) vars))))))))) (else (values #f #f #f)))) ((predicate-pair? pat) (let ((renamed (or (core-hashtable-ref ren (cadr pat) #f) (generate-temporary-symbol)))) (core-hashtable-set! ren (cadr pat) renamed) (if (null? (cddr pat)) (values (cons `(,renamed ,ref) match) bind vars) (compile-match ren mem (caddr pat) ref (cons `(,renamed ,ref) match) bind vars)))) ((pair? pat) (let-values (((match2 bind2 vars2) (compile-match ren mem (car pat) (car+ ref) (cons `(pair? ,ref) match) bind vars))) (cond (match2 (compile-match ren mem (cdr pat) (cdr+ ref) match2 bind2 vars2)) (else (values #f #f #f))))) ((eq? pat '...) (values #f #f #f)) ((eq? pat '_) (values match bind vars)) ((symbol? pat) (values match (cons ref bind) (cons pat vars))) ((null? pat) (values (cons `(null? ,ref) match) bind vars)) (else (values (cons `(,(choose-pred pat) ,ref ,pat) match) bind vars))))) (define reorder-tests (lambda (lst preds) (let loop ((lst lst) (preds preds) (acc '())) (if (null? preds) (append acc lst) (let-values (((hits rest) (partition (lambda (e) (memq (car e) (car preds))) lst))) (loop rest (cdr preds) (append acc hits))))))) (define reorder (lambda (clauses) (map (lambda (clause) `(,(car clause) ,(reorder-tests (cadr clause) '((pair? and) (null?) (list?))) ,@(cddr clause))) clauses))) (define cse-length (lambda (clause1 clause2) (let loop ((n 0) (e1 (cadr clause1)) (e2 (cadr clause2))) (cond ((or (null? e1) (null? e2) (not (equal? (car e1) (car e2)))) n) (else (loop (+ n 1) (cdr e1) (cdr e2))))))) (define cse-1 (lambda (clauses current) (let* ((cs-lst (map (lambda (clause) (cond ((eq? clause current) -1) (else (cse-length clause current)))) clauses)) (cs-max (let ((lst (filter (lambda (n) (>= n 2)) cs-lst))) (cond ((null? lst) 0) (else (apply min lst)))))) (and (>= cs-max 2) (let* ((cs-tag (generate-temporary-symbol)) (clause1 (list-head (cadr current) cs-max)) (clause2 (map (lambda (clause len) (cond ((or (= len -1) (>= len cs-max)) `(,(car clause) ,(cons cs-tag (list-tail (cadr clause) cs-max)) ,@(cddr clause))) (else clause))) clauses cs-lst))) (if (symbol? (car clause1)) (append clause2 (list (list cs-tag clause1))) (cons (list cs-tag clause1) clause2))))))) (define cse (lambda (clauses) (let loop ((lst clauses)) (if (null? lst) clauses (cond ((cse-1 clauses (car lst)) => cse) (else (loop (cdr lst)))))))) (define-syntax destructuring-bind (lambda (x) (syntax-case x () ((?_ ?pat ?expr ?body ...) (let ((pat (syntax->datum #'?pat)) (datum (generate-temporary-symbol)) (ren (make-core-hashtable)) (mem (vector '()))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((not (null? (vector-ref mem 0))) (syntax-violation 'destructuring-bind "tail match not supported" x pat)) ((duplicates? vars) (syntax-violation 'destructuring-bind "duplicate variables" x pat)) (match (with-syntax ((?datum (datum->syntax #'k datum)) ((?vars ...) (map (lambda (e) (datum->syntax #'?_ e)) vars)) ((?inits ...) (map (lambda (e) (datum->syntax #'k e)) inits)) ((?body ...) (datum->syntax #'?_ (syntax->datum (syntax (?body ...)))))) (syntax (let ((?datum ?expr)) (let ((?vars ?inits) ...) ?body ...))))) (else (syntax-violation 'destructuring-bind "malformed pattern" x pat))))))))) (define-syntax destructuring-match (lambda (x) (syntax-case x () ((?_ ?expr ?clauses ...) (let ((datum (generate-temporary-symbol)) (ren (make-core-hashtable)) (mem (vector '()))) (let ((code (cse (reorder (map (lambda (clause) (syntax-case clause () ((?pat) (let ((pat (syntax->datum #'?pat))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((duplicates? vars) (syntax-violation 'destructuring-match "duplicate variables" x pat)) (match (list #f (reverse match) '() '() (syntax #t) (syntax #t))) (else (syntax-violation 'destructuring-match "malformed pattern" x pat)))))) ((?pat ?body) (let ((pat (syntax->datum #'?pat))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((duplicates? vars) (syntax-violation 'destructuring-match "duplicate variables" x pat)) (match (list #f (reverse match) vars inits (syntax ?body) (syntax #t))) (else (syntax-violation 'destructuring-match "malformed pattern" x pat)))))) ((?pat ?fender ?body) (let ((pat (syntax->datum #'?pat))) (let-values (((match inits vars) (compile-match ren mem pat datum '() '() '()))) (cond ((duplicates? vars) (syntax-violation 'destructuring-match "duplicate variables" x pat)) (match (list #f (reverse match) vars inits (syntax ?body) (syntax ?fender))) (else (syntax-violation 'destructuring-match "malformed pattern" x pat)))))) (_ (syntax-violation 'destructuring-match "malformed clause" x clause)))) (syntax (?clauses ...))))))) (let-values (((shares others) (partition car code))) (let ((subexprs (map (lambda (e) `(,(car e) (and ,@(cadr e)))) shares)) (clauses (map cdr others))) (with-syntax ((?datum (datum->syntax #'k datum)) (((?pred-lhs ?pred-rhs) ...) (map (lambda (a) (list (datum->syntax #'k (cdr a)) (datum->syntax #'?_ (car a)))) (core-hashtable->alist ren))) ((?mem ...) (map (lambda (e) (datum->syntax #'k (cdr e))) (vector-ref mem 0))) ((?subexprs ...) (map (lambda (e) (datum->syntax #'k e)) subexprs)) ((?dispatch ...) (map (lambda (clause) (let-values (((tests vars inits body fender) (apply values clause))) (with-syntax (((?vars ...) (map (lambda (e) (datum->syntax #'?_ e)) vars)) ((?inits ...) (map (lambda (e) (datum->syntax #'k e)) inits)) ((?tests ...) (map (lambda (e) (datum->syntax #'k e)) tests)) (?fender (datum->syntax #'?_ (syntax->datum fender))) (?body (datum->syntax #'?_ (syntax->datum body)))) (if (eq? (syntax->datum (syntax ?fender)) #t) (syntax ((and ?tests ...) (let ((?vars ?inits) ...) ?body))) (syntax ((and ?tests ... (let ((?vars ?inits) ...) ?fender)) (let ((?vars ?inits) ...) ?body))))))) clauses))) (syntax (let ((?datum ?expr) (?pred-lhs ?pred-rhs) ... (?mem #f) ...) (let* (?subexprs ...) (cond ?dispatch ... (else #f)))))))))))))) (for-each (lambda (e) (core-hashtable-set! ca---r (car e) (cdr e))) '((car . caar) (cdr . cadr) (caar . caaar) (cadr . caadr) (cdar . cadar) (cddr . caddr) (caaar . caaaar) (caadr . caaadr) (cadar . caadar) (caddr . caaddr) (cdaar . cadaar) (cdadr . cadadr) (cddar . caddar) (cdddr . cadddr))) (for-each (lambda (e) (core-hashtable-set! cd---r (car e) (cdr e))) '((car . cdar) (cdr . cddr) (caar . cdaar) (cadr . cdadr) (cdar . cddar) (cddr . cdddr) (caaar . cdaaar) (caadr . cdaadr) (cadar . cdadar) (caddr . cdaddr) (cdaar . cddaar) (cdadr . cddadr) (cddar . cdddar) (cdddr . cddddr)))
ce6328464572f17b9287efeae47b3a207b6807ad512e3ee61cbd9732d1071769
nakkaya/static
core.clj
(ns static.test.core (:require [clojure.test :refer :all] [static.core :refer :all] [static.io :refer :all] [static.test.dummy-fs :refer :all]) (:import (java.io File) (org.apache.commons.io FileUtils))) (defn delete-file-recursively [f] (FileUtils/deleteDirectory f)) (defn dummy-fs-fixture [f] (setup-logging) (create-dummy-fs) (create) (f) (delete-file-recursively (File. "resources/")) (delete-file-recursively (File. "html/")) (.delete (File. "config.clj"))) (use-fixtures :once dummy-fs-fixture) (deftest test-markdown (let [[metadata content] (read-doc "resources/site/dummy.markdown")] (is (= "unit test" (:tags metadata))) (is (= "some dummy desc" (:description metadata))) (is (= "dummy content" (:title metadata))) (is (= "Some dummy file for unit testing." (re-find #"Some dummy file for unit testing." @content))))) (deftest test-cssgen (let [[metadata content] (read-doc "resources/site/style.cssgen")] (is (= "font-size: 1em;" (re-find #"font-size: 1em;" @content))))) (deftest test-org (let [[metadata content] (read-doc (File. "resources/posts/2050-07-07-dummy-future-post-7.org"))] (is (= "org-mode org-babel" (:tags metadata))) (is (= "Dummy org-mode post" (:title metadata))) (is (= "Sum 1 and 2" (re-find #"Sum 1 and 2" @content))) (is (= 2 (count (:links metadata)))))) (deftest test-clj (let [[metadata content] (read-doc (File. "resources/site/dummy_clj.clj"))] (is (= "Dummy Clj File" (:title metadata))) (is (= "Dummy Clj Content" (re-find #"Dummy Clj Content" @content))) (is (= "<h3>" (re-find #"<h3>" @content))))) (deftest test-io (is (= (count (list-files :posts)) 8)) (is (.exists (File. "html/first-alias/index.html"))) (is (.exists (File. "html/a/b/c/alias/index.html"))) (is (.exists (File. "html/second-alias/index.html")))) (deftest test-st-template (let [file (File. "html/html_template.html") content (slurp file)] (is (= "Dummy Html Post Template" (re-find #"Dummy Html Post Template" content))) (is (= "<title>Html Template Test</title>" (re-find #"<title>Html Template Test</title>" content))))) (deftest test-rss-feed (let [rss (File. "html/rss-feed") content (slurp rss)] (is (= true (.exists rss))) (is (= "<title>Dummy Site</title>" (re-find #"<title>Dummy Site</title>" content))) (is (= "<link></link>" (re-find #"<link></link>" content))) (is (= "<title>dummy future post 1</title>" (re-find #"<title>dummy future post 1</title>" content))) (is (= "-future-post-4/" (re-find #"-future-post-4/" content))))) (deftest test-site-map (let [sitemap (File. "html/sitemap.xml") content (slurp sitemap)] (is (= true (.exists sitemap))) (is (= "<loc></loc>" (re-find #"<loc></loc>" content))) (is (= "-future-post-1/" (re-find #"-future-post-1/" content))) (is (= "<loc></loc>" (re-find #"<loc></loc>" content))))) (deftest test-rss-feed (let [tags (File. "html/tags/index.html") content (slurp tags)] (is (= 5 (count ((tag-map) "same")))) (is (= true (.exists tags))) (is (= "<a name=\"e4e8\">e4e8</a>" (re-find #"<a name=\"e4e8\">e4e8</a>" content))) (is (= "<a href=\"/2050/01/01/dummy-future-post-1/\">" (re-find #"<a href=\"/2050/01/01/dummy-future-post-1/\">" content))))) (deftest test-latest-posts (let [page (File. "html/latest-posts/0/index.html")] (is (= true (.exists page))))) (deftest test-archives (let [index (File. "html/archives/index.html") a-2050-01 (File. "html/archives/2050/01/index.html")] (is (= true (.exists index))) (is (= true (.exists a-2050-01))))) (deftest test-process-posts (let [post1 (File. "html/2050/02/02/dummy-future-post-2/index.html") post2 (File. "html/2050/04/04/dummy-future-post-4/index.html")] (is (= true (.exists post1))) (is (= true (.exists post2))))) (deftest test-process-site (let [html (File. "html/dummy.html") static (File. "html/dummy.static")] (is (= true (.exists html))) (is (= true (.exists static))) (is (= "Some dummy file for unit testing." (re-find #"Some dummy file for unit testing." (slurp html)))) (is (= "Hello, World!!" (re-find #"Hello, World!!" (slurp static))))))
null
https://raw.githubusercontent.com/nakkaya/static/59b51210ee4dffa2a4b48971a5d994b70e548817/test/static/test/core.clj
clojure
(ns static.test.core (:require [clojure.test :refer :all] [static.core :refer :all] [static.io :refer :all] [static.test.dummy-fs :refer :all]) (:import (java.io File) (org.apache.commons.io FileUtils))) (defn delete-file-recursively [f] (FileUtils/deleteDirectory f)) (defn dummy-fs-fixture [f] (setup-logging) (create-dummy-fs) (create) (f) (delete-file-recursively (File. "resources/")) (delete-file-recursively (File. "html/")) (.delete (File. "config.clj"))) (use-fixtures :once dummy-fs-fixture) (deftest test-markdown (let [[metadata content] (read-doc "resources/site/dummy.markdown")] (is (= "unit test" (:tags metadata))) (is (= "some dummy desc" (:description metadata))) (is (= "dummy content" (:title metadata))) (is (= "Some dummy file for unit testing." (re-find #"Some dummy file for unit testing." @content))))) (deftest test-cssgen (let [[metadata content] (read-doc "resources/site/style.cssgen")] (is (= "font-size: 1em;" (re-find #"font-size: 1em;" @content))))) (deftest test-org (let [[metadata content] (read-doc (File. "resources/posts/2050-07-07-dummy-future-post-7.org"))] (is (= "org-mode org-babel" (:tags metadata))) (is (= "Dummy org-mode post" (:title metadata))) (is (= "Sum 1 and 2" (re-find #"Sum 1 and 2" @content))) (is (= 2 (count (:links metadata)))))) (deftest test-clj (let [[metadata content] (read-doc (File. "resources/site/dummy_clj.clj"))] (is (= "Dummy Clj File" (:title metadata))) (is (= "Dummy Clj Content" (re-find #"Dummy Clj Content" @content))) (is (= "<h3>" (re-find #"<h3>" @content))))) (deftest test-io (is (= (count (list-files :posts)) 8)) (is (.exists (File. "html/first-alias/index.html"))) (is (.exists (File. "html/a/b/c/alias/index.html"))) (is (.exists (File. "html/second-alias/index.html")))) (deftest test-st-template (let [file (File. "html/html_template.html") content (slurp file)] (is (= "Dummy Html Post Template" (re-find #"Dummy Html Post Template" content))) (is (= "<title>Html Template Test</title>" (re-find #"<title>Html Template Test</title>" content))))) (deftest test-rss-feed (let [rss (File. "html/rss-feed") content (slurp rss)] (is (= true (.exists rss))) (is (= "<title>Dummy Site</title>" (re-find #"<title>Dummy Site</title>" content))) (is (= "<link></link>" (re-find #"<link></link>" content))) (is (= "<title>dummy future post 1</title>" (re-find #"<title>dummy future post 1</title>" content))) (is (= "-future-post-4/" (re-find #"-future-post-4/" content))))) (deftest test-site-map (let [sitemap (File. "html/sitemap.xml") content (slurp sitemap)] (is (= true (.exists sitemap))) (is (= "<loc></loc>" (re-find #"<loc></loc>" content))) (is (= "-future-post-1/" (re-find #"-future-post-1/" content))) (is (= "<loc></loc>" (re-find #"<loc></loc>" content))))) (deftest test-rss-feed (let [tags (File. "html/tags/index.html") content (slurp tags)] (is (= 5 (count ((tag-map) "same")))) (is (= true (.exists tags))) (is (= "<a name=\"e4e8\">e4e8</a>" (re-find #"<a name=\"e4e8\">e4e8</a>" content))) (is (= "<a href=\"/2050/01/01/dummy-future-post-1/\">" (re-find #"<a href=\"/2050/01/01/dummy-future-post-1/\">" content))))) (deftest test-latest-posts (let [page (File. "html/latest-posts/0/index.html")] (is (= true (.exists page))))) (deftest test-archives (let [index (File. "html/archives/index.html") a-2050-01 (File. "html/archives/2050/01/index.html")] (is (= true (.exists index))) (is (= true (.exists a-2050-01))))) (deftest test-process-posts (let [post1 (File. "html/2050/02/02/dummy-future-post-2/index.html") post2 (File. "html/2050/04/04/dummy-future-post-4/index.html")] (is (= true (.exists post1))) (is (= true (.exists post2))))) (deftest test-process-site (let [html (File. "html/dummy.html") static (File. "html/dummy.static")] (is (= true (.exists html))) (is (= true (.exists static))) (is (= "Some dummy file for unit testing." (re-find #"Some dummy file for unit testing." (slurp html)))) (is (= "Hello, World!!" (re-find #"Hello, World!!" (slurp static))))))
ae04d904c1a252558a3c847897a6d4c527d66d604df2efd8447cc0e0b9f497d3
erp12/fijit
try_test.clj
(ns erp12.fijit.try-test (:require [clojure.test :refer :all] [expectations.clojure.test :refer :all] [erp12.fijit.try :as sc-try]) (:import (clojure.lang ExceptionInfo))) (deftest get-test (testing "Re-throwing improved errors" (let [msg "Failed division!"] (expect (more-> ExceptionInfo type msg ex-message) (get (sc-try/scala-try (/ 1 0)) (throw (ex-info msg {:numerator 1 :denominator 0})))))))
null
https://raw.githubusercontent.com/erp12/fijit/7657cf2e6058cd916e2024bf9d16ad1f2a07d48b/test/erp12/fijit/try_test.clj
clojure
(ns erp12.fijit.try-test (:require [clojure.test :refer :all] [expectations.clojure.test :refer :all] [erp12.fijit.try :as sc-try]) (:import (clojure.lang ExceptionInfo))) (deftest get-test (testing "Re-throwing improved errors" (let [msg "Failed division!"] (expect (more-> ExceptionInfo type msg ex-message) (get (sc-try/scala-try (/ 1 0)) (throw (ex-info msg {:numerator 1 :denominator 0})))))))
7a31ef5677b1ec59fd33218039a6cbd678f7466cc911fa0543aab44b78c8f695
racket/web-server
hmac-sha1.rkt
#lang racket/base (require racket/contract web-server/stuffers/stuffer racket/runtime-path openssl/libcrypto (rename-in ffi/unsafe [-> f->])) (define EVP_SHA1 (and libcrypto (get-ffi-obj 'EVP_sha1 libcrypto (_fun f-> _fpointer)))) (define HMAC-SHA1/raw (if libcrypto (get-ffi-obj 'HMAC libcrypto (_fun [EVP_MD : _fpointer = (EVP_SHA1)] [key : _bytes] [key_len : _int = (bytes-length key)] [data : _bytes] [data_len : _int = (bytes-length data)] [md : (_bytes o 20)] [md_len : (_ptr o _uint)] f-> _bytes f-> md)) (lambda (key data) (error 'HMAC-SHA1/raw "libcrypto could not load")))) (define (HMAC-SHA1 key data) (HMAC-SHA1/raw key data) ; It returns the same pointer always #;(bytes-copy A SHA1 is 20 bytes , including 0s (make-sized-byte-string (HMAC-SHA1/raw key data) 20))) (define (HMAC-SHA1-stuffer key) (make-stuffer (lambda (ib) (bytes-append (HMAC-SHA1 key ib) ib)) (lambda (ob) (define hib (subbytes ob 0 20)) (define ib (subbytes ob 20)) (define true-hib (HMAC-SHA1 key ib)) (if (bytes=? hib true-hib) ib (error 'HMAC-SHA1-stuffer "Signature does not match!"))))) (provide/contract [HMAC-SHA1 (bytes? bytes? . -> . bytes?)] [HMAC-SHA1-stuffer (bytes? . -> . (stuffer/c bytes? bytes?))])
null
https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-lib/web-server/stuffers/hmac-sha1.rkt
racket
It returns the same pointer always (bytes-copy
#lang racket/base (require racket/contract web-server/stuffers/stuffer racket/runtime-path openssl/libcrypto (rename-in ffi/unsafe [-> f->])) (define EVP_SHA1 (and libcrypto (get-ffi-obj 'EVP_sha1 libcrypto (_fun f-> _fpointer)))) (define HMAC-SHA1/raw (if libcrypto (get-ffi-obj 'HMAC libcrypto (_fun [EVP_MD : _fpointer = (EVP_SHA1)] [key : _bytes] [key_len : _int = (bytes-length key)] [data : _bytes] [data_len : _int = (bytes-length data)] [md : (_bytes o 20)] [md_len : (_ptr o _uint)] f-> _bytes f-> md)) (lambda (key data) (error 'HMAC-SHA1/raw "libcrypto could not load")))) (define (HMAC-SHA1 key data) (HMAC-SHA1/raw key data) A SHA1 is 20 bytes , including 0s (make-sized-byte-string (HMAC-SHA1/raw key data) 20))) (define (HMAC-SHA1-stuffer key) (make-stuffer (lambda (ib) (bytes-append (HMAC-SHA1 key ib) ib)) (lambda (ob) (define hib (subbytes ob 0 20)) (define ib (subbytes ob 20)) (define true-hib (HMAC-SHA1 key ib)) (if (bytes=? hib true-hib) ib (error 'HMAC-SHA1-stuffer "Signature does not match!"))))) (provide/contract [HMAC-SHA1 (bytes? bytes? . -> . bytes?)] [HMAC-SHA1-stuffer (bytes? . -> . (stuffer/c bytes? bytes?))])
29c9ea35a4a17182dfeeb8460cfbeb591641fed4b2e6d34e77970543b70e7e4f
racketscript/racketscript
simple.rkt
#lang racket (define (extract-current-continuation-marks key) (continuation-mark-set->list (current-continuation-marks) key)) (displayln (with-continuation-mark 'key 'mark (extract-current-continuation-marks 'key))) (displayln (with-continuation-mark 'key1 'mark1 (with-continuation-mark 'key2 'mark2 (list (extract-current-continuation-marks 'key1) (extract-current-continuation-marks 'key2))))) (displayln (with-continuation-mark 'key 'mark1 (with-continuation-mark 'key 'mark2 ; replaces previous mark (extract-current-continuation-marks 'key)))) (displayln (with-continuation-mark 'key 'mark1 (list ; continuation extended to evaluate the argument (with-continuation-mark 'key 'mark2 (extract-current-continuation-marks 'key)))))
null
https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/tests/wcm/simple.rkt
racket
replaces previous mark continuation extended to evaluate the argument
#lang racket (define (extract-current-continuation-marks key) (continuation-mark-set->list (current-continuation-marks) key)) (displayln (with-continuation-mark 'key 'mark (extract-current-continuation-marks 'key))) (displayln (with-continuation-mark 'key1 'mark1 (with-continuation-mark 'key2 'mark2 (list (extract-current-continuation-marks 'key1) (extract-current-continuation-marks 'key2))))) (displayln (with-continuation-mark 'key 'mark1 (extract-current-continuation-marks 'key)))) (displayln (with-continuation-mark 'key 'mark1 (with-continuation-mark 'key 'mark2 (extract-current-continuation-marks 'key)))))
c9db12c75e512091b6ddfcd6d33b3521bf734654f2766461d61ea99796f06e48
sneeuwballen/zipperposition
trace_tstp.mli
This file is free software , part of Logtk . See file " license " for more details . (** {1 Trace of a TSTP prover} *) open Logtk type id = Ast_tptp.name type term = STerm.t type form = STerm.t type clause = term SLiteral.t list type t = | Axiom of string * string (* filename, axiom name *) | Theory of string (* a theory used to do an inference *) | InferForm of form * step lazy_t | InferClause of clause * step lazy_t and step = { id : id; rule : string; parents : t array; esa : bool; (** Equisatisfiable step? *) } val equal : t -> t -> bool val compare : t -> t -> int val mk_f_axiom : id:id -> form -> file:string -> name:string -> t val mk_c_axiom : id:id -> clause -> file:string -> name:string -> t val mk_f_step : ?esa:bool -> id:id -> form -> rule:string -> t list -> t val mk_c_step : ?esa:bool -> id:id -> clause -> rule:string -> t list -> t val is_axiom : t -> bool val is_theory : t -> bool val is_step : t -> bool val is_proof_of_false : t -> bool val get_id : t -> id * Obtain the ID of the proof step . @raise Invalid_argument if the step is Axiom or Theory @raise Invalid_argument if the step is Axiom or Theory *) val force : t -> unit (** Force the lazy proof step, if any *) (** {3 Proof traversal} *) module StepTbl : Hashtbl.S with type key = t type proof_set = unit StepTbl.t val is_dag : t -> bool * Is the proof a proper DAG ? val traverse : ?traversed:proof_set -> t -> (t -> unit) -> unit (** Traverse the proof. Each proof node is traversed only once, using the set to recognize already traversed proofs. *) val to_iter : t -> t Iter.t (** Traversal of parent proofs *) val depth : t -> int * depth of the proof val size : t -> int (** Number of nodes in the proof *) * { 3 IO } type 'a or_error = ('a, string) CCResult.t val of_decls : form Ast_tptp.t Iter.t -> t or_error * Try to extract a proof from a list of TSTP statements . val parse : ?recursive:bool -> string -> t or_error (** Try to parse a proof from a file. *) include Interfaces.PRINT with type t := t (** Debug printing, non recursive *) val pp1 : t CCFormat.printer (** Print proof step, and its parents *) val pp_tstp : t CCFormat.printer (** print the whole proofs *)
null
https://raw.githubusercontent.com/sneeuwballen/zipperposition/7f1455fbe2e7509907f927649c288141b1a3a247/src/parsers/trace_tstp.mli
ocaml
* {1 Trace of a TSTP prover} filename, axiom name a theory used to do an inference * Equisatisfiable step? * Force the lazy proof step, if any * {3 Proof traversal} * Traverse the proof. Each proof node is traversed only once, using the set to recognize already traversed proofs. * Traversal of parent proofs * Number of nodes in the proof * Try to parse a proof from a file. * Debug printing, non recursive * Print proof step, and its parents * print the whole proofs
This file is free software , part of Logtk . See file " license " for more details . open Logtk type id = Ast_tptp.name type term = STerm.t type form = STerm.t type clause = term SLiteral.t list type t = | InferForm of form * step lazy_t | InferClause of clause * step lazy_t and step = { id : id; rule : string; parents : t array; } val equal : t -> t -> bool val compare : t -> t -> int val mk_f_axiom : id:id -> form -> file:string -> name:string -> t val mk_c_axiom : id:id -> clause -> file:string -> name:string -> t val mk_f_step : ?esa:bool -> id:id -> form -> rule:string -> t list -> t val mk_c_step : ?esa:bool -> id:id -> clause -> rule:string -> t list -> t val is_axiom : t -> bool val is_theory : t -> bool val is_step : t -> bool val is_proof_of_false : t -> bool val get_id : t -> id * Obtain the ID of the proof step . @raise Invalid_argument if the step is Axiom or Theory @raise Invalid_argument if the step is Axiom or Theory *) val force : t -> unit module StepTbl : Hashtbl.S with type key = t type proof_set = unit StepTbl.t val is_dag : t -> bool * Is the proof a proper DAG ? val traverse : ?traversed:proof_set -> t -> (t -> unit) -> unit val to_iter : t -> t Iter.t val depth : t -> int * depth of the proof val size : t -> int * { 3 IO } type 'a or_error = ('a, string) CCResult.t val of_decls : form Ast_tptp.t Iter.t -> t or_error * Try to extract a proof from a list of TSTP statements . val parse : ?recursive:bool -> string -> t or_error include Interfaces.PRINT with type t := t val pp1 : t CCFormat.printer val pp_tstp : t CCFormat.printer
7238f11385bc72f3797b7eb759ae657cd5f7cd4fd47fd9b2ee7bc4f0ba156ecd
rbkmoney/consuela
consuela_zombie_reaper.erl
%%% %%% A process to defer reaping up zombie names, which process is dead but name is still possibly there in %%% Consul. Also can be used to asynchronously reap registrations when a processes die for example. -module(consuela_zombie_reaper). %% api -type registry() :: consuela_registry:t(). -export([start_link/2]). -export([enqueue/2]). -export([enqueue/3]). TODO % -export([dequeue/3]) ?. -export([drain/1]). %% gen server -behaviour(gen_server). -export([init/1]). -export([handle_call/3]). -export([handle_cast/2]). -export([handle_info/2]). -export([terminate/2]). -export([code_change/3]). %% pulse -type beat() :: { {zombie, zombie()}, enqueued | {reaping, succeeded | {skipped, _Reason} | {failed, _Reason}} } | { {timer, reference()}, {started, timeout()} | fired | reset } | {unexpected, {{call, from()} | cast | info, _Msg}}. -callback handle_beat(beat(), _PulseOpts) -> _. -export([handle_beat/2]). -export_type([beat/0]). %% -type ref() :: pid(). -type opts() :: #{ retry => genlib_retry:strategy(), pulse => {module(), _PulseOpts} }. -export_type([opts/0]). -export_type([ref/0]). -spec start_link(registry(), opts()) -> {ok, pid()}. start_link(Registry, Opts) -> gen_server:start_link(?MODULE, {Registry, Opts}, []). -spec enqueue(ref(), [zombie()]) -> ok. enqueue(Ref, Zombies) -> enqueue(Ref, Zombies, #{}). -type enqueue_opts() :: #{ % Try to drain queue right away? (false by default) drain => boolean(), % Wait for enqueue confirmation? (false by default0 sync => boolean() }. -spec enqueue(ref(), [zombie()], enqueue_opts()) -> ok. enqueue(Ref, Zombies, Opts = #{sync := true}) -> gen_server:call(Ref, {enqueue, Zombies, maps:without([sync], Opts)}); enqueue(Ref, Zombies, Opts) -> gen_server:cast(Ref, {enqueue, Zombies, Opts}). -spec drain(ref()) -> ok. drain(Ref) -> gen_server:cast(Ref, drain). %% -type zombie() :: consuela_registry:reg(). -type st() :: #{ queue := queue:queue(zombie()), registry := consuela_registry:t(), retry_strategy := genlib_retry:strategy(), retry_state => genlib_retry:strategy(), timeout => timeout(), timer => reference(), pulse := {module(), _PulseOpts} }. -type from() :: {pid(), reference()}. -spec init({consuela_registry:t(), opts()}) -> {ok, st()}. init({Registry, Opts}) -> % to have a chance to drain queue containing processes which just died _ = erlang:process_flag(trap_exit, true), St = maps:fold( fun (retry, V, St) -> St#{retry_strategy => V}; (pulse, {Module, _} = V, St) when is_atom(Module) -> St#{pulse => V} end, #{ queue => queue:new(), registry => Registry, retry_strategy => genlib_retry:linear({max_total_timeout, 10 * 60 * 1000}, 5000), pulse => {?MODULE, []} }, Opts ), {ok, reset_retry_state(St)}. -type call() :: {enqueue, [zombie()], enqueue_opts()}. -spec handle_call(call(), from(), st()) -> {noreply, st()}. handle_call({enqueue, Zombies, Opts}, _From, St) -> {reply, ok, handle_enqueue(Zombies, Opts, St)}; handle_call(Call, From, St) -> _ = beat({unexpected, {{call, From}, Call}}, St), {noreply, St}. -type cast() :: {enqueue, [zombie()], enqueue_opts()} | drain. -spec handle_cast(cast(), st()) -> {noreply, st()}. handle_cast({enqueue, Zombies, Opts}, St) -> {noreply, handle_enqueue(Zombies, Opts, St)}; handle_cast(drain, St) -> {noreply, try_drain_head(St)}; handle_cast(Cast, St) -> _ = beat({unexpected, {cast, Cast}}, St), {noreply, St}. -type info() :: {timeout, reference(), clean}. -spec handle_info(info(), st()) -> {noreply, st()}. handle_info({timeout, TimerRef, clean}, St = #{timer := TimerRef}) -> _ = beat({{timer, TimerRef}, fired}, St), {noreply, try_clean_head(regular, maps:remove(timer, St))}; handle_info(Info, St) -> _ = beat({unexpected, {info, Info}}, St), {noreply, St}. -spec terminate(_Reason, st()) -> ok. terminate(shutdown, St) -> ok = drain_queue(St); terminate({shutdown, _Reason}, St) -> ok = drain_queue(St); terminate(_Error, _St) -> ok. -spec code_change(_Vsn | {down, _Vsn}, st(), _Extra) -> {ok, st()}. code_change(_Vsn, St, _Extra) -> {ok, St}. %% handle_enqueue(Zombies, Opts, St0) -> St1 = lists:foldl(fun enqueue_zombie/2, St0, Zombies), case Opts of #{drain := true} -> try_clean_head(draining, St1); #{} -> try_start_timer(St1) end. enqueue_zombie(Zombie, St0 = #{queue := Q}) -> St1 = St0#{queue := queue:in(Zombie, Q)}, _ = beat({{zombie, Zombie}, enqueued}, St1), St1. try_drain_head(St = #{queue := Queue}) -> case queue:is_empty(Queue) of false -> try_clean_head(draining, St); true -> St end. try_clean_head(Mode, St0 = #{queue := Q0}) -> {{value, Zombie}, Q1} = queue:out(Q0), case unregister(Zombie, St0) of ok -> St1 = St0#{queue := Q1}, try_force_timer(reset_retry_state(St1)); {error, _} -> case Mode of regular -> start_timer(advance_retry_state(St0)); draining -> try_start_timer(St0) end end. drain_queue(St = #{queue := Q}) -> drain_queue(queue:to_list(Q), St). drain_queue([Zombie | Rest] = Q, St) -> case unregister(Zombie, St) of ok -> drain_queue(Rest, St); {error, _} -> drain_queue(Q, St) end; drain_queue([], _St) -> ok. unregister(Zombie, St = #{registry := Registry}) -> case consuela_registry:unregister(Zombie, Registry) of {done, ok} -> _ = beat({{zombie, Zombie}, {reaping, succeeded}}, St), ok; {done, {error, stale}} -> _ = beat({{zombie, Zombie}, {reaping, {skipped, stale}}}, St), ok; {failed, Reason} -> _ = beat({{zombie, Zombie}, {reaping, {failed, Reason}}}, St), {error, Reason} end. try_force_timer(St) -> try_start_timer(0, try_reset_timer(St)). try_start_timer(St = #{timeout := Timeout}) -> try_start_timer(Timeout, St). try_start_timer(_Timeout, St = #{timer := _}) -> St; try_start_timer(Timeout, St = #{queue := Queue}) -> case queue:is_empty(Queue) of false -> start_timer(Timeout, St); true -> St end. try_reset_timer(St = #{timer := TimerRef}) when is_reference(TimerRef) -> ok = consuela_timer:reset(TimerRef), _ = beat({{timer, TimerRef}, reset}, St), maps:remove(timer, St); try_reset_timer(St = #{}) -> St. start_timer(St = #{timeout := Timeout}) -> start_timer(Timeout, St). start_timer(Timeout, St = #{}) -> false = maps:is_key(timer, St), TimerRef = consuela_timer:start(Timeout, clean), _ = beat({{timer, TimerRef}, {started, Timeout}}, St), St#{timer => TimerRef}. reset_retry_state(St = #{retry_strategy := Retry}) -> TODO % Will not work well with timecapped strategies, we need to separate constructor from state. advance_retry_state(St#{retry_state => Retry}). advance_retry_state(St = #{retry_state := RetrySt0}) -> case genlib_retry:next_step(RetrySt0) of {wait, Timeout, RetrySt1} -> St#{retry_state := RetrySt1, timeout => Timeout}; finish -> % No reason to live anymore exit(retries_exhausted) end. %% -spec beat(beat(), st()) -> _. beat(Beat, #{pulse := {Module, PulseOpts}}) -> TODO handle errors ? Module:handle_beat(Beat, PulseOpts). -spec handle_beat(beat(), [trace]) -> ok. handle_beat(Beat, [trace]) -> logger:debug("[~p] ~p", [?MODULE, Beat]); handle_beat(_Beat, []) -> ok.
null
https://raw.githubusercontent.com/rbkmoney/consuela/56d065bff0f1c8de4cede40d670b9061942b4ea8/src/consuela_zombie_reaper.erl
erlang
A process to defer reaping up zombie names, which process is dead but name is still possibly there in Consul. Also can be used to asynchronously reap registrations when a processes die for example. api -export([dequeue/3]) ?. gen server pulse Try to drain queue right away? (false by default) Wait for enqueue confirmation? (false by default0 to have a chance to drain queue containing processes which just died Will not work well with timecapped strategies, we need to separate constructor from state. No reason to live anymore
-module(consuela_zombie_reaper). -type registry() :: consuela_registry:t(). -export([start_link/2]). -export([enqueue/2]). -export([enqueue/3]). TODO -export([drain/1]). -behaviour(gen_server). -export([init/1]). -export([handle_call/3]). -export([handle_cast/2]). -export([handle_info/2]). -export([terminate/2]). -export([code_change/3]). -type beat() :: { {zombie, zombie()}, enqueued | {reaping, succeeded | {skipped, _Reason} | {failed, _Reason}} } | { {timer, reference()}, {started, timeout()} | fired | reset } | {unexpected, {{call, from()} | cast | info, _Msg}}. -callback handle_beat(beat(), _PulseOpts) -> _. -export([handle_beat/2]). -export_type([beat/0]). -type ref() :: pid(). -type opts() :: #{ retry => genlib_retry:strategy(), pulse => {module(), _PulseOpts} }. -export_type([opts/0]). -export_type([ref/0]). -spec start_link(registry(), opts()) -> {ok, pid()}. start_link(Registry, Opts) -> gen_server:start_link(?MODULE, {Registry, Opts}, []). -spec enqueue(ref(), [zombie()]) -> ok. enqueue(Ref, Zombies) -> enqueue(Ref, Zombies, #{}). -type enqueue_opts() :: #{ drain => boolean(), sync => boolean() }. -spec enqueue(ref(), [zombie()], enqueue_opts()) -> ok. enqueue(Ref, Zombies, Opts = #{sync := true}) -> gen_server:call(Ref, {enqueue, Zombies, maps:without([sync], Opts)}); enqueue(Ref, Zombies, Opts) -> gen_server:cast(Ref, {enqueue, Zombies, Opts}). -spec drain(ref()) -> ok. drain(Ref) -> gen_server:cast(Ref, drain). -type zombie() :: consuela_registry:reg(). -type st() :: #{ queue := queue:queue(zombie()), registry := consuela_registry:t(), retry_strategy := genlib_retry:strategy(), retry_state => genlib_retry:strategy(), timeout => timeout(), timer => reference(), pulse := {module(), _PulseOpts} }. -type from() :: {pid(), reference()}. -spec init({consuela_registry:t(), opts()}) -> {ok, st()}. init({Registry, Opts}) -> _ = erlang:process_flag(trap_exit, true), St = maps:fold( fun (retry, V, St) -> St#{retry_strategy => V}; (pulse, {Module, _} = V, St) when is_atom(Module) -> St#{pulse => V} end, #{ queue => queue:new(), registry => Registry, retry_strategy => genlib_retry:linear({max_total_timeout, 10 * 60 * 1000}, 5000), pulse => {?MODULE, []} }, Opts ), {ok, reset_retry_state(St)}. -type call() :: {enqueue, [zombie()], enqueue_opts()}. -spec handle_call(call(), from(), st()) -> {noreply, st()}. handle_call({enqueue, Zombies, Opts}, _From, St) -> {reply, ok, handle_enqueue(Zombies, Opts, St)}; handle_call(Call, From, St) -> _ = beat({unexpected, {{call, From}, Call}}, St), {noreply, St}. -type cast() :: {enqueue, [zombie()], enqueue_opts()} | drain. -spec handle_cast(cast(), st()) -> {noreply, st()}. handle_cast({enqueue, Zombies, Opts}, St) -> {noreply, handle_enqueue(Zombies, Opts, St)}; handle_cast(drain, St) -> {noreply, try_drain_head(St)}; handle_cast(Cast, St) -> _ = beat({unexpected, {cast, Cast}}, St), {noreply, St}. -type info() :: {timeout, reference(), clean}. -spec handle_info(info(), st()) -> {noreply, st()}. handle_info({timeout, TimerRef, clean}, St = #{timer := TimerRef}) -> _ = beat({{timer, TimerRef}, fired}, St), {noreply, try_clean_head(regular, maps:remove(timer, St))}; handle_info(Info, St) -> _ = beat({unexpected, {info, Info}}, St), {noreply, St}. -spec terminate(_Reason, st()) -> ok. terminate(shutdown, St) -> ok = drain_queue(St); terminate({shutdown, _Reason}, St) -> ok = drain_queue(St); terminate(_Error, _St) -> ok. -spec code_change(_Vsn | {down, _Vsn}, st(), _Extra) -> {ok, st()}. code_change(_Vsn, St, _Extra) -> {ok, St}. handle_enqueue(Zombies, Opts, St0) -> St1 = lists:foldl(fun enqueue_zombie/2, St0, Zombies), case Opts of #{drain := true} -> try_clean_head(draining, St1); #{} -> try_start_timer(St1) end. enqueue_zombie(Zombie, St0 = #{queue := Q}) -> St1 = St0#{queue := queue:in(Zombie, Q)}, _ = beat({{zombie, Zombie}, enqueued}, St1), St1. try_drain_head(St = #{queue := Queue}) -> case queue:is_empty(Queue) of false -> try_clean_head(draining, St); true -> St end. try_clean_head(Mode, St0 = #{queue := Q0}) -> {{value, Zombie}, Q1} = queue:out(Q0), case unregister(Zombie, St0) of ok -> St1 = St0#{queue := Q1}, try_force_timer(reset_retry_state(St1)); {error, _} -> case Mode of regular -> start_timer(advance_retry_state(St0)); draining -> try_start_timer(St0) end end. drain_queue(St = #{queue := Q}) -> drain_queue(queue:to_list(Q), St). drain_queue([Zombie | Rest] = Q, St) -> case unregister(Zombie, St) of ok -> drain_queue(Rest, St); {error, _} -> drain_queue(Q, St) end; drain_queue([], _St) -> ok. unregister(Zombie, St = #{registry := Registry}) -> case consuela_registry:unregister(Zombie, Registry) of {done, ok} -> _ = beat({{zombie, Zombie}, {reaping, succeeded}}, St), ok; {done, {error, stale}} -> _ = beat({{zombie, Zombie}, {reaping, {skipped, stale}}}, St), ok; {failed, Reason} -> _ = beat({{zombie, Zombie}, {reaping, {failed, Reason}}}, St), {error, Reason} end. try_force_timer(St) -> try_start_timer(0, try_reset_timer(St)). try_start_timer(St = #{timeout := Timeout}) -> try_start_timer(Timeout, St). try_start_timer(_Timeout, St = #{timer := _}) -> St; try_start_timer(Timeout, St = #{queue := Queue}) -> case queue:is_empty(Queue) of false -> start_timer(Timeout, St); true -> St end. try_reset_timer(St = #{timer := TimerRef}) when is_reference(TimerRef) -> ok = consuela_timer:reset(TimerRef), _ = beat({{timer, TimerRef}, reset}, St), maps:remove(timer, St); try_reset_timer(St = #{}) -> St. start_timer(St = #{timeout := Timeout}) -> start_timer(Timeout, St). start_timer(Timeout, St = #{}) -> false = maps:is_key(timer, St), TimerRef = consuela_timer:start(Timeout, clean), _ = beat({{timer, TimerRef}, {started, Timeout}}, St), St#{timer => TimerRef}. reset_retry_state(St = #{retry_strategy := Retry}) -> TODO advance_retry_state(St#{retry_state => Retry}). advance_retry_state(St = #{retry_state := RetrySt0}) -> case genlib_retry:next_step(RetrySt0) of {wait, Timeout, RetrySt1} -> St#{retry_state := RetrySt1, timeout => Timeout}; finish -> exit(retries_exhausted) end. -spec beat(beat(), st()) -> _. beat(Beat, #{pulse := {Module, PulseOpts}}) -> TODO handle errors ? Module:handle_beat(Beat, PulseOpts). -spec handle_beat(beat(), [trace]) -> ok. handle_beat(Beat, [trace]) -> logger:debug("[~p] ~p", [?MODULE, Beat]); handle_beat(_Beat, []) -> ok.
eeba07e8b576fc3ac8ce48e7d1afd4ad4da174de832520fd54fbf7a4e47b6b94
vitorenesduarte/tricks
tricks.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2018 . All Rights Reserved . %% This file is provided to you 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. %% %% ------------------------------------------------------------------- -module(tricks). -author("Vitor Enes <>"). -include("tricks.hrl"). -behaviour(gen_server). %% API -export([start_link/0, run/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2]). -record(state, {}). -spec start_link() -> {ok, pid()} | ignore | error(). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %% @doc Run an experiment. -spec run(maps:map()) -> {ok, exp_id()} | error(). run(Exp) -> gen_server:call(?MODULE, {run, Exp}, infinity). init([]) -> lager:info("tricks initialized!"), {ok, #state{}}. handle_call({run, Experiment}, _From, State) -> ExpId = do_run(Experiment), {reply, {ok, ExpId}, State}. handle_cast(Msg, State) -> {stop, {unhandled, Msg}, State}. @private Run an experiment given its config and kuberl config . do_run(Experiment) -> #{experiment := EntrySpecs} = Experiment, ExpId = tricks_exp:exp_id(), lists:foreach( fun(EntrySpec0) -> #{replicas := Replicas}=EntrySpec = set_replicas_info(EntrySpec0), {Start, End} = get_workflow_info(EntrySpec), lists:foreach( fun(PodId) -> %% pod body Body = tricks_exp:pod_body(ExpId, PodId, EntrySpec), %% schedule pod tricks_scheduler:schedule_pod(ExpId, Body, Start, End) end, lists:seq(0, Replicas - 1) ) end, EntrySpecs ), ExpId. @private Set replicas info . If not defined , set it as 1 ( default value ) . -spec set_replicas_info(maps:map()) -> maps:map(). set_replicas_info(EntrySpec0) -> case maps:is_key(replicas, EntrySpec0) of true -> EntrySpec0; false -> maps:put(replicas, 1, EntrySpec0) end. @private Get workflow info . %% - Default start: now %% - Default stop : never -spec get_workflow_info(maps:map()) -> {now | event(), never | event()}. get_workflow_info(EntrySpec) -> Workflow = maps:get(workflow, EntrySpec, #{}), {parse_workflow_info(maps:get(start, Workflow, now)), parse_workflow_info(maps:get(stop, Workflow, never))}. @private parse_workflow_info(#{name := Name, value := Value}) -> {Name, Value}; parse_workflow_info(A) when is_atom(A) -> A.
null
https://raw.githubusercontent.com/vitorenesduarte/tricks/9ba11252be128be481b4d4a00fe162ccdbdac501/src/tricks.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- API gen_server callbacks @doc Run an experiment. pod body schedule pod - Default start: now - Default stop : never
Copyright ( c ) 2018 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(tricks). -author("Vitor Enes <>"). -include("tricks.hrl"). -behaviour(gen_server). -export([start_link/0, run/1]). -export([init/1, handle_call/3, handle_cast/2]). -record(state, {}). -spec start_link() -> {ok, pid()} | ignore | error(). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec run(maps:map()) -> {ok, exp_id()} | error(). run(Exp) -> gen_server:call(?MODULE, {run, Exp}, infinity). init([]) -> lager:info("tricks initialized!"), {ok, #state{}}. handle_call({run, Experiment}, _From, State) -> ExpId = do_run(Experiment), {reply, {ok, ExpId}, State}. handle_cast(Msg, State) -> {stop, {unhandled, Msg}, State}. @private Run an experiment given its config and kuberl config . do_run(Experiment) -> #{experiment := EntrySpecs} = Experiment, ExpId = tricks_exp:exp_id(), lists:foreach( fun(EntrySpec0) -> #{replicas := Replicas}=EntrySpec = set_replicas_info(EntrySpec0), {Start, End} = get_workflow_info(EntrySpec), lists:foreach( fun(PodId) -> Body = tricks_exp:pod_body(ExpId, PodId, EntrySpec), tricks_scheduler:schedule_pod(ExpId, Body, Start, End) end, lists:seq(0, Replicas - 1) ) end, EntrySpecs ), ExpId. @private Set replicas info . If not defined , set it as 1 ( default value ) . -spec set_replicas_info(maps:map()) -> maps:map(). set_replicas_info(EntrySpec0) -> case maps:is_key(replicas, EntrySpec0) of true -> EntrySpec0; false -> maps:put(replicas, 1, EntrySpec0) end. @private Get workflow info . -spec get_workflow_info(maps:map()) -> {now | event(), never | event()}. get_workflow_info(EntrySpec) -> Workflow = maps:get(workflow, EntrySpec, #{}), {parse_workflow_info(maps:get(start, Workflow, now)), parse_workflow_info(maps:get(stop, Workflow, never))}. @private parse_workflow_info(#{name := Name, value := Value}) -> {Name, Value}; parse_workflow_info(A) when is_atom(A) -> A.
e2e2d3b85405fefb671271334b7a419655545bff2ef8e4481938e8c57ecc2e6e
malcolmreynolds/GSLL
dilogarithm.lisp
Dilogarithm , Fri Mar 17 2006 - 18:44 Time - stamp : < 2008 - 10 - 21 22:57:50EDT dilogarithm.lisp > $ Id$ (in-package :gsl) ;;; dilog merge complex and real (defgeneric dilogarithm (x) "The dilogarithm.")) (defmfun dilogarithm ((x float)) "gsl_sf_dilog_e" ((x :double) (ret sf-result)) :definition :method) (defmfun dilogarithm ((x complex)) "gsl_sf_complex_dilog_e" (((abs x) :double) ((phase x) :double) (re sf-result) (im sf-result)) :definition :method :return ((complex (val re) (val im)) (complex (err re) (err im)))) (save-test dilogarithm (dilogarithm 1.0d0) (dilogarithm #c(0.0d0 1.0d0)))
null
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/special-functions/dilogarithm.lisp
lisp
dilog merge complex and real
Dilogarithm , Fri Mar 17 2006 - 18:44 Time - stamp : < 2008 - 10 - 21 22:57:50EDT dilogarithm.lisp > $ Id$ (in-package :gsl) (defgeneric dilogarithm (x) "The dilogarithm.")) (defmfun dilogarithm ((x float)) "gsl_sf_dilog_e" ((x :double) (ret sf-result)) :definition :method) (defmfun dilogarithm ((x complex)) "gsl_sf_complex_dilog_e" (((abs x) :double) ((phase x) :double) (re sf-result) (im sf-result)) :definition :method :return ((complex (val re) (val im)) (complex (err re) (err im)))) (save-test dilogarithm (dilogarithm 1.0d0) (dilogarithm #c(0.0d0 1.0d0)))
de7735517b6b063c371427a1ebf7dcedd27b47cab7501bef078908594a7942f1
ChillkroeteTTS/fischer
ws.cljs
(ns fischerboot.ws (:require [clojure.string :as str] [cljs.core.async :as async :refer (<! >! put! chan)] [taoensso.encore :as encore :refer-macros (have have?)] [taoensso.timbre :as timbre :refer-macros (tracef debugf infof warnf errorf)] [taoensso.sente :as sente :refer (cb-success?)] [fischerboot.ws-reframe-interop :as rfinterop]) (:require-macros [cljs.core.async.macros :as asyncm :refer (go go-loop)])) (let [{:keys [chsk ch-recv send-fn state]} (sente/make-channel-socket-client! "/ws" {:host "localhost:8080" :type :auto :packer :edn})] (def chsk chsk) ChannelSocket 's receive channel ChannelSocket 's send API fn , read - only atom ) (defmulti -event-msg-handler "Multimethod to handle Sente `event-msg`s" :id ; Dispatch on event-id ) (defn event-msg-handler "Wraps `-event-msg-handler` with logging, error catching, etc." [{:as ev-msg :keys [id ?data event]}] (-event-msg-handler ev-msg)) (defmethod -event-msg-handler :default ; Default/fallback case (no other matching handler) [{:as ev-msg :keys [event]}] (infof "Unhandled event: %s" event)) (defmethod -event-msg-handler :chsk/state [{:as ev-msg :keys [?data]}] (let [[old-state-map new-state-map] (have vector? ?data)] (if (:first-open? new-state-map) (infof "Channel socket successfully established!: %s" new-state-map) (infof "Channel socket state change: %s" new-state-map)))) (defmethod -event-msg-handler :chsk/recv [{:as ev-msg :keys [?data]}] (infof "Push event from server: %s" ?data) (rfinterop/handle-push-event (first ?data) (second ?data))) (defmethod -event-msg-handler :chsk/handshake [{:as ev-msg :keys [?data]}] (let [[?uid ?csrf-token ?handshake-data] ?data] (infof "Handshake: %s" ?data))) ;; TODO Add your (defmethod -event-msg-handler <event-id> [ev-msg] <body>)s here... (defonce router_ (atom nil)) (defn stop-router! [] (when-let [stop-f @router_] (stop-f))) (defn start-router! [] (stop-router!) (reset! router_ (sente/start-client-chsk-router! ch-chsk event-msg-handler))) (defn start! [] (start-router!)) (defonce _start-once (start!))
null
https://raw.githubusercontent.com/ChillkroeteTTS/fischer/2f479ac0d410f536f5bd89659d7f69113422784a/src/cljs/fischerboot/ws.cljs
clojure
Dispatch on event-id Default/fallback case (no other matching handler) TODO Add your (defmethod -event-msg-handler <event-id> [ev-msg] <body>)s here...
(ns fischerboot.ws (:require [clojure.string :as str] [cljs.core.async :as async :refer (<! >! put! chan)] [taoensso.encore :as encore :refer-macros (have have?)] [taoensso.timbre :as timbre :refer-macros (tracef debugf infof warnf errorf)] [taoensso.sente :as sente :refer (cb-success?)] [fischerboot.ws-reframe-interop :as rfinterop]) (:require-macros [cljs.core.async.macros :as asyncm :refer (go go-loop)])) (let [{:keys [chsk ch-recv send-fn state]} (sente/make-channel-socket-client! "/ws" {:host "localhost:8080" :type :auto :packer :edn})] (def chsk chsk) ChannelSocket 's receive channel ChannelSocket 's send API fn , read - only atom ) (defmulti -event-msg-handler "Multimethod to handle Sente `event-msg`s" ) (defn event-msg-handler "Wraps `-event-msg-handler` with logging, error catching, etc." [{:as ev-msg :keys [id ?data event]}] (-event-msg-handler ev-msg)) (defmethod -event-msg-handler [{:as ev-msg :keys [event]}] (infof "Unhandled event: %s" event)) (defmethod -event-msg-handler :chsk/state [{:as ev-msg :keys [?data]}] (let [[old-state-map new-state-map] (have vector? ?data)] (if (:first-open? new-state-map) (infof "Channel socket successfully established!: %s" new-state-map) (infof "Channel socket state change: %s" new-state-map)))) (defmethod -event-msg-handler :chsk/recv [{:as ev-msg :keys [?data]}] (infof "Push event from server: %s" ?data) (rfinterop/handle-push-event (first ?data) (second ?data))) (defmethod -event-msg-handler :chsk/handshake [{:as ev-msg :keys [?data]}] (let [[?uid ?csrf-token ?handshake-data] ?data] (infof "Handshake: %s" ?data))) (defonce router_ (atom nil)) (defn stop-router! [] (when-let [stop-f @router_] (stop-f))) (defn start-router! [] (stop-router!) (reset! router_ (sente/start-client-chsk-router! ch-chsk event-msg-handler))) (defn start! [] (start-router!)) (defonce _start-once (start!))
4666158aebeadc7fb619869332ef62f741812ba9781a655ea4c561ed0d3bb3d4
developandplay/material-components-web-miso
LinearProgress.hs
{-# LANGUAGE OverloadedStrings #-} module Material.LinearProgress ( Config (..), config, setReverse, setClosed, setAttributes, indeterminate, determinate, buffered, ) where import qualified Data.Map as M import Data.Maybe import Miso -- | Linear progress configuration data Config msg = Config { reverse :: Bool, closed :: Bool, additionalAttributes :: [Attribute msg] } data Variant = Indeterminate | Determinate Float | Buffered Float Float deriving (Eq) -- | Default linear progress configuration config :: Config msg config = Config { Material.LinearProgress.reverse = False, closed = False, additionalAttributes = [] } -- | Specify whether a linear progress indicator should be hidden setClosed :: Bool -> Config msg -> Config msg setClosed closed config_ = config_ {closed = closed} -- | Specify whether the direction of a linear progress indicator should be reversed setReverse :: Bool -> Config msg -> Config msg setReverse reverse config_ = config_ {Material.LinearProgress.reverse = reverse} -- | Specify additional attributes setAttributes :: [Attribute msg] -> Config msg -> Config msg setAttributes additionalAttributes config_ = config_ {additionalAttributes = additionalAttributes} linearProgress :: Variant -> Config msg -> View msg linearProgress variant (config_@Config {additionalAttributes = additionalAttributes}) = nodeHtml "mdc-linear-progress" ( mapMaybe id [ rootCs, displayCss, roleAttr, variantCs variant, determinateProp variant, progressProp variant, bufferProp variant, reverseProp config_, closedProp config_ ] ++ additionalAttributes ) [ bufferElt, primaryBarElt, secondaryBarElt ] -- | Indeterminate linear progress variant indeterminate :: Config msg -> View msg indeterminate config_ = linearProgress Indeterminate config_ -- | Determinate linear progress variant determinate :: Config msg -> Float -> View msg determinate config_ progress = linearProgress (Determinate progress) config_ -- | Buffered linear progress variant buffered :: Config msg -> Float -> Float -> View msg buffered config_ progress buffered = linearProgress (Buffered progress buffered) config_ rootCs :: Maybe (Attribute msg) rootCs = Just (class_ "mdc-linear-progress") displayCss :: Maybe (Attribute msg) displayCss = Just (style_ $ M.singleton "display" "block") roleAttr :: Maybe (Attribute msg) roleAttr = Just (stringProp "role" "progressbar") variantCs :: Variant -> Maybe (Attribute msg) variantCs variant = case variant of Indeterminate -> Just (class_ "mdc-linear-progress--indeterminate") _ -> Nothing determinateProp :: Variant -> Maybe (Attribute msg) determinateProp variant = Just (boolProp "determinate" (variant /= Indeterminate)) progressProp :: Variant -> Maybe (Attribute msg) progressProp variant = Just ( prop "progress" ( case variant of Determinate progress -> progress Buffered progress _ -> progress _ -> 0 ) ) bufferProp :: Variant -> Maybe (Attribute msg) bufferProp variant = Just ( prop "buffer" ( case variant of Buffered _ buffer -> buffer _ -> 0 ) ) reverseProp :: Config msg -> Maybe (Attribute msg) reverseProp Config {Material.LinearProgress.reverse = reverse} = case reverse of False -> Nothing True -> Just (boolProp "reverse" reverse) closedProp :: Config msg -> Maybe (Attribute msg) closedProp Config {closed = closed} = Just (boolProp "closed" closed) bufferElt :: View msg bufferElt = div_ [class_ "mdc-linear-progress__buffer"] [ bufferBarElt, bufferDotsElt ] bufferBarElt :: View msg bufferBarElt = div_ [class_ "mdc-linear-progress__buffer-bar"] [] bufferDotsElt :: View msg bufferDotsElt = div_ [class_ "mdc-linear-progress__buffer-dots"] [] primaryBarElt :: View msg primaryBarElt = div_ [class_ "mdc-linear-progress__bar mdc-linear-progress__primary-bar"] [barInnerElt] secondaryBarElt :: View msg secondaryBarElt = div_ [class_ "mdc-linear-progress__bar mdc-linear-progress__secondary-bar"] [barInnerElt] barInnerElt :: View msg barInnerElt = div_ [class_ "mdc-linear-progress__bar-inner"] []
null
https://raw.githubusercontent.com/developandplay/material-components-web-miso/97a20097bf522b62743c884b66757eb895edd690/sample-app-jsaddle/Material/LinearProgress.hs
haskell
# LANGUAGE OverloadedStrings # | Linear progress configuration | Default linear progress configuration | Specify whether a linear progress indicator should be hidden | Specify whether the direction of a linear progress indicator should be reversed | Specify additional attributes | Indeterminate linear progress variant | Determinate linear progress variant | Buffered linear progress variant
module Material.LinearProgress ( Config (..), config, setReverse, setClosed, setAttributes, indeterminate, determinate, buffered, ) where import qualified Data.Map as M import Data.Maybe import Miso data Config msg = Config { reverse :: Bool, closed :: Bool, additionalAttributes :: [Attribute msg] } data Variant = Indeterminate | Determinate Float | Buffered Float Float deriving (Eq) config :: Config msg config = Config { Material.LinearProgress.reverse = False, closed = False, additionalAttributes = [] } setClosed :: Bool -> Config msg -> Config msg setClosed closed config_ = config_ {closed = closed} setReverse :: Bool -> Config msg -> Config msg setReverse reverse config_ = config_ {Material.LinearProgress.reverse = reverse} setAttributes :: [Attribute msg] -> Config msg -> Config msg setAttributes additionalAttributes config_ = config_ {additionalAttributes = additionalAttributes} linearProgress :: Variant -> Config msg -> View msg linearProgress variant (config_@Config {additionalAttributes = additionalAttributes}) = nodeHtml "mdc-linear-progress" ( mapMaybe id [ rootCs, displayCss, roleAttr, variantCs variant, determinateProp variant, progressProp variant, bufferProp variant, reverseProp config_, closedProp config_ ] ++ additionalAttributes ) [ bufferElt, primaryBarElt, secondaryBarElt ] indeterminate :: Config msg -> View msg indeterminate config_ = linearProgress Indeterminate config_ determinate :: Config msg -> Float -> View msg determinate config_ progress = linearProgress (Determinate progress) config_ buffered :: Config msg -> Float -> Float -> View msg buffered config_ progress buffered = linearProgress (Buffered progress buffered) config_ rootCs :: Maybe (Attribute msg) rootCs = Just (class_ "mdc-linear-progress") displayCss :: Maybe (Attribute msg) displayCss = Just (style_ $ M.singleton "display" "block") roleAttr :: Maybe (Attribute msg) roleAttr = Just (stringProp "role" "progressbar") variantCs :: Variant -> Maybe (Attribute msg) variantCs variant = case variant of Indeterminate -> Just (class_ "mdc-linear-progress--indeterminate") _ -> Nothing determinateProp :: Variant -> Maybe (Attribute msg) determinateProp variant = Just (boolProp "determinate" (variant /= Indeterminate)) progressProp :: Variant -> Maybe (Attribute msg) progressProp variant = Just ( prop "progress" ( case variant of Determinate progress -> progress Buffered progress _ -> progress _ -> 0 ) ) bufferProp :: Variant -> Maybe (Attribute msg) bufferProp variant = Just ( prop "buffer" ( case variant of Buffered _ buffer -> buffer _ -> 0 ) ) reverseProp :: Config msg -> Maybe (Attribute msg) reverseProp Config {Material.LinearProgress.reverse = reverse} = case reverse of False -> Nothing True -> Just (boolProp "reverse" reverse) closedProp :: Config msg -> Maybe (Attribute msg) closedProp Config {closed = closed} = Just (boolProp "closed" closed) bufferElt :: View msg bufferElt = div_ [class_ "mdc-linear-progress__buffer"] [ bufferBarElt, bufferDotsElt ] bufferBarElt :: View msg bufferBarElt = div_ [class_ "mdc-linear-progress__buffer-bar"] [] bufferDotsElt :: View msg bufferDotsElt = div_ [class_ "mdc-linear-progress__buffer-dots"] [] primaryBarElt :: View msg primaryBarElt = div_ [class_ "mdc-linear-progress__bar mdc-linear-progress__primary-bar"] [barInnerElt] secondaryBarElt :: View msg secondaryBarElt = div_ [class_ "mdc-linear-progress__bar mdc-linear-progress__secondary-bar"] [barInnerElt] barInnerElt :: View msg barInnerElt = div_ [class_ "mdc-linear-progress__bar-inner"] []
bf0419e2a588f083e8783b78dcf6a9c4c80cb20fae56c0d7c1fd3c13166501c6
mbutterick/beautiful-racket
chip8.rkt
#lang br ;-to-write-an-emulator-chip-8-interpreter/ ; ; (define (split-bytes val) (cond [(zero? val) (list 0)] [else (define-values (bytes residual) (for/fold ([bytes empty][residual val]) ([i (in-naturals)] #:break (zero? residual)) (define m (modulo residual 16)) (values (cons m bytes) (arithmetic-shift residual -4)))) bytes])) (module+ test (require rackunit) (check-equal? (split-bytes #x2B45) (list #x2 #xB #x4 #x5)) (check-equal? (split-bytes #xCD) (list #xC #xD)) (check-equal? (split-bytes #xA) (list #xA)) (check-equal? (split-bytes #x0) (list #x0))) (define (join-bytes bytes) (for/sum ([b (in-list (reverse bytes))] [i (in-naturals)]) (* b (expt 16 i)))) (module+ test (check-equal? #x2B45 (join-bytes (list #x2 #xB #x4 #x5))) (check-equal? #xCD (join-bytes (list #xC #xD))) (check-equal? #xA (join-bytes (list #xA))) (check-equal? #x0 (join-bytes (list #x0)))) (define-macro (define-memory-vector ID [FIELD LENGTH SIZE] ...) (with-pattern ([(PREFIXED-ID ...) (prefix-id #'ID "-" #'(FIELD ...))] [(PREFIXED-ID-REF ...) (suffix-id #'(PREFIXED-ID ...) "-ref")] [(PREFIXED-ID-SET! ...) (suffix-id #'(PREFIXED-ID ...) "-set!")] [(FIELD-OFFSET ...) (reverse (cdr (for/fold ([accum-stxs (list #'0)]) ([len-size-stx (in-list (syntax->list #'((LENGTH SIZE) ...)))]) (cons (with-pattern ([accum (car accum-stxs)] [(len size) len-size-stx]) #'(+ (* len size) accum)) accum-stxs))))]) #'(begin (define ID (make-vector (+ (* LENGTH SIZE) ...))) (define (PREFIXED-ID-REF idx) (unless (< idx LENGTH) (raise-argument-error 'PREFIXED-ID-REF (format "index less than field length ~a" LENGTH) idx)) (join-bytes (for/list ([i (in-range SIZE)]) (vector-ref ID (+ FIELD-OFFSET i idx))))) ... (define (PREFIXED-ID-SET! idx val) (unless (< idx LENGTH) (raise-argument-error 'PREFIXED-ID-SET! (format "index less than field length ~a" LENGTH) idx)) (unless (< val (expt 16 SIZE)) (raise-argument-error 'PREFIXED-ID-SET! (format "value less than field size ~a" (expt 16 SIZE)) val)) (for ([i (in-range SIZE)] [b (in-list (split-bytes val))]) (vector-set! ID (+ FIELD-OFFSET i idx) b))) ...))) (define-memory-vector chip8 two bytes one byte per one byte per index register , 0x000 to 0xFFF ( 1.5 bytes ) program counter , 0x000 to 0xFFF ( 1.5 bytes ) [gfx (* 64 32) 1] ; pixels [delay_timer 1 1] [sound_timer 1 1] 2 bytes each [sp 1 2] ; stack pointer [key 16 1]) ; keys ;; Set up render system and register input callbacks ;(setup-graphics chip8) ;(setup-input chip8) Initialize the Chip8 system and load the game into the memory #;(define (initialize c) Initialize registers and memory once ) ;(initialize chip8) ;(load-game chip8 "pong") #;(define (emulate-cycle c) // ; // Decode Opcode ; // Execute Opcode ; ; // Update timers ) ;; Emulation loop #;(let loop () ;; Emulate one cycle (emulate-cycle chip8) ;; If the draw flag is set, update the screen (when (draw-flag? chip8) (draw-graphics chip8)) Store key press state ( Press and Release ) (set-keys chip8) (loop))
null
https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/chip8-demo/chip8.rkt
racket
-to-write-an-emulator-chip-8-interpreter/ pixels stack pointer keys Set up render system and register input callbacks (setup-graphics chip8) (setup-input chip8) (define (initialize c) (initialize chip8) (load-game chip8 "pong") (define (emulate-cycle c) // Decode Opcode // Execute Opcode // Update timers Emulation loop (let loop () Emulate one cycle If the draw flag is set, update the screen
#lang br (define (split-bytes val) (cond [(zero? val) (list 0)] [else (define-values (bytes residual) (for/fold ([bytes empty][residual val]) ([i (in-naturals)] #:break (zero? residual)) (define m (modulo residual 16)) (values (cons m bytes) (arithmetic-shift residual -4)))) bytes])) (module+ test (require rackunit) (check-equal? (split-bytes #x2B45) (list #x2 #xB #x4 #x5)) (check-equal? (split-bytes #xCD) (list #xC #xD)) (check-equal? (split-bytes #xA) (list #xA)) (check-equal? (split-bytes #x0) (list #x0))) (define (join-bytes bytes) (for/sum ([b (in-list (reverse bytes))] [i (in-naturals)]) (* b (expt 16 i)))) (module+ test (check-equal? #x2B45 (join-bytes (list #x2 #xB #x4 #x5))) (check-equal? #xCD (join-bytes (list #xC #xD))) (check-equal? #xA (join-bytes (list #xA))) (check-equal? #x0 (join-bytes (list #x0)))) (define-macro (define-memory-vector ID [FIELD LENGTH SIZE] ...) (with-pattern ([(PREFIXED-ID ...) (prefix-id #'ID "-" #'(FIELD ...))] [(PREFIXED-ID-REF ...) (suffix-id #'(PREFIXED-ID ...) "-ref")] [(PREFIXED-ID-SET! ...) (suffix-id #'(PREFIXED-ID ...) "-set!")] [(FIELD-OFFSET ...) (reverse (cdr (for/fold ([accum-stxs (list #'0)]) ([len-size-stx (in-list (syntax->list #'((LENGTH SIZE) ...)))]) (cons (with-pattern ([accum (car accum-stxs)] [(len size) len-size-stx]) #'(+ (* len size) accum)) accum-stxs))))]) #'(begin (define ID (make-vector (+ (* LENGTH SIZE) ...))) (define (PREFIXED-ID-REF idx) (unless (< idx LENGTH) (raise-argument-error 'PREFIXED-ID-REF (format "index less than field length ~a" LENGTH) idx)) (join-bytes (for/list ([i (in-range SIZE)]) (vector-ref ID (+ FIELD-OFFSET i idx))))) ... (define (PREFIXED-ID-SET! idx val) (unless (< idx LENGTH) (raise-argument-error 'PREFIXED-ID-SET! (format "index less than field length ~a" LENGTH) idx)) (unless (< val (expt 16 SIZE)) (raise-argument-error 'PREFIXED-ID-SET! (format "value less than field size ~a" (expt 16 SIZE)) val)) (for ([i (in-range SIZE)] [b (in-list (split-bytes val))]) (vector-set! ID (+ FIELD-OFFSET i idx) b))) ...))) (define-memory-vector chip8 two bytes one byte per one byte per index register , 0x000 to 0xFFF ( 1.5 bytes ) program counter , 0x000 to 0xFFF ( 1.5 bytes ) [delay_timer 1 1] [sound_timer 1 1] 2 bytes each Initialize the Chip8 system and load the game into the memory Initialize registers and memory once ) // ) (emulate-cycle chip8) (when (draw-flag? chip8) (draw-graphics chip8)) Store key press state ( Press and Release ) (set-keys chip8) (loop))
6eabdea66e422efca3fe64164dbc2a0589db1a8f5c64c74cecca78a17186200a
serperu/secer
orddict_tests.erl
-module(orddict_tests). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). from_list_old_test() -> from_list_test_common(orddict_old). from_list_new_ok_test() -> from_list_test_common(orddict_new_ok). from_list_new_wrong_test() -> from_list_test_common(orddict_new_wrong). from_list_test_common(Mod) -> ?assertEqual( [{0,1}, {1, 2}, {2, 3}], Mod:from_list([{0,1}, {1, 2}, {2, 3}])), ?assertEqual( [{0,2}, {2, 3}], Mod:from_list([{0,1}, {0, 2}, {2, 3}])), ?assertError( function_clause, Mod:from_list([1, {1, 2}, {2, 3}])). from_list_old_test_vs_new_wrong_test() -> from_list_vs(orddict_old, orddict_new_wrong). from_list_old_test_vs_new_ok_test() -> from_list_vs(orddict_old, orddict_new_ok). from_list_vs(Mod1, Mod2) -> Case1 = [{0,1}, {1, 2}, {2, 3}], Case2 = [{0,1}, {0, 2}, {2, 3}], Case3 = [1, {1, 2}, {2, 3}], ?assertEqual( Mod1:from_list(Case1), Mod2:from_list(Case1)), ?assertEqual( Mod1:from_list(Case2), Mod2:from_list(Case2)), ?assertEqual( Mod1:from_list(Case3), Mod2:from_list(Case3)).
null
https://raw.githubusercontent.com/serperu/secer/ffe2f9602356c34c9465c44534c82cc758b809b5/examples/orddict/orddict_tests.erl
erlang
-module(orddict_tests). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). from_list_old_test() -> from_list_test_common(orddict_old). from_list_new_ok_test() -> from_list_test_common(orddict_new_ok). from_list_new_wrong_test() -> from_list_test_common(orddict_new_wrong). from_list_test_common(Mod) -> ?assertEqual( [{0,1}, {1, 2}, {2, 3}], Mod:from_list([{0,1}, {1, 2}, {2, 3}])), ?assertEqual( [{0,2}, {2, 3}], Mod:from_list([{0,1}, {0, 2}, {2, 3}])), ?assertError( function_clause, Mod:from_list([1, {1, 2}, {2, 3}])). from_list_old_test_vs_new_wrong_test() -> from_list_vs(orddict_old, orddict_new_wrong). from_list_old_test_vs_new_ok_test() -> from_list_vs(orddict_old, orddict_new_ok). from_list_vs(Mod1, Mod2) -> Case1 = [{0,1}, {1, 2}, {2, 3}], Case2 = [{0,1}, {0, 2}, {2, 3}], Case3 = [1, {1, 2}, {2, 3}], ?assertEqual( Mod1:from_list(Case1), Mod2:from_list(Case1)), ?assertEqual( Mod1:from_list(Case2), Mod2:from_list(Case2)), ?assertEqual( Mod1:from_list(Case3), Mod2:from_list(Case3)).
27a900503963cd8fe4db70802c5d9b3a8fab122d9db2b1e010bbef60b0877d3e
zalando-stups/kio
user.clj
(ns user "Tools for interactive development with the REPL. This file should not be included in a production build of the application." (:require [clojure.java.javadoc :refer [javadoc]] [clojure.pprint :refer [pprint]] [clojure.reflect :refer [reflect]] [clojure.repl :refer [apropos dir doc find-doc pst source]] [clojure.tools.namespace.repl :refer [refresh refresh-all]] [com.stuartsierra.component :as component] [clojure.test :refer [run-all-tests]] [org.zalando.stups.kio.core :as core])) (def system "A Var containing an object representing the application under development." nil) (defn slurp-if-exists [file] (when (.exists (clojure.java.io/as-file file)) (slurp file))) (defn load-dev-config [file] (clojure.edn/read-string (slurp-if-exists file))) (defn start "Starts the system running, sets the Var #'system." [extra-config] (alter-var-root #'system (constantly (core/run (merge {:system-log-level "INFO"} extra-config (load-dev-config "./dev-config.edn")))))) (defn stop "Stops the system if it is currently running, updates the Var #'system." [] (alter-var-root #'system (fn [s] (when s (component/stop s))))) (defn go "Initializes and starts the system running." ([extra-config] (start extra-config) :ready) ([] (go {}))) (defn reset "Stops the system, reloads modified source files, and restarts it." [] (stop) (refresh :after 'user/go)) (defn run-tests [] (run-all-tests #"org.zalando.stups.kio.unit-test.*-test")) (defn run-integration-tests [] (run-all-tests #"org.zalando.stups.kio.integration-test.*-test")) (defn tests "Stops the system, reloads modified source files and runs tests" [] (stop) (refresh :after 'user/run-tests))
null
https://raw.githubusercontent.com/zalando-stups/kio/d84dd2e27d155340c4d2ae45908a11d637563493/dev/user.clj
clojure
(ns user "Tools for interactive development with the REPL. This file should not be included in a production build of the application." (:require [clojure.java.javadoc :refer [javadoc]] [clojure.pprint :refer [pprint]] [clojure.reflect :refer [reflect]] [clojure.repl :refer [apropos dir doc find-doc pst source]] [clojure.tools.namespace.repl :refer [refresh refresh-all]] [com.stuartsierra.component :as component] [clojure.test :refer [run-all-tests]] [org.zalando.stups.kio.core :as core])) (def system "A Var containing an object representing the application under development." nil) (defn slurp-if-exists [file] (when (.exists (clojure.java.io/as-file file)) (slurp file))) (defn load-dev-config [file] (clojure.edn/read-string (slurp-if-exists file))) (defn start "Starts the system running, sets the Var #'system." [extra-config] (alter-var-root #'system (constantly (core/run (merge {:system-log-level "INFO"} extra-config (load-dev-config "./dev-config.edn")))))) (defn stop "Stops the system if it is currently running, updates the Var #'system." [] (alter-var-root #'system (fn [s] (when s (component/stop s))))) (defn go "Initializes and starts the system running." ([extra-config] (start extra-config) :ready) ([] (go {}))) (defn reset "Stops the system, reloads modified source files, and restarts it." [] (stop) (refresh :after 'user/go)) (defn run-tests [] (run-all-tests #"org.zalando.stups.kio.unit-test.*-test")) (defn run-integration-tests [] (run-all-tests #"org.zalando.stups.kio.integration-test.*-test")) (defn tests "Stops the system, reloads modified source files and runs tests" [] (stop) (refresh :after 'user/run-tests))
599dda2b76d3642184f9b565b7dee50d020d1f2f1f9b9a097935fe70dcc3abde
melhadad/fuf
alt.lisp
;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package: FUG5 -*- ;;; ----------------------------------------------------------------------- ;;; File: alt.l ;;; Description: Unification of disjunctions Author : Created : 22 May 1990 ;;; Modified: find-good-branches returns a list of all branches ;;; compatible with index - allows for none in index. ;;; allows for typed constants in index. ;;; 15 Jun 90: Added pair argument. ;;; 02 Jul 90: Added path2 arg. 22 Feb 91 : Allowed list of bk - class instead of only 1 . ;;; 28 Jul 91: New syntax for alts (:x and order free). Add IGNORE and WAIT ( freeze ) . 11 Aug 91 : Add trace fro IGNORE and WAIT . ;;; 29 Oct 91: Fix trace-format calls. Add *trace-wait*. ;;; 09 Dec 91: Added after-wait in alt-unify and descendants. ;;; 02 Jan 91: Fixed indexed to accept random order too. 03 Jan 91 : Untrace alt when freezing . ;;; 20 Oct 92: Added level to trace-format and trace-demo Package : FUG5 ;;; ----------------------------------------------------------------------- ;;; FUF - a functional unification - based text generation system . ( . 5.4 ) ;;; Copyright ( c ) 1987 - 2014 by . all rights reserved . ;;; ;;; Permission to use, copy, and/or distribute for any purpose and ;;; without fee is hereby granted, provided that both the above copyright ;;; notice and this permission notice appear in all copies and derived works. ;;; Fees for distribution or use of this software or derived works may only ;;; be charged with express written permission of the copyright holder. THIS SOFTWARE IS PROVIDED ` ` AS IS '' WITHOUT EXPRESS OR IMPLIED WARRANTY . ;;; ----------------------------------------------------------------------- (in-package "FUG5") (format t "Alt unifier...~%") ;; ------------------------------------------------------------ ;; Functions to deal with NON-deterministic unifications These functions modify their argument FAIL each time a choice ;; is made. ;; ------------------------------------------------------------ ;; ------------------------------------------------------------ UTILITIES to manipulate alt expressions ;; Kept for old syntax only. Not useful anymore. ;; ------------------------------------------------------------ (defun alt-trace-expr (sexpr) (or (leaf-p sexpr) (and (consp sexpr) (eq (car sexpr) 'trace)))) (defun alt-trace-flag (sexpr) (if (leaf-p sexpr) sexpr (car (last sexpr)))) (defun alt-index-expr (sexpr) (and (consp sexpr) (eq (car sexpr) 'index))) (defun alt-index-attr (sexpr) (car (last sexpr))) (defun alt-demo-expr (sexpr) (and (consp sexpr) (eq (car sexpr) 'demo-message))) (defun alt-bk-class-expr (sexpr) (and (consp sexpr) (eq (car sexpr) 'bk-class))) (defun alt-bk-class-class (sexpr) (let ((expr (last sexpr))) (if (symbolp (car expr)) expr (car (last sexpr))))) (proclaim '(inline alt-trace-expr alt-trace-flag alt-index-expr alt-index-attr alt-demo-expr alt-bk-class-expr alt-bk-class-class)) ;; Utility to display an underlined demo message when tracing (defun show-demo-msg (demo traced frame) (when demo (trace-demo traced frame 12 "") (trace-demo traced frame 12 demo) (trace-demo traced frame 12 "~a" (make-sequence 'string (length demo) :initial-element #\-)))) ;; --------------------------------------------------------------------- ;; BRANCHES: takes an alt pair and return the branches, possibly ;; a tracing flag and an index declaration ( 9 values : branches traced indexed demo bk - class order wait ;; ignore-unless ignore-when) OPTIONS : same as branches for an opt pair . returns 3 values . ;; --------------------------------------------------------------------- ;; NEW Syntax of alt-pair is (:x notation is prefered, old one kept for compatibility ) . [ Jul 28 , 1991 ] ;; (alt { traceflag | (trace on traceflag) | (:trace flag) } ;; { (index on path) | (:index path)} ;; { (demo str) | (:demo str)} ;; { (bk-class class) | (:bk-class class) } ;; { (:order {:random | :sequential}) } ;; { (:wait list) } ;; { (:ignore list) } ;; ( fd1 ... fdn )) ;; NOW ALLOW ANNOTATIONS IN ANY ORDER. (defun find-alt-annotation (key alt) "Extract the value val of annotation (key val) in an alt pair. Return nil if no annotation for key is found." (let ((pair (safe-assoc key alt))) (if pair (second pair) ;; Deal with old syntax for compatibility (case key (:trace (alt-trace-flag (safe-assoc 'trace alt))) (:index (alt-index-attr (safe-assoc 'index alt))) (:demo (safe-second (safe-assoc 'demo alt))) (:bk-class (alt-bk-class-class (safe-assoc 'bk-class alt))) (otherwise nil))))) (defun branches (alt-pair) (setq alt-pair (cdr alt-pair)) (let ((traced nil) (indexed nil) (demo nil) (bk-class nil) (order nil) (wait nil) (ignore-unless nil) (ignore-when nil) (branches nil)) First special case of trace that can be a single atom (when (alt-trace-expr (car alt-pair)) (setq traced (alt-trace-flag (pop alt-pair)))) ;; Now all annotations are in pair formats (unless traced (setq traced (find-alt-annotation :trace alt-pair))) (setq indexed (find-alt-annotation :index alt-pair)) (setq demo (find-alt-annotation :demo alt-pair)) (setq bk-class (find-alt-annotation :bk-class alt-pair)) (setq order (find-alt-annotation :order alt-pair)) (setq wait (normalize-wait (find-alt-annotation :wait alt-pair))) (setq ignore-unless (find-alt-annotation :ignore-unless alt-pair)) (setq ignore-when (find-alt-annotation :ignore-when alt-pair)) ;; branches must be last (setq branches (car (last alt-pair))) ;; Normalize values of annotations (if (path-p indexed) (setq indexed (path-l indexed))) (unless (listp indexed) (setq indexed (list indexed))) (when (stringp demo) (setq demo (format nil demo))) (unless (listp wait) (setq wait (list wait))) (unless (eq order :random) (setq order :sequential)) (values branches traced indexed demo bk-class order wait ignore-unless ignore-when))) ;; Syntax of opt-pair is: ;; (opt { trace } { (bk-class class) } fd) (defun option (opt-pair) (setq opt-pair (cdr opt-pair)) (let ((trace nil) (bk-class nil) (fd nil)) (when (alt-trace-expr (car opt-pair)) (setq trace (alt-trace-flag (pop opt-pair)))) (if (alt-bk-class-expr (car opt-pair)) (setq bk-class (alt-bk-class-class (pop opt-pair)) fd (car opt-pair)) (if (null opt-pair) (setq fd trace trace nil) (setq fd (car opt-pair)))) (values fd trace bk-class))) ;; --------------------------------------------------------------------- ;; FIND-GOOD-BRANCHES: filter out branches that do not match the key of an ;; index: hence the constraint on the index of an alt: ;; the value of an index can be a pointer - but it MUST NOT point outside ;; of the branch or within a disjunction in the branch. ;; --------------------------------------------------------------------- (defun find-good-branches (key index branches) (remove-if-not #'(lambda (branch) (let ((val-in-branch (top-gdp branch (make-path :l index)))) (or (null val-in-branch) (and key (eq 'given val-in-branch)) (eq 'any val-in-branch) (subsume val-in-branch key) (and (if *use-given* (not (underp val-in-branch)) t) (subsume key val-in-branch))))) branches)) ;; --------------------------------------------------------------------- ;; OPT-UNIFY ;; --------------------------------------------------------------------- (defun opt-unify (fd1 fd2 path1 path2 frame fail success &key (pair :unknown)) (multiple-value-bind (option flag bk-class) (option (car fd2)) (when (trace-enabled flag) (handle-trace flag frame t)) (trace-format flag frame 10 "Trying with option ~s at level ~s" flag path1) (backtrack frame new-frame bk-class flag (unify fd1 option path1 path2 new-frame (make-failure fail (when (trace-enabled flag) (handle-trace flag frame t) (trace-format flag frame 10 "Trying without option ~s at level ~s~%" flag path1)) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair)) #'(lambda (fd fail frame) (when (trace-enabled flag) (trace-format flag frame 10 "Success with option ~s at level ~s~%" flag path1) (handle-trace flag frame t)) (unify fd (cdr fd2) path1 path2 frame fail success :pair pair)) :pair pair)))) ;; --------------------------------------------------------------------- ;; ALT-UNIFY ;; --------------------------------------------------------------------- ;; alt-unify parses the alt construct and based on annotations, dispatches ;; to the appropriate specialized function. (defun alt-unify (fd1 fd2 path1 path2 frame fail success &key indexed-given order-given force-wait after-wait (pair :unknown) &aux key) (declare (special *input*)) (multiple-value-bind (branches traced indexed demo bk-class order wait ignore-unless ignore-when) (branches (car fd2)) ;; Handle tracing messages (when (trace-enabled traced) (show-demo-msg demo traced frame) (push traced (frame-trace-flags frame)) (incf (frame-trace-level frame))) ;; indexed and order can be given as arg or from annotations. arg ;; prevails. ;; force-wait t means don't consider the wait annotation. (when order-given (setq order order-given)) (when force-wait (setq wait nil)) (unless indexed (setq indexed indexed-given)) (when indexed (setq key (gdp *input* (make-path :l (append (path-l path1) indexed))))) Dispatch based on annotations to specialized function (cond ((null branches) (error "An alt must have at least one branch")) NOTE : WAIT has priority on IGNORE ;; WAIT annotation: if need to freeze, push on agenda and continue ((not (check-wait wait path2)) (let ((id (add-agenda frame (car fd2) wait path1 path2 after-wait indexed order ignore-unless ignore-when pair))) (trace-format (or *trace-wait* (trace-enabled traced)) frame 15 "Freezing alt ~s: waiting for ~s [agenda ~s]" traced wait id) (when (trace-enabled traced) (pop (frame-trace-flags frame)) (decf (frame-trace-level frame))) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair))) IGNORE annotations ((check-ignore-unless ignore-unless path1 path2) (trace-format traced frame 15 "Ignoring alt ~s: ignore-unless matches" traced) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair)) ((check-ignore-when ignore-when path1 path2) (trace-format traced frame 15 "Ignoring alt ~s: ignore-when matches" traced) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair)) ;; INDEX annotation ((not (member key '(nil any given))) (alt-unify-indexed fd1 (cdr fd2) path1 path2 bk-class frame fail success after-wait traced key branches indexed :random order :pair pair)) ;; OK, proceed (t (when (and indexed demo) (trace-demo traced frame 5 "Key not specified in input. Need to search")) (trace-format (and (trace-enabled traced) indexed) frame 5 "No value given in input for index ~s - No jump" indexed) (if (eq order :random) (ralt-unify-simple fd1 (cdr fd2) path1 path2 bk-class frame fail success after-wait traced (copy-list branches) 1 branches :pair pair) (alt-unify-simple fd1 (cdr fd2) path1 path2 bk-class frame fail success after-wait traced branches 1 nil :pair pair)))))) ;; --------------------------------------------------------------------- ALT - UNIFY - SIMPLE : alt is not indexed . Traverse each branch , and backtrack ;; to the next branch if fail. When no more branch, fail. ;; (change the fail argument when trying a branch) ;; NOTE: orig-branches is just used for tracing purposes when called from ;; alt-unify-indexed to identify the current branch in the textual ;; representation of the grammar. ;; --------------------------------------------------------------------- (defun alt-unify-simple (fd1 fd2 path1 path2 bk-class frame fail success after-wait traced branches branch-number orig-branches &key (pair :unknown)) ; eat the tracing flags between branches (when (and (tracing-flag (car branches)) (trace-enabled (car branches))) (handle-trace (pop branches) frame)) (cond ((null branches) (when (trace-enabled traced) (trace-format traced frame 30 "Fail in alt ~s at level ~s~%" traced path1) (handle-trace traced frame t)) (*fail* fail frame *same* path2 pair)) (t (trace-format traced frame 10 "Entering alt ~s -- Branch #~s" traced (if orig-branches (1+ (position (car branches) orig-branches :test #'equalp)) branch-number)) (backtrack frame new-frame bk-class traced (unify fd1 (car branches) path1 path2 new-frame (make-failure fail (alt-unify-simple fd1 fd2 path1 path2 bk-class frame fail success after-wait traced (cdr branches) (1+ branch-number) orig-branches :pair pair)) #'(lambda (fd fail frame) (when (trace-enabled traced) (trace-format traced frame 10 "Success with branch ~s in alt ~s~%" branch-number traced) (handle-trace traced frame t)) (when after-wait (funcall after-wait)) (unify fd fd2 path1 path2 frame fail success :pair pair)) :pair pair))))) ;; --------------------------------------------------------------------- ;; ALT-UNIFY-INDEXED: alt is indexed. ;; Prune the set of branches to retain only those compatible with index. If only one branch , unification is deterministic , just jump to the right ;; branch and use it. If more than one , search on restricted set . ;; --------------------------------------------------------------------- (defun alt-unify-indexed (fd1 fd2 path1 path2 bk-class frame fail success after-wait traced key branches indexed &key random (pair :unknown)) (let ((good-branches (find-good-branches key indexed branches))) (cond ((null good-branches) (trace-format traced frame 30 "fail on indexed alt ~s: no branch in ~ the grammar for ~s~%" traced key) (*fail* fail frame *same* path2 pair)) ((= 1 (length good-branches)) (trace-format traced frame 10 "Entering alt ~s -- Jump indexed to branch #~s: ~ ~s matches input ~s" traced (1+ (position (car good-branches) branches :test #'equalp)) (top-gdp (car good-branches) (make-path :l indexed)) key) (unify fd1 (car good-branches) path1 path2 frame fail #'(lambda (fd fail frame) (when traced (trace-format traced frame 10 "Success with branch #~s ~s in alt ~s~%" (1+ (position (car good-branches) branches :test #'equalp)) key traced) (handle-trace traced frame t)) (when after-wait (funcall after-wait)) (unify fd fd2 path1 path2 frame fail success :pair pair)) :pair pair)) (t (if traced (trace-format traced frame 5 "Entering indexed ~a ~s -- Trying with ~s branches out of ~s" (if random "Ralt" "alt") traced (length good-branches) (length branches))) (if (eq random :random) (ralt-unify-simple fd1 fd2 path1 path2 bk-class frame fail success after-wait traced good-branches 1 branches :pair pair) (alt-unify-simple fd1 fd2 path1 path2 bk-class frame fail success after-wait traced good-branches 1 branches :pair pair)))))) ;; ----------------------------------------------------------------------- (provide "$fug5/alt") ;; -----------------------------------------------------------------------
null
https://raw.githubusercontent.com/melhadad/fuf/57bd0e31afc6aaa03b85f45f4c7195af701508b8/src/alt.lisp
lisp
-*- Mode:Lisp; Syntax:Common-Lisp; Package: FUG5 -*- ----------------------------------------------------------------------- File: alt.l Description: Unification of disjunctions Modified: find-good-branches returns a list of all branches compatible with index - allows for none in index. allows for typed constants in index. 15 Jun 90: Added pair argument. 02 Jul 90: Added path2 arg. 28 Jul 91: New syntax for alts (:x and order free). 29 Oct 91: Fix trace-format calls. Add *trace-wait*. 09 Dec 91: Added after-wait in alt-unify and descendants. 02 Jan 91: Fixed indexed to accept random order too. 20 Oct 92: Added level to trace-format and trace-demo ----------------------------------------------------------------------- Permission to use, copy, and/or distribute for any purpose and without fee is hereby granted, provided that both the above copyright notice and this permission notice appear in all copies and derived works. Fees for distribution or use of this software or derived works may only be charged with express written permission of the copyright holder. ----------------------------------------------------------------------- ------------------------------------------------------------ Functions to deal with NON-deterministic unifications is made. ------------------------------------------------------------ ------------------------------------------------------------ Kept for old syntax only. Not useful anymore. ------------------------------------------------------------ Utility to display an underlined demo message when tracing --------------------------------------------------------------------- BRANCHES: takes an alt pair and return the branches, possibly a tracing flag and an index declaration ignore-unless ignore-when) --------------------------------------------------------------------- NEW Syntax of alt-pair is (:x notation is prefered, old one kept for (alt { traceflag | (trace on traceflag) | (:trace flag) } { (index on path) | (:index path)} { (demo str) | (:demo str)} { (bk-class class) | (:bk-class class) } { (:order {:random | :sequential}) } { (:wait list) } { (:ignore list) } ( fd1 ... fdn )) NOW ALLOW ANNOTATIONS IN ANY ORDER. Deal with old syntax for compatibility Now all annotations are in pair formats branches must be last Normalize values of annotations Syntax of opt-pair is: (opt { trace } { (bk-class class) } fd) --------------------------------------------------------------------- FIND-GOOD-BRANCHES: filter out branches that do not match the key of an index: hence the constraint on the index of an alt: the value of an index can be a pointer - but it MUST NOT point outside of the branch or within a disjunction in the branch. --------------------------------------------------------------------- --------------------------------------------------------------------- OPT-UNIFY --------------------------------------------------------------------- --------------------------------------------------------------------- ALT-UNIFY --------------------------------------------------------------------- alt-unify parses the alt construct and based on annotations, dispatches to the appropriate specialized function. Handle tracing messages indexed and order can be given as arg or from annotations. arg prevails. force-wait t means don't consider the wait annotation. WAIT annotation: if need to freeze, push on agenda and continue INDEX annotation OK, proceed --------------------------------------------------------------------- to the next branch if fail. When no more branch, fail. (change the fail argument when trying a branch) NOTE: orig-branches is just used for tracing purposes when called from alt-unify-indexed to identify the current branch in the textual representation of the grammar. --------------------------------------------------------------------- eat the tracing flags between branches --------------------------------------------------------------------- ALT-UNIFY-INDEXED: alt is indexed. Prune the set of branches to retain only those compatible with index. branch and use it. --------------------------------------------------------------------- ----------------------------------------------------------------------- -----------------------------------------------------------------------
Author : Created : 22 May 1990 22 Feb 91 : Allowed list of bk - class instead of only 1 . Add IGNORE and WAIT ( freeze ) . 11 Aug 91 : Add trace fro IGNORE and WAIT . 03 Jan 91 : Untrace alt when freezing . Package : FUG5 FUF - a functional unification - based text generation system . ( . 5.4 ) Copyright ( c ) 1987 - 2014 by . all rights reserved . THIS SOFTWARE IS PROVIDED ` ` AS IS '' WITHOUT EXPRESS OR IMPLIED WARRANTY . (in-package "FUG5") (format t "Alt unifier...~%") These functions modify their argument FAIL each time a choice UTILITIES to manipulate alt expressions (defun alt-trace-expr (sexpr) (or (leaf-p sexpr) (and (consp sexpr) (eq (car sexpr) 'trace)))) (defun alt-trace-flag (sexpr) (if (leaf-p sexpr) sexpr (car (last sexpr)))) (defun alt-index-expr (sexpr) (and (consp sexpr) (eq (car sexpr) 'index))) (defun alt-index-attr (sexpr) (car (last sexpr))) (defun alt-demo-expr (sexpr) (and (consp sexpr) (eq (car sexpr) 'demo-message))) (defun alt-bk-class-expr (sexpr) (and (consp sexpr) (eq (car sexpr) 'bk-class))) (defun alt-bk-class-class (sexpr) (let ((expr (last sexpr))) (if (symbolp (car expr)) expr (car (last sexpr))))) (proclaim '(inline alt-trace-expr alt-trace-flag alt-index-expr alt-index-attr alt-demo-expr alt-bk-class-expr alt-bk-class-class)) (defun show-demo-msg (demo traced frame) (when demo (trace-demo traced frame 12 "") (trace-demo traced frame 12 demo) (trace-demo traced frame 12 "~a" (make-sequence 'string (length demo) :initial-element #\-)))) ( 9 values : branches traced indexed demo bk - class order wait OPTIONS : same as branches for an opt pair . returns 3 values . compatibility ) . [ Jul 28 , 1991 ] (defun find-alt-annotation (key alt) "Extract the value val of annotation (key val) in an alt pair. Return nil if no annotation for key is found." (let ((pair (safe-assoc key alt))) (if pair (second pair) (case key (:trace (alt-trace-flag (safe-assoc 'trace alt))) (:index (alt-index-attr (safe-assoc 'index alt))) (:demo (safe-second (safe-assoc 'demo alt))) (:bk-class (alt-bk-class-class (safe-assoc 'bk-class alt))) (otherwise nil))))) (defun branches (alt-pair) (setq alt-pair (cdr alt-pair)) (let ((traced nil) (indexed nil) (demo nil) (bk-class nil) (order nil) (wait nil) (ignore-unless nil) (ignore-when nil) (branches nil)) First special case of trace that can be a single atom (when (alt-trace-expr (car alt-pair)) (setq traced (alt-trace-flag (pop alt-pair)))) (unless traced (setq traced (find-alt-annotation :trace alt-pair))) (setq indexed (find-alt-annotation :index alt-pair)) (setq demo (find-alt-annotation :demo alt-pair)) (setq bk-class (find-alt-annotation :bk-class alt-pair)) (setq order (find-alt-annotation :order alt-pair)) (setq wait (normalize-wait (find-alt-annotation :wait alt-pair))) (setq ignore-unless (find-alt-annotation :ignore-unless alt-pair)) (setq ignore-when (find-alt-annotation :ignore-when alt-pair)) (setq branches (car (last alt-pair))) (if (path-p indexed) (setq indexed (path-l indexed))) (unless (listp indexed) (setq indexed (list indexed))) (when (stringp demo) (setq demo (format nil demo))) (unless (listp wait) (setq wait (list wait))) (unless (eq order :random) (setq order :sequential)) (values branches traced indexed demo bk-class order wait ignore-unless ignore-when))) (defun option (opt-pair) (setq opt-pair (cdr opt-pair)) (let ((trace nil) (bk-class nil) (fd nil)) (when (alt-trace-expr (car opt-pair)) (setq trace (alt-trace-flag (pop opt-pair)))) (if (alt-bk-class-expr (car opt-pair)) (setq bk-class (alt-bk-class-class (pop opt-pair)) fd (car opt-pair)) (if (null opt-pair) (setq fd trace trace nil) (setq fd (car opt-pair)))) (values fd trace bk-class))) (defun find-good-branches (key index branches) (remove-if-not #'(lambda (branch) (let ((val-in-branch (top-gdp branch (make-path :l index)))) (or (null val-in-branch) (and key (eq 'given val-in-branch)) (eq 'any val-in-branch) (subsume val-in-branch key) (and (if *use-given* (not (underp val-in-branch)) t) (subsume key val-in-branch))))) branches)) (defun opt-unify (fd1 fd2 path1 path2 frame fail success &key (pair :unknown)) (multiple-value-bind (option flag bk-class) (option (car fd2)) (when (trace-enabled flag) (handle-trace flag frame t)) (trace-format flag frame 10 "Trying with option ~s at level ~s" flag path1) (backtrack frame new-frame bk-class flag (unify fd1 option path1 path2 new-frame (make-failure fail (when (trace-enabled flag) (handle-trace flag frame t) (trace-format flag frame 10 "Trying without option ~s at level ~s~%" flag path1)) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair)) #'(lambda (fd fail frame) (when (trace-enabled flag) (trace-format flag frame 10 "Success with option ~s at level ~s~%" flag path1) (handle-trace flag frame t)) (unify fd (cdr fd2) path1 path2 frame fail success :pair pair)) :pair pair)))) (defun alt-unify (fd1 fd2 path1 path2 frame fail success &key indexed-given order-given force-wait after-wait (pair :unknown) &aux key) (declare (special *input*)) (multiple-value-bind (branches traced indexed demo bk-class order wait ignore-unless ignore-when) (branches (car fd2)) (when (trace-enabled traced) (show-demo-msg demo traced frame) (push traced (frame-trace-flags frame)) (incf (frame-trace-level frame))) (when order-given (setq order order-given)) (when force-wait (setq wait nil)) (unless indexed (setq indexed indexed-given)) (when indexed (setq key (gdp *input* (make-path :l (append (path-l path1) indexed))))) Dispatch based on annotations to specialized function (cond ((null branches) (error "An alt must have at least one branch")) NOTE : WAIT has priority on IGNORE ((not (check-wait wait path2)) (let ((id (add-agenda frame (car fd2) wait path1 path2 after-wait indexed order ignore-unless ignore-when pair))) (trace-format (or *trace-wait* (trace-enabled traced)) frame 15 "Freezing alt ~s: waiting for ~s [agenda ~s]" traced wait id) (when (trace-enabled traced) (pop (frame-trace-flags frame)) (decf (frame-trace-level frame))) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair))) IGNORE annotations ((check-ignore-unless ignore-unless path1 path2) (trace-format traced frame 15 "Ignoring alt ~s: ignore-unless matches" traced) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair)) ((check-ignore-when ignore-when path1 path2) (trace-format traced frame 15 "Ignoring alt ~s: ignore-when matches" traced) (unify fd1 (cdr fd2) path1 path2 frame fail success :pair pair)) ((not (member key '(nil any given))) (alt-unify-indexed fd1 (cdr fd2) path1 path2 bk-class frame fail success after-wait traced key branches indexed :random order :pair pair)) (t (when (and indexed demo) (trace-demo traced frame 5 "Key not specified in input. Need to search")) (trace-format (and (trace-enabled traced) indexed) frame 5 "No value given in input for index ~s - No jump" indexed) (if (eq order :random) (ralt-unify-simple fd1 (cdr fd2) path1 path2 bk-class frame fail success after-wait traced (copy-list branches) 1 branches :pair pair) (alt-unify-simple fd1 (cdr fd2) path1 path2 bk-class frame fail success after-wait traced branches 1 nil :pair pair)))))) ALT - UNIFY - SIMPLE : alt is not indexed . Traverse each branch , and backtrack (defun alt-unify-simple (fd1 fd2 path1 path2 bk-class frame fail success after-wait traced branches branch-number orig-branches &key (pair :unknown)) (when (and (tracing-flag (car branches)) (trace-enabled (car branches))) (handle-trace (pop branches) frame)) (cond ((null branches) (when (trace-enabled traced) (trace-format traced frame 30 "Fail in alt ~s at level ~s~%" traced path1) (handle-trace traced frame t)) (*fail* fail frame *same* path2 pair)) (t (trace-format traced frame 10 "Entering alt ~s -- Branch #~s" traced (if orig-branches (1+ (position (car branches) orig-branches :test #'equalp)) branch-number)) (backtrack frame new-frame bk-class traced (unify fd1 (car branches) path1 path2 new-frame (make-failure fail (alt-unify-simple fd1 fd2 path1 path2 bk-class frame fail success after-wait traced (cdr branches) (1+ branch-number) orig-branches :pair pair)) #'(lambda (fd fail frame) (when (trace-enabled traced) (trace-format traced frame 10 "Success with branch ~s in alt ~s~%" branch-number traced) (handle-trace traced frame t)) (when after-wait (funcall after-wait)) (unify fd fd2 path1 path2 frame fail success :pair pair)) :pair pair))))) If only one branch , unification is deterministic , just jump to the right If more than one , search on restricted set . (defun alt-unify-indexed (fd1 fd2 path1 path2 bk-class frame fail success after-wait traced key branches indexed &key random (pair :unknown)) (let ((good-branches (find-good-branches key indexed branches))) (cond ((null good-branches) (trace-format traced frame 30 "fail on indexed alt ~s: no branch in ~ the grammar for ~s~%" traced key) (*fail* fail frame *same* path2 pair)) ((= 1 (length good-branches)) (trace-format traced frame 10 "Entering alt ~s -- Jump indexed to branch #~s: ~ ~s matches input ~s" traced (1+ (position (car good-branches) branches :test #'equalp)) (top-gdp (car good-branches) (make-path :l indexed)) key) (unify fd1 (car good-branches) path1 path2 frame fail #'(lambda (fd fail frame) (when traced (trace-format traced frame 10 "Success with branch #~s ~s in alt ~s~%" (1+ (position (car good-branches) branches :test #'equalp)) key traced) (handle-trace traced frame t)) (when after-wait (funcall after-wait)) (unify fd fd2 path1 path2 frame fail success :pair pair)) :pair pair)) (t (if traced (trace-format traced frame 5 "Entering indexed ~a ~s -- Trying with ~s branches out of ~s" (if random "Ralt" "alt") traced (length good-branches) (length branches))) (if (eq random :random) (ralt-unify-simple fd1 fd2 path1 path2 bk-class frame fail success after-wait traced good-branches 1 branches :pair pair) (alt-unify-simple fd1 fd2 path1 path2 bk-class frame fail success after-wait traced good-branches 1 branches :pair pair)))))) (provide "$fug5/alt")
c368aae5a6684083ef962d7bcf036579485f769a4a58549a24a1c8e0c7f53a60
DogLooksGood/holdem
store.cljs
(ns poker.events.store (:require [akiroz.re-frame.storage :refer [reg-co-fx!]])) (reg-co-fx! :holdem {:fx :store :cofx :store})
null
https://raw.githubusercontent.com/DogLooksGood/holdem/bc0f93ed65cab54890c91f78bb95fe3ba020a41f/src/cljs/poker/events/store.cljs
clojure
(ns poker.events.store (:require [akiroz.re-frame.storage :refer [reg-co-fx!]])) (reg-co-fx! :holdem {:fx :store :cofx :store})
f4f288a702584729cf7e76a6b31a9c81280d16782e26ca52d75469e53db52228
patricoferris/ocaml-multicore-monorepo
test.ml
open Eio.Std module Ctf = Eio.Private.Ctf let () = Logs.(set_level ~all:true (Some Debug)); Logs.set_reporter @@ Logs.format_reporter (); Printexc.record_backtrace true let read_one_byte ~sw r = Fiber.fork_promise ~sw (fun () -> let r = Option.get (Eio_linux.get_fd_opt r) in Eio_linux.Low_level.await_readable r; let b = Bytes.create 1 in let got = Unix.read (Eio_linux.FD.to_unix `Peek r) b 0 1 in assert (got = 1); Bytes.to_string b ) let test_poll_add () = Eio_linux.run @@ fun _stdenv -> Switch.run @@ fun sw -> let r, w = Eio_linux.pipe sw in let thread = read_one_byte ~sw r in Fiber.yield (); let w = Option.get (Eio_linux.get_fd_opt w) in Eio_linux.Low_level.await_writable w; let sent = Unix.write (Eio_linux.FD.to_unix `Peek w) (Bytes.of_string "!") 0 1 in assert (sent = 1); let result = Promise.await_exn thread in Alcotest.(check string) "Received data" "!" result let test_poll_add_busy () = Eio_linux.run ~queue_depth:2 @@ fun _stdenv -> Switch.run @@ fun sw -> let r, w = Eio_linux.pipe sw in let a = read_one_byte ~sw r in let b = read_one_byte ~sw r in Fiber.yield (); let w = Option.get (Eio_linux.get_fd_opt w) |> Eio_linux.FD.to_unix `Peek in let sent = Unix.write w (Bytes.of_string "!!") 0 2 in assert (sent = 2); let a = Promise.await_exn a in Alcotest.(check string) "Received data" "!" a; let b = Promise.await_exn b in Alcotest.(check string) "Received data" "!" b (* Write a string to a pipe and read it out again. *) let test_copy () = Eio_linux.run ~queue_depth:3 @@ fun _stdenv -> Switch.run @@ fun sw -> let msg = "Hello!" in let from_pipe, to_pipe = Eio_linux.pipe sw in let buffer = Buffer.create 20 in Fiber.both (fun () -> Eio.Flow.copy from_pipe (Eio.Flow.buffer_sink buffer)) (fun () -> Eio.Flow.copy (Eio.Flow.string_source msg) to_pipe; Eio.Flow.copy (Eio.Flow.string_source msg) to_pipe; Eio.Flow.close to_pipe ); Alcotest.(check string) "Copy correct" (msg ^ msg) (Buffer.contents buffer); Eio.Flow.close from_pipe Write a string via 2 pipes . The copy from the 1st to 2nd pipe will be optimised and so tests a different code - path . let test_direct_copy () = Eio_linux.run ~queue_depth:4 @@ fun _stdenv -> Switch.run @@ fun sw -> let msg = "Hello!" in let from_pipe1, to_pipe1 = Eio_linux.pipe sw in let from_pipe2, to_pipe2 = Eio_linux.pipe sw in let buffer = Buffer.create 20 in let to_output = Eio.Flow.buffer_sink buffer in Switch.run (fun sw -> Fiber.fork ~sw (fun () -> Ctf.label "copy1"; Eio.Flow.copy from_pipe1 to_pipe2; Eio.Flow.close to_pipe2); Fiber.fork ~sw (fun () -> Ctf.label "copy2"; Eio.Flow.copy from_pipe2 to_output); Eio.Flow.copy (Eio.Flow.string_source msg) to_pipe1; Eio.Flow.close to_pipe1; ); Alcotest.(check string) "Copy correct" msg (Buffer.contents buffer); Eio.Flow.close from_pipe1; Eio.Flow.close from_pipe2 Read and write using IO vectors rather than the fixed buffers . let test_iovec () = Eio_linux.run ~queue_depth:4 @@ fun _stdenv -> Switch.run @@ fun sw -> let from_pipe, to_pipe = Eio_linux.pipe sw in let from_pipe = Eio_linux.get_fd from_pipe in let to_pipe = Eio_linux.get_fd to_pipe in let message = Cstruct.of_string "Got [ ] and [ ]" in let rec recv = function | [] -> () | cs -> let got = Eio_linux.Low_level.readv from_pipe cs in recv (Cstruct.shiftv cs got) in Fiber.both (fun () -> recv [Cstruct.sub message 5 3; Cstruct.sub message 15 3]) (fun () -> let b = Cstruct.of_string "barfoo" in Eio_linux.Low_level.writev to_pipe [Cstruct.sub b 3 3; Cstruct.sub b 0 3]; Eio_linux.FD.close to_pipe ); Alcotest.(check string) "Transfer correct" "Got [foo] and [bar]" (Cstruct.to_string message) let () = let open Alcotest in run "eioio" [ "io", [ test_case "copy" `Quick test_copy; test_case "direct_copy" `Quick test_direct_copy; test_case "poll_add" `Quick test_poll_add; test_case "poll_add_busy" `Quick test_poll_add_busy; test_case "iovec" `Quick test_iovec; ]; ]
null
https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/624b3293ee41e83736fe7ac3a79f810c2b70f68b/duniverse/eio/lib_eio_linux/tests/test.ml
ocaml
Write a string to a pipe and read it out again.
open Eio.Std module Ctf = Eio.Private.Ctf let () = Logs.(set_level ~all:true (Some Debug)); Logs.set_reporter @@ Logs.format_reporter (); Printexc.record_backtrace true let read_one_byte ~sw r = Fiber.fork_promise ~sw (fun () -> let r = Option.get (Eio_linux.get_fd_opt r) in Eio_linux.Low_level.await_readable r; let b = Bytes.create 1 in let got = Unix.read (Eio_linux.FD.to_unix `Peek r) b 0 1 in assert (got = 1); Bytes.to_string b ) let test_poll_add () = Eio_linux.run @@ fun _stdenv -> Switch.run @@ fun sw -> let r, w = Eio_linux.pipe sw in let thread = read_one_byte ~sw r in Fiber.yield (); let w = Option.get (Eio_linux.get_fd_opt w) in Eio_linux.Low_level.await_writable w; let sent = Unix.write (Eio_linux.FD.to_unix `Peek w) (Bytes.of_string "!") 0 1 in assert (sent = 1); let result = Promise.await_exn thread in Alcotest.(check string) "Received data" "!" result let test_poll_add_busy () = Eio_linux.run ~queue_depth:2 @@ fun _stdenv -> Switch.run @@ fun sw -> let r, w = Eio_linux.pipe sw in let a = read_one_byte ~sw r in let b = read_one_byte ~sw r in Fiber.yield (); let w = Option.get (Eio_linux.get_fd_opt w) |> Eio_linux.FD.to_unix `Peek in let sent = Unix.write w (Bytes.of_string "!!") 0 2 in assert (sent = 2); let a = Promise.await_exn a in Alcotest.(check string) "Received data" "!" a; let b = Promise.await_exn b in Alcotest.(check string) "Received data" "!" b let test_copy () = Eio_linux.run ~queue_depth:3 @@ fun _stdenv -> Switch.run @@ fun sw -> let msg = "Hello!" in let from_pipe, to_pipe = Eio_linux.pipe sw in let buffer = Buffer.create 20 in Fiber.both (fun () -> Eio.Flow.copy from_pipe (Eio.Flow.buffer_sink buffer)) (fun () -> Eio.Flow.copy (Eio.Flow.string_source msg) to_pipe; Eio.Flow.copy (Eio.Flow.string_source msg) to_pipe; Eio.Flow.close to_pipe ); Alcotest.(check string) "Copy correct" (msg ^ msg) (Buffer.contents buffer); Eio.Flow.close from_pipe Write a string via 2 pipes . The copy from the 1st to 2nd pipe will be optimised and so tests a different code - path . let test_direct_copy () = Eio_linux.run ~queue_depth:4 @@ fun _stdenv -> Switch.run @@ fun sw -> let msg = "Hello!" in let from_pipe1, to_pipe1 = Eio_linux.pipe sw in let from_pipe2, to_pipe2 = Eio_linux.pipe sw in let buffer = Buffer.create 20 in let to_output = Eio.Flow.buffer_sink buffer in Switch.run (fun sw -> Fiber.fork ~sw (fun () -> Ctf.label "copy1"; Eio.Flow.copy from_pipe1 to_pipe2; Eio.Flow.close to_pipe2); Fiber.fork ~sw (fun () -> Ctf.label "copy2"; Eio.Flow.copy from_pipe2 to_output); Eio.Flow.copy (Eio.Flow.string_source msg) to_pipe1; Eio.Flow.close to_pipe1; ); Alcotest.(check string) "Copy correct" msg (Buffer.contents buffer); Eio.Flow.close from_pipe1; Eio.Flow.close from_pipe2 Read and write using IO vectors rather than the fixed buffers . let test_iovec () = Eio_linux.run ~queue_depth:4 @@ fun _stdenv -> Switch.run @@ fun sw -> let from_pipe, to_pipe = Eio_linux.pipe sw in let from_pipe = Eio_linux.get_fd from_pipe in let to_pipe = Eio_linux.get_fd to_pipe in let message = Cstruct.of_string "Got [ ] and [ ]" in let rec recv = function | [] -> () | cs -> let got = Eio_linux.Low_level.readv from_pipe cs in recv (Cstruct.shiftv cs got) in Fiber.both (fun () -> recv [Cstruct.sub message 5 3; Cstruct.sub message 15 3]) (fun () -> let b = Cstruct.of_string "barfoo" in Eio_linux.Low_level.writev to_pipe [Cstruct.sub b 3 3; Cstruct.sub b 0 3]; Eio_linux.FD.close to_pipe ); Alcotest.(check string) "Transfer correct" "Got [foo] and [bar]" (Cstruct.to_string message) let () = let open Alcotest in run "eioio" [ "io", [ test_case "copy" `Quick test_copy; test_case "direct_copy" `Quick test_direct_copy; test_case "poll_add" `Quick test_poll_add; test_case "poll_add_busy" `Quick test_poll_add_busy; test_case "iovec" `Quick test_iovec; ]; ]
dd45e88a7e250b829d885b13c94f358ca80b6cb2b72ab5e6d38cc6cb94f7cb71
ocamllabs/ocaml-modular-implicits
tracing.ml
List.fold_left;; #trace List.fold_left;; 0;; List.fold_left (+) 0 [1;2;3];;
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-toplevel/tracing.ml
ocaml
List.fold_left;; #trace List.fold_left;; 0;; List.fold_left (+) 0 [1;2;3];;