_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
d4606a83e22211ea18f13da7812a965ea085bbafa795875d9fefdbdba7f0ae33
huangjs/cl
generate-sys-proclaim.lisp
(load "../lisp-utils/defsystem.lisp") (compiler::emit-fn t) (mk::oos "maxima" :compile :verbose t) (compiler::make-all-proclaims "*/*.fn" "*/*/*/*.fn")
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/generate-sys-proclaim.lisp
lisp
(load "../lisp-utils/defsystem.lisp") (compiler::emit-fn t) (mk::oos "maxima" :compile :verbose t) (compiler::make-all-proclaims "*/*.fn" "*/*/*/*.fn")
c8162776b3f6ff4c34e36d22ec2662ac91512b7ac1a85851269d0472fb11fa12
mathematical-systems/clml
dtpmv.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 "BLAS") (let* ((zero 0.0)) (declare (type (double-float 0.0 0.0) zero) (ignorable zero)) (defun dtpmv (uplo trans diag n ap x incx) (declare (type (array double-float (*)) x ap) (type (simple-array character (*)) diag trans uplo) (type (f2cl-lib:integer4) incx n)) (f2cl-lib:with-multi-array-data ((uplo character uplo-%data% uplo-%offset%) (trans character trans-%data% trans-%offset%) (diag character diag-%data% diag-%offset%) (ap double-float ap-%data% ap-%offset%) (x double-float x-%data% x-%offset%)) (prog ((nounit nil) (i 0) (info 0) (ix 0) (j 0) (jx 0) (k 0) (kk 0) (kx 0) (temp 0.0)) (declare (type (double-float) temp) (type f2cl-lib:logical nounit) (type (f2cl-lib:integer4) i info ix j jx k kk kx)) (setf info 0) (cond ((and (not (lsame uplo "U")) (not (lsame uplo "L"))) (setf info 1)) ((and (not (lsame trans "N")) (not (lsame trans "T")) (not (lsame trans "C"))) (setf info 2)) ((and (not (lsame diag "U")) (not (lsame diag "N"))) (setf info 3)) ((< n 0) (setf info 4)) ((= incx 0) (setf info 7))) (cond ((/= info 0) (xerbla "DTPMV " info) (go end_label))) (if (= n 0) (go end_label)) (setf nounit (lsame diag "N")) (cond ((<= incx 0) (setf kx (f2cl-lib:int-sub 1 (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx)))) ((/= incx 1) (setf kx 1))) (cond ((lsame trans "N") (cond ((lsame uplo "U") (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label10)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-add kk j)) label20))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk j (f2cl-lib:int-sub 2))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-add ix incx)) label30)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk j)) label40))))) (t (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i n (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i (f2cl-lib:int-add j 1)) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label50)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label60))) (t (setf kx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (setf jx kx) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub (f2cl-lib:int-add n (f2cl-lib:int-sub (f2cl-lib:int-add j 1)))))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-sub ix incx)) label70)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label80))))))) (t (cond ((lsame uplo "U") (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-sub kk 1)) (f2cl-lib:fdo (i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)) (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i 1) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label90)) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-sub kk j)) label100))) (t (setf jx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk (f2cl-lib:int-sub 1)) (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub j) 1)) nil) (tagbody (setf ix (f2cl-lib:int-sub ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label110)) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk j)) label120))))) (t (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-add kk 1)) (f2cl-lib:fdo (i (f2cl-lib:int-add j 1) (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label130)) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label140))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk 1) (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk n (f2cl-lib:int-sub j))) nil) (tagbody (setf ix (f2cl-lib:int-add ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label150)) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label160)))))))) (go end_label) end_label (return (values nil nil nil nil nil nil nil)))))) (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::dtpmv fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((simple-array character (1)) (simple-array character (1)) (simple-array character (1)) (fortran-to-lisp::integer4) (array double-float (*)) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil nil) :calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
null
https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/blas/dtpmv.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 "BLAS") (let* ((zero 0.0)) (declare (type (double-float 0.0 0.0) zero) (ignorable zero)) (defun dtpmv (uplo trans diag n ap x incx) (declare (type (array double-float (*)) x ap) (type (simple-array character (*)) diag trans uplo) (type (f2cl-lib:integer4) incx n)) (f2cl-lib:with-multi-array-data ((uplo character uplo-%data% uplo-%offset%) (trans character trans-%data% trans-%offset%) (diag character diag-%data% diag-%offset%) (ap double-float ap-%data% ap-%offset%) (x double-float x-%data% x-%offset%)) (prog ((nounit nil) (i 0) (info 0) (ix 0) (j 0) (jx 0) (k 0) (kk 0) (kx 0) (temp 0.0)) (declare (type (double-float) temp) (type f2cl-lib:logical nounit) (type (f2cl-lib:integer4) i info ix j jx k kk kx)) (setf info 0) (cond ((and (not (lsame uplo "U")) (not (lsame uplo "L"))) (setf info 1)) ((and (not (lsame trans "N")) (not (lsame trans "T")) (not (lsame trans "C"))) (setf info 2)) ((and (not (lsame diag "U")) (not (lsame diag "N"))) (setf info 3)) ((< n 0) (setf info 4)) ((= incx 0) (setf info 7))) (cond ((/= info 0) (xerbla "DTPMV " info) (go end_label))) (if (= n 0) (go end_label)) (setf nounit (lsame diag "N")) (cond ((<= incx 0) (setf kx (f2cl-lib:int-sub 1 (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx)))) ((/= incx 1) (setf kx 1))) (cond ((lsame trans "N") (cond ((lsame uplo "U") (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label10)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-add kk j)) label20))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk j (f2cl-lib:int-sub 2))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-add ix incx)) label30)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-sub (f2cl-lib:int-add kk j) 1)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk j)) label40))))) (t (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (j) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (setf k kk) (f2cl-lib:fdo (i n (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i (f2cl-lib:int-add j 1)) nil) (tagbody (setf (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label50)) (if nounit (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label60))) (t (setf kx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (setf jx kx) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (cond ((/= (f2cl-lib:fref x (jx) ((1 *))) zero) (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix kx) (f2cl-lib:fdo (k kk (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub (f2cl-lib:int-add n (f2cl-lib:int-sub (f2cl-lib:int-add j 1)))))) nil) (tagbody (setf (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (+ (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%) (* temp (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%)))) (setf ix (f2cl-lib:int-sub ix incx)) label70)) (if nounit (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (* (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) (f2cl-lib:fref ap-%data% ((f2cl-lib:int-add (f2cl-lib:int-sub kk n) j)) ((1 *)) ap-%offset%)))))) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label80))))))) (t (cond ((lsame uplo "U") (setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2))) (cond ((= incx 1) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-sub kk 1)) (f2cl-lib:fdo (i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)) (f2cl-lib:int-add i (f2cl-lib:int-sub 1))) ((> i 1) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-sub k 1)) label90)) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-sub kk j)) label100))) (t (setf jx (f2cl-lib:int-add kx (f2cl-lib:int-mul (f2cl-lib:int-sub n 1) incx))) (f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1))) ((> j 1) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk (f2cl-lib:int-sub 1)) (f2cl-lib:int-add k (f2cl-lib:int-sub 1))) ((> k (f2cl-lib:int-add kk (f2cl-lib:int-sub j) 1)) nil) (tagbody (setf ix (f2cl-lib:int-sub ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label110)) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-sub jx incx)) (setf kk (f2cl-lib:int-sub kk j)) label120))))) (t (setf kk 1) (cond ((= incx 1) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (setf k (f2cl-lib:int-add kk 1)) (f2cl-lib:fdo (i (f2cl-lib:int-add j 1) (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (i) ((1 *)) x-%offset%)))) (setf k (f2cl-lib:int-add k 1)) label130)) (setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%) temp) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label140))) (t (setf jx kx) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j n) nil) (tagbody (setf temp (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)) (setf ix jx) (if nounit (setf temp (* temp (f2cl-lib:fref ap-%data% (kk) ((1 *)) ap-%offset%)))) (f2cl-lib:fdo (k (f2cl-lib:int-add kk 1) (f2cl-lib:int-add k 1)) ((> k (f2cl-lib:int-add kk n (f2cl-lib:int-sub j))) nil) (tagbody (setf ix (f2cl-lib:int-add ix incx)) (setf temp (+ temp (* (f2cl-lib:fref ap-%data% (k) ((1 *)) ap-%offset%) (f2cl-lib:fref x-%data% (ix) ((1 *)) x-%offset%)))) label150)) (setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%) temp) (setf jx (f2cl-lib:int-add jx incx)) (setf kk (f2cl-lib:int-add kk (f2cl-lib:int-add (f2cl-lib:int-sub n j) 1))) label160)))))))) (go end_label) end_label (return (values nil nil nil nil nil nil nil)))))) (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::dtpmv fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((simple-array character (1)) (simple-array character (1)) (simple-array character (1)) (fortran-to-lisp::integer4) (array double-float (*)) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil nil) :calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
cd314827c37753ba40b5fce08aa60567880eb52c8f0291a49f84cc6990d8be58
pcalcado/rtfspec
must_not_fail_spec.clj
(use 'rtfspec) (spec "2. MUST NOT This phrase, or the phrase 'SHALL NOT', mean that the definition is an absolute prohibition of the specification." (must-not "avoid failure if false" (= true true)) (must-not "have trouble when ailing in multiple lines" (or false true false)))
null
https://raw.githubusercontent.com/pcalcado/rtfspec/c733f504031635316fdc401ec371e8f03c01f380/test/smoke/failure/must_not_fail_spec.clj
clojure
(use 'rtfspec) (spec "2. MUST NOT This phrase, or the phrase 'SHALL NOT', mean that the definition is an absolute prohibition of the specification." (must-not "avoid failure if false" (= true true)) (must-not "have trouble when ailing in multiple lines" (or false true false)))
203ee5b3b25ec6ab381dffb2387f0f7a332c98281cd97b4b529a5374a150ef32
penpot/penpot
projects.clj
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.rpc.commands.projects (:require [app.common.spec :as us] [app.db :as db] [app.loggers.audit :as-alias audit] [app.loggers.webhooks :as webhooks] [app.rpc :as-alias rpc] [app.rpc.commands.teams :as teams] [app.rpc.doc :as-alias doc] [app.rpc.helpers :as rph] [app.rpc.permissions :as perms] [app.rpc.quotes :as quotes] [app.util.services :as sv] [app.util.time :as dt] [clojure.spec.alpha :as s])) (s/def ::id ::us/uuid) (s/def ::name ::us/string) ;; --- Check Project Permissions (def ^:private sql:project-permissions "select tpr.is_owner, tpr.is_admin, tpr.can_edit from team_profile_rel as tpr inner join project as p on (p.team_id = tpr.team_id) where p.id = ? and tpr.profile_id = ? union all select ppr.is_owner, ppr.is_admin, ppr.can_edit from project_profile_rel as ppr where ppr.project_id = ? and ppr.profile_id = ?") (defn- get-permissions [conn profile-id project-id] (let [rows (db/exec! conn [sql:project-permissions project-id profile-id project-id profile-id]) is-owner (boolean (some :is-owner rows)) is-admin (boolean (some :is-admin rows)) can-edit (boolean (some :can-edit rows))] (when (seq rows) {:is-owner is-owner :is-admin (or is-owner is-admin) :can-edit (or is-owner is-admin can-edit) :can-read true}))) (def has-edit-permissions? (perms/make-edition-predicate-fn get-permissions)) (def has-read-permissions? (perms/make-read-predicate-fn get-permissions)) (def check-edition-permissions! (perms/make-check-fn has-edit-permissions?)) (def check-read-permissions! (perms/make-check-fn has-read-permissions?)) ;; --- QUERY: Get projects (declare get-projects) (s/def ::team-id ::us/uuid) (s/def ::get-projects (s/keys :req [::rpc/profile-id] :req-un [::team-id])) (sv/defmethod ::get-projects {::doc/added "1.18"} [{:keys [::db/pool]} {:keys [::rpc/profile-id team-id]}] (with-open [conn (db/open pool)] (teams/check-read-permissions! conn profile-id team-id) (get-projects conn profile-id team-id))) (def sql:projects "select p.*, coalesce(tpp.is_pinned, false) as is_pinned, (select count(*) from file as f where f.project_id = p.id and deleted_at is null) as count from project as p inner join team as t on (t.id = p.team_id) left join team_project_profile_rel as tpp on (tpp.project_id = p.id and tpp.team_id = p.team_id and tpp.profile_id = ?) where p.team_id = ? and p.deleted_at is null and t.deleted_at is null order by p.modified_at desc") (defn get-projects [conn profile-id team-id] (db/exec! conn [sql:projects profile-id team-id])) ;; --- QUERY: Get all projects (declare get-all-projects) (s/def ::get-all-projects (s/keys :req [::rpc/profile-id])) (sv/defmethod ::get-all-projects {::doc/added "1.18"} [{:keys [::db/pool]} {:keys [::rpc/profile-id]}] (with-open [conn (db/open pool)] (get-all-projects conn profile-id))) (def sql:all-projects "select p1.*, t.name as team_name, t.is_default as is_default_team from project as p1 inner join team as t on (t.id = p1.team_id) where t.id in (select team_id from team_profile_rel as tpr where tpr.profile_id = ? and (tpr.can_edit = true or tpr.is_owner = true or tpr.is_admin = true)) and t.deleted_at is null and p1.deleted_at is null union select p2.*, t.name as team_name, t.is_default as is_default_team from project as p2 inner join team as t on (t.id = p2.team_id) where p2.id in (select project_id from project_profile_rel as ppr where ppr.profile_id = ? and (ppr.can_edit = true or ppr.is_owner = true or ppr.is_admin = true)) and t.deleted_at is null and p2.deleted_at is null order by team_name, name;") (defn get-all-projects [conn profile-id] (db/exec! conn [sql:all-projects profile-id profile-id])) ;; --- QUERY: Get project (s/def ::get-project (s/keys :req [::rpc/profile-id] :req-un [::id])) (sv/defmethod ::get-project {::doc/added "1.18"} [{:keys [::db/pool]} {:keys [::rpc/profile-id id]}] (with-open [conn (db/open pool)] (let [project (db/get-by-id conn :project id)] (check-read-permissions! conn profile-id id) project))) --- MUTATION : Create Project (s/def ::create-project (s/keys :req [::rpc/profile-id] :req-un [::team-id ::name] :opt-un [::id])) (sv/defmethod ::create-project {::doc/added "1.18" ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id team-id] :as params}] (db/with-atomic [conn pool] (teams/check-edition-permissions! conn profile-id team-id) (quotes/check-quote! conn {::quotes/id ::quotes/projects-per-team ::quotes/profile-id profile-id ::quotes/team-id team-id}) (let [params (assoc params :profile-id profile-id) project (teams/create-project conn params)] (teams/create-project-role conn profile-id (:id project) :owner) (db/insert! conn :team-project-profile-rel {:project-id (:id project) :profile-id profile-id :team-id team-id :is-pinned true}) (assoc project :is-pinned true)))) --- MUTATION : Toggle Project Pin (def ^:private sql:update-project-pin "insert into team_project_profile_rel (team_id, project_id, profile_id, is_pinned) values (?, ?, ?, ?) on conflict (team_id, project_id, profile_id) do update set is_pinned=?") (s/def ::is-pinned ::us/boolean) (s/def ::project-id ::us/uuid) (s/def ::update-project-pin (s/keys :req [::rpc/profile-id] :req-un [::id ::team-id ::is-pinned])) (sv/defmethod ::update-project-pin {::doc/added "1.18" ::webhooks/batch-timeout (dt/duration "5s") ::webhooks/batch-key (webhooks/key-fn ::rpc/profile-id :id) ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id id team-id is-pinned] :as params}] (db/with-atomic [conn pool] (check-edition-permissions! conn profile-id id) (db/exec-one! conn [sql:update-project-pin team-id id profile-id is-pinned is-pinned]) nil)) ;; --- MUTATION: Rename Project (declare rename-project) (s/def ::rename-project (s/keys :req [::rpc/profile-id] :req-un [::name ::id])) (sv/defmethod ::rename-project {::doc/added "1.18" ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id id name] :as params}] (db/with-atomic [conn pool] (check-edition-permissions! conn profile-id id) (let [project (db/get-by-id conn :project id ::db/for-update? true)] (db/update! conn :project {:name name} {:id id}) (rph/with-meta (rph/wrap) {::audit/props {:team-id (:team-id project) :prev-name (:name project)}})))) ;; --- MUTATION: Delete Project (s/def ::delete-project (s/keys :req [::rpc/profile-id] :req-un [::id])) ;; TODO: right now, we just don't allow delete default projects, in a ;; future we need to ensure raise a correct exception signaling that ;; this is not allowed. (sv/defmethod ::delete-project {::doc/added "1.18" ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id id] :as params}] (db/with-atomic [conn pool] (check-edition-permissions! conn profile-id id) (let [project (db/update! conn :project {:deleted-at (dt/now)} {:id id :is-default false})] (rph/with-meta (rph/wrap) {::audit/props {:team-id (:team-id project) :name (:name project) :created-at (:created-at project) :modified-at (:modified-at project)}}))))
null
https://raw.githubusercontent.com/penpot/penpot/42e97f8be105af41757f8e896b93a99032a2b72a/backend/src/app/rpc/commands/projects.clj
clojure
Copyright (c) KALEIDOS INC --- Check Project Permissions --- QUERY: Get projects --- QUERY: Get all projects ") --- QUERY: Get project --- MUTATION: Rename Project --- MUTATION: Delete Project TODO: right now, we just don't allow delete default projects, in a future we need to ensure raise a correct exception signaling that this is not allowed.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.rpc.commands.projects (:require [app.common.spec :as us] [app.db :as db] [app.loggers.audit :as-alias audit] [app.loggers.webhooks :as webhooks] [app.rpc :as-alias rpc] [app.rpc.commands.teams :as teams] [app.rpc.doc :as-alias doc] [app.rpc.helpers :as rph] [app.rpc.permissions :as perms] [app.rpc.quotes :as quotes] [app.util.services :as sv] [app.util.time :as dt] [clojure.spec.alpha :as s])) (s/def ::id ::us/uuid) (s/def ::name ::us/string) (def ^:private sql:project-permissions "select tpr.is_owner, tpr.is_admin, tpr.can_edit from team_profile_rel as tpr inner join project as p on (p.team_id = tpr.team_id) where p.id = ? and tpr.profile_id = ? union all select ppr.is_owner, ppr.is_admin, ppr.can_edit from project_profile_rel as ppr where ppr.project_id = ? and ppr.profile_id = ?") (defn- get-permissions [conn profile-id project-id] (let [rows (db/exec! conn [sql:project-permissions project-id profile-id project-id profile-id]) is-owner (boolean (some :is-owner rows)) is-admin (boolean (some :is-admin rows)) can-edit (boolean (some :can-edit rows))] (when (seq rows) {:is-owner is-owner :is-admin (or is-owner is-admin) :can-edit (or is-owner is-admin can-edit) :can-read true}))) (def has-edit-permissions? (perms/make-edition-predicate-fn get-permissions)) (def has-read-permissions? (perms/make-read-predicate-fn get-permissions)) (def check-edition-permissions! (perms/make-check-fn has-edit-permissions?)) (def check-read-permissions! (perms/make-check-fn has-read-permissions?)) (declare get-projects) (s/def ::team-id ::us/uuid) (s/def ::get-projects (s/keys :req [::rpc/profile-id] :req-un [::team-id])) (sv/defmethod ::get-projects {::doc/added "1.18"} [{:keys [::db/pool]} {:keys [::rpc/profile-id team-id]}] (with-open [conn (db/open pool)] (teams/check-read-permissions! conn profile-id team-id) (get-projects conn profile-id team-id))) (def sql:projects "select p.*, coalesce(tpp.is_pinned, false) as is_pinned, (select count(*) from file as f where f.project_id = p.id and deleted_at is null) as count from project as p inner join team as t on (t.id = p.team_id) left join team_project_profile_rel as tpp on (tpp.project_id = p.id and tpp.team_id = p.team_id and tpp.profile_id = ?) where p.team_id = ? and p.deleted_at is null and t.deleted_at is null order by p.modified_at desc") (defn get-projects [conn profile-id team-id] (db/exec! conn [sql:projects profile-id team-id])) (declare get-all-projects) (s/def ::get-all-projects (s/keys :req [::rpc/profile-id])) (sv/defmethod ::get-all-projects {::doc/added "1.18"} [{:keys [::db/pool]} {:keys [::rpc/profile-id]}] (with-open [conn (db/open pool)] (get-all-projects conn profile-id))) (def sql:all-projects "select p1.*, t.name as team_name, t.is_default as is_default_team from project as p1 inner join team as t on (t.id = p1.team_id) where t.id in (select team_id from team_profile_rel as tpr where tpr.profile_id = ? and (tpr.can_edit = true or tpr.is_owner = true or tpr.is_admin = true)) and t.deleted_at is null and p1.deleted_at is null union select p2.*, t.name as team_name, t.is_default as is_default_team from project as p2 inner join team as t on (t.id = p2.team_id) where p2.id in (select project_id from project_profile_rel as ppr where ppr.profile_id = ? and (ppr.can_edit = true or ppr.is_owner = true or ppr.is_admin = true)) and t.deleted_at is null and p2.deleted_at is null (defn get-all-projects [conn profile-id] (db/exec! conn [sql:all-projects profile-id profile-id])) (s/def ::get-project (s/keys :req [::rpc/profile-id] :req-un [::id])) (sv/defmethod ::get-project {::doc/added "1.18"} [{:keys [::db/pool]} {:keys [::rpc/profile-id id]}] (with-open [conn (db/open pool)] (let [project (db/get-by-id conn :project id)] (check-read-permissions! conn profile-id id) project))) --- MUTATION : Create Project (s/def ::create-project (s/keys :req [::rpc/profile-id] :req-un [::team-id ::name] :opt-un [::id])) (sv/defmethod ::create-project {::doc/added "1.18" ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id team-id] :as params}] (db/with-atomic [conn pool] (teams/check-edition-permissions! conn profile-id team-id) (quotes/check-quote! conn {::quotes/id ::quotes/projects-per-team ::quotes/profile-id profile-id ::quotes/team-id team-id}) (let [params (assoc params :profile-id profile-id) project (teams/create-project conn params)] (teams/create-project-role conn profile-id (:id project) :owner) (db/insert! conn :team-project-profile-rel {:project-id (:id project) :profile-id profile-id :team-id team-id :is-pinned true}) (assoc project :is-pinned true)))) --- MUTATION : Toggle Project Pin (def ^:private sql:update-project-pin "insert into team_project_profile_rel (team_id, project_id, profile_id, is_pinned) values (?, ?, ?, ?) on conflict (team_id, project_id, profile_id) do update set is_pinned=?") (s/def ::is-pinned ::us/boolean) (s/def ::project-id ::us/uuid) (s/def ::update-project-pin (s/keys :req [::rpc/profile-id] :req-un [::id ::team-id ::is-pinned])) (sv/defmethod ::update-project-pin {::doc/added "1.18" ::webhooks/batch-timeout (dt/duration "5s") ::webhooks/batch-key (webhooks/key-fn ::rpc/profile-id :id) ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id id team-id is-pinned] :as params}] (db/with-atomic [conn pool] (check-edition-permissions! conn profile-id id) (db/exec-one! conn [sql:update-project-pin team-id id profile-id is-pinned is-pinned]) nil)) (declare rename-project) (s/def ::rename-project (s/keys :req [::rpc/profile-id] :req-un [::name ::id])) (sv/defmethod ::rename-project {::doc/added "1.18" ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id id name] :as params}] (db/with-atomic [conn pool] (check-edition-permissions! conn profile-id id) (let [project (db/get-by-id conn :project id ::db/for-update? true)] (db/update! conn :project {:name name} {:id id}) (rph/with-meta (rph/wrap) {::audit/props {:team-id (:team-id project) :prev-name (:name project)}})))) (s/def ::delete-project (s/keys :req [::rpc/profile-id] :req-un [::id])) (sv/defmethod ::delete-project {::doc/added "1.18" ::webhooks/event? true} [{:keys [::db/pool] :as cfg} {:keys [::rpc/profile-id id] :as params}] (db/with-atomic [conn pool] (check-edition-permissions! conn profile-id id) (let [project (db/update! conn :project {:deleted-at (dt/now)} {:id id :is-default false})] (rph/with-meta (rph/wrap) {::audit/props {:team-id (:team-id project) :name (:name project) :created-at (:created-at project) :modified-at (:modified-at project)}}))))
46fd8250ba046ed048edcdcfa544231f31352a6a7c0045cc7cd0bd197830edeb
JacquesCarette/Drasil
Unicode.hs
-- | Special type for unicode characters. module Language.Drasil.Unicode(Special(Circle), RenderSpecial(special)) where -- | Special characters include partial derivatives and the degree circle. data Special = Circle -- remove by refactoring how units are done deriving (Eq, Ord) -- | Class for rendering special characters. class RenderSpecial r where special :: Special -> r
null
https://raw.githubusercontent.com/JacquesCarette/Drasil/93cb12d84e35a938aaa20d27da9c16504dc37f59/code/drasil-lang/lib/Language/Drasil/Unicode.hs
haskell
| Special type for unicode characters. | Special characters include partial derivatives and the degree circle. remove by refactoring how units are done | Class for rendering special characters.
module Language.Drasil.Unicode(Special(Circle), RenderSpecial(special)) where deriving (Eq, Ord) class RenderSpecial r where special :: Special -> r
385e3f540b2d6eaa576966abbd38d1eb55ae8b5e00ac069b53f0d2837455f704
jjmeyer0/gt
grammar.mli
module Grammar : sig type highlights = string * (string * string list) list type symbol = string * bool type production = Production of string * string * symbol list * symbol list list option type lexclass = string * string type grammar = Grammar of string list option * string * string * string option * production list * lexclass list * unit Trie.trie * highlights val get_ln_comment_delim : string option -> string val is_list : string -> bool val is_repetition : string -> bool val is_opt : string -> bool val is_terminal : symbol -> bool val starts_with_nonterminal : symbol list -> bool val sym_name : symbol -> string val svn_pos : symbol list -> string -> int val is_in_ast : unit Trie.trie -> string * bool -> bool val string_of_terminal : grammar -> string * 'a -> string val num_productions : grammar -> int val get_symbols : grammar -> symbol list val get_terminals : grammar -> symbol list val get_nonterminals : grammar -> symbol list val get_start_symbol : grammar -> symbol val output_symbol : (string -> unit) -> symbol -> unit val output_lexclasses : (string -> unit) -> unit Trie.trie -> (string * string) list -> unit val output_productions : (string -> unit) -> production list -> unit val output_grammar : (string -> unit) -> grammar -> unit val check_for_keywords : grammar -> unit end
null
https://raw.githubusercontent.com/jjmeyer0/gt/c0c7febc2e3fd532d44617f663b224cc0b9c7cf2/src/grammar.mli
ocaml
module Grammar : sig type highlights = string * (string * string list) list type symbol = string * bool type production = Production of string * string * symbol list * symbol list list option type lexclass = string * string type grammar = Grammar of string list option * string * string * string option * production list * lexclass list * unit Trie.trie * highlights val get_ln_comment_delim : string option -> string val is_list : string -> bool val is_repetition : string -> bool val is_opt : string -> bool val is_terminal : symbol -> bool val starts_with_nonterminal : symbol list -> bool val sym_name : symbol -> string val svn_pos : symbol list -> string -> int val is_in_ast : unit Trie.trie -> string * bool -> bool val string_of_terminal : grammar -> string * 'a -> string val num_productions : grammar -> int val get_symbols : grammar -> symbol list val get_terminals : grammar -> symbol list val get_nonterminals : grammar -> symbol list val get_start_symbol : grammar -> symbol val output_symbol : (string -> unit) -> symbol -> unit val output_lexclasses : (string -> unit) -> unit Trie.trie -> (string * string) list -> unit val output_productions : (string -> unit) -> production list -> unit val output_grammar : (string -> unit) -> grammar -> unit val check_for_keywords : grammar -> unit end
02839845295ee9d4bbea8da278957ff0e5792742c373fd394bdfc66ff6c5329a
nuprl/gradual-typing-performance
speech-bubble.rkt
#lang racket/base (provide speech-bubble) (require racket/draw racket/runtime-path) (define-runtime-path speech-bubble-img "speech-bubble.png") (define speech-bubble (read-bitmap speech-bubble-img))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/2htdp/planetcute/speech-bubble.rkt
racket
#lang racket/base (provide speech-bubble) (require racket/draw racket/runtime-path) (define-runtime-path speech-bubble-img "speech-bubble.png") (define speech-bubble (read-bitmap speech-bubble-img))
6b908b7ec31008cd559305b88d48664b34de6ade15882c1d4409496ff001b4a4
ml4tp/tcoq
arguments_renaming.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Names open Globnames open Environ open Term val rename_arguments : bool -> global_reference -> Name.t list -> unit (** [Not_found] is raised if no names are defined for [r] *) val arguments_names : global_reference -> Name.t list val rename_type_of_constant : env -> pconstant -> types val rename_type_of_inductive : env -> pinductive -> types val rename_type_of_constructor : env -> pconstructor -> types val rename_typing : env -> constr -> unsafe_judgment
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/pretyping/arguments_renaming.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * [Not_found] is raised if no names are defined for [r]
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Globnames open Environ open Term val rename_arguments : bool -> global_reference -> Name.t list -> unit val arguments_names : global_reference -> Name.t list val rename_type_of_constant : env -> pconstant -> types val rename_type_of_inductive : env -> pinductive -> types val rename_type_of_constructor : env -> pconstructor -> types val rename_typing : env -> constr -> unsafe_judgment
11ceea88fb7a52e5056727c0791094569ab6bc9f5572f408aae66fc7d1ebe1d0
ProjectMAC/propagators
virtual-environments.scm
;;; ---------------------------------------------------------------------- Copyright 2009 - 2010 . ;;; ---------------------------------------------------------------------- This file is part of Propagator Network Prototype . ;;; Propagator Network Prototype is free software ; you can ;;; redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) ;;; any later version. ;;; Propagator Network Prototype is distributed in the hope that it ;;; will be useful, but WITHOUT ANY WARRANTY; without even the implied ;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ;;; See the GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with Propagator Network Prototype . If not , see ;;; </>. ;;; ---------------------------------------------------------------------- ;;;; Fully-virtual environments. See environments.tex. (declare (usual-integrations make-cell cell?)) ;;;; Frames ;;; A frame tag is a record with an identity and a parent list. The ;;; notion is that the information in a cell at a frame is the stuff ;;; computed directly in that frame, or anywhere up the chain of ;;; ancestors. This is orthogonal to whether a frame can have ;;; multiple parents. (define-structure (frame (constructor %make-frame) (safe-accessors #t)) parents strict-ancestors) ; Cache the ancestor computation (define (%compute-ancestors frames) (delete-duplicates (append-map frame-ancestors frames))) (define (frame-ancestors frame) (cons frame (frame-strict-ancestors frame))) (define (make-frame parents) (%make-frame parents (%compute-ancestors parents))) ;;;; Virtual Copy Sets ;;; A virtual copies set is a structure that associates frame tags ;;; (which for the nonce need only be assumed to be eq?-comparable) ;;; with information. (define-structure (virtual-copies (safe-accessors #t)) alist) (declare-type-tester virtual-copies? rtd:virtual-copies) (define alist->virtual-copies make-virtual-copies) (define virtual-copies->alist virtual-copies-alist) (define-method generic-match ((pattern <pair>) (object rtd:virtual-copies)) (generic-match pattern (virtual-copies->alist object))) (define (frame-binding copy-set frame) ;; TODO Of course, an alist is the worst possible data structure for ;; this purpose, but it's built-in and it's persistent. (assq frame (virtual-copies-alist copy-set))) (define (occurring-frames copy-set) (map car (virtual-copies-alist copy-set))) (define (occurring-frames* copy-sets) (delete-duplicates (append-map occurring-frames copy-sets))) (define (frame-occurs? copy-set frame) (not (not (frame-binding copy-set frame)))) (define (direct-frame-content copy-set frame) (let ((occurrence (frame-binding copy-set frame))) (if occurrence (cdr occurrence) nothing))) ;;;; Frame & Copy-set Interactions ;;; The intention is that the full information content of a cell in a ;;; frame is the merge of all information available in that frame and ;;; all that frame's ancestors. I can implement that intention directly per below ; or I can use one - cell cross - frame propagators ;;; to maintain the invariant that the direct content in every frame ;;; stabilizes to be the same as the intended full content; or I can ;;; hatch some scheme whereby that intention is maintained in some ;;; implicit manner but not represented explicitly. That's a choice. (define (full-frame-content copy-set frame) (fold merge nothing (map (lambda (frame) (direct-frame-content copy-set frame)) (frame-ancestors frame)))) (define (ancestral-occurrence-count copy-set frame) (count (lambda (frame) (frame-occurs? copy-set frame)) (frame-ancestors frame))) ;; See environments.tex for the meaning of "acceptable". (define (acceptable-frame? frame copy-sets) (apply boolean/and (map (lambda (copy-set) (<= 1 (ancestral-occurrence-count copy-set frame))) copy-sets))) ;; See environments.tex for the meaning of "good". (define (good-frame? frame copy-sets) (and (acceptable-frame? frame copy-sets) (not (apply boolean/or (map (lambda (parent) (acceptable-frame? parent copy-sets)) (frame-parents frame)))))) (define (good-frames copy-sets) ;; TODO I'm *certain* there's a more efficient way to do this (filter (lambda (frame) (good-frame? frame copy-sets)) (occurring-frames* copy-sets))) (define (lexical-invariant? copy-set) (apply boolean/and (map (lambda (frame) (<= (ancestral-occurrence-count copy-set frame) 1)) (occurring-frames copy-set)))) ;; This operation, as named, depends on the lexical invariant above ;; holding good. (define (the-occurring-parent frame copy-set) (find (lambda (parent) (frame-occurs? copy-set parent)) (frame-ancestors frame))) ;;;; Equating and merging virtual copy sets (define (v-c-equal? copy-set1 copy-set2) (let ((the-frames (occurring-frames copy-set1))) (and (lset= eq? the-frames (occurring-frames copy-set2)) (apply boolean/and (map (lambda (frame) (equivalent? (full-frame-content copy-set1 frame) (full-frame-content copy-set2 frame))) the-frames))))) ;;; This merge is OK if "normal" propagators use v-c-i/o-unpacking ;;; (below) for their operations. Then they will respect the ;;; occurrence structure so the merge operation doesn't have to. (define (virtual-copy-merge copy-set1 copy-set2) (define (frame-by-frame f) (lambda args (alist->virtual-copies (map (lambda (frame) (cons frame (apply f (map (lambda (arg) (full-frame-content arg frame)) args)))) (occurring-frames* args))))) ((frame-by-frame merge) copy-set1 copy-set2)) (defhandler merge virtual-copy-merge virtual-copies? virtual-copies?) (defhandler equivalent? v-c-equal? virtual-copies? virtual-copies?) (defhandler contradictory? (lambda (vcs) (any contradictory? (map cdr (virtual-copies->alist vcs)))) virtual-copies?) ;;;; Propagator Machinery ;;; Doing virtual copies via the generic-unpack mechanism presents three problems . First , imagine a binary operation with two ;;; virtual-copies arguments. A direct implementation of ;;; virtual-copy-bind would evaluate that operation on all ;;; quadratically many combinations of pairs of frames, and then do ;;; something to only keep the pieces we had wanted. That could get ugly . Second , the unpacking mechanism below actually needs to ;;; look at all the neighbor cells in order to decide which sets of ;;; frames to operate on. Third, if one goes through the standard ;;; unpack-flatten mechanism, then a binary operation working on a pair of virtual copies of of something will find itself trying to flatten a set of virtual copies of of virtual copies of of something . Doing that correctly requires a ;;; mechanism to turn a TMS of virtual copies of X into a virtual ;;; copies of a TMS of X; but under the current regime (i.e. without ;;; knowing what type the final result is supposed to be) the existence of that mechanism will force all of virtual copies to become virtual copies of . But what if I * want * to ;;; subject the frames to TMS premises in some region of the network? ;;; This is a very general problem. Are monad transformers such ;;; conversion mechanisms? Or do they prevent this issue from arising ;;; by some other means? (Or are they completely unrelated?) This ;;; whole mess is perhaps a function of not being able to look at what ;;; the client wants. (define (v-c-i/o-unpacking f) (lambda args (let ((output (car (last-pair args))) (inputs (except-last-pair args))) (alist->virtual-copies (map (lambda (frame) (cons (the-occurring-parent frame output) (apply f (map (lambda (copy-set) (full-frame-content copy-set frame)) inputs)))) (good-frames args)))))) (define (i/o-function->propagator-constructor f) (lambda cells (let ((output (car (last-pair cells)))) (propagator cells (lambda () (add-content output (apply f (map content cells)))))))) ;; Now the version with the metadata (define (i/o-function->propagator-constructor f) (lambda cells (let ((output (car (last-pair cells)))) (propagator cells (eq-label! (lambda () (add-content output (apply f (map content cells)))) TODO Currently ok , because the last " input " is only used ;; for virtualization 'inputs (except-last-pair cells) 'name f 'outputs (list output)))))) (define (doit f) (i/o-function->propagator-constructor (eq-put! (lambda args TODO this to other information types (if (any nothing? args) nothing (apply (v-c-i/o-unpacking (nary-unpacking f)) args))) 'name f))) ;;;; Propagators (define vc:adder (doit generic-+)) (define vc:subtractor (doit generic--)) (define vc:multiplier (doit generic-*)) (define vc:divider (doit generic-/)) (define vc:absolute-value (doit generic-abs)) (define vc:squarer (doit generic-square)) (define vc:sqrter (doit generic-sqrt)) (define vc:=? (doit generic-=)) (define vc:<? (doit generic-<)) (define vc:>? (doit generic->)) (define vc:<=? (doit generic-<=)) (define vc:>=? (doit generic->=)) (define vc:inverter (doit generic-not)) (define vc:conjoiner (doit generic-and)) (define vc:disjoiner (doit generic-or)) (define (vc:const value) (doit (eq-put! (lambda () value) 'name (list 'const value)))) (define vc:switch (doit switch-function)) (define generic-quotient (make-generic-operator 2 'quotient quotient)) (eq-put! generic-quotient 'name 'quotient) (define vc:quotient (doit generic-quotient)) (define generic-remainder (make-generic-operator 2 'remainder remainder)) (eq-put! generic-remainder 'name 'remainder) (define vc:remainder (doit generic-remainder))
null
https://raw.githubusercontent.com/ProjectMAC/propagators/add671f009e62441e77735a88980b6b21fad7a79/extensions/virtual-environments.scm
scheme
---------------------------------------------------------------------- ---------------------------------------------------------------------- you can redistribute it and/or modify it under the terms of the GNU any later version. will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. </>. ---------------------------------------------------------------------- Fully-virtual environments. See environments.tex. Frames A frame tag is a record with an identity and a parent list. The notion is that the information in a cell at a frame is the stuff computed directly in that frame, or anywhere up the chain of ancestors. This is orthogonal to whether a frame can have multiple parents. Cache the ancestor computation Virtual Copy Sets A virtual copies set is a structure that associates frame tags (which for the nonce need only be assumed to be eq?-comparable) with information. TODO Of course, an alist is the worst possible data structure for this purpose, but it's built-in and it's persistent. Frame & Copy-set Interactions The intention is that the full information content of a cell in a frame is the merge of all information available in that frame and all that frame's ancestors. I can implement that intention or I can use one - cell cross - frame propagators to maintain the invariant that the direct content in every frame stabilizes to be the same as the intended full content; or I can hatch some scheme whereby that intention is maintained in some implicit manner but not represented explicitly. That's a choice. See environments.tex for the meaning of "acceptable". See environments.tex for the meaning of "good". TODO I'm *certain* there's a more efficient way to do this This operation, as named, depends on the lexical invariant above holding good. Equating and merging virtual copy sets This merge is OK if "normal" propagators use v-c-i/o-unpacking (below) for their operations. Then they will respect the occurrence structure so the merge operation doesn't have to. Propagator Machinery Doing virtual copies via the generic-unpack mechanism presents virtual-copies arguments. A direct implementation of virtual-copy-bind would evaluate that operation on all quadratically many combinations of pairs of frames, and then do something to only keep the pieces we had wanted. That could get look at all the neighbor cells in order to decide which sets of frames to operate on. Third, if one goes through the standard unpack-flatten mechanism, then a binary operation working on a mechanism to turn a TMS of virtual copies of X into a virtual copies of a TMS of X; but under the current regime (i.e. without knowing what type the final result is supposed to be) the subject the frames to TMS premises in some region of the network? This is a very general problem. Are monad transformers such conversion mechanisms? Or do they prevent this issue from arising by some other means? (Or are they completely unrelated?) This whole mess is perhaps a function of not being able to look at what the client wants. Now the version with the metadata for virtualization Propagators
Copyright 2009 - 2010 . This file is part of Propagator Network Prototype . General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) Propagator Network Prototype is distributed in the hope that it You should have received a copy of the GNU General Public License along with Propagator Network Prototype . If not , see (declare (usual-integrations make-cell cell?)) (define-structure (frame (constructor %make-frame) (safe-accessors #t)) parents (define (%compute-ancestors frames) (delete-duplicates (append-map frame-ancestors frames))) (define (frame-ancestors frame) (cons frame (frame-strict-ancestors frame))) (define (make-frame parents) (%make-frame parents (%compute-ancestors parents))) (define-structure (virtual-copies (safe-accessors #t)) alist) (declare-type-tester virtual-copies? rtd:virtual-copies) (define alist->virtual-copies make-virtual-copies) (define virtual-copies->alist virtual-copies-alist) (define-method generic-match ((pattern <pair>) (object rtd:virtual-copies)) (generic-match pattern (virtual-copies->alist object))) (define (frame-binding copy-set frame) (assq frame (virtual-copies-alist copy-set))) (define (occurring-frames copy-set) (map car (virtual-copies-alist copy-set))) (define (occurring-frames* copy-sets) (delete-duplicates (append-map occurring-frames copy-sets))) (define (frame-occurs? copy-set frame) (not (not (frame-binding copy-set frame)))) (define (direct-frame-content copy-set frame) (let ((occurrence (frame-binding copy-set frame))) (if occurrence (cdr occurrence) nothing))) (define (full-frame-content copy-set frame) (fold merge nothing (map (lambda (frame) (direct-frame-content copy-set frame)) (frame-ancestors frame)))) (define (ancestral-occurrence-count copy-set frame) (count (lambda (frame) (frame-occurs? copy-set frame)) (frame-ancestors frame))) (define (acceptable-frame? frame copy-sets) (apply boolean/and (map (lambda (copy-set) (<= 1 (ancestral-occurrence-count copy-set frame))) copy-sets))) (define (good-frame? frame copy-sets) (and (acceptable-frame? frame copy-sets) (not (apply boolean/or (map (lambda (parent) (acceptable-frame? parent copy-sets)) (frame-parents frame)))))) (define (good-frames copy-sets) (filter (lambda (frame) (good-frame? frame copy-sets)) (occurring-frames* copy-sets))) (define (lexical-invariant? copy-set) (apply boolean/and (map (lambda (frame) (<= (ancestral-occurrence-count copy-set frame) 1)) (occurring-frames copy-set)))) (define (the-occurring-parent frame copy-set) (find (lambda (parent) (frame-occurs? copy-set parent)) (frame-ancestors frame))) (define (v-c-equal? copy-set1 copy-set2) (let ((the-frames (occurring-frames copy-set1))) (and (lset= eq? the-frames (occurring-frames copy-set2)) (apply boolean/and (map (lambda (frame) (equivalent? (full-frame-content copy-set1 frame) (full-frame-content copy-set2 frame))) the-frames))))) (define (virtual-copy-merge copy-set1 copy-set2) (define (frame-by-frame f) (lambda args (alist->virtual-copies (map (lambda (frame) (cons frame (apply f (map (lambda (arg) (full-frame-content arg frame)) args)))) (occurring-frames* args))))) ((frame-by-frame merge) copy-set1 copy-set2)) (defhandler merge virtual-copy-merge virtual-copies? virtual-copies?) (defhandler equivalent? v-c-equal? virtual-copies? virtual-copies?) (defhandler contradictory? (lambda (vcs) (any contradictory? (map cdr (virtual-copies->alist vcs)))) virtual-copies?) three problems . First , imagine a binary operation with two ugly . Second , the unpacking mechanism below actually needs to pair of virtual copies of of something will find itself trying to flatten a set of virtual copies of of virtual copies of of something . Doing that correctly requires a existence of that mechanism will force all of virtual copies to become virtual copies of . But what if I * want * to (define (v-c-i/o-unpacking f) (lambda args (let ((output (car (last-pair args))) (inputs (except-last-pair args))) (alist->virtual-copies (map (lambda (frame) (cons (the-occurring-parent frame output) (apply f (map (lambda (copy-set) (full-frame-content copy-set frame)) inputs)))) (good-frames args)))))) (define (i/o-function->propagator-constructor f) (lambda cells (let ((output (car (last-pair cells)))) (propagator cells (lambda () (add-content output (apply f (map content cells)))))))) (define (i/o-function->propagator-constructor f) (lambda cells (let ((output (car (last-pair cells)))) (propagator cells (eq-label! (lambda () (add-content output (apply f (map content cells)))) TODO Currently ok , because the last " input " is only used 'inputs (except-last-pair cells) 'name f 'outputs (list output)))))) (define (doit f) (i/o-function->propagator-constructor (eq-put! (lambda args TODO this to other information types (if (any nothing? args) nothing (apply (v-c-i/o-unpacking (nary-unpacking f)) args))) 'name f))) (define vc:adder (doit generic-+)) (define vc:subtractor (doit generic--)) (define vc:multiplier (doit generic-*)) (define vc:divider (doit generic-/)) (define vc:absolute-value (doit generic-abs)) (define vc:squarer (doit generic-square)) (define vc:sqrter (doit generic-sqrt)) (define vc:=? (doit generic-=)) (define vc:<? (doit generic-<)) (define vc:>? (doit generic->)) (define vc:<=? (doit generic-<=)) (define vc:>=? (doit generic->=)) (define vc:inverter (doit generic-not)) (define vc:conjoiner (doit generic-and)) (define vc:disjoiner (doit generic-or)) (define (vc:const value) (doit (eq-put! (lambda () value) 'name (list 'const value)))) (define vc:switch (doit switch-function)) (define generic-quotient (make-generic-operator 2 'quotient quotient)) (eq-put! generic-quotient 'name 'quotient) (define vc:quotient (doit generic-quotient)) (define generic-remainder (make-generic-operator 2 'remainder remainder)) (eq-put! generic-remainder 'name 'remainder) (define vc:remainder (doit generic-remainder))
673cd778ec46334c7fba89fe19e8e6ccf395c91538e25cf3f783ba178cea3883
helium/gateway-config
gateway_gatt_char_wifi_services.erl
-module(gateway_gatt_char_wifi_services). -include("gateway_gatt.hrl"). -include("pb/gateway_gatt_char_wifi_services_pb.hrl"). -ifdef(TEST). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). -endif. -behavior(gatt_characteristic). -export([ init/2, uuid/1, flags/1, read_value/2, encode_services/1, encode_services/2 ]). -record(state, { path :: ebus:object_path(), value = <<>> :: binary() }). -define(MAX_VALUE_SIZE, 512). uuid(_) -> ?UUID_GATEWAY_GATT_CHAR_WIFI_SERVICES. flags(_) -> [read]. init(Path, _) -> Descriptors = [ {gatt_descriptor_cud, 0, ["WiFi Services"]}, {gatt_descriptor_pf, 1, [utf8_string]} ], {ok, Descriptors, #state{path = Path}}. read_value(State = #state{value = Value}, #{"offset" := Offset}) -> {ok, binary:part(Value, Offset, byte_size(Value) - Offset), State}; read_value(State = #state{}, _Opts) -> Services = gateway_config:wifi_services(), Names = [Name || {Name, _} <- Services], case encode_services(Names) of {ok, _, Bin} -> {ok, Bin, State#state{value = Bin}}; {error, _} -> {ok, <<"error">>, State#state{value = <<>>}} end. -spec encode_services([string()]) -> {ok, [string()], binary()} | {error, term()}. encode_services(Names) -> encode_services({Names, []}, ?MAX_VALUE_SIZE). -spec encode_services({[string()], [string()]}, pos_integer()) -> {ok, [string()], binary()} | {error, term()}. encode_services({Services, Tail}, MaxSize) -> Bin = encode_names(Services), case byte_size(Bin) > MaxSize of true when length(Services) == 1 -> {error, service_length}; true -> encode_services(lists:split(length(Services) div 2, Services), MaxSize); false when length(Tail) =< 1 -> {ok, Services, Bin}; false -> {Add, NewTail} = lists:split(length(Tail) div 2, Tail), encode_services({Services ++ Add, NewTail}, MaxSize) end. -spec encode_names([string()]) -> binary(). encode_names(Names) -> Msg = #gateway_wifi_services_v1_pb{services = Names}, gateway_gatt_char_wifi_services_pb:encode_msg(Msg). -ifdef(TEST). uuid_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), ?assertEqual(?UUID_GATEWAY_GATT_CHAR_WIFI_SERVICES, ?MODULE:uuid(Char)), ok. flags_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), ?assertEqual([read], ?MODULE:flags(Char)), ok. success_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), Services = [ {"Verizon-MiFi7730L-F4C0", 70}, {"LAKEHOUSE", 57}, {"ARRIS-D2D7", 53}, {"HP-Print-3D-Deskjet 3520 series", 43}, {"Sun WiFi", 41}, {"RVi-CC-a81b6a993575", 37}, {"RVi-CC-6064059e03ac", 37} ], ServiceNames = [Name || {Name, _} <- Services], meck:new(gateway_config, [passthrough]), meck:expect( gateway_config, wifi_services, fun() -> Services end ), %% Ensure we can read the characteristic {ok, Bin, _Char2} = ?MODULE:read_value(Char, #{}), %% And that it decodes to the right list of names ?assertMatch( #gateway_wifi_services_v1_pb{services = ServiceNames}, gateway_gatt_char_wifi_services_pb:decode_msg(Bin, gateway_wifi_services_v1_pb) ), ?assert(meck:validate(gateway_config)), meck:unload(gateway_config), ok. error_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), Services = [{binary_to_list(crypto:strong_rand_bytes(?MAX_VALUE_SIZE + 1)), 80}], meck:new(gateway_config, [passthrough]), meck:expect( gateway_config, wifi_services, fun() -> Services end ), ?assertMatch({ok, <<"error">>, _}, ?MODULE:read_value(Char, #{})), ?assert(meck:validate(gateway_config)), meck:unload(gateway_config), ok. to_range(M, N) -> Base = N div M, {Base * M, (Base + 1) * M}. %% Test the properties of how we encode a list of service ids prop_encode() -> ?FORALL( Names, service_id_list(), collect( to_range(10, length(Names)), begin case encode_services(Names) of {ok, EncodedNames, Encoded} -> %% If the list encodes successfully {EncodedNames, Tail} = lists:split(length(EncodedNames), Names), case Tail of [] -> %% and there is no remaining service %% ids, the encoded list must be the %% right size. byte_size(Encoded) =< ?MAX_VALUE_SIZE andalso EncodedNames == Names; _ -> %% and there are remaining service ids , then just adding one of the %% remaining ones must push it past the size EncodeOneMore = encode_names(EncodedNames ++ [hd(Tail)]), lists:prefix(EncodedNames, Names) andalso byte_size(EncodeOneMore) > ?MAX_VALUE_SIZE end; {error, service_length} -> %% If there was a encodeing failure, the _ first _ name must have been too long . EncodedFirst = encode_names([hd(Names)]), byte_size(EncodedFirst) > ?MAX_VALUE_SIZE end end ) ). Geneerate service ids that are mostly the right size , but %% occasionally outrageously long. service_id() -> frequency([ {5, ?SIZED(Size, resize(1000 * Size, list(byte())))}, {90, list(byte())} ]). service_id_list() -> frequency([ {5, ?SIZED(Size, resize(10 * Size, list(service_id())))}, {90, list(service_id())} ]). encode_test() -> ?assert(proper:quickcheck(prop_encode(), [long_result])), ok. -endif.
null
https://raw.githubusercontent.com/helium/gateway-config/5a98da0d2711a87f67c80ec6ea9f710dbed727ff/src/gateway_gatt_char_wifi_services.erl
erlang
Ensure we can read the characteristic And that it decodes to the right list of names Test the properties of how we encode a list of service ids If the list encodes successfully and there is no remaining service ids, the encoded list must be the right size. and there are remaining service remaining ones must push it past If there was a encodeing failure, the occasionally outrageously long.
-module(gateway_gatt_char_wifi_services). -include("gateway_gatt.hrl"). -include("pb/gateway_gatt_char_wifi_services_pb.hrl"). -ifdef(TEST). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). -endif. -behavior(gatt_characteristic). -export([ init/2, uuid/1, flags/1, read_value/2, encode_services/1, encode_services/2 ]). -record(state, { path :: ebus:object_path(), value = <<>> :: binary() }). -define(MAX_VALUE_SIZE, 512). uuid(_) -> ?UUID_GATEWAY_GATT_CHAR_WIFI_SERVICES. flags(_) -> [read]. init(Path, _) -> Descriptors = [ {gatt_descriptor_cud, 0, ["WiFi Services"]}, {gatt_descriptor_pf, 1, [utf8_string]} ], {ok, Descriptors, #state{path = Path}}. read_value(State = #state{value = Value}, #{"offset" := Offset}) -> {ok, binary:part(Value, Offset, byte_size(Value) - Offset), State}; read_value(State = #state{}, _Opts) -> Services = gateway_config:wifi_services(), Names = [Name || {Name, _} <- Services], case encode_services(Names) of {ok, _, Bin} -> {ok, Bin, State#state{value = Bin}}; {error, _} -> {ok, <<"error">>, State#state{value = <<>>}} end. -spec encode_services([string()]) -> {ok, [string()], binary()} | {error, term()}. encode_services(Names) -> encode_services({Names, []}, ?MAX_VALUE_SIZE). -spec encode_services({[string()], [string()]}, pos_integer()) -> {ok, [string()], binary()} | {error, term()}. encode_services({Services, Tail}, MaxSize) -> Bin = encode_names(Services), case byte_size(Bin) > MaxSize of true when length(Services) == 1 -> {error, service_length}; true -> encode_services(lists:split(length(Services) div 2, Services), MaxSize); false when length(Tail) =< 1 -> {ok, Services, Bin}; false -> {Add, NewTail} = lists:split(length(Tail) div 2, Tail), encode_services({Services ++ Add, NewTail}, MaxSize) end. -spec encode_names([string()]) -> binary(). encode_names(Names) -> Msg = #gateway_wifi_services_v1_pb{services = Names}, gateway_gatt_char_wifi_services_pb:encode_msg(Msg). -ifdef(TEST). uuid_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), ?assertEqual(?UUID_GATEWAY_GATT_CHAR_WIFI_SERVICES, ?MODULE:uuid(Char)), ok. flags_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), ?assertEqual([read], ?MODULE:flags(Char)), ok. success_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), Services = [ {"Verizon-MiFi7730L-F4C0", 70}, {"LAKEHOUSE", 57}, {"ARRIS-D2D7", 53}, {"HP-Print-3D-Deskjet 3520 series", 43}, {"Sun WiFi", 41}, {"RVi-CC-a81b6a993575", 37}, {"RVi-CC-6064059e03ac", 37} ], ServiceNames = [Name || {Name, _} <- Services], meck:new(gateway_config, [passthrough]), meck:expect( gateway_config, wifi_services, fun() -> Services end ), {ok, Bin, _Char2} = ?MODULE:read_value(Char, #{}), ?assertMatch( #gateway_wifi_services_v1_pb{services = ServiceNames}, gateway_gatt_char_wifi_services_pb:decode_msg(Bin, gateway_wifi_services_v1_pb) ), ?assert(meck:validate(gateway_config)), meck:unload(gateway_config), ok. error_test() -> {ok, _, Char} = ?MODULE:init("", [proxy]), Services = [{binary_to_list(crypto:strong_rand_bytes(?MAX_VALUE_SIZE + 1)), 80}], meck:new(gateway_config, [passthrough]), meck:expect( gateway_config, wifi_services, fun() -> Services end ), ?assertMatch({ok, <<"error">>, _}, ?MODULE:read_value(Char, #{})), ?assert(meck:validate(gateway_config)), meck:unload(gateway_config), ok. to_range(M, N) -> Base = N div M, {Base * M, (Base + 1) * M}. prop_encode() -> ?FORALL( Names, service_id_list(), collect( to_range(10, length(Names)), begin case encode_services(Names) of {ok, EncodedNames, Encoded} -> {EncodedNames, Tail} = lists:split(length(EncodedNames), Names), case Tail of [] -> byte_size(Encoded) =< ?MAX_VALUE_SIZE andalso EncodedNames == Names; _ -> ids , then just adding one of the the size EncodeOneMore = encode_names(EncodedNames ++ [hd(Tail)]), lists:prefix(EncodedNames, Names) andalso byte_size(EncodeOneMore) > ?MAX_VALUE_SIZE end; {error, service_length} -> _ first _ name must have been too long . EncodedFirst = encode_names([hd(Names)]), byte_size(EncodedFirst) > ?MAX_VALUE_SIZE end end ) ). Geneerate service ids that are mostly the right size , but service_id() -> frequency([ {5, ?SIZED(Size, resize(1000 * Size, list(byte())))}, {90, list(byte())} ]). service_id_list() -> frequency([ {5, ?SIZED(Size, resize(10 * Size, list(service_id())))}, {90, list(service_id())} ]). encode_test() -> ?assert(proper:quickcheck(prop_encode(), [long_result])), ok. -endif.
a705e846fb07eb378bdf54e7800d3aba680302e6c961d561a59441defa2907e0
rescript-lang/rescript-compiler
bsb_package_kind.ml
Copyright ( C ) 2020 - Hongbo Zhang , Authors of ReScript * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) type dep_payload = { package_specs : Bsb_package_specs.t; jsx : Bsb_jsx.t } type t = | Toplevel | Dependency of dep_payload | Pinned_dependency of dep_payload (* This package specs comes from the toplevel to override the current settings *) let encode_no_nl (x : t) = match x with | Toplevel -> "0" | Dependency x -> "1" ^ Bsb_package_specs.package_flag_of_package_specs x.package_specs ~dirname:"." ^ Bsb_jsx.encode_no_nl x.jsx | Pinned_dependency x -> "2" ^ Bsb_package_specs.package_flag_of_package_specs x.package_specs ~dirname:"." ^ Bsb_jsx.encode_no_nl x.jsx
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/ef3420e05f1546d572162ea0ca3f5d35d2a07e26/jscomp/bsb/bsb_package_kind.ml
ocaml
This package specs comes from the toplevel to override the current settings
Copyright ( C ) 2020 - Hongbo Zhang , Authors of ReScript * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) type dep_payload = { package_specs : Bsb_package_specs.t; jsx : Bsb_jsx.t } type t = | Toplevel | Dependency of dep_payload | Pinned_dependency of dep_payload let encode_no_nl (x : t) = match x with | Toplevel -> "0" | Dependency x -> "1" ^ Bsb_package_specs.package_flag_of_package_specs x.package_specs ~dirname:"." ^ Bsb_jsx.encode_no_nl x.jsx | Pinned_dependency x -> "2" ^ Bsb_package_specs.package_flag_of_package_specs x.package_specs ~dirname:"." ^ Bsb_jsx.encode_no_nl x.jsx
dd7e245b62731796761d0c98bb47c4cf6466bb63d26db0c0bc42ad550cb9a061
ocsigen/eliom
ppx_eliom_server_ex.ml
open Ppx_eliom_server [@@warning "-33"] let () = Ppxlib.Driver.run_as_ppx_rewriter ()
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/ppx/ppx_eliom_server_ex.ml
ocaml
open Ppx_eliom_server [@@warning "-33"] let () = Ppxlib.Driver.run_as_ppx_rewriter ()
e828ceba8947281ccc80875d0151742b939b3479c33a196ae3ed9d32d1092314
quil-lang/quilc
chip-table-tests.lisp
;;;; tests/chip-library/chip-table-tests.lisp ;;;; Author : (in-package #:cl-quil.chip-library-tests) (deftest default-chips () (is (equalp (call-chip-builder "8q") (q::build-8q-chip))) (is (equalp (call-chip-builder "20Q") (q::build-skew-rectangular-chip 0 4 5)))) (deftest define-chip () ;; Uses the non-sense name "" (install-chip-builder "" nil :no-warn t) (is (not (install-chip-builder "" #'q::build-skew-rectangular-chip))) (is (equalp (q::build-skew-rectangular-chip 0 1 2) (call-chip-builder "" 0 1 2))) (is (install-chip-builder "" nil :no-warn t)) (is (not (install-chip-builder "" nil))))
null
https://raw.githubusercontent.com/quil-lang/quilc/36f6ffb979bbd460efb85a0b4cd1277e5e673aab/tests/chip-library/chip-table-tests.lisp
lisp
tests/chip-library/chip-table-tests.lisp Uses the non-sense name ""
Author : (in-package #:cl-quil.chip-library-tests) (deftest default-chips () (is (equalp (call-chip-builder "8q") (q::build-8q-chip))) (is (equalp (call-chip-builder "20Q") (q::build-skew-rectangular-chip 0 4 5)))) (deftest define-chip () (install-chip-builder "" nil :no-warn t) (is (not (install-chip-builder "" #'q::build-skew-rectangular-chip))) (is (equalp (q::build-skew-rectangular-chip 0 1 2) (call-chip-builder "" 0 1 2))) (is (install-chip-builder "" nil :no-warn t)) (is (not (install-chip-builder "" nil))))
1363f4ce00b4ce0aa5299af3a19f4beb76f6bd44f887301eb4140291b85019bc
khayyamsaleem/gradual-typing
caster.scm
;; Cast (load "pmatch.scm") (load "types.scm") ;; Syntactic Extensions (define-syntax fn-erase (syntax-rules (:) ((_ (: v type)) '(v)) ((_ ((: v type) v2 ...)) `(v ,@(fn-erase v2 ...))))) (define-syntax fn ;; Can we avoid the use of eval here? (syntax-rules (:) ((_ (: v type) (: return) body ...) (lambda (v) body ...)) ((_ (: v type) body ...) (lambda (v) body ...)) ((_ ((: v type) v2 ...) (: return) body ...) (fn ((: v type) v2 ...) body ...)) ((_ ((: v type) v2 ...) body ...) (let ((env (the-environment))) (eval `(lambda ,(fn-erase ((: v type) v2 ...)) body ...) env))) ((_ () body ...) (lambda () body ...)))) (define-syntax listof (syntax-rules (:) ((_ (: type) . items) (quote items)))) ;; Helpers (define (all-equal? ls) (or (or (null? ls) (null? (cdr ls))) (and (equal? (car ls) (cadr ls)) (all-equal? (cdr ls))))) ;; Type environments are hash tables now (define (te/new) (make-hash-table)) (define (te/lookup te var) (hash-table/get te var #f)) (define (te/extend te var type) (hash-table/put! te var type) te) (define (te/nextend te vars types) (for-each (lambda (k v) (hash-table/put! te k v)) vars types) te) (define (te/remove te var) (hash-table/remove! te var) te) (define (te/nremove te vars) (for-each (lambda (v) (te/remove te v)) vars) te) (define (te/merge te1 te2) (define (put-func h1 h2) (hash-table/for-each h2 (lambda (k v) (hash-table/put! h1 k v)))) (let ((te (te/new))) (put-func te te1) (put-func te te2) te)) (define (te/nmerge tes) (fold-left (lambda (acc x) (te/merge acc x)) (car tes) tes)) (define (te/copy te) (let ((te-copy (te/new))) (hash-table/for-each te (lambda (k v) (hash-table/put! te-copy k v))) te-copy)) (define te->alist hash-table->alist) (define (alist->te alist) (let ((te (te/new))) (for-each (lambda (e) (hash-table/put! te (car e) (cdr e))) alist) te)) ;; Cast Judgements (define-structure (cj) te exp type) ;; / is more readable than - at times (define cj/te cj-te) (define cj/exp cj-exp) (define cj/type cj-type) ;; Dealing with casts (define (cast? exp) (and (pair? exp) (eq? (car exp) ':))) (define (make-cast exp type) `(: ,exp ,type)) (define (uncast exp) (and (cast? exp) (cadr exp))) (define cast/exp uncast) (define (cast/type exp) (and (cast? exp) (caddr exp))) Transform to intermediate langugae ;; Returns a cast judgement (define (transform exp te) (pmatch exp (,e (guard (number? e)) (make-cj te (make-cast e 'number) 'number)) (,e (guard (string? e)) (make-cj te (make-cast e 'string) 'string)) (,e (guard (boolean? e)) (make-cj te (make-cast e 'boolean) 'boolean)) (,e (guard (char? e)) (make-cj te (make-cast e 'char) 'char)) (,e (guard (symbol? e)) (let ((binding (te/lookup te e))) ; te/lookup returns #f if e not bound (if binding (make-cj te (make-cast e binding) binding) (make-cj (te/extend te e 'any) (make-cast e 'any) 'any)))) ((pair ,x ,y) (let* ((x-tf (transform x te)) (y-tf (transform y te)) (new-te (te/nmerge (list te (cj/te x-tf) (cj/te y-tf))))) (make-cj te (make-cast `(pair ,(cj/exp x-tf) ,(cj/exp y-tf)) (make-pair-type (cj/type x-tf) (cj/type y-tf))) (make-pair-type (cj/type x-tf) (cj/type y-tf))))) ((listof (: ,type) . ,items) (if (null? items) (make-cj te (make-cast `(listof (: ,type)) (make-list-type type)) (make-list-type type)) (let* ((items-tf (map (lambda (e) (transform e te)) items)) (items-types (map (lambda (e) (cj/type e)) items-tf)) (items-cast (map (lambda (e) (cj/exp e)) items-tf))) (if ;; (and (~ type (car items-types)) (all-equal? items-types)) (~ type (car items-types)) (let* ( ;; (new-te (te/nmerge (map (lambda (e) (te/extend (cj/te e) ;; (uncast (cj/exp e)) ;; type)) items-tf))) (new-te (te/nmerge (map (lambda (e) (cj/te e)) items-tf))) (cast-items (map (lambda (e) (make-cast (uncast e) type)) items-cast)) (cast-exp (make-cast `(listof (: ,type) ,@cast-items) (make-list-type type)))) (make-cj (te/merge new-te te) cast-exp (make-list-type type))) (error "TypeError: " 'list 'elements 'should 'type 'consistent))))) ((defvar (: ,var ,type) ,val) (let ((val-tf (transform val te))) (if (~ (cj/type val-tf) type) (make-cj (te/merge (cj/te val-tf) (te/extend te var type)) (make-cast `(defvar (: ,var ,type) ,(cj/exp val-tf)) 'unit) 'unit) (error "TypeError: " 'expected type 'in 'defvar var 'but 'got (cj/type val-tf))))) ((if ,pred ,clause1 ,clause2) (let ((pred-tf (transform pred te))) (if (equal? (cj/type pred-tf) 'boolean) (let* ((clause1-tf (transform clause1 te)) (clause2-tf (transform clause2 te))) (if ;; (equal? (cj/type clause1-tf) (cj/type clause2-tf)) (~ (cj/type clause1-tf) (cj/type clause2-tf)) (let ((new-te (te/nmerge (map (lambda (e) (cj/te e)) (list pred-tf clause1-tf clause2-tf)))) (cast-exp (make-cast `(if ,(cj/exp pred-tf) ,(cj/exp clause1-tf) ,(cj/exp clause2-tf)) (cj/type clause1-tf)))) (make-cj (te/merge new-te te) cast-exp (cj/type clause1-tf))) (error "TypeError: " 'if 'branches 'should 'have 'consistent 'type '- 'got (cj/type clause1-tf) 'and (cj/type clause2-tf)))) (error "TypeError: " pred 'should 'be 'a 'boolean '- 'got (cj/type pred-tf))))) ((fn (: ,v ,type) ,body) (let* ((new-te (te/extend (te/copy te) v type)) (body-tf (transform body new-te)) (cast-exp (make-cast `(fn (: ,v ,type) ,(cj/exp body-tf)) `(-> ,type ,(cj/type body-tf))))) (make-cj (te/merge (te/remove new-te v) te) cast-exp `(-> ,type ,(cj/type body-tf))))) ;; ((fn (: ,v ,type) ,body) ;; (let* ((new-te (te/extend (te/copy te) v type)) ;; (body-tf (transform body new-te))) ;; (begin ;; (display "Type of ") (display v) (display " in body : ") ;; (display (te/lookup (cj/te body-tf) v)) (newline) ;; (if (not (equal? (te/lookup (cj/te body-tf) v) type)) ;; (error "Cannot use " v 'as (te/lookup (cj/te body-tf) v)) ;; (let ((cast-exp (make-cast `(fn (: ,v ,type) ,(cj/exp body-tf)) ;; `(-> ,type ,(cj/type body-tf))))) ;; (make-cj (te/merge (te/remove new-te v) te) cast-exp `(-> ,type ,(cj/type body-tf)))))))) ((fn (: ,v ,type) (: ,ret-type) ,body) (let* ((new-te (te/extend (te/copy te) v type)) (body-tf (transform body new-te)) (co-domain-type (cj/type body-tf))) (if (~ co-domain-type ret-type) (let ((cast-exp (make-cast `(fn (: ,v ,type) (: ,ret-type) ,(cj/exp body-tf)) `(-> ,type ,ret-type)))) (make-cj (te/merge (te/remove new-te v) te) cast-exp `(-> ,type ,ret-type))) (error "TypeError : " 'expected ret-type 'got co-domain-type 'for body)))) ((fn ((: ,v ,type) . ,res) ,body) (let* ((bindings (map (lambda (x) (cons (cast/exp x) (cast/type x))) res)) (new-te (te/merge (te/copy te) (alist->te (cons (cons v type) bindings)))) (body-tf (transform body new-te)) (co-domain-type (cj/type body-tf)) (cast-exp (make-cast `(fn ((: ,v ,type) ,@res) ,(cj/exp body-tf)) `(-> ,(list->pair-type (map (lambda (x) (cast/type x)) (cons `(: ,v ,type) res))) ,co-domain-type)))) (make-cj (te/merge te (te/nremove new-te (map (lambda (x) (car x)) (cons (cons v type) bindings)))) cast-exp (cast/type cast-exp)))) ((defn (: ,name ,type) (,arg1 . ,args) ,body) ( display " DEFN " ) ;; (newline) (if (not (arrow-type? type)) (error "TypeError: " name 'should 'be 'a 'function 'type) (if (pair-type? (domain type)) (if (not (equal? (pair-arity (domain type)) (length `(,arg1 ,@args)))) (error "TypeError: " 'expected (pair-arity (domain type)) 'arguments 'for name '- 'got (length `(,arg1 ,@args))) (let* ( ;; (bindings (map (lambda (x y) (cons (cdr (domain type)) ` ( arg1 , @args ) ) ) ) ) (new-te (te/nextend te `(,arg1 ,@args) (cdr (domain type)))) ;; (throw ( begin ( display " * te : " ) ( display ( te->alist new - te ) ) ( newline ) 3 ) ) (body-tf (transform body (te/extend new-te name type))) (cast-exp (make-cast `(defn (: ,name ,type) (,arg1 ,@args) ,(cj/exp body-tf)) 'unit)) ( ;; (begin (display "CAST-EXP: ") (display cast-exp) (newline) ;; (display "BODY-TF-TYPE: ") (display (cj/type body-tf)) (newline) ( display " * * * * * * * * * * * * * * " ) ( newline ) 3 ) ) ) (if (~ (cj/type body-tf) (co-domain type)) (make-tj (te/merge (te/extend te name type) (te/nremove new-te `(,arg1 ,@args))) cast-exp 'unit) (error "TypeError: " 'inconsistent 'return 'type 'in 'defn name)))) ;; if not a pair type (if (not (null? args)) (error "TypeError: " 'expected 1 'argument 'for name '- 'got (length `(,arg1 ,@args))) (let* ((new-te (te/nextend te (list name arg1) (list type (domain type)))) (body-tf (transform body new-te)) (cast-exp (make-cast `(defn (: ,name ,type) (,arg1) ,(cj/exp body-tf)) 'unit))) (if (~ (cj/type body-tf) (co-domain type)) (make-tj (te/merge te (te/remove new-te arg1)) cast-exp 'unit) (error "TypeError: " 'inconsistent 'return 'type 'in 'defn name))))))) ((fn ((: ,v ,type) . ,res) (: ,ret-type) ,body) (let* ((e-tf (transform `(fn ((: ,v ,type) . ,res) ,body) te)) (co-domain-type (cj/type e-tf))) (if (~ co-domain-type ret-type) (let ((rt `(-> ,(list->pair-type (map (lambda (x) (cast/type x)) (cons `(: ,v ,type) res))) ,ret-type))) (make-cj (cj/te e-tf) (make-cast (uncast (cj/exp e-tf)) rt) rt)) (error "TypeError : " 'expected ret-type 'got co-domain-type)))) function with arity 1 (let* ((rator-tf (transform rator te)) ; a cast judgement (cj) object (rand-tf (transform rand te)) (rator-type (cj/type rator-tf)) (rand-type (cj/type rand-tf))) ;; (display "Rator TE: ") ( display ( te->alist ( cj / ) ) ) ;; (newline) ;; (display "Rand TE: ") ;; (display (te->alist (cj/te rand-tf))) (newline) (if (any-type? rator-type) (let ((new-te (te/merge (cj/te rand-tf) (te/extend (cj/te rator-tf) rator `(-> ,rand-type any)))) (cast-exp (make-cast (list (make-cast (uncast (cj/exp rator-tf)) `(-> ,rand-type any)) (cj/exp rand-tf)) 'any))) ;; (display "Final TE: ") ;; (display (te->alist new-te)) (newline) (make-cj new-te cast-exp 'any)) (if (arrow-type? rator-type) (if (equal? (domain rator-type) rand-type) (let ((new-te (te/merge (cj/te rator-tf) (cj/te rand-tf))) (cast-exp (make-cast (list (cj/exp rator-tf) (cj/exp rand-tf)) (co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (if (and (~ (domain rator-type) rand-type) (not (any-type? rand-type))) ;; (~ (domain rator-type) rand-type) (let ((new-te (te/merge (cj/te rator-tf) (cj/te rand-tf) ;; (te/extend (cj/te rand-tf) ;; rand (domain rator-type)) )) (cast-exp (make-cast (list (cj/exp rator-tf) (make-cast (uncast (cj/exp rand-tf)) (domain rator-type))) (co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (error "TypeError : " 'expected (domain rator-type) 'got rand-type 'for rand))) (error "TypeError : " rator 'must 'be 'a 'function))))) ((,rator . ,rands) (let* ((rator-tf (transform rator te)) (rator-type (cj/type rator-tf)) (rand-tf (map (lambda (e) (transform e te)) rands)) (rand-cast (map (lambda (e) (cj/exp e)) rand-tf)) (rand-type (list->pair-type (fold-right (lambda (x acc) (cons (cj/type x) acc)) '() rand-tf)))) ;; (display "Rand type ") ;; (display rand-type) ;; (newline) ;; (display "Rator type ") ;; (display rator-type) (newline) (if (any-type? rator-type) (let* ((new-te (te/nmerge (append (list (te/extend (cj/te rator-tf) rator `(-> ,rand-type any))) (map (lambda (x) (cj/te x)) rand-tf)))) (cast-exp (make-cast `((: ,rator (-> ,rand-type any)) ,@rand-cast) 'any))) (make-cj new-te cast-exp 'any)) (if (arrow-type? rator-type) (if (or (equal? (domain rator-type) rand-type) (and (equal? (arity rator-type) 'n) (equal? (domain rator-type) (cadr rand-type)) (all-equal? (cdr rand-type)))) (let* ((new-te (te/nmerge (append (list (cj/te rator-tf)) (map (lambda (x) (cj/te x)) rand-tf)))) (cast-exp `(: (,(cj/exp rator-tf) ,@rand-cast) ,(co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (if (or (~ (domain rator-type) rand-type) (and (equal? (arity rator-type) 'n) (~ (domain rator-type) (cadr rand-type)) (all-equal? (cdr rand-type)))) (let* ( ;; (rc (map (lambda (x y) (make-cast (uncast x) y)) ;; rand-cast ;; (if (pair? (domain rator-type)) ;; (cdr (domain rator-type)) ;; (domain rator-type)))) (rc (if (pair? (domain rator-type)) (map (lambda (x y) (make-cast (uncast x) y)) rand-cast (cdr (domain rator-type))) (map (lambda (x) (make-cast (uncast x) (domain rator-type))) rand-cast))) ;; (rc-te (map (lambda (x y z) (te/extend (cj/te x) y z)) ;; rand-tf rands (cdr (domain rator-type)))) (rc-te (if (pair? (domain rator-type)) (map (lambda (x y z) (te/extend (cj/te x) y z)) rand-tf rands (cdr (domain rator-type))) (map (lambda (x y) (te/extend (cj/te x) y (domain rator-type))) rand-tf rands))) (new-te (te/nmerge (append (list (cj/te rator-tf)) rc-te))) (cast-exp `(: (,(cj/exp rator-tf) ,@rc) ,(co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (begin ;; (display rand-type) ;; (newline) ;; (display rator-type) (error "TypeError: " 'inconsistent 'argument 'types 'for rator)))) (error "TypeError: " rator 'must 'be 'a 'function))))) (else (error "TRANSFORM -- Unknown type for --" exp)))) (define (c exp alis) (let ((res (transform exp (alist->te alis)))) (display (cj/exp res)) (newline) (display "Γ = ") (display (te->alist (cj/te res))) (display " => ") (display exp) (display " : ") (display (cj/type res)) (newline) res)) ;; Typing Judgements (define-structure (tj) te exp type) (define tj/te tj-te) (define tj/exp tj-exp) (define tj/type tj-type) (define (check expr tenv) (define (tc exp type te) (pmatch exp ((: ,e ,t) (guard (and (~ type t) (not (equal? type t)))) ;; (display "Casting ") ;; (display e) (display " from ") (display t) (display " to ") ;; (display type) ;; (newline) (tc `(: ,e ,type) type te)) ((: ,e ,t) (guard (symbol? e)) (let ((binding (te/lookup te e))) (if binding (if (~ binding type) ;; (make-tj (te/extend te e type) exp binding) (make-tj te exp binding) (error "TypeError: " 'expected binding 'got type 'for e)) ;; The part below never actually runs (?) need to test a bit more. (make-tj (te/extend e t) exp t)))) ((: (defvar (: ,v ,s) ,val) ,t) (let* ((tc-val (tc val s te))) (if (~ (tj/type tc-val) s) (let ((new-te (te/merge (tj/te tc-val) (te/extend te v s)))) (make-tj new-te exp t)) (error "TypeError: " 'value 'type (tj/type tc-val) 'is 'not 'consistent 'with s)))) ((: (pair ,x ,y) ,t) (let* ((tc-x (tc x (cadr t) te)) (tc-y (tc y (caddr t) te)) (new-te (te/merge (tj/te tc-x) (tj/te tc-y)))) (make-tj (te/merge te new-te) exp t))) ((: (listof (: ,s) . ,items) ,t) (if (null? items) (make-tj te exp t) (let* ((tc-items (map (lambda (e) (tc e s te)) items)) ;; (items-te (te/nmerge (map (lambda (e) (te/extend (tj/te e) ;; (cast/exp (tj/exp e)) ;; s)) tc-items))) (items-te (te/nmerge (map (lambda (e) (tj/te e)) tc-items))) (new-te (te/merge te items-te))) (make-tj new-te exp t)))) ((: (if ,pred ,clause1 ,clause2) ,t) (let* ((tc-pred (tc pred 'boolean te)) (tc-clause1 (tc clause1 type te)) (tc-clause2 (tc clause2 type te)) (new-te (te/nmerge (map (lambda (e) (tj/te e)) (list tc-pred tc-clause1 tc-clause2))))) (make-tj (te/merge te new-te) exp t))) ((: (defn (: ,v ,s) (,arg1 . ,args) ,body) ,t) ( display ( length ` ( , arg1 , @args ) ) ) ;; (newline) (if (pair-type? (domain s)) (let* ((new-te (te/extend (te/nextend te `(,arg1 ,@args) (cdr (domain s))) v s)) (tc-body (tc body (co-domain s) new-te))) (if (~ (tj/type tc-body) (co-domain s)) (make-tj new-te exp t) (error "TypeError: " 'inconsistent 'function 'body 'in v))) (let* ((new-te (te/extend te arg1 (domain s))) (tc-body (tc body (co-domain s) (te/extend new-te v s)))) (if (~ (tj/type tc-body) (co-domain s)) (make-tj new-te exp t) (error "TypeError: " 'inconsistent 'function 'body 'in v))))) ((: (fn (: ,v ,s) ,body) ,t) ;; check consistency with t? (let ((tc-body (tc body (co-domain type) (te/extend (te/copy te) v s)))) (if (~ (tj/type tc-body) (co-domain type)) (make-tj (te/remove (tj/te tc-body) v) exp t) (error "TypeError: " 'expected (co-domain type) 'got (tj/type tc-body) 'for body)))) ((: (fn (: ,v ,s) (: ,ret) ,body) ,t) (let ((tc-body (tc body (co-domain type) (te/extend (te/copy te) v s)))) (if (~ (tj/type tc-body) ret) (make-tj (te/remove (tj/te tc-body) v) exp t) (error "TypeError: " 'expected (co-domain type) 'got (tj/type tc-body) 'for body)))) ((: (,rator ,rand) ,t) (let* ( ;; (tc-rator (tc rator `(-> ,(cast/type rand) ,type) te)) (tc-rator (tc rator (cast/type rator) te)) (tc-rand (tc rand (domain (cast/type rator)) te)) (new-te (te/merge (tj/te tc-rator) (tj/te tc-rand)))) (make-tj new-te exp t))) ((: (,rator . ,rands) ,t) (let* ((tc-rator (tc rator (cast/type rator) te)) ;; Check each rand (tc-rands (map (lambda (e) (tc e (cast/type e) te)) rands)) (rands-te (te/nmerge (map (lambda (e) (tj/te e)) tc-rands))) (new-te (te/merge (tj/te tc-rator) rands-te))) (make-tj new-te exp t))) ((: ,e char) (guard (char? e)) (make-tj te exp 'char)) ((: ,e boolean) (guard (boolean? e)) (make-tj te exp 'boolean)) ((: ,e string) (guard (string? e)) (make-tj te exp 'string)) ((: ,e number) (guard (number? e)) (make-tj te exp 'number)) ((: ,e any) (make-tj te exp 'any)) (else (error "Unknown type for --" exp)))) (let ((c (transform expr ;; (alist->te tenv) tenv))) (tc (cj/exp c) (cj/type c) (cj/te c)))) (define (t exp te) (let ((res (check exp (alist->te te)))) ;; (display (tj/exp res)) ;; (newline) (display "Γ{") (display (te->alist (tj/te res))) (display "} ⊦ ") (display exp) (display " : ") (display (tj/type res)) (newline) res))
null
https://raw.githubusercontent.com/khayyamsaleem/gradual-typing/f647f4852addeb559264190de66daa81dc1f4891/caster.scm
scheme
Cast Syntactic Extensions Can we avoid the use of eval here? Helpers Type environments are hash tables now Cast Judgements / is more readable than - at times Dealing with casts Returns a cast judgement te/lookup returns #f if e not bound (and (~ type (car items-types)) (all-equal? items-types)) (new-te (te/nmerge (map (lambda (e) (te/extend (cj/te e) (uncast (cj/exp e)) type)) items-tf))) (equal? (cj/type clause1-tf) (cj/type clause2-tf)) ((fn (: ,v ,type) ,body) (let* ((new-te (te/extend (te/copy te) v type)) (body-tf (transform body new-te))) (begin (display "Type of ") (display v) (display " in body : ") (display (te/lookup (cj/te body-tf) v)) (newline) (if (not (equal? (te/lookup (cj/te body-tf) v) type)) (error "Cannot use " v 'as (te/lookup (cj/te body-tf) v)) (let ((cast-exp (make-cast `(fn (: ,v ,type) ,(cj/exp body-tf)) `(-> ,type ,(cj/type body-tf))))) (make-cj (te/merge (te/remove new-te v) te) cast-exp `(-> ,type ,(cj/type body-tf)))))))) (newline) (bindings (map (lambda (x y) (cons (cdr (domain type)) (throw (begin (display "CAST-EXP: ") (display cast-exp) (newline) (display "BODY-TF-TYPE: ") (display (cj/type body-tf)) (newline) if not a pair type a cast judgement (cj) object (display "Rator TE: ") (newline) (display "Rand TE: ") (display (te->alist (cj/te rand-tf))) (newline) (display "Final TE: ") (display (te->alist new-te)) (newline) (~ (domain rator-type) rand-type) (te/extend (cj/te rand-tf) rand (domain rator-type)) (display "Rand type ") (display rand-type) (newline) (display "Rator type ") (display rator-type) (newline) (rc (map (lambda (x y) (make-cast (uncast x) y)) rand-cast (if (pair? (domain rator-type)) (cdr (domain rator-type)) (domain rator-type)))) (rc-te (map (lambda (x y z) (te/extend (cj/te x) y z)) rand-tf rands (cdr (domain rator-type)))) (display rand-type) (newline) (display rator-type) Typing Judgements (display "Casting ") (display e) (display " from ") (display t) (display " to ") (display type) (newline) (make-tj (te/extend te e type) exp binding) The part below never actually runs (?) need to test a bit more. (items-te (te/nmerge (map (lambda (e) (te/extend (tj/te e) (cast/exp (tj/exp e)) s)) tc-items))) (newline) check consistency with t? (tc-rator (tc rator `(-> ,(cast/type rand) ,type) te)) Check each rand (alist->te tenv) (display (tj/exp res)) (newline)
(load "pmatch.scm") (load "types.scm") (define-syntax fn-erase (syntax-rules (:) ((_ (: v type)) '(v)) ((_ ((: v type) v2 ...)) `(v ,@(fn-erase v2 ...))))) (define-syntax fn (syntax-rules (:) ((_ (: v type) (: return) body ...) (lambda (v) body ...)) ((_ (: v type) body ...) (lambda (v) body ...)) ((_ ((: v type) v2 ...) (: return) body ...) (fn ((: v type) v2 ...) body ...)) ((_ ((: v type) v2 ...) body ...) (let ((env (the-environment))) (eval `(lambda ,(fn-erase ((: v type) v2 ...)) body ...) env))) ((_ () body ...) (lambda () body ...)))) (define-syntax listof (syntax-rules (:) ((_ (: type) . items) (quote items)))) (define (all-equal? ls) (or (or (null? ls) (null? (cdr ls))) (and (equal? (car ls) (cadr ls)) (all-equal? (cdr ls))))) (define (te/new) (make-hash-table)) (define (te/lookup te var) (hash-table/get te var #f)) (define (te/extend te var type) (hash-table/put! te var type) te) (define (te/nextend te vars types) (for-each (lambda (k v) (hash-table/put! te k v)) vars types) te) (define (te/remove te var) (hash-table/remove! te var) te) (define (te/nremove te vars) (for-each (lambda (v) (te/remove te v)) vars) te) (define (te/merge te1 te2) (define (put-func h1 h2) (hash-table/for-each h2 (lambda (k v) (hash-table/put! h1 k v)))) (let ((te (te/new))) (put-func te te1) (put-func te te2) te)) (define (te/nmerge tes) (fold-left (lambda (acc x) (te/merge acc x)) (car tes) tes)) (define (te/copy te) (let ((te-copy (te/new))) (hash-table/for-each te (lambda (k v) (hash-table/put! te-copy k v))) te-copy)) (define te->alist hash-table->alist) (define (alist->te alist) (let ((te (te/new))) (for-each (lambda (e) (hash-table/put! te (car e) (cdr e))) alist) te)) (define-structure (cj) te exp type) (define cj/te cj-te) (define cj/exp cj-exp) (define cj/type cj-type) (define (cast? exp) (and (pair? exp) (eq? (car exp) ':))) (define (make-cast exp type) `(: ,exp ,type)) (define (uncast exp) (and (cast? exp) (cadr exp))) (define cast/exp uncast) (define (cast/type exp) (and (cast? exp) (caddr exp))) Transform to intermediate langugae (define (transform exp te) (pmatch exp (,e (guard (number? e)) (make-cj te (make-cast e 'number) 'number)) (,e (guard (string? e)) (make-cj te (make-cast e 'string) 'string)) (,e (guard (boolean? e)) (make-cj te (make-cast e 'boolean) 'boolean)) (,e (guard (char? e)) (make-cj te (make-cast e 'char) 'char)) (,e (guard (symbol? e)) (if binding (make-cj te (make-cast e binding) binding) (make-cj (te/extend te e 'any) (make-cast e 'any) 'any)))) ((pair ,x ,y) (let* ((x-tf (transform x te)) (y-tf (transform y te)) (new-te (te/nmerge (list te (cj/te x-tf) (cj/te y-tf))))) (make-cj te (make-cast `(pair ,(cj/exp x-tf) ,(cj/exp y-tf)) (make-pair-type (cj/type x-tf) (cj/type y-tf))) (make-pair-type (cj/type x-tf) (cj/type y-tf))))) ((listof (: ,type) . ,items) (if (null? items) (make-cj te (make-cast `(listof (: ,type)) (make-list-type type)) (make-list-type type)) (let* ((items-tf (map (lambda (e) (transform e te)) items)) (items-types (map (lambda (e) (cj/type e)) items-tf)) (items-cast (map (lambda (e) (cj/exp e)) items-tf))) (~ type (car items-types)) (new-te (te/nmerge (map (lambda (e) (cj/te e)) items-tf))) (cast-items (map (lambda (e) (make-cast (uncast e) type)) items-cast)) (cast-exp (make-cast `(listof (: ,type) ,@cast-items) (make-list-type type)))) (make-cj (te/merge new-te te) cast-exp (make-list-type type))) (error "TypeError: " 'list 'elements 'should 'type 'consistent))))) ((defvar (: ,var ,type) ,val) (let ((val-tf (transform val te))) (if (~ (cj/type val-tf) type) (make-cj (te/merge (cj/te val-tf) (te/extend te var type)) (make-cast `(defvar (: ,var ,type) ,(cj/exp val-tf)) 'unit) 'unit) (error "TypeError: " 'expected type 'in 'defvar var 'but 'got (cj/type val-tf))))) ((if ,pred ,clause1 ,clause2) (let ((pred-tf (transform pred te))) (if (equal? (cj/type pred-tf) 'boolean) (let* ((clause1-tf (transform clause1 te)) (clause2-tf (transform clause2 te))) (~ (cj/type clause1-tf) (cj/type clause2-tf)) (let ((new-te (te/nmerge (map (lambda (e) (cj/te e)) (list pred-tf clause1-tf clause2-tf)))) (cast-exp (make-cast `(if ,(cj/exp pred-tf) ,(cj/exp clause1-tf) ,(cj/exp clause2-tf)) (cj/type clause1-tf)))) (make-cj (te/merge new-te te) cast-exp (cj/type clause1-tf))) (error "TypeError: " 'if 'branches 'should 'have 'consistent 'type '- 'got (cj/type clause1-tf) 'and (cj/type clause2-tf)))) (error "TypeError: " pred 'should 'be 'a 'boolean '- 'got (cj/type pred-tf))))) ((fn (: ,v ,type) ,body) (let* ((new-te (te/extend (te/copy te) v type)) (body-tf (transform body new-te)) (cast-exp (make-cast `(fn (: ,v ,type) ,(cj/exp body-tf)) `(-> ,type ,(cj/type body-tf))))) (make-cj (te/merge (te/remove new-te v) te) cast-exp `(-> ,type ,(cj/type body-tf))))) ((fn (: ,v ,type) (: ,ret-type) ,body) (let* ((new-te (te/extend (te/copy te) v type)) (body-tf (transform body new-te)) (co-domain-type (cj/type body-tf))) (if (~ co-domain-type ret-type) (let ((cast-exp (make-cast `(fn (: ,v ,type) (: ,ret-type) ,(cj/exp body-tf)) `(-> ,type ,ret-type)))) (make-cj (te/merge (te/remove new-te v) te) cast-exp `(-> ,type ,ret-type))) (error "TypeError : " 'expected ret-type 'got co-domain-type 'for body)))) ((fn ((: ,v ,type) . ,res) ,body) (let* ((bindings (map (lambda (x) (cons (cast/exp x) (cast/type x))) res)) (new-te (te/merge (te/copy te) (alist->te (cons (cons v type) bindings)))) (body-tf (transform body new-te)) (co-domain-type (cj/type body-tf)) (cast-exp (make-cast `(fn ((: ,v ,type) ,@res) ,(cj/exp body-tf)) `(-> ,(list->pair-type (map (lambda (x) (cast/type x)) (cons `(: ,v ,type) res))) ,co-domain-type)))) (make-cj (te/merge te (te/nremove new-te (map (lambda (x) (car x)) (cons (cons v type) bindings)))) cast-exp (cast/type cast-exp)))) ((defn (: ,name ,type) (,arg1 . ,args) ,body) ( display " DEFN " ) (if (not (arrow-type? type)) (error "TypeError: " name 'should 'be 'a 'function 'type) (if (pair-type? (domain type)) (if (not (equal? (pair-arity (domain type)) (length `(,arg1 ,@args)))) (error "TypeError: " 'expected (pair-arity (domain type)) 'arguments 'for name '- 'got (length `(,arg1 ,@args))) ` ( arg1 , @args ) ) ) ) ) (new-te (te/nextend te `(,arg1 ,@args) (cdr (domain type)))) ( begin ( display " * te : " ) ( display ( te->alist new - te ) ) ( newline ) 3 ) ) (body-tf (transform body (te/extend new-te name type))) (cast-exp (make-cast `(defn (: ,name ,type) (,arg1 ,@args) ,(cj/exp body-tf)) 'unit)) ( ( display " * * * * * * * * * * * * * * " ) ( newline ) 3 ) ) ) (if (~ (cj/type body-tf) (co-domain type)) (make-tj (te/merge (te/extend te name type) (te/nremove new-te `(,arg1 ,@args))) cast-exp 'unit) (error "TypeError: " 'inconsistent 'return 'type 'in 'defn name)))) (if (not (null? args)) (error "TypeError: " 'expected 1 'argument 'for name '- 'got (length `(,arg1 ,@args))) (let* ((new-te (te/nextend te (list name arg1) (list type (domain type)))) (body-tf (transform body new-te)) (cast-exp (make-cast `(defn (: ,name ,type) (,arg1) ,(cj/exp body-tf)) 'unit))) (if (~ (cj/type body-tf) (co-domain type)) (make-tj (te/merge te (te/remove new-te arg1)) cast-exp 'unit) (error "TypeError: " 'inconsistent 'return 'type 'in 'defn name))))))) ((fn ((: ,v ,type) . ,res) (: ,ret-type) ,body) (let* ((e-tf (transform `(fn ((: ,v ,type) . ,res) ,body) te)) (co-domain-type (cj/type e-tf))) (if (~ co-domain-type ret-type) (let ((rt `(-> ,(list->pair-type (map (lambda (x) (cast/type x)) (cons `(: ,v ,type) res))) ,ret-type))) (make-cj (cj/te e-tf) (make-cast (uncast (cj/exp e-tf)) rt) rt)) (error "TypeError : " 'expected ret-type 'got co-domain-type)))) function with arity 1 (rand-tf (transform rand te)) (rator-type (cj/type rator-tf)) (rand-type (cj/type rand-tf))) ( display ( te->alist ( cj / ) ) ) (if (any-type? rator-type) (let ((new-te (te/merge (cj/te rand-tf) (te/extend (cj/te rator-tf) rator `(-> ,rand-type any)))) (cast-exp (make-cast (list (make-cast (uncast (cj/exp rator-tf)) `(-> ,rand-type any)) (cj/exp rand-tf)) 'any))) (make-cj new-te cast-exp 'any)) (if (arrow-type? rator-type) (if (equal? (domain rator-type) rand-type) (let ((new-te (te/merge (cj/te rator-tf) (cj/te rand-tf))) (cast-exp (make-cast (list (cj/exp rator-tf) (cj/exp rand-tf)) (co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (if (and (~ (domain rator-type) rand-type) (not (any-type? rand-type))) (let ((new-te (te/merge (cj/te rator-tf) (cj/te rand-tf) )) (cast-exp (make-cast (list (cj/exp rator-tf) (make-cast (uncast (cj/exp rand-tf)) (domain rator-type))) (co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (error "TypeError : " 'expected (domain rator-type) 'got rand-type 'for rand))) (error "TypeError : " rator 'must 'be 'a 'function))))) ((,rator . ,rands) (let* ((rator-tf (transform rator te)) (rator-type (cj/type rator-tf)) (rand-tf (map (lambda (e) (transform e te)) rands)) (rand-cast (map (lambda (e) (cj/exp e)) rand-tf)) (rand-type (list->pair-type (fold-right (lambda (x acc) (cons (cj/type x) acc)) '() rand-tf)))) (if (any-type? rator-type) (let* ((new-te (te/nmerge (append (list (te/extend (cj/te rator-tf) rator `(-> ,rand-type any))) (map (lambda (x) (cj/te x)) rand-tf)))) (cast-exp (make-cast `((: ,rator (-> ,rand-type any)) ,@rand-cast) 'any))) (make-cj new-te cast-exp 'any)) (if (arrow-type? rator-type) (if (or (equal? (domain rator-type) rand-type) (and (equal? (arity rator-type) 'n) (equal? (domain rator-type) (cadr rand-type)) (all-equal? (cdr rand-type)))) (let* ((new-te (te/nmerge (append (list (cj/te rator-tf)) (map (lambda (x) (cj/te x)) rand-tf)))) (cast-exp `(: (,(cj/exp rator-tf) ,@rand-cast) ,(co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (if (or (~ (domain rator-type) rand-type) (and (equal? (arity rator-type) 'n) (~ (domain rator-type) (cadr rand-type)) (all-equal? (cdr rand-type)))) (rc (if (pair? (domain rator-type)) (map (lambda (x y) (make-cast (uncast x) y)) rand-cast (cdr (domain rator-type))) (map (lambda (x) (make-cast (uncast x) (domain rator-type))) rand-cast))) (rc-te (if (pair? (domain rator-type)) (map (lambda (x y z) (te/extend (cj/te x) y z)) rand-tf rands (cdr (domain rator-type))) (map (lambda (x y) (te/extend (cj/te x) y (domain rator-type))) rand-tf rands))) (new-te (te/nmerge (append (list (cj/te rator-tf)) rc-te))) (cast-exp `(: (,(cj/exp rator-tf) ,@rc) ,(co-domain rator-type)))) (make-cj new-te cast-exp (co-domain rator-type))) (error "TypeError: " 'inconsistent 'argument 'types 'for rator)))) (error "TypeError: " rator 'must 'be 'a 'function))))) (else (error "TRANSFORM -- Unknown type for --" exp)))) (define (c exp alis) (let ((res (transform exp (alist->te alis)))) (display (cj/exp res)) (newline) (display "Γ = ") (display (te->alist (cj/te res))) (display " => ") (display exp) (display " : ") (display (cj/type res)) (newline) res)) (define-structure (tj) te exp type) (define tj/te tj-te) (define tj/exp tj-exp) (define tj/type tj-type) (define (check expr tenv) (define (tc exp type te) (pmatch exp ((: ,e ,t) (guard (and (~ type t) (not (equal? type t)))) (tc `(: ,e ,type) type te)) ((: ,e ,t) (guard (symbol? e)) (let ((binding (te/lookup te e))) (if binding (if (~ binding type) (make-tj te exp binding) (error "TypeError: " 'expected binding 'got type 'for e)) (make-tj (te/extend e t) exp t)))) ((: (defvar (: ,v ,s) ,val) ,t) (let* ((tc-val (tc val s te))) (if (~ (tj/type tc-val) s) (let ((new-te (te/merge (tj/te tc-val) (te/extend te v s)))) (make-tj new-te exp t)) (error "TypeError: " 'value 'type (tj/type tc-val) 'is 'not 'consistent 'with s)))) ((: (pair ,x ,y) ,t) (let* ((tc-x (tc x (cadr t) te)) (tc-y (tc y (caddr t) te)) (new-te (te/merge (tj/te tc-x) (tj/te tc-y)))) (make-tj (te/merge te new-te) exp t))) ((: (listof (: ,s) . ,items) ,t) (if (null? items) (make-tj te exp t) (let* ((tc-items (map (lambda (e) (tc e s te)) items)) (items-te (te/nmerge (map (lambda (e) (tj/te e)) tc-items))) (new-te (te/merge te items-te))) (make-tj new-te exp t)))) ((: (if ,pred ,clause1 ,clause2) ,t) (let* ((tc-pred (tc pred 'boolean te)) (tc-clause1 (tc clause1 type te)) (tc-clause2 (tc clause2 type te)) (new-te (te/nmerge (map (lambda (e) (tj/te e)) (list tc-pred tc-clause1 tc-clause2))))) (make-tj (te/merge te new-te) exp t))) ((: (defn (: ,v ,s) (,arg1 . ,args) ,body) ,t) ( display ( length ` ( , arg1 , @args ) ) ) (if (pair-type? (domain s)) (let* ((new-te (te/extend (te/nextend te `(,arg1 ,@args) (cdr (domain s))) v s)) (tc-body (tc body (co-domain s) new-te))) (if (~ (tj/type tc-body) (co-domain s)) (make-tj new-te exp t) (error "TypeError: " 'inconsistent 'function 'body 'in v))) (let* ((new-te (te/extend te arg1 (domain s))) (tc-body (tc body (co-domain s) (te/extend new-te v s)))) (if (~ (tj/type tc-body) (co-domain s)) (make-tj new-te exp t) (error "TypeError: " 'inconsistent 'function 'body 'in v))))) ((: (fn (: ,v ,s) ,body) ,t) (let ((tc-body (tc body (co-domain type) (te/extend (te/copy te) v s)))) (if (~ (tj/type tc-body) (co-domain type)) (make-tj (te/remove (tj/te tc-body) v) exp t) (error "TypeError: " 'expected (co-domain type) 'got (tj/type tc-body) 'for body)))) ((: (fn (: ,v ,s) (: ,ret) ,body) ,t) (let ((tc-body (tc body (co-domain type) (te/extend (te/copy te) v s)))) (if (~ (tj/type tc-body) ret) (make-tj (te/remove (tj/te tc-body) v) exp t) (error "TypeError: " 'expected (co-domain type) 'got (tj/type tc-body) 'for body)))) ((: (,rator ,rand) ,t) (tc-rator (tc rator (cast/type rator) te)) (tc-rand (tc rand (domain (cast/type rator)) te)) (new-te (te/merge (tj/te tc-rator) (tj/te tc-rand)))) (make-tj new-te exp t))) ((: (,rator . ,rands) ,t) (let* ((tc-rator (tc rator (cast/type rator) te)) (tc-rands (map (lambda (e) (tc e (cast/type e) te)) rands)) (rands-te (te/nmerge (map (lambda (e) (tj/te e)) tc-rands))) (new-te (te/merge (tj/te tc-rator) rands-te))) (make-tj new-te exp t))) ((: ,e char) (guard (char? e)) (make-tj te exp 'char)) ((: ,e boolean) (guard (boolean? e)) (make-tj te exp 'boolean)) ((: ,e string) (guard (string? e)) (make-tj te exp 'string)) ((: ,e number) (guard (number? e)) (make-tj te exp 'number)) ((: ,e any) (make-tj te exp 'any)) (else (error "Unknown type for --" exp)))) tenv))) (tc (cj/exp c) (cj/type c) (cj/te c)))) (define (t exp te) (let ((res (check exp (alist->te te)))) (display "Γ{") (display (te->alist (tj/te res))) (display "} ⊦ ") (display exp) (display " : ") (display (tj/type res)) (newline) res))
6ebba57d918096eac6cb91064ba4615f0a755e6a95d5da2fcb75dfa188bfaefc
arttuka/reagent-material-ui
on_device_training_rounded.cljs
(ns reagent-mui.icons.on-device-training-rounded "Imports @mui/icons-material/OnDeviceTrainingRounded as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def on-device-training-rounded (create-svg-icon [(e "path" #js {"d" "M11.5 17h1c.28 0 .5-.22.5-.5s-.22-.5-.5-.5h-1c-.28 0-.5.22-.5.5s.22.5.5.5zm.02-5.94c-.71.16-1.29.74-1.46 1.44-.23.94.21 1.8.94 2.22v.53c0 .14.11.25.25.25h1.5c.14 0 .25-.11.25-.25v-.53c.6-.35 1-.98 1-1.72 0-1.26-1.17-2.25-2.48-1.94z"}) (e "path" #js {"d" "M18 1.01 6 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM18 18H6V6h12v12z"}) (e "path" #js {"d" "M15.33 15.27c.36.36.99.26 1.21-.2.29-.63.46-1.33.46-2.07s-.17-1.44-.46-2.07c-.22-.47-.84-.57-1.21-.2-.22.22-.28.56-.15.84.2.44.31.92.31 1.43s-.11.99-.31 1.43c-.12.29-.07.62.15.84zm-6.66 0c.22-.22.28-.56.15-.84-.21-.44-.32-.92-.32-1.43 0-1.93 1.57-3.5 3.5-3.5v.69c0 .22.25.33.42.19l1.62-1.44c.11-.1.11-.27 0-.37l-1.62-1.44c-.17-.15-.42-.04-.42.18V8c-2.76 0-5 2.24-5 5 0 .74.17 1.44.46 2.07.22.47.84.57 1.21.2z"})] "OnDeviceTrainingRounded"))
null
https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/on_device_training_rounded.cljs
clojure
(ns reagent-mui.icons.on-device-training-rounded "Imports @mui/icons-material/OnDeviceTrainingRounded as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def on-device-training-rounded (create-svg-icon [(e "path" #js {"d" "M11.5 17h1c.28 0 .5-.22.5-.5s-.22-.5-.5-.5h-1c-.28 0-.5.22-.5.5s.22.5.5.5zm.02-5.94c-.71.16-1.29.74-1.46 1.44-.23.94.21 1.8.94 2.22v.53c0 .14.11.25.25.25h1.5c.14 0 .25-.11.25-.25v-.53c.6-.35 1-.98 1-1.72 0-1.26-1.17-2.25-2.48-1.94z"}) (e "path" #js {"d" "M18 1.01 6 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM18 18H6V6h12v12z"}) (e "path" #js {"d" "M15.33 15.27c.36.36.99.26 1.21-.2.29-.63.46-1.33.46-2.07s-.17-1.44-.46-2.07c-.22-.47-.84-.57-1.21-.2-.22.22-.28.56-.15.84.2.44.31.92.31 1.43s-.11.99-.31 1.43c-.12.29-.07.62.15.84zm-6.66 0c.22-.22.28-.56.15-.84-.21-.44-.32-.92-.32-1.43 0-1.93 1.57-3.5 3.5-3.5v.69c0 .22.25.33.42.19l1.62-1.44c.11-.1.11-.27 0-.37l-1.62-1.44c-.17-.15-.42-.04-.42.18V8c-2.76 0-5 2.24-5 5 0 .74.17 1.44.46 2.07.22.47.84.57 1.21.2z"})] "OnDeviceTrainingRounded"))
541cf07e9d691ab2bf4725bdff85b37986743bc59cd5d3b007811071560c14c0
bgusach/exercises-htdp2e
ex-249.rkt
#lang htdp/isl (define (f x) x) (cons f '()) (f f) (cons f (cons 10 (cons (f 10) '())))
null
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/3-abstraction/ex-249.rkt
racket
#lang htdp/isl (define (f x) x) (cons f '()) (f f) (cons f (cons 10 (cons (f 10) '())))
c248980620bbca79a42ee80953664b889eeb7abb2918ccc5e1db5c01cec2905e
nominolo/lambdachine
UnpackCString.hs
# LANGUAGE MagicHash , NoImplicitPrelude , UnboxedTuples , BangPatterns # module Bc.UnpackCString where import GHC.Base import GHC.List test = length "foobarbarbeonuhnsaoehunsaoheunsoanuehaonsu" == 42
null
https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/tests/Bc/UnpackCString.hs
haskell
# LANGUAGE MagicHash , NoImplicitPrelude , UnboxedTuples , BangPatterns # module Bc.UnpackCString where import GHC.Base import GHC.List test = length "foobarbarbeonuhnsaoehunsaoheunsoanuehaonsu" == 42
d121464032585356952d505df1c8afd552b561e69e17946cec84b3c8a288156b
csabahruska/jhc-components
UniqueMonad.hs
module Util.UniqueMonad(UniqT,Uniq, runUniq, runUniqT, execUniq1, execUniq, execUniqT, UniqueProducer(..)) where import Control.Applicative import Control.Monad.Identity import Control.Monad.Reader import Control.Monad.State import Data.Unique import GenUtil instance UniqueProducer IO where newUniq = do u <- newUnique return $ hashUnique u instance Monad m => UniqueProducer (UniqT m) where newUniq = UniqT $ do modify (+1) get -- | Run the transformer version of the unique int generator. runUniqT :: Monad m => UniqT m a -> Int -> m (a,Int) runUniqT (UniqT sm) s = runStateT sm s -- | Run the bare version of the unique int generator. runUniq :: Int -> Uniq a -> (a,Int) runUniq x y = runIdentity $ runUniqT y x | Execute the bare unique int generator starting with 1 . execUniq1 :: Uniq a -> a execUniq1 x = fst $ runUniq 1 x -- | Execute the bare unique int generator starting with the suplied number. execUniq :: Int -> Uniq a -> a execUniq st x = fst $ runUniq st x -- | Execute the transformer version of the unique int generator starting with the suplied number. execUniqT :: Monad m => Int -> UniqT m a -> m a execUniqT s (UniqT sm) = liftM fst $ runStateT sm s instance (Monad m, Monad (t m), MonadTrans t, UniqueProducer m) => UniqueProducer (t m) where newUniq = lift newUniq -- | Unique integer generator monad transformer. newtype UniqT m a = UniqT (StateT Int m a) deriving(Monad, Applicative, MonadTrans, Functor, MonadFix, MonadPlus) instance MonadReader s m => MonadReader s (UniqT m) where ask = UniqT $ ask local f (UniqT x) = UniqT $ local f x -- | Unique integer generator monad. type Uniq = UniqT Identity
null
https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-common/src/Util/UniqueMonad.hs
haskell
| Run the transformer version of the unique int generator. | Run the bare version of the unique int generator. | Execute the bare unique int generator starting with the suplied number. | Execute the transformer version of the unique int generator starting with the suplied number. | Unique integer generator monad transformer. | Unique integer generator monad.
module Util.UniqueMonad(UniqT,Uniq, runUniq, runUniqT, execUniq1, execUniq, execUniqT, UniqueProducer(..)) where import Control.Applicative import Control.Monad.Identity import Control.Monad.Reader import Control.Monad.State import Data.Unique import GenUtil instance UniqueProducer IO where newUniq = do u <- newUnique return $ hashUnique u instance Monad m => UniqueProducer (UniqT m) where newUniq = UniqT $ do modify (+1) get runUniqT :: Monad m => UniqT m a -> Int -> m (a,Int) runUniqT (UniqT sm) s = runStateT sm s runUniq :: Int -> Uniq a -> (a,Int) runUniq x y = runIdentity $ runUniqT y x | Execute the bare unique int generator starting with 1 . execUniq1 :: Uniq a -> a execUniq1 x = fst $ runUniq 1 x execUniq :: Int -> Uniq a -> a execUniq st x = fst $ runUniq st x execUniqT :: Monad m => Int -> UniqT m a -> m a execUniqT s (UniqT sm) = liftM fst $ runStateT sm s instance (Monad m, Monad (t m), MonadTrans t, UniqueProducer m) => UniqueProducer (t m) where newUniq = lift newUniq newtype UniqT m a = UniqT (StateT Int m a) deriving(Monad, Applicative, MonadTrans, Functor, MonadFix, MonadPlus) instance MonadReader s m => MonadReader s (UniqT m) where ask = UniqT $ ask local f (UniqT x) = UniqT $ local f x type Uniq = UniqT Identity
a99b0de8bfaadf2c8947af8413e093d28a8ddcda6fd17783b749177d397388cd
igorhvr/bedlam
test-cset.scm
;; Test of the internal character-set API. This is here so we can switch ;; representation of csets more easily. Some of these are based on SRFI 14 tests (cond-expand (chicken-5 (import test (chicken irregex))) (else (use test extras utils irregex))) (load "irregex.scm") (define (vowel? c) (member c '(#\a #\e #\i #\o #\u))) (test-begin) (test-assert (cset=? (plist->cset '(#\a #\a #\e #\e #\i #\i #\o #\o #\u #\u)) (string->cset "ioeauaiii"))) (test (plist->cset '(#\x #\y)) (string->cset "xy")) (test-assert (not (cset=? (plist->cset '(#\x #\x #\y #\y #\z #\z)) (string->cset "xy")))) (test-assert (not (cset=? (plist->cset '(#\x #\z)) (string->cset "xy")))) (test-assert (cset=? (string->cset "abcdef12345") (cset-union (range->cset (integer->char 97) (integer->char 102)) (string->cset "12345")))) (test-assert (cset=? (range->cset #\d #\j) (cset-union (plist->cset '(#\d #\f #\h #\j)) (string->cset "g")))) (test-assert (cset=? (range->cset #\d #\j) (cset-union (string->cset "g") (plist->cset '(#\d #\f #\h #\j))))) (test-assert (not (cset=? (string->cset "abcef12345") ; without the 'd' (cset-union (range->cset (integer->char 97) (integer->char 102)) (string->cset "12345"))))) (test 10 (cset-size (cset-intersection (sre->cset 'ascii) (sre->cset 'digit)))) (test '(#\x #\x) (cset->plist (plist->cset '(#\x #\x)))) (test-assert (not (equal? '(#\X #\X) (cset->plist (plist->cset '(#\x #\x)))))) (test '(#\a #\d #\x #\z) (cset->plist (plist->cset '(#\a #\d #\x #\z)))) (test-assert (cset-contains? (string->cset "xyz") #\x)) (test-assert (not (cset-contains? (string->cset "xyz") #\a))) (test-assert (cset-contains? (range->cset #\x #\z) #\x)) (test-assert (not (cset-contains? (range->cset #\x #\z) #\a))) (let ((cs (plist->cset '(#\a #\c #\h #\j #\l #\l #\n #\n)))) (test-assert (cset-contains? cs #\a)) (test-assert (cset-contains? cs #\b)) (test-assert (cset-contains? cs #\c)) (test-assert (not (cset-contains? cs #\d))) (test-assert (cset-contains? cs #\h)) (test-assert (cset-contains? cs #\i)) (test-assert (cset-contains? cs #\j)) (test-assert (not (cset-contains? cs #\k))) (test-assert (cset-contains? cs #\l)) (test-assert (not (cset-contains? cs #\m))) (test-assert (cset-contains? cs #\n))) (let ((cs (plist->cset '(#\a #\c #\l #\l #\n #\n)))) (test-assert (cset-contains? cs #\a)) (test-assert (cset-contains? cs #\b)) (test-assert (cset-contains? cs #\c)) (test-assert (not (cset-contains? cs #\d))) (test-assert (not (cset-contains? cs #\k))) (test-assert (cset-contains? cs #\l)) (test-assert (not (cset-contains? cs #\m))) (test-assert (cset-contains? cs #\n))) (test-assert (cset=? (plist->cset '(#\a #\c #\l #\l #\n #\n)) (cset-intersection (plist->cset '(#\a #\c #\l #\l #\n #\n)) (plist->cset '(#\a #\e #\h #\l #\n #\p))))) (test-assert (cset=? (plist->cset '(#\b #\b #\l #\l #\n #\n)) (cset-intersection (plist->cset '(#\a #\c #\h #\l #\n #\n)) (plist->cset '(#\b #\b #\l #\l #\n #\n))))) (test-assert (cset=? (cset-intersection (sre->cset 'hex-digit) (cset-complement (sre->cset 'digit))) (string->cset "abcdefABCDEF"))) (test-assert (cset=? (cset-union (sre->cset 'hex-digit) (string->cset "abcdefghijkl")) (string->cset "abcdefABCDEFghijkl0123456789"))) (test-assert (cset=? (cset-difference (string->cset "abcdefghijklmn") (sre->cset 'hex-digit)) (string->cset "ghijklmn"))) (test-assert (cset=? (string->cset "0123456789") (cset-difference (sre->cset 'hex-digit) (sre->cset 'alpha)))) (test-assert (cset=? (string->cset "abcdefABCDEF") (cset-intersection (sre->cset 'hex-digit) (sre->cset 'alpha)))) (test-end)
null
https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/irregex/irregex-0.9.8/test-cset.scm
scheme
Test of the internal character-set API. This is here so we can switch representation of csets more easily. without the 'd'
Some of these are based on SRFI 14 tests (cond-expand (chicken-5 (import test (chicken irregex))) (else (use test extras utils irregex))) (load "irregex.scm") (define (vowel? c) (member c '(#\a #\e #\i #\o #\u))) (test-begin) (test-assert (cset=? (plist->cset '(#\a #\a #\e #\e #\i #\i #\o #\o #\u #\u)) (string->cset "ioeauaiii"))) (test (plist->cset '(#\x #\y)) (string->cset "xy")) (test-assert (not (cset=? (plist->cset '(#\x #\x #\y #\y #\z #\z)) (string->cset "xy")))) (test-assert (not (cset=? (plist->cset '(#\x #\z)) (string->cset "xy")))) (test-assert (cset=? (string->cset "abcdef12345") (cset-union (range->cset (integer->char 97) (integer->char 102)) (string->cset "12345")))) (test-assert (cset=? (range->cset #\d #\j) (cset-union (plist->cset '(#\d #\f #\h #\j)) (string->cset "g")))) (test-assert (cset=? (range->cset #\d #\j) (cset-union (string->cset "g") (plist->cset '(#\d #\f #\h #\j))))) (test-assert (cset-union (range->cset (integer->char 97) (integer->char 102)) (string->cset "12345"))))) (test 10 (cset-size (cset-intersection (sre->cset 'ascii) (sre->cset 'digit)))) (test '(#\x #\x) (cset->plist (plist->cset '(#\x #\x)))) (test-assert (not (equal? '(#\X #\X) (cset->plist (plist->cset '(#\x #\x)))))) (test '(#\a #\d #\x #\z) (cset->plist (plist->cset '(#\a #\d #\x #\z)))) (test-assert (cset-contains? (string->cset "xyz") #\x)) (test-assert (not (cset-contains? (string->cset "xyz") #\a))) (test-assert (cset-contains? (range->cset #\x #\z) #\x)) (test-assert (not (cset-contains? (range->cset #\x #\z) #\a))) (let ((cs (plist->cset '(#\a #\c #\h #\j #\l #\l #\n #\n)))) (test-assert (cset-contains? cs #\a)) (test-assert (cset-contains? cs #\b)) (test-assert (cset-contains? cs #\c)) (test-assert (not (cset-contains? cs #\d))) (test-assert (cset-contains? cs #\h)) (test-assert (cset-contains? cs #\i)) (test-assert (cset-contains? cs #\j)) (test-assert (not (cset-contains? cs #\k))) (test-assert (cset-contains? cs #\l)) (test-assert (not (cset-contains? cs #\m))) (test-assert (cset-contains? cs #\n))) (let ((cs (plist->cset '(#\a #\c #\l #\l #\n #\n)))) (test-assert (cset-contains? cs #\a)) (test-assert (cset-contains? cs #\b)) (test-assert (cset-contains? cs #\c)) (test-assert (not (cset-contains? cs #\d))) (test-assert (not (cset-contains? cs #\k))) (test-assert (cset-contains? cs #\l)) (test-assert (not (cset-contains? cs #\m))) (test-assert (cset-contains? cs #\n))) (test-assert (cset=? (plist->cset '(#\a #\c #\l #\l #\n #\n)) (cset-intersection (plist->cset '(#\a #\c #\l #\l #\n #\n)) (plist->cset '(#\a #\e #\h #\l #\n #\p))))) (test-assert (cset=? (plist->cset '(#\b #\b #\l #\l #\n #\n)) (cset-intersection (plist->cset '(#\a #\c #\h #\l #\n #\n)) (plist->cset '(#\b #\b #\l #\l #\n #\n))))) (test-assert (cset=? (cset-intersection (sre->cset 'hex-digit) (cset-complement (sre->cset 'digit))) (string->cset "abcdefABCDEF"))) (test-assert (cset=? (cset-union (sre->cset 'hex-digit) (string->cset "abcdefghijkl")) (string->cset "abcdefABCDEFghijkl0123456789"))) (test-assert (cset=? (cset-difference (string->cset "abcdefghijklmn") (sre->cset 'hex-digit)) (string->cset "ghijklmn"))) (test-assert (cset=? (string->cset "0123456789") (cset-difference (sre->cset 'hex-digit) (sre->cset 'alpha)))) (test-assert (cset=? (string->cset "abcdefABCDEF") (cset-intersection (sre->cset 'hex-digit) (sre->cset 'alpha)))) (test-end)
edd400557b53f3ba115c37f4b70b2ec195e573ddacc21836e1b23fe9bd027179
hjwylde/werewolf
Command.hs
| Module : Game . Werewolf . Variant . NoRoleReveal . Command Description : Suite of command messages used throughout the game . Copyright : ( c ) , 2016 License : : A ' Message ' is used to relay information back to either all players or a single player . This module defines suite of command messages used throughout the werewolf game for the ' NoRoleReveal ' variant . Module : Game.Werewolf.Variant.NoRoleReveal.Command Description : Suite of command messages used throughout the game. Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : A 'Message' is used to relay information back to either all players or a single player. This module defines suite of command messages used throughout the werewolf game for the 'NoRoleReveal' variant. -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Game.Werewolf.Variant.NoRoleReveal.Command ( -- * Choose playerShotText, * nocturnalRolePingedText, werewolvesPingedText, -- * Quit callerQuitText, -- * Status currentNocturnalTurnText, deadPlayersText, ) where import Control.Lens import Data.String.Humanise import Data.String.Interpolate.Extra import Data.Text (Text) import Game.Werewolf import Game.Werewolf.Message playerShotText :: Player -> Text playerShotText player = [iFile|variant/no-role-reveal/command/choose/player-shot.txt|] nocturnalRolePingedText :: Role -> Text nocturnalRolePingedText _ = [iFile|variant/no-role-reveal/command/ping/nocturnal-role-pinged.txt|] werewolvesPingedText :: Text werewolvesPingedText = [iFile|variant/no-role-reveal/command/ping/werewolves-pinged.txt|] callerQuitText :: Player -> Text callerQuitText caller = [iFile|variant/no-role-reveal/command/quit/caller-quit.txt|] currentNocturnalTurnText :: Game -> Text currentNocturnalTurnText _ = [iFile|variant/no-role-reveal/command/status/current-nocturnal-turn.txt|] deadPlayersText :: Game -> Text deadPlayersText game = [iFile|variant/no-role-reveal/command/status/dead-players.txt|]
null
https://raw.githubusercontent.com/hjwylde/werewolf/d22a941120a282127fc3e2db52e7c86b5d238344/app/Game/Werewolf/Variant/NoRoleReveal/Command.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE QuasiQuotes # * Choose * Quit * Status
| Module : Game . Werewolf . Variant . NoRoleReveal . Command Description : Suite of command messages used throughout the game . Copyright : ( c ) , 2016 License : : A ' Message ' is used to relay information back to either all players or a single player . This module defines suite of command messages used throughout the werewolf game for the ' NoRoleReveal ' variant . Module : Game.Werewolf.Variant.NoRoleReveal.Command Description : Suite of command messages used throughout the game. Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : A 'Message' is used to relay information back to either all players or a single player. This module defines suite of command messages used throughout the werewolf game for the 'NoRoleReveal' variant. -} module Game.Werewolf.Variant.NoRoleReveal.Command ( playerShotText, * nocturnalRolePingedText, werewolvesPingedText, callerQuitText, currentNocturnalTurnText, deadPlayersText, ) where import Control.Lens import Data.String.Humanise import Data.String.Interpolate.Extra import Data.Text (Text) import Game.Werewolf import Game.Werewolf.Message playerShotText :: Player -> Text playerShotText player = [iFile|variant/no-role-reveal/command/choose/player-shot.txt|] nocturnalRolePingedText :: Role -> Text nocturnalRolePingedText _ = [iFile|variant/no-role-reveal/command/ping/nocturnal-role-pinged.txt|] werewolvesPingedText :: Text werewolvesPingedText = [iFile|variant/no-role-reveal/command/ping/werewolves-pinged.txt|] callerQuitText :: Player -> Text callerQuitText caller = [iFile|variant/no-role-reveal/command/quit/caller-quit.txt|] currentNocturnalTurnText :: Game -> Text currentNocturnalTurnText _ = [iFile|variant/no-role-reveal/command/status/current-nocturnal-turn.txt|] deadPlayersText :: Game -> Text deadPlayersText game = [iFile|variant/no-role-reveal/command/status/dead-players.txt|]
33dbda0f441f53690f636829a915990ab6858e0befbb87e5594894984896d80e
dryewo/cyrus
authenticator.clj
(ns {{namespace}}.authenticator (:require [mount.lite :as m] [dovetail.core :as log] [cyrus-config.core :as cfg]{{#swagger1st-oauth2}} [fahrscheine-bitte.core :as oauth2]{{/swagger1st-oauth2}}{{#ui-oauth2}} [cyrus-ui-oauth2.core :as ui-oauth2]{{/ui-oauth2}})) (cfg/def TOKENINFO_URL "URL to check access tokens against. If not set, tokens won't be checked.") {{#swagger1st-oauth2}} Checks if TOKENINFO_URL is set and returns a pass - through handler in case it 's not ;; Works as a security handler for io.sarnowski.swagger1st.core/protector (m/defstate oauth2-s1st-security-handler :start (if TOKENINFO_URL (let [access-token-resolver-fn (oauth2/make-cached-access-token-resolver TOKENINFO_URL {})] (log/info "Checking OAuth2 access tokens against %s." TOKENINFO_URL) (oauth2/make-oauth2-s1st-security-handler access-token-resolver-fn oauth2/check-corresponding-attributes)) (do (log/warn "TOKENINFO_URL is not set; NOT CHECKING ACCESS TOKENS!") (fn [request definition requirements] request)))) (defn log-access-denied-reason [reason] (log/info "Access denied: %s" reason)) (defn wrap-reason-logger [handler] (oauth2/wrap-log-auth-error handler log-access-denied-reason)) {{/swagger1st-oauth2}}{{#ui-oauth2}} (cfg/def EXTERNAL_URL "Public URL of the deployed application, used to generate redirect back from IAM provider.") (cfg/def UI_ALLOW_ANON "Whether to allow unauthenticated users in web UI." {:spec boolean?}) (m/defstate ui-oauth2-profile :start (if UI_ALLOW_ANON (do (log/warn "UI_ALLOW_ANON is set; NOT PROTECTING UI!") nil) Go to and register a new app ( use :8080 / ui / callback ) , ;; copy its client credentials here. {:authorize-url "" :access-token-url "" :client-id "CLIENT_ID" :client-secret "CLIENT_SECRET" :scopes ["user:email"] :allow-anon? UI_ALLOW_ANON :external-url EXTERNAL_URL :default-landing-endpoint "/ui" :redirect-endpoint "/ui/callback" :login-endpoint "/ui/login" :logout-endpoint "/ui/logout"})) (defn wrap-ui-oauth2 [handler] (if @ui-oauth2-profile (ui-oauth2/wrap-ui-oauth2 handler @ui-oauth2-profile) handler)) {{/ui-oauth2}}
null
https://raw.githubusercontent.com/dryewo/cyrus/880c842e0baa11887854ec3d912c044a2a500449/resources/leiningen/new/cyrus/src/_namespace_/authenticator.clj
clojure
Works as a security handler for io.sarnowski.swagger1st.core/protector copy its client credentials here.
(ns {{namespace}}.authenticator (:require [mount.lite :as m] [dovetail.core :as log] [cyrus-config.core :as cfg]{{#swagger1st-oauth2}} [fahrscheine-bitte.core :as oauth2]{{/swagger1st-oauth2}}{{#ui-oauth2}} [cyrus-ui-oauth2.core :as ui-oauth2]{{/ui-oauth2}})) (cfg/def TOKENINFO_URL "URL to check access tokens against. If not set, tokens won't be checked.") {{#swagger1st-oauth2}} Checks if TOKENINFO_URL is set and returns a pass - through handler in case it 's not (m/defstate oauth2-s1st-security-handler :start (if TOKENINFO_URL (let [access-token-resolver-fn (oauth2/make-cached-access-token-resolver TOKENINFO_URL {})] (log/info "Checking OAuth2 access tokens against %s." TOKENINFO_URL) (oauth2/make-oauth2-s1st-security-handler access-token-resolver-fn oauth2/check-corresponding-attributes)) (do (log/warn "TOKENINFO_URL is not set; NOT CHECKING ACCESS TOKENS!") (fn [request definition requirements] request)))) (defn log-access-denied-reason [reason] (log/info "Access denied: %s" reason)) (defn wrap-reason-logger [handler] (oauth2/wrap-log-auth-error handler log-access-denied-reason)) {{/swagger1st-oauth2}}{{#ui-oauth2}} (cfg/def EXTERNAL_URL "Public URL of the deployed application, used to generate redirect back from IAM provider.") (cfg/def UI_ALLOW_ANON "Whether to allow unauthenticated users in web UI." {:spec boolean?}) (m/defstate ui-oauth2-profile :start (if UI_ALLOW_ANON (do (log/warn "UI_ALLOW_ANON is set; NOT PROTECTING UI!") nil) Go to and register a new app ( use :8080 / ui / callback ) , {:authorize-url "" :access-token-url "" :client-id "CLIENT_ID" :client-secret "CLIENT_SECRET" :scopes ["user:email"] :allow-anon? UI_ALLOW_ANON :external-url EXTERNAL_URL :default-landing-endpoint "/ui" :redirect-endpoint "/ui/callback" :login-endpoint "/ui/login" :logout-endpoint "/ui/logout"})) (defn wrap-ui-oauth2 [handler] (if @ui-oauth2-profile (ui-oauth2/wrap-ui-oauth2 handler @ui-oauth2-profile) handler)) {{/ui-oauth2}}
820452559e2f9f9399833314d768326c764d4a4f3d8bcc0a9de34de9f8e25cb2
gsakkas/rite
20060420-11:57:34-64faf25cf828b203532860f001bbe336.seminal.ml
exception Unimplemented exception RuntimeTypeError exception DoesNotTypecheck of string (****** Syntax for our language, including types (do not change) *****) type exp = Var of string | Lam of string * typ * exp | Apply of exp * exp | Closure of string * exp * (env ref) | Int of int | Plus of exp * exp | If of exp * exp * exp | RecordE of (string * exp) list # # # # # # # # # # # # # # # # # # | Get of exp * string | Set of exp * string * exp | Letrec of typ * string * string * typ * exp | Cast of exp * typ and env = (string * exp) list and access = Read | Write | Both and typ = IntT | ArrowT of typ * typ | RecordT of (string * typ * access) list and ctxt = (string * typ) list (****** Interpreter for our language (do not change) *****) let rec interp env e = match e with Var s -> (try List.assoc s env with Not_found -> raise RuntimeTypeError) | Lam(s,_,e2) -> Closure(s,e2,ref env) | Closure _ -> e | Apply(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match v1 with Closure(s,e3,env2) -> interp((s,v2)::(!env2)) e3 | _ -> raise RuntimeTypeError) | Plus(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match(v1,v2) with (Int i, Int j) -> Int (i+j) | _ -> raise RuntimeTypeError) | If(e1,e2,e3) -> let v1 = interp env e1 in (match v1 with Int 0 -> interp env e3 | Int _ -> interp env e2 | _ -> raise RuntimeTypeError) | Int _ -> e | RecordV _ -> e | RecordE lst -> RecordV (List.map (fun (s,r) -> (s,ref(interp env r))) lst) | Get(e,s) -> (match interp env e with RecordV lst -> (try !(List.assoc s lst) with Not_found -> raise RuntimeTypeError) | _ -> raise RuntimeTypeError) | Set(e1,s,e2) -> (match interp env e1 with RecordV lst -> let r=try List.assoc s lst with Not_found -> raise RuntimeTypeError in let ans = interp env e2 in r := ans; ans | _ -> raise RuntimeTypeError) | Letrec(_,f,x,_,e) -> let r = ref env in let c = Closure(x,e,r) in let _ = r := (f,c)::(!r) in c | Cast(e,t) -> interp env e let interp e = interp [] e (***** helper functions provided to you (do not change) *****) raise exception if same field name appears > 1 time let rec loop lst1 lst2 = match lst2 with [] -> () | (s,t,a)::tl -> if (List.exists (fun (s2,_,_) -> s2=s) lst1) then raise (DoesNotTypecheck "") else loop ((s,t,a)::lst1) tl in loop [] lst # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match t with IntT -> () | ArrowT(t1,t2) -> checkType t1; checkType t2 | RecordT lst -> fields_unique lst; List.iter (fun (_,t,_) -> checkType t) lst # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match lst with [] -> None | (s,t,a)::tl -> if s=str then Some (t,a) else getFieldType tl str * * * * * * * Problem 1 : complete subtype and typecheck * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match t1,t2 with _ -> print_endline ("In subtype") # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match e with Var s -> (try List.assoc s ctxt with Not_found -> raise (DoesNotTypecheck "")) | Lam(s,t,e) -> checkType t; ArrowT(t,typecheck ((s,t)::ctxt) e) | Closure _ -> raise (DoesNotTypecheck "not a source program") | Int _ -> IntT | Plus(e1,e2) -> if subtype (typecheck ctxt e1) IntT && subtype (typecheck ctxt e2) IntT then IntT else raise (DoesNotTypecheck "") | _ -> raise Unimplemented let typecheck e = typecheck [] e (********** examples and testing ***********) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ########################################################### *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let lam x t e = Lam(x,t,e) let app e1 e2 = Apply(e1,e2) let vx = Var "x" let vy = Var "y" let vf = Var "f" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ########## ############################################################ ################################################# ########################################################### ################### ## ###################### ################### ## ############################################################################# ## ########## ######################################################################### ####################### ################## ############################## ###################################################### ########################################################## ########################### ###################################### ########################################## ###################### ################### ## ################### ## ##################################################### ####################################################### ##################################################### ####################################################### ## *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060420-11%3A57%3A34-64faf25cf828b203532860f001bbe336.seminal.ml
ocaml
***** Syntax for our language, including types (do not change) **** ***** Interpreter for our language (do not change) **** **** helper functions provided to you (do not change) **** ********* examples and testing **********
exception Unimplemented exception RuntimeTypeError exception DoesNotTypecheck of string type exp = Var of string | Lam of string * typ * exp | Apply of exp * exp | Closure of string * exp * (env ref) | Int of int | Plus of exp * exp | If of exp * exp * exp | RecordE of (string * exp) list # # # # # # # # # # # # # # # # # # | Get of exp * string | Set of exp * string * exp | Letrec of typ * string * string * typ * exp | Cast of exp * typ and env = (string * exp) list and access = Read | Write | Both and typ = IntT | ArrowT of typ * typ | RecordT of (string * typ * access) list and ctxt = (string * typ) list let rec interp env e = match e with Var s -> (try List.assoc s env with Not_found -> raise RuntimeTypeError) | Lam(s,_,e2) -> Closure(s,e2,ref env) | Closure _ -> e | Apply(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match v1 with Closure(s,e3,env2) -> interp((s,v2)::(!env2)) e3 | _ -> raise RuntimeTypeError) | Plus(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match(v1,v2) with (Int i, Int j) -> Int (i+j) | _ -> raise RuntimeTypeError) | If(e1,e2,e3) -> let v1 = interp env e1 in (match v1 with Int 0 -> interp env e3 | Int _ -> interp env e2 | _ -> raise RuntimeTypeError) | Int _ -> e | RecordV _ -> e | RecordE lst -> RecordV (List.map (fun (s,r) -> (s,ref(interp env r))) lst) | Get(e,s) -> (match interp env e with RecordV lst -> (try !(List.assoc s lst) with Not_found -> raise RuntimeTypeError) | _ -> raise RuntimeTypeError) | Set(e1,s,e2) -> (match interp env e1 with RecordV lst -> let r=try List.assoc s lst with Not_found -> raise RuntimeTypeError in let ans = interp env e2 in r := ans; ans | _ -> raise RuntimeTypeError) | Letrec(_,f,x,_,e) -> let r = ref env in let c = Closure(x,e,r) in let _ = r := (f,c)::(!r) in c | Cast(e,t) -> interp env e let interp e = interp [] e raise exception if same field name appears > 1 time let rec loop lst1 lst2 = match lst2 with [] -> () | (s,t,a)::tl -> if (List.exists (fun (s2,_,_) -> s2=s) lst1) then raise (DoesNotTypecheck "") else loop ((s,t,a)::lst1) tl in loop [] lst # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match t with IntT -> () | ArrowT(t1,t2) -> checkType t1; checkType t2 | RecordT lst -> fields_unique lst; List.iter (fun (_,t,_) -> checkType t) lst # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match lst with [] -> None | (s,t,a)::tl -> if s=str then Some (t,a) else getFieldType tl str * * * * * * * Problem 1 : complete subtype and typecheck * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match t1,t2 with _ -> print_endline ("In subtype") # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # match e with Var s -> (try List.assoc s ctxt with Not_found -> raise (DoesNotTypecheck "")) | Lam(s,t,e) -> checkType t; ArrowT(t,typecheck ((s,t)::ctxt) e) | Closure _ -> raise (DoesNotTypecheck "not a source program") | Int _ -> IntT | Plus(e1,e2) -> if subtype (typecheck ctxt e1) IntT && subtype (typecheck ctxt e2) IntT then IntT else raise (DoesNotTypecheck "") | _ -> raise Unimplemented let typecheck e = typecheck [] e # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ########################################################### *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let lam x t e = Lam(x,t,e) let app e1 e2 = Apply(e1,e2) let vx = Var "x" let vy = Var "y" let vf = Var "f" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ########## ############################################################ ################################################# ########################################################### ################### ## ###################### ################### ## ############################################################################# ## ########## ######################################################################### ####################### ################## ############################## ###################################################### ########################################################## ########################### ###################################### ########################################## ###################### ################### ## ################### ## ##################################################### ####################################################### ##################################################### ####################################################### ## *)
0b67c0c3ebe3a60716e7718865227aabc99f48a0c2596eb8391ac299519fe64a
RichiH/git-annex
PreCommit.hs
git - annex command - - Copyright 2010 - 2014 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2010-2014 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} # LANGUAGE CPP # module Command.PreCommit where import Command import Config import qualified Command.Add import qualified Command.Fix import Annex.Direct import Annex.Hook import Annex.Link import Annex.View import Annex.Version import Annex.View.ViewedFile import Annex.LockFile import Logs.View import Logs.MetaData import Types.View import Types.MetaData import qualified Git.Index as Git import qualified Git.LsFiles as Git import qualified Data.Set as S cmd :: Command cmd = command "pre-commit" SectionPlumbing "run by git pre-commit hook" paramPaths (withParams seek) seek :: CmdParams -> CommandSeek seek ps = lockPreCommitHook $ ifM isDirect ( do -- update direct mode mappings for committed files withWords startDirect ps runAnnexHook preCommitAnnexHook , do ifM (not <$> versionSupportsUnlockedPointers <&&> liftIO Git.haveFalseIndex) ( do (fs, cleanup) <- inRepo $ Git.typeChangedStaged ps whenM (anyM isOldUnlocked fs) $ giveup "Cannot make a partial commit with unlocked annexed files. You should `git annex add` the files you want to commit, and then run git commit." void $ liftIO cleanup , do l <- workTreeItems ps -- fix symlinks to files being committed flip withFilesToBeCommitted l $ \f -> maybe stop (Command.Fix.start Command.Fix.FixSymlinks f) =<< isAnnexLink f -- inject unlocked files into the annex -- (not needed when repo version uses -- unlocked pointer files) unlessM versionSupportsUnlockedPointers $ withFilesOldUnlockedToBeCommitted startInjectUnlocked l ) runAnnexHook preCommitAnnexHook -- committing changes to a view updates metadata mv <- currentView case mv of Nothing -> noop Just v -> withViewChanges (addViewMetaData v) (removeViewMetaData v) ) startInjectUnlocked :: FilePath -> CommandStart startInjectUnlocked f = next $ do unlessM (callCommandAction $ Command.Add.start f) $ error $ "failed to add " ++ f ++ "; canceling commit" next $ return True startDirect :: [String] -> CommandStart startDirect _ = next $ next preCommitDirect addViewMetaData :: View -> ViewedFile -> Key -> CommandStart addViewMetaData v f k = do showStart "metadata" f next $ next $ changeMetaData k $ fromView v f removeViewMetaData :: View -> ViewedFile -> Key -> CommandStart removeViewMetaData v f k = do showStart "metadata" f next $ next $ changeMetaData k $ unsetMetaData $ fromView v f changeMetaData :: Key -> MetaData -> CommandCleanup changeMetaData k metadata = do showMetaDataChange metadata addMetaData k metadata return True showMetaDataChange :: MetaData -> Annex () showMetaDataChange = showLongNote . unlines . concatMap showmeta . fromMetaData where showmeta (f, vs) = map (showmetavalue f) $ S.toList vs showmetavalue f v = fromMetaField f ++ showset v ++ "=" ++ fromMetaValue v showset v | isSet v = "+" | otherwise = "-" {- Takes exclusive lock; blocks until available. -} lockPreCommitHook :: Annex a -> Annex a lockPreCommitHook = withExclusiveLock gitAnnexPreCommitLock
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command/PreCommit.hs
haskell
update direct mode mappings for committed files fix symlinks to files being committed inject unlocked files into the annex (not needed when repo version uses unlocked pointer files) committing changes to a view updates metadata Takes exclusive lock; blocks until available.
git - annex command - - Copyright 2010 - 2014 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2010-2014 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} # LANGUAGE CPP # module Command.PreCommit where import Command import Config import qualified Command.Add import qualified Command.Fix import Annex.Direct import Annex.Hook import Annex.Link import Annex.View import Annex.Version import Annex.View.ViewedFile import Annex.LockFile import Logs.View import Logs.MetaData import Types.View import Types.MetaData import qualified Git.Index as Git import qualified Git.LsFiles as Git import qualified Data.Set as S cmd :: Command cmd = command "pre-commit" SectionPlumbing "run by git pre-commit hook" paramPaths (withParams seek) seek :: CmdParams -> CommandSeek seek ps = lockPreCommitHook $ ifM isDirect ( do withWords startDirect ps runAnnexHook preCommitAnnexHook , do ifM (not <$> versionSupportsUnlockedPointers <&&> liftIO Git.haveFalseIndex) ( do (fs, cleanup) <- inRepo $ Git.typeChangedStaged ps whenM (anyM isOldUnlocked fs) $ giveup "Cannot make a partial commit with unlocked annexed files. You should `git annex add` the files you want to commit, and then run git commit." void $ liftIO cleanup , do l <- workTreeItems ps flip withFilesToBeCommitted l $ \f -> maybe stop (Command.Fix.start Command.Fix.FixSymlinks f) =<< isAnnexLink f unlessM versionSupportsUnlockedPointers $ withFilesOldUnlockedToBeCommitted startInjectUnlocked l ) runAnnexHook preCommitAnnexHook mv <- currentView case mv of Nothing -> noop Just v -> withViewChanges (addViewMetaData v) (removeViewMetaData v) ) startInjectUnlocked :: FilePath -> CommandStart startInjectUnlocked f = next $ do unlessM (callCommandAction $ Command.Add.start f) $ error $ "failed to add " ++ f ++ "; canceling commit" next $ return True startDirect :: [String] -> CommandStart startDirect _ = next $ next preCommitDirect addViewMetaData :: View -> ViewedFile -> Key -> CommandStart addViewMetaData v f k = do showStart "metadata" f next $ next $ changeMetaData k $ fromView v f removeViewMetaData :: View -> ViewedFile -> Key -> CommandStart removeViewMetaData v f k = do showStart "metadata" f next $ next $ changeMetaData k $ unsetMetaData $ fromView v f changeMetaData :: Key -> MetaData -> CommandCleanup changeMetaData k metadata = do showMetaDataChange metadata addMetaData k metadata return True showMetaDataChange :: MetaData -> Annex () showMetaDataChange = showLongNote . unlines . concatMap showmeta . fromMetaData where showmeta (f, vs) = map (showmetavalue f) $ S.toList vs showmetavalue f v = fromMetaField f ++ showset v ++ "=" ++ fromMetaValue v showset v | isSet v = "+" | otherwise = "-" lockPreCommitHook :: Annex a -> Annex a lockPreCommitHook = withExclusiveLock gitAnnexPreCommitLock
ea65a9fe0f537b05af2d6118c957057c91ee807a5bffe59b9ca8757377d7c53b
mstksg/inCode
Api.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE TypeInType #-} # LANGUAGE TypeOperators # {-# OPTIONS_GHC -Wall #-} module Api where import Data.Aeson import Data.IntMap (IntMap) import Data.IntSet (IntSet) import Data.Proxy import Data.Text (Text) import GHC.Generics import Servant.API data Task = Task { taskStatus :: Bool , taskDesc :: Text } deriving (Show, Generic) instance ToJSON Task instance FromJSON Task type TodoApi = "list" :> QueryFlag "filtered" :> Get '[JSON] (IntMap Task) :<|> "add" :> QueryParam' '[Required] "desc" Text :> Post '[JSON] Int :<|> "set" :> Capture "id" Int :> QueryParam "completed" Bool :> Post '[JSON] () :<|> "delete" :> Capture "id" Int :> Post '[JSON] () :<|> "prune" :> Post '[JSON] IntSet todoApi :: Proxy TodoApi todoApi = Proxy
null
https://raw.githubusercontent.com/mstksg/inCode/e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a/code-samples/servant-services/Api.hs
haskell
# LANGUAGE TypeInType # # OPTIONS_GHC -Wall #
# LANGUAGE DeriveGeneric # # LANGUAGE TypeOperators # module Api where import Data.Aeson import Data.IntMap (IntMap) import Data.IntSet (IntSet) import Data.Proxy import Data.Text (Text) import GHC.Generics import Servant.API data Task = Task { taskStatus :: Bool , taskDesc :: Text } deriving (Show, Generic) instance ToJSON Task instance FromJSON Task type TodoApi = "list" :> QueryFlag "filtered" :> Get '[JSON] (IntMap Task) :<|> "add" :> QueryParam' '[Required] "desc" Text :> Post '[JSON] Int :<|> "set" :> Capture "id" Int :> QueryParam "completed" Bool :> Post '[JSON] () :<|> "delete" :> Capture "id" Int :> Post '[JSON] () :<|> "prune" :> Post '[JSON] IntSet todoApi :: Proxy TodoApi todoApi = Proxy
2841cacc9dd6487a8d57d6fe7bf59aab84f31d6c73ddfb16f02db6fd999d2d99
lukexi/halive
Computation.hs
main = print [1..10]
null
https://raw.githubusercontent.com/lukexi/halive/cae5b327730bcea5ef25bb05e5a12a283eade97d/demo/Computation.hs
haskell
main = print [1..10]
bee7518e323edfe7bddd74dfc0d0723d4b47b29f5edd5f03f981e5fb7a0f984c
lisp-mirror/airship-scheme
package.lisp
;;;; -*- mode: common-lisp; -*- (cl:defpackage #:airship-scheme/tests (:use #:airship-scheme #:cl) (:import-from #:5am #:is) (:export #:airship-scheme/tests) (:local-nicknames (:scheme :airship-scheme) (:f :float-features)))
null
https://raw.githubusercontent.com/lisp-mirror/airship-scheme/12dbbb3b0fe7ea7cf82e44cbaf736729cc005469/tests/package.lisp
lisp
-*- mode: common-lisp; -*-
(cl:defpackage #:airship-scheme/tests (:use #:airship-scheme #:cl) (:import-from #:5am #:is) (:export #:airship-scheme/tests) (:local-nicknames (:scheme :airship-scheme) (:f :float-features)))
47e2f5ae1616bdb4542aefdeabf03d6c9d419a1cd5206119301e5ffc05a8f62a
clj-commons/iapetos
fn_test.clj
(ns iapetos.collector.fn-test (:require [clojure.test :refer :all] [clojure.test.check [generators :as gen] [properties :as prop] [clojure-test :refer [defspec]]] [iapetos.test.generators :as g] [iapetos.core :as prometheus] [iapetos.collector.fn :as fn])) # # Generators (defn gen-fn-registry [label-keys] (g/registry-fn #(fn/initialize %1 {:labels label-keys}))) (def gen-labels (gen/not-empty (gen/map g/metric-string g/metric-string))) ;; ## Tests (defspec t-wrap-instrumentation 10 (prop/for-all [[labels registry-fn] (gen/let [labels gen-labels registry-fn (gen-fn-registry (keys labels))] [labels registry-fn]) [type f] (gen/elements [[:success #(Thread/sleep 20)] [:failure #(do (Thread/sleep 20) (throw (Exception.)))]])] (let [registry (registry-fn) f' (fn/wrap-instrumentation f registry "f" {:labels labels}) start-time (System/currentTimeMillis) start (System/nanoTime) _ (dotimes [_ 5] (try (f') (catch Throwable _))) end-time (System/currentTimeMillis) delta (/ (- (System/nanoTime) start) 1e9) val-of #(prometheus/value registry %1 (into {} (list {:fn "f"} labels %2)))] (and (<= 0.1 (:sum (val-of :fn/duration-seconds {})) delta) (= 5.0 (:count (val-of :fn/duration-seconds {}))) (or (= type :success) (= 5.0 (val-of :fn/exceptions-total {:exceptionClass "java.lang.Exception"}))) (or (= type :failure) (= 5.0 (val-of :fn/runs-total {:result "success"}))) (or (= type :success) (= 5.0 (val-of :fn/runs-total {:result "failure"}))) (or (= type :success) (<= (- end-time 20) (* 1000 (val-of :fn/last-failure-unixtime {})) end-time)))))) (def test-fn nil) (defn- reset-test-fn! [f] (alter-var-root #'test-fn (constantly f)) (alter-meta! #'test-fn (constantly {}))) (defspec t-instrument! 10 (prop/for-all [[labels registry-fn] (gen/let [labels gen-labels registry-fn (gen-fn-registry (keys labels))] [labels registry-fn]) [type f] (gen/elements [[:success #(Thread/sleep 20)] [:failure #(do (Thread/sleep 20) (throw (Exception.)))]])] (reset-test-fn! f) (let [registry (doto (registry-fn) (fn/instrument! #'test-fn {:labels labels})) start-time (System/currentTimeMillis) start (System/nanoTime) fn-name "iapetos.collector.fn-test/test-fn" _ (dotimes [_ 5] (try (test-fn) (catch Throwable _))) end-time (System/currentTimeMillis) delta (/ (- (System/nanoTime) start) 1e9) val-of #(prometheus/value registry %1 (into {} (list {:fn fn-name} labels %2)))] (and (<= 0.1 (:sum (val-of :fn/duration-seconds {})) delta) (= 5.0 (:count (val-of :fn/duration-seconds {}))) (or (= type :success) (= 5.0 (val-of :fn/exceptions-total {:exceptionClass "java.lang.Exception"}))) (or (= type :failure) (= 5.0 (val-of :fn/runs-total {:result "success"}))) (or (= type :success) (= 5.0 (val-of :fn/runs-total {:result "failure"}))) (or (= type :success) (<= (- end-time 20) (* 1000 (val-of :fn/last-failure-unixtime {})) end-time))))))
null
https://raw.githubusercontent.com/clj-commons/iapetos/0fecedaf8454e17e41b05e0e14754a311b9f4ce2/test/iapetos/collector/fn_test.clj
clojure
## Tests
(ns iapetos.collector.fn-test (:require [clojure.test :refer :all] [clojure.test.check [generators :as gen] [properties :as prop] [clojure-test :refer [defspec]]] [iapetos.test.generators :as g] [iapetos.core :as prometheus] [iapetos.collector.fn :as fn])) # # Generators (defn gen-fn-registry [label-keys] (g/registry-fn #(fn/initialize %1 {:labels label-keys}))) (def gen-labels (gen/not-empty (gen/map g/metric-string g/metric-string))) (defspec t-wrap-instrumentation 10 (prop/for-all [[labels registry-fn] (gen/let [labels gen-labels registry-fn (gen-fn-registry (keys labels))] [labels registry-fn]) [type f] (gen/elements [[:success #(Thread/sleep 20)] [:failure #(do (Thread/sleep 20) (throw (Exception.)))]])] (let [registry (registry-fn) f' (fn/wrap-instrumentation f registry "f" {:labels labels}) start-time (System/currentTimeMillis) start (System/nanoTime) _ (dotimes [_ 5] (try (f') (catch Throwable _))) end-time (System/currentTimeMillis) delta (/ (- (System/nanoTime) start) 1e9) val-of #(prometheus/value registry %1 (into {} (list {:fn "f"} labels %2)))] (and (<= 0.1 (:sum (val-of :fn/duration-seconds {})) delta) (= 5.0 (:count (val-of :fn/duration-seconds {}))) (or (= type :success) (= 5.0 (val-of :fn/exceptions-total {:exceptionClass "java.lang.Exception"}))) (or (= type :failure) (= 5.0 (val-of :fn/runs-total {:result "success"}))) (or (= type :success) (= 5.0 (val-of :fn/runs-total {:result "failure"}))) (or (= type :success) (<= (- end-time 20) (* 1000 (val-of :fn/last-failure-unixtime {})) end-time)))))) (def test-fn nil) (defn- reset-test-fn! [f] (alter-var-root #'test-fn (constantly f)) (alter-meta! #'test-fn (constantly {}))) (defspec t-instrument! 10 (prop/for-all [[labels registry-fn] (gen/let [labels gen-labels registry-fn (gen-fn-registry (keys labels))] [labels registry-fn]) [type f] (gen/elements [[:success #(Thread/sleep 20)] [:failure #(do (Thread/sleep 20) (throw (Exception.)))]])] (reset-test-fn! f) (let [registry (doto (registry-fn) (fn/instrument! #'test-fn {:labels labels})) start-time (System/currentTimeMillis) start (System/nanoTime) fn-name "iapetos.collector.fn-test/test-fn" _ (dotimes [_ 5] (try (test-fn) (catch Throwable _))) end-time (System/currentTimeMillis) delta (/ (- (System/nanoTime) start) 1e9) val-of #(prometheus/value registry %1 (into {} (list {:fn fn-name} labels %2)))] (and (<= 0.1 (:sum (val-of :fn/duration-seconds {})) delta) (= 5.0 (:count (val-of :fn/duration-seconds {}))) (or (= type :success) (= 5.0 (val-of :fn/exceptions-total {:exceptionClass "java.lang.Exception"}))) (or (= type :failure) (= 5.0 (val-of :fn/runs-total {:result "success"}))) (or (= type :success) (= 5.0 (val-of :fn/runs-total {:result "failure"}))) (or (= type :success) (<= (- end-time 20) (* 1000 (val-of :fn/last-failure-unixtime {})) end-time))))))
8a2ce2944ca9381e66a061a56d950cf0a11538f6e289c8599103e88d2f1323d6
HealthSamurai/us-npi
api_test.clj
(ns usnpi.api-test (:require [clojure.test :refer :all] [ring.mock.request :as mock] [usnpi.util-test :refer [read-body]] [usnpi.core :as usnpi])) (deftest test-root-page (testing "The root page returns the request map" (let [req (mock/request :get "/") res (usnpi/app req)] (is (= (:status res) 200))))) (deftest test-caps-page (testing "The metadata page returns a CapabilityStatement object." (let [req (mock/request :get "/metadata") res (usnpi/app req)] (is (= (:status res) 200)) (is (= (-> res read-body :resourceType) "CapabilityStatement")))))
null
https://raw.githubusercontent.com/HealthSamurai/us-npi/a28a8ec8d45e19fadab0528791e7de78f19dc87e/test/usnpi/api_test.clj
clojure
(ns usnpi.api-test (:require [clojure.test :refer :all] [ring.mock.request :as mock] [usnpi.util-test :refer [read-body]] [usnpi.core :as usnpi])) (deftest test-root-page (testing "The root page returns the request map" (let [req (mock/request :get "/") res (usnpi/app req)] (is (= (:status res) 200))))) (deftest test-caps-page (testing "The metadata page returns a CapabilityStatement object." (let [req (mock/request :get "/metadata") res (usnpi/app req)] (is (= (:status res) 200)) (is (= (-> res read-body :resourceType) "CapabilityStatement")))))
6b52b25c6b05eb03a6f65446ee0a93f39152a3cd244c832231bc2f217c8ab80b
fourmolu/fourmolu
operators-3-four-out.hs
foo = op <> n <+> colon <+> prettySe <+> text "=" <+> prettySe <> text sc
null
https://raw.githubusercontent.com/fourmolu/fourmolu/1f8903a92c8d5001dc1ec8ecfd4a04a3b61c3283/data/examples/declaration/value/function/operators-3-four-out.hs
haskell
foo = op <> n <+> colon <+> prettySe <+> text "=" <+> prettySe <> text sc
985311f12f47c4b65cf013654c9de4a12eed4d03b6e9112a6b9383af9a72dab1
kind2-mc/kind2
lustreAstHelpers.mli
This file is part of the Kind 2 model checker . Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright (c) 2015 by the Board of Trustees of the University of Iowa 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. *) (** Some helper functions on the surface level parsed AST *) open LustreAst (** {1 Helpers} *) val expr_is_id : expr -> bool (** Returns whether or not the expression is an Ident variant *) val expr_is_const : expr -> bool * Returns whether or not the expression is a Const variant val expr_is_true : expr -> bool (** Returns whether or not the expression is a Bool Const variant with the True value *) val expr_is_false : expr -> bool (** Returns whether or not the expression is a Bool Const variant with the False value *) val pos_of_expr : expr -> Lib.position (** Returns the position of an expression *) val expr_contains_call : expr -> bool (** Checks if the expression contains a call to a node *) val type_arity : lustre_type -> int * int * Returns the arity of a type , a function ( TArr ) has arity ` ( a , b ) ` where ` a ` is the number of inputs and ` b ` is the number of outputs , every other type has arity ` ( 0 , 0 ) ` where `a` is the number of inputs and `b` is the number of outputs, every other type has arity `(0, 0)` *) val type_contains_subrange : lustre_type -> bool * Returns true if the lustre type expression contains an IntRange or if it is an IntRange val substitute : HString.t -> expr -> expr -> expr * the supplied identifier and expression into the last expression val has_unguarded_pre : expr -> bool (** Returns true if the expression has unguareded pre's *) val has_unguarded_pre_no_warn : expr -> bool (** Returns true if the expression has unguareded pre's. Does not print warning. *) val has_pre_or_arrow : expr -> Lib.position option (** Returns true if the expression has a `pre` or a `->`. *) val contract_has_pre_or_arrow : contract -> Lib.position option (** Returns true iff a contract mentions a `pre` or a `->`. Does not (cannot) check contract calls recursively, checks only inputs and outputs. *) val node_local_decl_has_pre_or_arrow : node_local_decl -> Lib.position option (** Checks whether a node local declaration has a `pre` or a `->`. *) val node_item_has_pre_or_arrow : node_item -> Lib.position option (** Checks whether a node equation has a `pre` or a `->`. *) val replace_lasts : LustreAst.index list -> string -> SI.t -> expr -> expr * SI.t * [ replace_lasts allowed prefix acc e ] replaces [ last x ] expressions in AST [ e ] by abstract identifiers prefixed with [ prefix ] . Only identifiers that appear in the list [ allowed ] are allowed to appear under a last . It returns the new AST expression and a set of identifers for which the last application was replaced . [e] by abstract identifiers prefixed with [prefix]. Only identifiers that appear in the list [allowed] are allowed to appear under a last. It returns the new AST expression and a set of identifers for which the last application was replaced. *) val vars_of_node_calls: expr -> SI.t (** returns all identifiers from the [expr] ast that are inside node calls *) val vars: expr -> SI.t (** returns all the [ident] that appear in the expr ast*) val vars_of_struct_item_with_pos: struct_item -> (Lib.position * index) list (** returns all variables that appear in a [struct_item] with associated positions *) val vars_of_struct_item: struct_item -> SI.t (** returns all variables that appear in a [struct_item] *) val defined_vars_with_pos: node_item -> (Lib.position * index) list * returns all the variables that appear in the lhs of the equation of the node body with associated positions val vars_of_ty_ids: typed_ident -> SI.t (** returns all the variables that occur in the expression of a typed identifier declaration *) val add_exp: Lib.position -> expr -> expr -> expr * Return an AST that adds two expressions val abs_diff: Lib.position -> expr -> expr -> expr * returns an AST which is the absolute difference of two expr ast val extract_ip_ty: const_clocked_typed_decl -> ident * lustre_type (** returns the pair of identifier and its type from the node input streams *) val extract_op_ty: clocked_typed_decl -> ident * lustre_type (** returns the pair of identifier and its type from the node output streams *) val is_const_arg: const_clocked_typed_decl -> bool (** Returns [true] if the node input stream is a constant *) val is_type_num: lustre_type -> bool * returns [ true ] if the type is a number type i.e. Int , Real , IntRange , or Machine Integer val is_type_int: lustre_type -> bool * returns [ true ] if the type is an integer type , i.e. Int , or IntRange val is_type_real_or_int: lustre_type -> bool * returns [ true ] if the type is a real or integer type , i.e , Real , Int , or IntRange val is_type_int_or_machine_int: lustre_type -> bool * returns [ true ] if the type is an integer type or machine int , i.e. Int , IntRange , or Machine Integer val is_type_unsigned_machine_int: lustre_type -> bool * returns [ true ] if the type is an unsigned machine int . i.e. UInt , UInt32 etc . val is_type_signed_machine_int: lustre_type -> bool * returns [ true ] if the type is an signed machine int . i.e. Int , Int32 etc . val is_type_machine_int: lustre_type -> bool (** returns [true] if the type is a signed or unsiged machine integer. *) val is_type_array: lustre_type -> bool (** returns [true] if the type is an array type *) val is_machine_type_of_associated_width: (lustre_type * lustre_type) -> bool * returns [ true ] if the first component of the type is of the same width as the second component . eg . Int8 and UInt8 returns [ true ] but Int16 and UInt8 return [ false ] as the second component. eg. Int8 and UInt8 returns [true] but Int16 and UInt8 return [false] *) val is_type_or_const_decl: declaration -> bool (** returns [true] if it is a type or a constant declaration *) val flatten_group_types: lustre_type list -> lustre_type list (** Flatten group type structure *) val split_program: declaration list -> (declaration list * declaration list) * Splits the program into two . First component are the type and constant declarations and Second component are the nodes , contract and function declarations . Second component are the nodes, contract and function declarations. *) val abstract_pre_subexpressions: expr -> expr (** Abstracts out the pre expressions into a constant so that the built graph does not create a cycle.*) val replace_idents: index list -> index list -> expr -> expr * For every identifier , if that identifier is position n in locals1 , replace it with position n in locals2 replace it with position n in locals2 *) val extract_node_equation: node_item -> (eq_lhs * expr) list * Extracts out all the node equations as an associated list of rhs and lhs of the equation val get_last_node_name: declaration list -> ident option (** Gets the name of the last node declared in the file. *) val move_node_to_last: ident -> declaration list -> declaration list (** Moves the node with given name to the end of the list *) val sort_typed_ident: typed_ident list -> typed_ident list (** Sort typed identifiers *) val sort_idents: ident list -> ident list (** Sort identifiers *) val syn_expr_equal : int option -> expr -> expr -> (bool, unit) result * Check syntactic equality o expressions ( ignoring positions ) up to a certain optional depth . If the depth is reached , then [ Error ( ) ] is returned , otherwise [ Ok false ] if the two expressions are unequal and [ Ok true ] if they are equal . If the depth is reached, then [Error ()] is returned, otherwise [Ok false] if the two expressions are unequal and [Ok true] if they are equal. *) val syn_type_equal : int option -> lustre_type -> lustre_type -> (bool, unit) result * Check syntactic equality of types ( ignoring positions ) up to a certain optional depth . If the depth is reached , then [ Error ( ) ] is returned , otherwise [ Ok false ] if the two expressions are unequal and [ Ok true ] if they are equal . If the depth is reached, then [Error ()] is returned, otherwise [Ok false] if the two expressions are unequal and [Ok true] if they are equal.*) val hash : int option -> expr -> int (** Compute the hash of an AST expression to the given depth. After the depth limit is reached the same hash value is assigned to every sub expression. This function does not include position information in the hash. *) val rename_contract_vars : expr -> expr * Rename contract variables from internal names ( with format # _ contract_var ) to syntax names
null
https://raw.githubusercontent.com/kind2-mc/kind2/d34694b4461323322fdcc291aa3c3d9c453fc098/src/lustre/lustreAstHelpers.mli
ocaml
* Some helper functions on the surface level parsed AST * {1 Helpers} * Returns whether or not the expression is an Ident variant * Returns whether or not the expression is a Bool Const variant with the True value * Returns whether or not the expression is a Bool Const variant with the False value * Returns the position of an expression * Checks if the expression contains a call to a node * Returns true if the expression has unguareded pre's * Returns true if the expression has unguareded pre's. Does not print warning. * Returns true if the expression has a `pre` or a `->`. * Returns true iff a contract mentions a `pre` or a `->`. Does not (cannot) check contract calls recursively, checks only inputs and outputs. * Checks whether a node local declaration has a `pre` or a `->`. * Checks whether a node equation has a `pre` or a `->`. * returns all identifiers from the [expr] ast that are inside node calls * returns all the [ident] that appear in the expr ast * returns all variables that appear in a [struct_item] with associated positions * returns all variables that appear in a [struct_item] * returns all the variables that occur in the expression of a typed identifier declaration * returns the pair of identifier and its type from the node input streams * returns the pair of identifier and its type from the node output streams * Returns [true] if the node input stream is a constant * returns [true] if the type is a signed or unsiged machine integer. * returns [true] if the type is an array type * returns [true] if it is a type or a constant declaration * Flatten group type structure * Abstracts out the pre expressions into a constant so that the built graph does not create a cycle. * Gets the name of the last node declared in the file. * Moves the node with given name to the end of the list * Sort typed identifiers * Sort identifiers * Compute the hash of an AST expression to the given depth. After the depth limit is reached the same hash value is assigned to every sub expression. This function does not include position information in the hash.
This file is part of the Kind 2 model checker . Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright (c) 2015 by the Board of Trustees of the University of Iowa 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. *) open LustreAst val expr_is_id : expr -> bool val expr_is_const : expr -> bool * Returns whether or not the expression is a Const variant val expr_is_true : expr -> bool val expr_is_false : expr -> bool val pos_of_expr : expr -> Lib.position val expr_contains_call : expr -> bool val type_arity : lustre_type -> int * int * Returns the arity of a type , a function ( TArr ) has arity ` ( a , b ) ` where ` a ` is the number of inputs and ` b ` is the number of outputs , every other type has arity ` ( 0 , 0 ) ` where `a` is the number of inputs and `b` is the number of outputs, every other type has arity `(0, 0)` *) val type_contains_subrange : lustre_type -> bool * Returns true if the lustre type expression contains an IntRange or if it is an IntRange val substitute : HString.t -> expr -> expr -> expr * the supplied identifier and expression into the last expression val has_unguarded_pre : expr -> bool val has_unguarded_pre_no_warn : expr -> bool val has_pre_or_arrow : expr -> Lib.position option val contract_has_pre_or_arrow : contract -> Lib.position option val node_local_decl_has_pre_or_arrow : node_local_decl -> Lib.position option val node_item_has_pre_or_arrow : node_item -> Lib.position option val replace_lasts : LustreAst.index list -> string -> SI.t -> expr -> expr * SI.t * [ replace_lasts allowed prefix acc e ] replaces [ last x ] expressions in AST [ e ] by abstract identifiers prefixed with [ prefix ] . Only identifiers that appear in the list [ allowed ] are allowed to appear under a last . It returns the new AST expression and a set of identifers for which the last application was replaced . [e] by abstract identifiers prefixed with [prefix]. Only identifiers that appear in the list [allowed] are allowed to appear under a last. It returns the new AST expression and a set of identifers for which the last application was replaced. *) val vars_of_node_calls: expr -> SI.t val vars: expr -> SI.t val vars_of_struct_item_with_pos: struct_item -> (Lib.position * index) list val vars_of_struct_item: struct_item -> SI.t val defined_vars_with_pos: node_item -> (Lib.position * index) list * returns all the variables that appear in the lhs of the equation of the node body with associated positions val vars_of_ty_ids: typed_ident -> SI.t val add_exp: Lib.position -> expr -> expr -> expr * Return an AST that adds two expressions val abs_diff: Lib.position -> expr -> expr -> expr * returns an AST which is the absolute difference of two expr ast val extract_ip_ty: const_clocked_typed_decl -> ident * lustre_type val extract_op_ty: clocked_typed_decl -> ident * lustre_type val is_const_arg: const_clocked_typed_decl -> bool val is_type_num: lustre_type -> bool * returns [ true ] if the type is a number type i.e. Int , Real , IntRange , or Machine Integer val is_type_int: lustre_type -> bool * returns [ true ] if the type is an integer type , i.e. Int , or IntRange val is_type_real_or_int: lustre_type -> bool * returns [ true ] if the type is a real or integer type , i.e , Real , Int , or IntRange val is_type_int_or_machine_int: lustre_type -> bool * returns [ true ] if the type is an integer type or machine int , i.e. Int , IntRange , or Machine Integer val is_type_unsigned_machine_int: lustre_type -> bool * returns [ true ] if the type is an unsigned machine int . i.e. UInt , UInt32 etc . val is_type_signed_machine_int: lustre_type -> bool * returns [ true ] if the type is an signed machine int . i.e. Int , Int32 etc . val is_type_machine_int: lustre_type -> bool val is_type_array: lustre_type -> bool val is_machine_type_of_associated_width: (lustre_type * lustre_type) -> bool * returns [ true ] if the first component of the type is of the same width as the second component . eg . Int8 and UInt8 returns [ true ] but Int16 and UInt8 return [ false ] as the second component. eg. Int8 and UInt8 returns [true] but Int16 and UInt8 return [false] *) val is_type_or_const_decl: declaration -> bool val flatten_group_types: lustre_type list -> lustre_type list val split_program: declaration list -> (declaration list * declaration list) * Splits the program into two . First component are the type and constant declarations and Second component are the nodes , contract and function declarations . Second component are the nodes, contract and function declarations. *) val abstract_pre_subexpressions: expr -> expr val replace_idents: index list -> index list -> expr -> expr * For every identifier , if that identifier is position n in locals1 , replace it with position n in locals2 replace it with position n in locals2 *) val extract_node_equation: node_item -> (eq_lhs * expr) list * Extracts out all the node equations as an associated list of rhs and lhs of the equation val get_last_node_name: declaration list -> ident option val move_node_to_last: ident -> declaration list -> declaration list val sort_typed_ident: typed_ident list -> typed_ident list val sort_idents: ident list -> ident list val syn_expr_equal : int option -> expr -> expr -> (bool, unit) result * Check syntactic equality o expressions ( ignoring positions ) up to a certain optional depth . If the depth is reached , then [ Error ( ) ] is returned , otherwise [ Ok false ] if the two expressions are unequal and [ Ok true ] if they are equal . If the depth is reached, then [Error ()] is returned, otherwise [Ok false] if the two expressions are unequal and [Ok true] if they are equal. *) val syn_type_equal : int option -> lustre_type -> lustre_type -> (bool, unit) result * Check syntactic equality of types ( ignoring positions ) up to a certain optional depth . If the depth is reached , then [ Error ( ) ] is returned , otherwise [ Ok false ] if the two expressions are unequal and [ Ok true ] if they are equal . If the depth is reached, then [Error ()] is returned, otherwise [Ok false] if the two expressions are unequal and [Ok true] if they are equal.*) val hash : int option -> expr -> int val rename_contract_vars : expr -> expr * Rename contract variables from internal names ( with format # _ contract_var ) to syntax names
6a38e03f8c1ebaebcfe794e39047ac8f2a09aab5a599cb77de785f070ee5b30c
47degrees/yin-yang-haskell-workshop
V2GreetSolution.hs
{-# language OverloadedStrings #-} module V2GreetSolution where import Network.Simple.TCP main :: IO () main = serve (Host "127.0.0.1") "8080" $ \(socket, _) -> do name <- recv socket 10000 case name of Nothing -> return () Just nm -> do let greeting = "Hello, " <> nm send socket greeting
null
https://raw.githubusercontent.com/47degrees/yin-yang-haskell-workshop/dd9c3076fecf26cafd4f30c4906dd94e003ca651/2-simple-server/V2GreetSolution.hs
haskell
# language OverloadedStrings #
module V2GreetSolution where import Network.Simple.TCP main :: IO () main = serve (Host "127.0.0.1") "8080" $ \(socket, _) -> do name <- recv socket 10000 case name of Nothing -> return () Just nm -> do let greeting = "Hello, " <> nm send socket greeting
86b28c4312f0e802d23ef0ef5cb28715f5c6d9cb77f86bf8ca353dec828b824a
hidaris/thinking-dumps
UnbalancedSet.rkt
#lang typed/racket (require "Element.rkt") (define-type Elem TT) (define-type Tree (U E T)) (struct E () #:transparent) (struct T ([u : Tree] [v : Elem] [w : Tree]) #:transparent) (define-type-alias Set Tree) (: empty : Set) (define empty (E)) (: member : (Elem Set -> Boolean)) (define (member x s) (match s [(E) false] [(T a y b) (if (lt x y) (member x a) (if (lt y x) (member x b) true))])) (: insert : (Elem Set -> Set)) (define (insert x s) (match s [(E) (T (E) x (E))] [(T a y b) (if (lt x y) (T (insert x a) y b) (if (lt y x) (T a y (insert x b)) s))]))
null
https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/pfds/chap2/UnbalancedSet.rkt
racket
#lang typed/racket (require "Element.rkt") (define-type Elem TT) (define-type Tree (U E T)) (struct E () #:transparent) (struct T ([u : Tree] [v : Elem] [w : Tree]) #:transparent) (define-type-alias Set Tree) (: empty : Set) (define empty (E)) (: member : (Elem Set -> Boolean)) (define (member x s) (match s [(E) false] [(T a y b) (if (lt x y) (member x a) (if (lt y x) (member x b) true))])) (: insert : (Elem Set -> Set)) (define (insert x s) (match s [(E) (T (E) x (E))] [(T a y b) (if (lt x y) (T (insert x a) y b) (if (lt y x) (T a y (insert x b)) s))]))
49376187d36c63d7fe8643625f065b8b7baf1c2f258c04b64c82202fcfb87037
RedPRL/ocaml-bwd
Bwd.mli
type 'a bwd = 'a BwdDef.bwd = | Emp | Snoc of 'a bwd * 'a (** This module is similar to {!module:List} but for backward lists. *) module Bwd : module type of BwdNoLabels (** This module is similar to {!module:ListLabels} but for backward lists. *) module BwdLabels : module type of BwdLabels (**/**) * An alias of { ! module : . Notation } for infix notation . module BwdNotation : module type of BwdNotation [@@ocaml.alert deprecated "Use Bwd.Infix instead"]
null
https://raw.githubusercontent.com/RedPRL/ocaml-bwd/14866f9bd38ec289a4a44779b8685ed83865820a/src/Bwd.mli
ocaml
* This module is similar to {!module:List} but for backward lists. * This module is similar to {!module:ListLabels} but for backward lists. */*
type 'a bwd = 'a BwdDef.bwd = | Emp | Snoc of 'a bwd * 'a module Bwd : module type of BwdNoLabels module BwdLabels : module type of BwdLabels * An alias of { ! module : . Notation } for infix notation . module BwdNotation : module type of BwdNotation [@@ocaml.alert deprecated "Use Bwd.Infix instead"]
cd7ace91ba6e8a7671941f138ebdcb6a8aac1e63e5815fd2a92347a138c6da44
nuvla/api-server
group_template.clj
(ns sixsq.nuvla.server.resources.group-template " Templates for creating a new `group`. The collection contains a single template (group-template/generic) that serves as a placeholder. It is not needed for creating a group and does not provide any useful defaults. " (:require [clojure.tools.logging :as log] [sixsq.nuvla.auth.acl-resource :as a] [sixsq.nuvla.auth.utils.acl :as acl-utils] [sixsq.nuvla.server.resources.common.crud :as crud] [sixsq.nuvla.server.resources.common.std-crud :as std-crud] [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.resource-metadata :as md] [sixsq.nuvla.server.resources.spec.group-template :as group-tpl] [sixsq.nuvla.server.util.metadata :as gen-md] [sixsq.nuvla.server.util.response :as r])) (def ^:const resource-type (u/ns->type *ns*)) (def ^:const collection-type (u/ns->collection-type *ns*)) (def resource-acl (acl-utils/normalize-acl {:owners ["group/nuvla-admin"] :view-data ["group/nuvla-user"]})) (def collection-acl {:query ["group/nuvla-admin" "group/nuvla-user"] :add ["group/nuvla-admin"]}) ;; ;; resource ;; (def ^:const resource {:id (str resource-type "/generic") :name "Create Group" :description "used to create a new group" :acl resource-acl :resource-metadata "resource-metadata/group-template-generic"}) ;; ;; atom to keep track of the group-template resources (only 1 for now) ;; (def templates (atom {})) (defn complete-resource "Completes the document with the resource-type and timestamps." [resource] (-> resource (merge {:resource-type resource-type}) u/update-timestamps)) (defn register "Registers a group-template with the server." [resource] (when-let [{:keys [id] :as full-resource} (complete-resource resource)] (try (crud/validate full-resource) (swap! templates assoc id full-resource) (log/info "loaded group-template" id) (catch Exception _ (log/error "invalid group-template:" resource))))) ;; ;; multimethods for validation ;; (def validate-fn (u/create-spec-validation-fn ::group-tpl/schema)) (defmethod crud/validate resource-type [resource] (validate-fn resource)) ;; ;; CRUD operations ;; (defmethod crud/retrieve resource-type [{{uuid :uuid} :params :as request}] (try (let [id (str resource-type "/" uuid)] (-> (get @templates id) (a/throw-cannot-view request) (a/select-viewable-keys request) (r/json-response))) (catch Exception e (or (ex-data e) (throw e))))) ;; must override the default implementation so that the ;; data can be pulled from the atom rather than the database (defmethod crud/retrieve-by-id resource-type [id & _] (try (get @templates id) (catch Exception e (or (ex-data e) (throw e))))) (defmethod crud/query resource-type [request] (a/throw-cannot-query collection-acl request) (let [wrapper-fn (std-crud/collection-wrapper-fn resource-type collection-acl collection-type false false) entries (or (filter #(a/can-view? % request) (vals @templates)) []) ;; FIXME: At least the paging options should be supported. count-before-pagination (count entries) wrapped-entries (wrapper-fn request entries) entries-and-count (assoc wrapped-entries :count count-before-pagination)] (r/json-response entries-and-count))) ;; ;; initialization: create metadata for this collection ;; (def resource-metadata (gen-md/generate-metadata ::ns ::group-tpl/schema)) (def resource-metadata-create (gen-md/generate-metadata nil ::ns ::group-tpl/schema-create "create")) (defn initialize [] (register resource) (md/register resource-metadata) (md/register resource-metadata-create))
null
https://raw.githubusercontent.com/nuvla/api-server/7095076ae6eff4b8f21b17e7673886854ba90e2d/code/src/sixsq/nuvla/server/resources/group_template.clj
clojure
resource atom to keep track of the group-template resources (only 1 for now) multimethods for validation CRUD operations must override the default implementation so that the data can be pulled from the atom rather than the database FIXME: At least the paging options should be supported. initialization: create metadata for this collection
(ns sixsq.nuvla.server.resources.group-template " Templates for creating a new `group`. The collection contains a single template (group-template/generic) that serves as a placeholder. It is not needed for creating a group and does not provide any useful defaults. " (:require [clojure.tools.logging :as log] [sixsq.nuvla.auth.acl-resource :as a] [sixsq.nuvla.auth.utils.acl :as acl-utils] [sixsq.nuvla.server.resources.common.crud :as crud] [sixsq.nuvla.server.resources.common.std-crud :as std-crud] [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.resource-metadata :as md] [sixsq.nuvla.server.resources.spec.group-template :as group-tpl] [sixsq.nuvla.server.util.metadata :as gen-md] [sixsq.nuvla.server.util.response :as r])) (def ^:const resource-type (u/ns->type *ns*)) (def ^:const collection-type (u/ns->collection-type *ns*)) (def resource-acl (acl-utils/normalize-acl {:owners ["group/nuvla-admin"] :view-data ["group/nuvla-user"]})) (def collection-acl {:query ["group/nuvla-admin" "group/nuvla-user"] :add ["group/nuvla-admin"]}) (def ^:const resource {:id (str resource-type "/generic") :name "Create Group" :description "used to create a new group" :acl resource-acl :resource-metadata "resource-metadata/group-template-generic"}) (def templates (atom {})) (defn complete-resource "Completes the document with the resource-type and timestamps." [resource] (-> resource (merge {:resource-type resource-type}) u/update-timestamps)) (defn register "Registers a group-template with the server." [resource] (when-let [{:keys [id] :as full-resource} (complete-resource resource)] (try (crud/validate full-resource) (swap! templates assoc id full-resource) (log/info "loaded group-template" id) (catch Exception _ (log/error "invalid group-template:" resource))))) (def validate-fn (u/create-spec-validation-fn ::group-tpl/schema)) (defmethod crud/validate resource-type [resource] (validate-fn resource)) (defmethod crud/retrieve resource-type [{{uuid :uuid} :params :as request}] (try (let [id (str resource-type "/" uuid)] (-> (get @templates id) (a/throw-cannot-view request) (a/select-viewable-keys request) (r/json-response))) (catch Exception e (or (ex-data e) (throw e))))) (defmethod crud/retrieve-by-id resource-type [id & _] (try (get @templates id) (catch Exception e (or (ex-data e) (throw e))))) (defmethod crud/query resource-type [request] (a/throw-cannot-query collection-acl request) (let [wrapper-fn (std-crud/collection-wrapper-fn resource-type collection-acl collection-type false false) entries (or (filter #(a/can-view? % request) (vals @templates)) []) count-before-pagination (count entries) wrapped-entries (wrapper-fn request entries) entries-and-count (assoc wrapped-entries :count count-before-pagination)] (r/json-response entries-and-count))) (def resource-metadata (gen-md/generate-metadata ::ns ::group-tpl/schema)) (def resource-metadata-create (gen-md/generate-metadata nil ::ns ::group-tpl/schema-create "create")) (defn initialize [] (register resource) (md/register resource-metadata) (md/register resource-metadata-create))
d43c1080d5000f06ead2e731413349c62282526af6550ecd59cc82a80c599c98
lokedhs/cl-gdata
atom.lisp
(in-package :cl-gdata-misc) (alexandria:define-constant +ATOM-TAG-FEED+ "#feed" :test 'equal) (alexandria:define-constant +ATOM-TAG-EDIT+ "edit" :test 'equal) (alexandria:define-constant +ATOM-XML-MIME-TYPE+ "application/atom+xml" :test 'equal) (defclass node-dom-mixin () ((feeds :type list :initarg :feeds :reader document-feeds :documentation "A list of links from this document. Each entry is a list of the three attributes in a \"link\" node: \"rel\", \"type\", \"href\".") (node-dom :initarg :node-dom :reader node-dom :documentation "The DOM node that was used to initialise this document"))) (defmethod initialize-instance :after ((node node-dom-mixin) &key node-dom &allow-other-keys) (when node-dom (with-slots (feeds) node (with-gdata-namespaces (setf feeds (xpath:map-node-set->list #'(lambda (n) (list (dom:get-attribute n "rel") (dom:get-attribute n "type") (dom:get-attribute n "href"))) (xpath:evaluate "atom:link" node-dom))))))) (defun find-document-feed (document rel type) "This version should be eliminated once all existing code has been moved to atom-feed-entry instances" (check-type document node-dom-mixin) (let ((found-feed (find-if #'(lambda (feed) (and (equal (car feed) rel) (equal (cadr feed) type))) (document-feeds document)))) (unless found-feed (error "Feed not found. rel=~s type=~s" rel type)) (caddr found-feed))) ;;; ;;; Feed class ;;; (defclass feed (node-dom-mixin) ((etag :type string :reader feed-etag) (entry-list :type list :reader feed-entry-list) (entry-type :type symbol :initarg :entry-type :initform (error "~s needed when instantiating ~s" :entry-type 'feed) :reader feed-entry-type)) (:documentation "Class that holds the data for an entire feed.")) (defmethod initialize-instance :after ((obj feed) &key &allow-other-keys) (with-gdata-namespaces (setf (slot-value obj 'etag) (value-by-xpath "/atom:feed/@gd:etag" (node-dom obj))) (setf (slot-value obj 'entry-list) (load-atom-feed (node-dom obj) (feed-entry-type obj))))) ;;; MOP stuff ;;; (defclass atom-feed-entry-class (standard-class) () (:documentation "Metaclass for atom feed entry classes.")) (defmethod closer-mop:validate-superclass ((class atom-feed-entry-class) (superclass standard-object)) t) (defclass atom-feed-entry-slot-definition-mixin () ((field-node :initarg :node :accessor field-node) (field-node-collectionp :initarg :node-collectionp :accessor node-collectionp) (field-node-type :initarg :node-type :accessor field-node-type) (field-node-default :initarg :node-default :accessor node-default) (field-node-clear-function :initarg :node-clear-function :accessor node-clear-function) (field-node-updater-function :initarg :node-updater-function :accessor node-updater-function))) (defclass atom-feed-entry-direct-slot-definition (atom-feed-entry-slot-definition-mixin closer-mop:standard-direct-slot-definition) ()) (defclass atom-feed-entry-effective-slot-definition (atom-feed-entry-slot-definition-mixin closer-mop:standard-effective-slot-definition) ()) (defmethod closer-mop:direct-slot-definition-class ((class atom-feed-entry-class) &rest initargs) (declare (ignore initargs)) (find-class 'atom-feed-entry-direct-slot-definition)) (defmethod closer-mop:effective-slot-definition-class ((class atom-feed-entry-class) &rest initargs) (declare (ignore initargs)) (find-class 'atom-feed-entry-effective-slot-definition)) (defun ensure-slot-value (instance field-name &optional default-value) "Returns the value of slot FIELD-NAME in INSTANCE. If the slot is unbound, return DEFAULT-VALUE." (if (and (slot-exists-p instance field-name) (slot-boundp instance field-name)) (slot-value instance field-name) default-value)) (defmethod closer-mop:compute-effective-slot-definition ((class atom-feed-entry-class) slot-name direct-slots) (let ((result (call-next-method))) (setf (field-node result) (ensure-slot-value (car direct-slots) 'field-node)) (setf (node-collectionp result) (ensure-slot-value (car direct-slots) 'field-node-collectionp)) (setf (node-default result) (ensure-slot-value (car direct-slots) 'field-node-default)) (setf (field-node-type result) (ensure-slot-value (car direct-slots) 'field-node-type)) (setf (node-clear-function result) (ensure-slot-value (car direct-slots) 'field-node-clear-function)) (setf (node-updater-function result) (ensure-slot-value (car direct-slots) 'field-node-updater-function)) result)) (defclass atom-feed-entry () ((feeds :type list :reader feed-entry-feeds :node ("atom:link" "@rel" "@type" "@href") :node-collectionp t :documentation "List of all link elements") (title :type string :reader feed-entry-title :node "atom:title/text()" :node-default "" :documentation "Content of the <title> node") (node-dom :initarg :node-dom :reader node-dom :documentation "The underlying dom for this node")) (:documentation "Common superclass for all Atom feed entries") (:metaclass atom-feed-entry-class)) (defgeneric parse-text-value (value typename) (:documentation "Converts VALUE to the type TYPE.") (:method (value (typename (eql nil))) value) (:method (value (typename (eql :string))) value) (:method (value (typename (eql :number))) (parse-number:parse-number value)) (:method (value (typename (eql :true-false))) (cond ((equal value "true") t) ((equal value "false") nil) (t (error "Unexpected value: ~s" value)))) (:method (value (typename t)) (error "Illegal type name: ~s" typename))) (defgeneric update-feed-entry-node (element destination-doc) (:documentation "Update the undelying DOM node to reflect any changes to the entry.")) (defmethod update-feed-entry-node ((element atom-feed-entry) destination-doc) (with-gdata-namespaces (let* ((class (class-of element)) (old-node (node-dom element)) (node (dom:import-node destination-doc old-node t))) (dolist (slot (closer-mop:class-slots class)) (let* ((node-descriptor (field-node slot)) (collectionp (node-collectionp slot)) (clear-function (node-clear-function slot)) (updater-function (node-updater-function slot))) (when (and node-descriptor updater-function) (when clear-function (funcall clear-function node)) (let ((value (closer-mop:slot-value-using-class class element slot))) (if collectionp (mapc #'(lambda (v) (funcall updater-function node v slot)) value) (funcall updater-function node value slot)))))) node))) (defun update-from-xpath (node entry slot-descriptor) (let* ((node-descriptor (field-node slot-descriptor))) (when (node-collectionp slot-descriptor) (error "~s can't be used if ~s is non-nil" 'update-from-xpath 'collectionp)) (unless (stringp node-descriptor) (error "destructured nodes can't be updated yet")) (setf (dom:node-value (xpath:first-node (xpath:evaluate node-descriptor node))) entry))) (defun %read-subpaths (pathlist node) (mapcar #'(lambda (descriptor) ;; The subpath can either be a string designating an xpath that specified string data, or a list with two elements , an xpath and a type designator (let* ((path (if (listp descriptor) (car descriptor) descriptor)) (type (if (listp descriptor) (cadr descriptor) nil)) (n (xpath:first-node (xpath:evaluate path node)))) (if n (parse-text-value (dom:node-value n) type) nil))) pathlist)) (defmethod initialize-instance :after ((obj atom-feed-entry) &key node-dom &allow-other-keys) (with-gdata-namespaces (let ((class (class-of obj))) (dolist (slot (closer-mop:class-slots class)) (let* ((node-descriptor (field-node slot)) (collectionp (node-collectionp slot)) (type (field-node-type slot))) (cond ((null node-descriptor) nil) ((typep node-descriptor 'string) (let ((nodes (xpath:evaluate node-descriptor node-dom))) (setf (closer-mop:slot-value-using-class class obj slot) (if collectionp (xpath:map-node-set->list #'(lambda (n) (parse-text-value (dom:node-value n) type)) nodes) (if (xpath:node-set-empty-p nodes) (node-default slot) (parse-text-value (dom:node-value (xpath:first-node nodes)) type)))))) ((typep node-descriptor 'list) (let ((nodes (xpath:evaluate (car node-descriptor) node-dom))) (setf (closer-mop:slot-value-using-class class obj slot) (if collectionp (xpath:map-node-set->list #'(lambda (n) (%read-subpaths (cdr node-descriptor) n)) nodes) (if (xpath:node-set-empty-p nodes) (node-default slot) (%read-subpaths (cdr node-descriptor) (xpath:first-node nodes))))))) (t (error "Illegal node format: ~s" node-descriptor)))))))) (defmethod print-object ((obj atom-feed-entry) out) (print-unreadable-safely (title) obj out (format out "~s" title))) (defun find-feed-from-atom-feed-entry (entry rel &optional (type +ATOM-XML-MIME-TYPE+)) (check-type entry atom-feed-entry) (let ((found-feed (find-if #'(lambda (feed) (and (equal (car feed) rel) (equal (cadr feed) type))) (feed-entry-feeds entry)))) (unless found-feed (error "Feed not found. rel=~s type=~s" rel type)) (caddr found-feed))) ;;; ;;; Loading of feeds ;;; (defgeneric load-atom-feed (document class-name) (:documentation "Loads an atom feed into a list of atom-feed-entry instances")) (defmethod load-atom-feed (document (class symbol)) (load-atom-feed document (find-class class))) (defmethod load-atom-feed (document (class atom-feed-entry-class)) ;; (dom:map-document (cxml:make-namespace-normalizer (cxml:make-character-stream-sink *standard-output*)) document) (with-gdata-namespaces (xpath:map-node-set->list #'(lambda (n) (make-instance class :node-dom n)) (xpath:evaluate "/atom:feed/atom:entry" document)))) (defun load-atom-feed-url (url class &key (session *gdata-session*) (version "3.0")) (load-atom-feed (load-and-parse url :session session :version version) class)) (defun load-feed (url class &key (session *gdata-session*) (version "3.0")) (let ((doc (load-and-parse url :session session :version version))) (make-instance 'feed :node-dom doc :entry-type class)))
null
https://raw.githubusercontent.com/lokedhs/cl-gdata/3ca1ed63e358ccb4bfbbaa5f09755cc8ef980db6/src/atom.lisp
lisp
Feed class The subpath can either be a string designating an xpath that specified string data, Loading of feeds (dom:map-document (cxml:make-namespace-normalizer (cxml:make-character-stream-sink *standard-output*)) document)
(in-package :cl-gdata-misc) (alexandria:define-constant +ATOM-TAG-FEED+ "#feed" :test 'equal) (alexandria:define-constant +ATOM-TAG-EDIT+ "edit" :test 'equal) (alexandria:define-constant +ATOM-XML-MIME-TYPE+ "application/atom+xml" :test 'equal) (defclass node-dom-mixin () ((feeds :type list :initarg :feeds :reader document-feeds :documentation "A list of links from this document. Each entry is a list of the three attributes in a \"link\" node: \"rel\", \"type\", \"href\".") (node-dom :initarg :node-dom :reader node-dom :documentation "The DOM node that was used to initialise this document"))) (defmethod initialize-instance :after ((node node-dom-mixin) &key node-dom &allow-other-keys) (when node-dom (with-slots (feeds) node (with-gdata-namespaces (setf feeds (xpath:map-node-set->list #'(lambda (n) (list (dom:get-attribute n "rel") (dom:get-attribute n "type") (dom:get-attribute n "href"))) (xpath:evaluate "atom:link" node-dom))))))) (defun find-document-feed (document rel type) "This version should be eliminated once all existing code has been moved to atom-feed-entry instances" (check-type document node-dom-mixin) (let ((found-feed (find-if #'(lambda (feed) (and (equal (car feed) rel) (equal (cadr feed) type))) (document-feeds document)))) (unless found-feed (error "Feed not found. rel=~s type=~s" rel type)) (caddr found-feed))) (defclass feed (node-dom-mixin) ((etag :type string :reader feed-etag) (entry-list :type list :reader feed-entry-list) (entry-type :type symbol :initarg :entry-type :initform (error "~s needed when instantiating ~s" :entry-type 'feed) :reader feed-entry-type)) (:documentation "Class that holds the data for an entire feed.")) (defmethod initialize-instance :after ((obj feed) &key &allow-other-keys) (with-gdata-namespaces (setf (slot-value obj 'etag) (value-by-xpath "/atom:feed/@gd:etag" (node-dom obj))) (setf (slot-value obj 'entry-list) (load-atom-feed (node-dom obj) (feed-entry-type obj))))) MOP stuff (defclass atom-feed-entry-class (standard-class) () (:documentation "Metaclass for atom feed entry classes.")) (defmethod closer-mop:validate-superclass ((class atom-feed-entry-class) (superclass standard-object)) t) (defclass atom-feed-entry-slot-definition-mixin () ((field-node :initarg :node :accessor field-node) (field-node-collectionp :initarg :node-collectionp :accessor node-collectionp) (field-node-type :initarg :node-type :accessor field-node-type) (field-node-default :initarg :node-default :accessor node-default) (field-node-clear-function :initarg :node-clear-function :accessor node-clear-function) (field-node-updater-function :initarg :node-updater-function :accessor node-updater-function))) (defclass atom-feed-entry-direct-slot-definition (atom-feed-entry-slot-definition-mixin closer-mop:standard-direct-slot-definition) ()) (defclass atom-feed-entry-effective-slot-definition (atom-feed-entry-slot-definition-mixin closer-mop:standard-effective-slot-definition) ()) (defmethod closer-mop:direct-slot-definition-class ((class atom-feed-entry-class) &rest initargs) (declare (ignore initargs)) (find-class 'atom-feed-entry-direct-slot-definition)) (defmethod closer-mop:effective-slot-definition-class ((class atom-feed-entry-class) &rest initargs) (declare (ignore initargs)) (find-class 'atom-feed-entry-effective-slot-definition)) (defun ensure-slot-value (instance field-name &optional default-value) "Returns the value of slot FIELD-NAME in INSTANCE. If the slot is unbound, return DEFAULT-VALUE." (if (and (slot-exists-p instance field-name) (slot-boundp instance field-name)) (slot-value instance field-name) default-value)) (defmethod closer-mop:compute-effective-slot-definition ((class atom-feed-entry-class) slot-name direct-slots) (let ((result (call-next-method))) (setf (field-node result) (ensure-slot-value (car direct-slots) 'field-node)) (setf (node-collectionp result) (ensure-slot-value (car direct-slots) 'field-node-collectionp)) (setf (node-default result) (ensure-slot-value (car direct-slots) 'field-node-default)) (setf (field-node-type result) (ensure-slot-value (car direct-slots) 'field-node-type)) (setf (node-clear-function result) (ensure-slot-value (car direct-slots) 'field-node-clear-function)) (setf (node-updater-function result) (ensure-slot-value (car direct-slots) 'field-node-updater-function)) result)) (defclass atom-feed-entry () ((feeds :type list :reader feed-entry-feeds :node ("atom:link" "@rel" "@type" "@href") :node-collectionp t :documentation "List of all link elements") (title :type string :reader feed-entry-title :node "atom:title/text()" :node-default "" :documentation "Content of the <title> node") (node-dom :initarg :node-dom :reader node-dom :documentation "The underlying dom for this node")) (:documentation "Common superclass for all Atom feed entries") (:metaclass atom-feed-entry-class)) (defgeneric parse-text-value (value typename) (:documentation "Converts VALUE to the type TYPE.") (:method (value (typename (eql nil))) value) (:method (value (typename (eql :string))) value) (:method (value (typename (eql :number))) (parse-number:parse-number value)) (:method (value (typename (eql :true-false))) (cond ((equal value "true") t) ((equal value "false") nil) (t (error "Unexpected value: ~s" value)))) (:method (value (typename t)) (error "Illegal type name: ~s" typename))) (defgeneric update-feed-entry-node (element destination-doc) (:documentation "Update the undelying DOM node to reflect any changes to the entry.")) (defmethod update-feed-entry-node ((element atom-feed-entry) destination-doc) (with-gdata-namespaces (let* ((class (class-of element)) (old-node (node-dom element)) (node (dom:import-node destination-doc old-node t))) (dolist (slot (closer-mop:class-slots class)) (let* ((node-descriptor (field-node slot)) (collectionp (node-collectionp slot)) (clear-function (node-clear-function slot)) (updater-function (node-updater-function slot))) (when (and node-descriptor updater-function) (when clear-function (funcall clear-function node)) (let ((value (closer-mop:slot-value-using-class class element slot))) (if collectionp (mapc #'(lambda (v) (funcall updater-function node v slot)) value) (funcall updater-function node value slot)))))) node))) (defun update-from-xpath (node entry slot-descriptor) (let* ((node-descriptor (field-node slot-descriptor))) (when (node-collectionp slot-descriptor) (error "~s can't be used if ~s is non-nil" 'update-from-xpath 'collectionp)) (unless (stringp node-descriptor) (error "destructured nodes can't be updated yet")) (setf (dom:node-value (xpath:first-node (xpath:evaluate node-descriptor node))) entry))) (defun %read-subpaths (pathlist node) (mapcar #'(lambda (descriptor) or a list with two elements , an xpath and a type designator (let* ((path (if (listp descriptor) (car descriptor) descriptor)) (type (if (listp descriptor) (cadr descriptor) nil)) (n (xpath:first-node (xpath:evaluate path node)))) (if n (parse-text-value (dom:node-value n) type) nil))) pathlist)) (defmethod initialize-instance :after ((obj atom-feed-entry) &key node-dom &allow-other-keys) (with-gdata-namespaces (let ((class (class-of obj))) (dolist (slot (closer-mop:class-slots class)) (let* ((node-descriptor (field-node slot)) (collectionp (node-collectionp slot)) (type (field-node-type slot))) (cond ((null node-descriptor) nil) ((typep node-descriptor 'string) (let ((nodes (xpath:evaluate node-descriptor node-dom))) (setf (closer-mop:slot-value-using-class class obj slot) (if collectionp (xpath:map-node-set->list #'(lambda (n) (parse-text-value (dom:node-value n) type)) nodes) (if (xpath:node-set-empty-p nodes) (node-default slot) (parse-text-value (dom:node-value (xpath:first-node nodes)) type)))))) ((typep node-descriptor 'list) (let ((nodes (xpath:evaluate (car node-descriptor) node-dom))) (setf (closer-mop:slot-value-using-class class obj slot) (if collectionp (xpath:map-node-set->list #'(lambda (n) (%read-subpaths (cdr node-descriptor) n)) nodes) (if (xpath:node-set-empty-p nodes) (node-default slot) (%read-subpaths (cdr node-descriptor) (xpath:first-node nodes))))))) (t (error "Illegal node format: ~s" node-descriptor)))))))) (defmethod print-object ((obj atom-feed-entry) out) (print-unreadable-safely (title) obj out (format out "~s" title))) (defun find-feed-from-atom-feed-entry (entry rel &optional (type +ATOM-XML-MIME-TYPE+)) (check-type entry atom-feed-entry) (let ((found-feed (find-if #'(lambda (feed) (and (equal (car feed) rel) (equal (cadr feed) type))) (feed-entry-feeds entry)))) (unless found-feed (error "Feed not found. rel=~s type=~s" rel type)) (caddr found-feed))) (defgeneric load-atom-feed (document class-name) (:documentation "Loads an atom feed into a list of atom-feed-entry instances")) (defmethod load-atom-feed (document (class symbol)) (load-atom-feed document (find-class class))) (defmethod load-atom-feed (document (class atom-feed-entry-class)) (with-gdata-namespaces (xpath:map-node-set->list #'(lambda (n) (make-instance class :node-dom n)) (xpath:evaluate "/atom:feed/atom:entry" document)))) (defun load-atom-feed-url (url class &key (session *gdata-session*) (version "3.0")) (load-atom-feed (load-and-parse url :session session :version version) class)) (defun load-feed (url class &key (session *gdata-session*) (version "3.0")) (let ((doc (load-and-parse url :session session :version version))) (make-instance 'feed :node-dom doc :entry-type class)))
e22fd24287539eddf0c9e221699f97354b471626af0bdfcef2852ff070fed892
fulcrologic/fulcro-rad-tutorial
client.cljs
(ns com.example.client (:require [com.example.ui :as ui :refer [Root]] [com.example.ui.login-dialog :refer [LoginForm]] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.mutations :as m] [com.fulcrologic.rad.application :as rad-app] [com.fulcrologic.rad.authorization :as auth] [com.fulcrologic.rad.rendering.semantic-ui.semantic-ui-controls :as sui] [com.fulcrologic.fulcro.algorithms.timbre-support :refer [console-appender prefix-output-fn]] [taoensso.timbre :as log] [com.fulcrologic.rad.type-support.date-time :as datetime] [com.fulcrologic.rad.routing.html5-history :as hist5 :refer [html5-history]] [com.fulcrologic.rad.routing.history :as history] [com.fulcrologic.rad.routing :as routing])) (m/defmutation fix-route "Mutation. Called after auth startup. Looks at the session. If the user is not logged in, it triggers authentication" [_] (action [{:keys [app]}] (let [logged-in (auth/verified-authorities app)] (if (empty? logged-in) (routing/route-to! app ui/LandingPage {}) (hist5/restore-route! app ui/LandingPage {}))))) (defonce app (rad-app/fulcro-rad-app {:client-did-mount (fn [app] (auth/start! app [LoginForm] {:after-session-check `fix-route}))})) (defn refresh [] ;; hot code reload of installed controls (log/info "Reinstalling controls") (rad-app/install-ui-controls! app sui/all-controls) (app/mount! app Root "app")) (defn init [] (log/info "Starting App") (log/merge-config! {:output-fn prefix-output-fn :appenders {:console (console-appender)}}) ;; a default tz until they log in (datetime/set-timezone! "America/Los_Angeles") (history/install-route-history! app (html5-history)) (rad-app/install-ui-controls! app sui/all-controls) (app/mount! app Root "app"))
null
https://raw.githubusercontent.com/fulcrologic/fulcro-rad-tutorial/809b8f8833363be7dc0c9a66307b1fa164da4d70/src/main/com/example/client.cljs
clojure
hot code reload of installed controls a default tz until they log in
(ns com.example.client (:require [com.example.ui :as ui :refer [Root]] [com.example.ui.login-dialog :refer [LoginForm]] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.mutations :as m] [com.fulcrologic.rad.application :as rad-app] [com.fulcrologic.rad.authorization :as auth] [com.fulcrologic.rad.rendering.semantic-ui.semantic-ui-controls :as sui] [com.fulcrologic.fulcro.algorithms.timbre-support :refer [console-appender prefix-output-fn]] [taoensso.timbre :as log] [com.fulcrologic.rad.type-support.date-time :as datetime] [com.fulcrologic.rad.routing.html5-history :as hist5 :refer [html5-history]] [com.fulcrologic.rad.routing.history :as history] [com.fulcrologic.rad.routing :as routing])) (m/defmutation fix-route "Mutation. Called after auth startup. Looks at the session. If the user is not logged in, it triggers authentication" [_] (action [{:keys [app]}] (let [logged-in (auth/verified-authorities app)] (if (empty? logged-in) (routing/route-to! app ui/LandingPage {}) (hist5/restore-route! app ui/LandingPage {}))))) (defonce app (rad-app/fulcro-rad-app {:client-did-mount (fn [app] (auth/start! app [LoginForm] {:after-session-check `fix-route}))})) (defn refresh [] (log/info "Reinstalling controls") (rad-app/install-ui-controls! app sui/all-controls) (app/mount! app Root "app")) (defn init [] (log/info "Starting App") (log/merge-config! {:output-fn prefix-output-fn :appenders {:console (console-appender)}}) (datetime/set-timezone! "America/Los_Angeles") (history/install-route-history! app (html5-history)) (rad-app/install-ui-controls! app sui/all-controls) (app/mount! app Root "app"))
0b06803c298d5902dba662e9eae5cbcc2a172dbb4089f1fcbe0a4f8d83e612a7
coq/coq
declaremods.ml
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Pp open CErrors open Util open Names open Declarations open Entries open Libnames open Libobject open Mod_subst * { 6 Inlining levels } (** Rigid / flexible module signature *) type 'a module_signature = | Enforce of 'a (** ... : T *) | Check of 'a list (** ... <: T1 <: T2, possibly empty *) (** Which module inline annotations should we honor, either None or the ones whose level is less or equal to the given integer *) type inline = | NoInline | DefaultInline | InlineAt of int let default_inline () = Some (Flags.get_inline_level ()) let inl2intopt = function | NoInline -> None | InlineAt i -> Some i | DefaultInline -> default_inline () (** These functions register the visibility of the module and iterates through its components. They are called by plenty of module functions *) let consistency_checks exists dir = if exists then let _ = try Nametab.locate_module (qualid_of_dirpath dir) with Not_found -> user_err (DirPath.print dir ++ str " should already exist!") in () else if Nametab.exists_module dir then user_err (DirPath.print dir ++ str " already exists.") let rec get_module_path = function | MEident mp -> mp | MEwith (me,_) -> get_module_path me | MEapply (me,_) -> get_module_path me let type_of_mod mp env = function | true -> (Environ.lookup_module mp env).mod_type | false -> (Environ.lookup_modtype mp env).mod_type * { 6 Name management } Auxiliary functions to transform full_path and kernel_name given by Lib into ModPath.t and DirPath.t needed for modules Auxiliary functions to transform full_path and kernel_name given by Lib into ModPath.t and DirPath.t needed for modules *) let mp_of_kn kn = let mp,l = KerName.repr kn in MPdot (mp,l) let dir_of_sp sp = let dir,id = repr_path sp in add_dirpath_suffix dir id * The [ ModActions ] abstraction represent operations on modules that are specific to a given stage . Two instances are defined below , for Synterp and Interp . that are specific to a given stage. Two instances are defined below, for Synterp and Interp. *) module type ModActions = sig type typexpr type env val stage : Summary.Stage.t val substobjs_table_name : string val modobjs_table_name : string val enter_module : ModPath.t -> DirPath.t -> int -> unit val enter_modtype : ModPath.t -> full_path -> int -> unit val open_module : open_filter -> ModPath.t -> DirPath.t -> int -> unit module Lib : Lib.StagedLibS (** Create the substitution corresponding to some functor applications *) val compute_subst : is_mod:bool -> env -> MBId.t list -> ModPath.t -> ModPath.t list -> Entries.inline -> MBId.t list * substitution end module SynterpActions : ModActions with type env = unit with type typexpr = Constrexpr.universe_decl_expr option * Constrexpr.constr_expr = struct type typexpr = Constrexpr.universe_decl_expr option * Constrexpr.constr_expr type env = unit let stage = Summary.Stage.Synterp let substobjs_table_name = "MODULE-SYNTAX-SUBSTOBJS" let modobjs_table_name = "MODULE-SYNTAX-OBJS" let enter_module obj_mp obj_dir i = consistency_checks false obj_dir; Nametab.push_module (Until i) obj_dir obj_mp let enter_modtype mp sp i = if Nametab.exists_modtype sp then anomaly (pr_path sp ++ str " already exists."); Nametab.push_modtype (Nametab.Until i) sp mp let open_module f obj_mp obj_dir i = consistency_checks true obj_dir; if in_filter ~cat:None f then Nametab.push_module (Nametab.Exactly i) obj_dir obj_mp module Lib = Lib.Synterp let rec compute_subst () mbids mp_l inl = match mbids,mp_l with | _,[] -> mbids,empty_subst | [],r -> user_err Pp.(str "Application of a functor with too few arguments.") | mbid::mbids,mp::mp_l -> let mbid_left,subst = compute_subst () mbids mp_l inl in mbid_left,join (map_mbid mbid mp empty_delta_resolver) subst let compute_subst ~is_mod () mbids mp1 mp_l inl = compute_subst () mbids mp_l inl end module InterpActions : ModActions with type env = Environ.env with type typexpr = Constr.t * Univ.AbstractContext.t option = struct type typexpr = Constr.t * Univ.AbstractContext.t option type env = Environ.env let stage = Summary.Stage.Interp let substobjs_table_name = "MODULE-SUBSTOBJS" let modobjs_table_name = "MODULE-OBJS" * { 6 Current module type information } This information is stored by each [ start_modtype ] for use in a later [ end_modtype ] . This information is stored by each [start_modtype] for use in a later [end_modtype]. *) let enter_module obj_mp obj_dir i = () let enter_modtype mp sp i = () let open_module f obj_mp obj_dir i = () module Lib = Lib.Interp let rec compute_subst env mbids sign mp_l inl = match mbids,mp_l with | _,[] -> mbids,empty_subst | [],r -> user_err Pp.(str "Application of a functor with too few arguments.") | mbid::mbids,mp::mp_l -> let farg_id, farg_b, fbody_b = Modops.destr_functor sign in let mb = Environ.lookup_module mp env in let mbid_left,subst = compute_subst env mbids fbody_b mp_l inl in let resolver = if Modops.is_functor mb.mod_type then empty_delta_resolver else Modops.inline_delta_resolver env inl mp farg_id farg_b mb.mod_delta in mbid_left,join (map_mbid mbid mp resolver) subst let compute_subst ~is_mod env mbids mp1 mp_l inl = let typ = type_of_mod mp1 env is_mod in compute_subst env mbids typ mp_l inl end type module_objects = { module_prefix : Nametab.object_prefix; module_substituted_objects : Libobject.t list; module_keep_objects : Libobject.t list; } * The [ StagedModS ] abstraction describes module operations at a given stage . module type StagedModS = sig type typexpr type env val get_module_sobjs : bool -> env -> Entries.inline -> typexpr module_alg_expr -> substitutive_objects val do_module : (int -> Nametab.object_prefix -> Libobject.t list -> unit) -> int -> DirPath.t -> ModPath.t -> substitutive_objects -> Libobject.t list -> unit val load_objects : int -> Nametab.object_prefix -> Libobject.t list -> unit val open_object : open_filter -> int -> Nametab.object_prefix * Libobject.t -> unit val collect_modules : (open_filter * ModPath.t) list -> open_filter MPmap.t * (open_filter * (Nametab.object_prefix * Libobject.t)) list -> open_filter MPmap.t * (open_filter * (Nametab.object_prefix * Libobject.t)) list val add_leaf : Libobject.t -> unit val add_leaves : Libobject.t list -> unit val expand_aobjs : Libobject.algebraic_objects -> Libobject.t list val get_applications : typexpr module_alg_expr -> ModPath.t * ModPath.t list val debug_print_modtab : unit -> Pp.t module ModObjs : sig val all : unit -> module_objects MPmap.t end end (** Some utilities about substitutive objects : substitution, expansion *) let sobjs_no_functor (mbids,_) = List.is_empty mbids let subst_filtered sub (f,mp as x) = let mp' = subst_mp sub mp in if mp == mp' then x else f, mp' let rec subst_aobjs sub = function | Objs o as objs -> let o' = subst_objects sub o in if o == o' then objs else Objs o' | Ref (mp, sub0) as r -> let sub0' = join sub0 sub in if sub0' == sub0 then r else Ref (mp, sub0') and subst_sobjs sub (mbids,aobjs as sobjs) = let aobjs' = subst_aobjs sub aobjs in if aobjs' == aobjs then sobjs else (mbids, aobjs') and subst_objects subst seg = let subst_one node = match node with | AtomicObject obj -> let obj' = Libobject.subst_object (subst,obj) in if obj' == obj then node else AtomicObject obj' | ModuleObject (id, sobjs) -> let sobjs' = subst_sobjs subst sobjs in if sobjs' == sobjs then node else ModuleObject (id, sobjs') | ModuleTypeObject (id, sobjs) -> let sobjs' = subst_sobjs subst sobjs in if sobjs' == sobjs then node else ModuleTypeObject (id, sobjs') | IncludeObject aobjs -> let aobjs' = subst_aobjs subst aobjs in if aobjs' == aobjs then node else IncludeObject aobjs' | ExportObject { mpl } -> let mpl' = List.Smart.map (subst_filtered subst) mpl in if mpl'==mpl then node else ExportObject { mpl = mpl' } | KeepObject _ -> assert false in List.Smart.map subst_one seg * The [ StagedMod ] abstraction factors out the code dealing with modules that is common to all stages . that is common to all stages. *) module StagedMod(Actions : ModActions) = struct type typexpr = Actions.typexpr type env = Actions.env * ModSubstObjs : a cache of module substitutive objects This table is common to modules and module types . - For a Module M:=N , the objects of N will be reloaded with M after substitution . - For a Module M : SIG:= ... , the module M gets its objects from SIG Invariants : - A alias ( i.e. a module path inside a Ref constructor ) should never lead to another alias , but rather to a concrete Objs constructor . We will plug later a handler dealing with missing entries in the cache . Such missing entries may come from inner parts of module types , which are n't registered by the standard libobject machinery . This table is common to modules and module types. - For a Module M:=N, the objects of N will be reloaded with M after substitution. - For a Module M:SIG:=..., the module M gets its objects from SIG Invariants: - A alias (i.e. a module path inside a Ref constructor) should never lead to another alias, but rather to a concrete Objs constructor. We will plug later a handler dealing with missing entries in the cache. Such missing entries may come from inner parts of module types, which aren't registered by the standard libobject machinery. *) module ModSubstObjs : sig val set : ModPath.t -> substitutive_objects -> unit val get : ModPath.t -> substitutive_objects val set_missing_handler : (ModPath.t -> substitutive_objects) -> unit end = struct let table = Summary.ref ~stage:Actions.stage (MPmap.empty : substitutive_objects MPmap.t) ~name:Actions.substobjs_table_name let missing_handler = ref (fun mp -> assert false) let set_missing_handler f = (missing_handler := f) let set mp objs = (table := MPmap.add mp objs !table) let get mp = try MPmap.find mp !table with Not_found -> !missing_handler mp end let expand_aobjs = function | Objs o -> o | Ref (mp, sub) -> match ModSubstObjs.get mp with | (_,Objs o) -> subst_objects sub o | _ -> assert false (* Invariant : any alias points to concrete objs *) let expand_sobjs (_,aobjs) = expand_aobjs aobjs * { 6 ModObjs : a cache of module objects } For each module , we also store a cache of " prefix " , " substituted objects " , " keep objects " . This is used for instance to implement the " Import " command . substituted objects : roughly the objects above after the substitution - we need to keep them to call open_object when the module is opened ( imported ) keep objects : The list of non - substitutive objects - as above , for each of them we will call open_object when the module is opened ( Some ) Invariants : * If the module is a functor , it wo n't appear in this cache . * Module objects in substitutive_objects part have empty substituted objects . * Modules which where created with Module M:=mexpr or with Module M : SIG . ... End M. have the keep list empty . For each module, we also store a cache of "prefix", "substituted objects", "keep objects". This is used for instance to implement the "Import" command. substituted objects : roughly the objects above after the substitution - we need to keep them to call open_object when the module is opened (imported) keep objects : The list of non-substitutive objects - as above, for each of them we will call open_object when the module is opened (Some) Invariants: * If the module is a functor, it won't appear in this cache. * Module objects in substitutive_objects part have empty substituted objects. * Modules which where created with Module M:=mexpr or with Module M:SIG. ... End M. have the keep list empty. *) module ModObjs : sig val set : ModPath.t -> module_objects -> unit val get : ModPath.t -> module_objects (* may raise Not_found *) val all : unit -> module_objects MPmap.t end = struct let table = Summary.ref ~stage:Actions.stage (MPmap.empty : module_objects MPmap.t) ~name:Actions.modobjs_table_name let set mp objs = (table := MPmap.add mp objs !table) let get mp = MPmap.find mp !table let all () = !table end * { 6 Declaration of module substitutive objects } (** Iterate some function [iter_objects] on all components of a module *) let do_module iter_objects i obj_dir obj_mp sobjs kobjs = let prefix = Nametab.{ obj_dir ; obj_mp; } in Actions.enter_module obj_mp obj_dir i; ModSubstObjs.set obj_mp sobjs; (* If we're not a functor, let's iter on the internal components *) if sobjs_no_functor sobjs then begin let objs = expand_sobjs sobjs in let module_objects = { module_prefix = prefix; module_substituted_objects = objs; module_keep_objects = kobjs; } in ModObjs.set obj_mp module_objects; iter_objects (i+1) prefix objs; iter_objects (i+1) prefix kobjs end let do_module' iter_objects i ((sp,kn),sobjs) = do_module iter_objects i (dir_of_sp sp) (mp_of_kn kn) sobjs [] * : Interactive modules and module types can not be recached ! This used to be checked here via a flag along the substobjs . This used to be checked here via a flag along the substobjs. *) * { 6 Declaration of module type substitutive objects } * : Interactive modules and module types can not be recached ! This used to be checked more properly here . This used to be checked more properly here. *) let load_modtype i sp mp sobjs = Actions.enter_modtype mp sp i; ModSubstObjs.set mp sobjs * { 6 Declaration of substitutive objects for Include } let rec load_object i (prefix, obj) = match obj with | AtomicObject o -> Libobject.load_object i (prefix, o) | ModuleObject (id,sobjs) -> let name = Lib.make_oname prefix id in do_module' load_objects i (name, sobjs) | ModuleTypeObject (id,sobjs) -> let name = Lib.make_oname prefix id in let (sp,kn) = name in load_modtype i sp (mp_of_kn kn) sobjs | IncludeObject aobjs -> load_include i (prefix, aobjs) | ExportObject _ -> () | KeepObject (id,objs) -> let name = Lib.make_oname prefix id in load_keep i (name, objs) and load_objects i prefix objs = List.iter (fun obj -> load_object i (prefix, obj)) objs and load_include i (prefix, aobjs) = let o = expand_aobjs aobjs in load_objects i prefix o and load_keep i ((sp,kn),kobjs) = (* Invariant : seg isn't empty *) let obj_dir = dir_of_sp sp and obj_mp = mp_of_kn kn in let prefix = Nametab.{ obj_dir ; obj_mp; } in let modobjs = try ModObjs.get obj_mp with Not_found -> assert false (* a substobjs should already be loaded *) in assert Nametab.(eq_op modobjs.module_prefix prefix); assert (List.is_empty modobjs.module_keep_objects); ModObjs.set obj_mp { modobjs with module_keep_objects = kobjs }; load_objects i prefix kobjs * { 6 Implementation of Import and Export commands } let mark_object f obj (exports,acc) = (exports, (f,obj)::acc) let rec collect_modules mpl acc = List.fold_left (fun acc fmp -> collect_module fmp acc) acc (List.rev mpl) and collect_module (f,mp) acc = try May raise Not_found for unknown module and for functors let modobjs = ModObjs.get mp in let prefix = modobjs.module_prefix in let acc = collect_objects f 1 prefix modobjs.module_keep_objects acc in collect_objects f 1 prefix modobjs.module_substituted_objects acc with Not_found when Actions.stage = Summary.Stage.Synterp -> acc and collect_object f i prefix obj acc = match obj with | ExportObject { mpl } -> collect_exports f i mpl acc | AtomicObject _ | IncludeObject _ | KeepObject _ | ModuleObject _ | ModuleTypeObject _ -> mark_object f (prefix,obj) acc and collect_objects f i prefix objs acc = List.fold_left (fun acc obj -> collect_object f i prefix obj acc) acc (List.rev objs) and collect_export f (f',mp) (exports,objs as acc) = match filter_and f f' with | None -> acc | Some f -> let exports' = MPmap.update mp (function | None -> Some f | Some f0 -> Some (filter_or f f0)) exports in (* If the map doesn't change there is nothing new to export. It's possible that [filter_and] or [filter_or] mangled precise filters such that we repeat uselessly, but the important [Unfiltered] case is handled correctly. *) if exports == exports' then acc else collect_module (f,mp) (exports', objs) and collect_exports f i mpl acc = if Int.equal i 1 then List.fold_left (fun acc fmp -> collect_export f fmp acc) acc (List.rev mpl) else acc let open_modtype i ((sp,kn),_) = let mp = mp_of_kn kn in let mp' = try Nametab.locate_modtype (qualid_of_path sp) with Not_found -> anomaly (pr_path sp ++ str " should already exist!"); in assert (ModPath.equal mp mp'); Nametab.push_modtype (Nametab.Exactly i) sp mp let rec open_object f i (prefix, obj) = match obj with | AtomicObject o -> Libobject.open_object f i (prefix, o) | ModuleObject (id,sobjs) -> let name = Lib.make_oname prefix id in let dir = dir_of_sp (fst name) in let mp = mp_of_kn (snd name) in open_module f i dir mp sobjs | ModuleTypeObject (id,sobjs) -> let name = Lib.make_oname prefix id in open_modtype i (name, sobjs) | IncludeObject aobjs -> open_include f i (prefix, aobjs) | ExportObject { mpl } -> open_export f i mpl | KeepObject (id,objs) -> let name = Lib.make_oname prefix id in open_keep f i (name, objs) and open_module f i obj_dir obj_mp sobjs = Actions.open_module f obj_mp obj_dir i; (* If we're not a functor, let's iter on the internal components *) if sobjs_no_functor sobjs then begin let modobjs = ModObjs.get obj_mp in open_objects f (i+1) modobjs.module_prefix modobjs.module_substituted_objects end and open_objects f i prefix objs = List.iter (fun obj -> open_object f i (prefix, obj)) objs and open_include f i (prefix, aobjs) = let o = expand_aobjs aobjs in open_objects f i prefix o and open_export f i mpl = let _,objs = collect_exports f i mpl (MPmap.empty, []) in List.iter (fun (f,o) -> open_object f 1 o) objs and open_keep f i ((sp,kn),kobjs) = let obj_dir = dir_of_sp sp and obj_mp = mp_of_kn kn in let prefix = Nametab.{ obj_dir; obj_mp; } in open_objects f i prefix kobjs let cache_include (prefix, aobjs) = let o = expand_aobjs aobjs in load_objects 1 prefix o; open_objects unfiltered 1 prefix o and cache_keep ((sp,kn),kobjs) = anomaly (Pp.str "This module should not be cached!") let cache_object (prefix, obj) = match obj with | AtomicObject o -> Libobject.cache_object (prefix, o) | ModuleObject (id,sobjs) -> let name = Lib.make_oname prefix id in do_module' load_objects 1 (name, sobjs) | ModuleTypeObject (id,sobjs) -> let name = Lib.make_oname prefix id in let (sp,kn) = name in load_modtype 0 sp (mp_of_kn kn) sobjs | IncludeObject aobjs -> cache_include (prefix, aobjs) | ExportObject { mpl } -> anomaly Pp.(str "Export should not be cached") | KeepObject (id,objs) -> let name = Lib.make_oname prefix id in cache_keep (name, objs) (* Adding operations with containers *) let add_leaf obj = cache_object (Lib.prefix (),obj); match Actions.stage with | Summary.Stage.Synterp -> Lib.Synterp.add_leaf_entry obj | Summary.Stage.Interp -> Lib.Interp.add_leaf_entry obj let add_leaves objs = let add_obj obj = begin match Actions.stage with | Summary.Stage.Synterp -> Lib.Synterp.add_leaf_entry obj | Summary.Stage.Interp -> Lib.Interp.add_leaf_entry obj end; load_object 1 (Lib.prefix (),obj) in List.iter add_obj objs * { 6 Handler for missing entries in ModSubstObjs } * Since the inner of Module Types are not added by default to the ModSubstObjs table , we compensate this by explicit traversal of Module Types inner objects when needed . Quite a hack ... the ModSubstObjs table, we compensate this by explicit traversal of Module Types inner objects when needed. Quite a hack... *) let mp_id mp id = MPdot (mp, Label.of_id id) let rec register_mod_objs mp obj = match obj with | ModuleObject (id,sobjs) -> ModSubstObjs.set (mp_id mp id) sobjs | ModuleTypeObject (id,sobjs) -> ModSubstObjs.set (mp_id mp id) sobjs | IncludeObject aobjs -> List.iter (register_mod_objs mp) (expand_aobjs aobjs) | _ -> () let handle_missing_substobjs mp = match mp with | MPdot (mp',l) -> let objs = expand_sobjs (ModSubstObjs.get mp') in List.iter (register_mod_objs mp') objs; ModSubstObjs.get mp | _ -> assert false (* Only inner parts of module types should be missing *) let () = ModSubstObjs.set_missing_handler handle_missing_substobjs * { 6 From module expression to substitutive objects } * Turn a chain of [ ] into the head ModPath.t and the list of ModPath.t parameters ( deepest param coming first ) . The left part of a [ MSEapply ] must be either [ MSEident ] or another [ MSEapply ] . list of ModPath.t parameters (deepest param coming first). The left part of a [MSEapply] must be either [MSEident] or another [MSEapply]. *) let get_applications mexpr = let rec get params = function | MEident mp -> mp, params | MEapply (fexpr, mp) -> get (mp::params) fexpr | MEwith _ -> user_err Pp.(str "Non-atomic functor application.") in get [] mexpr (** Create the objects of a "with Module" structure. *) let rec replace_module_object idl mp0 objs0 mp1 objs1 = match idl, objs0 with | _,[] -> [] | id::idl,(ModuleObject (id', sobjs))::tail when Id.equal id id' -> begin let mp_id = MPdot(mp0, Label.of_id id) in let objs = match idl with | [] -> subst_objects (map_mp mp1 mp_id empty_delta_resolver) objs1 | _ -> let objs_id = expand_sobjs sobjs in replace_module_object idl mp_id objs_id mp1 objs1 in (ModuleObject (id, ([], Objs objs)))::tail end | idl,lobj::tail -> lobj::replace_module_object idl mp0 tail mp1 objs1 * Substitutive objects of a module expression ( or module type ) let rec get_module_sobjs is_mod env inl = function | MEident mp -> begin match ModSubstObjs.get mp with | (mbids,Objs _) when not (ModPath.is_bound mp) -> (mbids,Ref (mp, empty_subst)) (* we create an alias *) | sobjs -> sobjs end | MEwith (mty, WithDef _) -> get_module_sobjs is_mod env inl mty | MEwith (mty, WithMod (idl,mp1)) -> assert (not is_mod); let sobjs0 = get_module_sobjs is_mod env inl mty in if not (sobjs_no_functor sobjs0) then user_err Pp.(str "Illegal use of a functor."); (* For now, we expand everything, to be safe *) let mp0 = get_module_path mty in let objs0 = expand_sobjs sobjs0 in let objs1 = expand_sobjs (ModSubstObjs.get mp1) in ([], Objs (replace_module_object idl mp0 objs0 mp1 objs1)) | MEapply _ as me -> let mp1, mp_l = get_applications me in let mbids, aobjs = get_module_sobjs is_mod env inl (MEident mp1) in let mbids_left,subst = Actions.compute_subst ~is_mod env mbids mp1 mp_l inl in (mbids_left, subst_aobjs subst aobjs) let debug_print_modtab () = let pr_seg = function | [] -> str "[]" | l -> str "[." ++ int (List.length l) ++ str ".]" in let pr_modinfo mp modobjs s = let objs = modobjs.module_substituted_objects @ modobjs.module_keep_objects in s ++ str (ModPath.to_string mp) ++ spc () ++ pr_seg objs in let modules = MPmap.fold pr_modinfo (ModObjs.all ()) (mt ()) in hov 0 modules end module SynterpVisitor : StagedModS with type env = SynterpActions.env with type typexpr = Constrexpr.universe_decl_expr option * Constrexpr.constr_expr = StagedMod(SynterpActions) module InterpVisitor : StagedModS with type env = InterpActions.env with type typexpr = Constr.t * Univ.AbstractContext.t option = StagedMod(InterpActions) * { 6 Modules : start , end , declare } type current_module_syntax_info = { cur_mp : ModPath.t; cur_typ : ((Constrexpr.universe_decl_expr option * Constrexpr.constr_expr) module_alg_expr * int option) option; cur_mbids : MBId.t list; } let default_module_syntax_info mp = { cur_mp = mp; cur_typ = None; cur_mbids = [] } let openmod_syntax_info = Summary.ref None ~stage:Summary.Stage.Synterp ~name:"MODULE-SYNTAX-INFO" * { 6 Current module information } This information is stored by each [ start_module ] for use in a later [ end_module ] . This information is stored by each [start_module] for use in a later [end_module]. *) type current_module_info = { cur_typ : (module_struct_entry * int option) option; (** type via ":" *) cur_typs : module_type_body list (** types via "<:" *) } let default_module_info = { cur_typ = None; cur_typs = [] } let openmod_info = Summary.ref default_module_info ~name:"MODULE-INFO" let start_library dir = let mp = Global.start_library dir in openmod_info := default_module_info; openmod_syntax_info := Some (default_module_syntax_info mp); Lib.start_compilation dir mp let set_openmod_syntax_info info = match !openmod_syntax_info with | None -> anomaly Pp.(str "bad init of openmod_syntax_info") | Some _ -> openmod_syntax_info := Some info let openmod_syntax_info () = match !openmod_syntax_info with | None -> anomaly Pp.(str "missing init of openmod_syntax_info") | Some v -> v module RawModOps = struct module Synterp = struct let build_subtypes mtys = List.map (fun (m,ann) -> let inl = inl2intopt ann in let mte, base, kind = Modintern.intern_module_ast Modintern.ModType m in (mte, base, kind, inl)) mtys let intern_arg (idl,(typ,ann)) = let inl = inl2intopt ann in let lib_dir = Lib.library_dp() in let (mty, base, kind) = Modintern.intern_module_ast Modintern.ModType typ in let sobjs = SynterpVisitor.get_module_sobjs false () inl mty in let mp0 = get_module_path mty in let map {CAst.v=id} = let dir = DirPath.make [id] in let mbid = MBId.make lib_dir id in let mp = MPbound mbid in (* We can use an empty delta resolver because we load only syntax objects *) let sobjs = subst_sobjs (map_mp mp0 mp empty_delta_resolver) sobjs in SynterpVisitor.do_module SynterpVisitor.load_objects 1 dir mp sobjs []; mbid in List.map map idl, (mty, base, kind, inl) let intern_args params = List.map intern_arg params let start_module_core id args res fs = (* Loads the parsing objects in arguments *) let args = intern_args args in let mbids = List.flatten @@ List.map (fun (mbidl,_) -> mbidl) args in let res_entry_o, sign = match res with | Enforce (res,ann) -> let inl = inl2intopt ann in let (mte, base, kind) = Modintern.intern_module_ast Modintern.ModType res in Some (mte, inl), Enforce (mte, base, kind, inl) | Check resl -> None, Check (build_subtypes resl) in let mp = ModPath.MPdot((openmod_syntax_info ()).cur_mp, Label.of_id id) in mp, res_entry_o, mbids, sign, args let start_module export id args res fs = let mp, res_entry_o, mbids, sign, args = start_module_core id args res fs in set_openmod_syntax_info { cur_mp = mp; cur_typ = res_entry_o; cur_mbids = mbids }; let prefix = Lib.Synterp.start_module export id mp fs in Nametab.(push_dir (Until 1) (prefix.obj_dir) (GlobDirRef.DirOpenModule prefix.obj_mp)); mp, args, sign let end_module_core id (m_info : current_module_syntax_info) objects fs = let {Lib.Synterp.substobjs = substitute; keepobjs = keep; anticipateobjs = special; } = objects in (* For sealed modules, we use the substitutive objects of their signatures *) let sobjs0, keep, special = match m_info.cur_typ with | None -> ([], Objs substitute), keep, special | Some (mty, inline) -> SynterpVisitor.get_module_sobjs false () inline mty, [], [] in Summary.unfreeze_summaries ~partial:true fs; let sobjs = let (ms,objs) = sobjs0 in (m_info.cur_mbids@ms,objs) in (* We substitute objects if the module is sealed by a signature *) let sobjs = match m_info.cur_typ with | None -> sobjs | Some (mty, _) -> subst_sobjs (map_mp (get_module_path mty) m_info.cur_mp empty_delta_resolver) sobjs in let node = ModuleObject (id,sobjs) in (* We add the keep objects, if any, and if this isn't a functor *) let objects = match keep, m_info.cur_mbids with | [], _ | _, _ :: _ -> special@[node] | _ -> special@[node;KeepObject (id,keep)] in (* Name consistency check : start_ vs. end_module *) Printf.eprintf " newoname=%s , oldoname=%s\n " ( string_of_path ( fst newoname ) ) ( string_of_path ( fst oldoname ) ) ; assert ( DirPath.equal ( ) ; assert ( ModPath.equal oldprefix . Nametab.obj_mp mp ) ; Printf.eprintf "newoname=%s, oldoname=%s\n" (string_of_path (fst newoname)) (string_of_path (fst oldoname)); assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp); assert (ModPath.equal oldprefix.Nametab.obj_mp mp); *) Printf.eprintf " newoname=%s , oldoname=%s\n " ( string_of_path ( fst newoname ) ) ( string_of_path ( fst oldoname ) ) ; Printf.eprintf " newoname=%s , cur_mp=%s\n " ( ModPath.debug_to_string ( mp_of_kn ( snd newoname ) ) ) ( ModPath.debug_to_string m_info.cur_mp ) ; m_info.cur_mp, objects let end_module () = let oldprefix,fs,objects = Lib.Synterp.end_module () in let m_info = openmod_syntax_info () in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let mp,objects = end_module_core id m_info objects fs in let () = SynterpVisitor.add_leaves objects in (* Name consistency check : kernel vs. library *) CDebug.debug_synterp ( fun ( ) - > Pp.(str"prefix= " + + DirPath.print ( ( ) + + str " , " + + DirPath.print olddp ) ) ; assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp); mp let get_functor_sobjs is_mod inl (mbids,mexpr) = let (mbids0, aobjs) = SynterpVisitor.get_module_sobjs is_mod () inl mexpr in (mbids @ mbids0, aobjs) let declare_module id args res mexpr_o fs = (* We simulate the beginning of an interactive module, then we adds the module parameters to the global env. *) let mp = ModPath.MPdot((openmod_syntax_info ()).cur_mp, Label.of_id id) in let args = intern_args args in let mbids = List.flatten @@ List.map fst args in let mty_entry_o = match res with | Enforce (mty,ann) -> let inl = inl2intopt ann in let (mte, base, kind) = Modintern.intern_module_ast Modintern.ModType mty in Enforce (mte, base, kind, inl) | Check mtys -> Check (build_subtypes mtys) in let mexpr_entry_o = match mexpr_o with | None -> None | Some (mexpr,ann) -> let (mte, base, kind) = Modintern.intern_module_ast Modintern.Module mexpr in Some (mte, base, kind, inl2intopt ann) in let sobjs, mp0 = match mexpr_entry_o, mty_entry_o with | None, Check _ -> assert false (* No body, no type ... *) | _, Enforce (typ,_,_,inl_res) -> get_functor_sobjs false inl_res (mbids,typ), get_module_path typ | Some (body, _, _, inl_expr), Check _ -> get_functor_sobjs true inl_expr (mbids,body), get_module_path body in (* Undo the simulated interactive building of the module and declare the module as a whole *) Summary.unfreeze_summaries ~partial:true fs; (* We can use an empty delta resolver on syntax objects *) let sobjs = subst_sobjs (map_mp mp0 mp empty_delta_resolver) sobjs in ignore (SynterpVisitor.add_leaf (ModuleObject (id,sobjs))); mp, args, mexpr_entry_o, mty_entry_o end module Interp = struct * { 6 Auxiliary functions concerning subtyping checks } let check_sub mtb sub_mtb_l = let fold sub_mtb (cst, env) = let state = ((Environ.universes env, cst), Reductionops.inferred_universes) in let graph, cst = Subtyping.check_subtypes state env mtb sub_mtb in (cst, Environ.set_universes graph env) in let cst, _ = List.fold_right fold sub_mtb_l (Univ.Constraints.empty, Global.env ()) in Global.add_constraints cst (** This function checks if the type calculated for the module [mp] is a "<:"-like subtype of all signatures in [sub_mtb_l]. Uses only the global environment. *) let check_subtypes mp sub_mtb_l = let mb = try Global.lookup_module mp with Not_found -> assert false in let mtb = Modops.module_type_of_module mb in check_sub mtb sub_mtb_l (** Same for module type [mp] *) let check_subtypes_mt mp sub_mtb_l = let mtb = try Global.lookup_modtype mp with Not_found -> assert false in check_sub mtb sub_mtb_l let current_modresolver () = fst @@ Safe_typing.delta_of_senv @@ Global.safe_env () let current_struct () = let struc = Safe_typing.structure_body_of_safe_env @@ Global.safe_env () in NoFunctor (List.rev struc) (** Prepare the module type list for check of subtypes *) let build_subtypes env mp args mtys = let (ctx, ans) = List.fold_left_map (fun ctx (mte,base,kind,inl) -> let mte, ctx' = Modintern.interp_module_ast env Modintern.ModType base mte in let env = Environ.push_context_set ~strict:true ctx' env in let ctx = Univ.ContextSet.union ctx ctx' in let state = ((Environ.universes env, Univ.Constraints.empty), Reductionops.inferred_universes) in let mtb, (_, cst) = Mod_typing.translate_modtype state env mp inl (args,mte) in let ctx = Univ.ContextSet.add_constraints cst ctx in ctx, mtb) Univ.ContextSet.empty mtys in (ans, ctx) (** Process a declaration of functor parameter(s) (Id1 .. Idn : Typ) i.e. possibly multiple names with the same module type. Global environment is updated on the fly. Objects in these parameters are also loaded. Output is accumulated on top of [acc] (in reverse order). *) let intern_arg (acc, cst) (mbidl,(mty, base, kind, inl)) = let env = Global.env() in let (mty, cst') = Modintern.interp_module_ast env kind base mty in let () = Global.push_context_set ~strict:true cst' in let () = let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, (_, cst) = Mod_typing.translate_modtype state (Global.env ()) base inl ([], mty) in Global.add_constraints cst in let env = Global.env () in let sobjs = InterpVisitor.get_module_sobjs false env inl mty in let mp0 = get_module_path mty in let fold acc mbid = let id = MBId.to_id mbid in let dir = DirPath.make [id] in let mp = MPbound mbid in let resolver = Global.add_module_parameter mbid mty inl in let sobjs = subst_sobjs (map_mp mp0 mp resolver) sobjs in InterpVisitor.do_module InterpVisitor.load_objects 1 dir mp sobjs []; (mbid,mty,inl)::acc in let acc = List.fold_left fold acc mbidl in (acc, Univ.ContextSet.union cst cst') * Process a list of declarations of functor parameters ( Id11 .. Id1n : Typ1) .. (Idk1 .. Idkm : Typk ) Global environment is updated on the fly . The calls to [ interp_modast ] should be interleaved with these env updates , otherwise some " with Definition " could be rejected . Returns a list of mbids and entries ( in reversed order ) . This used to be a [ List.concat ( List.map ... ) ] , but this should be more efficient and independent of [ List.map ] eval order . (Id11 .. Id1n : Typ1)..(Idk1 .. Idkm : Typk) Global environment is updated on the fly. The calls to [interp_modast] should be interleaved with these env updates, otherwise some "with Definition" could be rejected. Returns a list of mbids and entries (in reversed order). This used to be a [List.concat (List.map ...)], but this should be more efficient and independent of [List.map] eval order. *) let intern_args params = let args, ctx = List.fold_left intern_arg ([], Univ.ContextSet.empty) params in List.rev args, ctx let start_module_core id args res fs = let mp = Global.start_module id in let params, ctx = intern_args args in let () = Global.push_context_set ~strict:true ctx in let env = Global.env () in let res_entry_o, subtyps, ctx' = match res with | Enforce (mte, base, kind, inl) -> let (mte, ctx) = Modintern.interp_module_ast env kind base mte in let env = Environ.push_context_set ~strict:true ctx env in (* We check immediately that mte is well-formed *) let state = ((Environ.universes env, Univ.Constraints.empty), Reductionops.inferred_universes) in let _, _, _, (_, cst) = Mod_typing.translate_mse state env None inl mte in let ctx = Univ.ContextSet.add_constraints cst ctx in Some (mte, inl), [], ctx | Check resl -> let typs, ctx = build_subtypes env mp params resl in None, typs, ctx in let () = Global.push_context_set ~strict:true ctx' in mp, res_entry_o, subtyps, params, Univ.ContextSet.union ctx ctx' let start_module export id args res fs = let mp, res_entry_o, subtyps, _, _ = start_module_core id args res fs in openmod_info := { cur_typ = res_entry_o; cur_typs = subtyps }; let _ = Lib.Interp.start_module export id mp fs in mp let end_module_core id m_info objects fs = let {Lib.Interp.substobjs = substitute; keepobjs = keep; anticipateobjs = special; } = objects in (* For sealed modules, we use the substitutive objects of their signatures *) let sobjs0, keep = match m_info.cur_typ with | None -> ([], Objs substitute), keep | Some (mty, inline) -> InterpVisitor.get_module_sobjs false (Global.env()) inline mty, [] in let struc = current_struct () in let restype' = Option.map (fun (ty,inl) -> (([],ty),inl)) m_info.cur_typ in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, (_, cst) = Mod_typing.finalize_module state (Global.env ()) (Global.current_modpath ()) (struc, current_modresolver ()) restype' in let () = Global.add_constraints cst in let mp,mbids,resolver = Global.end_module fs id m_info.cur_typ in let sobjs = let (ms,objs) = sobjs0 in (mbids@ms,objs) in let () = check_subtypes mp m_info.cur_typs in (* We substitute objects if the module is sealed by a signature *) let sobjs = match m_info.cur_typ with | None -> sobjs | Some (mty, _) -> subst_sobjs (map_mp (get_module_path mty) mp resolver) sobjs in let node = ModuleObject (id,sobjs) in (* We add the keep objects, if any, and if this isn't a functor *) let objects = match keep, mbids with | [], _ | _, _ :: _ -> special@[node] | _ -> special@[node;KeepObject (id,keep)] in mp, objects let end_module () = let oldprefix,fs,objects = Lib.Interp.end_module () in let m_info = !openmod_info in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let mp,objects = end_module_core id m_info objects fs in let () = InterpVisitor.add_leaves objects in (* Name consistency check : kernel vs. library *) assert (ModPath.equal oldprefix.Nametab.obj_mp mp); mp let get_functor_sobjs is_mod env inl (params,mexpr) = let (mbids, aobjs) = InterpVisitor.get_module_sobjs is_mod env inl mexpr in (List.map pi1 params @ mbids, aobjs) TODO cleanup push universes directly to global env let declare_module id args res mexpr_o fs = (* We simulate the beginning of an interactive module, then we adds the module parameters to the global env. *) let mp, mty_entry_o, subs, params, ctx = start_module_core id args res fs in let env = Global.env () in let mexpr_entry_o, inl_expr, ctx' = match mexpr_o with | None -> None, default_inline (), Univ.ContextSet.empty | Some (mte, base, kind, inl) -> let (mte, ctx) = Modintern.interp_module_ast env kind base mte in Some mte, inl, ctx in let env = Environ.push_context_set ~strict:true ctx' env in let ctx = Univ.ContextSet.union ctx ctx' in let entry, inl_res = match mexpr_entry_o, mty_entry_o with | None, None -> assert false (* No body, no type ... *) | None, Some (typ, inl) -> MType (params, typ), inl | Some body, otyp -> MExpr (params, body, Option.map fst otyp), Option.cata snd (default_inline ()) otyp in let sobjs, mp0 = match entry with | MType (_,mte) | MExpr (_,_,Some mte) -> get_functor_sobjs false env inl_res (params,mte), get_module_path mte | MExpr (_,me,None) -> get_functor_sobjs true env inl_expr (params,me), get_module_path me in (* Undo the simulated interactive building of the module and declare the module as a whole *) Summary.unfreeze_summaries ~partial:true fs; let inl = match inl_expr with | None -> None | _ -> inl_res in let () = Global.push_context_set ~strict:true ctx in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, (_, cst) = Mod_typing.translate_module state (Global.env ()) mp inl entry in let () = Global.add_constraints cst in let mp_env,resolver = Global.add_module id entry inl in (* Name consistency check : kernel vs. library *) assert (ModPath.equal mp (mp_of_kn (Lib.make_kn id))); assert (ModPath.equal mp mp_env); let () = check_subtypes mp subs in let sobjs = subst_sobjs (map_mp mp0 mp resolver) sobjs in InterpVisitor.add_leaf (ModuleObject (id,sobjs)); mp end end * { 6 Module types : start , end , declare } module RawModTypeOps = struct module Synterp = struct let start_modtype_core id cur_mp args mtys fs = let mp = ModPath.MPdot(cur_mp, Label.of_id id) in let args = RawModOps.Synterp.intern_args args in let mbids = List.flatten @@ List.map (fun (mbidl,_) -> mbidl) args in let sub_mty_l = RawModOps.Synterp.build_subtypes mtys in mp, mbids, args, sub_mty_l let start_modtype id args mtys fs = let mp, mbids, args, sub_mty_l = start_modtype_core id (openmod_syntax_info ()).cur_mp args mtys fs in set_openmod_syntax_info { cur_mp = mp; cur_typ = None; cur_mbids = mbids }; let prefix = Lib.Synterp.start_modtype id mp fs in Nametab.(push_dir (Until 1) (prefix.obj_dir) (GlobDirRef.DirOpenModtype prefix.obj_mp)); mp, args, sub_mty_l let end_modtype_core id mbids objects fs = let {Lib.Synterp.substobjs = substitute; keepobjs = _; anticipateobjs = special; } = objects in Summary.unfreeze_summaries ~partial:true fs; let modtypeobjs = (mbids, Objs substitute) in (special@[ModuleTypeObject (id,modtypeobjs)]) let end_modtype () = let oldprefix,fs,objects = Lib.Synterp.end_modtype () in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let objects = end_modtype_core id (openmod_syntax_info ()).cur_mbids objects fs in SynterpVisitor.add_leaves objects; (openmod_syntax_info ()).cur_mp let declare_modtype id args mtys (mty,ann) fs = let inl = inl2intopt ann in (* We simulate the beginning of an interactive module, then we adds the module parameters to the global env. *) let mp, mbids, args, sub_mty_l = start_modtype_core id (openmod_syntax_info ()).cur_mp args mtys fs in let mte, base, kind = Modintern.intern_module_ast Modintern.ModType mty in let entry = mbids, mte in let sobjs = RawModOps.Synterp.get_functor_sobjs false inl entry in let subst = map_mp (get_module_path (snd entry)) mp empty_delta_resolver in let sobjs = subst_sobjs subst sobjs in (* Undo the simulated interactive building of the module type and declare the module type as a whole *) Summary.unfreeze_summaries ~partial:true fs; ignore (SynterpVisitor.add_leaf (ModuleTypeObject (id,sobjs))); mp, args, (mte, base, kind, inl), sub_mty_l end module Interp = struct let openmodtype_info = Summary.ref ([] : module_type_body list) ~name:"MODTYPE-INFO" let start_modtype_core id args mtys fs = let mp = Global.start_modtype id in let params, params_ctx = RawModOps.Interp.intern_args args in let () = Global.push_context_set ~strict:true params_ctx in let env = Global.env () in let sub_mty_l, sub_mty_ctx = RawModOps.Interp.build_subtypes env mp params mtys in let () = Global.push_context_set ~strict:true sub_mty_ctx in mp, params, sub_mty_l, Univ.ContextSet.union params_ctx sub_mty_ctx let start_modtype id args mtys fs = let mp, _, sub_mty_l, _ = start_modtype_core id args mtys fs in openmodtype_info := sub_mty_l; let prefix = Lib.Interp.start_modtype id mp fs in Nametab.(push_dir (Until 1) (prefix.obj_dir) (GlobDirRef.DirOpenModtype mp)); mp let end_modtype_core id sub_mty_l objects fs = let {Lib.Interp.substobjs = substitute; keepobjs = _; anticipateobjs = special; } = objects in let mp, mbids = Global.end_modtype fs id in let () = RawModOps.Interp.check_subtypes_mt mp sub_mty_l in let modtypeobjs = (mbids, Objs substitute) in let objects = special@[ModuleTypeObject (id,modtypeobjs)] in mp, objects let end_modtype () = let oldprefix,fs,objects = Lib.Interp.end_modtype () in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let sub_mty_l = !openmodtype_info in let mp, objects = end_modtype_core id sub_mty_l objects fs in let () = InterpVisitor.add_leaves objects in Check name consistence : start _ vs. end_modtype , kernel vs. library assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp); assert (ModPath.equal oldprefix.Nametab.obj_mp mp); mp let declare_modtype id args mtys (mte,base,kind,inl) fs = (* We simulate the beginning of an interactive module, then we adds the module parameters to the global env. *) let mp, params, sub_mty_l, ctx = start_modtype_core id args mtys fs in let env = Global.env () in let mte, mte_ctx = Modintern.interp_module_ast env kind base mte in let () = Global.push_context_set ~strict:true mte_ctx in let env = Global.env () in (* We check immediately that mte is well-formed *) let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, _, _, (_, mte_cst) = Mod_typing.translate_mse state env None inl mte in let () = Global.push_context_set ~strict:true (Univ.Level.Set.empty,mte_cst) in let entry = params, mte in let env = Global.env () in let sobjs = RawModOps.Interp.get_functor_sobjs false env inl entry in let subst = map_mp (get_module_path (snd entry)) mp empty_delta_resolver in let sobjs = subst_sobjs subst sobjs in (* Undo the simulated interactive building of the module type and declare the module type as a whole *) Summary.unfreeze_summaries ~partial:true fs; (* We enrich the global environment *) let () = Global.push_context_set ~strict:true ctx in let () = Global.push_context_set ~strict:true mte_ctx in let () = Global.push_context_set ~strict:true (Univ.Level.Set.empty,mte_cst) in let mp_env = Global.add_modtype id entry inl in (* Name consistency check : kernel vs. library *) assert (ModPath.equal mp_env mp); (* Subtyping checks *) let () = RawModOps.Interp.check_subtypes_mt mp sub_mty_l in InterpVisitor.add_leaf (ModuleTypeObject (id, sobjs)); mp end end * { 6 Include } module RawIncludeOps = struct exception NoIncludeSelf module Synterp = struct let rec include_subst mp mbids = match mbids with | [] -> empty_subst | mbid::mbids -> let subst = include_subst mp mbids in join (map_mbid mbid mp empty_delta_resolver) subst let declare_one_include_core cur_mp (me_ast,annot) = let me, base, kind = Modintern.intern_module_ast Modintern.ModAny me_ast in let is_mod = (kind == Modintern.Module) in let inl = inl2intopt annot in let mbids,aobjs = SynterpVisitor.get_module_sobjs is_mod () inl me in let subst_self = try if List.is_empty mbids then raise NoIncludeSelf; include_subst cur_mp mbids with NoIncludeSelf -> empty_subst in let base_mp = get_module_path me in (* We can use an empty delta resolver on syntax objects *) let subst = join subst_self (map_mp base_mp cur_mp empty_delta_resolver) in let aobjs = subst_aobjs subst aobjs in (me, base, kind, inl), aobjs let declare_one_include (me_ast,annot) = let res, aobjs = declare_one_include_core (openmod_syntax_info ()).cur_mp (me_ast,annot) in SynterpVisitor.add_leaf (IncludeObject aobjs); res let declare_include me_asts = List.map declare_one_include me_asts end module Interp = struct let rec include_subst env mp reso mbids sign inline = match mbids with | [] -> empty_subst | mbid::mbids -> let farg_id, farg_b, fbody_b = Modops.destr_functor sign in let subst = include_subst env mp reso mbids fbody_b inline in let mp_delta = Modops.inline_delta_resolver env inline mp farg_id farg_b reso in join (map_mbid mbid mp mp_delta) subst let rec decompose_functor mpl typ = match mpl, typ with | [], _ -> typ | _::mpl, MoreFunctor(_,_,str) -> decompose_functor mpl str | _ -> user_err Pp.(str "Application of a functor with too much arguments.") let type_of_incl env is_mod = function | MEident mp -> type_of_mod mp env is_mod | MEapply _ as me -> let mp0, mp_l = InterpVisitor.get_applications me in decompose_functor mp_l (type_of_mod mp0 env is_mod) | MEwith _ -> raise NoIncludeSelf (** Implements [Include F] where [F] has parameters [mbids] to be instantiated by fields of the current "self" module, i.e. using subtyping, by the current module itself. *) let declare_one_include_core (me,base,kind,inl) = let env = Global.env() in let me, cst = Modintern.interp_module_ast env kind base me in let () = Global.push_context_set ~strict:true cst in let env = Global.env () in let is_mod = (kind == Modintern.Module) in let cur_mp = Global.current_modpath () in let mbids,aobjs = InterpVisitor.get_module_sobjs is_mod env inl me in let subst_self = try if List.is_empty mbids then raise NoIncludeSelf; let typ = type_of_incl env is_mod me in let reso = RawModOps.Interp.current_modresolver () in include_subst env cur_mp reso mbids typ inl with NoIncludeSelf -> empty_subst in let base_mp = get_module_path me in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let sign, (), resolver, (_, cst) = Mod_typing.translate_mse_include is_mod state (Global.env ()) (Global.current_modpath ()) inl me in let () = Global.add_constraints cst in let () = assert (ModPath.equal cur_mp (Global.current_modpath ())) in (* Include Self support *) let mb = { mod_mp = cur_mp; mod_expr = (); mod_type = RawModOps.Interp.current_struct (); mod_type_alg = None; mod_delta = RawModOps.Interp.current_modresolver (); mod_retroknowledge = ModTypeRK } in let rec compute_sign sign = match sign with | MoreFunctor(mbid,mtb,str) -> let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let (_, cst) = Subtyping.check_subtypes state (Global.env ()) mb mtb in let () = Global.add_constraints cst in let mpsup_delta = Modops.inline_delta_resolver (Global.env ()) inl cur_mp mbid mtb mb.mod_delta in let subst = Mod_subst.map_mbid mbid cur_mp mpsup_delta in compute_sign (Modops.subst_signature subst str) | NoFunctor str -> () in let () = compute_sign sign in let resolver = Global.add_include me is_mod inl in let subst = join subst_self (map_mp base_mp cur_mp resolver) in subst_aobjs subst aobjs let declare_one_include (me,base,kind,inl) = let aobjs = declare_one_include_core (me,base,kind,inl) in InterpVisitor.add_leaf (IncludeObject aobjs) let declare_include me_asts = List.iter declare_one_include me_asts end end * { 6 Module operations handling summary freeze / unfreeze } let protect_summaries stage f = let fs = Summary.freeze_staged_summaries stage ~marshallable:false in try f fs with reraise -> (* Something wrong: undo the whole process *) let reraise = Exninfo.capture reraise in let () = Summary.unfreeze_summaries ~partial:true fs in Exninfo.iraise reraise * { 6 Libraries } type library_name = DirPath.t (** A library object is made of some substitutive objects and some "keep" objects. *) type library_objects = Libobject.t list * Libobject.t list module Synterp = struct let start_module export id args res = protect_summaries Summary.Stage.Synterp (RawModOps.Synterp.start_module export id args res) let end_module = RawModOps.Synterp.end_module (** Declare a module in terms of a list of module bodies, by including them. Typically used for `Module M := N <+ P`. *) let declare_module_includes id args res mexpr_l fs = let mp, res_entry_o, mbids, sign, args = RawModOps.Synterp.start_module_core id args res fs in let mod_info = { cur_mp = mp; cur_typ = res_entry_o; cur_mbids = mbids } in let includes = List.map_left (RawIncludeOps.Synterp.declare_one_include_core mp) mexpr_l in let bodies, incl_objs = List.split includes in let incl_objs = List.map (fun x -> IncludeObject x) incl_objs in let objects = Lib.Synterp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let mp, objects = RawModOps.Synterp.end_module_core id mod_info objects fs in SynterpVisitor.add_leaves objects; mp, args, bodies, sign (** Declare a module type in terms of a list of module bodies, by including them. Typically used for `Module Type M := N <+ P`. *) let declare_modtype_includes id args res mexpr_l fs = let mp, mbids, args, subtyps = RawModTypeOps.Synterp.start_modtype_core id (openmod_syntax_info ()).cur_mp args res fs in let includes = List.map_left (RawIncludeOps.Synterp.declare_one_include_core mp) mexpr_l in let bodies, incl_objs = List.split includes in let incl_objs = List.map (fun x -> IncludeObject x) incl_objs in let objects = Lib.Synterp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let objects = RawModTypeOps.Synterp.end_modtype_core id mbids objects fs in SynterpVisitor.add_leaves objects; mp, args, bodies, subtyps let declare_module id args mtys me_l = let declare_me fs = match me_l with | [] -> let mp, args, body, sign = RawModOps.Synterp.declare_module id args mtys None fs in assert (Option.is_empty body); mp, args, [], sign | [me] -> let mp, args, body, sign = RawModOps.Synterp.declare_module id args mtys (Some me) fs in mp, args, [Option.get body], sign | me_l -> declare_module_includes id args mtys me_l fs in protect_summaries Summary.Stage.Synterp declare_me let start_modtype id args mtys = protect_summaries Summary.Stage.Synterp (RawModTypeOps.Synterp.start_modtype id args mtys) let end_modtype = RawModTypeOps.Synterp.end_modtype let declare_modtype id args mtys mty_l = let declare_mt fs = match mty_l with | [] -> assert false | [mty] -> let mp, args, body, sign = RawModTypeOps.Synterp.declare_modtype id args mtys mty fs in mp, args, [body], sign | mty_l -> declare_modtype_includes id args mtys mty_l fs in protect_summaries Summary.Stage.Synterp declare_mt let declare_include me_asts = protect_summaries Summary.Stage.Synterp (fun _ -> RawIncludeOps.Synterp.declare_include me_asts) let register_library dir (objs:library_objects) = let mp = MPfile dir in let sobjs,keepobjs = objs in SynterpVisitor.do_module SynterpVisitor.load_objects 1 dir mp ([],Objs sobjs) keepobjs let import_modules ~export mpl = let _,objs = SynterpVisitor.collect_modules mpl (MPmap.empty, []) in List.iter (fun (f,o) -> SynterpVisitor.open_object f 1 o) objs; match export with | Lib.Import -> () | Lib.Export -> let entry = ExportObject { mpl } in Lib.Synterp.add_leaf_entry entry let import_module f ~export mp = import_modules ~export [f,mp] end module Interp = struct let start_module export id args sign = protect_summaries Summary.Stage.Interp (RawModOps.Interp.start_module export id args sign) let end_module = RawModOps.Interp.end_module (** Declare a module in terms of a list of module bodies, by including them. Typically used for `Module M := N <+ P`. *) let declare_module_includes id args res mexpr_l fs = let mp, res_entry_o, subtyps, _, _ = RawModOps.Interp.start_module_core id args res fs in let mod_info = { cur_typ = res_entry_o; cur_typs = subtyps } in let incl_objs = List.map_left (fun x -> IncludeObject (RawIncludeOps.Interp.declare_one_include_core x)) mexpr_l in let objects = Lib.Interp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let mp, objects = RawModOps.Interp.end_module_core id mod_info objects fs in InterpVisitor.add_leaves objects; mp (** Declare a module type in terms of a list of module bodies, by including them. Typically used for `Module Type M := N <+ P`. *) let declare_modtype_includes id args res mexpr_l fs = let mp, _, subtyps, _ = RawModTypeOps.Interp.start_modtype_core id args res fs in let incl_objs = List.map_left (fun x -> IncludeObject (RawIncludeOps.Interp.declare_one_include_core x)) mexpr_l in let objects = Lib.Interp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let mp, objects = RawModTypeOps.Interp.end_modtype_core id subtyps objects fs in InterpVisitor.add_leaves objects; mp let declare_module id args mtys me_l = let declare_me fs = match me_l with | [] -> RawModOps.Interp.declare_module id args mtys None fs | [me] -> RawModOps.Interp.declare_module id args mtys (Some me) fs | me_l -> declare_module_includes id args mtys me_l fs in protect_summaries Summary.Stage.Interp declare_me let start_modtype id args mtys = protect_summaries Summary.Stage.Interp (RawModTypeOps.Interp.start_modtype id args mtys) let end_modtype = RawModTypeOps.Interp.end_modtype let declare_modtype id args mtys mty_l = let declare_mt fs = match mty_l with | [] -> assert false | [mty] -> RawModTypeOps.Interp.declare_modtype id args mtys mty fs | mty_l -> declare_modtype_includes id args mtys mty_l fs in protect_summaries Summary.Stage.Interp declare_mt let declare_include me_asts = if Lib.sections_are_opened () then user_err Pp.(str "Include is not allowed inside sections."); protect_summaries Summary.Stage.Interp (fun _ -> RawIncludeOps.Interp.declare_include me_asts) (** For the native compiler, we cache the library values *) let register_library dir cenv (objs:library_objects) digest univ = let mp = MPfile dir in let () = try (* Is this library already loaded ? *) ignore(Global.lookup_module mp); with Not_found -> begin (* If not, let's do it now ... *) let mp' = Global.import cenv univ digest in if not (ModPath.equal mp mp') then anomaly (Pp.str "Unexpected disk module name.") end in let sobjs,keepobjs = objs in InterpVisitor.do_module InterpVisitor.load_objects 1 dir mp ([],Objs sobjs) keepobjs let import_modules ~export mpl = let _,objs = InterpVisitor.collect_modules mpl (MPmap.empty, []) in List.iter (fun (f,o) -> InterpVisitor.open_object f 1 o) objs; match export with | Lib.Import -> () | Lib.Export -> let entry = ExportObject { mpl } in Lib.Interp.add_leaf_entry entry let import_module f ~export mp = import_modules ~export [f,mp] end let end_library_hook = ref [] let append_end_library_hook f = end_library_hook := f :: !end_library_hook let end_library_hook () = List.iter (fun f -> f ()) (List.rev !end_library_hook) let end_library ~output_native_objects dir = end_library_hook(); let prefix, lib_stack, lib_stack_syntax = Lib.end_compilation dir in let mp,cenv,ast = Global.export ~output_native_objects dir in assert (ModPath.equal mp (MPfile dir)); let {Lib.Interp.substobjs = substitute; keepobjs = keep; anticipateobjs = _; } = lib_stack in let {Lib.Synterp.substobjs = substitute_syntax; keepobjs = keep_syntax; anticipateobjs = _; } = lib_stack_syntax in cenv,(substitute,keep),(substitute_syntax,keep_syntax),ast * { 6 Iterators } let iter_all_interp_segments f = let rec apply_obj prefix obj = match obj with | IncludeObject aobjs -> let objs = InterpVisitor.expand_aobjs aobjs in List.iter (apply_obj prefix) objs | _ -> f prefix obj in let apply_mod_obj _ modobjs = let prefix = modobjs.module_prefix in List.iter (apply_obj prefix) modobjs.module_substituted_objects; List.iter (apply_obj prefix) modobjs.module_keep_objects in let apply_nodes (node, os) = List.iter (fun o -> f (Lib.node_prefix node) o) os in MPmap.iter apply_mod_obj (InterpVisitor.ModObjs.all ()); List.iter apply_nodes (Lib.contents ()) * { 6 Some types used to shorten declaremods.mli } type module_params = (lident list * (Constrexpr.module_ast * inline)) list type module_expr = (Modintern.module_struct_expr * ModPath.t * Modintern.module_kind * Entries.inline) type module_params_expr = (MBId.t list * module_expr) list * { 6 Debug } let debug_print_modtab () = InterpVisitor.debug_print_modtab () * For printing modules , [ process_module_binding ] adds names of bound module ( and its components ) to Nametab . It also loads objects associated to it . bound module (and its components) to Nametab. It also loads objects associated to it. *) let process_module_binding mbid me = let dir = DirPath.make [MBId.to_id mbid] in let mp = MPbound mbid in let sobjs = InterpVisitor.get_module_sobjs false (Global.env()) (default_inline ()) me in let subst = map_mp (get_module_path me) mp empty_delta_resolver in let sobjs = subst_sobjs subst sobjs in SynterpVisitor.do_module SynterpVisitor.load_objects 1 dir mp sobjs []; InterpVisitor.do_module InterpVisitor.load_objects 1 dir mp sobjs [] (** Compatibility layer *) let import_module f ~export mp = Synterp.import_module f ~export mp; Interp.import_module f ~export mp let declare_module id args mtys me_l = let mp, args, bodies, sign = Synterp.declare_module id args mtys me_l in Interp.declare_module id args sign bodies let start_module export id args res = let mp, args, sign = Synterp.start_module export id args res in Interp.start_module export id args sign let end_module () = let _mp = Synterp.end_module () in Interp.end_module () let declare_modtype id args mtys mty_l = let mp, args, bodies, subtyps = Synterp.declare_modtype id args mtys mty_l in Interp.declare_modtype id args subtyps bodies let start_modtype id args mtys = let mp, args, sub_mty_l = Synterp.start_modtype id args mtys in Interp.start_modtype id args sub_mty_l let end_modtype () = let _mp = Synterp.end_modtype () in Interp.end_modtype () let declare_include me_asts = let l = Synterp.declare_include me_asts in Interp.declare_include l
null
https://raw.githubusercontent.com/coq/coq/2be68bf1a3359c259a85dbb8e2b5d5075ba68f90/vernac/declaremods.ml
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * Rigid / flexible module signature * ... : T * ... <: T1 <: T2, possibly empty * Which module inline annotations should we honor, either None or the ones whose level is less or equal to the given integer * These functions register the visibility of the module and iterates through its components. They are called by plenty of module functions * Create the substitution corresponding to some functor applications * Some utilities about substitutive objects : substitution, expansion Invariant : any alias points to concrete objs may raise Not_found * Iterate some function [iter_objects] on all components of a module If we're not a functor, let's iter on the internal components Invariant : seg isn't empty a substobjs should already be loaded If the map doesn't change there is nothing new to export. It's possible that [filter_and] or [filter_or] mangled precise filters such that we repeat uselessly, but the important [Unfiltered] case is handled correctly. If we're not a functor, let's iter on the internal components Adding operations with containers Only inner parts of module types should be missing * Create the objects of a "with Module" structure. we create an alias For now, we expand everything, to be safe * type via ":" * types via "<:" We can use an empty delta resolver because we load only syntax objects Loads the parsing objects in arguments For sealed modules, we use the substitutive objects of their signatures We substitute objects if the module is sealed by a signature We add the keep objects, if any, and if this isn't a functor Name consistency check : start_ vs. end_module Name consistency check : kernel vs. library We simulate the beginning of an interactive module, then we adds the module parameters to the global env. No body, no type ... Undo the simulated interactive building of the module and declare the module as a whole We can use an empty delta resolver on syntax objects * This function checks if the type calculated for the module [mp] is a "<:"-like subtype of all signatures in [sub_mtb_l]. Uses only the global environment. * Same for module type [mp] * Prepare the module type list for check of subtypes * Process a declaration of functor parameter(s) (Id1 .. Idn : Typ) i.e. possibly multiple names with the same module type. Global environment is updated on the fly. Objects in these parameters are also loaded. Output is accumulated on top of [acc] (in reverse order). We check immediately that mte is well-formed For sealed modules, we use the substitutive objects of their signatures We substitute objects if the module is sealed by a signature We add the keep objects, if any, and if this isn't a functor Name consistency check : kernel vs. library We simulate the beginning of an interactive module, then we adds the module parameters to the global env. No body, no type ... Undo the simulated interactive building of the module and declare the module as a whole Name consistency check : kernel vs. library We simulate the beginning of an interactive module, then we adds the module parameters to the global env. Undo the simulated interactive building of the module type and declare the module type as a whole We simulate the beginning of an interactive module, then we adds the module parameters to the global env. We check immediately that mte is well-formed Undo the simulated interactive building of the module type and declare the module type as a whole We enrich the global environment Name consistency check : kernel vs. library Subtyping checks We can use an empty delta resolver on syntax objects * Implements [Include F] where [F] has parameters [mbids] to be instantiated by fields of the current "self" module, i.e. using subtyping, by the current module itself. Include Self support Something wrong: undo the whole process * A library object is made of some substitutive objects and some "keep" objects. * Declare a module in terms of a list of module bodies, by including them. Typically used for `Module M := N <+ P`. * Declare a module type in terms of a list of module bodies, by including them. Typically used for `Module Type M := N <+ P`. * Declare a module in terms of a list of module bodies, by including them. Typically used for `Module M := N <+ P`. * Declare a module type in terms of a list of module bodies, by including them. Typically used for `Module Type M := N <+ P`. * For the native compiler, we cache the library values Is this library already loaded ? If not, let's do it now ... * Compatibility layer
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Pp open CErrors open Util open Names open Declarations open Entries open Libnames open Libobject open Mod_subst * { 6 Inlining levels } type 'a module_signature = type inline = | NoInline | DefaultInline | InlineAt of int let default_inline () = Some (Flags.get_inline_level ()) let inl2intopt = function | NoInline -> None | InlineAt i -> Some i | DefaultInline -> default_inline () let consistency_checks exists dir = if exists then let _ = try Nametab.locate_module (qualid_of_dirpath dir) with Not_found -> user_err (DirPath.print dir ++ str " should already exist!") in () else if Nametab.exists_module dir then user_err (DirPath.print dir ++ str " already exists.") let rec get_module_path = function | MEident mp -> mp | MEwith (me,_) -> get_module_path me | MEapply (me,_) -> get_module_path me let type_of_mod mp env = function | true -> (Environ.lookup_module mp env).mod_type | false -> (Environ.lookup_modtype mp env).mod_type * { 6 Name management } Auxiliary functions to transform full_path and kernel_name given by Lib into ModPath.t and DirPath.t needed for modules Auxiliary functions to transform full_path and kernel_name given by Lib into ModPath.t and DirPath.t needed for modules *) let mp_of_kn kn = let mp,l = KerName.repr kn in MPdot (mp,l) let dir_of_sp sp = let dir,id = repr_path sp in add_dirpath_suffix dir id * The [ ModActions ] abstraction represent operations on modules that are specific to a given stage . Two instances are defined below , for Synterp and Interp . that are specific to a given stage. Two instances are defined below, for Synterp and Interp. *) module type ModActions = sig type typexpr type env val stage : Summary.Stage.t val substobjs_table_name : string val modobjs_table_name : string val enter_module : ModPath.t -> DirPath.t -> int -> unit val enter_modtype : ModPath.t -> full_path -> int -> unit val open_module : open_filter -> ModPath.t -> DirPath.t -> int -> unit module Lib : Lib.StagedLibS val compute_subst : is_mod:bool -> env -> MBId.t list -> ModPath.t -> ModPath.t list -> Entries.inline -> MBId.t list * substitution end module SynterpActions : ModActions with type env = unit with type typexpr = Constrexpr.universe_decl_expr option * Constrexpr.constr_expr = struct type typexpr = Constrexpr.universe_decl_expr option * Constrexpr.constr_expr type env = unit let stage = Summary.Stage.Synterp let substobjs_table_name = "MODULE-SYNTAX-SUBSTOBJS" let modobjs_table_name = "MODULE-SYNTAX-OBJS" let enter_module obj_mp obj_dir i = consistency_checks false obj_dir; Nametab.push_module (Until i) obj_dir obj_mp let enter_modtype mp sp i = if Nametab.exists_modtype sp then anomaly (pr_path sp ++ str " already exists."); Nametab.push_modtype (Nametab.Until i) sp mp let open_module f obj_mp obj_dir i = consistency_checks true obj_dir; if in_filter ~cat:None f then Nametab.push_module (Nametab.Exactly i) obj_dir obj_mp module Lib = Lib.Synterp let rec compute_subst () mbids mp_l inl = match mbids,mp_l with | _,[] -> mbids,empty_subst | [],r -> user_err Pp.(str "Application of a functor with too few arguments.") | mbid::mbids,mp::mp_l -> let mbid_left,subst = compute_subst () mbids mp_l inl in mbid_left,join (map_mbid mbid mp empty_delta_resolver) subst let compute_subst ~is_mod () mbids mp1 mp_l inl = compute_subst () mbids mp_l inl end module InterpActions : ModActions with type env = Environ.env with type typexpr = Constr.t * Univ.AbstractContext.t option = struct type typexpr = Constr.t * Univ.AbstractContext.t option type env = Environ.env let stage = Summary.Stage.Interp let substobjs_table_name = "MODULE-SUBSTOBJS" let modobjs_table_name = "MODULE-OBJS" * { 6 Current module type information } This information is stored by each [ start_modtype ] for use in a later [ end_modtype ] . This information is stored by each [start_modtype] for use in a later [end_modtype]. *) let enter_module obj_mp obj_dir i = () let enter_modtype mp sp i = () let open_module f obj_mp obj_dir i = () module Lib = Lib.Interp let rec compute_subst env mbids sign mp_l inl = match mbids,mp_l with | _,[] -> mbids,empty_subst | [],r -> user_err Pp.(str "Application of a functor with too few arguments.") | mbid::mbids,mp::mp_l -> let farg_id, farg_b, fbody_b = Modops.destr_functor sign in let mb = Environ.lookup_module mp env in let mbid_left,subst = compute_subst env mbids fbody_b mp_l inl in let resolver = if Modops.is_functor mb.mod_type then empty_delta_resolver else Modops.inline_delta_resolver env inl mp farg_id farg_b mb.mod_delta in mbid_left,join (map_mbid mbid mp resolver) subst let compute_subst ~is_mod env mbids mp1 mp_l inl = let typ = type_of_mod mp1 env is_mod in compute_subst env mbids typ mp_l inl end type module_objects = { module_prefix : Nametab.object_prefix; module_substituted_objects : Libobject.t list; module_keep_objects : Libobject.t list; } * The [ StagedModS ] abstraction describes module operations at a given stage . module type StagedModS = sig type typexpr type env val get_module_sobjs : bool -> env -> Entries.inline -> typexpr module_alg_expr -> substitutive_objects val do_module : (int -> Nametab.object_prefix -> Libobject.t list -> unit) -> int -> DirPath.t -> ModPath.t -> substitutive_objects -> Libobject.t list -> unit val load_objects : int -> Nametab.object_prefix -> Libobject.t list -> unit val open_object : open_filter -> int -> Nametab.object_prefix * Libobject.t -> unit val collect_modules : (open_filter * ModPath.t) list -> open_filter MPmap.t * (open_filter * (Nametab.object_prefix * Libobject.t)) list -> open_filter MPmap.t * (open_filter * (Nametab.object_prefix * Libobject.t)) list val add_leaf : Libobject.t -> unit val add_leaves : Libobject.t list -> unit val expand_aobjs : Libobject.algebraic_objects -> Libobject.t list val get_applications : typexpr module_alg_expr -> ModPath.t * ModPath.t list val debug_print_modtab : unit -> Pp.t module ModObjs : sig val all : unit -> module_objects MPmap.t end end let sobjs_no_functor (mbids,_) = List.is_empty mbids let subst_filtered sub (f,mp as x) = let mp' = subst_mp sub mp in if mp == mp' then x else f, mp' let rec subst_aobjs sub = function | Objs o as objs -> let o' = subst_objects sub o in if o == o' then objs else Objs o' | Ref (mp, sub0) as r -> let sub0' = join sub0 sub in if sub0' == sub0 then r else Ref (mp, sub0') and subst_sobjs sub (mbids,aobjs as sobjs) = let aobjs' = subst_aobjs sub aobjs in if aobjs' == aobjs then sobjs else (mbids, aobjs') and subst_objects subst seg = let subst_one node = match node with | AtomicObject obj -> let obj' = Libobject.subst_object (subst,obj) in if obj' == obj then node else AtomicObject obj' | ModuleObject (id, sobjs) -> let sobjs' = subst_sobjs subst sobjs in if sobjs' == sobjs then node else ModuleObject (id, sobjs') | ModuleTypeObject (id, sobjs) -> let sobjs' = subst_sobjs subst sobjs in if sobjs' == sobjs then node else ModuleTypeObject (id, sobjs') | IncludeObject aobjs -> let aobjs' = subst_aobjs subst aobjs in if aobjs' == aobjs then node else IncludeObject aobjs' | ExportObject { mpl } -> let mpl' = List.Smart.map (subst_filtered subst) mpl in if mpl'==mpl then node else ExportObject { mpl = mpl' } | KeepObject _ -> assert false in List.Smart.map subst_one seg * The [ StagedMod ] abstraction factors out the code dealing with modules that is common to all stages . that is common to all stages. *) module StagedMod(Actions : ModActions) = struct type typexpr = Actions.typexpr type env = Actions.env * ModSubstObjs : a cache of module substitutive objects This table is common to modules and module types . - For a Module M:=N , the objects of N will be reloaded with M after substitution . - For a Module M : SIG:= ... , the module M gets its objects from SIG Invariants : - A alias ( i.e. a module path inside a Ref constructor ) should never lead to another alias , but rather to a concrete Objs constructor . We will plug later a handler dealing with missing entries in the cache . Such missing entries may come from inner parts of module types , which are n't registered by the standard libobject machinery . This table is common to modules and module types. - For a Module M:=N, the objects of N will be reloaded with M after substitution. - For a Module M:SIG:=..., the module M gets its objects from SIG Invariants: - A alias (i.e. a module path inside a Ref constructor) should never lead to another alias, but rather to a concrete Objs constructor. We will plug later a handler dealing with missing entries in the cache. Such missing entries may come from inner parts of module types, which aren't registered by the standard libobject machinery. *) module ModSubstObjs : sig val set : ModPath.t -> substitutive_objects -> unit val get : ModPath.t -> substitutive_objects val set_missing_handler : (ModPath.t -> substitutive_objects) -> unit end = struct let table = Summary.ref ~stage:Actions.stage (MPmap.empty : substitutive_objects MPmap.t) ~name:Actions.substobjs_table_name let missing_handler = ref (fun mp -> assert false) let set_missing_handler f = (missing_handler := f) let set mp objs = (table := MPmap.add mp objs !table) let get mp = try MPmap.find mp !table with Not_found -> !missing_handler mp end let expand_aobjs = function | Objs o -> o | Ref (mp, sub) -> match ModSubstObjs.get mp with | (_,Objs o) -> subst_objects sub o let expand_sobjs (_,aobjs) = expand_aobjs aobjs * { 6 ModObjs : a cache of module objects } For each module , we also store a cache of " prefix " , " substituted objects " , " keep objects " . This is used for instance to implement the " Import " command . substituted objects : roughly the objects above after the substitution - we need to keep them to call open_object when the module is opened ( imported ) keep objects : The list of non - substitutive objects - as above , for each of them we will call open_object when the module is opened ( Some ) Invariants : * If the module is a functor , it wo n't appear in this cache . * Module objects in substitutive_objects part have empty substituted objects . * Modules which where created with Module M:=mexpr or with Module M : SIG . ... End M. have the keep list empty . For each module, we also store a cache of "prefix", "substituted objects", "keep objects". This is used for instance to implement the "Import" command. substituted objects : roughly the objects above after the substitution - we need to keep them to call open_object when the module is opened (imported) keep objects : The list of non-substitutive objects - as above, for each of them we will call open_object when the module is opened (Some) Invariants: * If the module is a functor, it won't appear in this cache. * Module objects in substitutive_objects part have empty substituted objects. * Modules which where created with Module M:=mexpr or with Module M:SIG. ... End M. have the keep list empty. *) module ModObjs : sig val set : ModPath.t -> module_objects -> unit val all : unit -> module_objects MPmap.t end = struct let table = Summary.ref ~stage:Actions.stage (MPmap.empty : module_objects MPmap.t) ~name:Actions.modobjs_table_name let set mp objs = (table := MPmap.add mp objs !table) let get mp = MPmap.find mp !table let all () = !table end * { 6 Declaration of module substitutive objects } let do_module iter_objects i obj_dir obj_mp sobjs kobjs = let prefix = Nametab.{ obj_dir ; obj_mp; } in Actions.enter_module obj_mp obj_dir i; ModSubstObjs.set obj_mp sobjs; if sobjs_no_functor sobjs then begin let objs = expand_sobjs sobjs in let module_objects = { module_prefix = prefix; module_substituted_objects = objs; module_keep_objects = kobjs; } in ModObjs.set obj_mp module_objects; iter_objects (i+1) prefix objs; iter_objects (i+1) prefix kobjs end let do_module' iter_objects i ((sp,kn),sobjs) = do_module iter_objects i (dir_of_sp sp) (mp_of_kn kn) sobjs [] * : Interactive modules and module types can not be recached ! This used to be checked here via a flag along the substobjs . This used to be checked here via a flag along the substobjs. *) * { 6 Declaration of module type substitutive objects } * : Interactive modules and module types can not be recached ! This used to be checked more properly here . This used to be checked more properly here. *) let load_modtype i sp mp sobjs = Actions.enter_modtype mp sp i; ModSubstObjs.set mp sobjs * { 6 Declaration of substitutive objects for Include } let rec load_object i (prefix, obj) = match obj with | AtomicObject o -> Libobject.load_object i (prefix, o) | ModuleObject (id,sobjs) -> let name = Lib.make_oname prefix id in do_module' load_objects i (name, sobjs) | ModuleTypeObject (id,sobjs) -> let name = Lib.make_oname prefix id in let (sp,kn) = name in load_modtype i sp (mp_of_kn kn) sobjs | IncludeObject aobjs -> load_include i (prefix, aobjs) | ExportObject _ -> () | KeepObject (id,objs) -> let name = Lib.make_oname prefix id in load_keep i (name, objs) and load_objects i prefix objs = List.iter (fun obj -> load_object i (prefix, obj)) objs and load_include i (prefix, aobjs) = let o = expand_aobjs aobjs in load_objects i prefix o and load_keep i ((sp,kn),kobjs) = let obj_dir = dir_of_sp sp and obj_mp = mp_of_kn kn in let prefix = Nametab.{ obj_dir ; obj_mp; } in let modobjs = try ModObjs.get obj_mp in assert Nametab.(eq_op modobjs.module_prefix prefix); assert (List.is_empty modobjs.module_keep_objects); ModObjs.set obj_mp { modobjs with module_keep_objects = kobjs }; load_objects i prefix kobjs * { 6 Implementation of Import and Export commands } let mark_object f obj (exports,acc) = (exports, (f,obj)::acc) let rec collect_modules mpl acc = List.fold_left (fun acc fmp -> collect_module fmp acc) acc (List.rev mpl) and collect_module (f,mp) acc = try May raise Not_found for unknown module and for functors let modobjs = ModObjs.get mp in let prefix = modobjs.module_prefix in let acc = collect_objects f 1 prefix modobjs.module_keep_objects acc in collect_objects f 1 prefix modobjs.module_substituted_objects acc with Not_found when Actions.stage = Summary.Stage.Synterp -> acc and collect_object f i prefix obj acc = match obj with | ExportObject { mpl } -> collect_exports f i mpl acc | AtomicObject _ | IncludeObject _ | KeepObject _ | ModuleObject _ | ModuleTypeObject _ -> mark_object f (prefix,obj) acc and collect_objects f i prefix objs acc = List.fold_left (fun acc obj -> collect_object f i prefix obj acc) acc (List.rev objs) and collect_export f (f',mp) (exports,objs as acc) = match filter_and f f' with | None -> acc | Some f -> let exports' = MPmap.update mp (function | None -> Some f | Some f0 -> Some (filter_or f f0)) exports in if exports == exports' then acc else collect_module (f,mp) (exports', objs) and collect_exports f i mpl acc = if Int.equal i 1 then List.fold_left (fun acc fmp -> collect_export f fmp acc) acc (List.rev mpl) else acc let open_modtype i ((sp,kn),_) = let mp = mp_of_kn kn in let mp' = try Nametab.locate_modtype (qualid_of_path sp) with Not_found -> anomaly (pr_path sp ++ str " should already exist!"); in assert (ModPath.equal mp mp'); Nametab.push_modtype (Nametab.Exactly i) sp mp let rec open_object f i (prefix, obj) = match obj with | AtomicObject o -> Libobject.open_object f i (prefix, o) | ModuleObject (id,sobjs) -> let name = Lib.make_oname prefix id in let dir = dir_of_sp (fst name) in let mp = mp_of_kn (snd name) in open_module f i dir mp sobjs | ModuleTypeObject (id,sobjs) -> let name = Lib.make_oname prefix id in open_modtype i (name, sobjs) | IncludeObject aobjs -> open_include f i (prefix, aobjs) | ExportObject { mpl } -> open_export f i mpl | KeepObject (id,objs) -> let name = Lib.make_oname prefix id in open_keep f i (name, objs) and open_module f i obj_dir obj_mp sobjs = Actions.open_module f obj_mp obj_dir i; if sobjs_no_functor sobjs then begin let modobjs = ModObjs.get obj_mp in open_objects f (i+1) modobjs.module_prefix modobjs.module_substituted_objects end and open_objects f i prefix objs = List.iter (fun obj -> open_object f i (prefix, obj)) objs and open_include f i (prefix, aobjs) = let o = expand_aobjs aobjs in open_objects f i prefix o and open_export f i mpl = let _,objs = collect_exports f i mpl (MPmap.empty, []) in List.iter (fun (f,o) -> open_object f 1 o) objs and open_keep f i ((sp,kn),kobjs) = let obj_dir = dir_of_sp sp and obj_mp = mp_of_kn kn in let prefix = Nametab.{ obj_dir; obj_mp; } in open_objects f i prefix kobjs let cache_include (prefix, aobjs) = let o = expand_aobjs aobjs in load_objects 1 prefix o; open_objects unfiltered 1 prefix o and cache_keep ((sp,kn),kobjs) = anomaly (Pp.str "This module should not be cached!") let cache_object (prefix, obj) = match obj with | AtomicObject o -> Libobject.cache_object (prefix, o) | ModuleObject (id,sobjs) -> let name = Lib.make_oname prefix id in do_module' load_objects 1 (name, sobjs) | ModuleTypeObject (id,sobjs) -> let name = Lib.make_oname prefix id in let (sp,kn) = name in load_modtype 0 sp (mp_of_kn kn) sobjs | IncludeObject aobjs -> cache_include (prefix, aobjs) | ExportObject { mpl } -> anomaly Pp.(str "Export should not be cached") | KeepObject (id,objs) -> let name = Lib.make_oname prefix id in cache_keep (name, objs) let add_leaf obj = cache_object (Lib.prefix (),obj); match Actions.stage with | Summary.Stage.Synterp -> Lib.Synterp.add_leaf_entry obj | Summary.Stage.Interp -> Lib.Interp.add_leaf_entry obj let add_leaves objs = let add_obj obj = begin match Actions.stage with | Summary.Stage.Synterp -> Lib.Synterp.add_leaf_entry obj | Summary.Stage.Interp -> Lib.Interp.add_leaf_entry obj end; load_object 1 (Lib.prefix (),obj) in List.iter add_obj objs * { 6 Handler for missing entries in ModSubstObjs } * Since the inner of Module Types are not added by default to the ModSubstObjs table , we compensate this by explicit traversal of Module Types inner objects when needed . Quite a hack ... the ModSubstObjs table, we compensate this by explicit traversal of Module Types inner objects when needed. Quite a hack... *) let mp_id mp id = MPdot (mp, Label.of_id id) let rec register_mod_objs mp obj = match obj with | ModuleObject (id,sobjs) -> ModSubstObjs.set (mp_id mp id) sobjs | ModuleTypeObject (id,sobjs) -> ModSubstObjs.set (mp_id mp id) sobjs | IncludeObject aobjs -> List.iter (register_mod_objs mp) (expand_aobjs aobjs) | _ -> () let handle_missing_substobjs mp = match mp with | MPdot (mp',l) -> let objs = expand_sobjs (ModSubstObjs.get mp') in List.iter (register_mod_objs mp') objs; ModSubstObjs.get mp | _ -> let () = ModSubstObjs.set_missing_handler handle_missing_substobjs * { 6 From module expression to substitutive objects } * Turn a chain of [ ] into the head ModPath.t and the list of ModPath.t parameters ( deepest param coming first ) . The left part of a [ MSEapply ] must be either [ MSEident ] or another [ MSEapply ] . list of ModPath.t parameters (deepest param coming first). The left part of a [MSEapply] must be either [MSEident] or another [MSEapply]. *) let get_applications mexpr = let rec get params = function | MEident mp -> mp, params | MEapply (fexpr, mp) -> get (mp::params) fexpr | MEwith _ -> user_err Pp.(str "Non-atomic functor application.") in get [] mexpr let rec replace_module_object idl mp0 objs0 mp1 objs1 = match idl, objs0 with | _,[] -> [] | id::idl,(ModuleObject (id', sobjs))::tail when Id.equal id id' -> begin let mp_id = MPdot(mp0, Label.of_id id) in let objs = match idl with | [] -> subst_objects (map_mp mp1 mp_id empty_delta_resolver) objs1 | _ -> let objs_id = expand_sobjs sobjs in replace_module_object idl mp_id objs_id mp1 objs1 in (ModuleObject (id, ([], Objs objs)))::tail end | idl,lobj::tail -> lobj::replace_module_object idl mp0 tail mp1 objs1 * Substitutive objects of a module expression ( or module type ) let rec get_module_sobjs is_mod env inl = function | MEident mp -> begin match ModSubstObjs.get mp with | (mbids,Objs _) when not (ModPath.is_bound mp) -> | sobjs -> sobjs end | MEwith (mty, WithDef _) -> get_module_sobjs is_mod env inl mty | MEwith (mty, WithMod (idl,mp1)) -> assert (not is_mod); let sobjs0 = get_module_sobjs is_mod env inl mty in if not (sobjs_no_functor sobjs0) then user_err Pp.(str "Illegal use of a functor."); let mp0 = get_module_path mty in let objs0 = expand_sobjs sobjs0 in let objs1 = expand_sobjs (ModSubstObjs.get mp1) in ([], Objs (replace_module_object idl mp0 objs0 mp1 objs1)) | MEapply _ as me -> let mp1, mp_l = get_applications me in let mbids, aobjs = get_module_sobjs is_mod env inl (MEident mp1) in let mbids_left,subst = Actions.compute_subst ~is_mod env mbids mp1 mp_l inl in (mbids_left, subst_aobjs subst aobjs) let debug_print_modtab () = let pr_seg = function | [] -> str "[]" | l -> str "[." ++ int (List.length l) ++ str ".]" in let pr_modinfo mp modobjs s = let objs = modobjs.module_substituted_objects @ modobjs.module_keep_objects in s ++ str (ModPath.to_string mp) ++ spc () ++ pr_seg objs in let modules = MPmap.fold pr_modinfo (ModObjs.all ()) (mt ()) in hov 0 modules end module SynterpVisitor : StagedModS with type env = SynterpActions.env with type typexpr = Constrexpr.universe_decl_expr option * Constrexpr.constr_expr = StagedMod(SynterpActions) module InterpVisitor : StagedModS with type env = InterpActions.env with type typexpr = Constr.t * Univ.AbstractContext.t option = StagedMod(InterpActions) * { 6 Modules : start , end , declare } type current_module_syntax_info = { cur_mp : ModPath.t; cur_typ : ((Constrexpr.universe_decl_expr option * Constrexpr.constr_expr) module_alg_expr * int option) option; cur_mbids : MBId.t list; } let default_module_syntax_info mp = { cur_mp = mp; cur_typ = None; cur_mbids = [] } let openmod_syntax_info = Summary.ref None ~stage:Summary.Stage.Synterp ~name:"MODULE-SYNTAX-INFO" * { 6 Current module information } This information is stored by each [ start_module ] for use in a later [ end_module ] . This information is stored by each [start_module] for use in a later [end_module]. *) type current_module_info = { } let default_module_info = { cur_typ = None; cur_typs = [] } let openmod_info = Summary.ref default_module_info ~name:"MODULE-INFO" let start_library dir = let mp = Global.start_library dir in openmod_info := default_module_info; openmod_syntax_info := Some (default_module_syntax_info mp); Lib.start_compilation dir mp let set_openmod_syntax_info info = match !openmod_syntax_info with | None -> anomaly Pp.(str "bad init of openmod_syntax_info") | Some _ -> openmod_syntax_info := Some info let openmod_syntax_info () = match !openmod_syntax_info with | None -> anomaly Pp.(str "missing init of openmod_syntax_info") | Some v -> v module RawModOps = struct module Synterp = struct let build_subtypes mtys = List.map (fun (m,ann) -> let inl = inl2intopt ann in let mte, base, kind = Modintern.intern_module_ast Modintern.ModType m in (mte, base, kind, inl)) mtys let intern_arg (idl,(typ,ann)) = let inl = inl2intopt ann in let lib_dir = Lib.library_dp() in let (mty, base, kind) = Modintern.intern_module_ast Modintern.ModType typ in let sobjs = SynterpVisitor.get_module_sobjs false () inl mty in let mp0 = get_module_path mty in let map {CAst.v=id} = let dir = DirPath.make [id] in let mbid = MBId.make lib_dir id in let mp = MPbound mbid in let sobjs = subst_sobjs (map_mp mp0 mp empty_delta_resolver) sobjs in SynterpVisitor.do_module SynterpVisitor.load_objects 1 dir mp sobjs []; mbid in List.map map idl, (mty, base, kind, inl) let intern_args params = List.map intern_arg params let start_module_core id args res fs = let args = intern_args args in let mbids = List.flatten @@ List.map (fun (mbidl,_) -> mbidl) args in let res_entry_o, sign = match res with | Enforce (res,ann) -> let inl = inl2intopt ann in let (mte, base, kind) = Modintern.intern_module_ast Modintern.ModType res in Some (mte, inl), Enforce (mte, base, kind, inl) | Check resl -> None, Check (build_subtypes resl) in let mp = ModPath.MPdot((openmod_syntax_info ()).cur_mp, Label.of_id id) in mp, res_entry_o, mbids, sign, args let start_module export id args res fs = let mp, res_entry_o, mbids, sign, args = start_module_core id args res fs in set_openmod_syntax_info { cur_mp = mp; cur_typ = res_entry_o; cur_mbids = mbids }; let prefix = Lib.Synterp.start_module export id mp fs in Nametab.(push_dir (Until 1) (prefix.obj_dir) (GlobDirRef.DirOpenModule prefix.obj_mp)); mp, args, sign let end_module_core id (m_info : current_module_syntax_info) objects fs = let {Lib.Synterp.substobjs = substitute; keepobjs = keep; anticipateobjs = special; } = objects in let sobjs0, keep, special = match m_info.cur_typ with | None -> ([], Objs substitute), keep, special | Some (mty, inline) -> SynterpVisitor.get_module_sobjs false () inline mty, [], [] in Summary.unfreeze_summaries ~partial:true fs; let sobjs = let (ms,objs) = sobjs0 in (m_info.cur_mbids@ms,objs) in let sobjs = match m_info.cur_typ with | None -> sobjs | Some (mty, _) -> subst_sobjs (map_mp (get_module_path mty) m_info.cur_mp empty_delta_resolver) sobjs in let node = ModuleObject (id,sobjs) in let objects = match keep, m_info.cur_mbids with | [], _ | _, _ :: _ -> special@[node] | _ -> special@[node;KeepObject (id,keep)] in Printf.eprintf " newoname=%s , oldoname=%s\n " ( string_of_path ( fst newoname ) ) ( string_of_path ( fst oldoname ) ) ; assert ( DirPath.equal ( ) ; assert ( ModPath.equal oldprefix . Nametab.obj_mp mp ) ; Printf.eprintf "newoname=%s, oldoname=%s\n" (string_of_path (fst newoname)) (string_of_path (fst oldoname)); assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp); assert (ModPath.equal oldprefix.Nametab.obj_mp mp); *) Printf.eprintf " newoname=%s , oldoname=%s\n " ( string_of_path ( fst newoname ) ) ( string_of_path ( fst oldoname ) ) ; Printf.eprintf " newoname=%s , cur_mp=%s\n " ( ModPath.debug_to_string ( mp_of_kn ( snd newoname ) ) ) ( ModPath.debug_to_string m_info.cur_mp ) ; m_info.cur_mp, objects let end_module () = let oldprefix,fs,objects = Lib.Synterp.end_module () in let m_info = openmod_syntax_info () in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let mp,objects = end_module_core id m_info objects fs in let () = SynterpVisitor.add_leaves objects in CDebug.debug_synterp ( fun ( ) - > Pp.(str"prefix= " + + DirPath.print ( ( ) + + str " , " + + DirPath.print olddp ) ) ; assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp); mp let get_functor_sobjs is_mod inl (mbids,mexpr) = let (mbids0, aobjs) = SynterpVisitor.get_module_sobjs is_mod () inl mexpr in (mbids @ mbids0, aobjs) let declare_module id args res mexpr_o fs = let mp = ModPath.MPdot((openmod_syntax_info ()).cur_mp, Label.of_id id) in let args = intern_args args in let mbids = List.flatten @@ List.map fst args in let mty_entry_o = match res with | Enforce (mty,ann) -> let inl = inl2intopt ann in let (mte, base, kind) = Modintern.intern_module_ast Modintern.ModType mty in Enforce (mte, base, kind, inl) | Check mtys -> Check (build_subtypes mtys) in let mexpr_entry_o = match mexpr_o with | None -> None | Some (mexpr,ann) -> let (mte, base, kind) = Modintern.intern_module_ast Modintern.Module mexpr in Some (mte, base, kind, inl2intopt ann) in let sobjs, mp0 = match mexpr_entry_o, mty_entry_o with | _, Enforce (typ,_,_,inl_res) -> get_functor_sobjs false inl_res (mbids,typ), get_module_path typ | Some (body, _, _, inl_expr), Check _ -> get_functor_sobjs true inl_expr (mbids,body), get_module_path body in Summary.unfreeze_summaries ~partial:true fs; let sobjs = subst_sobjs (map_mp mp0 mp empty_delta_resolver) sobjs in ignore (SynterpVisitor.add_leaf (ModuleObject (id,sobjs))); mp, args, mexpr_entry_o, mty_entry_o end module Interp = struct * { 6 Auxiliary functions concerning subtyping checks } let check_sub mtb sub_mtb_l = let fold sub_mtb (cst, env) = let state = ((Environ.universes env, cst), Reductionops.inferred_universes) in let graph, cst = Subtyping.check_subtypes state env mtb sub_mtb in (cst, Environ.set_universes graph env) in let cst, _ = List.fold_right fold sub_mtb_l (Univ.Constraints.empty, Global.env ()) in Global.add_constraints cst let check_subtypes mp sub_mtb_l = let mb = try Global.lookup_module mp with Not_found -> assert false in let mtb = Modops.module_type_of_module mb in check_sub mtb sub_mtb_l let check_subtypes_mt mp sub_mtb_l = let mtb = try Global.lookup_modtype mp with Not_found -> assert false in check_sub mtb sub_mtb_l let current_modresolver () = fst @@ Safe_typing.delta_of_senv @@ Global.safe_env () let current_struct () = let struc = Safe_typing.structure_body_of_safe_env @@ Global.safe_env () in NoFunctor (List.rev struc) let build_subtypes env mp args mtys = let (ctx, ans) = List.fold_left_map (fun ctx (mte,base,kind,inl) -> let mte, ctx' = Modintern.interp_module_ast env Modintern.ModType base mte in let env = Environ.push_context_set ~strict:true ctx' env in let ctx = Univ.ContextSet.union ctx ctx' in let state = ((Environ.universes env, Univ.Constraints.empty), Reductionops.inferred_universes) in let mtb, (_, cst) = Mod_typing.translate_modtype state env mp inl (args,mte) in let ctx = Univ.ContextSet.add_constraints cst ctx in ctx, mtb) Univ.ContextSet.empty mtys in (ans, ctx) let intern_arg (acc, cst) (mbidl,(mty, base, kind, inl)) = let env = Global.env() in let (mty, cst') = Modintern.interp_module_ast env kind base mty in let () = Global.push_context_set ~strict:true cst' in let () = let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, (_, cst) = Mod_typing.translate_modtype state (Global.env ()) base inl ([], mty) in Global.add_constraints cst in let env = Global.env () in let sobjs = InterpVisitor.get_module_sobjs false env inl mty in let mp0 = get_module_path mty in let fold acc mbid = let id = MBId.to_id mbid in let dir = DirPath.make [id] in let mp = MPbound mbid in let resolver = Global.add_module_parameter mbid mty inl in let sobjs = subst_sobjs (map_mp mp0 mp resolver) sobjs in InterpVisitor.do_module InterpVisitor.load_objects 1 dir mp sobjs []; (mbid,mty,inl)::acc in let acc = List.fold_left fold acc mbidl in (acc, Univ.ContextSet.union cst cst') * Process a list of declarations of functor parameters ( Id11 .. Id1n : Typ1) .. (Idk1 .. Idkm : Typk ) Global environment is updated on the fly . The calls to [ interp_modast ] should be interleaved with these env updates , otherwise some " with Definition " could be rejected . Returns a list of mbids and entries ( in reversed order ) . This used to be a [ List.concat ( List.map ... ) ] , but this should be more efficient and independent of [ List.map ] eval order . (Id11 .. Id1n : Typ1)..(Idk1 .. Idkm : Typk) Global environment is updated on the fly. The calls to [interp_modast] should be interleaved with these env updates, otherwise some "with Definition" could be rejected. Returns a list of mbids and entries (in reversed order). This used to be a [List.concat (List.map ...)], but this should be more efficient and independent of [List.map] eval order. *) let intern_args params = let args, ctx = List.fold_left intern_arg ([], Univ.ContextSet.empty) params in List.rev args, ctx let start_module_core id args res fs = let mp = Global.start_module id in let params, ctx = intern_args args in let () = Global.push_context_set ~strict:true ctx in let env = Global.env () in let res_entry_o, subtyps, ctx' = match res with | Enforce (mte, base, kind, inl) -> let (mte, ctx) = Modintern.interp_module_ast env kind base mte in let env = Environ.push_context_set ~strict:true ctx env in let state = ((Environ.universes env, Univ.Constraints.empty), Reductionops.inferred_universes) in let _, _, _, (_, cst) = Mod_typing.translate_mse state env None inl mte in let ctx = Univ.ContextSet.add_constraints cst ctx in Some (mte, inl), [], ctx | Check resl -> let typs, ctx = build_subtypes env mp params resl in None, typs, ctx in let () = Global.push_context_set ~strict:true ctx' in mp, res_entry_o, subtyps, params, Univ.ContextSet.union ctx ctx' let start_module export id args res fs = let mp, res_entry_o, subtyps, _, _ = start_module_core id args res fs in openmod_info := { cur_typ = res_entry_o; cur_typs = subtyps }; let _ = Lib.Interp.start_module export id mp fs in mp let end_module_core id m_info objects fs = let {Lib.Interp.substobjs = substitute; keepobjs = keep; anticipateobjs = special; } = objects in let sobjs0, keep = match m_info.cur_typ with | None -> ([], Objs substitute), keep | Some (mty, inline) -> InterpVisitor.get_module_sobjs false (Global.env()) inline mty, [] in let struc = current_struct () in let restype' = Option.map (fun (ty,inl) -> (([],ty),inl)) m_info.cur_typ in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, (_, cst) = Mod_typing.finalize_module state (Global.env ()) (Global.current_modpath ()) (struc, current_modresolver ()) restype' in let () = Global.add_constraints cst in let mp,mbids,resolver = Global.end_module fs id m_info.cur_typ in let sobjs = let (ms,objs) = sobjs0 in (mbids@ms,objs) in let () = check_subtypes mp m_info.cur_typs in let sobjs = match m_info.cur_typ with | None -> sobjs | Some (mty, _) -> subst_sobjs (map_mp (get_module_path mty) mp resolver) sobjs in let node = ModuleObject (id,sobjs) in let objects = match keep, mbids with | [], _ | _, _ :: _ -> special@[node] | _ -> special@[node;KeepObject (id,keep)] in mp, objects let end_module () = let oldprefix,fs,objects = Lib.Interp.end_module () in let m_info = !openmod_info in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let mp,objects = end_module_core id m_info objects fs in let () = InterpVisitor.add_leaves objects in assert (ModPath.equal oldprefix.Nametab.obj_mp mp); mp let get_functor_sobjs is_mod env inl (params,mexpr) = let (mbids, aobjs) = InterpVisitor.get_module_sobjs is_mod env inl mexpr in (List.map pi1 params @ mbids, aobjs) TODO cleanup push universes directly to global env let declare_module id args res mexpr_o fs = let mp, mty_entry_o, subs, params, ctx = start_module_core id args res fs in let env = Global.env () in let mexpr_entry_o, inl_expr, ctx' = match mexpr_o with | None -> None, default_inline (), Univ.ContextSet.empty | Some (mte, base, kind, inl) -> let (mte, ctx) = Modintern.interp_module_ast env kind base mte in Some mte, inl, ctx in let env = Environ.push_context_set ~strict:true ctx' env in let ctx = Univ.ContextSet.union ctx ctx' in let entry, inl_res = match mexpr_entry_o, mty_entry_o with | None, Some (typ, inl) -> MType (params, typ), inl | Some body, otyp -> MExpr (params, body, Option.map fst otyp), Option.cata snd (default_inline ()) otyp in let sobjs, mp0 = match entry with | MType (_,mte) | MExpr (_,_,Some mte) -> get_functor_sobjs false env inl_res (params,mte), get_module_path mte | MExpr (_,me,None) -> get_functor_sobjs true env inl_expr (params,me), get_module_path me in Summary.unfreeze_summaries ~partial:true fs; let inl = match inl_expr with | None -> None | _ -> inl_res in let () = Global.push_context_set ~strict:true ctx in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, (_, cst) = Mod_typing.translate_module state (Global.env ()) mp inl entry in let () = Global.add_constraints cst in let mp_env,resolver = Global.add_module id entry inl in assert (ModPath.equal mp (mp_of_kn (Lib.make_kn id))); assert (ModPath.equal mp mp_env); let () = check_subtypes mp subs in let sobjs = subst_sobjs (map_mp mp0 mp resolver) sobjs in InterpVisitor.add_leaf (ModuleObject (id,sobjs)); mp end end * { 6 Module types : start , end , declare } module RawModTypeOps = struct module Synterp = struct let start_modtype_core id cur_mp args mtys fs = let mp = ModPath.MPdot(cur_mp, Label.of_id id) in let args = RawModOps.Synterp.intern_args args in let mbids = List.flatten @@ List.map (fun (mbidl,_) -> mbidl) args in let sub_mty_l = RawModOps.Synterp.build_subtypes mtys in mp, mbids, args, sub_mty_l let start_modtype id args mtys fs = let mp, mbids, args, sub_mty_l = start_modtype_core id (openmod_syntax_info ()).cur_mp args mtys fs in set_openmod_syntax_info { cur_mp = mp; cur_typ = None; cur_mbids = mbids }; let prefix = Lib.Synterp.start_modtype id mp fs in Nametab.(push_dir (Until 1) (prefix.obj_dir) (GlobDirRef.DirOpenModtype prefix.obj_mp)); mp, args, sub_mty_l let end_modtype_core id mbids objects fs = let {Lib.Synterp.substobjs = substitute; keepobjs = _; anticipateobjs = special; } = objects in Summary.unfreeze_summaries ~partial:true fs; let modtypeobjs = (mbids, Objs substitute) in (special@[ModuleTypeObject (id,modtypeobjs)]) let end_modtype () = let oldprefix,fs,objects = Lib.Synterp.end_modtype () in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let objects = end_modtype_core id (openmod_syntax_info ()).cur_mbids objects fs in SynterpVisitor.add_leaves objects; (openmod_syntax_info ()).cur_mp let declare_modtype id args mtys (mty,ann) fs = let inl = inl2intopt ann in let mp, mbids, args, sub_mty_l = start_modtype_core id (openmod_syntax_info ()).cur_mp args mtys fs in let mte, base, kind = Modintern.intern_module_ast Modintern.ModType mty in let entry = mbids, mte in let sobjs = RawModOps.Synterp.get_functor_sobjs false inl entry in let subst = map_mp (get_module_path (snd entry)) mp empty_delta_resolver in let sobjs = subst_sobjs subst sobjs in Summary.unfreeze_summaries ~partial:true fs; ignore (SynterpVisitor.add_leaf (ModuleTypeObject (id,sobjs))); mp, args, (mte, base, kind, inl), sub_mty_l end module Interp = struct let openmodtype_info = Summary.ref ([] : module_type_body list) ~name:"MODTYPE-INFO" let start_modtype_core id args mtys fs = let mp = Global.start_modtype id in let params, params_ctx = RawModOps.Interp.intern_args args in let () = Global.push_context_set ~strict:true params_ctx in let env = Global.env () in let sub_mty_l, sub_mty_ctx = RawModOps.Interp.build_subtypes env mp params mtys in let () = Global.push_context_set ~strict:true sub_mty_ctx in mp, params, sub_mty_l, Univ.ContextSet.union params_ctx sub_mty_ctx let start_modtype id args mtys fs = let mp, _, sub_mty_l, _ = start_modtype_core id args mtys fs in openmodtype_info := sub_mty_l; let prefix = Lib.Interp.start_modtype id mp fs in Nametab.(push_dir (Until 1) (prefix.obj_dir) (GlobDirRef.DirOpenModtype mp)); mp let end_modtype_core id sub_mty_l objects fs = let {Lib.Interp.substobjs = substitute; keepobjs = _; anticipateobjs = special; } = objects in let mp, mbids = Global.end_modtype fs id in let () = RawModOps.Interp.check_subtypes_mt mp sub_mty_l in let modtypeobjs = (mbids, Objs substitute) in let objects = special@[ModuleTypeObject (id,modtypeobjs)] in mp, objects let end_modtype () = let oldprefix,fs,objects = Lib.Interp.end_modtype () in let olddp, id = split_dirpath oldprefix.Nametab.obj_dir in let sub_mty_l = !openmodtype_info in let mp, objects = end_modtype_core id sub_mty_l objects fs in let () = InterpVisitor.add_leaves objects in Check name consistence : start _ vs. end_modtype , kernel vs. library assert (DirPath.equal (Lib.prefix()).Nametab.obj_dir olddp); assert (ModPath.equal oldprefix.Nametab.obj_mp mp); mp let declare_modtype id args mtys (mte,base,kind,inl) fs = let mp, params, sub_mty_l, ctx = start_modtype_core id args mtys fs in let env = Global.env () in let mte, mte_ctx = Modintern.interp_module_ast env kind base mte in let () = Global.push_context_set ~strict:true mte_ctx in let env = Global.env () in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let _, _, _, (_, mte_cst) = Mod_typing.translate_mse state env None inl mte in let () = Global.push_context_set ~strict:true (Univ.Level.Set.empty,mte_cst) in let entry = params, mte in let env = Global.env () in let sobjs = RawModOps.Interp.get_functor_sobjs false env inl entry in let subst = map_mp (get_module_path (snd entry)) mp empty_delta_resolver in let sobjs = subst_sobjs subst sobjs in Summary.unfreeze_summaries ~partial:true fs; let () = Global.push_context_set ~strict:true ctx in let () = Global.push_context_set ~strict:true mte_ctx in let () = Global.push_context_set ~strict:true (Univ.Level.Set.empty,mte_cst) in let mp_env = Global.add_modtype id entry inl in assert (ModPath.equal mp_env mp); let () = RawModOps.Interp.check_subtypes_mt mp sub_mty_l in InterpVisitor.add_leaf (ModuleTypeObject (id, sobjs)); mp end end * { 6 Include } module RawIncludeOps = struct exception NoIncludeSelf module Synterp = struct let rec include_subst mp mbids = match mbids with | [] -> empty_subst | mbid::mbids -> let subst = include_subst mp mbids in join (map_mbid mbid mp empty_delta_resolver) subst let declare_one_include_core cur_mp (me_ast,annot) = let me, base, kind = Modintern.intern_module_ast Modintern.ModAny me_ast in let is_mod = (kind == Modintern.Module) in let inl = inl2intopt annot in let mbids,aobjs = SynterpVisitor.get_module_sobjs is_mod () inl me in let subst_self = try if List.is_empty mbids then raise NoIncludeSelf; include_subst cur_mp mbids with NoIncludeSelf -> empty_subst in let base_mp = get_module_path me in let subst = join subst_self (map_mp base_mp cur_mp empty_delta_resolver) in let aobjs = subst_aobjs subst aobjs in (me, base, kind, inl), aobjs let declare_one_include (me_ast,annot) = let res, aobjs = declare_one_include_core (openmod_syntax_info ()).cur_mp (me_ast,annot) in SynterpVisitor.add_leaf (IncludeObject aobjs); res let declare_include me_asts = List.map declare_one_include me_asts end module Interp = struct let rec include_subst env mp reso mbids sign inline = match mbids with | [] -> empty_subst | mbid::mbids -> let farg_id, farg_b, fbody_b = Modops.destr_functor sign in let subst = include_subst env mp reso mbids fbody_b inline in let mp_delta = Modops.inline_delta_resolver env inline mp farg_id farg_b reso in join (map_mbid mbid mp mp_delta) subst let rec decompose_functor mpl typ = match mpl, typ with | [], _ -> typ | _::mpl, MoreFunctor(_,_,str) -> decompose_functor mpl str | _ -> user_err Pp.(str "Application of a functor with too much arguments.") let type_of_incl env is_mod = function | MEident mp -> type_of_mod mp env is_mod | MEapply _ as me -> let mp0, mp_l = InterpVisitor.get_applications me in decompose_functor mp_l (type_of_mod mp0 env is_mod) | MEwith _ -> raise NoIncludeSelf let declare_one_include_core (me,base,kind,inl) = let env = Global.env() in let me, cst = Modintern.interp_module_ast env kind base me in let () = Global.push_context_set ~strict:true cst in let env = Global.env () in let is_mod = (kind == Modintern.Module) in let cur_mp = Global.current_modpath () in let mbids,aobjs = InterpVisitor.get_module_sobjs is_mod env inl me in let subst_self = try if List.is_empty mbids then raise NoIncludeSelf; let typ = type_of_incl env is_mod me in let reso = RawModOps.Interp.current_modresolver () in include_subst env cur_mp reso mbids typ inl with NoIncludeSelf -> empty_subst in let base_mp = get_module_path me in let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let sign, (), resolver, (_, cst) = Mod_typing.translate_mse_include is_mod state (Global.env ()) (Global.current_modpath ()) inl me in let () = Global.add_constraints cst in let () = assert (ModPath.equal cur_mp (Global.current_modpath ())) in let mb = { mod_mp = cur_mp; mod_expr = (); mod_type = RawModOps.Interp.current_struct (); mod_type_alg = None; mod_delta = RawModOps.Interp.current_modresolver (); mod_retroknowledge = ModTypeRK } in let rec compute_sign sign = match sign with | MoreFunctor(mbid,mtb,str) -> let state = ((Global.universes (), Univ.Constraints.empty), Reductionops.inferred_universes) in let (_, cst) = Subtyping.check_subtypes state (Global.env ()) mb mtb in let () = Global.add_constraints cst in let mpsup_delta = Modops.inline_delta_resolver (Global.env ()) inl cur_mp mbid mtb mb.mod_delta in let subst = Mod_subst.map_mbid mbid cur_mp mpsup_delta in compute_sign (Modops.subst_signature subst str) | NoFunctor str -> () in let () = compute_sign sign in let resolver = Global.add_include me is_mod inl in let subst = join subst_self (map_mp base_mp cur_mp resolver) in subst_aobjs subst aobjs let declare_one_include (me,base,kind,inl) = let aobjs = declare_one_include_core (me,base,kind,inl) in InterpVisitor.add_leaf (IncludeObject aobjs) let declare_include me_asts = List.iter declare_one_include me_asts end end * { 6 Module operations handling summary freeze / unfreeze } let protect_summaries stage f = let fs = Summary.freeze_staged_summaries stage ~marshallable:false in try f fs with reraise -> let reraise = Exninfo.capture reraise in let () = Summary.unfreeze_summaries ~partial:true fs in Exninfo.iraise reraise * { 6 Libraries } type library_name = DirPath.t type library_objects = Libobject.t list * Libobject.t list module Synterp = struct let start_module export id args res = protect_summaries Summary.Stage.Synterp (RawModOps.Synterp.start_module export id args res) let end_module = RawModOps.Synterp.end_module let declare_module_includes id args res mexpr_l fs = let mp, res_entry_o, mbids, sign, args = RawModOps.Synterp.start_module_core id args res fs in let mod_info = { cur_mp = mp; cur_typ = res_entry_o; cur_mbids = mbids } in let includes = List.map_left (RawIncludeOps.Synterp.declare_one_include_core mp) mexpr_l in let bodies, incl_objs = List.split includes in let incl_objs = List.map (fun x -> IncludeObject x) incl_objs in let objects = Lib.Synterp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let mp, objects = RawModOps.Synterp.end_module_core id mod_info objects fs in SynterpVisitor.add_leaves objects; mp, args, bodies, sign let declare_modtype_includes id args res mexpr_l fs = let mp, mbids, args, subtyps = RawModTypeOps.Synterp.start_modtype_core id (openmod_syntax_info ()).cur_mp args res fs in let includes = List.map_left (RawIncludeOps.Synterp.declare_one_include_core mp) mexpr_l in let bodies, incl_objs = List.split includes in let incl_objs = List.map (fun x -> IncludeObject x) incl_objs in let objects = Lib.Synterp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let objects = RawModTypeOps.Synterp.end_modtype_core id mbids objects fs in SynterpVisitor.add_leaves objects; mp, args, bodies, subtyps let declare_module id args mtys me_l = let declare_me fs = match me_l with | [] -> let mp, args, body, sign = RawModOps.Synterp.declare_module id args mtys None fs in assert (Option.is_empty body); mp, args, [], sign | [me] -> let mp, args, body, sign = RawModOps.Synterp.declare_module id args mtys (Some me) fs in mp, args, [Option.get body], sign | me_l -> declare_module_includes id args mtys me_l fs in protect_summaries Summary.Stage.Synterp declare_me let start_modtype id args mtys = protect_summaries Summary.Stage.Synterp (RawModTypeOps.Synterp.start_modtype id args mtys) let end_modtype = RawModTypeOps.Synterp.end_modtype let declare_modtype id args mtys mty_l = let declare_mt fs = match mty_l with | [] -> assert false | [mty] -> let mp, args, body, sign = RawModTypeOps.Synterp.declare_modtype id args mtys mty fs in mp, args, [body], sign | mty_l -> declare_modtype_includes id args mtys mty_l fs in protect_summaries Summary.Stage.Synterp declare_mt let declare_include me_asts = protect_summaries Summary.Stage.Synterp (fun _ -> RawIncludeOps.Synterp.declare_include me_asts) let register_library dir (objs:library_objects) = let mp = MPfile dir in let sobjs,keepobjs = objs in SynterpVisitor.do_module SynterpVisitor.load_objects 1 dir mp ([],Objs sobjs) keepobjs let import_modules ~export mpl = let _,objs = SynterpVisitor.collect_modules mpl (MPmap.empty, []) in List.iter (fun (f,o) -> SynterpVisitor.open_object f 1 o) objs; match export with | Lib.Import -> () | Lib.Export -> let entry = ExportObject { mpl } in Lib.Synterp.add_leaf_entry entry let import_module f ~export mp = import_modules ~export [f,mp] end module Interp = struct let start_module export id args sign = protect_summaries Summary.Stage.Interp (RawModOps.Interp.start_module export id args sign) let end_module = RawModOps.Interp.end_module let declare_module_includes id args res mexpr_l fs = let mp, res_entry_o, subtyps, _, _ = RawModOps.Interp.start_module_core id args res fs in let mod_info = { cur_typ = res_entry_o; cur_typs = subtyps } in let incl_objs = List.map_left (fun x -> IncludeObject (RawIncludeOps.Interp.declare_one_include_core x)) mexpr_l in let objects = Lib.Interp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let mp, objects = RawModOps.Interp.end_module_core id mod_info objects fs in InterpVisitor.add_leaves objects; mp let declare_modtype_includes id args res mexpr_l fs = let mp, _, subtyps, _ = RawModTypeOps.Interp.start_modtype_core id args res fs in let incl_objs = List.map_left (fun x -> IncludeObject (RawIncludeOps.Interp.declare_one_include_core x)) mexpr_l in let objects = Lib.Interp.{ substobjs = incl_objs; keepobjs = []; anticipateobjs = []; } in let mp, objects = RawModTypeOps.Interp.end_modtype_core id subtyps objects fs in InterpVisitor.add_leaves objects; mp let declare_module id args mtys me_l = let declare_me fs = match me_l with | [] -> RawModOps.Interp.declare_module id args mtys None fs | [me] -> RawModOps.Interp.declare_module id args mtys (Some me) fs | me_l -> declare_module_includes id args mtys me_l fs in protect_summaries Summary.Stage.Interp declare_me let start_modtype id args mtys = protect_summaries Summary.Stage.Interp (RawModTypeOps.Interp.start_modtype id args mtys) let end_modtype = RawModTypeOps.Interp.end_modtype let declare_modtype id args mtys mty_l = let declare_mt fs = match mty_l with | [] -> assert false | [mty] -> RawModTypeOps.Interp.declare_modtype id args mtys mty fs | mty_l -> declare_modtype_includes id args mtys mty_l fs in protect_summaries Summary.Stage.Interp declare_mt let declare_include me_asts = if Lib.sections_are_opened () then user_err Pp.(str "Include is not allowed inside sections."); protect_summaries Summary.Stage.Interp (fun _ -> RawIncludeOps.Interp.declare_include me_asts) let register_library dir cenv (objs:library_objects) digest univ = let mp = MPfile dir in let () = try ignore(Global.lookup_module mp); with Not_found -> begin let mp' = Global.import cenv univ digest in if not (ModPath.equal mp mp') then anomaly (Pp.str "Unexpected disk module name.") end in let sobjs,keepobjs = objs in InterpVisitor.do_module InterpVisitor.load_objects 1 dir mp ([],Objs sobjs) keepobjs let import_modules ~export mpl = let _,objs = InterpVisitor.collect_modules mpl (MPmap.empty, []) in List.iter (fun (f,o) -> InterpVisitor.open_object f 1 o) objs; match export with | Lib.Import -> () | Lib.Export -> let entry = ExportObject { mpl } in Lib.Interp.add_leaf_entry entry let import_module f ~export mp = import_modules ~export [f,mp] end let end_library_hook = ref [] let append_end_library_hook f = end_library_hook := f :: !end_library_hook let end_library_hook () = List.iter (fun f -> f ()) (List.rev !end_library_hook) let end_library ~output_native_objects dir = end_library_hook(); let prefix, lib_stack, lib_stack_syntax = Lib.end_compilation dir in let mp,cenv,ast = Global.export ~output_native_objects dir in assert (ModPath.equal mp (MPfile dir)); let {Lib.Interp.substobjs = substitute; keepobjs = keep; anticipateobjs = _; } = lib_stack in let {Lib.Synterp.substobjs = substitute_syntax; keepobjs = keep_syntax; anticipateobjs = _; } = lib_stack_syntax in cenv,(substitute,keep),(substitute_syntax,keep_syntax),ast * { 6 Iterators } let iter_all_interp_segments f = let rec apply_obj prefix obj = match obj with | IncludeObject aobjs -> let objs = InterpVisitor.expand_aobjs aobjs in List.iter (apply_obj prefix) objs | _ -> f prefix obj in let apply_mod_obj _ modobjs = let prefix = modobjs.module_prefix in List.iter (apply_obj prefix) modobjs.module_substituted_objects; List.iter (apply_obj prefix) modobjs.module_keep_objects in let apply_nodes (node, os) = List.iter (fun o -> f (Lib.node_prefix node) o) os in MPmap.iter apply_mod_obj (InterpVisitor.ModObjs.all ()); List.iter apply_nodes (Lib.contents ()) * { 6 Some types used to shorten declaremods.mli } type module_params = (lident list * (Constrexpr.module_ast * inline)) list type module_expr = (Modintern.module_struct_expr * ModPath.t * Modintern.module_kind * Entries.inline) type module_params_expr = (MBId.t list * module_expr) list * { 6 Debug } let debug_print_modtab () = InterpVisitor.debug_print_modtab () * For printing modules , [ process_module_binding ] adds names of bound module ( and its components ) to Nametab . It also loads objects associated to it . bound module (and its components) to Nametab. It also loads objects associated to it. *) let process_module_binding mbid me = let dir = DirPath.make [MBId.to_id mbid] in let mp = MPbound mbid in let sobjs = InterpVisitor.get_module_sobjs false (Global.env()) (default_inline ()) me in let subst = map_mp (get_module_path me) mp empty_delta_resolver in let sobjs = subst_sobjs subst sobjs in SynterpVisitor.do_module SynterpVisitor.load_objects 1 dir mp sobjs []; InterpVisitor.do_module InterpVisitor.load_objects 1 dir mp sobjs [] let import_module f ~export mp = Synterp.import_module f ~export mp; Interp.import_module f ~export mp let declare_module id args mtys me_l = let mp, args, bodies, sign = Synterp.declare_module id args mtys me_l in Interp.declare_module id args sign bodies let start_module export id args res = let mp, args, sign = Synterp.start_module export id args res in Interp.start_module export id args sign let end_module () = let _mp = Synterp.end_module () in Interp.end_module () let declare_modtype id args mtys mty_l = let mp, args, bodies, subtyps = Synterp.declare_modtype id args mtys mty_l in Interp.declare_modtype id args subtyps bodies let start_modtype id args mtys = let mp, args, sub_mty_l = Synterp.start_modtype id args mtys in Interp.start_modtype id args sub_mty_l let end_modtype () = let _mp = Synterp.end_modtype () in Interp.end_modtype () let declare_include me_asts = let l = Synterp.declare_include me_asts in Interp.declare_include l
c9212bad80ae157538c6fce2250d17e0d5b28f647678b8e3e9eebf56e0b4edab
ferd/erlpass
erlpass.erl
@author < > [ / ] @doc is a simple wrapper library trying to abstract away common %% password operations using safe algorithms, in this case, bcrypt. -module(erlpass). -export([hash/1, hash/2, match/2, change/3, change/4]). -define(DEFAULT_WORK_FACTOR, 12). -type password() :: iodata(). %% A password, supports valid unicode. -type work_factor() :: 4..31. %% Work factor of the bcrypt algorithm. -type hash() :: binary(). %% The hashed password with a given work factor. -export_type([password/0, work_factor/0, hash/0]). @doc Similar to { @link hash/2 . < code > hash(Password , 12)</code > } . -spec hash(password()) -> hash(). hash(S) when is_binary(S); is_list(S) -> hash(S, ?DEFAULT_WORK_FACTOR). %% @doc Hashes a given {@link password(). <code>password</code>} with a given { @link work_factor ( ) . work factor } . Bcrypt will be used to create %% a {@link hash(). hash} of the password to be stored by the application. Compare the password to the hash by using { @link . < code > match/2</code > } . Bcrypt takes care of salting the hashes for you so this does not need to be %% done. The higher the work factor, the longer the password will take to be %% hashed and checked. -spec hash(password(), work_factor()) -> hash(). hash(Str, Factor) -> {ok, Hash} = bcrypt:hashpw(format_pass(Str), element(2, bcrypt:gen_salt(Factor))), list_to_binary(Hash). %% @doc Compares a given password to a hash. Returns <code>true</code> if %% the password matches, and <code>false</code> otherwise. The comparison %% is done in constant time (based on the hash length) -spec match(password(), hash()) -> boolean(). match(Pass, Hash) -> LHash = binary_to_list(Hash), {ok, ResHash} = bcrypt:hashpw(format_pass(Pass), LHash), verify_in_constant_time(LHash, ResHash). %% @doc If a given {@link password(). password} matches a given %% {@link hash(). hash}, the password is re-hashed again using %% the new {@link work_factor(). work factor}. This allows to update a %% given work factor to something stronger. @equiv change(Pass , Hash , Pass , Factor ) -spec change(password(), hash(), work_factor()) -> hash() | {error, bad_password}. change(Pass, Hash, Factor) -> change(Pass, Hash, Pass, Factor). %% @doc If a given old {@link password(). password} matches a given old %% {@link hash(). hash}, a new {@link password(). password} is hashed using the %% {@link work_factor(). work factor} passed in as an argument. %% Allows to safely change a password, only if the previous one was given %% with it. -spec change(password(), hash(), password(), work_factor()) -> hash() | {error, bad_password}. change(OldPass, Hash, NewPass, Factor) -> case match(OldPass, Hash) of true -> hash(NewPass, Factor); false -> {error, bad_password} end. %%% PRIVATE %% This 'list_to_binary' stuff is risky -- no idea what the implementation %% is like. %% We have to support unicode %% @doc transforms a given {@link password(). password} in a safe binary format %% that can be understood by the bcrypt library. -spec format_pass(iodata()) -> binary(). format_pass(Str) when is_list(Str) -> case unicode:characters_to_binary(Str) of {error, _Good, _Bad} -> list_to_binary(Str); {incomplete, _Good, _Bad} -> list_to_binary(Str); Bin -> Bin end; format_pass(Bin) when is_binary(Bin) -> Bin. @doc Verifies two hashes for matching purpose , in constant time . That allows %% a safer verification as no attacker can use the time it takes to compare hash %% values to find an attack vector (past figuring out the complexity) verify_in_constant_time([X|RestX], [Y|RestY], Result) -> verify_in_constant_time(RestX, RestY, (X bxor Y) bor Result); verify_in_constant_time([], [], Result) -> Result == 0. verify_in_constant_time(X, Y) when is_list(X) and is_list(Y) -> case length(X) == length(Y) of true -> verify_in_constant_time(X, Y, 0); false -> false end; verify_in_constant_time(_X, _Y) -> false.
null
https://raw.githubusercontent.com/ferd/erlpass/34bb7ca3dab46094893a5b31f0e6f2ffa60f2641/src/erlpass.erl
erlang
password operations using safe algorithms, in this case, bcrypt. A password, supports valid unicode. Work factor of the bcrypt algorithm. The hashed password with a given work factor. @doc Hashes a given {@link password(). <code>password</code>} with a given a {@link hash(). hash} of the password to be stored by the application. done. The higher the work factor, the longer the password will take to be hashed and checked. @doc Compares a given password to a hash. Returns <code>true</code> if the password matches, and <code>false</code> otherwise. The comparison is done in constant time (based on the hash length) @doc If a given {@link password(). password} matches a given {@link hash(). hash}, the password is re-hashed again using the new {@link work_factor(). work factor}. This allows to update a given work factor to something stronger. @doc If a given old {@link password(). password} matches a given old {@link hash(). hash}, a new {@link password(). password} is hashed using the {@link work_factor(). work factor} passed in as an argument. Allows to safely change a password, only if the previous one was given with it. PRIVATE This 'list_to_binary' stuff is risky -- no idea what the implementation is like. We have to support unicode @doc transforms a given {@link password(). password} in a safe binary format that can be understood by the bcrypt library. a safer verification as no attacker can use the time it takes to compare hash values to find an attack vector (past figuring out the complexity)
@author < > [ / ] @doc is a simple wrapper library trying to abstract away common -module(erlpass). -export([hash/1, hash/2, match/2, change/3, change/4]). -define(DEFAULT_WORK_FACTOR, 12). -type password() :: iodata(). -type work_factor() :: 4..31. -type hash() :: binary(). -export_type([password/0, work_factor/0, hash/0]). @doc Similar to { @link hash/2 . < code > hash(Password , 12)</code > } . -spec hash(password()) -> hash(). hash(S) when is_binary(S); is_list(S) -> hash(S, ?DEFAULT_WORK_FACTOR). { @link work_factor ( ) . work factor } . Bcrypt will be used to create Compare the password to the hash by using { @link . < code > match/2</code > } . Bcrypt takes care of salting the hashes for you so this does not need to be -spec hash(password(), work_factor()) -> hash(). hash(Str, Factor) -> {ok, Hash} = bcrypt:hashpw(format_pass(Str), element(2, bcrypt:gen_salt(Factor))), list_to_binary(Hash). -spec match(password(), hash()) -> boolean(). match(Pass, Hash) -> LHash = binary_to_list(Hash), {ok, ResHash} = bcrypt:hashpw(format_pass(Pass), LHash), verify_in_constant_time(LHash, ResHash). @equiv change(Pass , Hash , Pass , Factor ) -spec change(password(), hash(), work_factor()) -> hash() | {error, bad_password}. change(Pass, Hash, Factor) -> change(Pass, Hash, Pass, Factor). -spec change(password(), hash(), password(), work_factor()) -> hash() | {error, bad_password}. change(OldPass, Hash, NewPass, Factor) -> case match(OldPass, Hash) of true -> hash(NewPass, Factor); false -> {error, bad_password} end. -spec format_pass(iodata()) -> binary(). format_pass(Str) when is_list(Str) -> case unicode:characters_to_binary(Str) of {error, _Good, _Bad} -> list_to_binary(Str); {incomplete, _Good, _Bad} -> list_to_binary(Str); Bin -> Bin end; format_pass(Bin) when is_binary(Bin) -> Bin. @doc Verifies two hashes for matching purpose , in constant time . That allows verify_in_constant_time([X|RestX], [Y|RestY], Result) -> verify_in_constant_time(RestX, RestY, (X bxor Y) bor Result); verify_in_constant_time([], [], Result) -> Result == 0. verify_in_constant_time(X, Y) when is_list(X) and is_list(Y) -> case length(X) == length(Y) of true -> verify_in_constant_time(X, Y, 0); false -> false end; verify_in_constant_time(_X, _Y) -> false.
f15cf7e8cb0175635f75951bc2decd79a126c99b9f3934bd08f4ffac355b828e
hammerlab/coclobas
client.ml
open Internal_pervasives type t = { base_url: string [@main]; } [@@deriving yojson, show, make] let wrap_io d = Deferred_result.wrap_deferred d ~on_exn:(fun e -> `Client (`IO_exn e)) let wrap_parsing d = Deferred_result.wrap_deferred d ~on_exn:(fun e -> `Client (`Json_exn e)) let do_get uri = wrap_io Lwt.(fun () -> Cohttp_lwt_unix.Client.get uri >>= fun (resp, body) -> Cohttp_lwt_body.to_string body >>= fun b -> return (resp, b) ) let uri_of_ids base_url path ids = Uri.with_query (Uri.with_path (Uri.of_string base_url) path) ["id", ids] let response_is_ok ~uri ~meth ~body resp = begin match Cohttp.Response.status resp with | `OK -> return () | other -> fail (`Client (`Response (meth, uri, resp, body))) end let submit_job {base_url} spec = let uri = Uri.with_path (Uri.of_string base_url) "job/submit" in let body = Cohttp_lwt_body.of_string (Job.Specification.to_yojson spec |> Yojson.Safe.pretty_to_string) in wrap_io (fun () -> Cohttp_lwt_unix.Client.post uri ~body) >>= fun (resp, ret_body) -> wrap_io (fun () -> Cohttp_lwt_body.to_string ret_body) >>= fun body -> response_is_ok resp ~meth:`Post ~uri ~body >>= fun () -> return body let get_job_jsons {base_url} ~path ~ids = let uri = uri_of_ids base_url path ids in do_get uri >>= fun (resp, body) -> response_is_ok ~body resp ~meth:`Get ~uri >>= fun () -> wrap_parsing (fun () -> Lwt.return (Yojson.Safe.from_string body)) let get_job_json_one_key t ~path ~ids ~json_key ~of_yojson = get_job_jsons t ~path ~ids >>= fun json -> let uri = uri_of_ids t.base_url path ids in (* Only for error values: *) begin match json with | `List l -> Deferred_list.while_sequential l ~f:(function | `Assoc ["id", `String id; key, stjson] when key = json_key -> wrap_parsing Lwt.(fun () -> let open Ppx_deriving_yojson_runtime.Result in match of_yojson stjson with | Ok s -> return (id, s) | Error e -> fail (Failure e) ) | other -> fail (`Client (`Json_parsing (uri, "Not an Assoc", other))) ) | other -> fail (`Client (`Json_parsing (uri, "Not a List", other))) end let get_job_states t ids = get_job_json_one_key t ~path:"job/state" ~ids ~json_key:"state" ~of_yojson:Job.of_yojson let get_json_keys ~uri ~parsers json = begin match json with | `List l -> Deferred_list.while_sequential l ~f:(function | `Assoc kv as jkv-> Deferred_list.while_sequential parsers ~f:(fun (key, of_yojson) -> match List.find kv ~f:(fun (k, v) -> k = key) with | Some (_, vjson) -> wrap_parsing Lwt.(fun () -> match of_yojson vjson with | `Ok s -> return s | `Error e -> fail (Failure e) ) | None -> fail (`Client (`Json_parsing (uri, "No key: " ^ key, jkv))) ) | other -> fail (`Client (`Json_parsing (uri, "Not an Assoc", other))) ) | other -> fail (`Client (`Json_parsing (uri, "Not a List", other))) end (* For describe or logs *) let get_job_query_result ~path t ids = get_job_jsons t ~path ~ids >>= fun json -> let uri = uri_of_ids t.base_url path ids in (* Only for error values: *) begin match json with | `List l -> Deferred_list.while_sequential l ~f:(function | `Assoc ["id", `String id; "output", yoj] -> begin match (Job_common.Query_result.of_yojson yoj) with | Ok output -> return (id, output) | Error e -> fail (`Client (`Json_parsing (uri, "Not an query-result", yoj))) end | other -> fail (`Client (`Json_parsing (uri, "Not an {id: ... output: ...}", other))) ) | other -> fail (`Client (`Json_parsing (uri, "Not a List", other))) end let get_job_descriptions t ids = get_job_query_result ~path:"job/describe" t ids let get_job_logs t ids = get_job_query_result ~path:"job/logs" t ids let kill_jobs {base_url} ids = let uri = uri_of_ids base_url "job/kill" ids in do_get uri >>= fun (resp, body) -> response_is_ok resp ~body ~meth:`Get ~uri let get_server_status_string {base_url} = let uri = Uri.with_path (Uri.of_string base_url) "status" in do_get uri >>= fun (resp, body) -> response_is_ok resp ~body ~meth:`Get ~uri >>= fun () -> return body let get_cluster_description {base_url} = let uri = Uri.with_path (Uri.of_string base_url) "cluster/describe" in do_get uri >>= fun (resp, body) -> response_is_ok resp ~body ~meth:`Get ~uri >>= fun () -> return body let get_job_list {base_url} = let uri = Uri.with_path (Uri.of_string base_url) "jobs" in do_get uri >>= fun (resp, body) -> let json = Yojson.Safe.from_string body in let get_string name = function | `String i -> `Ok i | other -> `Error (sprintf "%s not a string" name) in get_json_keys ~uri json ~parsers:[ "id", get_string "status"; "status", get_string "status"; ] >>= fun (res : string list list) -> Deferred_list.while_sequential res ~f:( function | [id; status] -> return (`Id id, `Status status) | other -> ksprintf failwith "This should never happen: 2 parsers Vs %d results: [%s]" (List.length other) (String.concat ~sep:", " other) ) module Error = struct let to_string = function | `IO_exn e -> sprintf "Client.IO: %s" (Printexc.to_string e) | `Json_exn e -> sprintf "Client.Json-parsing: %s" (Printexc.to_string e) | `Json_parsing (uri, problem, json) -> sprintf "Client.Json-parsing: URI: %s, problem: %s, content: %s" (Uri.to_string uri) problem (Yojson.Safe.pretty_to_string json) | `Response (meth, uri, resp, body) -> sprintf "Client.Response: URI: %s, Meth: %s, Resp: %s, Body: %s" (Uri.to_string uri) begin match meth with | `Post -> "POST" | `Get -> "GET" end (Cohttp.Response.sexp_of_t resp |> Sexplib.Sexp.to_string_hum) body end
null
https://raw.githubusercontent.com/hammerlab/coclobas/5341ea53fdb5bcea0dfac3e4bd94213b34a48bb9/src/lib/client.ml
ocaml
Only for error values: For describe or logs Only for error values:
open Internal_pervasives type t = { base_url: string [@main]; } [@@deriving yojson, show, make] let wrap_io d = Deferred_result.wrap_deferred d ~on_exn:(fun e -> `Client (`IO_exn e)) let wrap_parsing d = Deferred_result.wrap_deferred d ~on_exn:(fun e -> `Client (`Json_exn e)) let do_get uri = wrap_io Lwt.(fun () -> Cohttp_lwt_unix.Client.get uri >>= fun (resp, body) -> Cohttp_lwt_body.to_string body >>= fun b -> return (resp, b) ) let uri_of_ids base_url path ids = Uri.with_query (Uri.with_path (Uri.of_string base_url) path) ["id", ids] let response_is_ok ~uri ~meth ~body resp = begin match Cohttp.Response.status resp with | `OK -> return () | other -> fail (`Client (`Response (meth, uri, resp, body))) end let submit_job {base_url} spec = let uri = Uri.with_path (Uri.of_string base_url) "job/submit" in let body = Cohttp_lwt_body.of_string (Job.Specification.to_yojson spec |> Yojson.Safe.pretty_to_string) in wrap_io (fun () -> Cohttp_lwt_unix.Client.post uri ~body) >>= fun (resp, ret_body) -> wrap_io (fun () -> Cohttp_lwt_body.to_string ret_body) >>= fun body -> response_is_ok resp ~meth:`Post ~uri ~body >>= fun () -> return body let get_job_jsons {base_url} ~path ~ids = let uri = uri_of_ids base_url path ids in do_get uri >>= fun (resp, body) -> response_is_ok ~body resp ~meth:`Get ~uri >>= fun () -> wrap_parsing (fun () -> Lwt.return (Yojson.Safe.from_string body)) let get_job_json_one_key t ~path ~ids ~json_key ~of_yojson = get_job_jsons t ~path ~ids >>= fun json -> begin match json with | `List l -> Deferred_list.while_sequential l ~f:(function | `Assoc ["id", `String id; key, stjson] when key = json_key -> wrap_parsing Lwt.(fun () -> let open Ppx_deriving_yojson_runtime.Result in match of_yojson stjson with | Ok s -> return (id, s) | Error e -> fail (Failure e) ) | other -> fail (`Client (`Json_parsing (uri, "Not an Assoc", other))) ) | other -> fail (`Client (`Json_parsing (uri, "Not a List", other))) end let get_job_states t ids = get_job_json_one_key t ~path:"job/state" ~ids ~json_key:"state" ~of_yojson:Job.of_yojson let get_json_keys ~uri ~parsers json = begin match json with | `List l -> Deferred_list.while_sequential l ~f:(function | `Assoc kv as jkv-> Deferred_list.while_sequential parsers ~f:(fun (key, of_yojson) -> match List.find kv ~f:(fun (k, v) -> k = key) with | Some (_, vjson) -> wrap_parsing Lwt.(fun () -> match of_yojson vjson with | `Ok s -> return s | `Error e -> fail (Failure e) ) | None -> fail (`Client (`Json_parsing (uri, "No key: " ^ key, jkv))) ) | other -> fail (`Client (`Json_parsing (uri, "Not an Assoc", other))) ) | other -> fail (`Client (`Json_parsing (uri, "Not a List", other))) end let get_job_query_result ~path t ids = get_job_jsons t ~path ~ids >>= fun json -> begin match json with | `List l -> Deferred_list.while_sequential l ~f:(function | `Assoc ["id", `String id; "output", yoj] -> begin match (Job_common.Query_result.of_yojson yoj) with | Ok output -> return (id, output) | Error e -> fail (`Client (`Json_parsing (uri, "Not an query-result", yoj))) end | other -> fail (`Client (`Json_parsing (uri, "Not an {id: ... output: ...}", other))) ) | other -> fail (`Client (`Json_parsing (uri, "Not a List", other))) end let get_job_descriptions t ids = get_job_query_result ~path:"job/describe" t ids let get_job_logs t ids = get_job_query_result ~path:"job/logs" t ids let kill_jobs {base_url} ids = let uri = uri_of_ids base_url "job/kill" ids in do_get uri >>= fun (resp, body) -> response_is_ok resp ~body ~meth:`Get ~uri let get_server_status_string {base_url} = let uri = Uri.with_path (Uri.of_string base_url) "status" in do_get uri >>= fun (resp, body) -> response_is_ok resp ~body ~meth:`Get ~uri >>= fun () -> return body let get_cluster_description {base_url} = let uri = Uri.with_path (Uri.of_string base_url) "cluster/describe" in do_get uri >>= fun (resp, body) -> response_is_ok resp ~body ~meth:`Get ~uri >>= fun () -> return body let get_job_list {base_url} = let uri = Uri.with_path (Uri.of_string base_url) "jobs" in do_get uri >>= fun (resp, body) -> let json = Yojson.Safe.from_string body in let get_string name = function | `String i -> `Ok i | other -> `Error (sprintf "%s not a string" name) in get_json_keys ~uri json ~parsers:[ "id", get_string "status"; "status", get_string "status"; ] >>= fun (res : string list list) -> Deferred_list.while_sequential res ~f:( function | [id; status] -> return (`Id id, `Status status) | other -> ksprintf failwith "This should never happen: 2 parsers Vs %d results: [%s]" (List.length other) (String.concat ~sep:", " other) ) module Error = struct let to_string = function | `IO_exn e -> sprintf "Client.IO: %s" (Printexc.to_string e) | `Json_exn e -> sprintf "Client.Json-parsing: %s" (Printexc.to_string e) | `Json_parsing (uri, problem, json) -> sprintf "Client.Json-parsing: URI: %s, problem: %s, content: %s" (Uri.to_string uri) problem (Yojson.Safe.pretty_to_string json) | `Response (meth, uri, resp, body) -> sprintf "Client.Response: URI: %s, Meth: %s, Resp: %s, Body: %s" (Uri.to_string uri) begin match meth with | `Post -> "POST" | `Get -> "GET" end (Cohttp.Response.sexp_of_t resp |> Sexplib.Sexp.to_string_hum) body end
8d8bb925757433b9c01d8a543bfce6ebb79bff537177bfad9b7ec8ffa18b160a
ghc/ghc
GenManyUbxSums.hs
#!/usr/bin/env runghc # LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # # LANGUAGE UnboxedSums # -- This little piece of code constructs a large set of functions -- constructing and deconstructing unboxed tuples of various types. module Main where import GHC.Exts import System.IO import Data.List (intersperse) inputs = ["Int", "Word"] sizes = ["","8","16","32","64"] -- ["Addr#","Int#","Int8#","Int16#","Int32#","Int64#","Word#","Word8#","Word16#","Word32#","Word64#"] types = "Addr#" : do r <- inputs s <- sizes return $ r++s++"#" We eventually build two sums , one of type ( # t1 | t2 # ) and one of ( # t1 | t3 ) . So we build all possible combinations of three types here . combos = do t1 <- types t2 <- types t3 <- types return (t1,t2,t3) mkCon ty = case ty of "Addr#" -> "Addr" "Int#" -> "I#" "Int8#" -> "I8#" "Int16#" -> "I16#" "Int32#" -> "I32#" "Int64#" -> "I64#" "Word#" -> "W#" "Word8#" -> "W8#" "Word16#" -> "W16#" "Word32#" -> "W32#" "Word64#" -> "W64#" Construct a function like the one below , varying the types in the sums based on the -- given type tuples. We need to NOINLINE or the function will be constant folded away . { - # NOINLINE fun0 # - } -- fun0 :: (# Addr# | I16# #) -> (# Addr# | I# #) -- fun0 x = case x of ( # x1 | # ) - > ( # x1 | # ) : : ( # Addr # | I # # ) mkFun n (t1,t2,t3) = "{-# NOINLINE fun" ++ show n ++ " #-}\n" ++ "fun" ++ show n ++ " :: (# " ++ t1 ++" | " ++ t2 ++ " #) -> (# " ++ t1 ++" | " ++ t3 ++ " #)\n" ++ "fun" ++ show n ++ " x = case x of\n" ++ " (# x1 | #) -> (# x1 | #) :: (# " ++ t1 ++ " | " ++ t3 ++ " #)" -- Generate functions for all the tuple combinations. mkFuns _ [] = "" mkFuns n (combo:combos) = mkFun n combo ++ "\n" ++ mkFuns (n+1) combos -- generate a test that will put a value into a unboxed sum and then retrieve it later on. It generates code like the one below : = let in_val = maxBound out_val = case in_val of I # x - > case fun0 ( # x | # ) of ( # y | # ) - > I # y -- in in_val == out_val mkTest n (t1,_,_)= let test_name = "test" ++ show n test_code = test_name ++ " =\n" ++ " let in_val = (maxBound)\n" ++ " out_val = case in_val of " ++ mkCon t1 ++ " x -> case fun" ++ show n ++ " (# x | #) of (# y | #) -> " ++ mkCon t1 ++ " y\n" ++ " in in_val == out_val" in (test_code,test_name) -- Test all the tuples mkTests n combos = let (defs, names) = unzip $ zipWith mkTest [0..] combos assert_results = "\nassert_results = and [" ++ (concat $ intersperse "," names) ++ "]\n" :: String in unlines defs ++ assert_results header = # LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # # LANGUAGE UnboxedSums # \module Main where\n\ \import GHC.Exts\n\ \import GHC.Word\n\ \import GHC.Int\n\ \import ManyUbxSums_Addr\n" main = do out <- openFile "ManyUbxSums.hs" WriteMode hPutStrLn out header let combo:_ = combos -- putStrLn $ mkFun 1 combo hPutStrLn out $ mkFuns 0 combos hPutStrLn out $ mkTests 0 combos hPutStrLn out "main = do" hPutStrLn out $ " putStrLn . show $ assert_results" -- The snippet below would print all individual test results. -- But for CI really just check if all results match the input -- let runTest n = hPutStrLn out $ " " + + show n + + " \ " + + ( show test " + + show n + + " ) " mapM runTest [ 0 .. length combos - 1 ] hClose out
null
https://raw.githubusercontent.com/ghc/ghc/31462d98c31e3ef48af2f6c6f2d379d74ccc63f5/testsuite/tests/unboxedsums/GenManyUbxSums.hs
haskell
This little piece of code constructs a large set of functions constructing and deconstructing unboxed tuples of various types. ["Addr#","Int#","Int8#","Int16#","Int32#","Int64#","Word#","Word8#","Word16#","Word32#","Word64#"] given type tuples. fun0 :: (# Addr# | I16# #) -> (# Addr# | I# #) fun0 x = case x of Generate functions for all the tuple combinations. generate a test that will put a value into a unboxed sum and then retrieve it later on. in in_val == out_val Test all the tuples putStrLn $ mkFun 1 combo The snippet below would print all individual test results. But for CI really just check if all results match the input let runTest n =
#!/usr/bin/env runghc # LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # # LANGUAGE UnboxedSums # module Main where import GHC.Exts import System.IO import Data.List (intersperse) inputs = ["Int", "Word"] sizes = ["","8","16","32","64"] types = "Addr#" : do r <- inputs s <- sizes return $ r++s++"#" We eventually build two sums , one of type ( # t1 | t2 # ) and one of ( # t1 | t3 ) . So we build all possible combinations of three types here . combos = do t1 <- types t2 <- types t3 <- types return (t1,t2,t3) mkCon ty = case ty of "Addr#" -> "Addr" "Int#" -> "I#" "Int8#" -> "I8#" "Int16#" -> "I16#" "Int32#" -> "I32#" "Int64#" -> "I64#" "Word#" -> "W#" "Word8#" -> "W8#" "Word16#" -> "W16#" "Word32#" -> "W32#" "Word64#" -> "W64#" Construct a function like the one below , varying the types in the sums based on the We need to NOINLINE or the function will be constant folded away . { - # NOINLINE fun0 # - } ( # x1 | # ) - > ( # x1 | # ) : : ( # Addr # | I # # ) mkFun n (t1,t2,t3) = "{-# NOINLINE fun" ++ show n ++ " #-}\n" ++ "fun" ++ show n ++ " :: (# " ++ t1 ++" | " ++ t2 ++ " #) -> (# " ++ t1 ++" | " ++ t3 ++ " #)\n" ++ "fun" ++ show n ++ " x = case x of\n" ++ " (# x1 | #) -> (# x1 | #) :: (# " ++ t1 ++ " | " ++ t3 ++ " #)" mkFuns _ [] = "" mkFuns n (combo:combos) = mkFun n combo ++ "\n" ++ mkFuns (n+1) combos It generates code like the one below : = let in_val = maxBound out_val = case in_val of I # x - > case fun0 ( # x | # ) of ( # y | # ) - > I # y mkTest n (t1,_,_)= let test_name = "test" ++ show n test_code = test_name ++ " =\n" ++ " let in_val = (maxBound)\n" ++ " out_val = case in_val of " ++ mkCon t1 ++ " x -> case fun" ++ show n ++ " (# x | #) of (# y | #) -> " ++ mkCon t1 ++ " y\n" ++ " in in_val == out_val" in (test_code,test_name) mkTests n combos = let (defs, names) = unzip $ zipWith mkTest [0..] combos assert_results = "\nassert_results = and [" ++ (concat $ intersperse "," names) ++ "]\n" :: String in unlines defs ++ assert_results header = # LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # # LANGUAGE UnboxedSums # \module Main where\n\ \import GHC.Exts\n\ \import GHC.Word\n\ \import GHC.Int\n\ \import ManyUbxSums_Addr\n" main = do out <- openFile "ManyUbxSums.hs" WriteMode hPutStrLn out header let combo:_ = combos hPutStrLn out $ mkFuns 0 combos hPutStrLn out $ mkTests 0 combos hPutStrLn out "main = do" hPutStrLn out $ " putStrLn . show $ assert_results" hPutStrLn out $ " " + + show n + + " \ " + + ( show test " + + show n + + " ) " mapM runTest [ 0 .. length combos - 1 ] hClose out
d2244d81573d4ea61c4e770352cef3483b4469b19460cfe8c3433d3abc496765
gsakkas/rite
2111.ml
type expr = | VarX | VarY | Sine of expr | Cosine of expr | Average of expr* expr | Times of expr* expr | Thresh of expr* expr* expr* expr;; let rec eval (e,x,y) = match e with | VarX -> x +. 0.0 | VarY -> y +. 0.0 | Average (a1,a2) -> (eval (VarX, a1, a2)) + (eval (VarY, a1, a2));; fix type expr = | VarX | VarY | Sine of expr | Cosine of expr | Average of expr * expr | Times of expr * expr | Thresh of expr * expr * expr * expr ; ; let rec eval ( e , x , y ) = match e with | VarX - > x + . 0.0 | VarY - > y + . 0.0 | Average ( a1,a2 ) - > ( eval ( VarX , x , y ) ) + . ( eval ( VarY , , y ) ) ; ; type expr = | VarX | VarY | Sine of expr | Cosine of expr | Average of expr* expr | Times of expr* expr | Thresh of expr* expr* expr* expr;; let rec eval (e,x,y) = match e with | VarX -> x +. 0.0 | VarY -> y +. 0.0 | Average (a1,a2) -> (eval (VarX, x, y)) +. (eval (VarY, x, y));; *) changed spans ( 15,24)-(15,69 ) eval ( VarX , x , y ) + . ( VarY , x , y ) BopG ( AppG [ EmptyG ] ) ( AppG [ EmptyG ] ) (15,24)-(15,69) eval (VarX , x , y) +. eval (VarY , x , y) BopG (AppG [EmptyG]) (AppG [EmptyG]) *) type error slice ( 11,4)-(15,71 ) ( ) ( 12,3)-(15,69 ) ( 13,14)-(13,22 ) ( 14,14)-(14,15 ) ( ) ( 15,24)-(15,45 ) ( 15,24)-(15,69 ) ( 15,25)-(15,29 ) ( 15,30)-(15,44 ) ( 15,41)-(15,43 ) (11,4)-(15,71) (11,15)-(15,69) (12,3)-(15,69) (13,14)-(13,22) (14,14)-(14,15) (14,14)-(14,22) (15,24)-(15,45) (15,24)-(15,69) (15,25)-(15,29) (15,30)-(15,44) (15,41)-(15,43) *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/2111.ml
ocaml
type expr = | VarX | VarY | Sine of expr | Cosine of expr | Average of expr* expr | Times of expr* expr | Thresh of expr* expr* expr* expr;; let rec eval (e,x,y) = match e with | VarX -> x +. 0.0 | VarY -> y +. 0.0 | Average (a1,a2) -> (eval (VarX, a1, a2)) + (eval (VarY, a1, a2));; fix type expr = | VarX | VarY | Sine of expr | Cosine of expr | Average of expr * expr | Times of expr * expr | Thresh of expr * expr * expr * expr ; ; let rec eval ( e , x , y ) = match e with | VarX - > x + . 0.0 | VarY - > y + . 0.0 | Average ( a1,a2 ) - > ( eval ( VarX , x , y ) ) + . ( eval ( VarY , , y ) ) ; ; type expr = | VarX | VarY | Sine of expr | Cosine of expr | Average of expr* expr | Times of expr* expr | Thresh of expr* expr* expr* expr;; let rec eval (e,x,y) = match e with | VarX -> x +. 0.0 | VarY -> y +. 0.0 | Average (a1,a2) -> (eval (VarX, x, y)) +. (eval (VarY, x, y));; *) changed spans ( 15,24)-(15,69 ) eval ( VarX , x , y ) + . ( VarY , x , y ) BopG ( AppG [ EmptyG ] ) ( AppG [ EmptyG ] ) (15,24)-(15,69) eval (VarX , x , y) +. eval (VarY , x , y) BopG (AppG [EmptyG]) (AppG [EmptyG]) *) type error slice ( 11,4)-(15,71 ) ( ) ( 12,3)-(15,69 ) ( 13,14)-(13,22 ) ( 14,14)-(14,15 ) ( ) ( 15,24)-(15,45 ) ( 15,24)-(15,69 ) ( 15,25)-(15,29 ) ( 15,30)-(15,44 ) ( 15,41)-(15,43 ) (11,4)-(15,71) (11,15)-(15,69) (12,3)-(15,69) (13,14)-(13,22) (14,14)-(14,15) (14,14)-(14,22) (15,24)-(15,45) (15,24)-(15,69) (15,25)-(15,29) (15,30)-(15,44) (15,41)-(15,43) *)
2949c1828b94a1420bd75869666d1df7a1dc07b283dae7d623cd2de9fb3cfe58
ocaml-ppx/ppx
test_ppx_bootstrap.mli
open! Ppx val expr : Ppx_ast.expression val pat : Ppx_ast.pattern val type_ : Ppx_ast.core_type val stri : Ppx_ast.structure_item val str : Ppx_ast.structure val sigi : Ppx_ast.signature_item val sig_ : Ppx_ast.signature val f_view : Ppx_ast.expression -> (Ppx_ast.expression * Ppx_ast.core_type) option
null
https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/bootstrap/test/test_ppx_bootstrap.mli
ocaml
open! Ppx val expr : Ppx_ast.expression val pat : Ppx_ast.pattern val type_ : Ppx_ast.core_type val stri : Ppx_ast.structure_item val str : Ppx_ast.structure val sigi : Ppx_ast.signature_item val sig_ : Ppx_ast.signature val f_view : Ppx_ast.expression -> (Ppx_ast.expression * Ppx_ast.core_type) option
e933b6e99a380bf858b976f72c2bd6b0fa679ec7be1ce9ce9ef71f62a0dcefd5
contested-space/seer
seer_app.erl
-module(seer_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> seer_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/contested-space/seer/f9879bce8632375d07b20443e8e3d7d88964b230/src/seer_app.erl
erlang
-module(seer_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> seer_sup:start_link(). stop(_State) -> ok.
4c273ac1af75821d3e84df7da0f2b5e5799ccc11fe1bba55da9ca9f89129778b
helium/erlang-multiaddr
multiaddr_test.erl
-module(multiaddr_test). -include_lib("eunit/include/eunit.hrl"). encode_success_test() -> Cases = ["/ip4/1.2.3.4", "/ip4/0.0.0.0", "/ip6/::1", "/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21", "/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21/udp/1234/quic", "/onion/timaq4ygg2iegci7:1234", "/onion/timaq4ygg2iegci7:80/http", "/udp/0", "/tcp/0", "/sctp/0", "/udp/1234", "/tcp/1234", "/sctp/1234", "/udp/65535", "/tcp/65535", "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/udp/1234/sctp/1234", "/udp/1234/udt", "/udp/1234/utp", "/tcp/1234/http", "/tcp/1234/https", "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/ip4/127.0.0.1/udp/1234", "/ip4/127.0.0.1/udp/0", "/ip4/127.0.0.1/tcp/1234", "/ip4/127.0.0.1/tcp/1234/", "/ip4/127.0.0.1/udp/1234/quic", "/ip4/127.0.0.1/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/127.0.0.1/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/unix/a/b/c/d/e", "/unix/stdio", "/ip4/1.2.3.4/tcp/80/unix/a/b/c/d/e/f", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234/unix/stdio" "/ip4/1.2.3.4/tcp/80/p2p-circuit/a/b/c/d/e/f", "/ip4/1.2.3.4/tcp/80/p2p-circuit/ip4/1.2.3.4/tcp/80" ], lists:map(fun(Case) -> Address = multiaddr:new(Case), ?assertNotMatch({error, _}, Address) end, Cases). encode_fail_test() -> Cases = ["/ip4", "/ip4/::1", "/ip4/fdpsofodsajfdoisa", "/ip6", "/udp", "/tcp", "/sctp", "/udp/65536", "/tcp/65536", "/quic/65536", "/onion/9imaq4ygg2iegci7:80", "/onion/aaimaq4ygg2iegci7:80", "/onion/timaq4ygg2iegci7:065536", "/onion/timaq4ygg2iegci7:-1", "/onion/timaq4ygg2iegci7", "/onion/timaq4ygg2iegci@:666", "/udp/1234/sctp", "/udp/1234/udt/1234", "/udp/1234/utp/1234", "/ip4/127.0.0.1/udp/jfodsajfidosajfoidsa", "/ip4/127.0.0.1/udp", "/ip4/127.0.0.1/tcp/jfodsajfidosajfoidsa", "/ip4/127.0.0.1/tcp", "/ip4/127.0.0.1/quic/1234", "/ip4/127.0.0.1/p2p", "/ip4/127.0.0.1/ipfs", " /ip4/127.0.0.1 / ipfs / tcp " , % % " tcp " passes base58 : base58_check "/unix", "/ip4/1.2.3.4/tcp/80/unix" ], lists:map(fun(Case) -> ?assertError(bad_arg, multiaddr:new(Case)) end, Cases). encode_binary_test() -> Cases = [ {"/ip4/127.0.0.1/udp/1234", "047f000001910204d2"}, {"/ip4/127.0.0.1/tcp/4321", "047f0000010610e1"}, {"/ip4/127.0.0.1/udp/1234/ip4/127.0.0.1/tcp/4321", "047f000001910204d2047f0000010610e1"}, {"/onion/aaimaq4ygg2iegci:80", "bc030010c0439831b48218480050"} ], lists:map(fun({Str, Enc}) -> Address = multiaddr:new(Str), Encoded = string:uppercase(Enc), ?assertEqual(Encoded, bin_to_hexstr(Address)), ?assertEqual(Address, multiaddr:new(multiaddr:to_string(hexstr_to_bin(Enc)))) end, Cases). protocols_test() -> Address = multiaddr:new("/ip4/127.0.0.1/udp/1234"), Protocols = multiaddr:protocols(Address), ?assertEqual(Protocols, multiaddr:protocols("/ip4/127.0.0.1/udp/1234")), ?assertEqual(2, length(Protocols)), ?assertMatch([{"ip4", "127.0.0.1"}, {"udp", "1234"}], Protocols), ?assertEqual(Address, multiaddr:new(multiaddr:to_string(Protocols))). %% from -to-hex-string-back-to-binary-in.html bin_to_hexstr(Bin) -> lists:flatten([io_lib:format("~2.16.0B", [X]) || X <- binary_to_list(Bin)]). hexstr_to_bin(S) -> hexstr_to_bin(S, []). hexstr_to_bin([], Acc) -> list_to_binary(lists:reverse(Acc)); hexstr_to_bin([X,Y|T], Acc) -> {ok, [V], []} = io_lib:fread("~16u", [X,Y]), hexstr_to_bin(T, [V | Acc]); hexstr_to_bin([X|T], Acc) -> {ok, [V], []} = io_lib:fread("~16u", lists:flatten([X,"0"])), hexstr_to_bin(T, [V | Acc]).
null
https://raw.githubusercontent.com/helium/erlang-multiaddr/9bf236917a336800f953150568291f192603446c/test/multiaddr_test.erl
erlang
% " tcp " passes base58 : base58_check from -to-hex-string-back-to-binary-in.html
-module(multiaddr_test). -include_lib("eunit/include/eunit.hrl"). encode_success_test() -> Cases = ["/ip4/1.2.3.4", "/ip4/0.0.0.0", "/ip6/::1", "/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21", "/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21/udp/1234/quic", "/onion/timaq4ygg2iegci7:1234", "/onion/timaq4ygg2iegci7:80/http", "/udp/0", "/tcp/0", "/sctp/0", "/udp/1234", "/tcp/1234", "/sctp/1234", "/udp/65535", "/tcp/65535", "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/udp/1234/sctp/1234", "/udp/1234/udt", "/udp/1234/utp", "/tcp/1234/http", "/tcp/1234/https", "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/ip4/127.0.0.1/udp/1234", "/ip4/127.0.0.1/udp/0", "/ip4/127.0.0.1/tcp/1234", "/ip4/127.0.0.1/tcp/1234/", "/ip4/127.0.0.1/udp/1234/quic", "/ip4/127.0.0.1/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/127.0.0.1/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/unix/a/b/c/d/e", "/unix/stdio", "/ip4/1.2.3.4/tcp/80/unix/a/b/c/d/e/f", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234/unix/stdio" "/ip4/1.2.3.4/tcp/80/p2p-circuit/a/b/c/d/e/f", "/ip4/1.2.3.4/tcp/80/p2p-circuit/ip4/1.2.3.4/tcp/80" ], lists:map(fun(Case) -> Address = multiaddr:new(Case), ?assertNotMatch({error, _}, Address) end, Cases). encode_fail_test() -> Cases = ["/ip4", "/ip4/::1", "/ip4/fdpsofodsajfdoisa", "/ip6", "/udp", "/tcp", "/sctp", "/udp/65536", "/tcp/65536", "/quic/65536", "/onion/9imaq4ygg2iegci7:80", "/onion/aaimaq4ygg2iegci7:80", "/onion/timaq4ygg2iegci7:065536", "/onion/timaq4ygg2iegci7:-1", "/onion/timaq4ygg2iegci7", "/onion/timaq4ygg2iegci@:666", "/udp/1234/sctp", "/udp/1234/udt/1234", "/udp/1234/utp/1234", "/ip4/127.0.0.1/udp/jfodsajfidosajfoidsa", "/ip4/127.0.0.1/udp", "/ip4/127.0.0.1/tcp/jfodsajfidosajfoidsa", "/ip4/127.0.0.1/tcp", "/ip4/127.0.0.1/quic/1234", "/ip4/127.0.0.1/p2p", "/ip4/127.0.0.1/ipfs", "/unix", "/ip4/1.2.3.4/tcp/80/unix" ], lists:map(fun(Case) -> ?assertError(bad_arg, multiaddr:new(Case)) end, Cases). encode_binary_test() -> Cases = [ {"/ip4/127.0.0.1/udp/1234", "047f000001910204d2"}, {"/ip4/127.0.0.1/tcp/4321", "047f0000010610e1"}, {"/ip4/127.0.0.1/udp/1234/ip4/127.0.0.1/tcp/4321", "047f000001910204d2047f0000010610e1"}, {"/onion/aaimaq4ygg2iegci:80", "bc030010c0439831b48218480050"} ], lists:map(fun({Str, Enc}) -> Address = multiaddr:new(Str), Encoded = string:uppercase(Enc), ?assertEqual(Encoded, bin_to_hexstr(Address)), ?assertEqual(Address, multiaddr:new(multiaddr:to_string(hexstr_to_bin(Enc)))) end, Cases). protocols_test() -> Address = multiaddr:new("/ip4/127.0.0.1/udp/1234"), Protocols = multiaddr:protocols(Address), ?assertEqual(Protocols, multiaddr:protocols("/ip4/127.0.0.1/udp/1234")), ?assertEqual(2, length(Protocols)), ?assertMatch([{"ip4", "127.0.0.1"}, {"udp", "1234"}], Protocols), ?assertEqual(Address, multiaddr:new(multiaddr:to_string(Protocols))). bin_to_hexstr(Bin) -> lists:flatten([io_lib:format("~2.16.0B", [X]) || X <- binary_to_list(Bin)]). hexstr_to_bin(S) -> hexstr_to_bin(S, []). hexstr_to_bin([], Acc) -> list_to_binary(lists:reverse(Acc)); hexstr_to_bin([X,Y|T], Acc) -> {ok, [V], []} = io_lib:fread("~16u", [X,Y]), hexstr_to_bin(T, [V | Acc]); hexstr_to_bin([X|T], Acc) -> {ok, [V], []} = io_lib:fread("~16u", lists:flatten([X,"0"])), hexstr_to_bin(T, [V | Acc]).
2f2c72268a571a86233373734c5bb155f33160cbb074f765b7bad93458706c43
infinitelives/infinitelives.pixi
pixelfont.clj
(ns infinitelives.pixi.pixelfont (:require [clojure.java.io :as io] [clojure.string :as string]) (:import [javax.imageio ImageIO])) (defn horizontal-strip [y x1 x2] (for [x (range x1 x2)] [x y])) (defn vertical-strip [x y1 y2] (for [y (range y1 y2)] [x y])) (defn alpha-at [image [x y]] (-> image (.getRGB x y) (bit-shift-right 24) (bit-and 0xff))) (defn alphas [image xy-seq] (map (partial alpha-at image) xy-seq)) (defn image-set-all-transparent? [image xy-seq] (not (some (comp not zero?) (alphas image xy-seq)))) (defn transparent-hlines [image x1 x2 y1 y2] (for [y (range y1 y2)] (image-set-all-transparent? image (horizontal-strip y x1 x2)))) (defn transparent-vlines [image x1 x2 y1 y2] (for [x (range x1 x2)] (image-set-all-transparent? image (vertical-strip x y1 y2)))) (defn strips [strip-fn dim image x1 x2 y1 y2] (let [strip-sizes (-> image (strip-fn x1 x2 y1 y2) (->> (map-indexed vector) (partition-by second) (map count)) )] (partition 2 (for [n (range (count strip-sizes))] (apply + (case dim :y y1 :x x1) (take (inc n) strip-sizes)))))) (def horizontal-strips (partial strips transparent-hlines :y)) (def vertical-strips (partial strips transparent-vlines :x)) (defn char-dimensions "returns a sequence of maps (with keys :x1 :x2 :y1 :y2 :row :pos :char)" [image xi1 xi2 yi1 yi2 chars] (let [hstrips (horizontal-strips image xi1 xi2 yi1 yi2) vsize (apply max (map #(Math/abs (apply - %)) hstrips))] (map #(assoc %1 :char %2) (for [[row [y1 y2]] (map-indexed vector hstrips) [pos [x1 x2]] (map-indexed vector (vertical-strips image xi1 xi2 y1 y2))] {:x1 x1 :y1 y1 :x2 x2 :y2 (+ y1 vsize) :row row :pos pos}) chars))) (defn offset-dimensions [dimensions key update-fn & args] (map #(apply update % key update-fn args) dimensions)) (defn process-row "for every char in dimensions that lie in row, run function update-fn on it with args." [dimensions row key update-fn & args] (->> dimensions (map #(if (= (:row %) row) (apply update % key update-fn args) %)))) (defn filename->keyword [fname] (-> fname (string/split #"/") last (string/split #"\.") first keyword)) (def default-chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"#$%&'()*+,-./0123456789:;<=>?@[\\]^_`{|}~") < = > ? @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ " ) (defmacro pixel-font[font-name filename [x1 y1] [x2 y2] & {:keys [chars processors kerning space] :or {chars default-chars processors [] kerning {} space 0}}] (let [image (->> filename (io/file "resources/public") ImageIO/read) chars (apply str chars) dimensions (char-dimensions image x1 x2 y1 y2 chars) {:keys [y1 y2]} (first dimensions) height (- y2 y1) final-dims (reduce (fn [acc [func & args]] (eval (concat [func (vec acc)] args))) dimensions processors)] `(load-pixel-font ~font-name ~(filename->keyword filename) ~(vec (for [{:keys [char x1 y1 x2 y2]} final-dims] [(str char) x1 y1 x2 y2])) ~kerning ~space ~height))) (comment (macroexpand '(pixel-font :test-font "test.png" [127 84] [350 128] :processors [ (offset-dimensions :x2 dec) (process-row 0 :x1 + 10) ] :chars "AB"))) (comment (def a (-> "test.png" io/file ImageIO/read ( horizontal - strips 0 200 0 200 ) ;(process-line 0 1000 89 96) (char-dimensions 127 350 84 128 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") (offset-dimensions :x2 dec) (process-row 0 :x1 + 10) (process-row 1 :x2 number?))))
null
https://raw.githubusercontent.com/infinitelives/infinitelives.pixi/877bd247f2bae327bc3a3bd70162a7880de9a0c7/src/clj/infinitelives/pixi/pixelfont.clj
clojure
<=>?@[\\]^_`{|}~") (process-line 0 1000 89 96)
(ns infinitelives.pixi.pixelfont (:require [clojure.java.io :as io] [clojure.string :as string]) (:import [javax.imageio ImageIO])) (defn horizontal-strip [y x1 x2] (for [x (range x1 x2)] [x y])) (defn vertical-strip [x y1 y2] (for [y (range y1 y2)] [x y])) (defn alpha-at [image [x y]] (-> image (.getRGB x y) (bit-shift-right 24) (bit-and 0xff))) (defn alphas [image xy-seq] (map (partial alpha-at image) xy-seq)) (defn image-set-all-transparent? [image xy-seq] (not (some (comp not zero?) (alphas image xy-seq)))) (defn transparent-hlines [image x1 x2 y1 y2] (for [y (range y1 y2)] (image-set-all-transparent? image (horizontal-strip y x1 x2)))) (defn transparent-vlines [image x1 x2 y1 y2] (for [x (range x1 x2)] (image-set-all-transparent? image (vertical-strip x y1 y2)))) (defn strips [strip-fn dim image x1 x2 y1 y2] (let [strip-sizes (-> image (strip-fn x1 x2 y1 y2) (->> (map-indexed vector) (partition-by second) (map count)) )] (partition 2 (for [n (range (count strip-sizes))] (apply + (case dim :y y1 :x x1) (take (inc n) strip-sizes)))))) (def horizontal-strips (partial strips transparent-hlines :y)) (def vertical-strips (partial strips transparent-vlines :x)) (defn char-dimensions "returns a sequence of maps (with keys :x1 :x2 :y1 :y2 :row :pos :char)" [image xi1 xi2 yi1 yi2 chars] (let [hstrips (horizontal-strips image xi1 xi2 yi1 yi2) vsize (apply max (map #(Math/abs (apply - %)) hstrips))] (map #(assoc %1 :char %2) (for [[row [y1 y2]] (map-indexed vector hstrips) [pos [x1 x2]] (map-indexed vector (vertical-strips image xi1 xi2 y1 y2))] {:x1 x1 :y1 y1 :x2 x2 :y2 (+ y1 vsize) :row row :pos pos}) chars))) (defn offset-dimensions [dimensions key update-fn & args] (map #(apply update % key update-fn args) dimensions)) (defn process-row "for every char in dimensions that lie in row, run function update-fn on it with args." [dimensions row key update-fn & args] (->> dimensions (map #(if (= (:row %) row) (apply update % key update-fn args) %)))) (defn filename->keyword [fname] (-> fname (string/split #"/") last (string/split #"\.") first keyword)) < = > ? @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ " ) (defmacro pixel-font[font-name filename [x1 y1] [x2 y2] & {:keys [chars processors kerning space] :or {chars default-chars processors [] kerning {} space 0}}] (let [image (->> filename (io/file "resources/public") ImageIO/read) chars (apply str chars) dimensions (char-dimensions image x1 x2 y1 y2 chars) {:keys [y1 y2]} (first dimensions) height (- y2 y1) final-dims (reduce (fn [acc [func & args]] (eval (concat [func (vec acc)] args))) dimensions processors)] `(load-pixel-font ~font-name ~(filename->keyword filename) ~(vec (for [{:keys [char x1 y1 x2 y2]} final-dims] [(str char) x1 y1 x2 y2])) ~kerning ~space ~height))) (comment (macroexpand '(pixel-font :test-font "test.png" [127 84] [350 128] :processors [ (offset-dimensions :x2 dec) (process-row 0 :x1 + 10) ] :chars "AB"))) (comment (def a (-> "test.png" io/file ImageIO/read ( horizontal - strips 0 200 0 200 ) (char-dimensions 127 350 84 128 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") (offset-dimensions :x2 dec) (process-row 0 :x1 + 10) (process-row 1 :x2 number?))))
0487d88456b8ab494f27d1d1e9243c8e524e1e921ddf6f8381674ad93c2a062d
bmeurer/ocamljit2
ctype.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ Id$ Operations on core types open Asttypes open Types exception Unify of (type_expr * type_expr) list exception Tags of label * label exception Subtype of (type_expr * type_expr) list * (type_expr * type_expr) list exception Cannot_expand exception Cannot_apply exception Recursive_abbrev val init_def: int -> unit (* Set the initial variable level *) val begin_def: unit -> unit (* Raise the variable level by one at the beginning of a definition. *) val end_def: unit -> unit Lower the variable level by one at the end of a definition val begin_class_def: unit -> unit val raise_nongen_level: unit -> unit val reset_global_level: unit -> unit (* Reset the global level before typing an expression *) val increase_global_level: unit -> int val restore_global_level: int -> unit This pair of functions is only used in Typetexp val newty: type_desc -> type_expr val newvar: unit -> type_expr (* Return a fresh variable *) val new_global_var: unit -> type_expr (* Return a fresh variable, bound at toplevel (as type variables ['a] in type constraints). *) val newobj: type_expr -> type_expr val newconstr: Path.t -> type_expr list -> type_expr val none: type_expr (* A dummy type expression *) val repr: type_expr -> type_expr (* Return the canonical representative of a type. *) val dummy_method: label val object_fields: type_expr -> type_expr val flatten_fields: type_expr -> (string * field_kind * type_expr) list * type_expr (* Transform a field type into a list of pairs label-type *) (* The fields are sorted *) val associate_fields: (string * field_kind * type_expr) list -> (string * field_kind * type_expr) list -> (string * field_kind * type_expr * field_kind * type_expr) list * (string * field_kind * type_expr) list * (string * field_kind * type_expr) list val opened_object: type_expr -> bool val close_object: type_expr -> unit val row_variable: type_expr -> type_expr (* Return the row variable of an open object type *) val set_object_name: Ident.t -> type_expr -> type_expr list -> type_expr -> unit val remove_object_name: type_expr -> unit val hide_private_methods: type_expr -> unit val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr val sort_row_fields: (label * row_field) list -> (label * row_field) list val merge_row_fields: (label * row_field) list -> (label * row_field) list -> (label * row_field) list * (label * row_field) list * (label * row_field * row_field) list val filter_row_fields: bool -> (label * row_field) list -> (label * row_field) list val generalize: type_expr -> unit in - place the given type val iterative_generalization: int -> type_expr list -> type_expr list (* Efficient repeated generalization of a type *) val generalize_expansive: Env.t -> type_expr -> unit the covariant part of a type , making contravariant branches non - generalizable contravariant branches non-generalizable *) val generalize_global: type_expr -> unit the structure of a type , lowering variables to ! to !global_level *) val generalize_structure: type_expr -> unit (* Same, but variables are only lowered to !current_level *) val generalize_spine: type_expr -> unit (* Special function to generalize a method during inference *) val correct_levels: type_expr -> type_expr (* Returns a copy with decreasing levels *) val limited_generalize: type_expr -> type_expr -> unit (* Only generalize some part of the type Make the remaining of the type non-generalizable *) val instance: type_expr -> type_expr (* Take an instance of a type scheme *) val instance_list: type_expr list -> type_expr list (* Take an instance of a list of type schemes *) val instance_constructor: constructor_description -> type_expr list * type_expr (* Same, for a constructor *) val instance_parameterized_type: type_expr list -> type_expr -> type_expr list * type_expr val instance_parameterized_type_2: type_expr list -> type_expr list -> type_expr -> type_expr list * type_expr list * type_expr val instance_declaration: type_declaration -> type_declaration val instance_class: type_expr list -> class_type -> type_expr list * class_type val instance_poly: bool -> type_expr list -> type_expr -> type_expr list * type_expr (* Take an instance of a type scheme containing free univars *) val instance_label: bool -> label_description -> type_expr list * type_expr * type_expr (* Same, for a label *) val apply: Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr (* [apply [p1...pN] t [a1...aN]] match the arguments [ai] to the parameters [pi] and returns the corresponding instance of [t]. Exception [Cannot_apply] is raised in case of failure. *) val expand_head_once: Env.t -> type_expr -> type_expr val expand_head: Env.t -> type_expr -> type_expr val try_expand_once_opt: Env.t -> type_expr -> type_expr val expand_head_opt: Env.t -> type_expr -> type_expr (** The compiler's own version of [expand_head] necessary for type-based optimisations. *) val full_expand: Env.t -> type_expr -> type_expr val enforce_constraints: Env.t -> type_expr -> unit val unify: Env.t -> type_expr -> type_expr -> unit Unify the two types given . Raise [ Unify ] if not possible . val unify_var: Env.t -> type_expr -> type_expr -> unit Same as [ unify ] , but allow free univars when first type is a variable . is a variable. *) val filter_arrow: Env.t -> type_expr -> label -> type_expr * type_expr (* A special case of unification (with l:'a -> 'b). *) val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr (* A special case of unification (with {m : 'a; 'b}). *) val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit (* A special case of unification (with {m : 'a; 'b}), returning unit. *) val deep_occur: type_expr -> type_expr -> bool val filter_self_method: Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref -> type_expr -> Ident.t * type_expr val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool Check if the first type scheme is more general than the second . val rigidify: type_expr -> type_expr list " Rigidify " a type and return its type variable val all_distinct_vars: Env.t -> type_expr list -> bool (* Check those types are all distinct type variables *) val matches : Env.t -> type_expr -> type_expr -> bool Same as [ moregeneral false ] , implemented using the two above functions and backtracking . Ignore levels functions and backtracking. Ignore levels *) type class_match_failure = CM_Virtual_class | CM_Parameter_arity_mismatch of int * int | CM_Type_parameter_mismatch of (type_expr * type_expr) list | CM_Class_type_mismatch of class_type * class_type | CM_Parameter_mismatch of (type_expr * type_expr) list | CM_Val_type_mismatch of string * (type_expr * type_expr) list | CM_Meth_type_mismatch of string * (type_expr * type_expr) list | CM_Non_mutable_value of string | CM_Non_concrete_value of string | CM_Missing_value of string | CM_Missing_method of string | CM_Hide_public of string | CM_Hide_virtual of string * string | CM_Public_method of string | CM_Private_method of string | CM_Virtual_method of string val match_class_types: ?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list Check if the first class type is more general than the second . val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool (* [equal env [x1...xn] tau [y1...yn] sigma] checks whether the parameterized types [/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. *) val match_class_declarations: Env.t -> type_expr list -> class_type -> type_expr list -> class_type -> class_match_failure list Check if the first class type is more general than the second . val enlarge_type: Env.t -> type_expr -> type_expr * bool (* Make a type larger, flag is true if some pruning had to be done *) val subtype: Env.t -> type_expr -> type_expr -> unit -> unit (* [subtype env t1 t2] checks that [t1] is a subtype of [t2]. It accumulates the constraints the type variables must enforce and returns a function that inforce this constraints. *) val nondep_type: Env.t -> Ident.t -> type_expr -> type_expr (* Return a type equivalent to the given type but without references to the given module identifier. Raise [Not_found] if no such type exists. *) val nondep_type_decl: Env.t -> Ident.t -> Ident.t -> bool -> type_declaration -> type_declaration (* Same for type declarations. *) val nondep_class_declaration: Env.t -> Ident.t -> class_declaration -> class_declaration (* Same for class declarations. *) val nondep_cltype_declaration: Env.t -> Ident.t -> cltype_declaration -> cltype_declaration (* Same for class type declarations. *) val correct_abbrev: Env.t -> Path.t -> type_expr list -> type_expr -> unit val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool val normalize_type: Env.t -> type_expr -> unit val closed_schema: type_expr -> bool (* Check whether the given type scheme contains no non-generic type variables *) val free_variables: ?env:Env.t -> type_expr -> type_expr list (* If env present, then check for incomplete definitions too *) val closed_type_decl: type_declaration -> type_expr option type closed_class_failure = CC_Method of type_expr * bool * string * type_expr | CC_Value of type_expr * bool * string * type_expr val closed_class: type_expr list -> class_signature -> closed_class_failure option (* Check whether all type variables are bound *) val unalias: type_expr -> type_expr val signature_of_class_type: class_type -> class_signature val self_type: class_type -> type_expr val class_type_arity: class_type -> int val arity: type_expr -> int (* Return the arity (as for curried functions) of the given type. *) val collapse_conj_params: Env.t -> type_expr list -> unit (* Collapse conjunctive types in class parameters *)
null
https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/typing/ctype.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Set the initial variable level Raise the variable level by one at the beginning of a definition. Reset the global level before typing an expression Return a fresh variable Return a fresh variable, bound at toplevel (as type variables ['a] in type constraints). A dummy type expression Return the canonical representative of a type. Transform a field type into a list of pairs label-type The fields are sorted Return the row variable of an open object type Efficient repeated generalization of a type Same, but variables are only lowered to !current_level Special function to generalize a method during inference Returns a copy with decreasing levels Only generalize some part of the type Make the remaining of the type non-generalizable Take an instance of a type scheme Take an instance of a list of type schemes Same, for a constructor Take an instance of a type scheme containing free univars Same, for a label [apply [p1...pN] t [a1...aN]] match the arguments [ai] to the parameters [pi] and returns the corresponding instance of [t]. Exception [Cannot_apply] is raised in case of failure. * The compiler's own version of [expand_head] necessary for type-based optimisations. A special case of unification (with l:'a -> 'b). A special case of unification (with {m : 'a; 'b}). A special case of unification (with {m : 'a; 'b}), returning unit. Check those types are all distinct type variables [equal env [x1...xn] tau [y1...yn] sigma] checks whether the parameterized types [/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. Make a type larger, flag is true if some pruning had to be done [subtype env t1 t2] checks that [t1] is a subtype of [t2]. It accumulates the constraints the type variables must enforce and returns a function that inforce this constraints. Return a type equivalent to the given type but without references to the given module identifier. Raise [Not_found] if no such type exists. Same for type declarations. Same for class declarations. Same for class type declarations. Check whether the given type scheme contains no non-generic type variables If env present, then check for incomplete definitions too Check whether all type variables are bound Return the arity (as for curried functions) of the given type. Collapse conjunctive types in class parameters
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ Id$ Operations on core types open Asttypes open Types exception Unify of (type_expr * type_expr) list exception Tags of label * label exception Subtype of (type_expr * type_expr) list * (type_expr * type_expr) list exception Cannot_expand exception Cannot_apply exception Recursive_abbrev val init_def: int -> unit val begin_def: unit -> unit val end_def: unit -> unit Lower the variable level by one at the end of a definition val begin_class_def: unit -> unit val raise_nongen_level: unit -> unit val reset_global_level: unit -> unit val increase_global_level: unit -> int val restore_global_level: int -> unit This pair of functions is only used in Typetexp val newty: type_desc -> type_expr val newvar: unit -> type_expr val new_global_var: unit -> type_expr val newobj: type_expr -> type_expr val newconstr: Path.t -> type_expr list -> type_expr val none: type_expr val repr: type_expr -> type_expr val dummy_method: label val object_fields: type_expr -> type_expr val flatten_fields: type_expr -> (string * field_kind * type_expr) list * type_expr val associate_fields: (string * field_kind * type_expr) list -> (string * field_kind * type_expr) list -> (string * field_kind * type_expr * field_kind * type_expr) list * (string * field_kind * type_expr) list * (string * field_kind * type_expr) list val opened_object: type_expr -> bool val close_object: type_expr -> unit val row_variable: type_expr -> type_expr val set_object_name: Ident.t -> type_expr -> type_expr list -> type_expr -> unit val remove_object_name: type_expr -> unit val hide_private_methods: type_expr -> unit val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr val sort_row_fields: (label * row_field) list -> (label * row_field) list val merge_row_fields: (label * row_field) list -> (label * row_field) list -> (label * row_field) list * (label * row_field) list * (label * row_field * row_field) list val filter_row_fields: bool -> (label * row_field) list -> (label * row_field) list val generalize: type_expr -> unit in - place the given type val iterative_generalization: int -> type_expr list -> type_expr list val generalize_expansive: Env.t -> type_expr -> unit the covariant part of a type , making contravariant branches non - generalizable contravariant branches non-generalizable *) val generalize_global: type_expr -> unit the structure of a type , lowering variables to ! to !global_level *) val generalize_structure: type_expr -> unit val generalize_spine: type_expr -> unit val correct_levels: type_expr -> type_expr val limited_generalize: type_expr -> type_expr -> unit val instance: type_expr -> type_expr val instance_list: type_expr list -> type_expr list val instance_constructor: constructor_description -> type_expr list * type_expr val instance_parameterized_type: type_expr list -> type_expr -> type_expr list * type_expr val instance_parameterized_type_2: type_expr list -> type_expr list -> type_expr -> type_expr list * type_expr list * type_expr val instance_declaration: type_declaration -> type_declaration val instance_class: type_expr list -> class_type -> type_expr list * class_type val instance_poly: bool -> type_expr list -> type_expr -> type_expr list * type_expr val instance_label: bool -> label_description -> type_expr list * type_expr * type_expr val apply: Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr val expand_head_once: Env.t -> type_expr -> type_expr val expand_head: Env.t -> type_expr -> type_expr val try_expand_once_opt: Env.t -> type_expr -> type_expr val expand_head_opt: Env.t -> type_expr -> type_expr val full_expand: Env.t -> type_expr -> type_expr val enforce_constraints: Env.t -> type_expr -> unit val unify: Env.t -> type_expr -> type_expr -> unit Unify the two types given . Raise [ Unify ] if not possible . val unify_var: Env.t -> type_expr -> type_expr -> unit Same as [ unify ] , but allow free univars when first type is a variable . is a variable. *) val filter_arrow: Env.t -> type_expr -> label -> type_expr * type_expr val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit val deep_occur: type_expr -> type_expr -> bool val filter_self_method: Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref -> type_expr -> Ident.t * type_expr val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool Check if the first type scheme is more general than the second . val rigidify: type_expr -> type_expr list " Rigidify " a type and return its type variable val all_distinct_vars: Env.t -> type_expr list -> bool val matches : Env.t -> type_expr -> type_expr -> bool Same as [ moregeneral false ] , implemented using the two above functions and backtracking . Ignore levels functions and backtracking. Ignore levels *) type class_match_failure = CM_Virtual_class | CM_Parameter_arity_mismatch of int * int | CM_Type_parameter_mismatch of (type_expr * type_expr) list | CM_Class_type_mismatch of class_type * class_type | CM_Parameter_mismatch of (type_expr * type_expr) list | CM_Val_type_mismatch of string * (type_expr * type_expr) list | CM_Meth_type_mismatch of string * (type_expr * type_expr) list | CM_Non_mutable_value of string | CM_Non_concrete_value of string | CM_Missing_value of string | CM_Missing_method of string | CM_Hide_public of string | CM_Hide_virtual of string * string | CM_Public_method of string | CM_Private_method of string | CM_Virtual_method of string val match_class_types: ?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list Check if the first class type is more general than the second . val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool val match_class_declarations: Env.t -> type_expr list -> class_type -> type_expr list -> class_type -> class_match_failure list Check if the first class type is more general than the second . val enlarge_type: Env.t -> type_expr -> type_expr * bool val subtype: Env.t -> type_expr -> type_expr -> unit -> unit val nondep_type: Env.t -> Ident.t -> type_expr -> type_expr val nondep_type_decl: Env.t -> Ident.t -> Ident.t -> bool -> type_declaration -> type_declaration val nondep_class_declaration: Env.t -> Ident.t -> class_declaration -> class_declaration val nondep_cltype_declaration: Env.t -> Ident.t -> cltype_declaration -> cltype_declaration val correct_abbrev: Env.t -> Path.t -> type_expr list -> type_expr -> unit val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool val normalize_type: Env.t -> type_expr -> unit val closed_schema: type_expr -> bool val free_variables: ?env:Env.t -> type_expr -> type_expr list val closed_type_decl: type_declaration -> type_expr option type closed_class_failure = CC_Method of type_expr * bool * string * type_expr | CC_Value of type_expr * bool * string * type_expr val closed_class: type_expr list -> class_signature -> closed_class_failure option val unalias: type_expr -> type_expr val signature_of_class_type: class_type -> class_signature val self_type: class_type -> type_expr val class_type_arity: class_type -> int val arity: type_expr -> int val collapse_conj_params: Env.t -> type_expr list -> unit
86ab4bbf78a27cfd5c1fc29c101d6eef720112eab12da2be638a4b962335241e
plumatic/grab-bag
flushing_log_test.clj
(ns store.flushing-log-test (:require [plumbing.core :refer :all] [plumbing.test :refer :all] [plumbing.graph :as graph] [plumbing.resource :as resource] [store.bucket :as bucket] [store.flushing-log :refer :all] [clojure.test :refer :all])) (deftest log!-test (let [bucket (bucket/bucket {})] (with-open [bundle (resource/bundle-run logging-bundle {:log-flush-size 2 :bucket bucket})] (assert (= 0 (bucket/count bucket))) (testing "first log makes it to bucket" (log! bundle 1) (is-= 0 (bucket/count bucket))) (testing "second log pushes it over the limit, and the log waits in the cache" (log! bundle 2) (log! bundle 3) (testing "one batch has been flushed" (is-eventually (= [[1 2]] (bucket/vals bucket)))))) (testing "after closing, the remaining log is finally written to the bucket" (is-=-by set [[1 2] [3]] (bucket/vals bucket)))))
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/store/test/store/flushing_log_test.clj
clojure
(ns store.flushing-log-test (:require [plumbing.core :refer :all] [plumbing.test :refer :all] [plumbing.graph :as graph] [plumbing.resource :as resource] [store.bucket :as bucket] [store.flushing-log :refer :all] [clojure.test :refer :all])) (deftest log!-test (let [bucket (bucket/bucket {})] (with-open [bundle (resource/bundle-run logging-bundle {:log-flush-size 2 :bucket bucket})] (assert (= 0 (bucket/count bucket))) (testing "first log makes it to bucket" (log! bundle 1) (is-= 0 (bucket/count bucket))) (testing "second log pushes it over the limit, and the log waits in the cache" (log! bundle 2) (log! bundle 3) (testing "one batch has been flushed" (is-eventually (= [[1 2]] (bucket/vals bucket)))))) (testing "after closing, the remaining log is finally written to the bucket" (is-=-by set [[1 2] [3]] (bucket/vals bucket)))))
76bb66ca403718ddffcf79ac4d4d51ca785b04eea6988f85ccdc84def92a845c
aelve/guide
Main.hs
{-# LANGUAGE FlexibleContexts #-} -- | Description : The main module that starts the server. module Guide.Main ( -- * Main main, -- * All supported commands runServer, dryRun, loadPublic, apiDocs, ) where import Imports -- Concurrent import Control.Concurrent.Async -- Monads and monad transformers import Control.Monad.Morph -- Web import Lucid hiding (for_) import Network.Wai.Middleware.Static (addBase, staticPolicy) import Web.Spock hiding (get, head, text) import Web.Spock.Config import Web.Spock.Lucid -- Spock-digestive import Web.Spock.Digestive (runForm) -- Highlighting import CMark.Highlight (pygments, styleToCss) -- acid-state import Data.Acid as Acid import Data.SafeCopy as SafeCopy import Data.Serialize.Get as Cereal -- IO import System.IO -- Catching Ctrl-C and termination import System.Signal HVect import Data.HVect hiding (length) import Guide.Api (runApiServer, apiSwaggerRendered) import Guide.App import Guide.Cli import Guide.Config import Guide.Handlers import Guide.JS (JS (..), allJSFunctions) import Guide.Logger import Guide.Routes (authRoute, haskellRoute) import Guide.ServerStuff import Guide.Session import Guide.State import Guide.Types import Guide.Uid import Guide.Views import Guide.Views.Utils (getCSS, getCsrfHeader, getJS, protectForm) import Guide.Database.Import (loadIntoPostgres) import qualified Data.ByteString as BS import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Web.Spock as Spock Note [ acid - state ] ~~~~~~~~~~~~~~~~~~~~ Until we are done with migrating to PostgreSQL , this app uses acid - state . Acid - state works as follows : * Everything is stored as values ( in particular , all data is stored in ' GlobalState ' ) . * All changes to the state ( and all queries ) have to be done by using ' dbUpdate'/'dbQuery ' and types ( GetItem , SetItemName , etc ) from the Types.hs module . * The data is kept in - memory , but all changes are logged to the disk ( which lets us recover the state in case of a crash by reapplying the changes ) and you ca n't access the state directly . When the application exits , it creates a snapshot of the state ( called “ checkpoint ” ) and writes it to the disk . Additionally , a checkpoint is created every hour ( grep for “ ” ) . * acid - state has a nasty feature – when the state has n't changed , ' createCheckpoint ' appends it to the previous checkpoint . When state does n't change for a long time , it means that checkpoints can grow to 100 MB or more . So , we employ a dirty bit and use ' instead of createCheckpoint . The former only creates the checkpoint if the dirty bit is set , which is good . * When any type is changed , we have to write a migration function that would read the old version of the type and turn it into the new version . This is done by ' changelog ' – you only need to provide the list of differences between the old type and the new type . * There are actually ways to access the state directly ( GetGlobalState and SetGlobalState ) , but the latter should only be used when doing something one - off ( e.g. if you need to migrate all IDs to a different ID scheme ) . ~~~~~~~~~~~~~~~~~~~~ Until we are done with migrating to PostgreSQL, this app uses acid-state. Acid-state works as follows: * Everything is stored as Haskell values (in particular, all data is stored in 'GlobalState'). * All changes to the state (and all queries) have to be done by using 'dbUpdate'/'dbQuery' and types (GetItem, SetItemName, etc) from the Types.hs module. * The data is kept in-memory, but all changes are logged to the disk (which lets us recover the state in case of a crash by reapplying the changes) and you can't access the state directly. When the application exits, it creates a snapshot of the state (called “checkpoint”) and writes it to the disk. Additionally, a checkpoint is created every hour (grep for “createCheckpoint”). * acid-state has a nasty feature – when the state hasn't changed, 'createCheckpoint' appends it to the previous checkpoint. When state doesn't change for a long time, it means that checkpoints can grow to 100 MB or more. So, we employ a dirty bit and use createCheckpoint' instead of createCheckpoint. The former only creates the checkpoint if the dirty bit is set, which is good. * When any type is changed, we have to write a migration function that would read the old version of the type and turn it into the new version. This is done by 'changelog' – you only need to provide the list of differences between the old type and the new type. * There are actually ways to access the state directly (GetGlobalState and SetGlobalState), but the latter should only be used when doing something one-off (e.g. if you need to migrate all IDs to a different ID scheme). -} ---------------------------------------------------------------------------- -- Main ---------------------------------------------------------------------------- -- | Parse an input and run a command. main :: IO () main = do command <- parseCommandLine config <- readConfig runCommand config command -- | Run a specific 'Command' with the given 'Config'. runCommand :: Config -> Command -> IO () runCommand config = \case RunServer -> runServer config DryRun -> dryRun config LoadPublic path -> loadPublic config path ApiDocs -> apiDocs config LoadIntoPostgres -> loadIntoPostgres config ---------------------------------------------------------------------------- -- Commands ---------------------------------------------------------------------------- -- | Start the server. runServer :: Config -> IO () runServer config@Config{..} = withLogger config $ \logger -> do installTerminationCatcher =<< myThreadId workAsync <- async $ withDB (pure ()) $ \db -> do hSetBuffering stdout NoBuffering -- Run checkpoints creator, new and old server concurrently. mapConcurrently_ id [ checkPoint db , runNewApi logger config db , runOldServer logger config db ] -- Hold processes running and finish on exit or exception. forever (threadDelay (1000000 * 60)) `finally` cancel workAsync -- | Load database from @state/@, check that it can be loaded successfully, -- and exit. dryRun :: Config -> IO () dryRun config = withLogger config $ \logger -> do db :: DB <- openLocalStateFrom "state/" (error "couldn't load state") logDebugIO logger "loaded the database successfully" closeAcidState db -- | Load 'PublicDB' from given file, create acid-state database from it, -- and exit. loadPublic :: Config -> FilePath -> IO () loadPublic config path = withLogger config $ \logger -> (Cereal.runGet SafeCopy.safeGet <$> BS.readFile path) >>= \case Left err -> error err Right publicDB -> do db <- openLocalStateFrom "state/" emptyState Acid.update db (ImportPublicDB publicDB) createCheckpointAndClose' db logDebugIO logger "PublicDB imported to GlobalState" -- | Dump API docs to the output. apiDocs :: Config -> IO () apiDocs config = withLogger config $ \_logger -> T.putStrLn apiSwaggerRendered ---------------------------------------------------------------------------- -- Helpers ---------------------------------------------------------------------------- lucidWithConfig :: (MonadIO m, HasSpock (ActionCtxT cxt m), SpockState (ActionCtxT cxt m) ~ ServerState) => HtmlT (ReaderT Config IO) a -> ActionCtxT cxt m a lucidWithConfig x = do cfg <- getConfig lucidIO (hoist (flip runReaderT cfg) x) | Create a checkpoint every six hours . Note : if nothing was changed , the -- checkpoint won't be created, which saves us some space. checkPoint :: DB -> IO b checkPoint db = forever $ do createCheckpoint' db threadDelay (1000000 * 3600 * 6) -- | Run the API (new server) runNewApi :: Logger -> Config -> AcidState GlobalState -> IO () runNewApi logger = runApiServer (pushLogger "api" logger) -- | Run Spock (old server). runOldServer :: Logger -> Config -> DB -> IO () runOldServer logger config@Config{..} db = do let serverState = ServerState { _config = config, _db = db } spockConfig <- do cfg <- defaultSpockCfg () PCNoDatabase serverState store <- newAcidSessionStore db let sessionCfg = SessionCfg { sc_cookieName = "spockcookie", sc_sessionTTL = 3600, sc_sessionIdEntropy = 64, sc_sessionExpandTTL = True, sc_emptySession = emptyGuideData, sc_store = store, sc_housekeepingInterval = 60 * 10, sc_hooks = defaultSessionHooks } return cfg { spc_maxRequestSize = Just (1024*1024), spc_csrfProtection = True, spc_sessionCfg = sessionCfg } logDebugIO logger $ format "Spock is running on port {}" portMain runSpockNoBanner portMain $ spock spockConfig guideApp -- TODO: Fix indentation after rebasing. guideApp :: GuideApp () guideApp = do createAdminUser -- TODO: perhaps it needs to be inside of “prehook -- initHook”? (I don't actually know what “prehook -- initHook” does, feel free to edit.) prehook initHook $ do middleware (staticPolicy (addBase "static")) Javascript Spock.get "/js.js" $ do setHeader "Content-Type" "application/javascript; charset=utf-8" (csrfTokenName, csrfTokenValue) <- getCsrfHeader let jqueryCsrfProtection = format "guidejs.csrfProtection.enable(\"{}\", \"{}\");" csrfTokenName csrfTokenValue js <- getJS Spock.bytes $ toUtf8ByteString (fromJS allJSFunctions <> js <> jqueryCsrfProtection) -- CSS Spock.get "/highlight.css" $ do setHeader "Content-Type" "text/css; charset=utf-8" Spock.bytes $ toUtf8ByteString (styleToCss pygments) Spock.get "/css.css" $ do setHeader "Content-Type" "text/css; charset=utf-8" css <- getCSS Spock.bytes $ toUtf8ByteString css Spock.get "/admin.css" $ do setHeader "Content-Type" "text/css; charset=utf-8" css <- getCSS admincss <- liftIO $ T.readFile "static/admin.css" Spock.bytes $ toUtf8ByteString (css <> admincss) Main page Spock.get root $ lucidWithConfig renderRoot -- Admin page prehook authHook $ prehook adminHook $ do Spock.get "admin" $ do s <- dbQuery GetGlobalState lucidIO $ renderAdmin s adminMethods Spock.get ("admin" <//> "links") $ do s <- dbQuery GetGlobalState lucidIO $ renderAdminLinks s Static pages Spock.get "markdown" $ lucidWithConfig $ renderStaticMd "Markdown" "markdown.md" Spock.get "license" $ lucidWithConfig $ renderStaticMd "License" "license.md" -- Haskell Spock.get (haskellRoute <//> root) $ do s <- dbQuery GetGlobalState q <- param "q" lucidWithConfig $ renderHaskellRoot s q -- Category pages Spock.get (haskellRoute <//> var) $ \path -> do -- The links look like /parsers-gao238b1 (because it's nice when -- you can find out where a link leads just by looking at it) let (_, catId) = T.breakOnEnd "-" path when (T.null catId) Spock.jumpNext mbCategory <- dbQuery (GetCategoryMaybe (Uid catId)) case mbCategory of Nothing -> Spock.jumpNext Just category -> do -- If the slug in the url is old (i.e. if it doesn't match the -- one we would've generated now), let's do a redirect when (categorySlug category /= path) $ -- TODO: this link shouldn't be absolute [absolute-links] Spock.redirect ("/haskell/" <> categorySlug category) lucidWithConfig $ renderCategoryPage category -- The add/set methods return rendered parts of the structure (added categories , changed items , etc ) so that the Javascript part could -- take them and inject into the page. We don't want to duplicate -- rendering on server side and on client side. methods -- plain "/auth" logs out a logged-in user and lets a logged-out user -- log in (this is not the best idea, granted, and we should just -- show logged-in users a “logout” link and logged-out users a -- “login” link instead) Spock.get (authRoute <//> root) $ do user <- getLoggedInUser if isJust user then Spock.redirect "/auth/logout" else Spock.redirect "/auth/login" Spock.getpost (authRoute <//> "login") $ authRedirect "/" loginAction Spock.get (authRoute <//> "logout") logoutAction Spock.getpost (authRoute <//> "register") $ authRedirect "/" signupAction loginAction :: GuideAction ctx () loginAction = do r <- runForm "login" loginForm case r of (v, Nothing) -> do formHtml <- protectForm loginFormView v lucidWithConfig $ renderRegister formHtml (v, Just Login {..}) -> do loginAttempt <- dbQuery $ LoginUser loginEmail (toUtf8ByteString loginUserPassword) case loginAttempt of Right user -> do modifySession (sessionUserID ?~ userID user) Spock.redirect "/" -- TODO: *properly* show error message/validation of input Left err -> do formHtml <- protectForm loginFormView v lucidWithConfig $ renderRegister $ do div_ $ toHtml ("Error: " <> err) formHtml logoutAction :: GuideAction ctx () logoutAction = do modifySession (sessionUserID .~ Nothing) Spock.redirect "/" signupAction :: GuideAction ctx () signupAction = do r <- runForm "register" registerForm case r of (v, Nothing) -> do formHtml <- protectForm registerFormView v lucidWithConfig $ renderRegister formHtml (v, Just UserRegistration {..}) -> do user <- makeUser registerUserName registerUserEmail (toUtf8ByteString registerUserPassword) success <- dbUpdate $ CreateUser user if success then do modifySession (sessionUserID ?~ userID user) Spock.redirect "" else do formHtml <- protectForm registerFormView v lucidWithConfig $ renderRegister formHtml initHook :: GuideAction () (HVect '[]) initHook = return HNil authHook :: GuideAction (HVect xs) (HVect (User ': xs)) authHook = do oldCtx <- getContext maybeUser <- getLoggedInUser case maybeUser of Nothing -> Spock.text "Not logged in." Just user -> return (user :&: oldCtx) adminHook :: ListContains n User xs => GuideAction (HVect xs) (HVect (IsAdmin ': xs)) adminHook = do oldCtx <- getContext let user = findFirst oldCtx if userIsAdmin user then return (IsAdmin :&: oldCtx) else Spock.text "Not authorized." -- | Redirect the user to a given path if they are logged in. authRedirect :: Text -> GuideAction ctx a -> GuideAction ctx a authRedirect path action = do user <- getLoggedInUser case user of Just _ -> Spock.redirect path Nothing -> action -- TODO: a function to find all links to Hackage that have version in them data Quit = CtrlC | ServiceStop deriving (Eq, Ord, Show) instance Exception Quit | Set up a handler that would catch SIGINT ( i.e. Ctrl - C ) and SIGTERM -- (i.e. service stop) and throw an exception instead of the signal. This -- lets us create a checkpoint and close connections on exit. installTerminationCatcher :: ThreadId -- ^ Thread to kill when the signal comes -> IO () installTerminationCatcher thread = void $ do installHandler sigINT (\_ -> throwTo thread CtrlC) installHandler sigTERM (\_ -> throwTo thread ServiceStop) -- | Create an admin user (with login “admin”, email “” -- and password specified in the config). -- -- The user won't be added if it exists already. createAdminUser :: GuideApp () createAdminUser = do dbUpdate DeleteAllUsers pass <- toUtf8ByteString . adminPassword <$> getConfig user <- makeUser "admin" "" pass void $ dbUpdate $ CreateUser (user & _userIsAdmin .~ True)
null
https://raw.githubusercontent.com/aelve/guide/96a338d61976344d2405a16b11567e5464820a9e/back/src/Guide/Main.hs
haskell
# LANGUAGE FlexibleContexts # | Description : The main module that starts the server. * Main * All supported commands Concurrent Monads and monad transformers Web Spock-digestive Highlighting acid-state IO Catching Ctrl-C and termination -------------------------------------------------------------------------- Main -------------------------------------------------------------------------- | Parse an input and run a command. | Run a specific 'Command' with the given 'Config'. -------------------------------------------------------------------------- Commands -------------------------------------------------------------------------- | Start the server. Run checkpoints creator, new and old server concurrently. Hold processes running and finish on exit or exception. | Load database from @state/@, check that it can be loaded successfully, and exit. | Load 'PublicDB' from given file, create acid-state database from it, and exit. | Dump API docs to the output. -------------------------------------------------------------------------- Helpers -------------------------------------------------------------------------- checkpoint won't be created, which saves us some space. | Run the API (new server) | Run Spock (old server). TODO: Fix indentation after rebasing. TODO: perhaps it needs to be inside of “prehook initHook”? (I don't actually know what “prehook initHook” does, feel free to edit.) CSS Admin page Haskell Category pages The links look like /parsers-gao238b1 (because it's nice when you can find out where a link leads just by looking at it) If the slug in the url is old (i.e. if it doesn't match the one we would've generated now), let's do a redirect TODO: this link shouldn't be absolute [absolute-links] The add/set methods return rendered parts of the structure (added take them and inject into the page. We don't want to duplicate rendering on server side and on client side. plain "/auth" logs out a logged-in user and lets a logged-out user log in (this is not the best idea, granted, and we should just show logged-in users a “logout” link and logged-out users a “login” link instead) TODO: *properly* show error message/validation of input | Redirect the user to a given path if they are logged in. TODO: a function to find all links to Hackage that have version in them (i.e. service stop) and throw an exception instead of the signal. This lets us create a checkpoint and close connections on exit. ^ Thread to kill when the signal comes | Create an admin user (with login “admin”, email “” and password specified in the config). The user won't be added if it exists already.
module Guide.Main ( main, runServer, dryRun, loadPublic, apiDocs, ) where import Imports import Control.Concurrent.Async import Control.Monad.Morph import Lucid hiding (for_) import Network.Wai.Middleware.Static (addBase, staticPolicy) import Web.Spock hiding (get, head, text) import Web.Spock.Config import Web.Spock.Lucid import Web.Spock.Digestive (runForm) import CMark.Highlight (pygments, styleToCss) import Data.Acid as Acid import Data.SafeCopy as SafeCopy import Data.Serialize.Get as Cereal import System.IO import System.Signal HVect import Data.HVect hiding (length) import Guide.Api (runApiServer, apiSwaggerRendered) import Guide.App import Guide.Cli import Guide.Config import Guide.Handlers import Guide.JS (JS (..), allJSFunctions) import Guide.Logger import Guide.Routes (authRoute, haskellRoute) import Guide.ServerStuff import Guide.Session import Guide.State import Guide.Types import Guide.Uid import Guide.Views import Guide.Views.Utils (getCSS, getCsrfHeader, getJS, protectForm) import Guide.Database.Import (loadIntoPostgres) import qualified Data.ByteString as BS import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Web.Spock as Spock Note [ acid - state ] ~~~~~~~~~~~~~~~~~~~~ Until we are done with migrating to PostgreSQL , this app uses acid - state . Acid - state works as follows : * Everything is stored as values ( in particular , all data is stored in ' GlobalState ' ) . * All changes to the state ( and all queries ) have to be done by using ' dbUpdate'/'dbQuery ' and types ( GetItem , SetItemName , etc ) from the Types.hs module . * The data is kept in - memory , but all changes are logged to the disk ( which lets us recover the state in case of a crash by reapplying the changes ) and you ca n't access the state directly . When the application exits , it creates a snapshot of the state ( called “ checkpoint ” ) and writes it to the disk . Additionally , a checkpoint is created every hour ( grep for “ ” ) . * acid - state has a nasty feature – when the state has n't changed , ' createCheckpoint ' appends it to the previous checkpoint . When state does n't change for a long time , it means that checkpoints can grow to 100 MB or more . So , we employ a dirty bit and use ' instead of createCheckpoint . The former only creates the checkpoint if the dirty bit is set , which is good . * When any type is changed , we have to write a migration function that would read the old version of the type and turn it into the new version . This is done by ' changelog ' – you only need to provide the list of differences between the old type and the new type . * There are actually ways to access the state directly ( GetGlobalState and SetGlobalState ) , but the latter should only be used when doing something one - off ( e.g. if you need to migrate all IDs to a different ID scheme ) . ~~~~~~~~~~~~~~~~~~~~ Until we are done with migrating to PostgreSQL, this app uses acid-state. Acid-state works as follows: * Everything is stored as Haskell values (in particular, all data is stored in 'GlobalState'). * All changes to the state (and all queries) have to be done by using 'dbUpdate'/'dbQuery' and types (GetItem, SetItemName, etc) from the Types.hs module. * The data is kept in-memory, but all changes are logged to the disk (which lets us recover the state in case of a crash by reapplying the changes) and you can't access the state directly. When the application exits, it creates a snapshot of the state (called “checkpoint”) and writes it to the disk. Additionally, a checkpoint is created every hour (grep for “createCheckpoint”). * acid-state has a nasty feature – when the state hasn't changed, 'createCheckpoint' appends it to the previous checkpoint. When state doesn't change for a long time, it means that checkpoints can grow to 100 MB or more. So, we employ a dirty bit and use createCheckpoint' instead of createCheckpoint. The former only creates the checkpoint if the dirty bit is set, which is good. * When any type is changed, we have to write a migration function that would read the old version of the type and turn it into the new version. This is done by 'changelog' – you only need to provide the list of differences between the old type and the new type. * There are actually ways to access the state directly (GetGlobalState and SetGlobalState), but the latter should only be used when doing something one-off (e.g. if you need to migrate all IDs to a different ID scheme). -} main :: IO () main = do command <- parseCommandLine config <- readConfig runCommand config command runCommand :: Config -> Command -> IO () runCommand config = \case RunServer -> runServer config DryRun -> dryRun config LoadPublic path -> loadPublic config path ApiDocs -> apiDocs config LoadIntoPostgres -> loadIntoPostgres config runServer :: Config -> IO () runServer config@Config{..} = withLogger config $ \logger -> do installTerminationCatcher =<< myThreadId workAsync <- async $ withDB (pure ()) $ \db -> do hSetBuffering stdout NoBuffering mapConcurrently_ id [ checkPoint db , runNewApi logger config db , runOldServer logger config db ] forever (threadDelay (1000000 * 60)) `finally` cancel workAsync dryRun :: Config -> IO () dryRun config = withLogger config $ \logger -> do db :: DB <- openLocalStateFrom "state/" (error "couldn't load state") logDebugIO logger "loaded the database successfully" closeAcidState db loadPublic :: Config -> FilePath -> IO () loadPublic config path = withLogger config $ \logger -> (Cereal.runGet SafeCopy.safeGet <$> BS.readFile path) >>= \case Left err -> error err Right publicDB -> do db <- openLocalStateFrom "state/" emptyState Acid.update db (ImportPublicDB publicDB) createCheckpointAndClose' db logDebugIO logger "PublicDB imported to GlobalState" apiDocs :: Config -> IO () apiDocs config = withLogger config $ \_logger -> T.putStrLn apiSwaggerRendered lucidWithConfig :: (MonadIO m, HasSpock (ActionCtxT cxt m), SpockState (ActionCtxT cxt m) ~ ServerState) => HtmlT (ReaderT Config IO) a -> ActionCtxT cxt m a lucidWithConfig x = do cfg <- getConfig lucidIO (hoist (flip runReaderT cfg) x) | Create a checkpoint every six hours . Note : if nothing was changed , the checkPoint :: DB -> IO b checkPoint db = forever $ do createCheckpoint' db threadDelay (1000000 * 3600 * 6) runNewApi :: Logger -> Config -> AcidState GlobalState -> IO () runNewApi logger = runApiServer (pushLogger "api" logger) runOldServer :: Logger -> Config -> DB -> IO () runOldServer logger config@Config{..} db = do let serverState = ServerState { _config = config, _db = db } spockConfig <- do cfg <- defaultSpockCfg () PCNoDatabase serverState store <- newAcidSessionStore db let sessionCfg = SessionCfg { sc_cookieName = "spockcookie", sc_sessionTTL = 3600, sc_sessionIdEntropy = 64, sc_sessionExpandTTL = True, sc_emptySession = emptyGuideData, sc_store = store, sc_housekeepingInterval = 60 * 10, sc_hooks = defaultSessionHooks } return cfg { spc_maxRequestSize = Just (1024*1024), spc_csrfProtection = True, spc_sessionCfg = sessionCfg } logDebugIO logger $ format "Spock is running on port {}" portMain runSpockNoBanner portMain $ spock spockConfig guideApp guideApp :: GuideApp () guideApp = do prehook initHook $ do middleware (staticPolicy (addBase "static")) Javascript Spock.get "/js.js" $ do setHeader "Content-Type" "application/javascript; charset=utf-8" (csrfTokenName, csrfTokenValue) <- getCsrfHeader let jqueryCsrfProtection = format "guidejs.csrfProtection.enable(\"{}\", \"{}\");" csrfTokenName csrfTokenValue js <- getJS Spock.bytes $ toUtf8ByteString (fromJS allJSFunctions <> js <> jqueryCsrfProtection) Spock.get "/highlight.css" $ do setHeader "Content-Type" "text/css; charset=utf-8" Spock.bytes $ toUtf8ByteString (styleToCss pygments) Spock.get "/css.css" $ do setHeader "Content-Type" "text/css; charset=utf-8" css <- getCSS Spock.bytes $ toUtf8ByteString css Spock.get "/admin.css" $ do setHeader "Content-Type" "text/css; charset=utf-8" css <- getCSS admincss <- liftIO $ T.readFile "static/admin.css" Spock.bytes $ toUtf8ByteString (css <> admincss) Main page Spock.get root $ lucidWithConfig renderRoot prehook authHook $ prehook adminHook $ do Spock.get "admin" $ do s <- dbQuery GetGlobalState lucidIO $ renderAdmin s adminMethods Spock.get ("admin" <//> "links") $ do s <- dbQuery GetGlobalState lucidIO $ renderAdminLinks s Static pages Spock.get "markdown" $ lucidWithConfig $ renderStaticMd "Markdown" "markdown.md" Spock.get "license" $ lucidWithConfig $ renderStaticMd "License" "license.md" Spock.get (haskellRoute <//> root) $ do s <- dbQuery GetGlobalState q <- param "q" lucidWithConfig $ renderHaskellRoot s q Spock.get (haskellRoute <//> var) $ \path -> do let (_, catId) = T.breakOnEnd "-" path when (T.null catId) Spock.jumpNext mbCategory <- dbQuery (GetCategoryMaybe (Uid catId)) case mbCategory of Nothing -> Spock.jumpNext Just category -> do when (categorySlug category /= path) $ Spock.redirect ("/haskell/" <> categorySlug category) lucidWithConfig $ renderCategoryPage category categories , changed items , etc ) so that the Javascript part could methods Spock.get (authRoute <//> root) $ do user <- getLoggedInUser if isJust user then Spock.redirect "/auth/logout" else Spock.redirect "/auth/login" Spock.getpost (authRoute <//> "login") $ authRedirect "/" loginAction Spock.get (authRoute <//> "logout") logoutAction Spock.getpost (authRoute <//> "register") $ authRedirect "/" signupAction loginAction :: GuideAction ctx () loginAction = do r <- runForm "login" loginForm case r of (v, Nothing) -> do formHtml <- protectForm loginFormView v lucidWithConfig $ renderRegister formHtml (v, Just Login {..}) -> do loginAttempt <- dbQuery $ LoginUser loginEmail (toUtf8ByteString loginUserPassword) case loginAttempt of Right user -> do modifySession (sessionUserID ?~ userID user) Spock.redirect "/" Left err -> do formHtml <- protectForm loginFormView v lucidWithConfig $ renderRegister $ do div_ $ toHtml ("Error: " <> err) formHtml logoutAction :: GuideAction ctx () logoutAction = do modifySession (sessionUserID .~ Nothing) Spock.redirect "/" signupAction :: GuideAction ctx () signupAction = do r <- runForm "register" registerForm case r of (v, Nothing) -> do formHtml <- protectForm registerFormView v lucidWithConfig $ renderRegister formHtml (v, Just UserRegistration {..}) -> do user <- makeUser registerUserName registerUserEmail (toUtf8ByteString registerUserPassword) success <- dbUpdate $ CreateUser user if success then do modifySession (sessionUserID ?~ userID user) Spock.redirect "" else do formHtml <- protectForm registerFormView v lucidWithConfig $ renderRegister formHtml initHook :: GuideAction () (HVect '[]) initHook = return HNil authHook :: GuideAction (HVect xs) (HVect (User ': xs)) authHook = do oldCtx <- getContext maybeUser <- getLoggedInUser case maybeUser of Nothing -> Spock.text "Not logged in." Just user -> return (user :&: oldCtx) adminHook :: ListContains n User xs => GuideAction (HVect xs) (HVect (IsAdmin ': xs)) adminHook = do oldCtx <- getContext let user = findFirst oldCtx if userIsAdmin user then return (IsAdmin :&: oldCtx) else Spock.text "Not authorized." authRedirect :: Text -> GuideAction ctx a -> GuideAction ctx a authRedirect path action = do user <- getLoggedInUser case user of Just _ -> Spock.redirect path Nothing -> action data Quit = CtrlC | ServiceStop deriving (Eq, Ord, Show) instance Exception Quit | Set up a handler that would catch SIGINT ( i.e. Ctrl - C ) and SIGTERM installTerminationCatcher -> IO () installTerminationCatcher thread = void $ do installHandler sigINT (\_ -> throwTo thread CtrlC) installHandler sigTERM (\_ -> throwTo thread ServiceStop) createAdminUser :: GuideApp () createAdminUser = do dbUpdate DeleteAllUsers pass <- toUtf8ByteString . adminPassword <$> getConfig user <- makeUser "admin" "" pass void $ dbUpdate $ CreateUser (user & _userIsAdmin .~ True)
8f41ce251d456d45bbaa523b1265da2a4f796c6ee1f22d45c2b327a5a6d13180
wireapp/wire-server
Report.hs
# LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} -- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Network.Wire.Bot.Report ( -- * Create Reports Report (reportTitle, reportDate, reportSections), createReport, -- * Access Report Data reportCounter, reportLabel, reportGauge, reportBucket, -- * Structure Reports SectionS, Section (sectionName, sectionMetrics), Metric (..), section, -- ** Predefined Sections defaultSections, botsSection, exceptionsSection, assertionsSection, eventsTotalSection, eventTypeSection, ) where import qualified Data.HashMap.Strict as HashMap import Data.Metrics import Data.Time.Clock import Imports import Network.Wire.Bot.Metrics import Network.Wire.Client.API.Push (EventType (..), eventTypeText) ------------------------------------------------------------------------------- -- * Create Reports data Report = Report { reportTitle :: !Text, reportDate :: !UTCTime, reportSections :: [Section], _data :: !Data } deriving (Eq) | Create a ' Report ' of the metrics in the given ' Section 's . -- Note that reports are not created atomically, i.e. reports that -- are created while bots are still active may not be fully consistent. createReport :: MonadIO m => Text -> Metrics -> SectionS -> m Report createReport t m (SectionS (Endo f)) = do d <- liftIO getCurrentTime v <- liftIO $ foldM go mempty (concatMap sectionMetrics s) pure $! Report t d s v where s = f [] go (Data cs ls bs gs) metric = case metric of Counter _ p -> do v <- counterValue =<< counterGet p m pure $! Data (HashMap.insert p v cs) ls bs gs Gauge _ p -> do v <- gaugeValue =<< gaugeGet p m pure $! Data cs ls bs (HashMap.insert p v gs) Histogram _ p hi -> do v <- histoGet hi m >>= histoValue pure $! Data cs ls (HashMap.insert p v bs) gs ------------------------------------------------------------------------------- -- * Access Report Data data Data = Data { _counters :: HashMap Path Double, _labels :: HashMap Path Text, _histograms :: HashMap Path (Map Bucket Int), _gauges :: HashMap Path Double } deriving (Eq) instance Semigroup Data where (<>) (Data a b c d) (Data w x y z) = Data (a <> w) (b <> x) (c <> y) (d <> z) instance Monoid Data where mempty = Data mempty mempty mempty mempty reportCounter :: Report -> Path -> Double reportCounter r p = fromMaybe 0 $ HashMap.lookup p (_counters (_data r)) reportLabel :: Report -> Path -> Text reportLabel r p = fromMaybe "" $ HashMap.lookup p (_labels (_data r)) reportGauge :: Report -> Path -> Double reportGauge r p = fromMaybe 0 $ HashMap.lookup p (_gauges (_data r)) reportBucket :: Report -> Path -> Map Bucket Int reportBucket r p = fromMaybe mempty $ HashMap.lookup p (_histograms (_data r)) ------------------------------------------------------------------------------- -- * Structure Reports newtype SectionS = SectionS (Endo [Section]) deriving (Semigroup, Monoid) data Section = Section { sectionName :: !Text, sectionMetrics :: [Metric] } deriving (Eq) data Metric = Counter !Text !Path | Gauge !Text !Path | Histogram !Text !Path !HistogramInfo deriving (Eq) section :: Text -> [Metric] -> SectionS section t m = SectionS $ Endo (Section t m :) defaultSections :: SectionS defaultSections = botsSection <> assertionsSection <> exceptionsSection <> eventsTotalSection <> foldMap eventTypeSection [(minBound :: EventType) ..] botsSection :: SectionS botsSection = section "Bots" [ Counter "Created (New)" botsCreatedNew, Counter "Created (Cached)" botsCreatedCached, Counter "Alive" botsAlive ] exceptionsSection :: SectionS exceptionsSection = section "Exceptions" [ Counter "Total" exceptionsTotal ] assertionsSection :: SectionS assertionsSection = section "Assertions" [ Counter "Total" assertionsTotal, Counter "Failed" assertionsFailed ] eventsTotalSection :: SectionS eventsTotalSection = section "Events (Total)" [ Counter "Received" eventsTotalRcvd, Counter "Acknowledged" eventsTotalAckd, Counter "Ignored" eventsTotalIgnd, Counter "Missed" eventsTotalMssd ] eventTypeSection :: EventType -> SectionS eventTypeSection t = section ("Event (" <> eventTypeText t <> ")") [ Counter "Received" (eventTypeRcvd t), Counter "Acknowledged" (eventTypeAckd t), Counter "Ignored" (eventTypeIgnd t), Counter "Missed" (eventTypeMssd t) ]
null
https://raw.githubusercontent.com/wireapp/wire-server/598c3c7b5c3c80a41c713a8fdb88e6658b2daba0/libs/api-bot/src/Network/Wire/Bot/Report.hs
haskell
# LANGUAGE OverloadedStrings # This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. * Create Reports * Access Report Data * Structure Reports ** Predefined Sections ----------------------------------------------------------------------------- * Create Reports Note that reports are not created atomically, i.e. reports that are created while bots are still active may not be fully consistent. ----------------------------------------------------------------------------- * Access Report Data ----------------------------------------------------------------------------- * Structure Reports
# LANGUAGE GeneralizedNewtypeDeriving # Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Network.Wire.Bot.Report Report (reportTitle, reportDate, reportSections), createReport, reportCounter, reportLabel, reportGauge, reportBucket, SectionS, Section (sectionName, sectionMetrics), Metric (..), section, defaultSections, botsSection, exceptionsSection, assertionsSection, eventsTotalSection, eventTypeSection, ) where import qualified Data.HashMap.Strict as HashMap import Data.Metrics import Data.Time.Clock import Imports import Network.Wire.Bot.Metrics import Network.Wire.Client.API.Push (EventType (..), eventTypeText) data Report = Report { reportTitle :: !Text, reportDate :: !UTCTime, reportSections :: [Section], _data :: !Data } deriving (Eq) | Create a ' Report ' of the metrics in the given ' Section 's . createReport :: MonadIO m => Text -> Metrics -> SectionS -> m Report createReport t m (SectionS (Endo f)) = do d <- liftIO getCurrentTime v <- liftIO $ foldM go mempty (concatMap sectionMetrics s) pure $! Report t d s v where s = f [] go (Data cs ls bs gs) metric = case metric of Counter _ p -> do v <- counterValue =<< counterGet p m pure $! Data (HashMap.insert p v cs) ls bs gs Gauge _ p -> do v <- gaugeValue =<< gaugeGet p m pure $! Data cs ls bs (HashMap.insert p v gs) Histogram _ p hi -> do v <- histoGet hi m >>= histoValue pure $! Data cs ls (HashMap.insert p v bs) gs data Data = Data { _counters :: HashMap Path Double, _labels :: HashMap Path Text, _histograms :: HashMap Path (Map Bucket Int), _gauges :: HashMap Path Double } deriving (Eq) instance Semigroup Data where (<>) (Data a b c d) (Data w x y z) = Data (a <> w) (b <> x) (c <> y) (d <> z) instance Monoid Data where mempty = Data mempty mempty mempty mempty reportCounter :: Report -> Path -> Double reportCounter r p = fromMaybe 0 $ HashMap.lookup p (_counters (_data r)) reportLabel :: Report -> Path -> Text reportLabel r p = fromMaybe "" $ HashMap.lookup p (_labels (_data r)) reportGauge :: Report -> Path -> Double reportGauge r p = fromMaybe 0 $ HashMap.lookup p (_gauges (_data r)) reportBucket :: Report -> Path -> Map Bucket Int reportBucket r p = fromMaybe mempty $ HashMap.lookup p (_histograms (_data r)) newtype SectionS = SectionS (Endo [Section]) deriving (Semigroup, Monoid) data Section = Section { sectionName :: !Text, sectionMetrics :: [Metric] } deriving (Eq) data Metric = Counter !Text !Path | Gauge !Text !Path | Histogram !Text !Path !HistogramInfo deriving (Eq) section :: Text -> [Metric] -> SectionS section t m = SectionS $ Endo (Section t m :) defaultSections :: SectionS defaultSections = botsSection <> assertionsSection <> exceptionsSection <> eventsTotalSection <> foldMap eventTypeSection [(minBound :: EventType) ..] botsSection :: SectionS botsSection = section "Bots" [ Counter "Created (New)" botsCreatedNew, Counter "Created (Cached)" botsCreatedCached, Counter "Alive" botsAlive ] exceptionsSection :: SectionS exceptionsSection = section "Exceptions" [ Counter "Total" exceptionsTotal ] assertionsSection :: SectionS assertionsSection = section "Assertions" [ Counter "Total" assertionsTotal, Counter "Failed" assertionsFailed ] eventsTotalSection :: SectionS eventsTotalSection = section "Events (Total)" [ Counter "Received" eventsTotalRcvd, Counter "Acknowledged" eventsTotalAckd, Counter "Ignored" eventsTotalIgnd, Counter "Missed" eventsTotalMssd ] eventTypeSection :: EventType -> SectionS eventTypeSection t = section ("Event (" <> eventTypeText t <> ")") [ Counter "Received" (eventTypeRcvd t), Counter "Acknowledged" (eventTypeAckd t), Counter "Ignored" (eventTypeIgnd t), Counter "Missed" (eventTypeMssd t) ]
556939b968b551b9e99f29038259088eef0857c4ef0485d21a8569c2182c926a
HaskellCNOrg/snap-web
ReplyForm.hs
{-# LANGUAGE OverloadedStrings #-} module Views.ReplyForm where import Data.Text (Text) import qualified Data.Text as T import Snap import Text.Digestive import Text.Digestive.FormExt import Text.Digestive.Snap ------------------------------------------------------------ data ReplyVo = ReplyVo { replyToTopicId :: T.Text , replyToReplyId :: T.Text -- Maybe Empty , replyContent :: T.Text } deriving (Show) ------------------------------------------------------------ runReplyForm :: MonadSnap m => m (View Text, Maybe ReplyVo) runReplyForm = runForm "reply-to-topic-form" replyForm replyForm :: Monad m => Form Text m ReplyVo replyForm = ReplyVo <$> "replyToTopicId" .: checkRequired "replyToTopicId is required" (text Nothing) <*> "replyToReplyId" .: text Nothing <*> "content" .: contentValidation (text Nothing) ------------------------------------------------------------ runReplyToRelpyForm :: MonadSnap m => m (View Text, Maybe ReplyVo) runReplyToRelpyForm = runForm "reply-to-reply-form" replyToRelpyForm -- | -- replyToRelpyForm :: Monad m => Form Text m ReplyVo replyToRelpyForm = ReplyVo <$> "replyToTopicId" .: checkRequired "replyToReplyTopicId is required" (text Nothing) <*> "replyToReplyId" .: checkRequired "replyToReplyReplyId is required" (text Nothing) <*> "replyContent" .: replyOfReplyContentMaxLength (contentValidation (text Nothing)) replyOfReplyContentMaxLength :: Monad m => Form Text m Text -> Form Text m Text replyOfReplyContentMaxLength = checkMaxLength 160 ------------------------------------------------------------ contentValidation :: Monad m => Form Text m Text -> Form Text m Text contentValidation = checkMinLength 6 . checkRequired "Reply content can not be empty."
null
https://raw.githubusercontent.com/HaskellCNOrg/snap-web/f104fd9b8fc5ae74fc7b8002f0eb3f182a61529e/src/Views/ReplyForm.hs
haskell
# LANGUAGE OverloadedStrings # ---------------------------------------------------------- Maybe Empty ---------------------------------------------------------- ---------------------------------------------------------- | ----------------------------------------------------------
module Views.ReplyForm where import Data.Text (Text) import qualified Data.Text as T import Snap import Text.Digestive import Text.Digestive.FormExt import Text.Digestive.Snap data ReplyVo = ReplyVo { replyToTopicId :: T.Text , replyContent :: T.Text } deriving (Show) runReplyForm :: MonadSnap m => m (View Text, Maybe ReplyVo) runReplyForm = runForm "reply-to-topic-form" replyForm replyForm :: Monad m => Form Text m ReplyVo replyForm = ReplyVo <$> "replyToTopicId" .: checkRequired "replyToTopicId is required" (text Nothing) <*> "replyToReplyId" .: text Nothing <*> "content" .: contentValidation (text Nothing) runReplyToRelpyForm :: MonadSnap m => m (View Text, Maybe ReplyVo) runReplyToRelpyForm = runForm "reply-to-reply-form" replyToRelpyForm replyToRelpyForm :: Monad m => Form Text m ReplyVo replyToRelpyForm = ReplyVo <$> "replyToTopicId" .: checkRequired "replyToReplyTopicId is required" (text Nothing) <*> "replyToReplyId" .: checkRequired "replyToReplyReplyId is required" (text Nothing) <*> "replyContent" .: replyOfReplyContentMaxLength (contentValidation (text Nothing)) replyOfReplyContentMaxLength :: Monad m => Form Text m Text -> Form Text m Text replyOfReplyContentMaxLength = checkMaxLength 160 contentValidation :: Monad m => Form Text m Text -> Form Text m Text contentValidation = checkMinLength 6 . checkRequired "Reply content can not be empty."
12b8137cafab14d2d837d55f7360b27cff2be31741c349859c61845d6fc418de
nominolo/scion
Core.hs
# LANGUAGE ExistentialQuantification , DeriveDataTypeable # module Scion.Types.Core ( * Generalised IO and Exception monads module Exception, MonadIO(..), io, gcatches, HandlerM(..), -- * Exception Types ScionException(..), scionError, -- * Logging Verbosity, silent, normal, verbose, deafening, LogMonad(..), ) where from GHC import Exception import Data.Typeable ( Typeable ) -- | A short name for 'liftIO'. io :: MonadIO m => IO a -> m a io = liftIO # INLINE io # | A generalised version of ' Control.Exception.catches ' . -- -- Example use: -- -- > f = expr `gcatches` [HandlerM (\(ex :: ArithException) -> handleArith ex), -- > HandlerM (\(ex :: IOException) -> handleIO ex)] -- gcatches :: (MonadIO m, ExceptionMonad m) => m a -> [HandlerM m a] -> m a gcatches act handlers = act `gcatch` catchesHandler handlers -- | You need this when using 'catches'. data HandlerM m a = forall e . Exception e => HandlerM (e -> m a) catchesHandler :: (MonadIO m, ExceptionMonad m) => [HandlerM m a] -> SomeException -> m a catchesHandler handlers e = foldr tryHandler (io (throwIO e)) handlers where tryHandler (HandlerM handler) res = case fromException e of Just e' -> handler e' Nothing -> res data ScionException = ScionException String deriving (Typeable) instance Show ScionException where show (ScionException msg) = "Scion Exception: " ++ msg instance Exception ScionException -- | Utility function for throwing a 'ScionException'. This uses -- 'throwIO' under the hood which ensures that exceptions are properly -- serialised with the underlying monad effects. scionError :: MonadIO m => String -> m a scionError msg = io $ throwIO $ ScionException msg -- | Describes the verbosity level for logging. newtype Verbosity = Verbosity Int deriving (Eq, Ord) -- | Minimal verbosity. silent :: Verbosity silent = Verbosity 0 -- | Default verbosity. normal :: Verbosity normal = Verbosity 1 -- | Increased verbosity. verbose :: Verbosity verbose = Verbosity 2 -- | Maximum verbosity. deafening :: Verbosity deafening = Verbosity 3 -- | A class for monads that support logging. class LogMonad m where -- | Sent a message with the given verbosity. -- -- A @message v msg@ is printed if the configured verbosity is @>= v@. message :: Verbosity -> String -> m () -- | Set verbosity level. setVerbosity :: Verbosity -> m () -- | Get current verbosity level. getVerbosity :: m Verbosity
null
https://raw.githubusercontent.com/nominolo/scion/99b4589175665687181a932cd836850205625f71/src/Scion/Types/Core.hs
haskell
* Exception Types * Logging | A short name for 'liftIO'. Example use: > f = expr `gcatches` [HandlerM (\(ex :: ArithException) -> handleArith ex), > HandlerM (\(ex :: IOException) -> handleIO ex)] | You need this when using 'catches'. | Utility function for throwing a 'ScionException'. This uses 'throwIO' under the hood which ensures that exceptions are properly serialised with the underlying monad effects. | Describes the verbosity level for logging. | Minimal verbosity. | Default verbosity. | Increased verbosity. | Maximum verbosity. | A class for monads that support logging. | Sent a message with the given verbosity. A @message v msg@ is printed if the configured verbosity is @>= v@. | Set verbosity level. | Get current verbosity level.
# LANGUAGE ExistentialQuantification , DeriveDataTypeable # module Scion.Types.Core ( * Generalised IO and Exception monads module Exception, MonadIO(..), io, gcatches, HandlerM(..), ScionException(..), scionError, Verbosity, silent, normal, verbose, deafening, LogMonad(..), ) where from GHC import Exception import Data.Typeable ( Typeable ) io :: MonadIO m => IO a -> m a io = liftIO # INLINE io # | A generalised version of ' Control.Exception.catches ' . gcatches :: (MonadIO m, ExceptionMonad m) => m a -> [HandlerM m a] -> m a gcatches act handlers = act `gcatch` catchesHandler handlers data HandlerM m a = forall e . Exception e => HandlerM (e -> m a) catchesHandler :: (MonadIO m, ExceptionMonad m) => [HandlerM m a] -> SomeException -> m a catchesHandler handlers e = foldr tryHandler (io (throwIO e)) handlers where tryHandler (HandlerM handler) res = case fromException e of Just e' -> handler e' Nothing -> res data ScionException = ScionException String deriving (Typeable) instance Show ScionException where show (ScionException msg) = "Scion Exception: " ++ msg instance Exception ScionException scionError :: MonadIO m => String -> m a scionError msg = io $ throwIO $ ScionException msg newtype Verbosity = Verbosity Int deriving (Eq, Ord) silent :: Verbosity silent = Verbosity 0 normal :: Verbosity normal = Verbosity 1 verbose :: Verbosity verbose = Verbosity 2 deafening :: Verbosity deafening = Verbosity 3 class LogMonad m where message :: Verbosity -> String -> m () setVerbosity :: Verbosity -> m () getVerbosity :: m Verbosity
11a0442e4a1816421d0d0bf2b2831625fcce91278e6a97ae0de80839481c6093
clj-kondo/clj-kondo
unused_vars.cljs
#!/usr/bin/env plk -K (ns script.unused-vars (:require [cljs.reader :as edn] [clojure.set :as set] [clojure.string :as str] [planck.shell :refer [sh]])) (defn -main [& paths] (let [out (:out (apply sh "clj-kondo" "--config" "{:output {:format :edn}, :analysis true}" "--lint" paths)) analysis (:analysis (edn/read-string out)) {:keys [:var-definitions :var-usages]} analysis defined-vars (set (map (juxt :ns :name) var-definitions)) used-vars (set (map (juxt :to :name) var-usages)) unused-vars (map (fn [[ns v]] (symbol (str ns) (str v))) (set/difference defined-vars used-vars))] (if (seq unused-vars) (do (println "The following vars are unused:") (println (str/join "\n" unused-vars))) (println "No unused vars found.")))) (set! *main-cli-fn* -main)
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/d012ab5614e0824dd51da9946dc8708dee7f498d/analysis/script/unused_vars.cljs
clojure
#!/usr/bin/env plk -K (ns script.unused-vars (:require [cljs.reader :as edn] [clojure.set :as set] [clojure.string :as str] [planck.shell :refer [sh]])) (defn -main [& paths] (let [out (:out (apply sh "clj-kondo" "--config" "{:output {:format :edn}, :analysis true}" "--lint" paths)) analysis (:analysis (edn/read-string out)) {:keys [:var-definitions :var-usages]} analysis defined-vars (set (map (juxt :ns :name) var-definitions)) used-vars (set (map (juxt :to :name) var-usages)) unused-vars (map (fn [[ns v]] (symbol (str ns) (str v))) (set/difference defined-vars used-vars))] (if (seq unused-vars) (do (println "The following vars are unused:") (println (str/join "\n" unused-vars))) (println "No unused vars found.")))) (set! *main-cli-fn* -main)
f7327b444c7f40daa0927139b5f89637f9ac74e7306a1f98fc9fbc30f3baaf8a
ghc/packages-directory
CopyFileWithMetadata.hs
# LANGUAGE CPP # module CopyFileWithMetadata where #include "util.inl" import qualified Data.List as List main :: TestEnv -> IO () main _t = (`finally` cleanup) $ do -- prepare source file writeFile "a" contents writeFile "b" "To be replaced\n" setModificationTime "a" mtime modifyWritable False "a" perm <- getPermissions "a" -- sanity check T(expectEq) () ["a", "b"] . List.sort =<< listDirectory "." -- copy file copyFileWithMetadata "a" "b" copyFileWithMetadata "a" "c" -- make sure we got the right results T(expectEq) () ["a", "b", "c"] . List.sort =<< listDirectory "." for_ ["b", "c"] $ \ f -> do T(expectEq) f perm =<< getPermissions f T(expectEq) f mtime =<< getModificationTime f T(expectEq) f contents =<< readFile f where contents = "This is the data\n" mtime = read "2000-01-01 00:00:00Z" cleanup = do -- needed to ensure the test runner can clean up our mess modifyWritable True "a" `catchIOError` \ _ -> return () modifyWritable True "b" `catchIOError` \ _ -> return () modifyWritable True "c" `catchIOError` \ _ -> return () modifyWritable b f = do perm <- getPermissions f setPermissions f (setOwnerWritable b perm)
null
https://raw.githubusercontent.com/ghc/packages-directory/75165a9d69bebba96e0e3a1e519ab481d1362dd2/tests/CopyFileWithMetadata.hs
haskell
prepare source file sanity check copy file make sure we got the right results needed to ensure the test runner can clean up our mess
# LANGUAGE CPP # module CopyFileWithMetadata where #include "util.inl" import qualified Data.List as List main :: TestEnv -> IO () main _t = (`finally` cleanup) $ do writeFile "a" contents writeFile "b" "To be replaced\n" setModificationTime "a" mtime modifyWritable False "a" perm <- getPermissions "a" T(expectEq) () ["a", "b"] . List.sort =<< listDirectory "." copyFileWithMetadata "a" "b" copyFileWithMetadata "a" "c" T(expectEq) () ["a", "b", "c"] . List.sort =<< listDirectory "." for_ ["b", "c"] $ \ f -> do T(expectEq) f perm =<< getPermissions f T(expectEq) f mtime =<< getModificationTime f T(expectEq) f contents =<< readFile f where contents = "This is the data\n" mtime = read "2000-01-01 00:00:00Z" cleanup = do modifyWritable True "a" `catchIOError` \ _ -> return () modifyWritable True "b" `catchIOError` \ _ -> return () modifyWritable True "c" `catchIOError` \ _ -> return () modifyWritable b f = do perm <- getPermissions f setPermissions f (setOwnerWritable b perm)
b41f505294eab32e2c401564e2956832e87544f46808b8d2f53ba173f4ef00e2
GaloisInc/macaw
AtomWrapper.hs
# LANGUAGE DataKinds # # LANGUAGE KindSignatures # {-# LANGUAGE RankNTypes #-} module Data.Macaw.AArch32.Symbolic.AtomWrapper ( AtomWrapper(..), liftAtomMap, liftAtomTrav, liftAtomIn ) where import Data.Kind ( Type ) import qualified Lang.Crucible.Types as C import qualified Data.Macaw.Types as MT import qualified Data.Macaw.Symbolic as MS newtype AtomWrapper (f :: C.CrucibleType -> Type) (tp :: MT.Type) = AtomWrapper (f (MS.ToCrucibleType tp)) liftAtomMap :: (forall s. f s -> g s) -> AtomWrapper f t -> AtomWrapper g t liftAtomMap f (AtomWrapper x) = AtomWrapper (f x) liftAtomTrav :: Functor m => (forall s. f s -> m (g s)) -> (AtomWrapper f t -> m (AtomWrapper g t)) liftAtomTrav f (AtomWrapper x) = AtomWrapper <$> f x liftAtomIn :: (forall s. f s -> a) -> AtomWrapper f t -> a liftAtomIn f (AtomWrapper x) = f x
null
https://raw.githubusercontent.com/GaloisInc/macaw/ff894f9286f976d0ab131325bea902ef6275aad2/macaw-aarch32-symbolic/src/Data/Macaw/AArch32/Symbolic/AtomWrapper.hs
haskell
# LANGUAGE RankNTypes #
# LANGUAGE DataKinds # # LANGUAGE KindSignatures # module Data.Macaw.AArch32.Symbolic.AtomWrapper ( AtomWrapper(..), liftAtomMap, liftAtomTrav, liftAtomIn ) where import Data.Kind ( Type ) import qualified Lang.Crucible.Types as C import qualified Data.Macaw.Types as MT import qualified Data.Macaw.Symbolic as MS newtype AtomWrapper (f :: C.CrucibleType -> Type) (tp :: MT.Type) = AtomWrapper (f (MS.ToCrucibleType tp)) liftAtomMap :: (forall s. f s -> g s) -> AtomWrapper f t -> AtomWrapper g t liftAtomMap f (AtomWrapper x) = AtomWrapper (f x) liftAtomTrav :: Functor m => (forall s. f s -> m (g s)) -> (AtomWrapper f t -> m (AtomWrapper g t)) liftAtomTrav f (AtomWrapper x) = AtomWrapper <$> f x liftAtomIn :: (forall s. f s -> a) -> AtomWrapper f t -> a liftAtomIn f (AtomWrapper x) = f x
2da4d061a4d29b66b93ca2d43f0c8aed70f065c4ba1b98b4107e681e891fade2
WFP-VAM/RAMResourcesScripts
FES.sps
* Encoding: UTF-8. ******************************************************************************** * SPSS Syntax for the Food Expenditure Share (FES) indicator ******************************************************************************* *Important note: the value of consumed in-kind assistance/gifts should be considered in the calculation of FES for both assessment exercises as well as monitoring exercises *-------------------------------------------------------------------------------* *1. Create variables for food expenditure, by source *-------------------------------------------------------------------------------* *Important note: add recall period of _7D or _1M to the variables names below depending on what has been selected for your CO. It is recommended to follow standard recall periods as in the module. *** 1.a Label variables: VARIABLE LABELS HHExpFCer_Purch_MN_7D 'Expenditures on cereals' HHExpFCer_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - cereals' HHExpFCer_Own_MN_7D 'Value of consumed own production - cereals' HHExpFTub_Purch_MN_7D 'Expenditures on tubers' HHExpFTub_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - tubers' HHExpFTub_Own_MN_7D 'Value of consumed own production - tubers' HHExpFPuls_Purch_MN_7D 'Expenditures on pulses & nuts' HHExpFPuls_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - pulses and nuts' HHExpFPuls_Own_MN_7D 'Value of consumed own production - pulses & nuts' HHExpFVeg_Purch_MN_7D 'Expenditures on vegetables' HHExpFVeg_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - vegetables' HHExpFVeg_Own_MN_7D 'Value of consumed own production - vegetables' HHExpFFrt_Purch_MN_7D 'Expenditures on fruits' HHExpFFrt_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - fruits' HHExpFFrt_Own_MN_7D 'Value of consumed own production - fruits' HHExpFAnimMeat_Purch_MN_7D 'Expenditures on meat' HHExpFAnimMeat_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - meat' HHExpFAnimMeat_Own_MN_7D 'Value of consumed own production - meat' HHExpFAnimFish_Purch_MN_7D 'Expenditures on fish' HHExpFAnimFish_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - fish' HHExpFAnimFish_Own_MN_7D 'Value of consumed own production - fish' HHExpFFats_Purch_MN_7D 'Expenditures on fats' HHExpFFats_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - fats' HHExpFFats_Own_MN_7D 'Value of consumed own production - fats' HHExpFDairy_Purch_MN_7D 'Expenditures on milk/dairy products' HHExpFDairy_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - milk/dairy products' HHExpFDairy_Own_MN_7D 'Value of consumed own production - milk/dairy products' HHExpFEgg_Purch_MN_7D 'Expenditures on eggs' HHExpFEgg_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - eggs' HHExpFEgg_Own_MN_7D 'Value of consumed own production - eggs' HHExpFSgr_Purch_MN_7D 'Expenditures on sugar/confectionery/desserts' HHExpFSgr_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - sugar/confectionery/desserts' HHExpFSgr_Own_MN_7D 'Value of consumed own production - sugar/confectionery/desserts' HHExpFCond_Purch_MN_7D 'Expenditures on condiments' HHExpFCond_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - condiments' HHExpFCond_Own_MN_7D 'Value of consumed own production - condiments' HHExpFBev_Purch_MN_7D 'Expenditures on beverages' HHExpFBev_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - beverages' HHExpFBev_Own_MN_7D 'Value of consumed own production - beverages' HHExpFOut_Purch_MN_7D 'Expenditures on snacks/meals prepared outside' HHExpFOut_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - snacks/meals prepared outside' HHExpFOut_Own_MN_7D 'Value of consumed own production - snacks/meals prepared outside'. EXECUTE. * If the questionnaire included further food categories/items label the respective variables *** 1.b Calculate total value of food expenditures/consumption by source make sure to express the newly created variables in monthly terms by multiplying by 30/7 *Monthly food expenditures in cash/credit COMPUTE HHExp_Food_Purch_MN_1M=SUM(HHExpFCer_Purch_MN_7D, HHExpFTub_Purch_MN_7D, HHExpFPuls_Purch_MN_7D, + HHExpFVeg_Purch_MN_7D, HHExpFFrt_Purch_MN_7D, HHExpFAnimMeat_Purch_MN_7D, HHExpFAnimFish_Purch_MN_7D, HHExpFFats_Purch_MN_7D, + HHExpFDairy_Purch_MN_7D, HHExpFEgg_Purch_MN_7D, HHExpFSgr_Purch_MN_7D, HHExpFCond_Purch_MN_7D, HHExpFBev_Purch_MN_7D, HHExpFOut_Purch_MN_7D). COMPUTE HHExp_Food_Purch_MN_1M=HHExp_Food_Purch_MN_1M*(30/7). /* conversion in monthly terms - do it only if recall period for food was 7 days. VARIABLE LABELS HHExp_Food_Purch_MN_1M 'Total monthly food expenditure (cash and credit)'. EXECUTE. *Monthly value of consumed food from gift/aid COMPUTE HHExp_Food_GiftAid_MN_1M=SUM(HHExpFCer_GiftAid_MN_7D, HHExpFTub_GiftAid_MN_7D, HHExpFPuls_GiftAid_MN_7D, + HHExpFVeg_GiftAid_MN_7D, HHExpFFrt_GiftAid_MN_7D, HHExpFAnimMeat_GiftAid_MN_7D, HHExpFAnimFish_GiftAid_MN_7D, HHExpFFats_GiftAid_MN_7D, + HHExpFDairy_GiftAid_MN_7D, HHExpFEgg_GiftAid_MN_7D, HHExpFSgr_GiftAid_MN_7D, HHExpFCond_GiftAid_MN_7D, HHExpFBev_GiftAid_MN_7D, HHExpFOut_GiftAid_MN_7D). COMPUTE HHExp_Food_GiftAid_MN_1M=HHExp_Food_GiftAid_MN_1M*(30/7). /*conversion in monthly terms - do it only if recall period for food was 7 days. VARIABLE LABELS HHExp_Food_GiftAid_MN_1M 'Total monthly food consumption from gifts/aid'. EXECUTE. *Monthly value of consumed food from own-production COMPUTE HHExp_Food_Own_MN_1M=SUM(HHExpFCer_Own_MN_7D, HHExpFTub_Own_MN_7D, HHExpFPuls_Own_MN_7D, + HHExpFVeg_Own_MN_7D, HHExpFFrt_Own_MN_7D, HHExpFAnimMeat_Own_MN_7D, HHExpFAnimFish_Own_MN_7D, HHExpFFats_Own_MN_7D, + HHExpFDairy_Own_MN_7D, HHExpFEgg_Own_MN_7D, HHExpFSgr_Own_MN_7D, HHExpFCond_Own_MN_7D, HHExpFBev_Own_MN_7D, HHExpFOut_Own_MN_7D). COMPUTE HHExp_Food_Own_MN_1M=HHExp_Food_Own_MN_1M*(30/7). /* conversion in monthly terms - do it only if recall period for food was 7 day. VARIABLE LABELS HHExp_Food_Own_MN_1M 'Total monthly food consumption from own-production'. EXECUTE. *-------------------------------------------------------------------------------* *2. Create variables for non-food expenditure, by source *-------------------------------------------------------------------------------* *** 2.a Label variables: *1 month recall period - variables labels. VARIABLE LABELS HHExpNFHyg_Purch_MN_1M 'Expenditures on hygiene' HHExpNFHyg_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - hygiene' HHExpNFTransp_Purch_MN_1M 'Expenditures on transport' HHExpNFTransp_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - transport' HHExpNFFuel_Purch_MN_1M 'Expenditures on fuel' HHExpNFFuel_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - fuel' HHExpNFWat_Purch_MN_1M 'Expenditures on water' HHExpNFWat_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - water' HHExpNFElec_Purch_MN_1M 'Expenditures on electricity' HHExpNFElec_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - electricity' HHExpNFEnerg_Purch_MN_1M 'Expenditures on energy (not electricity)' HHExpNFEnerg_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - energy (not electricity)' HHExpNFDwelSer_Purch_MN_1M 'Expenditures on services related to dwelling' HHExpNFDwelSer_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - services related to dwelling' HHExpNFPhone_Purch_MN_1M 'Expenditures on communication' HHExpNFPhone_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - communication' HHExpNFRecr_Purch_MN_1M 'Expenditures on recreation' HHExpNFRecr_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - recreation' HHExpNFAlcTobac_Purch_MN_1M 'Expenditures on alchol/tobacco' HHExpNFAlcTobac_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - alchol/tobacco'. EXECUTE. * If the questionnaire included further non-food categories/items label the respective variables *6 months recall period - variables lables. VARIABLE LABELS HHExpNFMedServ_Purch_MN_6M 'Expenditures on health services' HHExpNFMedServ_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - health services' HHExpNFMedGood_Purch_MN_6M 'Expenditures on medicines and health products' HHExpNFMedGood_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - medicines and health products' HHExpNFCloth_Purch_MN_6M 'Expenditures on clothing and footwear' HHExpNFCloth_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - clothing and footwear' HHExpNFEduFee_Purch_MN_6M 'Expenditures on education services' HHExpNFEduFee_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - education services' HHExpNFEduGood_Purch_MN_6M 'Expenditures on education goods' HHExpNFEduGood_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - education goods' HHExpNFRent_Purch_MN_6M 'Expenditures on rent' HHExpNFRent_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - rent' HHExpNFHHSoft_Purch_MN_6M 'Expenditures on non-durable furniture/utensils' HHExpNFHHSoft_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - non-durable furniture/utensils' HHExpNFHHMaint_Purch_MN_6M 'Expenditures on household routine maintenance' HHExpNFHHMaint_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - household routine maintenance'. EXECUTE. * If the questionnaire included further non-food categories/items label the respective variables. *** 2.b Calculate total value of non-food expenditures/consumption by source ** Total non-food expenditure (cash/credit) * 30 days recall. COMPUTE HHExpNFTotal_Purch_MN_30D=SUM(HHExpNFHyg_Purch_MN_1M, HHExpNFTransp_Purch_MN_1M, HHExpNFFuel_Purch_MN_1M, + HHExpNFWat_Purch_MN_1M, HHExpNFElec_Purch_MN_1M, HHExpNFEnerg_Purch_MN_1M, HHExpNFDwelSer_Purch_MN_1M, HHExpNFPhone_Purch_MN_1M, HHExpNFRecr_Purch_MN_1M, HHExpNFAlcTobac_Purch_MN_1M). EXECUTE. * 6 months recall. COMPUTE HHExpNFTotal_Purch_MN_6M=SUM(HHExpNFMedServ_Purch_MN_6M, HHExpNFMedGood_Purch_MN_6M, HHExpNFCloth_Purch_MN_6M, + HHExpNFEduFee_Purch_MN_6M, HHExpNFEduGood_Purch_MN_6M, HHExpNFRent_Purch_MN_6M, HHExpNFHHSoft_Purch_MN_6M, HHExpNFHHMaint_Purch_MN_6M). /* careful with rent: should include only if also incuded in MEB. EXECUTE. * Express 6 months in monthly terms. COMPUTE HHExpNFTotal_Purch_MN_6M=HHExpNFTotal_Purch_MN_6M/6. EXECUTE. * Sum. COMPUTE HHExpNFTotal_Purch_MN_1M=SUM(HHExpNFTotal_Purch_MN_30D, HHExpNFTotal_Purch_MN_6M). EXECUTE. VARIABLE LABELS HHExpNFTotal_Purch_MN_1M 'Total monthly non-food expenditure (cash and credit)'. delete variables HHExpNFTotal_Purch_MN_6M HHExpNFTotal_Purch_MN_30D. EXECUTE. ** Total value of consumed non-food from gift/aid * 30 days recall. COMPUTE HHExpNFTotal_GiftAid_MN_30D=SUM(HHExpNFHyg_GiftAid_MN_1M, HHExpNFTransp_GiftAid_MN_1M, HHExpNFFuel_GiftAid_MN_1M,+ HHExpNFWat_GiftAid_MN_1M, HHExpNFElec_GiftAid_MN_1M, HHExpNFEnerg_GiftAid_MN_1M, HHExpNFDwelSer_GiftAid_MN_1M, HHExpNFPhone_GiftAid_MN_1M, HHExpNFRecr_GiftAid_MN_1M, HHExpNFAlcTobac_GiftAid_MN_1M). EXECUTE. * 6 months recall. COMPUTE HHExpNFTotal_GiftAid_MN_6M=SUM(HHExpNFMedServ_GiftAid_MN_6M, HHExpNFMedGood_GiftAid_MN_6M, HHExpNFCloth_GiftAid_MN_6M, + HHExpNFEduFee_GiftAid_MN_6M, HHExpNFEduGood_GiftAid_MN_6M, HHExpNFRent_GiftAid_MN_6M, HHExpNFHHSoft_GiftAid_MN_6M, HHExpNFHHMaint_GiftAid_MN_6M). /* careful with rent: should include only if also incuded in MEB. EXECUTE. * Express 6 months in monthly terms. COMPUTE HHExpNFTotal_GiftAid_MN_6M=HHExpNFTotal_GiftAid_MN_6M/6. EXECUTE. * Sum. COMPUTE HHExpNFTotal_GiftAid_MN_1M=SUM(HHExpNFTotal_GiftAid_MN_30D, HHExpNFTotal_GiftAid_MN_6M). VARIABLE LABELS HHExpNFTotal_GiftAid_MN_1M 'Total monthly non-food consumption from gifts/aid'. EXECUTE. delete variables HHExpNFTotal_GiftAid_MN_6M HHExpNFTotal_GiftAid_MN_30D. EXECUTE. *-------------------------------------------------------------------------------* *3.Calculate total food and non-food consumption expenditures *-------------------------------------------------------------------------------* * Aggregate food expenditures, value of consumed food from gifts/assistance, and value of consumed food from own production. COMPUTE HHExpF_1M=SUM(HHExp_Food_Purch_MN_1M,HHExp_Food_GiftAid_MN_1M, HHExp_Food_Own_MN_1M). EXECUTE. *Aggregate NF expenditures and value of consumed non-food from gifts/assistance. COMPUTE HHExpNF_1M=SUM(HHExpNFTotal_Purch_MN_1M, HHExpNFTotal_GiftAid_MN_1M). EXECUTE. *-------------------------------------------------------------------------------* *4.Compute FES *-------------------------------------------------------------------------------* COMPUTE FES= HHExpF_1M /SUM(HHExpF_1M , HHExpNF_1M). EXECUTE. VARIABLE LABELS FES 'Household food expenditure share'. EXECUTE. RECODE FES (Lowest thru .4999999=1) (.50 thru .64999999=2) (.65 thru .74999999=3) (.75 thru Highest=4) into Foodexp_4pt. EXECUTE. Value labels Foodexp_4pt 1 '<50%' 2 '50-65%' 3 '65-75%' 4' > 75%'. Variable labels Foodexp_4pt 'Food expenditure share categories'. EXECUTE. FREQUENCIES Foodexp_4pt.
null
https://raw.githubusercontent.com/WFP-VAM/RAMResourcesScripts/236e1a630f053d27161c73dfe01a9ef04b7ebdcc/Indicators/Food-expenditure-share/FES.sps
scheme
* Encoding: UTF-8. ******************************************************************************** * SPSS Syntax for the Food Expenditure Share (FES) indicator ******************************************************************************* *Important note: the value of consumed in-kind assistance/gifts should be considered in the calculation of FES for both assessment exercises as well as monitoring exercises *-------------------------------------------------------------------------------* *1. Create variables for food expenditure, by source *-------------------------------------------------------------------------------* *Important note: add recall period of _7D or _1M to the variables names below depending on what has been selected for your CO. It is recommended to follow standard recall periods as in the module. *** 1.a Label variables: VARIABLE LABELS HHExpFCer_Purch_MN_7D 'Expenditures on cereals' HHExpFCer_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - cereals' HHExpFCer_Own_MN_7D 'Value of consumed own production - cereals' HHExpFTub_Purch_MN_7D 'Expenditures on tubers' HHExpFTub_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - tubers' HHExpFTub_Own_MN_7D 'Value of consumed own production - tubers' HHExpFPuls_Purch_MN_7D 'Expenditures on pulses & nuts' HHExpFPuls_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - pulses and nuts' HHExpFPuls_Own_MN_7D 'Value of consumed own production - pulses & nuts' HHExpFVeg_Purch_MN_7D 'Expenditures on vegetables' HHExpFVeg_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - vegetables' HHExpFVeg_Own_MN_7D 'Value of consumed own production - vegetables' HHExpFFrt_Purch_MN_7D 'Expenditures on fruits' HHExpFFrt_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - fruits' HHExpFFrt_Own_MN_7D 'Value of consumed own production - fruits' HHExpFAnimMeat_Purch_MN_7D 'Expenditures on meat' HHExpFAnimMeat_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - meat' HHExpFAnimMeat_Own_MN_7D 'Value of consumed own production - meat' HHExpFAnimFish_Purch_MN_7D 'Expenditures on fish' HHExpFAnimFish_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - fish' HHExpFAnimFish_Own_MN_7D 'Value of consumed own production - fish' HHExpFFats_Purch_MN_7D 'Expenditures on fats' HHExpFFats_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - fats' HHExpFFats_Own_MN_7D 'Value of consumed own production - fats' HHExpFDairy_Purch_MN_7D 'Expenditures on milk/dairy products' HHExpFDairy_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - milk/dairy products' HHExpFDairy_Own_MN_7D 'Value of consumed own production - milk/dairy products' HHExpFEgg_Purch_MN_7D 'Expenditures on eggs' HHExpFEgg_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - eggs' HHExpFEgg_Own_MN_7D 'Value of consumed own production - eggs' HHExpFSgr_Purch_MN_7D 'Expenditures on sugar/confectionery/desserts' HHExpFSgr_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - sugar/confectionery/desserts' HHExpFSgr_Own_MN_7D 'Value of consumed own production - sugar/confectionery/desserts' HHExpFCond_Purch_MN_7D 'Expenditures on condiments' HHExpFCond_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - condiments' HHExpFCond_Own_MN_7D 'Value of consumed own production - condiments' HHExpFBev_Purch_MN_7D 'Expenditures on beverages' HHExpFBev_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - beverages' HHExpFBev_Own_MN_7D 'Value of consumed own production - beverages' HHExpFOut_Purch_MN_7D 'Expenditures on snacks/meals prepared outside' HHExpFOut_GiftAid_MN_7D 'Value of consumed in-kind assistance and gifts - snacks/meals prepared outside' HHExpFOut_Own_MN_7D 'Value of consumed own production - snacks/meals prepared outside'. EXECUTE. * If the questionnaire included further food categories/items label the respective variables *** 1.b Calculate total value of food expenditures/consumption by source make sure to express the newly created variables in monthly terms by multiplying by 30/7 *Monthly food expenditures in cash/credit COMPUTE HHExp_Food_Purch_MN_1M=SUM(HHExpFCer_Purch_MN_7D, HHExpFTub_Purch_MN_7D, HHExpFPuls_Purch_MN_7D, + HHExpFVeg_Purch_MN_7D, HHExpFFrt_Purch_MN_7D, HHExpFAnimMeat_Purch_MN_7D, HHExpFAnimFish_Purch_MN_7D, HHExpFFats_Purch_MN_7D, + HHExpFDairy_Purch_MN_7D, HHExpFEgg_Purch_MN_7D, HHExpFSgr_Purch_MN_7D, HHExpFCond_Purch_MN_7D, HHExpFBev_Purch_MN_7D, HHExpFOut_Purch_MN_7D). COMPUTE HHExp_Food_Purch_MN_1M=HHExp_Food_Purch_MN_1M*(30/7). /* conversion in monthly terms - do it only if recall period for food was 7 days. VARIABLE LABELS HHExp_Food_Purch_MN_1M 'Total monthly food expenditure (cash and credit)'. EXECUTE. *Monthly value of consumed food from gift/aid COMPUTE HHExp_Food_GiftAid_MN_1M=SUM(HHExpFCer_GiftAid_MN_7D, HHExpFTub_GiftAid_MN_7D, HHExpFPuls_GiftAid_MN_7D, + HHExpFVeg_GiftAid_MN_7D, HHExpFFrt_GiftAid_MN_7D, HHExpFAnimMeat_GiftAid_MN_7D, HHExpFAnimFish_GiftAid_MN_7D, HHExpFFats_GiftAid_MN_7D, + HHExpFDairy_GiftAid_MN_7D, HHExpFEgg_GiftAid_MN_7D, HHExpFSgr_GiftAid_MN_7D, HHExpFCond_GiftAid_MN_7D, HHExpFBev_GiftAid_MN_7D, HHExpFOut_GiftAid_MN_7D). COMPUTE HHExp_Food_GiftAid_MN_1M=HHExp_Food_GiftAid_MN_1M*(30/7). /*conversion in monthly terms - do it only if recall period for food was 7 days. VARIABLE LABELS HHExp_Food_GiftAid_MN_1M 'Total monthly food consumption from gifts/aid'. EXECUTE. *Monthly value of consumed food from own-production COMPUTE HHExp_Food_Own_MN_1M=SUM(HHExpFCer_Own_MN_7D, HHExpFTub_Own_MN_7D, HHExpFPuls_Own_MN_7D, + HHExpFVeg_Own_MN_7D, HHExpFFrt_Own_MN_7D, HHExpFAnimMeat_Own_MN_7D, HHExpFAnimFish_Own_MN_7D, HHExpFFats_Own_MN_7D, + HHExpFDairy_Own_MN_7D, HHExpFEgg_Own_MN_7D, HHExpFSgr_Own_MN_7D, HHExpFCond_Own_MN_7D, HHExpFBev_Own_MN_7D, HHExpFOut_Own_MN_7D). COMPUTE HHExp_Food_Own_MN_1M=HHExp_Food_Own_MN_1M*(30/7). /* conversion in monthly terms - do it only if recall period for food was 7 day. VARIABLE LABELS HHExp_Food_Own_MN_1M 'Total monthly food consumption from own-production'. EXECUTE. *-------------------------------------------------------------------------------* *2. Create variables for non-food expenditure, by source *-------------------------------------------------------------------------------* *** 2.a Label variables: *1 month recall period - variables labels. VARIABLE LABELS HHExpNFHyg_Purch_MN_1M 'Expenditures on hygiene' HHExpNFHyg_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - hygiene' HHExpNFTransp_Purch_MN_1M 'Expenditures on transport' HHExpNFTransp_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - transport' HHExpNFFuel_Purch_MN_1M 'Expenditures on fuel' HHExpNFFuel_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - fuel' HHExpNFWat_Purch_MN_1M 'Expenditures on water' HHExpNFWat_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - water' HHExpNFElec_Purch_MN_1M 'Expenditures on electricity' HHExpNFElec_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - electricity' HHExpNFEnerg_Purch_MN_1M 'Expenditures on energy (not electricity)' HHExpNFEnerg_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - energy (not electricity)' HHExpNFDwelSer_Purch_MN_1M 'Expenditures on services related to dwelling' HHExpNFDwelSer_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - services related to dwelling' HHExpNFPhone_Purch_MN_1M 'Expenditures on communication' HHExpNFPhone_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - communication' HHExpNFRecr_Purch_MN_1M 'Expenditures on recreation' HHExpNFRecr_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - recreation' HHExpNFAlcTobac_Purch_MN_1M 'Expenditures on alchol/tobacco' HHExpNFAlcTobac_GiftAid_MN_1M 'Value of consumed in-kind assistance-gifts - alchol/tobacco'. EXECUTE. * If the questionnaire included further non-food categories/items label the respective variables *6 months recall period - variables lables. VARIABLE LABELS HHExpNFMedServ_Purch_MN_6M 'Expenditures on health services' HHExpNFMedServ_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - health services' HHExpNFMedGood_Purch_MN_6M 'Expenditures on medicines and health products' HHExpNFMedGood_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - medicines and health products' HHExpNFCloth_Purch_MN_6M 'Expenditures on clothing and footwear' HHExpNFCloth_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - clothing and footwear' HHExpNFEduFee_Purch_MN_6M 'Expenditures on education services' HHExpNFEduFee_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - education services' HHExpNFEduGood_Purch_MN_6M 'Expenditures on education goods' HHExpNFEduGood_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - education goods' HHExpNFRent_Purch_MN_6M 'Expenditures on rent' HHExpNFRent_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - rent' HHExpNFHHSoft_Purch_MN_6M 'Expenditures on non-durable furniture/utensils' HHExpNFHHSoft_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - non-durable furniture/utensils' HHExpNFHHMaint_Purch_MN_6M 'Expenditures on household routine maintenance' HHExpNFHHMaint_GiftAid_MN_6M 'Value of consumed in-kind assistance-gifts - household routine maintenance'. EXECUTE. * If the questionnaire included further non-food categories/items label the respective variables. *** 2.b Calculate total value of non-food expenditures/consumption by source ** Total non-food expenditure (cash/credit) * 30 days recall. COMPUTE HHExpNFTotal_Purch_MN_30D=SUM(HHExpNFHyg_Purch_MN_1M, HHExpNFTransp_Purch_MN_1M, HHExpNFFuel_Purch_MN_1M, + HHExpNFWat_Purch_MN_1M, HHExpNFElec_Purch_MN_1M, HHExpNFEnerg_Purch_MN_1M, HHExpNFDwelSer_Purch_MN_1M, HHExpNFPhone_Purch_MN_1M, HHExpNFRecr_Purch_MN_1M, HHExpNFAlcTobac_Purch_MN_1M). EXECUTE. * 6 months recall. COMPUTE HHExpNFTotal_Purch_MN_6M=SUM(HHExpNFMedServ_Purch_MN_6M, HHExpNFMedGood_Purch_MN_6M, HHExpNFCloth_Purch_MN_6M, + HHExpNFEduFee_Purch_MN_6M, HHExpNFEduGood_Purch_MN_6M, HHExpNFRent_Purch_MN_6M, HHExpNFHHSoft_Purch_MN_6M, HHExpNFHHMaint_Purch_MN_6M). /* careful with rent: should include only if also incuded in MEB. EXECUTE. * Express 6 months in monthly terms. COMPUTE HHExpNFTotal_Purch_MN_6M=HHExpNFTotal_Purch_MN_6M/6. EXECUTE. * Sum. COMPUTE HHExpNFTotal_Purch_MN_1M=SUM(HHExpNFTotal_Purch_MN_30D, HHExpNFTotal_Purch_MN_6M). EXECUTE. VARIABLE LABELS HHExpNFTotal_Purch_MN_1M 'Total monthly non-food expenditure (cash and credit)'. delete variables HHExpNFTotal_Purch_MN_6M HHExpNFTotal_Purch_MN_30D. EXECUTE. ** Total value of consumed non-food from gift/aid * 30 days recall. COMPUTE HHExpNFTotal_GiftAid_MN_30D=SUM(HHExpNFHyg_GiftAid_MN_1M, HHExpNFTransp_GiftAid_MN_1M, HHExpNFFuel_GiftAid_MN_1M,+ HHExpNFWat_GiftAid_MN_1M, HHExpNFElec_GiftAid_MN_1M, HHExpNFEnerg_GiftAid_MN_1M, HHExpNFDwelSer_GiftAid_MN_1M, HHExpNFPhone_GiftAid_MN_1M, HHExpNFRecr_GiftAid_MN_1M, HHExpNFAlcTobac_GiftAid_MN_1M). EXECUTE. * 6 months recall. COMPUTE HHExpNFTotal_GiftAid_MN_6M=SUM(HHExpNFMedServ_GiftAid_MN_6M, HHExpNFMedGood_GiftAid_MN_6M, HHExpNFCloth_GiftAid_MN_6M, + HHExpNFEduFee_GiftAid_MN_6M, HHExpNFEduGood_GiftAid_MN_6M, HHExpNFRent_GiftAid_MN_6M, HHExpNFHHSoft_GiftAid_MN_6M, HHExpNFHHMaint_GiftAid_MN_6M). /* careful with rent: should include only if also incuded in MEB. EXECUTE. * Express 6 months in monthly terms. COMPUTE HHExpNFTotal_GiftAid_MN_6M=HHExpNFTotal_GiftAid_MN_6M/6. EXECUTE. * Sum. COMPUTE HHExpNFTotal_GiftAid_MN_1M=SUM(HHExpNFTotal_GiftAid_MN_30D, HHExpNFTotal_GiftAid_MN_6M). VARIABLE LABELS HHExpNFTotal_GiftAid_MN_1M 'Total monthly non-food consumption from gifts/aid'. EXECUTE. delete variables HHExpNFTotal_GiftAid_MN_6M HHExpNFTotal_GiftAid_MN_30D. EXECUTE. *-------------------------------------------------------------------------------* *3.Calculate total food and non-food consumption expenditures *-------------------------------------------------------------------------------* * Aggregate food expenditures, value of consumed food from gifts/assistance, and value of consumed food from own production. COMPUTE HHExpF_1M=SUM(HHExp_Food_Purch_MN_1M,HHExp_Food_GiftAid_MN_1M, HHExp_Food_Own_MN_1M). EXECUTE. *Aggregate NF expenditures and value of consumed non-food from gifts/assistance. COMPUTE HHExpNF_1M=SUM(HHExpNFTotal_Purch_MN_1M, HHExpNFTotal_GiftAid_MN_1M). EXECUTE. *-------------------------------------------------------------------------------* *4.Compute FES *-------------------------------------------------------------------------------* COMPUTE FES= HHExpF_1M /SUM(HHExpF_1M , HHExpNF_1M). EXECUTE. VARIABLE LABELS FES 'Household food expenditure share'. EXECUTE. RECODE FES (Lowest thru .4999999=1) (.50 thru .64999999=2) (.65 thru .74999999=3) (.75 thru Highest=4) into Foodexp_4pt. EXECUTE. Value labels Foodexp_4pt 1 '<50%' 2 '50-65%' 3 '65-75%' 4' > 75%'. Variable labels Foodexp_4pt 'Food expenditure share categories'. EXECUTE. FREQUENCIES Foodexp_4pt.
7697025de6389dcec8bfd6fad375afc843145766f33b9a31771299f6818bac34
keera-studios/haskellifi-trayicon
ProtectedModel.hs
-- | Copyright : ( C ) trading as Keera Studios , 2012 -- License : BSD3 Maintainer : module Model.ProtectedModel ( ProtectedModel , onEvent , waitFor , module Exported ) where import Model.ProtectedModel.ProtectedModelInternals import Model.ReactiveModel.ModelEvents as Exported import Model.ProtectedModel.Initialisation as Exported import Model.ProtectedModel.WifiList as Exported
null
https://raw.githubusercontent.com/keera-studios/haskellifi-trayicon/d148387bb362f7cdc959c2a07e981675b7e6bc29/src/Model/ProtectedModel.hs
haskell
| License : BSD3
Copyright : ( C ) trading as Keera Studios , 2012 Maintainer : module Model.ProtectedModel ( ProtectedModel , onEvent , waitFor , module Exported ) where import Model.ProtectedModel.ProtectedModelInternals import Model.ReactiveModel.ModelEvents as Exported import Model.ProtectedModel.Initialisation as Exported import Model.ProtectedModel.WifiList as Exported
a4276dfd78859601b0cfd69411ce7d3bc674e69a13f2ea365817420667a66cc2
iburzynski/EMURGO_71
HOF-SOLUTION.hs
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} {-# HLINT ignore "Avoid lambda" #-} # HLINT ignore " Eta reduce " # {-# HLINT ignore "Use map" #-} {-# HLINT ignore "Use or" #-} {-# HLINT ignore "Use sum" #-} {-# HLINT ignore "Use product" #-} {-# HLINT ignore "Use foldr" #-} {-# HLINT ignore "Use and" #-} import Data.List (foldl') ---------------------------------------------------------------------------------------------------- -- *** HOMEWORK: Higher-Order Functions *** ---------------------------------------------------------------------------------------------------- -- *** Part I: Map/Filter *** -- Implement your own versions of the `map` and `filter` functions using primitive recursion. myMap :: (a -> b) -> [a] -> [b] myMap _ [] = [] myMap f (x : xs) = f x : myMap f xs myFilter :: (a -> Bool) -> [a] -> [a] myFilter _ [] = [] myFilter p (x : xs) | p x = x : myFilter p xs | otherwise = myFilter p xs * * * Part II : Folds * * * -- Implement the following built-in functions using folds. -- For each solution, think carefully about the following: 1 . Which type of fold should be used ? -- * Use `foldr` whenever possible * If a left fold is needed , use the strict version ` foldl ' ` ( imported from Data . List module ) 2 . Which binary function should be used for the reducer ? -- * Is there a built-in operator or function you can use? -- * If not, write your own using a lambda expression -- * Be mindful of parameter order! 3 . What is the initial ( identity ) value ? mySum :: Num a => [a] -> a mySum xs = foldr (+) 0 xs -- Point-free version: mySum = foldr ( + ) 0 myProduct :: Num a => [a] -> a myProduct xs = foldr (*) 1 xs -- For the following boolean functions, remember the built-in logical operators (||) and (&&): -- and [True, False, True] == False -- and [True, True, True] == True -- or [True, False, True] == True -- or [False, False, False] == False Fold Arguments 1 . Binary function ( reducer ) 2 . Initial ( identity ) value 3 . Collection ( foldable ) myAnd :: [Bool] -> Bool -- -19.6/base-4.15.1.0/Prelude.html#v:and myAnd bs = foldr (&&) True bs myOr :: [Bool] -> Bool -19.6/base-4.15.1.0/Prelude.html#v:or myOr = foldr (||) False myElem :: Eq a => a -> [a] -> Bool myElem q xs = foldr (\x acc -> acc || q == x) False xs The next 3 functions take a predicate ( function returning a ) as their first parameter myAny :: (a -> Bool) -> [a] -> Bool -- -19.6/base-4.15.1.0/Prelude.html#v:any myAny p xs = foldr (\x acc -> acc || p x) False xs myAll :: (a -> Bool) -> [a] -> Bool -- -19.6/base-4.15.1.0/Prelude.html#v:all myAll p xs = foldr (\x acc -> acc && p x) True xs myFilter' :: (a -> Bool) -> [a] -> [a] myFilter' p xs = foldr (\x acc -> if p x then x : acc else acc) [] xs myMap' :: (a -> b) -> [a] -> [b] myMap' f xs = foldr (\x acc -> f x : acc) [] xs -- Implement `reverse` using `foldr`. myReverseR :: [a] -> [a] myReverseR xs = foldr (\x acc -> acc ++ [x]) [] xs -- Implement `reverse` using `foldl'`. -- For a challenge, you can try using the `flip` function: flip :: (a -> b -> c) -> (b -> a -> c) -19.6/base-4.15.1.0/Prelude.html#v:flip myReverseL :: [a] -> [a] myReverseL xs = foldl' (\acc x -> x : acc) [] xs myReverseL' xs = foldl' (flip (:)) [] xs The next two functions are partial functions : they return an error when called on an empty list . -- Implement the non-empty patterns using folds: -- Hint: for the initial/identity value, use the head of the list and fold over the tail. myMaximum :: Ord a => [a] -> a ---19.6/base-4.15.1.0/Prelude.html#v:maximum myMaximum [] = error "empty list" myMaximum (x:xs) = foldr max x xs myMinimum :: Ord a => [a] -> a ---19.6/base-4.15.1.0/Prelude.html#v:minimum myMinimum [] = error "empty list" myMinimum (x:xs) = foldr min x xs
null
https://raw.githubusercontent.com/iburzynski/EMURGO_71/c529f1a5c717b7b8ff59bcff72d94f8198eeab89/HW_07-23/HOF-SOLUTION.hs
haskell
# OPTIONS_GHC -Wno-unrecognised-pragmas # # HLINT ignore "Avoid lambda" # # HLINT ignore "Use map" # # HLINT ignore "Use or" # # HLINT ignore "Use sum" # # HLINT ignore "Use product" # # HLINT ignore "Use foldr" # # HLINT ignore "Use and" # -------------------------------------------------------------------------------------------------- *** HOMEWORK: Higher-Order Functions *** -------------------------------------------------------------------------------------------------- *** Part I: Map/Filter *** Implement your own versions of the `map` and `filter` functions using primitive recursion. Implement the following built-in functions using folds. For each solution, think carefully about the following: * Use `foldr` whenever possible * Is there a built-in operator or function you can use? * If not, write your own using a lambda expression * Be mindful of parameter order! Point-free version: For the following boolean functions, remember the built-in logical operators (||) and (&&): and [True, False, True] == False and [True, True, True] == True or [True, False, True] == True or [False, False, False] == False -19.6/base-4.15.1.0/Prelude.html#v:and -19.6/base-4.15.1.0/Prelude.html#v:any -19.6/base-4.15.1.0/Prelude.html#v:all Implement `reverse` using `foldr`. Implement `reverse` using `foldl'`. For a challenge, you can try using the `flip` function: flip :: (a -> b -> c) -> (b -> a -> c) Implement the non-empty patterns using folds: Hint: for the initial/identity value, use the head of the list and fold over the tail. -19.6/base-4.15.1.0/Prelude.html#v:maximum -19.6/base-4.15.1.0/Prelude.html#v:minimum
# HLINT ignore " Eta reduce " # import Data.List (foldl') myMap :: (a -> b) -> [a] -> [b] myMap _ [] = [] myMap f (x : xs) = f x : myMap f xs myFilter :: (a -> Bool) -> [a] -> [a] myFilter _ [] = [] myFilter p (x : xs) | p x = x : myFilter p xs | otherwise = myFilter p xs * * * Part II : Folds * * * 1 . Which type of fold should be used ? * If a left fold is needed , use the strict version ` foldl ' ` ( imported from Data . List module ) 2 . Which binary function should be used for the reducer ? 3 . What is the initial ( identity ) value ? mySum :: Num a => [a] -> a mySum xs = foldr (+) 0 xs mySum = foldr ( + ) 0 myProduct :: Num a => [a] -> a myProduct xs = foldr (*) 1 xs Fold Arguments 1 . Binary function ( reducer ) 2 . Initial ( identity ) value 3 . Collection ( foldable ) myAnd :: [Bool] -> Bool myAnd bs = foldr (&&) True bs myOr :: [Bool] -> Bool -19.6/base-4.15.1.0/Prelude.html#v:or myOr = foldr (||) False myElem :: Eq a => a -> [a] -> Bool myElem q xs = foldr (\x acc -> acc || q == x) False xs The next 3 functions take a predicate ( function returning a ) as their first parameter myAny :: (a -> Bool) -> [a] -> Bool myAny p xs = foldr (\x acc -> acc || p x) False xs myAll :: (a -> Bool) -> [a] -> Bool myAll p xs = foldr (\x acc -> acc && p x) True xs myFilter' :: (a -> Bool) -> [a] -> [a] myFilter' p xs = foldr (\x acc -> if p x then x : acc else acc) [] xs myMap' :: (a -> b) -> [a] -> [b] myMap' f xs = foldr (\x acc -> f x : acc) [] xs myReverseR :: [a] -> [a] myReverseR xs = foldr (\x acc -> acc ++ [x]) [] xs -19.6/base-4.15.1.0/Prelude.html#v:flip myReverseL :: [a] -> [a] myReverseL xs = foldl' (\acc x -> x : acc) [] xs myReverseL' xs = foldl' (flip (:)) [] xs The next two functions are partial functions : they return an error when called on an empty list . myMaximum :: Ord a => [a] -> a myMaximum [] = error "empty list" myMaximum (x:xs) = foldr max x xs myMinimum :: Ord a => [a] -> a myMinimum [] = error "empty list" myMinimum (x:xs) = foldr min x xs
11607ee754848e0e1a43181d334edf351d3f1458828f4548601b178b55260e6d
gvannest/piscine_OCaml
avl.ml
type 'a tree = Nil | Node of 'a * 'a tree * 'a tree (* ********************* previous exercise 03 ***************************** *) let is_bst (tree:int tree) = let rec is_bst_left (tree_left:'a tree) maxValue (min:'a tree) (max:'a tree) = match tree_left with | Nil -> true | Node(v, l, r) when v > maxValue -> false | Node(v, l, r) -> match min with | Node(minValue, _, _) when v < minValue -> false | _ -> (is_bst_left l v min tree_left) && (is_bst_right r v tree_left max) and is_bst_right (tree_right:'a tree) minValue (min:'a tree) (max:'a tree) = match tree_right with | Nil -> true | Node(v, l, r) when v < minValue -> false | Node(v, l, r) -> match max with | Node(maxValue, _, _) when v > maxValue -> false | _ -> (is_bst_left l v min tree_right) && (is_bst_right r v tree_right max) in match tree with | Nil -> true | Node(v, l, r) -> (is_bst_left l v Nil tree) && (is_bst_right r v tree Nil) let rec search_bst value (bst:'a tree) = match bst with | Nil -> false | Node(v, l, r) -> if value = v then true else begin if value > v then (search_bst value r) else (search_bst value l) end let max a b = if a < b then b else a let abs a = if a < 0 then (-a) else a let rec height (node:'a tree) = match node with | Nil -> 0 | Node(_, l, r) -> 1 + (max (height l) (height r)) let is_balanced (tree:'a tree) = if (is_bst tree) = false then false else begin let rec is_balanced_loop (node:'a tree) = match node with | Nil -> true | Node(_, l, r) -> if (is_balanced_loop l = false) || (is_balanced_loop r = false) then false else begin let height_left = height l in let height_right = height r in if abs (height_left - height_right) > 1 then false else true end in is_balanced_loop tree end let add_bst (value:'a) (tree:'a tree) = if (search_bst value tree) then tree else begin let rec add_bst_aux (current_node:'a tree) = match current_node with | Nil -> Node(value, Nil, Nil) | Node(v, l, r) -> if value < v then Node(v, (add_bst_aux l), r) else Node(v, l, (add_bst_aux r)) in add_bst_aux tree end let delete_bst (value:'a) (tree:'a tree) = if not (search_bst value tree) then tree else begin let rec minValue node = match node with | Node(v, Nil, r) -> v | Node(v, l, r) -> minValue l | Nil -> failwith "Error : function minValue should not be called on empty tree" in let rec delete_bst_aux valueToDelete (current_node:'a tree) = match current_node with | Nil -> current_node | Node(v, l, r) when valueToDelete < v -> Node(v, delete_bst_aux valueToDelete l, r) | Node(v, l, r) when valueToDelete > v -> Node(v, l, delete_bst_aux valueToDelete r) | Node(v, l, r) when v == valueToDelete -> begin if (height current_node) = 1 then Nil else if l = Nil then r else if r = Nil then l else let min = minValue r in Node(min, l, delete_bst_aux min r) end | _ -> failwith "Error in patttern matching delete_bst" in delete_bst_aux value tree end * * * * * * * * * * * * * * * * * * * * * * * * * * * * exercise 04 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * let right_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, Nil, r) -> tree | Node(v, Node(vl, ll, lr), r) -> Node(vl, ll, Node(v, lr, r)) let left_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, l, Nil) -> tree | Node(v, l, Node(vr, rl, rr)) -> Node(vr, Node(v, l, rl), rr) let left_right_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, l, r) -> let new_right = right_rotate r in left_rotate (Node(v, l, new_right)) let right_left_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, l, r) -> let new_left = left_rotate l in right_rotate (Node(v, new_left, r)) let rotate_node node = match node with | Node(v, l, r) when height l > height r -> match l with | Node(vl, ll, lr) when height lr > height ll -> right_left_rotate node | _ -> right_rotate node | Node(v, l, r) when height r > height l -> match r with | Node(vr, rl, rr) when height rl > height rr -> left_right_rotate node | _ -> left_rotate node | _ -> failwith "Error in rotate_node : Node is Nil or balanced" let insert_avl value (avl:'a tree) = if not(is_balanced avl) then failwith "Error: the tree passed as avl to insert_avl is not balanced" else begin let newTree = add_bst value avl in if is_balanced newTree then newTree else begin let rec balancing_tree current_node = match current_node with | Node(v, l, r) when v < value -> let tree_right = balancing_tree r in if not(is_balanced tree_right) then Node(v, l, rotate_node tree_right) else Node(v, l, tree_right) | Node(v, l, r) when v > value -> let tree_left = balancing_tree l in if not(is_balanced tree_left) then Node(v, rotate_node tree_left, r) else Node(v, tree_left, r) | Node(v, l, r) when v = value -> current_node | _ -> failwith "Error in balancing tree : no match in pattern matching" in balancing_tree newTree end end let delete_avl value (avl:'a tree) = if not(is_balanced avl) then failwith "Error: the tree passed as avl to insert_avl is not balanced" else begin let newTree = delete_bst value avl in if is_balanced newTree then newTree else begin let rec balancing_tree current_node = match current_node with | Node(v, l, r) when v < value -> let tree_right = balancing_tree r in if not(is_balanced tree_right) then Node(v, l, rotate_node tree_right) else Node(v, l, tree_right) | Node(v, l, r) when v > value -> let tree_left = balancing_tree l in if not(is_balanced tree_left) then Node(v, rotate_node tree_left, r) else Node(v, tree_left, r) | Node(v, Nil, Nil) -> current_node | _ -> failwith "Error in balancing tree : no match in pattern matching" in balancing_tree newTree end end (* ******************** To print tree ************** *) let draw_tree (tree:'a tree) = let draw_square x y size = if size > 0 then begin Graphics.moveto (x - size/2) (y - size/2) ; Graphics.lineto (x - size/2) (y + size/2) ; Graphics.lineto (x + size/2) (y + size/2) ; Graphics.lineto (x + size/2) (y - size/2) ; Graphics.lineto (x - size/2) (y - size/2) ; end in let height = height tree in let rec draw_tree_aux current_node x y size factor = match current_node with | Node (v, l, r) -> begin draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5); Graphics.draw_string (string_of_int v) ; draw_tree_aux l (x - size * factor) (y - (size * 3)) size (factor - 1) ; Graphics.moveto x (y - size/2) ; Graphics.lineto (x - size * factor) (y - (size * 3- size / 2)) ; draw_tree_aux r (x + size * factor) (y - (size * 3)) size (factor - 1); Graphics.moveto x (y - size/2) ; Graphics.lineto (x + size * factor) (y - (size * 3 - size / 2)) end | Nil -> begin draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5) ; Graphics.draw_string "Nil" end in draw_tree_aux tree 900 1200 50 (height + 2) (* ************************* *************** *********************************** *) let main ()= let tree = Node(10, Node(5,Nil,Nil), Node(12,Nil,Nil)) in let tree1 = Node(10, Node(5 ,Node(2 ,Nil ,Nil) ,Node(6 ,Nil ,Nil)), Node(12 ,Node(11 ,Nil ,Nil) ,Node(14 ,Nil ,Nil))) in let tree2 = Node(10, Node(5 ,Node(2 ,Nil ,Nil) ,Node(8 ,Node(6 ,Nil ,Nil) ,Nil)), Node(16 ,Node(13 ,Node(11 ,Nil ,Nil) ,Node(14 ,Nil ,Nil)) ,Node(18 ,Nil ,Nil))) in (* ******************** insertion in avl ********************** *) Graphics.open_graph " 2048x2048" ; draw_tree tree2 ; ignore(Graphics.read_key ()) ; let tree27 = insert_avl 7 tree2 in Graphics.open_graph " 2048x2048" ; draw_tree tree27 ; ignore(Graphics.read_key ()) ; let tree2715 = insert_avl 15 tree27 in Graphics.open_graph " 2048x2048" ; draw_tree tree2715 ; ignore(Graphics.read_key ()) ; let tree2715_14 = delete_avl 14 tree2715 in Graphics.open_graph " 2048x2048" ; draw_tree tree2715_14 ; ignore(Graphics.read_key ()) (* ******************** unit tests right_rotate ********************** *) Graphics.open_graph " 2048x2048 " ; draw_tree tree ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( right_rotate tree ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( right_rotate tree1 ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( right_rotate tree2 ) ; ignore(Graphics.read_key ( ) ) ; draw_tree tree ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (right_rotate tree) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree1 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (right_rotate tree1) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree2 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (right_rotate tree2) ; ignore(Graphics.read_key ()) ; *) (* ******************** unit tests left_rotate ********************** *) Graphics.open_graph " 2048x2048 " ; draw_tree tree ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( left_rotate tree ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( left_rotate tree1 ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( left_rotate tree2 ) ; ignore(Graphics.read_key ( ) ) draw_tree tree ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (left_rotate tree) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree1 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (left_rotate tree1) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree2 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (left_rotate tree2) ; ignore(Graphics.read_key ()) *) let () = main ()
null
https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d03/ex04/avl.ml
ocaml
********************* previous exercise 03 ***************************** ******************** To print tree ************** ************************* *************** *********************************** ******************** insertion in avl ********************** ******************** unit tests right_rotate ********************** ******************** unit tests left_rotate **********************
type 'a tree = Nil | Node of 'a * 'a tree * 'a tree let is_bst (tree:int tree) = let rec is_bst_left (tree_left:'a tree) maxValue (min:'a tree) (max:'a tree) = match tree_left with | Nil -> true | Node(v, l, r) when v > maxValue -> false | Node(v, l, r) -> match min with | Node(minValue, _, _) when v < minValue -> false | _ -> (is_bst_left l v min tree_left) && (is_bst_right r v tree_left max) and is_bst_right (tree_right:'a tree) minValue (min:'a tree) (max:'a tree) = match tree_right with | Nil -> true | Node(v, l, r) when v < minValue -> false | Node(v, l, r) -> match max with | Node(maxValue, _, _) when v > maxValue -> false | _ -> (is_bst_left l v min tree_right) && (is_bst_right r v tree_right max) in match tree with | Nil -> true | Node(v, l, r) -> (is_bst_left l v Nil tree) && (is_bst_right r v tree Nil) let rec search_bst value (bst:'a tree) = match bst with | Nil -> false | Node(v, l, r) -> if value = v then true else begin if value > v then (search_bst value r) else (search_bst value l) end let max a b = if a < b then b else a let abs a = if a < 0 then (-a) else a let rec height (node:'a tree) = match node with | Nil -> 0 | Node(_, l, r) -> 1 + (max (height l) (height r)) let is_balanced (tree:'a tree) = if (is_bst tree) = false then false else begin let rec is_balanced_loop (node:'a tree) = match node with | Nil -> true | Node(_, l, r) -> if (is_balanced_loop l = false) || (is_balanced_loop r = false) then false else begin let height_left = height l in let height_right = height r in if abs (height_left - height_right) > 1 then false else true end in is_balanced_loop tree end let add_bst (value:'a) (tree:'a tree) = if (search_bst value tree) then tree else begin let rec add_bst_aux (current_node:'a tree) = match current_node with | Nil -> Node(value, Nil, Nil) | Node(v, l, r) -> if value < v then Node(v, (add_bst_aux l), r) else Node(v, l, (add_bst_aux r)) in add_bst_aux tree end let delete_bst (value:'a) (tree:'a tree) = if not (search_bst value tree) then tree else begin let rec minValue node = match node with | Node(v, Nil, r) -> v | Node(v, l, r) -> minValue l | Nil -> failwith "Error : function minValue should not be called on empty tree" in let rec delete_bst_aux valueToDelete (current_node:'a tree) = match current_node with | Nil -> current_node | Node(v, l, r) when valueToDelete < v -> Node(v, delete_bst_aux valueToDelete l, r) | Node(v, l, r) when valueToDelete > v -> Node(v, l, delete_bst_aux valueToDelete r) | Node(v, l, r) when v == valueToDelete -> begin if (height current_node) = 1 then Nil else if l = Nil then r else if r = Nil then l else let min = minValue r in Node(min, l, delete_bst_aux min r) end | _ -> failwith "Error in patttern matching delete_bst" in delete_bst_aux value tree end * * * * * * * * * * * * * * * * * * * * * * * * * * * * exercise 04 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * let right_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, Nil, r) -> tree | Node(v, Node(vl, ll, lr), r) -> Node(vl, ll, Node(v, lr, r)) let left_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, l, Nil) -> tree | Node(v, l, Node(vr, rl, rr)) -> Node(vr, Node(v, l, rl), rr) let left_right_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, l, r) -> let new_right = right_rotate r in left_rotate (Node(v, l, new_right)) let right_left_rotate (tree:'a tree) = match tree with | Nil -> tree | Node(v, l, r) -> let new_left = left_rotate l in right_rotate (Node(v, new_left, r)) let rotate_node node = match node with | Node(v, l, r) when height l > height r -> match l with | Node(vl, ll, lr) when height lr > height ll -> right_left_rotate node | _ -> right_rotate node | Node(v, l, r) when height r > height l -> match r with | Node(vr, rl, rr) when height rl > height rr -> left_right_rotate node | _ -> left_rotate node | _ -> failwith "Error in rotate_node : Node is Nil or balanced" let insert_avl value (avl:'a tree) = if not(is_balanced avl) then failwith "Error: the tree passed as avl to insert_avl is not balanced" else begin let newTree = add_bst value avl in if is_balanced newTree then newTree else begin let rec balancing_tree current_node = match current_node with | Node(v, l, r) when v < value -> let tree_right = balancing_tree r in if not(is_balanced tree_right) then Node(v, l, rotate_node tree_right) else Node(v, l, tree_right) | Node(v, l, r) when v > value -> let tree_left = balancing_tree l in if not(is_balanced tree_left) then Node(v, rotate_node tree_left, r) else Node(v, tree_left, r) | Node(v, l, r) when v = value -> current_node | _ -> failwith "Error in balancing tree : no match in pattern matching" in balancing_tree newTree end end let delete_avl value (avl:'a tree) = if not(is_balanced avl) then failwith "Error: the tree passed as avl to insert_avl is not balanced" else begin let newTree = delete_bst value avl in if is_balanced newTree then newTree else begin let rec balancing_tree current_node = match current_node with | Node(v, l, r) when v < value -> let tree_right = balancing_tree r in if not(is_balanced tree_right) then Node(v, l, rotate_node tree_right) else Node(v, l, tree_right) | Node(v, l, r) when v > value -> let tree_left = balancing_tree l in if not(is_balanced tree_left) then Node(v, rotate_node tree_left, r) else Node(v, tree_left, r) | Node(v, Nil, Nil) -> current_node | _ -> failwith "Error in balancing tree : no match in pattern matching" in balancing_tree newTree end end let draw_tree (tree:'a tree) = let draw_square x y size = if size > 0 then begin Graphics.moveto (x - size/2) (y - size/2) ; Graphics.lineto (x - size/2) (y + size/2) ; Graphics.lineto (x + size/2) (y + size/2) ; Graphics.lineto (x + size/2) (y - size/2) ; Graphics.lineto (x - size/2) (y - size/2) ; end in let height = height tree in let rec draw_tree_aux current_node x y size factor = match current_node with | Node (v, l, r) -> begin draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5); Graphics.draw_string (string_of_int v) ; draw_tree_aux l (x - size * factor) (y - (size * 3)) size (factor - 1) ; Graphics.moveto x (y - size/2) ; Graphics.lineto (x - size * factor) (y - (size * 3- size / 2)) ; draw_tree_aux r (x + size * factor) (y - (size * 3)) size (factor - 1); Graphics.moveto x (y - size/2) ; Graphics.lineto (x + size * factor) (y - (size * 3 - size / 2)) end | Nil -> begin draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5) ; Graphics.draw_string "Nil" end in draw_tree_aux tree 900 1200 50 (height + 2) let main ()= let tree = Node(10, Node(5,Nil,Nil), Node(12,Nil,Nil)) in let tree1 = Node(10, Node(5 ,Node(2 ,Nil ,Nil) ,Node(6 ,Nil ,Nil)), Node(12 ,Node(11 ,Nil ,Nil) ,Node(14 ,Nil ,Nil))) in let tree2 = Node(10, Node(5 ,Node(2 ,Nil ,Nil) ,Node(8 ,Node(6 ,Nil ,Nil) ,Nil)), Node(16 ,Node(13 ,Node(11 ,Nil ,Nil) ,Node(14 ,Nil ,Nil)) ,Node(18 ,Nil ,Nil))) in Graphics.open_graph " 2048x2048" ; draw_tree tree2 ; ignore(Graphics.read_key ()) ; let tree27 = insert_avl 7 tree2 in Graphics.open_graph " 2048x2048" ; draw_tree tree27 ; ignore(Graphics.read_key ()) ; let tree2715 = insert_avl 15 tree27 in Graphics.open_graph " 2048x2048" ; draw_tree tree2715 ; ignore(Graphics.read_key ()) ; let tree2715_14 = delete_avl 14 tree2715 in Graphics.open_graph " 2048x2048" ; draw_tree tree2715_14 ; ignore(Graphics.read_key ()) Graphics.open_graph " 2048x2048 " ; draw_tree tree ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( right_rotate tree ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( right_rotate tree1 ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( right_rotate tree2 ) ; ignore(Graphics.read_key ( ) ) ; draw_tree tree ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (right_rotate tree) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree1 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (right_rotate tree1) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree2 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (right_rotate tree2) ; ignore(Graphics.read_key ()) ; *) Graphics.open_graph " 2048x2048 " ; draw_tree tree ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( left_rotate tree ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( left_rotate tree1 ) ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; ; ignore(Graphics.read_key ( ) ) ; Graphics.open_graph " 2048x2048 " ; draw_tree ( left_rotate tree2 ) ; ignore(Graphics.read_key ( ) ) draw_tree tree ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (left_rotate tree) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree1 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (left_rotate tree1) ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree tree2 ; ignore(Graphics.read_key ()) ; Graphics.open_graph " 2048x2048" ; draw_tree (left_rotate tree2) ; ignore(Graphics.read_key ()) *) let () = main ()
a4027b851a568584c4b0b9b99beae2f5ed3f8a9ced1645c02fcbf298e45f80b2
kahua/Kahua
kahua-shell.scm
-*- mode : scheme ; coding : utf-8 -*- ;; Interactive shell script ;; Copyright ( c ) 2003 - 2007 Scheme Arts , L.L.C. , All rights reserved . Copyright ( c ) 2003 - 2007 Time Intermedia Corporation , All rights reserved . ;; See COPYING for terms and conditions of using this software ;; (use srfi-1) (use gauche.net) (use gauche.parseopt) (use util.list) (use kahua) (use gauche.process) (use gauche.termios) (use kahua.developer) ;; Deal with login ----------------------------------- (define (login-processor) (guard (e (else (print "ERROR: " (ref e 'message)) login-processor)) (display "Welcome to Kahua.") (newline) (let* ((user-mode (ref (kahua-config) 'user-mode)) (username (or user-mode (begin (format #t "username: ") (flush) (read-line)))) (password (if (sys-getenv "TERM") (get-password "password: ") (begin (format #t "password: ") (flush) (read-line))))) (cond ((find eof-object? (list username password)) (exit 0)) ((kahua-check-developer username password) select-worker-processor) (else (newline) (display "Permission denied.") (newline) (exit 0)))))) ;; Deal with select workers ------------------------------------ (define (show-workers) (define (show-time time) (sys-strftime "%b %e %H:%M" (sys-localtime time))) (let ((workers (send-command #f '(ls)))) (format #t "wno type since wid\n") (dolist (w workers) (format #t "~3d ~12a ~10a ~a\n" (get-keyword :worker-count w) (get-keyword :worker-type w) (show-time (get-keyword :start-time w)) (get-keyword :worker-id w))))) (define (select-worker-processor) (guard (e (else (let1 errmsg (ref e 'message) (print "ERROR: " errmsg) (if (#/connect failed to/ errmsg) (exit 70) select-worker-processor)))) (show-workers) (format #t "select wno> ") (flush) (let1 line (read-line) (if (eof-object? line) (exit 0) (let1 cmd (call-with-input-string line port->sexp-list) (if (null? cmd) select-worker-processor (connect-worker (car cmd)))))))) ;; Deal with worker command ------------------------------------ (define (connect-worker wno) (let* ((workers (send-command #f '(ls))) (the-worker (find (lambda (w) (eqv? (get-keyword :worker-count w) wno)) workers))) (newline) (if the-worker (make-worker-command-processor (get-keyword :worker-type the-worker) (get-keyword :worker-id the-worker)) (begin (format #t "No such worker: ~a\n" wno) select-worker-processor)))) (define (make-worker-command-processor type wid) (rec (worker-processor) (guard (e (else (display (ref e 'message)) (flush) worker-processor)) (format #t "~a(~a)> " type wid) (flush) (let1 expr (read) (cond ((eof-object? expr) (exit 0)) ((memq expr '(disconnect bye)) (read-line) select-worker-processor) (else NB : the first two elts of reply is error - output and std - output (let1 reply (send-command wid `(eval ',expr kahua-app-server)) (display (car reply)) (display (cadr reply)) (for-each (lambda (r) (display r) (newline)) (cddr reply)) worker-processor)))) ))) ;; Utility ----------------------------------------------------- (define (send-command wid cmd) (let ((sockaddr (worker-id->sockaddr wid (kahua-sockbase)))) (call-with-client-socket (make-client-socket sockaddr) (lambda (in out) (if wid (write '(("x-kahua-eval" "#t")) out) (write '(("x-kahua-worker" "spvr")) out)) (newline out) (write cmd out) (newline out) (flush out) ;; special treatment of 'shutdown'-command: we won't get ;; reply from that command. (if (and (not wid) (eq? (car cmd) 'shutdown)) '() (let* ((header (read in)) (body (read in))) (if (equal? (assoc-ref header "x-kahua-status") '("OK")) body (errorf "~a" body)))))))) (define (get-password prompt) (let* ((port (current-input-port)) (attr (sys-tcgetattr port)) (lflag (slot-ref attr 'lflag))) ;; Show prompt (display prompt) (flush) ;; Turn off echo during reading. (dynamic-wind (lambda () (slot-set! attr 'lflag (logand lflag (lognot (logior ECHO ECHOE ECHOK ECHONL)))) (sys-tcsetattr port TCSAFLUSH attr)) (lambda () (read-line port)) (lambda () (slot-set! attr 'lflag lflag) (sys-tcsetattr port TCSANOW attr) (display "\n"))))) ;; Entry ------------------------------------------------------- (define (main args) (let-args (cdr args) ((site "S=s") (conf-file "c=s") (gosh "gosh=s")) ;; wrapper script adds this. ignore. (set-signal-handler! SIGINT (lambda _ (exit 0))) (set-signal-handler! SIGHUP (lambda _ (exit 0))) (set-signal-handler! SIGTERM (lambda _ (exit 0))) (kahua-common-init site conf-file) (let loop ((command-processor login-processor)) (loop (command-processor))))) ;; Local variables: ;; mode: scheme ;; end:
null
https://raw.githubusercontent.com/kahua/Kahua/18e28cd307e733ce281e74b2d574cbfc60a5d390/src/kahua-shell.scm
scheme
coding : utf-8 -*- Interactive shell script See COPYING for terms and conditions of using this software Deal with login ----------------------------------- Deal with select workers ------------------------------------ Deal with worker command ------------------------------------ Utility ----------------------------------------------------- special treatment of 'shutdown'-command: we won't get reply from that command. Show prompt Turn off echo during reading. Entry ------------------------------------------------------- wrapper script adds this. ignore. Local variables: mode: scheme end:
Copyright ( c ) 2003 - 2007 Scheme Arts , L.L.C. , All rights reserved . Copyright ( c ) 2003 - 2007 Time Intermedia Corporation , All rights reserved . (use srfi-1) (use gauche.net) (use gauche.parseopt) (use util.list) (use kahua) (use gauche.process) (use gauche.termios) (use kahua.developer) (define (login-processor) (guard (e (else (print "ERROR: " (ref e 'message)) login-processor)) (display "Welcome to Kahua.") (newline) (let* ((user-mode (ref (kahua-config) 'user-mode)) (username (or user-mode (begin (format #t "username: ") (flush) (read-line)))) (password (if (sys-getenv "TERM") (get-password "password: ") (begin (format #t "password: ") (flush) (read-line))))) (cond ((find eof-object? (list username password)) (exit 0)) ((kahua-check-developer username password) select-worker-processor) (else (newline) (display "Permission denied.") (newline) (exit 0)))))) (define (show-workers) (define (show-time time) (sys-strftime "%b %e %H:%M" (sys-localtime time))) (let ((workers (send-command #f '(ls)))) (format #t "wno type since wid\n") (dolist (w workers) (format #t "~3d ~12a ~10a ~a\n" (get-keyword :worker-count w) (get-keyword :worker-type w) (show-time (get-keyword :start-time w)) (get-keyword :worker-id w))))) (define (select-worker-processor) (guard (e (else (let1 errmsg (ref e 'message) (print "ERROR: " errmsg) (if (#/connect failed to/ errmsg) (exit 70) select-worker-processor)))) (show-workers) (format #t "select wno> ") (flush) (let1 line (read-line) (if (eof-object? line) (exit 0) (let1 cmd (call-with-input-string line port->sexp-list) (if (null? cmd) select-worker-processor (connect-worker (car cmd)))))))) (define (connect-worker wno) (let* ((workers (send-command #f '(ls))) (the-worker (find (lambda (w) (eqv? (get-keyword :worker-count w) wno)) workers))) (newline) (if the-worker (make-worker-command-processor (get-keyword :worker-type the-worker) (get-keyword :worker-id the-worker)) (begin (format #t "No such worker: ~a\n" wno) select-worker-processor)))) (define (make-worker-command-processor type wid) (rec (worker-processor) (guard (e (else (display (ref e 'message)) (flush) worker-processor)) (format #t "~a(~a)> " type wid) (flush) (let1 expr (read) (cond ((eof-object? expr) (exit 0)) ((memq expr '(disconnect bye)) (read-line) select-worker-processor) (else NB : the first two elts of reply is error - output and std - output (let1 reply (send-command wid `(eval ',expr kahua-app-server)) (display (car reply)) (display (cadr reply)) (for-each (lambda (r) (display r) (newline)) (cddr reply)) worker-processor)))) ))) (define (send-command wid cmd) (let ((sockaddr (worker-id->sockaddr wid (kahua-sockbase)))) (call-with-client-socket (make-client-socket sockaddr) (lambda (in out) (if wid (write '(("x-kahua-eval" "#t")) out) (write '(("x-kahua-worker" "spvr")) out)) (newline out) (write cmd out) (newline out) (flush out) (if (and (not wid) (eq? (car cmd) 'shutdown)) '() (let* ((header (read in)) (body (read in))) (if (equal? (assoc-ref header "x-kahua-status") '("OK")) body (errorf "~a" body)))))))) (define (get-password prompt) (let* ((port (current-input-port)) (attr (sys-tcgetattr port)) (lflag (slot-ref attr 'lflag))) (display prompt) (flush) (dynamic-wind (lambda () (slot-set! attr 'lflag (logand lflag (lognot (logior ECHO ECHOE ECHOK ECHONL)))) (sys-tcsetattr port TCSAFLUSH attr)) (lambda () (read-line port)) (lambda () (slot-set! attr 'lflag lflag) (sys-tcsetattr port TCSANOW attr) (display "\n"))))) (define (main args) (let-args (cdr args) ((site "S=s") (conf-file "c=s") (set-signal-handler! SIGINT (lambda _ (exit 0))) (set-signal-handler! SIGHUP (lambda _ (exit 0))) (set-signal-handler! SIGTERM (lambda _ (exit 0))) (kahua-common-init site conf-file) (let loop ((command-processor login-processor)) (loop (command-processor)))))
d7d424c153ec77dce4992a2c424b35bd99ff02c970076aa1e7cda1bc62d2b535
Opetushallitus/ataru
field_types.cljc
(ns ataru.application.field-types) (def form-fields ["textField" "textArea" "dropdown" "multipleChoice" "singleChoice" "attachment" "hakukohteet"])
null
https://raw.githubusercontent.com/Opetushallitus/ataru/2d8ef1d3f972621e301a3818567d4e11219d2e82/src/cljc/ataru/application/field_types.cljc
clojure
(ns ataru.application.field-types) (def form-fields ["textField" "textArea" "dropdown" "multipleChoice" "singleChoice" "attachment" "hakukohteet"])
a685ec2ba4a854be78d9f7e986be7b15e4407e3c00de05b31de91cbd40e36fc5
jordwalke/rehp
ppx_deriving_json.mli
Js_of_ocaml library * / * Copyright Hugo Heuzard 2019 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright Hugo Heuzard 2019 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val json_of : Ppxlib.Deriving.t val to_json : Ppxlib.Deriving.t val of_json : Ppxlib.Deriving.t val json : Ppxlib.Deriving.t
null
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/ppx/ppx_deriving_json/lib/ppx_deriving_json.mli
ocaml
Js_of_ocaml library * / * Copyright Hugo Heuzard 2019 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright Hugo Heuzard 2019 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val json_of : Ppxlib.Deriving.t val to_json : Ppxlib.Deriving.t val of_json : Ppxlib.Deriving.t val json : Ppxlib.Deriving.t
67d0bcc2aeabaa3c05a42dd25b2a9d52ee45f0a7a1f4239d2f794f44db7adb19
moby/vpnkit
packets.ml
let icmp_echo_request ~id ~seq ~len = let payload = Cstruct.create len in let pattern = "plz reply i'm so lonely" in for i = 0 to Cstruct.length payload - 1 do Cstruct.set_char payload i pattern.[i mod (String.length pattern)] done; let req = Icmpv4_packet.({code = 0x00; ty = Icmpv4_wire.Echo_request; subheader = Id_and_seq (id, seq)}) in let header = Icmpv4_packet.Marshal.make_cstruct req ~payload in Cstruct.concat [ header; payload ]
null
https://raw.githubusercontent.com/moby/vpnkit/6dda85cda59e36875fcc6324205aaf0c7056ff0a/src/hostnet_test/packets.ml
ocaml
let icmp_echo_request ~id ~seq ~len = let payload = Cstruct.create len in let pattern = "plz reply i'm so lonely" in for i = 0 to Cstruct.length payload - 1 do Cstruct.set_char payload i pattern.[i mod (String.length pattern)] done; let req = Icmpv4_packet.({code = 0x00; ty = Icmpv4_wire.Echo_request; subheader = Id_and_seq (id, seq)}) in let header = Icmpv4_packet.Marshal.make_cstruct req ~payload in Cstruct.concat [ header; payload ]
7321beee69d4a9a3ac940fbba98df6b196d7a63255c7f532bfbebf189b3969dc
eerohele/sigel
components.clj
(ns sigel.xslt.components "A set of reusable XSLT components." (:require [sigel.xslt.elements :as xsl]) (:refer-clojure :exclude [identity])) (def identity "An XSLT identity template." (xsl/template {:match "@* | node()"} (xsl/copy (xsl/apply-templates {:select "@* | node()"})))) (defn xslt3-identity "An XSLT 3.0 stylesheet with an identity template and the XML Schema namespace () pre-bound to the `xs` namespace prefix." [& [a & xs]] (xsl/stylesheet (merge {:xmlns/xsl "" :version 3.0 :xmlns:xs "" :exclude-result-prefixes "xs"} a) identity xs)) (def identity-transformation (xslt3-identity nil))
null
https://raw.githubusercontent.com/eerohele/sigel/9c2c8e9526cccf7c3f980ef062ab404175f80da1/src/sigel/xslt/components.clj
clojure
(ns sigel.xslt.components "A set of reusable XSLT components." (:require [sigel.xslt.elements :as xsl]) (:refer-clojure :exclude [identity])) (def identity "An XSLT identity template." (xsl/template {:match "@* | node()"} (xsl/copy (xsl/apply-templates {:select "@* | node()"})))) (defn xslt3-identity "An XSLT 3.0 stylesheet with an identity template and the XML Schema namespace () pre-bound to the `xs` namespace prefix." [& [a & xs]] (xsl/stylesheet (merge {:xmlns/xsl "" :version 3.0 :xmlns:xs "" :exclude-result-prefixes "xs"} a) identity xs)) (def identity-transformation (xslt3-identity nil))
3f831abcbd74037c69e05af99225e3d5cdab4f36638a37d9e30f3c4dda1267bb
thierry-martinez/traverse
traverse_tests.ml
open Traverse let () = let module List = Primitives.List.Make (Applicative.Option (Applicative.Map)) in assert (List.traverse (S O) (fun x -> Some (x + 1)) [1; 2; 3] = Some [2; 3; 4]) let () = let module List = Primitives.List.Make (Applicative.Map) in assert (List.traverse (S (S O)) (fun x y -> x + y) [1; 2; 3] [4; 5; 6]= [5; 7; 9]) let () = let module List = Primitives.List.Make (Applicative.Option (Applicative.Map)) in let flag = ref 0 in assert (List.traverse (S O) (fun f -> if f () then Some () else None) [(fun () -> flag := 1; true); (fun () -> false); (fun () -> flag := 2; true)] = None); assert (!flag = 1)
null
https://raw.githubusercontent.com/thierry-martinez/traverse/9d03cf1e650dc70273b981b1178a16a4929987e6/tests/traverse_tests.ml
ocaml
open Traverse let () = let module List = Primitives.List.Make (Applicative.Option (Applicative.Map)) in assert (List.traverse (S O) (fun x -> Some (x + 1)) [1; 2; 3] = Some [2; 3; 4]) let () = let module List = Primitives.List.Make (Applicative.Map) in assert (List.traverse (S (S O)) (fun x y -> x + y) [1; 2; 3] [4; 5; 6]= [5; 7; 9]) let () = let module List = Primitives.List.Make (Applicative.Option (Applicative.Map)) in let flag = ref 0 in assert (List.traverse (S O) (fun f -> if f () then Some () else None) [(fun () -> flag := 1; true); (fun () -> false); (fun () -> flag := 2; true)] = None); assert (!flag = 1)
6023ed6ce18c5f4c07c5bb7c7f753c83aa07ec0e46bbc6d5695235de0f62154c
flipstone/haskell-for-beginners
2_files_and_streams_a.hs
Note : GHCI disables buffering on stdin , which produces unexpected ( though correct ) results for and -- friends. You can test your answers to the problems below -- by changing main below to be whichever action you'd like to run and using the runhaskell command at the shell prompt : -- -- runhaskell <path to file> -- main = yakkityYak Define an action that uses to read lines from stdin and prints out the number of -- yaks on each line. Verify that your action -- prints out lines as they are typed in. -- yakkityYak :: IO () yakkityYak = do content <- getContents putStr . unlines . map tellYakCount . lines $ content countYaks = length . filter (== "yak") . words tellYakCount line = "There are " ++ show (countYaks line) ++ " yaks" -- Redefine the action above using interact yakkityYak' = interact $ unlines . map tellYakCount . lines Define an action that reads lines from stdin -- and after each line prints the total number of -- characters read thus far. -- letterCount = interact $ unlines . map showTotal . runningTotal . lines where runningTotal = scanl1 (+) . map length showTotal n = show n ++ " characters so far" -- BONUS: Try running these actions from GHCI and explain -- what happens.
null
https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/answers/chapter_09/2_files_and_streams_a.hs
haskell
friends. You can test your answers to the problems below by changing main below to be whichever action you'd like runhaskell <path to file> yaks on each line. Verify that your action prints out lines as they are typed in. Redefine the action above using interact and after each line prints the total number of characters read thus far. BONUS: Try running these actions from GHCI and explain what happens.
Note : GHCI disables buffering on stdin , which produces unexpected ( though correct ) results for and to run and using the runhaskell command at the shell prompt : main = yakkityYak Define an action that uses to read lines from stdin and prints out the number of yakkityYak :: IO () yakkityYak = do content <- getContents putStr . unlines . map tellYakCount . lines $ content countYaks = length . filter (== "yak") . words tellYakCount line = "There are " ++ show (countYaks line) ++ " yaks" yakkityYak' = interact $ unlines . map tellYakCount . lines Define an action that reads lines from stdin letterCount = interact $ unlines . map showTotal . runningTotal . lines where runningTotal = scanl1 (+) . map length showTotal n = show n ++ " characters so far"
73a368442219d214ea71d7004443434d18bb26965a353d9fc6e9284e46d2718f
mainland/language-c-quote
Derive.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # -- | -- Module : Derive Copyright : ( c ) 2015 Drexel University -- License : BSD-style Maintainer : module Derive ( deriveM, deriveLocated, deriveRelocatable ) where import Data.Generics import Data.Loc import Text.PrettyPrint.Mainland as PP deriveM :: (a -> Doc) -> a -> IO () deriveM derive (_ :: a) = do putDoc $ derive (undefined :: a) putStrLn "" deriveLocated :: forall a . (Typeable a, Data a) => a -> Doc deriveLocated _ = nest 2 $ text "instance" <+> text "Located" <+> text (tyConName typeName) <+> text "where" </> stack (map locDef constructors) where (typeName, _) = splitTyConApp (typeOf (undefined::a)) constructors :: [(String, [String], Int)] constructors = map gen $ dataTypeConstrs (dataTypeOf (undefined::a)) where gen :: Constr -> (String, [String], Int) gen con = ( showConstr con , gmapQ (showConstr . toConstr) (fromConstrB empty' con :: a) , gmapQl (+) 0 (const 1) (fromConstrB empty' con :: a) ) locDef :: (String, [String], Int) -> Doc locDef (name, ks, ps) = nest 2 $ text "locOf" <+> wrap pattern <+> text "=" <+/> text rhs where wrap | ps /= 0 = parens | otherwise = id (pats, rhs) = go ks where go :: [String] -> ([String], String) go [] = ([], "noLoc") go ("SrcLoc" : ks') = ("l" : replicate (length ks') "_", "locOf l") go (_ : ks') = ("_" : pats', rhs') where (pats', rhs') = go ks' pattern = spread (text name : map text pats) deriveRelocatable :: forall a . (Typeable a, Data a) => a -> Doc deriveRelocatable _ = nest 2 $ text "instance" <+> text "Relocatable" <+> text (tyConName typeName) <+> text "where" </> stack (map locDef constructors) where (typeName, _) = splitTyConApp (typeOf (undefined::a)) constructors :: [(String, [String], Int)] constructors = map gen $ dataTypeConstrs (dataTypeOf (undefined::a)) where gen :: Constr -> (String, [String], Int) gen con = ( showConstr con , gmapQ (showConstr . toConstr) (fromConstrB empty' con :: a) , gmapQl (+) 0 (const 1) (fromConstrB empty' con :: a) ) locDef :: (String, [String], Int) -> Doc locDef (name, ks, ps) = nest 2 $ text "reloc" <+> (if usedloc then text "l" else text "_") <+> wrap (pattern lhspats) <+> text "=" <+/> wrap (pattern rhspats) where wrap | ps /= 0 = parens | otherwise = id (usedloc, lhspats, rhspats) = go 0 ks where go :: Int -> [String] -> (Bool, [String], [String]) go _ [] = (False, [], []) go i ("SrcLoc" : ks') = (True, "_" : rest, "(fromLoc l)" : rest) where rest = ["x" ++ show j | j <- [i+1..length ks']] go i (_ : ks') = (usedloc', p : lhspats', p : rhspats') where p = "x" ++ show i (usedloc', lhspats', rhspats') = go (i+1) ks' pattern pats = spread (text name : map text pats) empty' :: forall a. Data a => a empty' = Data.Generics.empty `extB` pos `extB` loc `extB` sloc where pos :: Pos pos = Pos "" 1 1 1 loc :: Loc loc = NoLoc sloc :: SrcLoc sloc = SrcLoc NoLoc
null
https://raw.githubusercontent.com/mainland/language-c-quote/c7a1ad5833b5567e7d746f4640624b16d61d2d94/bin/Derive.hs
haskell
# LANGUAGE DeriveDataTypeable # | Module : Derive License : BSD-style
# LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # Copyright : ( c ) 2015 Drexel University Maintainer : module Derive ( deriveM, deriveLocated, deriveRelocatable ) where import Data.Generics import Data.Loc import Text.PrettyPrint.Mainland as PP deriveM :: (a -> Doc) -> a -> IO () deriveM derive (_ :: a) = do putDoc $ derive (undefined :: a) putStrLn "" deriveLocated :: forall a . (Typeable a, Data a) => a -> Doc deriveLocated _ = nest 2 $ text "instance" <+> text "Located" <+> text (tyConName typeName) <+> text "where" </> stack (map locDef constructors) where (typeName, _) = splitTyConApp (typeOf (undefined::a)) constructors :: [(String, [String], Int)] constructors = map gen $ dataTypeConstrs (dataTypeOf (undefined::a)) where gen :: Constr -> (String, [String], Int) gen con = ( showConstr con , gmapQ (showConstr . toConstr) (fromConstrB empty' con :: a) , gmapQl (+) 0 (const 1) (fromConstrB empty' con :: a) ) locDef :: (String, [String], Int) -> Doc locDef (name, ks, ps) = nest 2 $ text "locOf" <+> wrap pattern <+> text "=" <+/> text rhs where wrap | ps /= 0 = parens | otherwise = id (pats, rhs) = go ks where go :: [String] -> ([String], String) go [] = ([], "noLoc") go ("SrcLoc" : ks') = ("l" : replicate (length ks') "_", "locOf l") go (_ : ks') = ("_" : pats', rhs') where (pats', rhs') = go ks' pattern = spread (text name : map text pats) deriveRelocatable :: forall a . (Typeable a, Data a) => a -> Doc deriveRelocatable _ = nest 2 $ text "instance" <+> text "Relocatable" <+> text (tyConName typeName) <+> text "where" </> stack (map locDef constructors) where (typeName, _) = splitTyConApp (typeOf (undefined::a)) constructors :: [(String, [String], Int)] constructors = map gen $ dataTypeConstrs (dataTypeOf (undefined::a)) where gen :: Constr -> (String, [String], Int) gen con = ( showConstr con , gmapQ (showConstr . toConstr) (fromConstrB empty' con :: a) , gmapQl (+) 0 (const 1) (fromConstrB empty' con :: a) ) locDef :: (String, [String], Int) -> Doc locDef (name, ks, ps) = nest 2 $ text "reloc" <+> (if usedloc then text "l" else text "_") <+> wrap (pattern lhspats) <+> text "=" <+/> wrap (pattern rhspats) where wrap | ps /= 0 = parens | otherwise = id (usedloc, lhspats, rhspats) = go 0 ks where go :: Int -> [String] -> (Bool, [String], [String]) go _ [] = (False, [], []) go i ("SrcLoc" : ks') = (True, "_" : rest, "(fromLoc l)" : rest) where rest = ["x" ++ show j | j <- [i+1..length ks']] go i (_ : ks') = (usedloc', p : lhspats', p : rhspats') where p = "x" ++ show i (usedloc', lhspats', rhspats') = go (i+1) ks' pattern pats = spread (text name : map text pats) empty' :: forall a. Data a => a empty' = Data.Generics.empty `extB` pos `extB` loc `extB` sloc where pos :: Pos pos = Pos "" 1 1 1 loc :: Loc loc = NoLoc sloc :: SrcLoc sloc = SrcLoc NoLoc
365b48df4d37d88c587cc4b7df3f686742a4b69662a031f43f2817b9d4751994
zotonic/zotonic
scomp_base_spinner.erl
@author < > 2009 %% @doc Show the spinner element Copyright 2009 %% 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(scomp_base_spinner). -behaviour(zotonic_scomp). -export([vary/2, render/3]). -include_lib("zotonic_core/include/zotonic.hrl"). vary(_Params, _Context) -> nocache. render(Params, _Vars, _Context) -> Image = proplists:get_value(image, Params, <<"/lib/images/spinner.gif">>), {ok, <<"<div id=\"spinner\" class=\"spinner\" style=\"display: none\"><img alt=\"activity indicator\" src=\"">>,Image,<<"\" /></div>">>}.
null
https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_base/src/scomps/scomp_base_spinner.erl
erlang
@doc Show the spinner element 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.
@author < > 2009 Copyright 2009 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(scomp_base_spinner). -behaviour(zotonic_scomp). -export([vary/2, render/3]). -include_lib("zotonic_core/include/zotonic.hrl"). vary(_Params, _Context) -> nocache. render(Params, _Vars, _Context) -> Image = proplists:get_value(image, Params, <<"/lib/images/spinner.gif">>), {ok, <<"<div id=\"spinner\" class=\"spinner\" style=\"display: none\"><img alt=\"activity indicator\" src=\"">>,Image,<<"\" /></div>">>}.
1dccec60e42736a3ffb8fcca2212f84baf57b4672108c0078ac919c970ab9cc2
haskell-trasa/trasa
Main.hs
# language LambdaCase , OverloadedStrings , TemplateHaskell # LambdaCase , OverloadedStrings , TemplateHaskell #-} module Main (main) where import Data.FileEmbed (embedStringFile) import Data.Foldable (for_) import Data.List (intercalate) import System.Directory (createDirectoryIfMissing, withCurrentDirectory) import System.Environment (getArgs) main :: IO () main = getArgs >>= \case [] -> do help ["--help"] -> do help [name] -> do write (project name) _ -> do help help :: IO () help = do let msg = "" <> "trasa-init: initialise a trasa project\n\n" <> "usage: trasa-init <name>\n" putStrLn msg -- | Simple file system tree structure. data TreeFs = Dir FilePath [TreeFs] -- ^ Name of directory (relative) and -- its containing entries | File FilePath String -- ^ File name (relative) and file content write :: TreeFs -> IO () write = \case File name content -> do writeFile name (content <> "\n") Dir name children -> do createDirectoryIfMissing False name withCurrentDirectory name $ for_ children write language_ :: String -> String language_ p = "{-# LANGUAGE " <> p <> " #-}" module_ :: String -> [String] -> String module_ m is = "module " <> m <> "\n" <> unlines (go is) where go :: [String] -> [String] go [] = [" (\n ) where"] go (x:xs) = map showExportLine (LeftParen x : (map Comma xs ++ [End])) data ExportLine = LeftParen String | Comma String | End showExportLine :: ExportLine -> String showExportLine = \case LeftParen i -> " ( " <> i Comma i -> " , " <> i End -> " ) where" import_ :: String -> Maybe [String] -> String import_ m Nothing = "import " <> m import_ m (Just is) = "import " <> m <> " (" <> intercalate ", " is <> ")" importQ_ :: String -> Maybe String -> String importQ_ m Nothing = "import qualified " <> m importQ_ m (Just q) = "import qualified " <> m <> " as " <> q project :: String -> TreeFs project name = Dir name [ File (name <> ".cabal") (cabalFile name) , Dir "src" [ client , common , server ] , Dir "app" [ File "Main.hs" $ unlines [ "module Main (main) where" , "" , "import qualified Server" , "" , "main :: IO ()" , "main = Server.main" ] ] , defaultNix name , shellNix name , Dir ".nix" [ File "nixpkgs.json" $(embedStringFile "./res/nixpkgs.json") , File "pinned-nixpkgs.nix" $(embedStringFile "./res/pinned-nixpkgs.nix") , File "trasa.nix" $(embedStringFile "./res/trasa.nix") , File "trasa-client.nix" $(embedStringFile "./res/trasa-client.nix") , File "trasa-server.nix" $(embedStringFile "./res/trasa-server.nix") ] , File "Makefile" $ unlines [ "package = " <> name , "" , "build:" , "\tcabal build" , "" , "clean:" , "\tcabal clean" , "" , "haddock:" , "\tcabal haddock" , "" , "ghci:" , "\tcabal repl" , "" , "ghcid:" , "\tghcid -c cabal repl -r \"Server.main\"" ] ] client :: TreeFs client = File "Client.hs" $ unlines [ language_ "OverloadedStrings" , "" , module_ "Client" ["helloWorld"] , import_ "Lucid" Nothing , import_ "Data.IORef" (Just ["IORef", "newIORef", "readIORef"]) , import_ "Network.HTTP.Client" (Just ["newManager", "defaultManagerSettings"]) , import_ "Trasa.Core" Nothing , import_ "Trasa.Client" (Just ["Scheme(..)", "Authority(..)", "Config(..)", "clientWith"]) , import_ "System.IO.Unsafe" (Just ["unsafePerformIO"]) , "" , import_ "Common" Nothing , "" , "scheme :: Scheme" , "scheme = Http" , "" , "authority :: Authority" , "authority = Authority scheme \"127.0.0.1\" (Just 8080)" , "" , "config :: IORef Config" , "config = unsafePerformIO $ do" , " mngr <- newManager defaultManagerSettings" , " newIORef (Config authority mempty mngr)" , "{-# NOINLINE config #-}" , "" , "client :: Prepared Route response -> IO (Either TrasaErr response)" , "client p = do" , " cfg <- readIORef config" , " clientWith (metaCodecToMetaClient . meta) cfg p" , "" , "prepare :: ()" , " => Route captures queries request response" , " -> Arguments captures queries request (Prepared Route response)" , "prepare = prepareWith meta" , "" , "helloWorld :: IO (Either TrasaErr (Html ()))" , "helloWorld = client $ prepare HelloWorld" ] common :: TreeFs common = File "Common.hs" $ unlines [ language_ "DataKinds" , language_ "GADTs" , language_ "KindSignatures" , language_ "LambdaCase" , language_ "OverloadedStrings" , language_ "TemplateHaskell" , "" , module_ "Common" [ "Route(..)" , "allRoutes" , "meta" ] , import_ "Data.Kind" (Just ["Type"]) , import_ "Data.String" (Just ["fromString"]) , import_ "Lucid" Nothing , import_ "Trasa.Core" Nothing , importQ_ "Data.ByteString.Lazy.Char8" (Just "BC8") , importQ_ "Trasa.Method" (Just "Method") , "" , "data Route :: [Type] -> [Param] -> Bodiedness -> Type -> Type where" , " HelloWorld :: Route '[] '[] 'Bodyless (Html ())" , "" , "meta :: ()" , " => Route captures queries request response" , " -> MetaCodec captures queries request response" , "meta = \\case" , " HelloWorld -> Meta (match \"hello\" ./ end) qend bodyless (resp (one bodyHtml)) Method.get" , "" , "bodyHtml :: BodyCodec (Html ())" , "bodyHtml = BodyCodec" , " (pure \"text/html\")" , " Lucid.renderBS" , " (Right . fromString . BC8.unpack)" , "" , "-- Generate all of our routes" , "$(generateAllRoutes ''Route)" ] server :: TreeFs server = File "Server.hs" $ unlines [ language_ "DataKinds" , language_ "GADTs" , language_ "KindSignatures" , language_ "LambdaCase" , language_ "OverloadedStrings" , language_ "ScopedTypeVariables" , "" , module_ "Server" ["main"] , import_ "Data.Functor.Identity" (Just ["Identity"]) , import_ "Lucid" Nothing , import_ "Network.Wai" (Just ["Application"]) , import_ "Network.Wai.Handler.Warp" (Just ["run"]) , import_ "Network.Wai.Middleware.RequestLogger" (Just ["logStdoutDev"]) , import_ "Trasa.Core" Nothing , import_ "Trasa.Server" (Just ["TrasaT", "serveWith"]) , "" , import_ "Common" Nothing , "" , "type App = TrasaT IO" , "" , "main :: IO ()" , "main = run 8080 (logStdoutDev application)" , "" , "application :: Application" , "application = serveWith" , " (metaCodecToMetaServer . meta)" , " routes" , " router" , "" , "routes :: forall captures queries request response. ()" , " => Route captures queries request response" , " -> Rec Identity captures" , " -> Rec Parameter queries" , " -> RequestBody Identity request" , " -> App response" , "routes route captures queries reqBody = case route of" , " HelloWorld -> go helloWorld" , " where" , " go :: Arguments captures queries request (App response) -> App response" , " go f = handler captures queries reqBody f" , "" , "router :: Router Route" , "router = routerWith" , " (mapMeta captureDecoding captureDecoding id id . meta)" , " allRoutes" , "" , "helloWorld :: App (Html ())" , "helloWorld = pure $ h1_ \"Hello, World!\"" ] cabalFile :: () => String -- ^ library name -> String cabalFile name = unlines [ "cabal-version: 2.2" , "name:" , " " <> name , "version:" , " 0.1" , "build-type:" , " Simple" , "" , "library" , " hs-source-dirs:" , " src" , " exposed-modules:" , " Client" , " Common" , " Server" , " build-depends:" , " , aeson" , " , base >= 4.11 && < 4.15" , " , bytestring" , " , http-client" , " , lucid" , " , quantification" , " , text" , " , trasa" , " , trasa-client" , " , trasa-server" , " , wai" , " , wai-extra" , " , warp" , " ghc-options:" , " -Wall -O2" , " default-language:" , " Haskell2010" , "" , "executable " <> name , " hs-source-dirs:" , " app" , " main-is:" , " Main.hs" , " build-depends:" , " , base" , " , " <> name , " ghc-options:" , " -Wall -O2" , " default-language:" , " Haskell2010" ] defaultNix :: String -> TreeFs defaultNix name = File "default.nix" $ unlines [ "{ system ? builtins.currentSystem" , ", compiler ? \"ghc865\"" , ", ..." , "}:" , "" , "with rec {" , " pkgs = import ./.nix/pinned-nixpkgs.nix {" , " inherit system;" , " config = {" , " allowUnfree = true;" , " packageOverrides = pkgs: rec {" , " haskellPackages = pkgs.haskell.packages.\"${compiler}\".override {" , " overrides = hself: hsuper:" , " with pkgs.haskell.lib; rec {" , " trasa = hself.callPackage ./.nix/trasa.nix {};" , " trasa-client = hself.callPackage ./.nix/trasa-client.nix {};" , " trasa-server = hself.callPackage ./.nix/trasa-server.nix {};" , " };" , " };" , " };" , " };" , " };" , "" , " src = pkgs.lib.cleanSource ./.;" , "};" , "" , "rec {" , " " <> name <> " =" , " with pkgs.haskell.lib;" , " with pkgs.haskellPackages;" , " overrideCabal (" , " justStaticExecutables (" , " callCabal2nix \"" <> name <> "\" src {}" , " )" , " ) (old: {" , " });" , "}" ] shellNix :: String -> TreeFs shellNix name = File "shell.nix" $ unlines [ "(import ./default.nix {})." <> name <> ".env" ]
null
https://raw.githubusercontent.com/haskell-trasa/trasa/bfc23d4fd5b895493ba650a7f607b5fa034179d7/trasa-init/app/Main.hs
haskell
| Simple file system tree structure. ^ Name of directory (relative) and its containing entries ^ File name (relative) and file content ^ library name
# language LambdaCase , OverloadedStrings , TemplateHaskell # LambdaCase , OverloadedStrings , TemplateHaskell #-} module Main (main) where import Data.FileEmbed (embedStringFile) import Data.Foldable (for_) import Data.List (intercalate) import System.Directory (createDirectoryIfMissing, withCurrentDirectory) import System.Environment (getArgs) main :: IO () main = getArgs >>= \case [] -> do help ["--help"] -> do help [name] -> do write (project name) _ -> do help help :: IO () help = do let msg = "" <> "trasa-init: initialise a trasa project\n\n" <> "usage: trasa-init <name>\n" putStrLn msg data TreeFs = Dir FilePath [TreeFs] | File FilePath String write :: TreeFs -> IO () write = \case File name content -> do writeFile name (content <> "\n") Dir name children -> do createDirectoryIfMissing False name withCurrentDirectory name $ for_ children write language_ :: String -> String language_ p = "{-# LANGUAGE " <> p <> " #-}" module_ :: String -> [String] -> String module_ m is = "module " <> m <> "\n" <> unlines (go is) where go :: [String] -> [String] go [] = [" (\n ) where"] go (x:xs) = map showExportLine (LeftParen x : (map Comma xs ++ [End])) data ExportLine = LeftParen String | Comma String | End showExportLine :: ExportLine -> String showExportLine = \case LeftParen i -> " ( " <> i Comma i -> " , " <> i End -> " ) where" import_ :: String -> Maybe [String] -> String import_ m Nothing = "import " <> m import_ m (Just is) = "import " <> m <> " (" <> intercalate ", " is <> ")" importQ_ :: String -> Maybe String -> String importQ_ m Nothing = "import qualified " <> m importQ_ m (Just q) = "import qualified " <> m <> " as " <> q project :: String -> TreeFs project name = Dir name [ File (name <> ".cabal") (cabalFile name) , Dir "src" [ client , common , server ] , Dir "app" [ File "Main.hs" $ unlines [ "module Main (main) where" , "" , "import qualified Server" , "" , "main :: IO ()" , "main = Server.main" ] ] , defaultNix name , shellNix name , Dir ".nix" [ File "nixpkgs.json" $(embedStringFile "./res/nixpkgs.json") , File "pinned-nixpkgs.nix" $(embedStringFile "./res/pinned-nixpkgs.nix") , File "trasa.nix" $(embedStringFile "./res/trasa.nix") , File "trasa-client.nix" $(embedStringFile "./res/trasa-client.nix") , File "trasa-server.nix" $(embedStringFile "./res/trasa-server.nix") ] , File "Makefile" $ unlines [ "package = " <> name , "" , "build:" , "\tcabal build" , "" , "clean:" , "\tcabal clean" , "" , "haddock:" , "\tcabal haddock" , "" , "ghci:" , "\tcabal repl" , "" , "ghcid:" , "\tghcid -c cabal repl -r \"Server.main\"" ] ] client :: TreeFs client = File "Client.hs" $ unlines [ language_ "OverloadedStrings" , "" , module_ "Client" ["helloWorld"] , import_ "Lucid" Nothing , import_ "Data.IORef" (Just ["IORef", "newIORef", "readIORef"]) , import_ "Network.HTTP.Client" (Just ["newManager", "defaultManagerSettings"]) , import_ "Trasa.Core" Nothing , import_ "Trasa.Client" (Just ["Scheme(..)", "Authority(..)", "Config(..)", "clientWith"]) , import_ "System.IO.Unsafe" (Just ["unsafePerformIO"]) , "" , import_ "Common" Nothing , "" , "scheme :: Scheme" , "scheme = Http" , "" , "authority :: Authority" , "authority = Authority scheme \"127.0.0.1\" (Just 8080)" , "" , "config :: IORef Config" , "config = unsafePerformIO $ do" , " mngr <- newManager defaultManagerSettings" , " newIORef (Config authority mempty mngr)" , "{-# NOINLINE config #-}" , "" , "client :: Prepared Route response -> IO (Either TrasaErr response)" , "client p = do" , " cfg <- readIORef config" , " clientWith (metaCodecToMetaClient . meta) cfg p" , "" , "prepare :: ()" , " => Route captures queries request response" , " -> Arguments captures queries request (Prepared Route response)" , "prepare = prepareWith meta" , "" , "helloWorld :: IO (Either TrasaErr (Html ()))" , "helloWorld = client $ prepare HelloWorld" ] common :: TreeFs common = File "Common.hs" $ unlines [ language_ "DataKinds" , language_ "GADTs" , language_ "KindSignatures" , language_ "LambdaCase" , language_ "OverloadedStrings" , language_ "TemplateHaskell" , "" , module_ "Common" [ "Route(..)" , "allRoutes" , "meta" ] , import_ "Data.Kind" (Just ["Type"]) , import_ "Data.String" (Just ["fromString"]) , import_ "Lucid" Nothing , import_ "Trasa.Core" Nothing , importQ_ "Data.ByteString.Lazy.Char8" (Just "BC8") , importQ_ "Trasa.Method" (Just "Method") , "" , "data Route :: [Type] -> [Param] -> Bodiedness -> Type -> Type where" , " HelloWorld :: Route '[] '[] 'Bodyless (Html ())" , "" , "meta :: ()" , " => Route captures queries request response" , " -> MetaCodec captures queries request response" , "meta = \\case" , " HelloWorld -> Meta (match \"hello\" ./ end) qend bodyless (resp (one bodyHtml)) Method.get" , "" , "bodyHtml :: BodyCodec (Html ())" , "bodyHtml = BodyCodec" , " (pure \"text/html\")" , " Lucid.renderBS" , " (Right . fromString . BC8.unpack)" , "" , "-- Generate all of our routes" , "$(generateAllRoutes ''Route)" ] server :: TreeFs server = File "Server.hs" $ unlines [ language_ "DataKinds" , language_ "GADTs" , language_ "KindSignatures" , language_ "LambdaCase" , language_ "OverloadedStrings" , language_ "ScopedTypeVariables" , "" , module_ "Server" ["main"] , import_ "Data.Functor.Identity" (Just ["Identity"]) , import_ "Lucid" Nothing , import_ "Network.Wai" (Just ["Application"]) , import_ "Network.Wai.Handler.Warp" (Just ["run"]) , import_ "Network.Wai.Middleware.RequestLogger" (Just ["logStdoutDev"]) , import_ "Trasa.Core" Nothing , import_ "Trasa.Server" (Just ["TrasaT", "serveWith"]) , "" , import_ "Common" Nothing , "" , "type App = TrasaT IO" , "" , "main :: IO ()" , "main = run 8080 (logStdoutDev application)" , "" , "application :: Application" , "application = serveWith" , " (metaCodecToMetaServer . meta)" , " routes" , " router" , "" , "routes :: forall captures queries request response. ()" , " => Route captures queries request response" , " -> Rec Identity captures" , " -> Rec Parameter queries" , " -> RequestBody Identity request" , " -> App response" , "routes route captures queries reqBody = case route of" , " HelloWorld -> go helloWorld" , " where" , " go :: Arguments captures queries request (App response) -> App response" , " go f = handler captures queries reqBody f" , "" , "router :: Router Route" , "router = routerWith" , " (mapMeta captureDecoding captureDecoding id id . meta)" , " allRoutes" , "" , "helloWorld :: App (Html ())" , "helloWorld = pure $ h1_ \"Hello, World!\"" ] cabalFile :: () => String -> String cabalFile name = unlines [ "cabal-version: 2.2" , "name:" , " " <> name , "version:" , " 0.1" , "build-type:" , " Simple" , "" , "library" , " hs-source-dirs:" , " src" , " exposed-modules:" , " Client" , " Common" , " Server" , " build-depends:" , " , aeson" , " , base >= 4.11 && < 4.15" , " , bytestring" , " , http-client" , " , lucid" , " , quantification" , " , text" , " , trasa" , " , trasa-client" , " , trasa-server" , " , wai" , " , wai-extra" , " , warp" , " ghc-options:" , " -Wall -O2" , " default-language:" , " Haskell2010" , "" , "executable " <> name , " hs-source-dirs:" , " app" , " main-is:" , " Main.hs" , " build-depends:" , " , base" , " , " <> name , " ghc-options:" , " -Wall -O2" , " default-language:" , " Haskell2010" ] defaultNix :: String -> TreeFs defaultNix name = File "default.nix" $ unlines [ "{ system ? builtins.currentSystem" , ", compiler ? \"ghc865\"" , ", ..." , "}:" , "" , "with rec {" , " pkgs = import ./.nix/pinned-nixpkgs.nix {" , " inherit system;" , " config = {" , " allowUnfree = true;" , " packageOverrides = pkgs: rec {" , " haskellPackages = pkgs.haskell.packages.\"${compiler}\".override {" , " overrides = hself: hsuper:" , " with pkgs.haskell.lib; rec {" , " trasa = hself.callPackage ./.nix/trasa.nix {};" , " trasa-client = hself.callPackage ./.nix/trasa-client.nix {};" , " trasa-server = hself.callPackage ./.nix/trasa-server.nix {};" , " };" , " };" , " };" , " };" , " };" , "" , " src = pkgs.lib.cleanSource ./.;" , "};" , "" , "rec {" , " " <> name <> " =" , " with pkgs.haskell.lib;" , " with pkgs.haskellPackages;" , " overrideCabal (" , " justStaticExecutables (" , " callCabal2nix \"" <> name <> "\" src {}" , " )" , " ) (old: {" , " });" , "}" ] shellNix :: String -> TreeFs shellNix name = File "shell.nix" $ unlines [ "(import ./default.nix {})." <> name <> ".env" ]
cd72ea43ee2bfcb7e81d248aeefb462c9b2ff519b21085840c353b5f5f9a1c2a
footprintanalytics/footprint-web
automagic_dashboards.clj
(ns metabase.api.automagic-dashboards (:require [buddy.core.codecs :as codecs] [cheshire.core :as json] [compojure.core :refer [GET]] [metabase.api.common :as api] [metabase.automagic-dashboards.comparison :refer [comparison-dashboard]] [metabase.automagic-dashboards.core :refer [automagic-analysis candidate-tables]] [metabase.automagic-dashboards.rules :as rules] [metabase.models.card :refer [Card]] [metabase.models.collection :refer [Collection]] [metabase.models.database :refer [Database]] [metabase.models.field :refer [Field]] [metabase.models.metric :refer [Metric]] [metabase.models.permissions :as perms] [metabase.models.query :as query] [metabase.models.query.permissions :as query-perms] [metabase.models.segment :refer [Segment]] [metabase.models.table :refer [Table]] [metabase.transforms.dashboard :as transform.dashboard] [metabase.transforms.materialize :as tf.materialize] [metabase.util.i18n :refer [deferred-tru]] [metabase.util.schema :as su] [ring.util.codec :as codec] [schema.core :as s] [toucan.db :as db])) (def ^:private Show (su/with-api-error-message (s/maybe (s/enum "all")) (deferred-tru "invalid show value"))) (def ^:private Prefix (su/with-api-error-message (s/pred (fn [prefix] (some #(not-empty (rules/get-rules [% prefix])) ["table" "metric" "field"]))) (deferred-tru "invalid value for prefix"))) (def ^:private Rule (su/with-api-error-message (s/pred (fn [rule] (some (fn [toplevel] (some (comp rules/get-rule (fn [prefix] [toplevel prefix rule]) :rule) (rules/get-rules [toplevel]))) ["table" "metric" "field"]))) (deferred-tru "invalid value for rule name"))) (def ^:private ^{:arglists '([s])} decode-base64-json (comp #(json/decode % keyword) codecs/bytes->str codec/base64-decode)) (def ^:private Base64EncodedJSON (su/with-api-error-message (s/pred decode-base64-json) (deferred-tru "value couldn''t be parsed as base64 encoded JSON"))) (api/defendpoint GET "/database/:id/candidates" "Return a list of candidates for automagic dashboards orderd by interestingness." [id] (-> (db/select-one Database :id id) api/read-check candidate-tables)) ;; ----------------------------------------- API Endpoints for viewing a transient dashboard ---------------- (defn- adhoc-query-read-check [query] (api/check-403 (perms/set-has-partial-permissions-for-set? @api/*current-user-permissions-set* (query-perms/perms-set (:dataset_query query), :throw-exceptions? true))) query) (defn- ensure-int [x] (if (string? x) (Integer/parseInt x) x)) (defmulti ^:private ->entity "Parse/decode/coerce string `s` an to an entity of `entity-type`. `s` is something like a unparsed integer row ID, encoded query, or transform name." {:arglists '([entity-type s])} (fn [entity-type _s] (keyword entity-type))) (defmethod ->entity :table [_entity-type table-id-str] table - id can also be a source query reference like ` card__1 ` so in that case we should pull the ID out and use the ;; `:question` method instead (if-let [[_ card-id-str] (when (string? table-id-str) (re-matches #"^card__(\d+$)" table-id-str))] (->entity :question card-id-str) (api/read-check (db/select-one Table :id (ensure-int table-id-str))))) (defmethod ->entity :segment [_entity-type segment-id-str] (api/read-check (db/select-one Segment :id (ensure-int segment-id-str)))) (defmethod ->entity :question [_entity-type card-id-str] (api/read-check (db/select-one Card :id (ensure-int card-id-str)))) (defmethod ->entity :adhoc [_entity-type encoded-query] (adhoc-query-read-check (query/adhoc-query (decode-base64-json encoded-query)))) (defmethod ->entity :metric [_entity-type metric-id-str] (api/read-check (db/select-one Metric :id (ensure-int metric-id-str)))) (defmethod ->entity :field [_entity-type field-id-str] (api/read-check (db/select-one Field :id (ensure-int field-id-str)))) (defmethod ->entity :transform [_entity-type transform-name] (api/read-check (db/select-one Collection :id (tf.materialize/get-collection transform-name))) transform-name) (def ^:private Entity (su/with-api-error-message (apply s/enum (map name (keys (methods ->entity)))) (deferred-tru "Invalid entity type"))) (def ^:private ComparisonEntity (su/with-api-error-message (s/enum "segment" "adhoc" "table") (deferred-tru "Invalid comparison entity type. Can only be one of \"table\", \"segment\", or \"adhoc\""))) (api/defendpoint GET "/:entity/:entity-id-or-query" "Return an automagic dashboard for entity `entity` with id `id`." [entity entity-id-or-query show] {show Show entity Entity} (if (= entity "transform") (transform.dashboard/dashboard (->entity entity entity-id-or-query)) (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show)})))) (api/defendpoint GET "/:entity/:entity-id-or-query/rule/:prefix/:rule" "Return an automagic dashboard for entity `entity` with id `id` using rule `rule`." [entity entity-id-or-query prefix rule show] {entity Entity show Show prefix Prefix rule Rule} (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show) :rule ["table" prefix rule]}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query" "Return an automagic dashboard analyzing cell in automagic dashboard for entity `entity` defined by query `cell-querry`." [entity entity-id-or-query cell-query show] {entity Entity show Show cell-query Base64EncodedJSON} (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show) :cell-query (decode-base64-json cell-query)}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:rule" "Return an automagic dashboard analyzing cell in question with id `id` defined by query `cell-querry` using rule `rule`." [entity entity-id-or-query cell-query prefix rule show] {entity Entity show Show prefix Prefix rule Rule cell-query Base64EncodedJSON} (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show) :rule ["table" prefix rule] :cell-query (decode-base64-json cell-query)}))) (api/defendpoint GET "/:entity/:entity-id-or-query/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for entity `entity` with id `id` compared with entity `comparison-entity` with id `comparison-entity-id-or-query.`" [entity entity-id-or-query show comparison-entity comparison-entity-id-or-query] {show Show entity Entity comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :query-filter nil :comparison? true})] (comparison-dashboard dashboard left right {}))) (api/defendpoint GET "/:entity/:entity-id-or-query/rule/:prefix/:rule/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for entity `entity` with id `id` using rule `rule`; compared with entity `comparison-entity` with id `comparison-entity-id-or-query.`." [entity entity-id-or-query prefix rule show comparison-entity comparison-entity-id-or-query] {entity Entity show Show prefix Prefix rule Rule comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :rule ["table" prefix rule] :query-filter nil :comparison? true})] (comparison-dashboard dashboard left right {}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for cell in automagic dashboard for entity `entity` with id `id` defined by query `cell-querry`; compared with entity `comparison-entity` with id `comparison-entity-id-or-query.`." [entity entity-id-or-query cell-query show comparison-entity comparison-entity-id-or-query] {entity Entity show Show cell-query Base64EncodedJSON comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :query-filter nil :comparison? true})] (comparison-dashboard dashboard left right {:left {:cell-query (decode-base64-json cell-query)}}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:rule/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for cell in automagic dashboard for entity `entity` with id `id` defined by query `cell-querry` using rule `rule`; compared with entity `comparison-entity` with id `comparison-entity-id-or-query.`." [entity entity-id-or-query cell-query prefix rule show comparison-entity comparison-entity-id-or-query] {entity Entity show Show prefix Prefix rule Rule cell-query Base64EncodedJSON comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :rule ["table" prefix rule] :query-filter nil})] (comparison-dashboard dashboard left right {:left {:cell-query (decode-base64-json cell-query)}}))) (api/define-routes)
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/api/automagic_dashboards.clj
clojure
----------------------------------------- API Endpoints for viewing a transient dashboard ---------------- `:question` method instead compared with entity `comparison-entity` with id compared with entity
(ns metabase.api.automagic-dashboards (:require [buddy.core.codecs :as codecs] [cheshire.core :as json] [compojure.core :refer [GET]] [metabase.api.common :as api] [metabase.automagic-dashboards.comparison :refer [comparison-dashboard]] [metabase.automagic-dashboards.core :refer [automagic-analysis candidate-tables]] [metabase.automagic-dashboards.rules :as rules] [metabase.models.card :refer [Card]] [metabase.models.collection :refer [Collection]] [metabase.models.database :refer [Database]] [metabase.models.field :refer [Field]] [metabase.models.metric :refer [Metric]] [metabase.models.permissions :as perms] [metabase.models.query :as query] [metabase.models.query.permissions :as query-perms] [metabase.models.segment :refer [Segment]] [metabase.models.table :refer [Table]] [metabase.transforms.dashboard :as transform.dashboard] [metabase.transforms.materialize :as tf.materialize] [metabase.util.i18n :refer [deferred-tru]] [metabase.util.schema :as su] [ring.util.codec :as codec] [schema.core :as s] [toucan.db :as db])) (def ^:private Show (su/with-api-error-message (s/maybe (s/enum "all")) (deferred-tru "invalid show value"))) (def ^:private Prefix (su/with-api-error-message (s/pred (fn [prefix] (some #(not-empty (rules/get-rules [% prefix])) ["table" "metric" "field"]))) (deferred-tru "invalid value for prefix"))) (def ^:private Rule (su/with-api-error-message (s/pred (fn [rule] (some (fn [toplevel] (some (comp rules/get-rule (fn [prefix] [toplevel prefix rule]) :rule) (rules/get-rules [toplevel]))) ["table" "metric" "field"]))) (deferred-tru "invalid value for rule name"))) (def ^:private ^{:arglists '([s])} decode-base64-json (comp #(json/decode % keyword) codecs/bytes->str codec/base64-decode)) (def ^:private Base64EncodedJSON (su/with-api-error-message (s/pred decode-base64-json) (deferred-tru "value couldn''t be parsed as base64 encoded JSON"))) (api/defendpoint GET "/database/:id/candidates" "Return a list of candidates for automagic dashboards orderd by interestingness." [id] (-> (db/select-one Database :id id) api/read-check candidate-tables)) (defn- adhoc-query-read-check [query] (api/check-403 (perms/set-has-partial-permissions-for-set? @api/*current-user-permissions-set* (query-perms/perms-set (:dataset_query query), :throw-exceptions? true))) query) (defn- ensure-int [x] (if (string? x) (Integer/parseInt x) x)) (defmulti ^:private ->entity "Parse/decode/coerce string `s` an to an entity of `entity-type`. `s` is something like a unparsed integer row ID, encoded query, or transform name." {:arglists '([entity-type s])} (fn [entity-type _s] (keyword entity-type))) (defmethod ->entity :table [_entity-type table-id-str] table - id can also be a source query reference like ` card__1 ` so in that case we should pull the ID out and use the (if-let [[_ card-id-str] (when (string? table-id-str) (re-matches #"^card__(\d+$)" table-id-str))] (->entity :question card-id-str) (api/read-check (db/select-one Table :id (ensure-int table-id-str))))) (defmethod ->entity :segment [_entity-type segment-id-str] (api/read-check (db/select-one Segment :id (ensure-int segment-id-str)))) (defmethod ->entity :question [_entity-type card-id-str] (api/read-check (db/select-one Card :id (ensure-int card-id-str)))) (defmethod ->entity :adhoc [_entity-type encoded-query] (adhoc-query-read-check (query/adhoc-query (decode-base64-json encoded-query)))) (defmethod ->entity :metric [_entity-type metric-id-str] (api/read-check (db/select-one Metric :id (ensure-int metric-id-str)))) (defmethod ->entity :field [_entity-type field-id-str] (api/read-check (db/select-one Field :id (ensure-int field-id-str)))) (defmethod ->entity :transform [_entity-type transform-name] (api/read-check (db/select-one Collection :id (tf.materialize/get-collection transform-name))) transform-name) (def ^:private Entity (su/with-api-error-message (apply s/enum (map name (keys (methods ->entity)))) (deferred-tru "Invalid entity type"))) (def ^:private ComparisonEntity (su/with-api-error-message (s/enum "segment" "adhoc" "table") (deferred-tru "Invalid comparison entity type. Can only be one of \"table\", \"segment\", or \"adhoc\""))) (api/defendpoint GET "/:entity/:entity-id-or-query" "Return an automagic dashboard for entity `entity` with id `id`." [entity entity-id-or-query show] {show Show entity Entity} (if (= entity "transform") (transform.dashboard/dashboard (->entity entity entity-id-or-query)) (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show)})))) (api/defendpoint GET "/:entity/:entity-id-or-query/rule/:prefix/:rule" "Return an automagic dashboard for entity `entity` with id `id` using rule `rule`." [entity entity-id-or-query prefix rule show] {entity Entity show Show prefix Prefix rule Rule} (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show) :rule ["table" prefix rule]}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query" "Return an automagic dashboard analyzing cell in automagic dashboard for entity `entity` defined by query `cell-querry`." [entity entity-id-or-query cell-query show] {entity Entity show Show cell-query Base64EncodedJSON} (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show) :cell-query (decode-base64-json cell-query)}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:rule" "Return an automagic dashboard analyzing cell in question with id `id` defined by query `cell-querry` using rule `rule`." [entity entity-id-or-query cell-query prefix rule show] {entity Entity show Show prefix Prefix rule Rule cell-query Base64EncodedJSON} (-> (->entity entity entity-id-or-query) (automagic-analysis {:show (keyword show) :rule ["table" prefix rule] :cell-query (decode-base64-json cell-query)}))) (api/defendpoint GET "/:entity/:entity-id-or-query/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for entity `entity` with id `id` compared with entity `comparison-entity` with id `comparison-entity-id-or-query.`" [entity entity-id-or-query show comparison-entity comparison-entity-id-or-query] {show Show entity Entity comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :query-filter nil :comparison? true})] (comparison-dashboard dashboard left right {}))) (api/defendpoint GET "/:entity/:entity-id-or-query/rule/:prefix/:rule/compare/:comparison-entity/:comparison-entity-id-or-query" compared with entity `comparison-entity` with id `comparison-entity-id-or-query.`." [entity entity-id-or-query prefix rule show comparison-entity comparison-entity-id-or-query] {entity Entity show Show prefix Prefix rule Rule comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :rule ["table" prefix rule] :query-filter nil :comparison? true})] (comparison-dashboard dashboard left right {}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for cell in automagic dashboard for entity `entity` `comparison-entity-id-or-query.`." [entity entity-id-or-query cell-query show comparison-entity comparison-entity-id-or-query] {entity Entity show Show cell-query Base64EncodedJSON comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :query-filter nil :comparison? true})] (comparison-dashboard dashboard left right {:left {:cell-query (decode-base64-json cell-query)}}))) (api/defendpoint GET "/:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:rule/compare/:comparison-entity/:comparison-entity-id-or-query" "Return an automagic comparison dashboard for cell in automagic dashboard for entity `entity` `comparison-entity` with id `comparison-entity-id-or-query.`." [entity entity-id-or-query cell-query prefix rule show comparison-entity comparison-entity-id-or-query] {entity Entity show Show prefix Prefix rule Rule cell-query Base64EncodedJSON comparison-entity ComparisonEntity} (let [left (->entity entity entity-id-or-query) right (->entity comparison-entity comparison-entity-id-or-query) dashboard (automagic-analysis left {:show (keyword show) :rule ["table" prefix rule] :query-filter nil})] (comparison-dashboard dashboard left right {:left {:cell-query (decode-base64-json cell-query)}}))) (api/define-routes)
7f1e3a7839433cd62778862f00a09984afd58c5c2f41d1ea7606cbcaa869872b
camlp5/camlp5
odyl_main.mli
(* camlp5r *) (* odyl_main.mli,v *) exception Error of string and string; value nolib : ref bool; value initialized : ref bool; value path : ref (list string); value loadfile : string -> unit; value directory : string -> unit; value go : ref (unit -> unit); value name : ref string;
null
https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/odyl/odyl_main.mli
ocaml
camlp5r odyl_main.mli,v
exception Error of string and string; value nolib : ref bool; value initialized : ref bool; value path : ref (list string); value loadfile : string -> unit; value directory : string -> unit; value go : ref (unit -> unit); value name : ref string;
6c4d60c485da335661fbc49f7f1ff806991e4db68be28addc4aedafe4bc4a9e3
Vetd-Inc/vetd-app
cookies.cljs
(ns vetd-app.cookies (:require [re-frame.core :as rf] [vetd-app.util :as util] goog.net.cookies)) (defn set-cookie! "Sets a cookie, the following optional parameters may be passed in as a map: :max-age - max-age for session cookie, defaults to -1 :path - path of the cookie, defaults to the full request path :domain - domain of the cookie, when null the browser will use the full request host name :secure? - boolean specifying whether the cookie should only be sent over a secure channel" [k content & [{:keys [max-age path domain secure?]} :as opts]] (let [k' (util/kw->str k) content' (clj->js content)] (if-not opts (.set goog.net.cookies k' content') (.set goog.net.cookies k' content' (or max-age -1) path domain (boolean secure?))))) (rf/reg-cofx :cookies (fn [cofx cookies-keys] (->> (for [k cookies-keys] [k (js->clj (.get goog.net.cookies (util/kw->str k)))]) (into {}) (assoc cofx :cookies)))) (rf/reg-fx :cookies (fn [m] (doseq [[k v] m] (if (vector? v) (apply set-cookie! k v) (set-cookie! k v)))))
null
https://raw.githubusercontent.com/Vetd-Inc/vetd-app/9b33b1443b9d84d39305a63fc58119f8e014cf11/src/cljs/app/vetd_app/cookies.cljs
clojure
(ns vetd-app.cookies (:require [re-frame.core :as rf] [vetd-app.util :as util] goog.net.cookies)) (defn set-cookie! "Sets a cookie, the following optional parameters may be passed in as a map: :max-age - max-age for session cookie, defaults to -1 :path - path of the cookie, defaults to the full request path :domain - domain of the cookie, when null the browser will use the full request host name :secure? - boolean specifying whether the cookie should only be sent over a secure channel" [k content & [{:keys [max-age path domain secure?]} :as opts]] (let [k' (util/kw->str k) content' (clj->js content)] (if-not opts (.set goog.net.cookies k' content') (.set goog.net.cookies k' content' (or max-age -1) path domain (boolean secure?))))) (rf/reg-cofx :cookies (fn [cofx cookies-keys] (->> (for [k cookies-keys] [k (js->clj (.get goog.net.cookies (util/kw->str k)))]) (into {}) (assoc cofx :cookies)))) (rf/reg-fx :cookies (fn [m] (doseq [[k v] m] (if (vector? v) (apply set-cookie! k v) (set-cookie! k v)))))
d4cb166187c0cdf81cb34f8fdc6271e2e55bef2eaff8f55589fc32abff89b1b2
nixeagle/cl-github
issues.lisp
(in-package :cl-github) ;;; Issues API (defgeneric search-issues (username repository state term &key login token) (:documentation "Search for TERM with STATE on USERNAME's REPOSITORY.")) (defgeneric show-issues (username repository state &key login token) (:documentation "Show all issues with STATE on USERNAME's REPOSITORY.")) (defgeneric show-issue (username repository issue &key login token) (:documentation "Show ISSUE on USERNAME's REPOSITORY.")) (defgeneric show-issue-comments (username repository issue &key login token)) (defgeneric open-issue (username repository title body &key login token) (:documentation "Open issue about TITLE with BODY on USERNAME's REPOSITORY.")) (defgeneric close-issue (username repository issue &key login token) (:documentation "Close ISSUE on USERNAME's REPOSITORY.")) (defgeneric reopen-issue (username repository issue &key login token) (:documentation "Reopen ISSUE on USERNAME's REPOSITORY.")) (defgeneric edit-issue (username repository issue title body &key login token) (:documentation "Edit ISSUE setting TITLE and BODY on USERNAME's REPOSITORY. Editing an issue causes your TITLE and BODY to completely replace the original TITLE and BODY.")) (defgeneric show-labels (username repository &key login token) (:documentation "Show issue labels for USERNAME's REPOSITORY.")) (defgeneric add-label (username repository issue label &key login token) (:documentation "Add LABEL to ISSUE on USERNAME's REPOSITORY.")) (defgeneric remove-label (username repository issue label &key login token) (:documentation "Remove LABEL from ISSUE on USERNAME's REPOSITORY.")) (defgeneric add-comment (username repository issue comment &key login token) (:documentation "Add COMMENT to ISSUE on USERNAME's REPOSITORY.")) (defclass issue-labels () (labels) (:documentation "Github issue tracker labels.")) (defclass issue () (number votes created-at body title updated-at closed-at user labels state) (:documentation "Github issue information.")) (defclass comment () (comment status) (:documentation "Comment on a github issue.")) (defclass issue-comment () ((body :reader issue-comment-body) (created-at :reader issue-comment-created-at) (id :reader issue-comment-id) (updated-at :reader issue-comment-updated-at) (user :reader issue-comment-user))) (deftype valid-issue-state () "Github issues have two valid states." ;; This is not actually used at this time. '(member :open :closed)) (defmethod search-issues ((username string) (repository string) (state string) (term string) &key login token) (to-json (request login token `("issues" "search" ,username ,repository ,state ,term)))) (defmethod show-issues ((username string) (repository string) (state string) &key login token) (to-json (request login token `("issues" "list" ,username ,repository ,state)))) (defmethod show-issue ((username string) (repository string) (issue string) &key login token) (to-json (request login token `("issues" "show" ,username ,repository ,issue)))) (defmethod show-issue ((username string) (repository string) (issue integer) &key login token) (show-issue username repository (princ-to-string issue) :login login :token token)) (defmethod show-issue-comments ((username string) (repository string) (issue string) &key login token) (to-json (request login token `("issues" "comments" ,username ,repository ,issue)))) (defmethod show-issue-comments ((username string) (repository string) (issue integer) &key login token) (show-issue-comments username repository (princ-to-string issue) :login login :token token)) (defmethod open-issue ((username string) (repository string) (title string) (body string) &key login token) (to-json (authed-request login token `("issues" "open" ,username ,repository) :title title :body body))) (defmethod close-issue ((username string) (repository string) (issue string) &key login token) (to-json (authed-request login token `("issues" "close" ,username ,repository ,issue)))) (defmethod close-issue ((username string) (repository string) (issue integer) &key login token) (close-issue username repository (princ-to-string issue) :login login :token token)) (defmethod reopen-issue ((username string) (repository string) (issue string) &key login token) (to-json (authed-request login token `("issues" "reopen" ,username ,repository ,issue)))) (defmethod reopen-issue ((username string) (repository string) (issue integer) &key login token) (reopen-issue username repository (princ-to-string issue) :login login :token token)) (defmethod edit-issue ((username string) (repository string) (issue string) (title string) (body string) &key login token) (to-json (authed-request login token `("issues" "edit" ,username ,repository ,issue) :title title :body body))) (defmethod edit-issue ((username string) (repository string) (issue integer) (title string) (body string) &key login token) (edit-issue username repository (princ-to-string issue) title body :login login :token token)) (defmethod show-labels ((username string) (repository string) &key login token) (json->list (request login token `("issues" "labels" ,username ,repository)))) (defmethod add-label ((username string) (repository string) (issue string) (label string) &key login token) (json->list (authed-request login token `("issues" "label" "add" ,username ,repository ,label ,issue)))) (defmethod add-label ((username string) (repository string) (issue integer) (label string) &key login token) (add-label username repository (princ-to-string issue) label :login login :token token)) (defmethod remove-label ((username string) (repository string) (issue string) (label string) &key login token) (json->list (authed-request login token `("issues" "label" "remove" ,username ,repository ,label ,issue)))) (defmethod remove-label ((username string) (repository string) (issue integer) (label string) &key login token) (remove-label username repository (princ-to-string issue) label :login login :token token)) (defmethod add-comment ((username string) (repository string) (issue string) (comment string) &key login token) (to-json (authed-request login token `("issues" "comment" ,username ,repository ,issue) :comment comment))) (defmethod add-comment ((username string) (repository string) (issue integer) (comment string) &key login token) (add-comment username repository (princ-to-string issue) comment :login login :token token))
null
https://raw.githubusercontent.com/nixeagle/cl-github/19ba2477ea65e52e74e166482407ea96bee8e395/issues.lisp
lisp
Issues API This is not actually used at this time.
(in-package :cl-github) (defgeneric search-issues (username repository state term &key login token) (:documentation "Search for TERM with STATE on USERNAME's REPOSITORY.")) (defgeneric show-issues (username repository state &key login token) (:documentation "Show all issues with STATE on USERNAME's REPOSITORY.")) (defgeneric show-issue (username repository issue &key login token) (:documentation "Show ISSUE on USERNAME's REPOSITORY.")) (defgeneric show-issue-comments (username repository issue &key login token)) (defgeneric open-issue (username repository title body &key login token) (:documentation "Open issue about TITLE with BODY on USERNAME's REPOSITORY.")) (defgeneric close-issue (username repository issue &key login token) (:documentation "Close ISSUE on USERNAME's REPOSITORY.")) (defgeneric reopen-issue (username repository issue &key login token) (:documentation "Reopen ISSUE on USERNAME's REPOSITORY.")) (defgeneric edit-issue (username repository issue title body &key login token) (:documentation "Edit ISSUE setting TITLE and BODY on USERNAME's REPOSITORY. Editing an issue causes your TITLE and BODY to completely replace the original TITLE and BODY.")) (defgeneric show-labels (username repository &key login token) (:documentation "Show issue labels for USERNAME's REPOSITORY.")) (defgeneric add-label (username repository issue label &key login token) (:documentation "Add LABEL to ISSUE on USERNAME's REPOSITORY.")) (defgeneric remove-label (username repository issue label &key login token) (:documentation "Remove LABEL from ISSUE on USERNAME's REPOSITORY.")) (defgeneric add-comment (username repository issue comment &key login token) (:documentation "Add COMMENT to ISSUE on USERNAME's REPOSITORY.")) (defclass issue-labels () (labels) (:documentation "Github issue tracker labels.")) (defclass issue () (number votes created-at body title updated-at closed-at user labels state) (:documentation "Github issue information.")) (defclass comment () (comment status) (:documentation "Comment on a github issue.")) (defclass issue-comment () ((body :reader issue-comment-body) (created-at :reader issue-comment-created-at) (id :reader issue-comment-id) (updated-at :reader issue-comment-updated-at) (user :reader issue-comment-user))) (deftype valid-issue-state () "Github issues have two valid states." '(member :open :closed)) (defmethod search-issues ((username string) (repository string) (state string) (term string) &key login token) (to-json (request login token `("issues" "search" ,username ,repository ,state ,term)))) (defmethod show-issues ((username string) (repository string) (state string) &key login token) (to-json (request login token `("issues" "list" ,username ,repository ,state)))) (defmethod show-issue ((username string) (repository string) (issue string) &key login token) (to-json (request login token `("issues" "show" ,username ,repository ,issue)))) (defmethod show-issue ((username string) (repository string) (issue integer) &key login token) (show-issue username repository (princ-to-string issue) :login login :token token)) (defmethod show-issue-comments ((username string) (repository string) (issue string) &key login token) (to-json (request login token `("issues" "comments" ,username ,repository ,issue)))) (defmethod show-issue-comments ((username string) (repository string) (issue integer) &key login token) (show-issue-comments username repository (princ-to-string issue) :login login :token token)) (defmethod open-issue ((username string) (repository string) (title string) (body string) &key login token) (to-json (authed-request login token `("issues" "open" ,username ,repository) :title title :body body))) (defmethod close-issue ((username string) (repository string) (issue string) &key login token) (to-json (authed-request login token `("issues" "close" ,username ,repository ,issue)))) (defmethod close-issue ((username string) (repository string) (issue integer) &key login token) (close-issue username repository (princ-to-string issue) :login login :token token)) (defmethod reopen-issue ((username string) (repository string) (issue string) &key login token) (to-json (authed-request login token `("issues" "reopen" ,username ,repository ,issue)))) (defmethod reopen-issue ((username string) (repository string) (issue integer) &key login token) (reopen-issue username repository (princ-to-string issue) :login login :token token)) (defmethod edit-issue ((username string) (repository string) (issue string) (title string) (body string) &key login token) (to-json (authed-request login token `("issues" "edit" ,username ,repository ,issue) :title title :body body))) (defmethod edit-issue ((username string) (repository string) (issue integer) (title string) (body string) &key login token) (edit-issue username repository (princ-to-string issue) title body :login login :token token)) (defmethod show-labels ((username string) (repository string) &key login token) (json->list (request login token `("issues" "labels" ,username ,repository)))) (defmethod add-label ((username string) (repository string) (issue string) (label string) &key login token) (json->list (authed-request login token `("issues" "label" "add" ,username ,repository ,label ,issue)))) (defmethod add-label ((username string) (repository string) (issue integer) (label string) &key login token) (add-label username repository (princ-to-string issue) label :login login :token token)) (defmethod remove-label ((username string) (repository string) (issue string) (label string) &key login token) (json->list (authed-request login token `("issues" "label" "remove" ,username ,repository ,label ,issue)))) (defmethod remove-label ((username string) (repository string) (issue integer) (label string) &key login token) (remove-label username repository (princ-to-string issue) label :login login :token token)) (defmethod add-comment ((username string) (repository string) (issue string) (comment string) &key login token) (to-json (authed-request login token `("issues" "comment" ,username ,repository ,issue) :comment comment))) (defmethod add-comment ((username string) (repository string) (issue integer) (comment string) &key login token) (add-comment username repository (princ-to-string issue) comment :login login :token token))
e1eebfd2375b4d6060ebc5956c6aabb2eadfc67b7e21d12e089b0d6f59ddb210
greglook/merkledag-ledger
ledger.clj
(ns finance.format.ledger "Code for working with text-based ledger files." (:require [clojure.java.io :as io] [clojure.string :as str] [finance.format.ledger.parse :as parse] [finance.format.ledger.print :as print])) ;; TODO: implement standard format API (defn parse-string "Parse a string of ledger text into a vector of entity maps." [text] (->> text (str/split-lines) (parse/parse-lines) (vec))) (defn parse "Parse the source, returning a lazy sequence of interpreted ledger entries. Source may be anything coercible to a reader." [source] (->> source (io/reader) (line-seq) (parse/parse-lines)))
null
https://raw.githubusercontent.com/greglook/merkledag-ledger/af938ba0c7e5e694e679d583a1cecf64f41452d8/src/finance/format/ledger.clj
clojure
TODO: implement standard format API
(ns finance.format.ledger "Code for working with text-based ledger files." (:require [clojure.java.io :as io] [clojure.string :as str] [finance.format.ledger.parse :as parse] [finance.format.ledger.print :as print])) (defn parse-string "Parse a string of ledger text into a vector of entity maps." [text] (->> text (str/split-lines) (parse/parse-lines) (vec))) (defn parse "Parse the source, returning a lazy sequence of interpreted ledger entries. Source may be anything coercible to a reader." [source] (->> source (io/reader) (line-seq) (parse/parse-lines)))
bb4267c89c6ec4a4e50c4027fd26a1ad6a77a89eaee08eeae5fee757bf045688
avsm/platform
opamStubs.mli
(**************************************************************************) (* *) Copyright 2018 MetaStack Solutions Ltd. (* *) (* 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. *) (* *) (**************************************************************************) * OS - specific functions requiring C code on at least one platform . Most functions are Windows - specific and raise an exception on other platforms . Most functions are Windows-specific and raise an exception on other platforms. *) include module type of struct include OpamStubsTypes end val getpid : unit -> int * On Windows , this returns the actual process ID , rather than the non - unique faked process ID returned by the Microsoft C Runtime ( see ) . On all other platforms , this is just an alias for [ Unix.getpid ] . faked process ID returned by the Microsoft C Runtime (see ). On all other platforms, this is just an alias for [Unix.getpid]. *) val getCurrentProcessID : unit -> int32 * Windows only . As { ! } , but without the possibility of truncating the ID on 32 - bit platforms . ID on 32-bit platforms. *) val getStdHandle : stdhandle -> handle (** Windows only. Return a standard handle. *) val getConsoleScreenBufferInfo : handle -> console_screen_buffer_info (** Windows only. Return current Console screen buffer information. *) val setConsoleTextAttribute : handle -> int -> unit (** Windows only. Set the console's text attribute setting. *) val fillConsoleOutputCharacter : handle -> char -> int -> int * int -> bool (** Windows only. [fillConsoleOutputCharacter buffer c n (x, y)] writes [c] [n] times starting at the given coordinate (and wrapping if required). *) val getConsoleMode : handle -> int (** Windows only. Returns the input/output mode of the console screen buffer referred to by the handle. @raise Not_found If the handle does not refer to a console. *) val setConsoleMode : handle -> int -> bool (** Windows only. Sets the input/output mode of the console screen buffer referred to by the handle, returning [true] if the operation isr successful. *) val getWindowsVersion : unit -> int * int * int * int * Windows only . Returns the Windows version as [ ( major , minor , build , revision ) ] . This function only works if opam is compiled OCaml 4.06.0 or later , it returns [ ( 0 , 0 , 0 , 0 ) ] otherwise . [(major, minor, build, revision)]. This function only works if opam is compiled OCaml 4.06.0 or later, it returns [(0, 0, 0, 0)] otherwise. *) val isWoW64 : unit -> bool * Returns [ false ] unless this process is a 32 - bit Windows process running in the sub - system ( i.e. is being run on 64 - bit Windows ) . in the WoW64 sub-system (i.e. is being run on 64-bit Windows). *) val waitpids : int list -> int -> int * Unix.process_status * Windows only . Given a list [ pids ] with [ length ] elements , [ waitpids pids length ] behaves like [ Unix.wait ] , returning the pid and exit status of the first process to terminate . [waitpids pids length] behaves like [Unix.wait], returning the pid and exit status of the first process to terminate. *) val writeRegistry : registry_root -> string -> string -> 'a registry_value -> 'a -> unit * Windows only . [ writeRegistry root key name value_type value ] sets the value [ name ] of type [ value_type ] in registry key [ key ] of [ root ] to [ value ] . @raise Failure If the value could not be set . @raise Not_found If [ key ] does not exist . value [name] of type [value_type] in registry key [key] of [root] to [value]. @raise Failure If the value could not be set. @raise Not_found If [key] does not exist. *) val getConsoleOutputCP : unit -> int * Windows only . Retrieves the current Console Output Code Page . val getCurrentConsoleFontEx : handle -> bool -> console_font_infoex (** Windows only. Gets information on the current console output font. *) val create_glyph_checker : string -> handle * handle * Windows only . Given a font name , returns a pair consisting of a screen DC and a font object , which will have been selected into the DC . @raise Failure If anything goes wrong with the GDI calls . and a font object, which will have been selected into the DC. @raise Failure If anything goes wrong with the GDI calls. *) val delete_glyph_checker : handle * handle -> unit * Windows only . Given [ ( dc , font ) ] , deletes the font object and releases the DC . DC. *) val has_glyph : handle * handle -> OpamCompat.Uchar.t -> bool * Windows only . [ has_glyph ( dc , font ) scalar ] returns [ true ] if [ font ] contains a glyph for [ scalar ] . @raise Failure If the call to [ GetGlyphIndicesW ] fails . contains a glyph for [scalar]. @raise Failure If the call to [GetGlyphIndicesW] fails. *) val isWoW64Process : int32 -> bool (** Windows only. General version of {!isWoW64} for any given process ID. See -us/library/windows/desktop/ms684139.aspx *) val process_putenv : int32 -> string -> string -> bool * Windows only . [ process_putenv pid name value ] sets the environment variable [ name ] to [ value ] in given process ID ( [ Unix.putenv ] must also be called to update the value in the current process ) . This function must not be called if the target process is 32 - bit and the current process is 64 - bit or vice versa ( outcomes vary from a no - op to a segfault ) . [name] to [value] in given process ID ([Unix.putenv] must also be called to update the value in the current process). This function must not be called if the target process is 32-bit and the current process is 64-bit or vice versa (outcomes vary from a no-op to a segfault). *) val shGetFolderPath : int -> shGFP_type -> string * Windows only . [ shGetFolderPath nFolder dwFlags ] retrieves the location of a special folder by CSIDL value . See -us/library/windows/desktop/bb762181.aspx folder by CSIDL value. See -us/library/windows/desktop/bb762181.aspx *) val sendMessageTimeout : nativeint -> int -> int -> ('a, 'b, 'c) winmessage -> 'a -> 'b -> int * 'c * Windows only . [ sendMessageTimeout hwnd timeout flags message wParam lParam ] sends a message to the given handle , but is guaranteed to return within [ timeout ] milliseconds . The result consists of two parts , [ fst ] is the return value from SendMessageTimeout , [ snd ] depends on both the message and [ fst ] . See -us/library/windows/desktop/ms644952.aspx sends a message to the given handle, but is guaranteed to return within [timeout] milliseconds. The result consists of two parts, [fst] is the return value from SendMessageTimeout, [snd] depends on both the message and [fst]. See -us/library/windows/desktop/ms644952.aspx *) val getParentProcessID : int32 -> int32 (** Windows only. [getParentProcessID pid] returns the process ID of the parent of [pid]. @raise Failure If walking the process tree fails to find the process. *) val getConsoleAlias : string -> string -> string (** Windows only. [getConsoleAlias alias exeName] retrieves the value for a given executable or [""] if the alias is not defined. See -us/windows/console/getconsolealias *)
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/opam-client.2.0.5%2Bdune/src/core/opamStubs.mli
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ * Windows only. Return a standard handle. * Windows only. Return current Console screen buffer information. * Windows only. Set the console's text attribute setting. * Windows only. [fillConsoleOutputCharacter buffer c n (x, y)] writes [c] [n] times starting at the given coordinate (and wrapping if required). * Windows only. Returns the input/output mode of the console screen buffer referred to by the handle. @raise Not_found If the handle does not refer to a console. * Windows only. Sets the input/output mode of the console screen buffer referred to by the handle, returning [true] if the operation isr successful. * Windows only. Gets information on the current console output font. * Windows only. General version of {!isWoW64} for any given process ID. See -us/library/windows/desktop/ms684139.aspx * Windows only. [getParentProcessID pid] returns the process ID of the parent of [pid]. @raise Failure If walking the process tree fails to find the process. * Windows only. [getConsoleAlias alias exeName] retrieves the value for a given executable or [""] if the alias is not defined. See -us/windows/console/getconsolealias
Copyright 2018 MetaStack Solutions Ltd. GNU Lesser General Public License version 2.1 , with the special * OS - specific functions requiring C code on at least one platform . Most functions are Windows - specific and raise an exception on other platforms . Most functions are Windows-specific and raise an exception on other platforms. *) include module type of struct include OpamStubsTypes end val getpid : unit -> int * On Windows , this returns the actual process ID , rather than the non - unique faked process ID returned by the Microsoft C Runtime ( see ) . On all other platforms , this is just an alias for [ Unix.getpid ] . faked process ID returned by the Microsoft C Runtime (see ). On all other platforms, this is just an alias for [Unix.getpid]. *) val getCurrentProcessID : unit -> int32 * Windows only . As { ! } , but without the possibility of truncating the ID on 32 - bit platforms . ID on 32-bit platforms. *) val getStdHandle : stdhandle -> handle val getConsoleScreenBufferInfo : handle -> console_screen_buffer_info val setConsoleTextAttribute : handle -> int -> unit val fillConsoleOutputCharacter : handle -> char -> int -> int * int -> bool val getConsoleMode : handle -> int val setConsoleMode : handle -> int -> bool val getWindowsVersion : unit -> int * int * int * int * Windows only . Returns the Windows version as [ ( major , minor , build , revision ) ] . This function only works if opam is compiled OCaml 4.06.0 or later , it returns [ ( 0 , 0 , 0 , 0 ) ] otherwise . [(major, minor, build, revision)]. This function only works if opam is compiled OCaml 4.06.0 or later, it returns [(0, 0, 0, 0)] otherwise. *) val isWoW64 : unit -> bool * Returns [ false ] unless this process is a 32 - bit Windows process running in the sub - system ( i.e. is being run on 64 - bit Windows ) . in the WoW64 sub-system (i.e. is being run on 64-bit Windows). *) val waitpids : int list -> int -> int * Unix.process_status * Windows only . Given a list [ pids ] with [ length ] elements , [ waitpids pids length ] behaves like [ Unix.wait ] , returning the pid and exit status of the first process to terminate . [waitpids pids length] behaves like [Unix.wait], returning the pid and exit status of the first process to terminate. *) val writeRegistry : registry_root -> string -> string -> 'a registry_value -> 'a -> unit * Windows only . [ writeRegistry root key name value_type value ] sets the value [ name ] of type [ value_type ] in registry key [ key ] of [ root ] to [ value ] . @raise Failure If the value could not be set . @raise Not_found If [ key ] does not exist . value [name] of type [value_type] in registry key [key] of [root] to [value]. @raise Failure If the value could not be set. @raise Not_found If [key] does not exist. *) val getConsoleOutputCP : unit -> int * Windows only . Retrieves the current Console Output Code Page . val getCurrentConsoleFontEx : handle -> bool -> console_font_infoex val create_glyph_checker : string -> handle * handle * Windows only . Given a font name , returns a pair consisting of a screen DC and a font object , which will have been selected into the DC . @raise Failure If anything goes wrong with the GDI calls . and a font object, which will have been selected into the DC. @raise Failure If anything goes wrong with the GDI calls. *) val delete_glyph_checker : handle * handle -> unit * Windows only . Given [ ( dc , font ) ] , deletes the font object and releases the DC . DC. *) val has_glyph : handle * handle -> OpamCompat.Uchar.t -> bool * Windows only . [ has_glyph ( dc , font ) scalar ] returns [ true ] if [ font ] contains a glyph for [ scalar ] . @raise Failure If the call to [ GetGlyphIndicesW ] fails . contains a glyph for [scalar]. @raise Failure If the call to [GetGlyphIndicesW] fails. *) val isWoW64Process : int32 -> bool val process_putenv : int32 -> string -> string -> bool * Windows only . [ process_putenv pid name value ] sets the environment variable [ name ] to [ value ] in given process ID ( [ Unix.putenv ] must also be called to update the value in the current process ) . This function must not be called if the target process is 32 - bit and the current process is 64 - bit or vice versa ( outcomes vary from a no - op to a segfault ) . [name] to [value] in given process ID ([Unix.putenv] must also be called to update the value in the current process). This function must not be called if the target process is 32-bit and the current process is 64-bit or vice versa (outcomes vary from a no-op to a segfault). *) val shGetFolderPath : int -> shGFP_type -> string * Windows only . [ shGetFolderPath nFolder dwFlags ] retrieves the location of a special folder by CSIDL value . See -us/library/windows/desktop/bb762181.aspx folder by CSIDL value. See -us/library/windows/desktop/bb762181.aspx *) val sendMessageTimeout : nativeint -> int -> int -> ('a, 'b, 'c) winmessage -> 'a -> 'b -> int * 'c * Windows only . [ sendMessageTimeout hwnd timeout flags message wParam lParam ] sends a message to the given handle , but is guaranteed to return within [ timeout ] milliseconds . The result consists of two parts , [ fst ] is the return value from SendMessageTimeout , [ snd ] depends on both the message and [ fst ] . See -us/library/windows/desktop/ms644952.aspx sends a message to the given handle, but is guaranteed to return within [timeout] milliseconds. The result consists of two parts, [fst] is the return value from SendMessageTimeout, [snd] depends on both the message and [fst]. See -us/library/windows/desktop/ms644952.aspx *) val getParentProcessID : int32 -> int32 val getConsoleAlias : string -> string -> string
3b3fc1620e9141033cee080427f6f0b402498af579b4eac2a25919903b9d7854
bsaleil/lc
print.scm
;;--------------------------------------------------------------------------- ;; Copyright ( c ) 2015 , . All rights reserved . ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are ;; met: ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; 3. The name of the author may not be used to endorse or promote ;; products derived from this software without specific prior written ;; permission. ;; THIS SOFTWARE IS PROVIDED ` ` AS IS '' AND ANY EXPRESS OR ;; 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. ;; ;;--------------------------------------------------------------------------- ;; Number (println 0) (println -0) (println -000) (println 12345) (println -12345) (println (* (+ 5 2) (- 5 1))) Boolean (println #t) (println #f) (println (not (not (not (<= 10 10))))) ;; Null (println '()) ;; Pair (println (cons 10 20)) (println (cons 10 (cons 20 '()))) (println (cons 99 (cons #f (cons '() '())))) ;; (println '(1 2 3)) (println '(1 2 (3 4) 5 6)) (println '(1 2 (3 4) 5)) ;; Char (println #\a) (println #\Z) (println #\?) (println #\newline) (println (integer->char 104)) ;; String (println "Hello World") (println "éêà") (println "10€ or 10$") (println (make-string 5 (integer->char 65))) (println (substring "Dark Vador" 0 4)) ;; Vector (println (make-vector 4 "Hi.")) (define v (make-vector 4 0)) (vector-set! v 2 "Hey") (println v) (println (vector-ref v 0)) ;; Symbol (println 'Hello) (define sym 'Dark) (define str " Vador") (println (string->symbol (string-append (symbol->string sym) str))) 0 0 0 12345 ;-12345 28 ;#t ;#f ;#f ; 1020 1020 99#f 123 123456 12345 ;a ;Z ;? ; ; ;h ;Hello World ;éêà 10 € or 10 $ AAAAA ;Dark ;Hi.Hi.Hi.Hi. ;00Hey0 0 ;Hello Dark Vador
null
https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/unit-tests/print.scm
scheme
--------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. 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, NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- Number Null Pair Char String Vector Symbol -12345 #t #f #f a Z ? h Hello World éêà Dark Hi.Hi.Hi.Hi. 00Hey0 Hello
Copyright ( c ) 2015 , . All rights reserved . THIS SOFTWARE IS PROVIDED ` ` AS IS '' AND ANY EXPRESS OR INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (println 0) (println -0) (println -000) (println 12345) (println -12345) (println (* (+ 5 2) (- 5 1))) Boolean (println #t) (println #f) (println (not (not (not (<= 10 10))))) (println '()) (println (cons 10 20)) (println (cons 10 (cons 20 '()))) (println (cons 99 (cons #f (cons '() '())))) (println '(1 2 3)) (println '(1 2 (3 4) 5 6)) (println '(1 2 (3 4) 5)) (println #\a) (println #\Z) (println #\?) (println #\newline) (println (integer->char 104)) (println "Hello World") (println "éêà") (println "10€ or 10$") (println (make-string 5 (integer->char 65))) (println (substring "Dark Vador" 0 4)) (println (make-vector 4 "Hi.")) (define v (make-vector 4 0)) (vector-set! v 2 "Hey") (println v) (println (vector-ref v 0)) (println 'Hello) (define sym 'Dark) (define str " Vador") (println (string->symbol (string-append (symbol->string sym) str))) 0 0 0 12345 28 1020 1020 99#f 123 123456 12345 10 € or 10 $ AAAAA 0 Dark Vador
84c6b7f339f9baf048dcb33b496ab51c33a0181bc63ee1a651bfbf01b7fd14f7
melange-re/melange
map_test.ml
open Mt module Int = struct type t = int let compare (x : int) (y : int) = Pervasives.compare x y end module Int_map = Map.Make(Int) module String_map = Map.Make(String) let of_list kvs = List.fold_left (fun acc (k,v) -> Int_map.add k v acc) Int_map.empty kvs let int_map_suites = let open Mt in Int_map.[ "add", (fun _ -> let v = of_list [ 1,'1';2,'3';3,'4'] in Eq (cardinal v , 3) ); "equal", (fun _ -> let v = of_list [ 1,'1';2,'3';3,'4'] in let u = of_list [ 2,'3';3,'4'; 1,'1'] in Eq (compare Pervasives.compare u v , 0) ); "equal2", (fun _ -> let v = of_list [ 1,'1';2,'3';3,'4'] in let u = of_list [ 2,'3';3,'4'; 1,'1'] in Eq (true, equal (fun x y -> x = y) u v ) ); "iteration", (fun _ -> let m = ref String_map.empty in let count = 1_0000 in for i = 0 to count do m := String_map.add (string_of_int i) (string_of_int i) !m done; let v = ref (-1) in for i = 0 to count do if (String_map.find (string_of_int i) !m ) != (string_of_int i) then v:= i done; Eq(!v, -1 ) ) ] ;; Mt.from_pair_suites __MODULE__ int_map_suites
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/map_test.ml
ocaml
open Mt module Int = struct type t = int let compare (x : int) (y : int) = Pervasives.compare x y end module Int_map = Map.Make(Int) module String_map = Map.Make(String) let of_list kvs = List.fold_left (fun acc (k,v) -> Int_map.add k v acc) Int_map.empty kvs let int_map_suites = let open Mt in Int_map.[ "add", (fun _ -> let v = of_list [ 1,'1';2,'3';3,'4'] in Eq (cardinal v , 3) ); "equal", (fun _ -> let v = of_list [ 1,'1';2,'3';3,'4'] in let u = of_list [ 2,'3';3,'4'; 1,'1'] in Eq (compare Pervasives.compare u v , 0) ); "equal2", (fun _ -> let v = of_list [ 1,'1';2,'3';3,'4'] in let u = of_list [ 2,'3';3,'4'; 1,'1'] in Eq (true, equal (fun x y -> x = y) u v ) ); "iteration", (fun _ -> let m = ref String_map.empty in let count = 1_0000 in for i = 0 to count do m := String_map.add (string_of_int i) (string_of_int i) !m done; let v = ref (-1) in for i = 0 to count do if (String_map.find (string_of_int i) !m ) != (string_of_int i) then v:= i done; Eq(!v, -1 ) ) ] ;; Mt.from_pair_suites __MODULE__ int_map_suites
ec33064378098c98da7200d549c69ecc98cd5e72efcf278187a36ae843997ec7
spectrum-finance/cardano-dex-contracts
Redeem.hs
# LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module ErgoDex.Contracts.Proxy.Redeem where import PlutusLedgerApi.V1.Crypto (PubKeyHash) import PlutusLedgerApi.V1.Value import qualified PlutusTx import PlutusTx.Builtins data RedeemConfig = RedeemConfig { poolNft :: AssetClass , poolX :: AssetClass , poolY :: AssetClass , poolLp :: AssetClass , exFee :: Integer , rewardPkh :: PubKeyHash , stakePkh :: Maybe PubKeyHash } deriving stock (Show) PlutusTx.makeIsDataIndexed ''RedeemConfig [('RedeemConfig, 0)]
null
https://raw.githubusercontent.com/spectrum-finance/cardano-dex-contracts/87bdbc26dbe9ae5f6c59e608d728330f8166f19c/cardano-dex-contracts-onchain/ErgoDex/Contracts/Proxy/Redeem.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module ErgoDex.Contracts.Proxy.Redeem where import PlutusLedgerApi.V1.Crypto (PubKeyHash) import PlutusLedgerApi.V1.Value import qualified PlutusTx import PlutusTx.Builtins data RedeemConfig = RedeemConfig { poolNft :: AssetClass , poolX :: AssetClass , poolY :: AssetClass , poolLp :: AssetClass , exFee :: Integer , rewardPkh :: PubKeyHash , stakePkh :: Maybe PubKeyHash } deriving stock (Show) PlutusTx.makeIsDataIndexed ''RedeemConfig [('RedeemConfig, 0)]
f29a38a7e44e5b0da067e778eb7f2b5fb09d0c0dd25140eff2e5a40f854165ce
ocaml/oasis-db
ODBCLIUpload.ml
* ' upload ' subcommand handler Upload a tarball which contains a _ oasis file . @author Upload a tarball which contains a _oasis file. @author Sylvain Le Gall *) open SubCommand open OASISUtils open OASISTypes open ODBGettext open ODBCLICommon open ODBRepository open Lwt open ExtLib let tarball_fn = ref None let repo = ref None let publink = ref None let main () = let ctxt = Lwt_unix.run (context_lwt ()) in let tarball_fn = match !tarball_fn with | Some fn -> fn | None -> failwith (s_ "No tarball to upload") in let publink = !publink in let api_uri = let repo, _ = match !repo with | Some nm -> begin try List.find (fun (repo, _) -> repo.repo_name = nm) ctxt.cli_repos with Not_found -> failwith (Printf.sprintf (f_ "Unable to find repository named '%s'") nm) end | None -> begin try List.find (fun (repo, _) -> repo.repo_api_uri <> None) ctxt.cli_repos with Not_found -> failwith (s_ "Unable to find a repository where upload is allowed") end in match repo.repo_api_uri with | Some uri -> uri | None -> failwith (Printf.sprintf (f_ "Selected repository '%s' doesn't have an API URI set") repo.repo_name) in ODBCurl.with_curl (fun curl -> let msg_split str = List.map String.strip (String.nsplit (String.strip str) "\n") in let curl_debug _ dbg_typ str = let hdr, display = match dbg_typ with | Curl.DEBUGTYPE_TEXT -> "text", true | Curl.DEBUGTYPE_HEADER_IN -> "header-in", true | Curl.DEBUGTYPE_HEADER_OUT -> "header-out", true | Curl.DEBUGTYPE_DATA_IN -> "data-in", true | Curl.DEBUGTYPE_DATA_OUT -> "data-out", false | Curl.DEBUGTYPE_END -> "end", true in if display then List.iter (fun s -> BaseMessage.debug "curl %s: %s" hdr s) (msg_split str) in let answer = Buffer.create 13 in let curl_write d = Buffer.add_string answer d; String.length d in Curl.set_followlocation curl true; (* Curl.set_failonerror curl true; *) Curl.set_verbose curl true; Curl.set_debugfunction curl curl_debug; Curl.set_httpheader curl ["Accept: text/plain"]; Curl.set_writefunction curl curl_write; (* Login *) Curl.set_url curl (* TODO: login/password *) (ODBCurl.uri_concat api_uri "login?login=admin1&password="); Curl.set_cookiefile curl ""; (* Enabled in-memory cookie *) Curl.perform curl; (* Uploads *) let () = let post_params = [Curl.CURLFORM_FILE("tarball", tarball_fn, Curl.DEFAULT)] in let post_params = match publink with | Some uri -> Curl.CURLFORM_CONTENT("publink", uri, Curl.DEFAULT) :: post_params | None -> post_params in let () = Curl.set_url curl (ODBCurl.uri_concat api_uri "upload"); Curl.set_post curl true; Curl.set_httppost curl post_params; Curl.perform curl in let http_code = Curl.get_httpcode curl in let msg_code = Printf.sprintf (f_ "HTTP code %d") http_code in let msg_lst = msg_split (Buffer.contents answer) in if 200 <= http_code && http_code < 400 then begin BaseMessage.debug "%s" msg_code; List.iter (fun s -> BaseMessage.info "%s" s) msg_lst end else begin List.iter (fun s -> BaseMessage.error "%s" s) (msg_code :: msg_lst); failwith (Printf.sprintf (f_ "Error while uploading '%s'") tarball_fn) end; Buffer.clear answer; in Logout Curl.set_url curl (ODBCurl.uri_concat api_uri "logout"); Curl.set_post curl false; Curl.perform curl) let scmd = {(SubCommand.make "upload" (s_ "Upload a tarball to the server") ODBCLIData.upload_mkd main) with scmd_specs = [ "-repo", Arg.String (fun s -> repo := Some s), "str Define the repository to upload to."; "-publink", Arg.String (fun s -> publink := Some s), "uri Define the public URI from where the tarball \ can be downloaded."; ]; scmd_anon = (fun fn -> if !tarball_fn <> None then failwith (Printf.sprintf (f_ "Subcommand upload can only upload a single \ tarball, don't know what to do wit '%s'") fn); tarball_fn := Some fn);} let () = SubCommand.register scmd
null
https://raw.githubusercontent.com/ocaml/oasis-db/f8b19d431102b5c5b7dced00a5242a5366ad263f/src/cli/ODBCLIUpload.ml
ocaml
Curl.set_failonerror curl true; Login TODO: login/password Enabled in-memory cookie Uploads
* ' upload ' subcommand handler Upload a tarball which contains a _ oasis file . @author Upload a tarball which contains a _oasis file. @author Sylvain Le Gall *) open SubCommand open OASISUtils open OASISTypes open ODBGettext open ODBCLICommon open ODBRepository open Lwt open ExtLib let tarball_fn = ref None let repo = ref None let publink = ref None let main () = let ctxt = Lwt_unix.run (context_lwt ()) in let tarball_fn = match !tarball_fn with | Some fn -> fn | None -> failwith (s_ "No tarball to upload") in let publink = !publink in let api_uri = let repo, _ = match !repo with | Some nm -> begin try List.find (fun (repo, _) -> repo.repo_name = nm) ctxt.cli_repos with Not_found -> failwith (Printf.sprintf (f_ "Unable to find repository named '%s'") nm) end | None -> begin try List.find (fun (repo, _) -> repo.repo_api_uri <> None) ctxt.cli_repos with Not_found -> failwith (s_ "Unable to find a repository where upload is allowed") end in match repo.repo_api_uri with | Some uri -> uri | None -> failwith (Printf.sprintf (f_ "Selected repository '%s' doesn't have an API URI set") repo.repo_name) in ODBCurl.with_curl (fun curl -> let msg_split str = List.map String.strip (String.nsplit (String.strip str) "\n") in let curl_debug _ dbg_typ str = let hdr, display = match dbg_typ with | Curl.DEBUGTYPE_TEXT -> "text", true | Curl.DEBUGTYPE_HEADER_IN -> "header-in", true | Curl.DEBUGTYPE_HEADER_OUT -> "header-out", true | Curl.DEBUGTYPE_DATA_IN -> "data-in", true | Curl.DEBUGTYPE_DATA_OUT -> "data-out", false | Curl.DEBUGTYPE_END -> "end", true in if display then List.iter (fun s -> BaseMessage.debug "curl %s: %s" hdr s) (msg_split str) in let answer = Buffer.create 13 in let curl_write d = Buffer.add_string answer d; String.length d in Curl.set_followlocation curl true; Curl.set_verbose curl true; Curl.set_debugfunction curl curl_debug; Curl.set_httpheader curl ["Accept: text/plain"]; Curl.set_writefunction curl curl_write; Curl.set_url curl (ODBCurl.uri_concat api_uri "login?login=admin1&password="); Curl.perform curl; let () = let post_params = [Curl.CURLFORM_FILE("tarball", tarball_fn, Curl.DEFAULT)] in let post_params = match publink with | Some uri -> Curl.CURLFORM_CONTENT("publink", uri, Curl.DEFAULT) :: post_params | None -> post_params in let () = Curl.set_url curl (ODBCurl.uri_concat api_uri "upload"); Curl.set_post curl true; Curl.set_httppost curl post_params; Curl.perform curl in let http_code = Curl.get_httpcode curl in let msg_code = Printf.sprintf (f_ "HTTP code %d") http_code in let msg_lst = msg_split (Buffer.contents answer) in if 200 <= http_code && http_code < 400 then begin BaseMessage.debug "%s" msg_code; List.iter (fun s -> BaseMessage.info "%s" s) msg_lst end else begin List.iter (fun s -> BaseMessage.error "%s" s) (msg_code :: msg_lst); failwith (Printf.sprintf (f_ "Error while uploading '%s'") tarball_fn) end; Buffer.clear answer; in Logout Curl.set_url curl (ODBCurl.uri_concat api_uri "logout"); Curl.set_post curl false; Curl.perform curl) let scmd = {(SubCommand.make "upload" (s_ "Upload a tarball to the server") ODBCLIData.upload_mkd main) with scmd_specs = [ "-repo", Arg.String (fun s -> repo := Some s), "str Define the repository to upload to."; "-publink", Arg.String (fun s -> publink := Some s), "uri Define the public URI from where the tarball \ can be downloaded."; ]; scmd_anon = (fun fn -> if !tarball_fn <> None then failwith (Printf.sprintf (f_ "Subcommand upload can only upload a single \ tarball, don't know what to do wit '%s'") fn); tarball_fn := Some fn);} let () = SubCommand.register scmd
56318c16479f695a52bc97a47f43d707f0f8caf6ca61404183314078ae138f08
pingles/curator
project.clj
(defproject curator "0.0.7" :description "Clojurified Apache Curator" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.apache.curator/curator-recipes "3.2.1"] [org.apache.curator/curator-framework "3.2.1"] [org.apache.curator/curator-x-discovery "3.2.1"]] :profiles {:dev {:dependencies [[org.slf4j/log4j-over-slf4j "1.7.24"] [org.slf4j/slf4j-simple "1.7.24"]] :exclusions [org.slf4j/slf4j-log4j12]}} :scm {:name "git" :url ""})
null
https://raw.githubusercontent.com/pingles/curator/f192b7df74066b3d84fadac4617e40834dd457e5/project.clj
clojure
(defproject curator "0.0.7" :description "Clojurified Apache Curator" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.apache.curator/curator-recipes "3.2.1"] [org.apache.curator/curator-framework "3.2.1"] [org.apache.curator/curator-x-discovery "3.2.1"]] :profiles {:dev {:dependencies [[org.slf4j/log4j-over-slf4j "1.7.24"] [org.slf4j/slf4j-simple "1.7.24"]] :exclusions [org.slf4j/slf4j-log4j12]}} :scm {:name "git" :url ""})
67d80ce0c37bd8d8e20c19cad02a649afac4d166bc2baaa5774d14424a55f9db
uwiger/gproc
gproc_bcast.erl
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- %% -------------------------------------------------- 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. %% -------------------------------------------------- %% @author < > %% %% @doc Gproc message broadcast server %% This module is used to support gproc:bcast(Key, Msg). %% gproc : bcast/2 allows for e.g. distributed publish / subscribe , without %% having to resort to global property registration. To ensure that erlang 's message ordering guarantees are kept , all sends %% are channeled through a broadcast server on each node. %% @end -module(gproc_bcast). -behaviour(gen_server). -export([start_link/0, init/1, handle_cast/2, handle_call/3, handle_info/2, terminate/2, code_change/3]). -include("gproc_int.hrl"). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> {ok, []}. handle_call(_, _, S) -> {reply, {error, unknown_call}, S}. handle_cast({send, Key, Msg}, S) -> ?MAY_FAIL(gproc:send(Key, Msg)), {noreply, S}; handle_cast(_, S) -> {noreply, S}. handle_info(_, S) -> {noreply, S}. terminate(_, _) -> ok. code_change(_, S, _) -> {ok, S}.
null
https://raw.githubusercontent.com/uwiger/gproc/3737f2b958a5908d7a3870046ae162c5b9bf971c/src/gproc_bcast.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. -------------------------------------------------- @doc Gproc message broadcast server This module is used to support gproc:bcast(Key, Msg). having to resort to global property registration. are channeled through a broadcast server on each node. @end
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- 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 @author < > gproc : bcast/2 allows for e.g. distributed publish / subscribe , without To ensure that erlang 's message ordering guarantees are kept , all sends -module(gproc_bcast). -behaviour(gen_server). -export([start_link/0, init/1, handle_cast/2, handle_call/3, handle_info/2, terminate/2, code_change/3]). -include("gproc_int.hrl"). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> {ok, []}. handle_call(_, _, S) -> {reply, {error, unknown_call}, S}. handle_cast({send, Key, Msg}, S) -> ?MAY_FAIL(gproc:send(Key, Msg)), {noreply, S}; handle_cast(_, S) -> {noreply, S}. handle_info(_, S) -> {noreply, S}. terminate(_, _) -> ok. code_change(_, S, _) -> {ok, S}.
adbba56c8206403c0807bb7d2e8897acd0f76d3e4fc814f18d13284c0088725a
project-oak/hafnium-verification
SymOp.mli
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (** Symbolic Operations and Failures: the units in which analysis work is measured *) open! IStd (** Internal state of the module *) type t val check_wallclock_alarm : unit -> unit (** if the wallclock alarm has expired, raise a timeout exception *) val get_remaining_wallclock_time : unit -> float (** Return the time remaining before the wallclock alarm expires *) val get_timeout_seconds : unit -> float option * Timeout in seconds for each function val get_total : unit -> int * Return the total number of symop 's since the beginning val pay : unit -> unit * Count one symop val reset_total : unit -> unit * Reset the total number of symop 's val restore_state : t -> unit (** Restore the old state. *) val save_state : keep_symop_total:bool -> t (** Return the old state, and revert the current state to the initial one. If keep_symop_total is true, share the total counter. *) val set_alarm : unit -> unit (** Reset the counter and activate the alarm *) val set_wallclock_alarm : float -> unit (** Set the wallclock alarm checked at every pay() *) val set_wallclock_timeout_handler : (unit -> unit) -> unit (** set the handler for the wallclock timeout *) val unset_alarm : unit -> unit (** De-activate the alarm *) val unset_wallclock_alarm : unit -> unit (** Unset the wallclock alarm checked at every pay() *) type failure_kind = | FKtimeout (** max time exceeded *) * exceeded | FKrecursion_timeout of int (** max recursion level exceeded *) | FKcrash of string (** uncaught exception or failed assertion *) exception Analysis_failure_exe of failure_kind (** Timeout exception *) val exn_not_failure : exn -> bool (** check that the exception is not a timeout exception *) val try_finally : f:(unit -> 'a) -> finally:(unit -> unit) -> 'a * [ ~f ~finally ] executes [ f ] and then [ finally ] even if [ f ] raises an exception . Assuming that [ finally ( ) ] terminates quickly [ Analysis_failure_exe ] exceptions are handled correctly . In particular , an exception raised by [ f ( ) ] is delayed until [ finally ( ) ] finishes , so [ finally ( ) ] should return reasonably quickly . Assuming that [finally ()] terminates quickly [Analysis_failure_exe] exceptions are handled correctly. In particular, an exception raised by [f ()] is delayed until [finally ()] finishes, so [finally ()] should return reasonably quickly. *) val pp_failure_kind : Format.formatter -> failure_kind -> unit val failure_kind_to_string : failure_kind -> string
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/base/SymOp.mli
ocaml
* Symbolic Operations and Failures: the units in which analysis work is measured * Internal state of the module * if the wallclock alarm has expired, raise a timeout exception * Return the time remaining before the wallclock alarm expires * Restore the old state. * Return the old state, and revert the current state to the initial one. If keep_symop_total is true, share the total counter. * Reset the counter and activate the alarm * Set the wallclock alarm checked at every pay() * set the handler for the wallclock timeout * De-activate the alarm * Unset the wallclock alarm checked at every pay() * max time exceeded * max recursion level exceeded * uncaught exception or failed assertion * Timeout exception * check that the exception is not a timeout exception
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd type t val check_wallclock_alarm : unit -> unit val get_remaining_wallclock_time : unit -> float val get_timeout_seconds : unit -> float option * Timeout in seconds for each function val get_total : unit -> int * Return the total number of symop 's since the beginning val pay : unit -> unit * Count one symop val reset_total : unit -> unit * Reset the total number of symop 's val restore_state : t -> unit val save_state : keep_symop_total:bool -> t val set_alarm : unit -> unit val set_wallclock_alarm : float -> unit val set_wallclock_timeout_handler : (unit -> unit) -> unit val unset_alarm : unit -> unit val unset_wallclock_alarm : unit -> unit type failure_kind = * exceeded exception Analysis_failure_exe of failure_kind val exn_not_failure : exn -> bool val try_finally : f:(unit -> 'a) -> finally:(unit -> unit) -> 'a * [ ~f ~finally ] executes [ f ] and then [ finally ] even if [ f ] raises an exception . Assuming that [ finally ( ) ] terminates quickly [ Analysis_failure_exe ] exceptions are handled correctly . In particular , an exception raised by [ f ( ) ] is delayed until [ finally ( ) ] finishes , so [ finally ( ) ] should return reasonably quickly . Assuming that [finally ()] terminates quickly [Analysis_failure_exe] exceptions are handled correctly. In particular, an exception raised by [f ()] is delayed until [finally ()] finishes, so [finally ()] should return reasonably quickly. *) val pp_failure_kind : Format.formatter -> failure_kind -> unit val failure_kind_to_string : failure_kind -> string
3684b04c844ec6893e7ae99eb054171d15a305d66769ab4c2f588b0cf3911b29
juhp/fbrnch
Commit.hs
module Cmd.Commit ( commitPkgs, ) where import Common import Common.System import Git import Package import Prompt FIXME reject if nvr ahead of newer branch FIXME use branches after all ? FIXME handle multiline changelog entries with " -m description " FIXME --undo last change : eg undo accidential --amend FIXME for single package assume --all if no stage commitPkgs :: Maybe CommitOpt -> Bool -> Bool -> [String] -> IO () commitPkgs mopt firstLine unstaged paths = do when (isJust mopt && firstLine) $ error' "--first-line cannot be used with other commit msg options" if null paths then commitPkg "." else mapM_ commitPkg paths where commitPkg :: FilePath -> IO () commitPkg dir = withExistingDirectory dir $ unlessM isGitDirClean $ do getPackageName dir >>= putPkgHdr addall <- if null paths then null <$> git "diff" ["--cached"] else return unstaged opts <- case mopt of Just opt -> return $ case opt of CommitMsg msg -> ["-m", msg] FIXME reject amend if already pushed CommitAmend -> ["--amend", "--no-edit"] Nothing -> do changelog <- do spec <- findSpecfile clog <- lines <$> cleanChangelog spec case clog of [] -> readCommitMsg [msg] -> putStrLn msg >> return msg msgs -> if firstLine then return $ removePrefix "- " $ head msgs else do diff <- git "diff" ["-U0", if addall then "HEAD" else "--cached"] let newlogs = filter (\c -> ('+' : c) `elem` lines diff) clog case newlogs of [] -> putStrLn diff >> readCommitMsg [msg] -> putStrLn msg >> return (removePrefix "- " msg) (m:ms) -> mapM_ putStrLn newlogs >> return (unlines (removePrefix "- " m:"":ms)) return ["-m", changelog] git_ "commit" $ ["-a" | addall] ++ opts readCommitMsg :: IO String readCommitMsg = do tty <- isTty if tty then do clog <- prompt "\nPlease input the commit message" if null clog then readCommitMsg else return clog else error' "please input commit message in a terminal"
null
https://raw.githubusercontent.com/juhp/fbrnch/521d268e90801366f1fefba995257f18e125a10c/src/Cmd/Commit.hs
haskell
undo last change : eg undo accidential --amend all if no stage
module Cmd.Commit ( commitPkgs, ) where import Common import Common.System import Git import Package import Prompt FIXME reject if nvr ahead of newer branch FIXME use branches after all ? FIXME handle multiline changelog entries with " -m description " commitPkgs :: Maybe CommitOpt -> Bool -> Bool -> [String] -> IO () commitPkgs mopt firstLine unstaged paths = do when (isJust mopt && firstLine) $ error' "--first-line cannot be used with other commit msg options" if null paths then commitPkg "." else mapM_ commitPkg paths where commitPkg :: FilePath -> IO () commitPkg dir = withExistingDirectory dir $ unlessM isGitDirClean $ do getPackageName dir >>= putPkgHdr addall <- if null paths then null <$> git "diff" ["--cached"] else return unstaged opts <- case mopt of Just opt -> return $ case opt of CommitMsg msg -> ["-m", msg] FIXME reject amend if already pushed CommitAmend -> ["--amend", "--no-edit"] Nothing -> do changelog <- do spec <- findSpecfile clog <- lines <$> cleanChangelog spec case clog of [] -> readCommitMsg [msg] -> putStrLn msg >> return msg msgs -> if firstLine then return $ removePrefix "- " $ head msgs else do diff <- git "diff" ["-U0", if addall then "HEAD" else "--cached"] let newlogs = filter (\c -> ('+' : c) `elem` lines diff) clog case newlogs of [] -> putStrLn diff >> readCommitMsg [msg] -> putStrLn msg >> return (removePrefix "- " msg) (m:ms) -> mapM_ putStrLn newlogs >> return (unlines (removePrefix "- " m:"":ms)) return ["-m", changelog] git_ "commit" $ ["-a" | addall] ++ opts readCommitMsg :: IO String readCommitMsg = do tty <- isTty if tty then do clog <- prompt "\nPlease input the commit message" if null clog then readCommitMsg else return clog else error' "please input commit message in a terminal"
4f7acc266dbdc80ab8b1eb9ae48d47ca37649f3e93c0dee1cc816e592cdd3545
dinosaure/pasteur
form.ml
open Tyxml.Html let checkbox ~name ?label:(contents= [ txt name ]) ?(value= "on") ?(checked= false) () = let checked = if checked then [ a_checked () ] else [] in label (input ~a:([ a_input_type `Checkbox ; a_name name ; a_value value ] @ checked) () :: contents) let post_href = Xml.uri_of_string "/" let css_href = Xml.uri_of_string "/pastisserie.css" let pasteur_js_href = Xml.uri_of_string "pasteur.js" let options = let ln = checkbox ~name:"ln" ~label:[ txt "Line numbers" ] () in let raw = checkbox ~name:"raw" ~label:[ txt "Raw paste" ] () in let encrypted = checkbox ~name:"encrypted" ~checked:true ~label:[ txt "Encrypted" ] () in [ ln; raw; encrypted; br () ] let language lst = let lang_id_of_lang = function | None -> "__no_highlighting__" | Some lang -> lang in let fn (name, lang) = option ~a:[ a_value (lang_id_of_lang lang) ] (txt name) in [ select ~a:[ a_name "hl" ] (List.map fn lst); br () ] let name_field = [ label ~a:[ a_label_for "user" ] [ txt "User (optional):"; ] ; br () ; input ~a:[ a_input_type `Text; a_name "user"; a_id "user" ] () ; br () ] let comment_field = [ label ~a:[ a_label_for "comment" ] [ txt "Comment (optional):"; ] ; br () ; input ~a:[ a_input_type `Text; a_name "comment"; a_id "comment" ] () ; br () ] let form lst = form ~a:[ a_id "pasteur" ] ([ input ~a:[ a_input_type `Text; a_name "content"; a_style "display: none;" ] () ; textarea ~a:[ a_name "paste"; a_rows 20; a_cols 80 ] (txt "") ; br () ] @ language lst @ options @ name_field @ comment_field @ [ input ~a:[ a_id "paste"; a_input_type `Button; a_onclick "doPost();"; a_value "Paste!" ] () ]) let html ~title:title_contents ~documentation languages : doc = html (head (title (txt title_contents)) [ meta ~a:[ a_http_equiv "Content-Type"; a_content "text/html; charset=utf-8;" ] () ; script ~a:[ a_src pasteur_js_href ] (txt "") ; link ~rel:[ `Stylesheet ] ~href:css_href () ]) (body [ h1 [ txt title_contents ; space () ; span ~a:[ a_style "font-size: 12px;" ] [ txt documentation ] ] ; form languages ])
null
https://raw.githubusercontent.com/dinosaure/pasteur/9564c66ae53082bc53584737452ddf2a6b8c85e7/form.ml
ocaml
open Tyxml.Html let checkbox ~name ?label:(contents= [ txt name ]) ?(value= "on") ?(checked= false) () = let checked = if checked then [ a_checked () ] else [] in label (input ~a:([ a_input_type `Checkbox ; a_name name ; a_value value ] @ checked) () :: contents) let post_href = Xml.uri_of_string "/" let css_href = Xml.uri_of_string "/pastisserie.css" let pasteur_js_href = Xml.uri_of_string "pasteur.js" let options = let ln = checkbox ~name:"ln" ~label:[ txt "Line numbers" ] () in let raw = checkbox ~name:"raw" ~label:[ txt "Raw paste" ] () in let encrypted = checkbox ~name:"encrypted" ~checked:true ~label:[ txt "Encrypted" ] () in [ ln; raw; encrypted; br () ] let language lst = let lang_id_of_lang = function | None -> "__no_highlighting__" | Some lang -> lang in let fn (name, lang) = option ~a:[ a_value (lang_id_of_lang lang) ] (txt name) in [ select ~a:[ a_name "hl" ] (List.map fn lst); br () ] let name_field = [ label ~a:[ a_label_for "user" ] [ txt "User (optional):"; ] ; br () ; input ~a:[ a_input_type `Text; a_name "user"; a_id "user" ] () ; br () ] let comment_field = [ label ~a:[ a_label_for "comment" ] [ txt "Comment (optional):"; ] ; br () ; input ~a:[ a_input_type `Text; a_name "comment"; a_id "comment" ] () ; br () ] let form lst = form ~a:[ a_id "pasteur" ] ([ input ~a:[ a_input_type `Text; a_name "content"; a_style "display: none;" ] () ; textarea ~a:[ a_name "paste"; a_rows 20; a_cols 80 ] (txt "") ; br () ] @ language lst @ options @ name_field @ comment_field @ [ input ~a:[ a_id "paste"; a_input_type `Button; a_onclick "doPost();"; a_value "Paste!" ] () ]) let html ~title:title_contents ~documentation languages : doc = html (head (title (txt title_contents)) [ meta ~a:[ a_http_equiv "Content-Type"; a_content "text/html; charset=utf-8;" ] () ; script ~a:[ a_src pasteur_js_href ] (txt "") ; link ~rel:[ `Stylesheet ] ~href:css_href () ]) (body [ h1 [ txt title_contents ; space () ; span ~a:[ a_style "font-size: 12px;" ] [ txt documentation ] ] ; form languages ])
7f974cc839a3d2a7567e72fcc8668456efd4612206008f010e7b874d01d8fa25
gethop-dev/hop-cli
grafana.clj
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this ;; file, You can obtain one at / (ns hop-cli.bootstrap.profile.registry.bi.grafana (:require [hop-cli.bootstrap.profile.registry :as registry] [hop-cli.bootstrap.util :as bp.util])) (defn- dashboard-manager-adapter-config [_settings] {:dev.gethop.dashboard-manager/grafana {:uri (tagged-literal 'duct/env ["GRAFANA_URI" 'Str]) :credentials [(tagged-literal 'duct/env ["GRAFANA_USERNAME" 'Str]) (tagged-literal 'duct/env ["GRAFANA_TEST_PASSWORD" 'Str])]}}) (defn- sso-apps-config [] {:sso-apps [{:name (tagged-literal 'duct/env ["OIDC_SSO_APP_1_NAME" 'Str]) :login-url (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGIN_URL" 'Str]) :login-method (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGIN_METHOD" 'Str]) :logout-url (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGOUT_URL" 'Str]) :logout-method (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGOUT_METHOD" 'Str])}]}) (defn- build-external-env-variables [settings env-path] (let [grafana-uri (bp.util/get-settings-value settings (conj env-path :uri)) integration-username (bp.util/get-settings-value settings (conj env-path :app-integration :username)) integration-password (bp.util/get-settings-value settings (conj env-path :app-integration :password)) single-sign-on? (bp.util/get-settings-value settings (conj env-path :sso))] (cond-> {:DS_MANAGER_URI grafana-uri :DS_MANAGER_CREDENTIALS_USER integration-username :DS_MANAGER_CREDENTIALS_PASSWORD integration-password} single-sign-on? (assoc :OIDC_SSO_APP_1_NAME "grafana" :OIDC_SSO_APP_1_LOGIN_METHOD "GET" :OIDC_SSO_APP_1_LOGIN_URL (format "%s/login" grafana-uri) :OIDC_SSO_APP_1_LOGOUT_METHOD "GET" :OIDC_SSO_APP_1_LOGOUT_URL (format "%s/logout" grafana-uri))))) (defn- build-container-env-variables [settings environment env-path] (let [server-domain (bp.util/get-settings-value settings (conj env-path :server-domain))] (cond-> Adapter configuration :DS_MANAGER_URI ":4000" :DS_MANAGER_CREDENTIALS_USER (bp.util/get-settings-value settings (conj env-path :app-integration :username)) :DS_MANAGER_CREDENTIALS_PASSWORD (bp.util/get-settings-value settings (conj env-path :app-integration :password)) ;; Docker :MEMORY_LIMIT_GRAFANA (str (bp.util/get-settings-value settings (conj env-path :memory-limit-mb)) "m") ;; General settings :GF_SECURITY_ALLOW_EMBEDDING "false" :GF_SERVER_DOMAIN (if (= :dev environment) (str "http://" server-domain) (str "https://" server-domain)) :GF_SERVER_HTTP_PORT "4000" :GF_SERVER_ROOT_URL "%(domain)s/grafana/" :GF_SERVER_SERVE_FROM_SUB_PATH "true" :GF_SNAPSHOTS_EXTERNAL_ENABLED "false" :GF_AUTH_ANONYMOUS_ENABLED "false" ;; Admin user :GF_SECURITY_ADMIN_USER (bp.util/get-settings-value settings (conj env-path :admin-user :username)) :GF_SECURITY_ADMIN_PASSWORD (bp.util/get-settings-value settings (conj env-path :admin-user :password)) ;; Database settings :GF_DATABASE_SSL_MODE "disable" :GF_DATABASE_TYPE "postgres" :GF_DATABASE_HOST (format "%s:%s" (bp.util/get-settings-value settings (conj env-path :database :host)) (bp.util/get-settings-value settings (conj env-path :database :port))) :GF_DATABASE_NAME (bp.util/get-settings-value settings (conj env-path :database :name)) :GF_DATABASE_USER (bp.util/get-settings-value settings (conj env-path :database :username)) :GF_DATABASE_PASSWORD (bp.util/get-settings-value settings (conj env-path :database :password)) :GF_DATABASE_SCHEMA (bp.util/get-settings-value settings (conj env-path :database :schema)) ;;OIDC :GF_AUTH_GENERIC_OAUTH_TOKEN_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :token-url)) :GF_AUTH_GENERIC_OAUTH_API_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :api-url)) :GF_AUTH_GENERIC_OAUTH_AUTH_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :auth-url)) :GF_AUTH_SIGNOUT_REDIRECT_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :logout-url)) :GF_AUTH_GENERIC_OAUTH_CLIENT_ID (bp.util/get-settings-value settings (conj env-path :oidc :? :client-id)) :GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET (bp.util/get-settings-value settings (conj env-path :oidc :? :client-secret)) :GF_AUTH_GENERIC_OAUTH_ENABLED "true" :GF_AUTH_GENERIC_OAUTH_ALLOW_SIGN_UP "false" :GF_AUTH_GENERIC_OAUTH_SCOPES "email openid" :GF_AUTH_LOGIN_COOKIE_NAME "grafana_session_cookie" :GF_AUTH_DISABLE_SIGNOUT_MENU "true" :GF_AUTH_GENERIC_OAUTH_SIGN_UP "false"} ;; Single sign on (bp.util/get-settings-value settings (conj env-path :sso)) (assoc :GF_AUTH_OAUTH_AUTO_LOGIN "true" :OIDC_SSO_APP_1_NAME "grafana" :OIDC_SSO_APP_1_LOGIN_METHOD "GET" :OIDC_SSO_APP_1_LOGIN_URL "/grafana/login" :OIDC_SSO_APP_1_LOGOUT_METHOD "GET" :OIDC_SSO_APP_1_LOGOUT_URL "/grafana/logout")))) (defn- build-env-variables [settings environment] (let [env-type (bp.util/get-env-type environment) base-path [:project :profiles :bi-grafana :deployment env-type :?] deployment-type (bp.util/get-settings-value settings (conj base-path :deployment-type)) env-path (conj base-path :environment environment)] (if (= :external deployment-type) (build-external-env-variables settings env-path) (build-container-env-variables settings environment env-path)))) (defn- build-docker-compose-files [settings] (let [common ["docker-compose.grafana.yml"] common-dev-ci ["docker-compose.grafana.common-dev-ci.yml"] ci ["docker-compose.grafana.ci.yml"]] (cond-> {:to-develop [] :ci [] :to-deploy []} (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-develop.?/deployment-type)) (assoc :to-develop (concat common common-dev-ci) :ci (concat common common-dev-ci ci)) (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-deploy.?/deployment-type)) (assoc :to-deploy common)))) (defn- build-docker-files-to-copy [settings] (bp.util/build-profile-docker-files-to-copy (build-docker-compose-files settings) "bi/grafana/" [{:src "bi/grafana/grafana" :dst "grafana"} {:src "bi/grafana/proxy" :dst "proxy"}])) (defn- build-outputs [settings] {:deployment {:to-develop {:container {:depends-on-postgres? (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-develop.container/db-deployment-type))}} :to-deploy {:container {:depends-on-postgres? (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-deploy.container/db-deployment-type))}}}}) (defmethod registry/pre-render-hook :bi-grafana [_ settings] {:dependencies '[[dev.gethop/dashboard-manager.grafana "0.2.8"]] :config-edn {:base (dashboard-manager-adapter-config settings) :config (sso-apps-config)} :environment-variables {:dev (build-env-variables settings :dev) :test (build-env-variables settings :test) :prod (build-env-variables settings :prod)} :files (build-docker-files-to-copy settings) :docker-compose (build-docker-compose-files settings) :extra-app-docker-compose-environment-variables ["OIDC_SSO_APP_1_NAME" "OIDC_SSO_APP_1_LOGIN_URL" "OIDC_SSO_APP_1_LOGIN_METHOD" "OIDC_SSO_APP_1_LOGOUT_URL" "OIDC_SSO_APP_1_LOGOUT_METHOD"] :outputs (build-outputs settings)})
null
https://raw.githubusercontent.com/gethop-dev/hop-cli/0b3240371fd2b7fbedf29d7420ce860619cc4f24/src/hop_cli/bootstrap/profile/registry/bi/grafana.clj
clojure
file, You can obtain one at / Docker General settings Admin user Database settings OIDC Single sign on
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this (ns hop-cli.bootstrap.profile.registry.bi.grafana (:require [hop-cli.bootstrap.profile.registry :as registry] [hop-cli.bootstrap.util :as bp.util])) (defn- dashboard-manager-adapter-config [_settings] {:dev.gethop.dashboard-manager/grafana {:uri (tagged-literal 'duct/env ["GRAFANA_URI" 'Str]) :credentials [(tagged-literal 'duct/env ["GRAFANA_USERNAME" 'Str]) (tagged-literal 'duct/env ["GRAFANA_TEST_PASSWORD" 'Str])]}}) (defn- sso-apps-config [] {:sso-apps [{:name (tagged-literal 'duct/env ["OIDC_SSO_APP_1_NAME" 'Str]) :login-url (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGIN_URL" 'Str]) :login-method (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGIN_METHOD" 'Str]) :logout-url (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGOUT_URL" 'Str]) :logout-method (tagged-literal 'duct/env ["OIDC_SSO_APP_1_LOGOUT_METHOD" 'Str])}]}) (defn- build-external-env-variables [settings env-path] (let [grafana-uri (bp.util/get-settings-value settings (conj env-path :uri)) integration-username (bp.util/get-settings-value settings (conj env-path :app-integration :username)) integration-password (bp.util/get-settings-value settings (conj env-path :app-integration :password)) single-sign-on? (bp.util/get-settings-value settings (conj env-path :sso))] (cond-> {:DS_MANAGER_URI grafana-uri :DS_MANAGER_CREDENTIALS_USER integration-username :DS_MANAGER_CREDENTIALS_PASSWORD integration-password} single-sign-on? (assoc :OIDC_SSO_APP_1_NAME "grafana" :OIDC_SSO_APP_1_LOGIN_METHOD "GET" :OIDC_SSO_APP_1_LOGIN_URL (format "%s/login" grafana-uri) :OIDC_SSO_APP_1_LOGOUT_METHOD "GET" :OIDC_SSO_APP_1_LOGOUT_URL (format "%s/logout" grafana-uri))))) (defn- build-container-env-variables [settings environment env-path] (let [server-domain (bp.util/get-settings-value settings (conj env-path :server-domain))] (cond-> Adapter configuration :DS_MANAGER_URI ":4000" :DS_MANAGER_CREDENTIALS_USER (bp.util/get-settings-value settings (conj env-path :app-integration :username)) :DS_MANAGER_CREDENTIALS_PASSWORD (bp.util/get-settings-value settings (conj env-path :app-integration :password)) :MEMORY_LIMIT_GRAFANA (str (bp.util/get-settings-value settings (conj env-path :memory-limit-mb)) "m") :GF_SECURITY_ALLOW_EMBEDDING "false" :GF_SERVER_DOMAIN (if (= :dev environment) (str "http://" server-domain) (str "https://" server-domain)) :GF_SERVER_HTTP_PORT "4000" :GF_SERVER_ROOT_URL "%(domain)s/grafana/" :GF_SERVER_SERVE_FROM_SUB_PATH "true" :GF_SNAPSHOTS_EXTERNAL_ENABLED "false" :GF_AUTH_ANONYMOUS_ENABLED "false" :GF_SECURITY_ADMIN_USER (bp.util/get-settings-value settings (conj env-path :admin-user :username)) :GF_SECURITY_ADMIN_PASSWORD (bp.util/get-settings-value settings (conj env-path :admin-user :password)) :GF_DATABASE_SSL_MODE "disable" :GF_DATABASE_TYPE "postgres" :GF_DATABASE_HOST (format "%s:%s" (bp.util/get-settings-value settings (conj env-path :database :host)) (bp.util/get-settings-value settings (conj env-path :database :port))) :GF_DATABASE_NAME (bp.util/get-settings-value settings (conj env-path :database :name)) :GF_DATABASE_USER (bp.util/get-settings-value settings (conj env-path :database :username)) :GF_DATABASE_PASSWORD (bp.util/get-settings-value settings (conj env-path :database :password)) :GF_DATABASE_SCHEMA (bp.util/get-settings-value settings (conj env-path :database :schema)) :GF_AUTH_GENERIC_OAUTH_TOKEN_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :token-url)) :GF_AUTH_GENERIC_OAUTH_API_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :api-url)) :GF_AUTH_GENERIC_OAUTH_AUTH_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :auth-url)) :GF_AUTH_SIGNOUT_REDIRECT_URL (bp.util/get-settings-value settings (conj env-path :oidc :? :logout-url)) :GF_AUTH_GENERIC_OAUTH_CLIENT_ID (bp.util/get-settings-value settings (conj env-path :oidc :? :client-id)) :GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET (bp.util/get-settings-value settings (conj env-path :oidc :? :client-secret)) :GF_AUTH_GENERIC_OAUTH_ENABLED "true" :GF_AUTH_GENERIC_OAUTH_ALLOW_SIGN_UP "false" :GF_AUTH_GENERIC_OAUTH_SCOPES "email openid" :GF_AUTH_LOGIN_COOKIE_NAME "grafana_session_cookie" :GF_AUTH_DISABLE_SIGNOUT_MENU "true" :GF_AUTH_GENERIC_OAUTH_SIGN_UP "false"} (bp.util/get-settings-value settings (conj env-path :sso)) (assoc :GF_AUTH_OAUTH_AUTO_LOGIN "true" :OIDC_SSO_APP_1_NAME "grafana" :OIDC_SSO_APP_1_LOGIN_METHOD "GET" :OIDC_SSO_APP_1_LOGIN_URL "/grafana/login" :OIDC_SSO_APP_1_LOGOUT_METHOD "GET" :OIDC_SSO_APP_1_LOGOUT_URL "/grafana/logout")))) (defn- build-env-variables [settings environment] (let [env-type (bp.util/get-env-type environment) base-path [:project :profiles :bi-grafana :deployment env-type :?] deployment-type (bp.util/get-settings-value settings (conj base-path :deployment-type)) env-path (conj base-path :environment environment)] (if (= :external deployment-type) (build-external-env-variables settings env-path) (build-container-env-variables settings environment env-path)))) (defn- build-docker-compose-files [settings] (let [common ["docker-compose.grafana.yml"] common-dev-ci ["docker-compose.grafana.common-dev-ci.yml"] ci ["docker-compose.grafana.ci.yml"]] (cond-> {:to-develop [] :ci [] :to-deploy []} (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-develop.?/deployment-type)) (assoc :to-develop (concat common common-dev-ci) :ci (concat common common-dev-ci ci)) (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-deploy.?/deployment-type)) (assoc :to-deploy common)))) (defn- build-docker-files-to-copy [settings] (bp.util/build-profile-docker-files-to-copy (build-docker-compose-files settings) "bi/grafana/" [{:src "bi/grafana/grafana" :dst "grafana"} {:src "bi/grafana/proxy" :dst "proxy"}])) (defn- build-outputs [settings] {:deployment {:to-develop {:container {:depends-on-postgres? (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-develop.container/db-deployment-type))}} :to-deploy {:container {:depends-on-postgres? (= :container (bp.util/get-settings-value settings :project.profiles.bi-grafana.deployment.to-deploy.container/db-deployment-type))}}}}) (defmethod registry/pre-render-hook :bi-grafana [_ settings] {:dependencies '[[dev.gethop/dashboard-manager.grafana "0.2.8"]] :config-edn {:base (dashboard-manager-adapter-config settings) :config (sso-apps-config)} :environment-variables {:dev (build-env-variables settings :dev) :test (build-env-variables settings :test) :prod (build-env-variables settings :prod)} :files (build-docker-files-to-copy settings) :docker-compose (build-docker-compose-files settings) :extra-app-docker-compose-environment-variables ["OIDC_SSO_APP_1_NAME" "OIDC_SSO_APP_1_LOGIN_URL" "OIDC_SSO_APP_1_LOGIN_METHOD" "OIDC_SSO_APP_1_LOGOUT_URL" "OIDC_SSO_APP_1_LOGOUT_METHOD"] :outputs (build-outputs settings)})
1af8854f75cf7bd6af0e848fb4943115c142280a05ae0e76eab2fffad1ca390b
silviucpp/erlxml
erlxml_nif.erl
-module(erlxml_nif). -author("silviu.caragea"). -define(NOT_LOADED, not_loaded(?LINE)). Maximum bytes passed to the NIF handler at once ( 20Kb ) -define(MAX_BYTES_TO_NIF, 20000). -on_load(load_nif/0). -export([ new_stream/1, chunk_feed_stream/2, reset_stream/1, dom_parse/1, to_binary/1 ]). %% nif functions load_nif() -> SoName = get_nif_library_path(), io:format(<<"Loading library: ~p ~n">>, [SoName]), ok = erlang:load_nif(SoName, 0). get_nif_library_path() -> case code:priv_dir(erlxml) of {error, bad_name} -> case filelib:is_dir(filename:join(["..", priv])) of true -> filename:join(["..", priv, ?MODULE]); false -> filename:join([priv, ?MODULE]) end; Dir -> filename:join(Dir, ?MODULE) end. not_loaded(Line) -> erlang:nif_error({not_loaded, [{module, ?MODULE}, {line, Line}]}). new_stream(_Opts) -> ?NOT_LOADED. feed_stream(_Parser, _Data) -> ?NOT_LOADED. reset_stream(_Parser) -> ?NOT_LOADED. dom_parse(_Data) -> ?NOT_LOADED. to_binary(_Data) -> ?NOT_LOADED. chunk_feed_stream(Parser, Data) when is_binary(Data) -> chunk_feed_stream(Parser, Data, byte_size(Data), null); chunk_feed_stream(Parser, Data) -> chunk_feed_stream(Parser, iolist_to_binary(Data)). chunk_feed_stream(Parser, Data, Size, Acc) -> case Size > ?MAX_BYTES_TO_NIF of true -> <<Chunk:?MAX_BYTES_TO_NIF/binary, Rest/binary>> = Data, case feed_stream(Parser, Chunk) of {ok, Elements} -> chunk_feed_stream(Parser, Rest, Size - ?MAX_BYTES_TO_NIF, aggregate_els(Acc, Elements)); Error -> Error end; _ -> case feed_stream(Parser, Data) of {ok, Elements} -> {ok, aggregate_els(Acc, Elements)}; Error -> Error end end. aggregate_els(null, Els) -> Els; aggregate_els(Acc, Els) -> Els ++ Acc.
null
https://raw.githubusercontent.com/silviucpp/erlxml/caa7ed198f6e8569b6e058047394f3799a38fec7/src/erlxml_nif.erl
erlang
nif functions
-module(erlxml_nif). -author("silviu.caragea"). -define(NOT_LOADED, not_loaded(?LINE)). Maximum bytes passed to the NIF handler at once ( 20Kb ) -define(MAX_BYTES_TO_NIF, 20000). -on_load(load_nif/0). -export([ new_stream/1, chunk_feed_stream/2, reset_stream/1, dom_parse/1, to_binary/1 ]). load_nif() -> SoName = get_nif_library_path(), io:format(<<"Loading library: ~p ~n">>, [SoName]), ok = erlang:load_nif(SoName, 0). get_nif_library_path() -> case code:priv_dir(erlxml) of {error, bad_name} -> case filelib:is_dir(filename:join(["..", priv])) of true -> filename:join(["..", priv, ?MODULE]); false -> filename:join([priv, ?MODULE]) end; Dir -> filename:join(Dir, ?MODULE) end. not_loaded(Line) -> erlang:nif_error({not_loaded, [{module, ?MODULE}, {line, Line}]}). new_stream(_Opts) -> ?NOT_LOADED. feed_stream(_Parser, _Data) -> ?NOT_LOADED. reset_stream(_Parser) -> ?NOT_LOADED. dom_parse(_Data) -> ?NOT_LOADED. to_binary(_Data) -> ?NOT_LOADED. chunk_feed_stream(Parser, Data) when is_binary(Data) -> chunk_feed_stream(Parser, Data, byte_size(Data), null); chunk_feed_stream(Parser, Data) -> chunk_feed_stream(Parser, iolist_to_binary(Data)). chunk_feed_stream(Parser, Data, Size, Acc) -> case Size > ?MAX_BYTES_TO_NIF of true -> <<Chunk:?MAX_BYTES_TO_NIF/binary, Rest/binary>> = Data, case feed_stream(Parser, Chunk) of {ok, Elements} -> chunk_feed_stream(Parser, Rest, Size - ?MAX_BYTES_TO_NIF, aggregate_els(Acc, Elements)); Error -> Error end; _ -> case feed_stream(Parser, Data) of {ok, Elements} -> {ok, aggregate_els(Acc, Elements)}; Error -> Error end end. aggregate_els(null, Els) -> Els; aggregate_els(Acc, Els) -> Els ++ Acc.
e5e5f4209f3fe598c3fd913c2c93808232ce291e3688ae4599e863b02da362ed
Helium4Haskell/helium
PropagateEq.hs
data A = A | B deriving Eq f x y = x == y main = f A B
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/correct/PropagateEq.hs
haskell
data A = A | B deriving Eq f x y = x == y main = f A B
d5bf2b9de5d50f4738de0c02173ddda7e4d68e17d20506170a6747670682add1
spell-music/csound-expression
ModArg.hs
# Language TypeFamilies , TypeSynonymInstances , MultiParamTypeClasses , FlexibleInstances , FlexibleContexts # -- | Argument modifiers. Functions to transform arguments of the function with flexibility. module Csound.Air.ModArg( -- * Basic class ModArg1(..), ModArg2(..), ModArg3(..), ModArg4(..), -- ** Delayed delModArg1, delModArg2, delModArg3, delModArg4, -- * Oscillators oscArg1, oscArg2, oscArg3, oscArg4, triArg1, triArg2, triArg3, triArg4, sqrArg1, sqrArg2, sqrArg3, sqrArg4, sawArg1, sawArg2, sawArg3, sawArg4, -- ** Random phase rndOscArg1, rndOscArg2, rndOscArg3, rndOscArg4, rndTriArg1, rndTriArg2, rndTriArg3, rndTriArg4, rndSqrArg1, rndSqrArg2, rndSqrArg3, rndSqrArg4, rndSawArg1, rndSawArg2, rndSawArg3, rndSawArg4, -- ** Delayed delOscArg1, delOscArg2, delOscArg3, delOscArg4, delTriArg1, delTriArg2, delTriArg3, delTriArg4, delSqrArg1, delSqrArg2, delSqrArg3, delSqrArg4, delSawArg1, delSawArg2, delSawArg3, delSawArg4, -- ** Delayed with Random phase delRndOscArg1, delRndOscArg2, delRndOscArg3, delRndOscArg4, delRndTriArg1, delRndTriArg2, delRndTriArg3, delRndTriArg4, delRndSqrArg1, delRndSqrArg2, delRndSqrArg3, delRndSqrArg4, delRndSawArg1, delRndSawArg2, delRndSawArg3, delRndSawArg4, -- * Noise noiseArg1, noiseArg2, noiseArg3, noiseArg4, pinkArg1, pinkArg2, pinkArg3, pinkArg4, jitArg1, jitArg2, jitArg3, jitArg4, gaussArg1, gaussArg2, gaussArg3, gaussArg4, gaussiArg1, gaussiArg2, gaussiArg3, gaussiArg4, -- ** Delayed delNoiseArg1, delNoiseArg2, delNoiseArg3, delNoiseArg4, delPinkArg1, delPinkArg2, delPinkArg3, delPinkArg4, delJitArg1, delJitArg2, delJitArg3, delJitArg4, delGaussArg1, delGaussArg2, delGaussArg3, delGaussArg4, delGaussiArg1, delGaussiArg2, delGaussiArg3, delGaussiArg4, -- * Envelopes adsrArg1, adsrArg2, adsrArg3, adsrArg4, xadsrArg1, xadsrArg2, xadsrArg3, xadsrArg4, -- ** Delayed delAdsrArg1, delAdsrArg2, delAdsrArg3, delAdsrArg4, delXadsrArg1, delXadsrArg2, delXadsrArg3, delXadsrArg4 ) where import Data.Kind (Type) import Csound.Typed import Csound.Typed.Opcode(gauss, gaussi, jitter, linseg, linsegr, expsegr) import Csound.Air.Wave import Csound.Air.Envelope -- trumpet: dac $ mul 1.3 $ mixAt 0.15 largeHall2 $ midi $ onMsg ( \cps - > ( ( linsegr [ 0,0.01 , 1 , 3 , 0.2 ] 0.2 0 ) . at ( ( 0.15 + 0.05 * uosc 0.2 ) 3 20 alp1 ( ( fades 0.2 0.2 ) $ 2700 + 0.6 * cps ) 0.2 ) . gaussArg1 0.03 ( \x - > return ( saw x ) + mul ( 0.12 * expseg [ 1 , 2 , 0.1 ] ) ( bat ( alp1 cps 0.4 ) white ) ) ) cps ) delEnv :: SigSpace a => D -> D -> a -> a delEnv delTime riseTime asig = mul (linseg [0, delTime, 0, riseTime, 1]) asig delModArg1 :: (SigSpace a, ModArg1 a b) => D -> D -> Sig -> a -> b -> ModArgOut1 a b delModArg1 delTime riseTime depth modSig f = modArg1 (delEnv delTime riseTime depth) modSig f delModArg2 :: (SigSpace a, ModArg2 a b) => D -> D -> Sig -> a -> b -> ModArgOut2 a b delModArg2 delTime riseTime depth modSig f = modArg2 (delEnv delTime riseTime depth) modSig f delModArg3 :: (SigSpace a, ModArg3 a b) => D -> D -> Sig -> a -> b -> ModArgOut3 a b delModArg3 delTime riseTime depth modSig f = modArg3 (delEnv delTime riseTime depth) modSig f delModArg4 :: (SigSpace a, ModArg4 a b) => D -> D -> Sig -> a -> b -> ModArgOut4 a b delModArg4 delTime riseTime depth modSig f = modArg4 (delEnv delTime riseTime depth) modSig f -- adsr mod adsrArg1 :: (ModArg1 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b adsrArg1 depth a d s r f = modArg1 depth (leg a d s r) f adsrArg2 :: (ModArg2 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b adsrArg2 depth a d s r f = modArg2 depth (leg a d s r) f adsrArg3 :: (ModArg3 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b adsrArg3 depth a d s r f = modArg3 depth (leg a d s r) f adsrArg4 :: (ModArg4 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b adsrArg4 depth a d s r f = modArg4 depth (leg a d s r) f -- delayed adsr mod delLeg :: D -> D -> D -> D -> D -> Sig delLeg delTime a d s r = linsegr [0, delTime, 0, a, 1, d, s] r 0 delAdsrArg1 :: (ModArg1 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b delAdsrArg1 delTime depth a d s r f = modArg1 depth (delLeg delTime a d s r) f delAdsrArg2 :: (ModArg2 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b delAdsrArg2 delTime depth a d s r f = modArg2 depth (delLeg delTime a d s r) f delAdsrArg3 :: (ModArg3 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b delAdsrArg3 delTime depth a d s r f = modArg3 depth (delLeg delTime a d s r) f delAdsrArg4 :: (ModArg4 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b delAdsrArg4 delTime depth a d s r f = modArg4 depth (delLeg delTime a d s r) f -- expon adsr mod xadsrArg1 :: (ModArg1 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b xadsrArg1 depth a d s r f = modArg1 depth (xeg a d s r) f xadsrArg2 :: (ModArg2 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b xadsrArg2 depth a d s r f = modArg2 depth (xeg a d s r) f xadsrArg3 :: (ModArg3 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b xadsrArg3 depth a d s r f = modArg3 depth (xeg a d s r) f xadsrArg4 :: (ModArg4 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b xadsrArg4 depth a d s r f = modArg4 depth (xeg a d s r) f -- delayed expon adsr mod delXeg :: D -> D -> D -> D -> D -> Sig delXeg delTime a d s r = expsegr [0.001, delTime, 0.001, a, 1, d, s] r 0.001 delXadsrArg1 :: (ModArg1 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b delXadsrArg1 delTime depth a d s r f = modArg1 depth (delXeg delTime a d s r) f delXadsrArg2 :: (ModArg2 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b delXadsrArg2 delTime depth a d s r f = modArg2 depth (delXeg delTime a d s r) f delXadsrArg3 :: (ModArg3 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b delXadsrArg3 delTime depth a d s r f = modArg3 depth (delXeg delTime a d s r) f delXadsrArg4 :: (ModArg4 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b delXadsrArg4 delTime depth a d s r f = modArg4 depth (delXeg delTime a d s r) f -- oscil lfo oscArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b oscArg1 depth rate f = modArg1 depth (osc rate) f oscArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b oscArg2 depth rate f = modArg2 depth (osc rate) f oscArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b oscArg3 depth rate f = modArg3 depth (osc rate) f oscArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b oscArg4 depth rate f = modArg4 depth (osc rate) f delayed oscil lfo delOscArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delOscArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (osc rate) f delOscArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delOscArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (osc rate) f delOscArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delOscArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (osc rate) f delOscArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delOscArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (osc rate) f -- tri lfo triArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b triArg1 depth rate f = modArg1 depth (tri rate) f triArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b triArg2 depth rate f = modArg2 depth (tri rate) f triArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b triArg3 depth rate f = modArg3 depth (tri rate) f triArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b triArg4 depth rate f = modArg4 depth (tri rate) f -- delayed tri lfo delTriArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delTriArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (tri rate) f delTriArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delTriArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (tri rate) f delTriArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delTriArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (tri rate) f delTriArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delTriArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (tri rate) f -- sqr lfo sqrArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b sqrArg1 depth rate f = modArg1 depth (sqr rate) f sqrArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b sqrArg2 depth rate f = modArg2 depth (sqr rate) f sqrArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b sqrArg3 depth rate f = modArg3 depth (sqr rate) f sqrArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b sqrArg4 depth rate f = modArg4 depth (sqr rate) f -- sqr lfo delSqrArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delSqrArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (sqr rate) f delSqrArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delSqrArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (sqr rate) f delSqrArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delSqrArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (sqr rate) f delSqrArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delSqrArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (sqr rate) f -- saw lfo sawArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b sawArg1 depth rate f = modArg1 depth (saw rate) f sawArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b sawArg2 depth rate f = modArg2 depth (saw rate) f sawArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b sawArg3 depth rate f = modArg3 depth (saw rate) f sawArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b sawArg4 depth rate f = modArg4 depth (saw rate) f -- delayed saw lfo delSawArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delSawArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (saw rate) f delSawArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delSawArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (saw rate) f delSawArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delSawArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (saw rate) f delSawArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delSawArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (saw rate) f oscil lfo rnd phase rndOscArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndOscArg1 depth rate f = modArg1 depth (rndOsc rate) f rndOscArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndOscArg2 depth rate f = modArg2 depth (rndOsc rate) f rndOscArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndOscArg3 depth rate f = modArg3 depth (rndOsc rate) f rndOscArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndOscArg4 depth rate f = modArg4 depth (rndOsc rate) f delayed oscil lfo rnd phase delRndOscArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndOscArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndOsc rate) f delRndOscArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndOscArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndOsc rate) f delRndOscArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndOscArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndOsc rate) f delRndOscArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndOscArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndOsc rate) f tri lfo rnd phase rndTriArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndTriArg1 depth rate f = modArg1 depth (rndTri rate) f rndTriArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndTriArg2 depth rate f = modArg2 depth (rndTri rate) f rndTriArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndTriArg3 depth rate f = modArg3 depth (rndTri rate) f rndTriArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndTriArg4 depth rate f = modArg4 depth (rndTri rate) f delayed tri lfo rnd phase delRndTriArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndTriArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndTri rate) f delRndTriArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndTriArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndTri rate) f delRndTriArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndTriArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndTri rate) f delRndTriArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndTriArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndTri rate) f sqr lfo rnd phase rndSqrArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndSqrArg1 depth rate f = modArg1 depth (rndSqr rate) f rndSqrArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndSqrArg2 depth rate f = modArg2 depth (rndSqr rate) f rndSqrArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndSqrArg3 depth rate f = modArg3 depth (rndSqr rate) f rndSqrArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndSqrArg4 depth rate f = modArg4 depth (rndSqr rate) f sqr lfo rnd phase delRndSqrArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndSqrArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndSqr rate) f delRndSqrArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndSqrArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndSqr rate) f delRndSqrArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndSqrArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndSqr rate) f delRndSqrArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndSqrArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndSqr rate) f sqr lfo rnd phase rndSawArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndSawArg1 depth rate f = modArg1 depth (rndSaw rate) f rndSawArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndSawArg2 depth rate f = modArg2 depth (rndSaw rate) f rndSawArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndSawArg3 depth rate f = modArg3 depth (rndSaw rate) f rndSawArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndSawArg4 depth rate f = modArg4 depth (rndSaw rate) f delayed sqr lfo rnd phase delRndSawArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndSawArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndSaw rate) f delRndSawArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndSawArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndSaw rate) f delRndSawArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndSawArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndSaw rate) f delRndSawArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndSawArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndSaw rate) f -- white noise noiseArg1 :: (ModArg1 (SE Sig) b) => Sig -> b -> ModArgOut1 (SE Sig) b noiseArg1 depth f = modArg1 depth white f noiseArg2 :: (ModArg2 (SE Sig) b) => Sig -> b -> ModArgOut2 (SE Sig) b noiseArg2 depth f = modArg2 depth white f noiseArg3 :: (ModArg3 (SE Sig) b) => Sig -> b -> ModArgOut3 (SE Sig) b noiseArg3 depth f = modArg3 depth white f noiseArg4 :: (ModArg4 (SE Sig) b) => Sig -> b -> ModArgOut4 (SE Sig) b noiseArg4 depth f = modArg4 depth white f -- delayed white noise delNoiseArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut1 (SE Sig) b delNoiseArg1 delTime riseTime depth f = delModArg1 delTime riseTime depth white f delNoiseArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut2 (SE Sig) b delNoiseArg2 delTime riseTime depth f = delModArg2 delTime riseTime depth white f delNoiseArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut3 (SE Sig) b delNoiseArg3 delTime riseTime depth f = delModArg3 delTime riseTime depth white f delNoiseArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut4 (SE Sig) b delNoiseArg4 delTime riseTime depth f = delModArg4 delTime riseTime depth white f -- pink noise pinkArg1 :: (ModArg1 (SE Sig) b) => Sig -> b -> ModArgOut1 (SE Sig) b pinkArg1 depth f = modArg1 depth pink f pinkArg2 :: (ModArg2 (SE Sig) b) => Sig -> b -> ModArgOut2 (SE Sig) b pinkArg2 depth f = modArg2 depth pink f pinkArg3 :: (ModArg3 (SE Sig) b) => Sig -> b -> ModArgOut3 (SE Sig) b pinkArg3 depth f = modArg3 depth pink f pinkArg4 :: (ModArg4 (SE Sig) b) => Sig -> b -> ModArgOut4 (SE Sig) b pinkArg4 depth f = modArg4 depth pink f -- pink noise delPinkArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut1 (SE Sig) b delPinkArg1 delTime riseTime depth f = delModArg1 delTime riseTime depth pink f delPinkArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut2 (SE Sig) b delPinkArg2 delTime riseTime depth f = delModArg2 delTime riseTime depth pink f delPinkArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut3 (SE Sig) b delPinkArg3 delTime riseTime depth f = delModArg3 delTime riseTime depth pink f delPinkArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut4 (SE Sig) b delPinkArg4 delTime riseTime depth f = delModArg4 delTime riseTime depth pink f -- jitter noise jitArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b jitArg1 depth cpsMin cpsMax f = modArg1 depth (jitter 1 cpsMin cpsMax) f jitArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b jitArg2 depth cpsMin cpsMax f = modArg2 depth (jitter 1 cpsMin cpsMax) f jitArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b jitArg3 depth cpsMin cpsMax f = modArg3 depth (jitter 1 cpsMin cpsMax) f jitArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b jitArg4 depth cpsMin cpsMax f = modArg4 depth (jitter 1 cpsMin cpsMax) f -- jitter noise delJitArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delJitArg1 delTime riseTime depth cpsMin cpsMax f = delModArg1 delTime riseTime depth (jitter 1 cpsMin cpsMax) f delJitArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delJitArg2 delTime riseTime depth cpsMin cpsMax f = delModArg2 delTime riseTime depth (jitter 1 cpsMin cpsMax) f delJitArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delJitArg3 delTime riseTime depth cpsMin cpsMax f = delModArg3 delTime riseTime depth (jitter 1 cpsMin cpsMax) f delJitArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delJitArg4 delTime riseTime depth cpsMin cpsMax f = delModArg4 delTime riseTime depth (jitter 1 cpsMin cpsMax) f -- gauss noise gaussArg1 :: (ModArg1 (SE Sig) b) => Sig -> b -> ModArgOut1 (SE Sig) b gaussArg1 depth f = modArg1 depth (gauss 1) f gaussArg2 :: (ModArg2 (SE Sig) b) => Sig -> b -> ModArgOut2 (SE Sig) b gaussArg2 depth f = modArg2 depth (gauss 1) f gaussArg3 :: (ModArg3 (SE Sig) b) => Sig -> b -> ModArgOut3 (SE Sig) b gaussArg3 depth f = modArg3 depth (gauss 1) f gaussArg4 :: (ModArg4 (SE Sig) b) => Sig -> b -> ModArgOut4 (SE Sig) b gaussArg4 depth f = modArg4 depth (gauss 1) f -- delayed gauss noise delGaussArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut1 (SE Sig) b delGaussArg1 delTime riseTime depth f = delModArg1 delTime riseTime depth (gauss 1) f delGaussArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut2 (SE Sig) b delGaussArg2 delTime riseTime depth f = delModArg2 delTime riseTime depth (gauss 1) f delGaussArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut3 (SE Sig) b delGaussArg3 delTime riseTime depth f = delModArg3 delTime riseTime depth (gauss 1) f delGaussArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut4 (SE Sig) b delGaussArg4 delTime riseTime depth f = delModArg4 delTime riseTime depth (gauss 1) f -- gauss noise with frequency gaussiArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b gaussiArg1 depth rate f = modArg1 depth (gaussi 1 1 rate) f gaussiArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b gaussiArg2 depth rate f = modArg2 depth (gaussi 1 1 rate) f gaussiArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b gaussiArg3 depth rate f = modArg3 depth (gaussi 1 1 rate) f gaussiArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b gaussiArg4 depth rate f = modArg4 depth (gaussi 1 1 rate) f -- delayed gauss noise with frequency delGaussiArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delGaussiArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (gaussi 1 1 rate) f delGaussiArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delGaussiArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (gaussi 1 1 rate) f delGaussiArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delGaussiArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (gaussi 1 1 rate) f delGaussiArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delGaussiArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (gaussi 1 1 rate) f -------------------------------------------- -------------------------------------------- -- modArg1 class ModArg1 a b where type ModArgOut1 a b :: Type modArg1 :: Sig -> a -> b -> ModArgOut1 a b -------------------------------------------- -- pure in, pure mono out instance ModArg1 Sig (Sig -> Sig) where type ModArgOut1 Sig (Sig -> Sig) = Sig -> Sig modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> Sig) where type ModArgOut1 Sig (Sig -> a -> Sig) = Sig -> a -> Sig modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> Sig) where type ModArgOut1 Sig (Sig -> a -> b -> Sig) = Sig -> a -> b -> Sig modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> Sig) where type ModArgOut1 Sig (Sig -> a -> b -> c -> Sig) = Sig -> a -> b -> c -> Sig modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 -------------------------------------------- -- pure in, pure stereo out instance ModArg1 Sig (Sig -> Sig2) where type ModArgOut1 Sig (Sig -> Sig2) = Sig -> Sig2 modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> Sig2) where type ModArgOut1 Sig (Sig -> a -> Sig2) = Sig -> a -> Sig2 modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> Sig2) = Sig -> a -> b -> Sig2 modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> c -> Sig2) = Sig -> a -> b -> c -> Sig2 modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 -------------------------------------------- -- pure in, dirty mono out instance ModArg1 Sig (Sig -> SE Sig) where type ModArgOut1 Sig (Sig -> SE Sig) = Sig -> SE Sig modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> SE Sig) where type ModArgOut1 Sig (Sig -> a -> SE Sig) = Sig -> a -> SE Sig modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> SE Sig) where type ModArgOut1 Sig (Sig -> a -> b -> SE Sig) = Sig -> a -> b -> SE Sig modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> SE Sig) where type ModArgOut1 Sig (Sig -> a -> b -> c -> SE Sig) = Sig -> a -> b -> c -> SE Sig modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 -------------------------------------------- -- pure in, dirty stereo out instance ModArg1 Sig (Sig -> SE Sig2) where type ModArgOut1 Sig (Sig -> SE Sig2) = Sig -> SE Sig2 modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> SE Sig2) where type ModArgOut1 Sig (Sig -> a -> SE Sig2) = Sig -> a -> SE Sig2 modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> SE Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> SE Sig2) = Sig -> a -> b -> SE Sig2 modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> SE Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> c -> SE Sig2) = Sig -> a -> b -> c -> SE Sig2 modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 -------------------------------------------- -- dirty in, pure mono out instance ModArg1 (SE Sig) (Sig -> Sig) where type ModArgOut1 (SE Sig) (Sig -> Sig) = Sig -> SE Sig modArg1 depth ma f = \x -> fmap (\a -> f (x * (1 + depth * a))) ma instance ModArg1 (SE Sig) (Sig -> a -> Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> Sig) = Sig -> a -> SE Sig modArg1 depth ma f = \x1 x2 -> fmap (\a -> f (x1 * (1 + depth * a)) x2) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> Sig) = Sig -> a -> b -> SE Sig modArg1 depth ma f = \x1 x2 x3 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> Sig) = Sig -> a -> b -> c -> SE Sig modArg1 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) ma -------------------------------------------- -- dirty in, pure stereo out instance ModArg1 (SE Sig) (Sig -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> Sig2) = Sig -> SE Sig2 modArg1 depth ma f = \x -> fmap (\a -> f (x * (1 + depth * a))) ma instance ModArg1 (SE Sig) (Sig -> a -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> Sig2) = Sig -> a -> SE Sig2 modArg1 depth ma f = \x1 x2 -> fmap (\a -> f (x1 * (1 + depth * a)) x2) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> Sig2) = Sig -> a -> b -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> Sig2) = Sig -> a -> b -> c -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) ma -------------------------------------------- -- dirty in, dirty mono out instance ModArg1 (SE Sig) (Sig -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> SE Sig) = Sig -> SE Sig modArg1 depth ma f = \x -> ma >>= (\a -> f (x * (1 + depth * a))) instance ModArg1 (SE Sig) (Sig -> a -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> SE Sig) = Sig -> a -> SE Sig modArg1 depth ma f = \x1 x2 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2) instance ModArg1 (SE Sig) (Sig -> a -> b -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> SE Sig) = Sig -> a -> b -> SE Sig modArg1 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3) instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> SE Sig) = Sig -> a -> b -> c -> SE Sig modArg1 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) -------------------------------------------- -- dirty in, dirty stereo out instance ModArg1 (SE Sig) (Sig -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> SE Sig2) = Sig -> SE Sig2 modArg1 depth ma f = \x -> ma >>= (\a -> f (x * (1 + depth * a))) instance ModArg1 (SE Sig) (Sig -> a -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> SE Sig2) = Sig -> a -> SE Sig2 modArg1 depth ma f = \x1 x2 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2) instance ModArg1 (SE Sig) (Sig -> a -> b -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> SE Sig2) = Sig -> a -> b -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3) instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> SE Sig2) = Sig -> a -> b -> c -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) -------------------------------------------- -------------------------------------------- -- modArg2 class ModArg2 a b where type ModArgOut2 a b :: Type modArg2 :: Sig -> a -> b -> ModArgOut2 a b -------------------------------------------- -- pure in, pure mono out instance ModArg2 Sig (a -> Sig -> Sig) where type ModArgOut2 Sig (a -> Sig -> Sig) = a -> Sig -> Sig modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> Sig) where type ModArgOut2 Sig (a -> Sig -> b -> Sig) = a -> Sig -> b -> Sig modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> Sig) where type ModArgOut2 Sig (a -> Sig -> b -> c -> Sig) = a -> Sig -> b -> c -> Sig modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 -------------------------------------------- -- pure in, pure stereo out instance ModArg2 Sig (a -> Sig -> Sig2) where type ModArgOut2 Sig (a -> Sig -> Sig2) = a -> Sig -> Sig2 modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> Sig2) = a -> Sig -> b -> Sig2 modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> c -> Sig2) = a -> Sig -> b -> c -> Sig2 modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 -------------------------------------------- -- pure in, dirty mono out instance ModArg2 Sig (a -> Sig -> SE Sig) where type ModArgOut2 Sig (a -> Sig -> SE Sig) = a -> Sig -> SE Sig modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> SE Sig) where type ModArgOut2 Sig (a -> Sig -> b -> SE Sig) = a -> Sig -> b -> SE Sig modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> SE Sig) where type ModArgOut2 Sig (a -> Sig -> b -> c -> SE Sig) = a -> Sig -> b -> c -> SE Sig modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 -------------------------------------------- -- pure in, dirty stereo out instance ModArg2 Sig (a -> Sig -> SE Sig2) where type ModArgOut2 Sig (a -> Sig -> SE Sig2) = a -> Sig -> SE Sig2 modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> SE Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> SE Sig2) = a -> Sig -> b -> SE Sig2 modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> SE Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> c -> SE Sig2) = a -> Sig -> b -> c -> SE Sig2 modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 -------------------------------------------- -- dirty in, pure mono out instance ModArg2 (SE Sig) (a -> Sig -> Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> Sig) = a -> Sig -> SE Sig modArg2 depth ma f = \x1 x2 -> fmap (\a -> f x1 (x2 * (1 + depth * a))) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> Sig) = a -> Sig -> b -> SE Sig modArg2 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> Sig) = a -> Sig -> b -> c -> SE Sig modArg2 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) ma -------------------------------------------- -- dirty in, pure stereo out instance ModArg2 (SE Sig) (a -> Sig -> Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> Sig2) = a -> Sig -> SE Sig2 modArg2 depth ma f = \x1 x2 -> fmap (\a -> f x1 (x2 * (1 + depth * a))) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> Sig2) = a -> Sig -> b -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> Sig2) = a -> Sig -> b -> c -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) ma -------------------------------------------- -- dirty in, dirty mono out instance ModArg2 (SE Sig) (a -> Sig -> SE Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> SE Sig) = a -> Sig -> SE Sig modArg2 depth ma f = \x1 x2 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a))) instance ModArg2 (SE Sig) (a -> Sig -> b -> SE Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> SE Sig) = a -> Sig -> b -> SE Sig modArg2 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3) instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> SE Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> SE Sig) = a -> Sig -> b -> c -> SE Sig modArg2 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) -------------------------------------------- -- dirty in, dirty stereo out instance ModArg2 (SE Sig) (a -> Sig -> SE Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> SE Sig2) = a -> Sig -> SE Sig2 modArg2 depth ma f = \x1 x2 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a))) instance ModArg2 (SE Sig) (a -> Sig -> b -> SE Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> SE Sig2) = a -> Sig -> b -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3) instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> SE Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> SE Sig2) = a -> Sig -> b -> c -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) -------------------------------------------- -------------------------------------------- -- modArg3 class ModArg3 a b where type ModArgOut3 a b :: Type modArg3 :: Sig -> a -> b -> ModArgOut3 a b -------------------------------------------- -- pure in, pure mono out instance ModArg3 Sig (a -> b -> Sig -> Sig) where type ModArgOut3 Sig (a -> b -> Sig -> Sig) = a -> b -> Sig -> Sig modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> Sig) where type ModArgOut3 Sig (a -> b -> Sig -> c -> Sig) = a -> b -> Sig -> c -> Sig modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 -------------------------------------------- -- pure in, pure stereo out instance ModArg3 Sig (a -> b -> Sig -> Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> Sig2) = a -> b -> Sig -> Sig2 modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> c -> Sig2) = a -> b -> Sig -> c -> Sig2 modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 -------------------------------------------- -- pure in, dirty mono out instance ModArg3 Sig (a -> b -> Sig -> SE Sig) where type ModArgOut3 Sig (a -> b -> Sig -> SE Sig) = a -> b -> Sig -> SE Sig modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> SE Sig) where type ModArgOut3 Sig (a -> b -> Sig -> c -> SE Sig) = a -> b -> Sig -> c -> SE Sig modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 -------------------------------------------- -- pure in, dirty stereo out instance ModArg3 Sig (a -> b -> Sig -> SE Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> SE Sig2) = a -> b -> Sig -> SE Sig2 modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> SE Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> c -> SE Sig2) = a -> b -> Sig -> c -> SE Sig2 modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 -------------------------------------------- -- dirty in, pure mono out instance ModArg3 (SE Sig) (a -> b -> Sig -> Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> Sig) = a -> b -> Sig -> SE Sig modArg3 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a))) ma instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> Sig) = a -> b -> Sig -> c -> SE Sig modArg3 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) ma -------------------------------------------- -- dirty in, pure stereo out instance ModArg3 (SE Sig) (a -> b -> Sig -> Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> Sig2) = a -> b -> Sig -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a))) ma instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> Sig2) = a -> b -> Sig -> c -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) ma -------------------------------------------- -- dirty in, dirty mono out instance ModArg3 (SE Sig) (a -> b -> Sig -> SE Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> SE Sig) = a -> b -> Sig -> SE Sig modArg3 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a))) instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> SE Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> SE Sig) = a -> b -> Sig -> c -> SE Sig modArg3 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) -------------------------------------------- -- dirty in, dirty stereo out instance ModArg3 (SE Sig) (a -> b -> Sig -> SE Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> SE Sig2) = a -> b -> Sig -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a))) instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> SE Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> SE Sig2) = a -> b -> Sig -> c -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) -------------------------------------------- -------------------------------------------- modArg4 class ModArg4 a b where type ModArgOut4 a b :: Type modArg4 :: Sig -> a -> b -> ModArgOut4 a b -------------------------------------------- -- pure in, pure mono out instance ModArg4 Sig (a -> b -> c -> Sig -> Sig) where type ModArgOut4 Sig (a -> b -> c -> Sig -> Sig) = a -> b -> c -> Sig -> Sig modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) -------------------------------------------- -- pure in, pure stereo out instance ModArg4 Sig (a -> b -> c -> Sig -> Sig2) where type ModArgOut4 Sig (a -> b -> c -> Sig -> Sig2) = a -> b -> c -> Sig -> Sig2 modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) -------------------------------------------- -- pure in, dirty mono out instance ModArg4 Sig (a -> b -> c -> Sig -> SE Sig) where type ModArgOut4 Sig (a -> b -> c -> Sig -> SE Sig) = a -> b -> c -> Sig -> SE Sig modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) -------------------------------------------- -- pure in, dirty stereo out instance ModArg4 Sig (a -> b -> c -> Sig -> SE Sig2) where type ModArgOut4 Sig (a -> b -> c -> Sig -> SE Sig2) = a -> b -> c -> Sig -> SE Sig2 modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) -------------------------------------------- -- dirty in, pure mono out instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> Sig) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> Sig) = a -> b -> c -> Sig -> SE Sig modArg4 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 x3 (x4 * (1 + depth * a))) ma -------------------------------------------- -- dirty in, pure stereo out instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> Sig2) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> Sig2) = a -> b -> c -> Sig -> SE Sig2 modArg4 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 x3 (x4 * (1 + depth * a))) ma -------------------------------------------- -- dirty in, dirty mono out instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> SE Sig) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> SE Sig) = a -> b -> c -> Sig -> SE Sig modArg4 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 x3 (x4 * (1 + depth * a))) -------------------------------------------- -- dirty in, dirty stereo out instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> SE Sig2) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> SE Sig2) = a -> b -> c -> Sig -> SE Sig2 modArg4 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 x3 (x4 * (1 + depth * a)))
null
https://raw.githubusercontent.com/spell-music/csound-expression/d80d1aaaa1930425672f28e9d5b9f82a3d82d4b8/csound-expression/src/Csound/Air/ModArg.hs
haskell
| Argument modifiers. Functions to transform arguments of the function with flexibility. * Basic class ** Delayed * Oscillators ** Random phase ** Delayed ** Delayed with Random phase * Noise ** Delayed * Envelopes ** Delayed trumpet: adsr mod delayed adsr mod expon adsr mod delayed expon adsr mod oscil lfo tri lfo delayed tri lfo sqr lfo sqr lfo saw lfo delayed saw lfo white noise delayed white noise pink noise pink noise jitter noise jitter noise gauss noise delayed gauss noise gauss noise with frequency delayed gauss noise with frequency ------------------------------------------ ------------------------------------------ modArg1 ------------------------------------------ pure in, pure mono out ------------------------------------------ pure in, pure stereo out ------------------------------------------ pure in, dirty mono out ------------------------------------------ pure in, dirty stereo out ------------------------------------------ dirty in, pure mono out ------------------------------------------ dirty in, pure stereo out ------------------------------------------ dirty in, dirty mono out ------------------------------------------ dirty in, dirty stereo out ------------------------------------------ ------------------------------------------ modArg2 ------------------------------------------ pure in, pure mono out ------------------------------------------ pure in, pure stereo out ------------------------------------------ pure in, dirty mono out ------------------------------------------ pure in, dirty stereo out ------------------------------------------ dirty in, pure mono out ------------------------------------------ dirty in, pure stereo out ------------------------------------------ dirty in, dirty mono out ------------------------------------------ dirty in, dirty stereo out ------------------------------------------ ------------------------------------------ modArg3 ------------------------------------------ pure in, pure mono out ------------------------------------------ pure in, pure stereo out ------------------------------------------ pure in, dirty mono out ------------------------------------------ pure in, dirty stereo out ------------------------------------------ dirty in, pure mono out ------------------------------------------ dirty in, pure stereo out ------------------------------------------ dirty in, dirty mono out ------------------------------------------ dirty in, dirty stereo out ------------------------------------------ ------------------------------------------ ------------------------------------------ pure in, pure mono out ------------------------------------------ pure in, pure stereo out ------------------------------------------ pure in, dirty mono out ------------------------------------------ pure in, dirty stereo out ------------------------------------------ dirty in, pure mono out ------------------------------------------ dirty in, pure stereo out ------------------------------------------ dirty in, dirty mono out ------------------------------------------ dirty in, dirty stereo out
# Language TypeFamilies , TypeSynonymInstances , MultiParamTypeClasses , FlexibleInstances , FlexibleContexts # module Csound.Air.ModArg( ModArg1(..), ModArg2(..), ModArg3(..), ModArg4(..), delModArg1, delModArg2, delModArg3, delModArg4, oscArg1, oscArg2, oscArg3, oscArg4, triArg1, triArg2, triArg3, triArg4, sqrArg1, sqrArg2, sqrArg3, sqrArg4, sawArg1, sawArg2, sawArg3, sawArg4, rndOscArg1, rndOscArg2, rndOscArg3, rndOscArg4, rndTriArg1, rndTriArg2, rndTriArg3, rndTriArg4, rndSqrArg1, rndSqrArg2, rndSqrArg3, rndSqrArg4, rndSawArg1, rndSawArg2, rndSawArg3, rndSawArg4, delOscArg1, delOscArg2, delOscArg3, delOscArg4, delTriArg1, delTriArg2, delTriArg3, delTriArg4, delSqrArg1, delSqrArg2, delSqrArg3, delSqrArg4, delSawArg1, delSawArg2, delSawArg3, delSawArg4, delRndOscArg1, delRndOscArg2, delRndOscArg3, delRndOscArg4, delRndTriArg1, delRndTriArg2, delRndTriArg3, delRndTriArg4, delRndSqrArg1, delRndSqrArg2, delRndSqrArg3, delRndSqrArg4, delRndSawArg1, delRndSawArg2, delRndSawArg3, delRndSawArg4, noiseArg1, noiseArg2, noiseArg3, noiseArg4, pinkArg1, pinkArg2, pinkArg3, pinkArg4, jitArg1, jitArg2, jitArg3, jitArg4, gaussArg1, gaussArg2, gaussArg3, gaussArg4, gaussiArg1, gaussiArg2, gaussiArg3, gaussiArg4, delNoiseArg1, delNoiseArg2, delNoiseArg3, delNoiseArg4, delPinkArg1, delPinkArg2, delPinkArg3, delPinkArg4, delJitArg1, delJitArg2, delJitArg3, delJitArg4, delGaussArg1, delGaussArg2, delGaussArg3, delGaussArg4, delGaussiArg1, delGaussiArg2, delGaussiArg3, delGaussiArg4, adsrArg1, adsrArg2, adsrArg3, adsrArg4, xadsrArg1, xadsrArg2, xadsrArg3, xadsrArg4, delAdsrArg1, delAdsrArg2, delAdsrArg3, delAdsrArg4, delXadsrArg1, delXadsrArg2, delXadsrArg3, delXadsrArg4 ) where import Data.Kind (Type) import Csound.Typed import Csound.Typed.Opcode(gauss, gaussi, jitter, linseg, linsegr, expsegr) import Csound.Air.Wave import Csound.Air.Envelope dac $ mul 1.3 $ mixAt 0.15 largeHall2 $ midi $ onMsg ( \cps - > ( ( linsegr [ 0,0.01 , 1 , 3 , 0.2 ] 0.2 0 ) . at ( ( 0.15 + 0.05 * uosc 0.2 ) 3 20 alp1 ( ( fades 0.2 0.2 ) $ 2700 + 0.6 * cps ) 0.2 ) . gaussArg1 0.03 ( \x - > return ( saw x ) + mul ( 0.12 * expseg [ 1 , 2 , 0.1 ] ) ( bat ( alp1 cps 0.4 ) white ) ) ) cps ) delEnv :: SigSpace a => D -> D -> a -> a delEnv delTime riseTime asig = mul (linseg [0, delTime, 0, riseTime, 1]) asig delModArg1 :: (SigSpace a, ModArg1 a b) => D -> D -> Sig -> a -> b -> ModArgOut1 a b delModArg1 delTime riseTime depth modSig f = modArg1 (delEnv delTime riseTime depth) modSig f delModArg2 :: (SigSpace a, ModArg2 a b) => D -> D -> Sig -> a -> b -> ModArgOut2 a b delModArg2 delTime riseTime depth modSig f = modArg2 (delEnv delTime riseTime depth) modSig f delModArg3 :: (SigSpace a, ModArg3 a b) => D -> D -> Sig -> a -> b -> ModArgOut3 a b delModArg3 delTime riseTime depth modSig f = modArg3 (delEnv delTime riseTime depth) modSig f delModArg4 :: (SigSpace a, ModArg4 a b) => D -> D -> Sig -> a -> b -> ModArgOut4 a b delModArg4 delTime riseTime depth modSig f = modArg4 (delEnv delTime riseTime depth) modSig f adsrArg1 :: (ModArg1 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b adsrArg1 depth a d s r f = modArg1 depth (leg a d s r) f adsrArg2 :: (ModArg2 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b adsrArg2 depth a d s r f = modArg2 depth (leg a d s r) f adsrArg3 :: (ModArg3 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b adsrArg3 depth a d s r f = modArg3 depth (leg a d s r) f adsrArg4 :: (ModArg4 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b adsrArg4 depth a d s r f = modArg4 depth (leg a d s r) f delLeg :: D -> D -> D -> D -> D -> Sig delLeg delTime a d s r = linsegr [0, delTime, 0, a, 1, d, s] r 0 delAdsrArg1 :: (ModArg1 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b delAdsrArg1 delTime depth a d s r f = modArg1 depth (delLeg delTime a d s r) f delAdsrArg2 :: (ModArg2 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b delAdsrArg2 delTime depth a d s r f = modArg2 depth (delLeg delTime a d s r) f delAdsrArg3 :: (ModArg3 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b delAdsrArg3 delTime depth a d s r f = modArg3 depth (delLeg delTime a d s r) f delAdsrArg4 :: (ModArg4 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b delAdsrArg4 delTime depth a d s r f = modArg4 depth (delLeg delTime a d s r) f xadsrArg1 :: (ModArg1 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b xadsrArg1 depth a d s r f = modArg1 depth (xeg a d s r) f xadsrArg2 :: (ModArg2 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b xadsrArg2 depth a d s r f = modArg2 depth (xeg a d s r) f xadsrArg3 :: (ModArg3 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b xadsrArg3 depth a d s r f = modArg3 depth (xeg a d s r) f xadsrArg4 :: (ModArg4 Sig b) => Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b xadsrArg4 depth a d s r f = modArg4 depth (xeg a d s r) f delXeg :: D -> D -> D -> D -> D -> Sig delXeg delTime a d s r = expsegr [0.001, delTime, 0.001, a, 1, d, s] r 0.001 delXadsrArg1 :: (ModArg1 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut1 Sig b delXadsrArg1 delTime depth a d s r f = modArg1 depth (delXeg delTime a d s r) f delXadsrArg2 :: (ModArg2 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut2 Sig b delXadsrArg2 delTime depth a d s r f = modArg2 depth (delXeg delTime a d s r) f delXadsrArg3 :: (ModArg3 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut3 Sig b delXadsrArg3 delTime depth a d s r f = modArg3 depth (delXeg delTime a d s r) f delXadsrArg4 :: (ModArg4 Sig b) => D -> Sig -> D -> D -> D -> D -> b -> ModArgOut4 Sig b delXadsrArg4 delTime depth a d s r f = modArg4 depth (delXeg delTime a d s r) f oscArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b oscArg1 depth rate f = modArg1 depth (osc rate) f oscArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b oscArg2 depth rate f = modArg2 depth (osc rate) f oscArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b oscArg3 depth rate f = modArg3 depth (osc rate) f oscArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b oscArg4 depth rate f = modArg4 depth (osc rate) f delayed oscil lfo delOscArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delOscArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (osc rate) f delOscArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delOscArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (osc rate) f delOscArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delOscArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (osc rate) f delOscArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delOscArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (osc rate) f triArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b triArg1 depth rate f = modArg1 depth (tri rate) f triArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b triArg2 depth rate f = modArg2 depth (tri rate) f triArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b triArg3 depth rate f = modArg3 depth (tri rate) f triArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b triArg4 depth rate f = modArg4 depth (tri rate) f delTriArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delTriArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (tri rate) f delTriArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delTriArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (tri rate) f delTriArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delTriArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (tri rate) f delTriArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delTriArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (tri rate) f sqrArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b sqrArg1 depth rate f = modArg1 depth (sqr rate) f sqrArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b sqrArg2 depth rate f = modArg2 depth (sqr rate) f sqrArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b sqrArg3 depth rate f = modArg3 depth (sqr rate) f sqrArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b sqrArg4 depth rate f = modArg4 depth (sqr rate) f delSqrArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delSqrArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (sqr rate) f delSqrArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delSqrArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (sqr rate) f delSqrArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delSqrArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (sqr rate) f delSqrArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delSqrArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (sqr rate) f sawArg1 :: (ModArg1 Sig b) => Sig -> Sig -> b -> ModArgOut1 Sig b sawArg1 depth rate f = modArg1 depth (saw rate) f sawArg2 :: (ModArg2 Sig b) => Sig -> Sig -> b -> ModArgOut2 Sig b sawArg2 depth rate f = modArg2 depth (saw rate) f sawArg3 :: (ModArg3 Sig b) => Sig -> Sig -> b -> ModArgOut3 Sig b sawArg3 depth rate f = modArg3 depth (saw rate) f sawArg4 :: (ModArg4 Sig b) => Sig -> Sig -> b -> ModArgOut4 Sig b sawArg4 depth rate f = modArg4 depth (saw rate) f delSawArg1 :: (ModArg1 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 Sig b delSawArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (saw rate) f delSawArg2 :: (ModArg2 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 Sig b delSawArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (saw rate) f delSawArg3 :: (ModArg3 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 Sig b delSawArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (saw rate) f delSawArg4 :: (ModArg4 Sig b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 Sig b delSawArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (saw rate) f oscil lfo rnd phase rndOscArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndOscArg1 depth rate f = modArg1 depth (rndOsc rate) f rndOscArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndOscArg2 depth rate f = modArg2 depth (rndOsc rate) f rndOscArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndOscArg3 depth rate f = modArg3 depth (rndOsc rate) f rndOscArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndOscArg4 depth rate f = modArg4 depth (rndOsc rate) f delayed oscil lfo rnd phase delRndOscArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndOscArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndOsc rate) f delRndOscArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndOscArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndOsc rate) f delRndOscArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndOscArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndOsc rate) f delRndOscArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndOscArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndOsc rate) f tri lfo rnd phase rndTriArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndTriArg1 depth rate f = modArg1 depth (rndTri rate) f rndTriArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndTriArg2 depth rate f = modArg2 depth (rndTri rate) f rndTriArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndTriArg3 depth rate f = modArg3 depth (rndTri rate) f rndTriArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndTriArg4 depth rate f = modArg4 depth (rndTri rate) f delayed tri lfo rnd phase delRndTriArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndTriArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndTri rate) f delRndTriArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndTriArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndTri rate) f delRndTriArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndTriArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndTri rate) f delRndTriArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndTriArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndTri rate) f sqr lfo rnd phase rndSqrArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndSqrArg1 depth rate f = modArg1 depth (rndSqr rate) f rndSqrArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndSqrArg2 depth rate f = modArg2 depth (rndSqr rate) f rndSqrArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndSqrArg3 depth rate f = modArg3 depth (rndSqr rate) f rndSqrArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndSqrArg4 depth rate f = modArg4 depth (rndSqr rate) f sqr lfo rnd phase delRndSqrArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndSqrArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndSqr rate) f delRndSqrArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndSqrArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndSqr rate) f delRndSqrArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndSqrArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndSqr rate) f delRndSqrArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndSqrArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndSqr rate) f sqr lfo rnd phase rndSawArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b rndSawArg1 depth rate f = modArg1 depth (rndSaw rate) f rndSawArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b rndSawArg2 depth rate f = modArg2 depth (rndSaw rate) f rndSawArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b rndSawArg3 depth rate f = modArg3 depth (rndSaw rate) f rndSawArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b rndSawArg4 depth rate f = modArg4 depth (rndSaw rate) f delayed sqr lfo rnd phase delRndSawArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delRndSawArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (rndSaw rate) f delRndSawArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delRndSawArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (rndSaw rate) f delRndSawArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delRndSawArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (rndSaw rate) f delRndSawArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delRndSawArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (rndSaw rate) f noiseArg1 :: (ModArg1 (SE Sig) b) => Sig -> b -> ModArgOut1 (SE Sig) b noiseArg1 depth f = modArg1 depth white f noiseArg2 :: (ModArg2 (SE Sig) b) => Sig -> b -> ModArgOut2 (SE Sig) b noiseArg2 depth f = modArg2 depth white f noiseArg3 :: (ModArg3 (SE Sig) b) => Sig -> b -> ModArgOut3 (SE Sig) b noiseArg3 depth f = modArg3 depth white f noiseArg4 :: (ModArg4 (SE Sig) b) => Sig -> b -> ModArgOut4 (SE Sig) b noiseArg4 depth f = modArg4 depth white f delNoiseArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut1 (SE Sig) b delNoiseArg1 delTime riseTime depth f = delModArg1 delTime riseTime depth white f delNoiseArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut2 (SE Sig) b delNoiseArg2 delTime riseTime depth f = delModArg2 delTime riseTime depth white f delNoiseArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut3 (SE Sig) b delNoiseArg3 delTime riseTime depth f = delModArg3 delTime riseTime depth white f delNoiseArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut4 (SE Sig) b delNoiseArg4 delTime riseTime depth f = delModArg4 delTime riseTime depth white f pinkArg1 :: (ModArg1 (SE Sig) b) => Sig -> b -> ModArgOut1 (SE Sig) b pinkArg1 depth f = modArg1 depth pink f pinkArg2 :: (ModArg2 (SE Sig) b) => Sig -> b -> ModArgOut2 (SE Sig) b pinkArg2 depth f = modArg2 depth pink f pinkArg3 :: (ModArg3 (SE Sig) b) => Sig -> b -> ModArgOut3 (SE Sig) b pinkArg3 depth f = modArg3 depth pink f pinkArg4 :: (ModArg4 (SE Sig) b) => Sig -> b -> ModArgOut4 (SE Sig) b pinkArg4 depth f = modArg4 depth pink f delPinkArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut1 (SE Sig) b delPinkArg1 delTime riseTime depth f = delModArg1 delTime riseTime depth pink f delPinkArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut2 (SE Sig) b delPinkArg2 delTime riseTime depth f = delModArg2 delTime riseTime depth pink f delPinkArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut3 (SE Sig) b delPinkArg3 delTime riseTime depth f = delModArg3 delTime riseTime depth pink f delPinkArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut4 (SE Sig) b delPinkArg4 delTime riseTime depth f = delModArg4 delTime riseTime depth pink f jitArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b jitArg1 depth cpsMin cpsMax f = modArg1 depth (jitter 1 cpsMin cpsMax) f jitArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b jitArg2 depth cpsMin cpsMax f = modArg2 depth (jitter 1 cpsMin cpsMax) f jitArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b jitArg3 depth cpsMin cpsMax f = modArg3 depth (jitter 1 cpsMin cpsMax) f jitArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b jitArg4 depth cpsMin cpsMax f = modArg4 depth (jitter 1 cpsMin cpsMax) f delJitArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delJitArg1 delTime riseTime depth cpsMin cpsMax f = delModArg1 delTime riseTime depth (jitter 1 cpsMin cpsMax) f delJitArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delJitArg2 delTime riseTime depth cpsMin cpsMax f = delModArg2 delTime riseTime depth (jitter 1 cpsMin cpsMax) f delJitArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delJitArg3 delTime riseTime depth cpsMin cpsMax f = delModArg3 delTime riseTime depth (jitter 1 cpsMin cpsMax) f delJitArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delJitArg4 delTime riseTime depth cpsMin cpsMax f = delModArg4 delTime riseTime depth (jitter 1 cpsMin cpsMax) f gaussArg1 :: (ModArg1 (SE Sig) b) => Sig -> b -> ModArgOut1 (SE Sig) b gaussArg1 depth f = modArg1 depth (gauss 1) f gaussArg2 :: (ModArg2 (SE Sig) b) => Sig -> b -> ModArgOut2 (SE Sig) b gaussArg2 depth f = modArg2 depth (gauss 1) f gaussArg3 :: (ModArg3 (SE Sig) b) => Sig -> b -> ModArgOut3 (SE Sig) b gaussArg3 depth f = modArg3 depth (gauss 1) f gaussArg4 :: (ModArg4 (SE Sig) b) => Sig -> b -> ModArgOut4 (SE Sig) b gaussArg4 depth f = modArg4 depth (gauss 1) f delGaussArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut1 (SE Sig) b delGaussArg1 delTime riseTime depth f = delModArg1 delTime riseTime depth (gauss 1) f delGaussArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut2 (SE Sig) b delGaussArg2 delTime riseTime depth f = delModArg2 delTime riseTime depth (gauss 1) f delGaussArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut3 (SE Sig) b delGaussArg3 delTime riseTime depth f = delModArg3 delTime riseTime depth (gauss 1) f delGaussArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> b -> ModArgOut4 (SE Sig) b delGaussArg4 delTime riseTime depth f = delModArg4 delTime riseTime depth (gauss 1) f gaussiArg1 :: (ModArg1 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut1 (SE Sig) b gaussiArg1 depth rate f = modArg1 depth (gaussi 1 1 rate) f gaussiArg2 :: (ModArg2 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut2 (SE Sig) b gaussiArg2 depth rate f = modArg2 depth (gaussi 1 1 rate) f gaussiArg3 :: (ModArg3 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut3 (SE Sig) b gaussiArg3 depth rate f = modArg3 depth (gaussi 1 1 rate) f gaussiArg4 :: (ModArg4 (SE Sig) b) => Sig -> Sig -> b -> ModArgOut4 (SE Sig) b gaussiArg4 depth rate f = modArg4 depth (gaussi 1 1 rate) f delGaussiArg1 :: (ModArg1 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut1 (SE Sig) b delGaussiArg1 delTime riseTime depth rate f = delModArg1 delTime riseTime depth (gaussi 1 1 rate) f delGaussiArg2 :: (ModArg2 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut2 (SE Sig) b delGaussiArg2 delTime riseTime depth rate f = delModArg2 delTime riseTime depth (gaussi 1 1 rate) f delGaussiArg3 :: (ModArg3 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut3 (SE Sig) b delGaussiArg3 delTime riseTime depth rate f = delModArg3 delTime riseTime depth (gaussi 1 1 rate) f delGaussiArg4 :: (ModArg4 (SE Sig) b) => D -> D -> Sig -> Sig -> b -> ModArgOut4 (SE Sig) b delGaussiArg4 delTime riseTime depth rate f = delModArg4 delTime riseTime depth (gaussi 1 1 rate) f class ModArg1 a b where type ModArgOut1 a b :: Type modArg1 :: Sig -> a -> b -> ModArgOut1 a b instance ModArg1 Sig (Sig -> Sig) where type ModArgOut1 Sig (Sig -> Sig) = Sig -> Sig modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> Sig) where type ModArgOut1 Sig (Sig -> a -> Sig) = Sig -> a -> Sig modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> Sig) where type ModArgOut1 Sig (Sig -> a -> b -> Sig) = Sig -> a -> b -> Sig modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> Sig) where type ModArgOut1 Sig (Sig -> a -> b -> c -> Sig) = Sig -> a -> b -> c -> Sig modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 instance ModArg1 Sig (Sig -> Sig2) where type ModArgOut1 Sig (Sig -> Sig2) = Sig -> Sig2 modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> Sig2) where type ModArgOut1 Sig (Sig -> a -> Sig2) = Sig -> a -> Sig2 modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> Sig2) = Sig -> a -> b -> Sig2 modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> c -> Sig2) = Sig -> a -> b -> c -> Sig2 modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 instance ModArg1 Sig (Sig -> SE Sig) where type ModArgOut1 Sig (Sig -> SE Sig) = Sig -> SE Sig modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> SE Sig) where type ModArgOut1 Sig (Sig -> a -> SE Sig) = Sig -> a -> SE Sig modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> SE Sig) where type ModArgOut1 Sig (Sig -> a -> b -> SE Sig) = Sig -> a -> b -> SE Sig modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> SE Sig) where type ModArgOut1 Sig (Sig -> a -> b -> c -> SE Sig) = Sig -> a -> b -> c -> SE Sig modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 instance ModArg1 Sig (Sig -> SE Sig2) where type ModArgOut1 Sig (Sig -> SE Sig2) = Sig -> SE Sig2 modArg1 depth a f = \x -> f (x * (1 + depth * a)) instance ModArg1 Sig (Sig -> a -> SE Sig2) where type ModArgOut1 Sig (Sig -> a -> SE Sig2) = Sig -> a -> SE Sig2 modArg1 depth a f = \x1 x2 -> f (x1 * (1 + depth * a)) x2 instance ModArg1 Sig (Sig -> a -> b -> SE Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> SE Sig2) = Sig -> a -> b -> SE Sig2 modArg1 depth a f = \x1 x2 x3 -> f (x1 * (1 + depth * a)) x2 x3 instance ModArg1 Sig (Sig -> a -> b -> c -> SE Sig2) where type ModArgOut1 Sig (Sig -> a -> b -> c -> SE Sig2) = Sig -> a -> b -> c -> SE Sig2 modArg1 depth a f = \x1 x2 x3 x4 -> f (x1 * (1 + depth * a)) x2 x3 x4 instance ModArg1 (SE Sig) (Sig -> Sig) where type ModArgOut1 (SE Sig) (Sig -> Sig) = Sig -> SE Sig modArg1 depth ma f = \x -> fmap (\a -> f (x * (1 + depth * a))) ma instance ModArg1 (SE Sig) (Sig -> a -> Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> Sig) = Sig -> a -> SE Sig modArg1 depth ma f = \x1 x2 -> fmap (\a -> f (x1 * (1 + depth * a)) x2) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> Sig) = Sig -> a -> b -> SE Sig modArg1 depth ma f = \x1 x2 x3 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> Sig) = Sig -> a -> b -> c -> SE Sig modArg1 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) ma instance ModArg1 (SE Sig) (Sig -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> Sig2) = Sig -> SE Sig2 modArg1 depth ma f = \x -> fmap (\a -> f (x * (1 + depth * a))) ma instance ModArg1 (SE Sig) (Sig -> a -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> Sig2) = Sig -> a -> SE Sig2 modArg1 depth ma f = \x1 x2 -> fmap (\a -> f (x1 * (1 + depth * a)) x2) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> Sig2) = Sig -> a -> b -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3) ma instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> Sig2) = Sig -> a -> b -> c -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) ma instance ModArg1 (SE Sig) (Sig -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> SE Sig) = Sig -> SE Sig modArg1 depth ma f = \x -> ma >>= (\a -> f (x * (1 + depth * a))) instance ModArg1 (SE Sig) (Sig -> a -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> SE Sig) = Sig -> a -> SE Sig modArg1 depth ma f = \x1 x2 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2) instance ModArg1 (SE Sig) (Sig -> a -> b -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> SE Sig) = Sig -> a -> b -> SE Sig modArg1 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3) instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> SE Sig) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> SE Sig) = Sig -> a -> b -> c -> SE Sig modArg1 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) instance ModArg1 (SE Sig) (Sig -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> SE Sig2) = Sig -> SE Sig2 modArg1 depth ma f = \x -> ma >>= (\a -> f (x * (1 + depth * a))) instance ModArg1 (SE Sig) (Sig -> a -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> SE Sig2) = Sig -> a -> SE Sig2 modArg1 depth ma f = \x1 x2 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2) instance ModArg1 (SE Sig) (Sig -> a -> b -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> SE Sig2) = Sig -> a -> b -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3) instance ModArg1 (SE Sig) (Sig -> a -> b -> c -> SE Sig2) where type ModArgOut1 (SE Sig) (Sig -> a -> b -> c -> SE Sig2) = Sig -> a -> b -> c -> SE Sig2 modArg1 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f (x1 * (1 + depth * a)) x2 x3 x4) class ModArg2 a b where type ModArgOut2 a b :: Type modArg2 :: Sig -> a -> b -> ModArgOut2 a b instance ModArg2 Sig (a -> Sig -> Sig) where type ModArgOut2 Sig (a -> Sig -> Sig) = a -> Sig -> Sig modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> Sig) where type ModArgOut2 Sig (a -> Sig -> b -> Sig) = a -> Sig -> b -> Sig modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> Sig) where type ModArgOut2 Sig (a -> Sig -> b -> c -> Sig) = a -> Sig -> b -> c -> Sig modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 instance ModArg2 Sig (a -> Sig -> Sig2) where type ModArgOut2 Sig (a -> Sig -> Sig2) = a -> Sig -> Sig2 modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> Sig2) = a -> Sig -> b -> Sig2 modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> c -> Sig2) = a -> Sig -> b -> c -> Sig2 modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 instance ModArg2 Sig (a -> Sig -> SE Sig) where type ModArgOut2 Sig (a -> Sig -> SE Sig) = a -> Sig -> SE Sig modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> SE Sig) where type ModArgOut2 Sig (a -> Sig -> b -> SE Sig) = a -> Sig -> b -> SE Sig modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> SE Sig) where type ModArgOut2 Sig (a -> Sig -> b -> c -> SE Sig) = a -> Sig -> b -> c -> SE Sig modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 instance ModArg2 Sig (a -> Sig -> SE Sig2) where type ModArgOut2 Sig (a -> Sig -> SE Sig2) = a -> Sig -> SE Sig2 modArg2 depth a f = \x1 x2 -> f x1 (x2 * (1 + depth * a)) instance ModArg2 Sig (a -> Sig -> b -> SE Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> SE Sig2) = a -> Sig -> b -> SE Sig2 modArg2 depth a f = \x1 x2 x3 -> f x1 (x2 * (1 + depth * a)) x3 instance ModArg2 Sig (a -> Sig -> b -> c -> SE Sig2) where type ModArgOut2 Sig (a -> Sig -> b -> c -> SE Sig2) = a -> Sig -> b -> c -> SE Sig2 modArg2 depth a f = \x1 x2 x3 x4 -> f x1 (x2 * (1 + depth * a)) x3 x4 instance ModArg2 (SE Sig) (a -> Sig -> Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> Sig) = a -> Sig -> SE Sig modArg2 depth ma f = \x1 x2 -> fmap (\a -> f x1 (x2 * (1 + depth * a))) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> Sig) = a -> Sig -> b -> SE Sig modArg2 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> Sig) = a -> Sig -> b -> c -> SE Sig modArg2 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) ma instance ModArg2 (SE Sig) (a -> Sig -> Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> Sig2) = a -> Sig -> SE Sig2 modArg2 depth ma f = \x1 x2 -> fmap (\a -> f x1 (x2 * (1 + depth * a))) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> Sig2) = a -> Sig -> b -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3) ma instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> Sig2) = a -> Sig -> b -> c -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) ma instance ModArg2 (SE Sig) (a -> Sig -> SE Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> SE Sig) = a -> Sig -> SE Sig modArg2 depth ma f = \x1 x2 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a))) instance ModArg2 (SE Sig) (a -> Sig -> b -> SE Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> SE Sig) = a -> Sig -> b -> SE Sig modArg2 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3) instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> SE Sig) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> SE Sig) = a -> Sig -> b -> c -> SE Sig modArg2 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) instance ModArg2 (SE Sig) (a -> Sig -> SE Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> SE Sig2) = a -> Sig -> SE Sig2 modArg2 depth ma f = \x1 x2 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a))) instance ModArg2 (SE Sig) (a -> Sig -> b -> SE Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> SE Sig2) = a -> Sig -> b -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3) instance ModArg2 (SE Sig) (a -> Sig -> b -> c -> SE Sig2) where type ModArgOut2 (SE Sig) (a -> Sig -> b -> c -> SE Sig2) = a -> Sig -> b -> c -> SE Sig2 modArg2 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 (x2 * (1 + depth * a)) x3 x4) class ModArg3 a b where type ModArgOut3 a b :: Type modArg3 :: Sig -> a -> b -> ModArgOut3 a b instance ModArg3 Sig (a -> b -> Sig -> Sig) where type ModArgOut3 Sig (a -> b -> Sig -> Sig) = a -> b -> Sig -> Sig modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> Sig) where type ModArgOut3 Sig (a -> b -> Sig -> c -> Sig) = a -> b -> Sig -> c -> Sig modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 instance ModArg3 Sig (a -> b -> Sig -> Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> Sig2) = a -> b -> Sig -> Sig2 modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> c -> Sig2) = a -> b -> Sig -> c -> Sig2 modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 instance ModArg3 Sig (a -> b -> Sig -> SE Sig) where type ModArgOut3 Sig (a -> b -> Sig -> SE Sig) = a -> b -> Sig -> SE Sig modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> SE Sig) where type ModArgOut3 Sig (a -> b -> Sig -> c -> SE Sig) = a -> b -> Sig -> c -> SE Sig modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 instance ModArg3 Sig (a -> b -> Sig -> SE Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> SE Sig2) = a -> b -> Sig -> SE Sig2 modArg3 depth a f = \x1 x2 x3 -> f x1 x2 (x3 * (1 + depth * a)) instance ModArg3 Sig (a -> b -> Sig -> c -> SE Sig2) where type ModArgOut3 Sig (a -> b -> Sig -> c -> SE Sig2) = a -> b -> Sig -> c -> SE Sig2 modArg3 depth a f = \x1 x2 x3 x4 -> f x1 x2 (x3 * (1 + depth * a)) x4 instance ModArg3 (SE Sig) (a -> b -> Sig -> Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> Sig) = a -> b -> Sig -> SE Sig modArg3 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a))) ma instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> Sig) = a -> b -> Sig -> c -> SE Sig modArg3 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) ma instance ModArg3 (SE Sig) (a -> b -> Sig -> Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> Sig2) = a -> b -> Sig -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a))) ma instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> Sig2) = a -> b -> Sig -> c -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) ma instance ModArg3 (SE Sig) (a -> b -> Sig -> SE Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> SE Sig) = a -> b -> Sig -> SE Sig modArg3 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a))) instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> SE Sig) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> SE Sig) = a -> b -> Sig -> c -> SE Sig modArg3 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) instance ModArg3 (SE Sig) (a -> b -> Sig -> SE Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> SE Sig2) = a -> b -> Sig -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a))) instance ModArg3 (SE Sig) (a -> b -> Sig -> c -> SE Sig2) where type ModArgOut3 (SE Sig) (a -> b -> Sig -> c -> SE Sig2) = a -> b -> Sig -> c -> SE Sig2 modArg3 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 (x3 * (1 + depth * a)) x4) modArg4 class ModArg4 a b where type ModArgOut4 a b :: Type modArg4 :: Sig -> a -> b -> ModArgOut4 a b instance ModArg4 Sig (a -> b -> c -> Sig -> Sig) where type ModArgOut4 Sig (a -> b -> c -> Sig -> Sig) = a -> b -> c -> Sig -> Sig modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) instance ModArg4 Sig (a -> b -> c -> Sig -> Sig2) where type ModArgOut4 Sig (a -> b -> c -> Sig -> Sig2) = a -> b -> c -> Sig -> Sig2 modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) instance ModArg4 Sig (a -> b -> c -> Sig -> SE Sig) where type ModArgOut4 Sig (a -> b -> c -> Sig -> SE Sig) = a -> b -> c -> Sig -> SE Sig modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) instance ModArg4 Sig (a -> b -> c -> Sig -> SE Sig2) where type ModArgOut4 Sig (a -> b -> c -> Sig -> SE Sig2) = a -> b -> c -> Sig -> SE Sig2 modArg4 depth a f = \x1 x2 x3 x4 -> f x1 x2 x3 (x4 * (1 + depth * a)) instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> Sig) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> Sig) = a -> b -> c -> Sig -> SE Sig modArg4 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 x3 (x4 * (1 + depth * a))) ma instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> Sig2) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> Sig2) = a -> b -> c -> Sig -> SE Sig2 modArg4 depth ma f = \x1 x2 x3 x4 -> fmap (\a -> f x1 x2 x3 (x4 * (1 + depth * a))) ma instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> SE Sig) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> SE Sig) = a -> b -> c -> Sig -> SE Sig modArg4 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 x3 (x4 * (1 + depth * a))) instance ModArg4 (SE Sig) (a -> b -> c -> Sig -> SE Sig2) where type ModArgOut4 (SE Sig) (a -> b -> c -> Sig -> SE Sig2) = a -> b -> c -> Sig -> SE Sig2 modArg4 depth ma f = \x1 x2 x3 x4 -> ma >>= (\a -> f x1 x2 x3 (x4 * (1 + depth * a)))
2b3805350e1c3f3e9a774e1223612c5dd8049d507c23ecf37244785c38ea73b7
acl2/acl2
exec-binary-strict-pure-lt.lisp
C Library ; Copyright ( C ) 2023 Kestrel Institute ( ) Copyright ( C ) 2023 Kestrel Technology LLC ( ) ; License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "C") (include-book "exec-binary-strict-pure-gen") (local (include-book "exec-binary-strict-pure-local")) (local (include-book "kestrel/built-ins/disable" :dir :system)) (local (acl2::disable-most-builtin-logic-defuns)) (local (acl2::disable-builtin-rewrite-rules-for-defaults)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (make-event (atc-exec-binary-rules-for-op-gen (binop-lt)))
null
https://raw.githubusercontent.com/acl2/acl2/44f76f208004466a9e6cdf3a07dac98b3799817d/books/kestrel/c/atc/symbolic-execution-rules/exec-binary-strict-pure-lt.lisp
lisp
C Library Copyright ( C ) 2023 Kestrel Institute ( ) Copyright ( C ) 2023 Kestrel Technology LLC ( ) License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . Author : ( ) (in-package "C") (include-book "exec-binary-strict-pure-gen") (local (include-book "exec-binary-strict-pure-local")) (local (include-book "kestrel/built-ins/disable" :dir :system)) (local (acl2::disable-most-builtin-logic-defuns)) (local (acl2::disable-builtin-rewrite-rules-for-defaults)) (make-event (atc-exec-binary-rules-for-op-gen (binop-lt)))
e0426474596a5dde0d7aa06e06e40b316376c2576f8a33a2425a2b3541de708b
gvolpe/haskell-book-exercises
palindrome.hs
import Control.Monad (forever) import Data.Char import System.Exit (exitSuccess) isPalindrome :: String -> Bool isPalindrome x = w == reverse w where f = filter (\x -> x /= '\'' && x /= ',') w = f $ concat $ words $ map toLower x palindrome :: IO () palindrome = forever $ do line1 <- getLine case (line1 == reverse line1) of True -> do putStrLn "It's a palindrome!" return () False -> do putStrLn "Nope!" exitSuccess main :: IO () main = palindrome
null
https://raw.githubusercontent.com/gvolpe/haskell-book-exercises/5c1b9d8dc729ee5a90c8709b9c889cbacb30a2cb/chapter13/palindrome.hs
haskell
import Control.Monad (forever) import Data.Char import System.Exit (exitSuccess) isPalindrome :: String -> Bool isPalindrome x = w == reverse w where f = filter (\x -> x /= '\'' && x /= ',') w = f $ concat $ words $ map toLower x palindrome :: IO () palindrome = forever $ do line1 <- getLine case (line1 == reverse line1) of True -> do putStrLn "It's a palindrome!" return () False -> do putStrLn "Nope!" exitSuccess main :: IO () main = palindrome
1ac26b01bc050e9c1e215affa17e506d6e2b123f4aede0af2043e306ac042ff8
ndmitchell/supero
Convert.hs
module Convert(convert, drop1mod) where import Type import Safe import Yhc.Core import Data.List import Data.Play import qualified Data.Map as Map import qualified Data.Set as Set convert :: Core -> Prog convert core = Prog (Map.fromList [(funcName x, x) | x <- concat fs]) where (n,fs) = mapAccumL convertFunc 0 $ coreFuncs $ fixPrims $ drop1mod core fixPrims :: Core -> Core fixPrims core = core{coreFuncs = mapUnderCore usePrim norm} where (prim,norm) = partition (isPrim . coreFuncBody) (coreFuncs core) prims = Set.fromList (map coreFuncName prim) usePrim (CoreFun x) | x `Set.member` prims = CorePrim x usePrim x = x isPrim (CorePos _ x) = isPrim x isPrim (CoreApp x []) = isPrim x isPrim (CoreVar x) = x == "primitive" isPrim _ = False drop1mod :: Core -> Core drop1mod (Core name imports datas funcs) = Core name imports (map g datas) (concatMap h funcs) where f x = case break (== '.') x of (_,"") -> x (_,_:xs) -> xs g (CoreData name free args) = CoreData (f name) free (map g2 args) g2 (CoreCtor name items) = CoreCtor (f name) items h (CoreFunc name args body) | name == "main" = [] | otherwise = [CoreFunc (f name) args (mapOverCore h2 body)] h2 (CoreFun x) = CoreFun $ f x h2 (CoreCon x) = CoreCon $ f x h2 x = x convertFunc :: Int -> CoreFunc -> (Int, [Func]) convertFunc n x = (n2, map f funcs2) where (n2,args2,expr2) = freshFree (coreFuncArgs x) (coreFuncBody x) n funcs2 = removeLets (CoreFunc (coreFuncName x) (map show args2) expr2) f (CoreFunc name args body) = Func name [FuncAlt 0 (map (Var . read) args) (convertExpr body)] convertExpr :: CoreExpr -> Expr convertExpr x = case x of CorePos _ x -> f x CoreCase x xs -> Case (f x) [(f a, f b) | (a,b) <- xs] CoreVar x -> Var $ read x CoreApp x xs -> Apply (f x) (fs xs) CoreCon x -> Ctr x CoreFun x -> Fun x CorePrim x -> Prim x CoreStr x -> Const $ ConstStr x CoreInt x -> Const $ ConstInt x CoreInteger x -> Const $ ConstInteger x CoreChr x -> Const $ ConstChr x _ -> error $ "Convert.convertExpr: " ++ show x where f = convertExpr fs = map f -- number the variables as appropriate freshFree :: [String] -> CoreExpr -> Int -> (Int, [Int], CoreExpr) freshFree args x n = (n+nvars, map (`lookupJust` rens) args, mapOverCore f x) where nvars = length vars vars = nub $ args ++ [i | CoreVar i <- allCore x] rens = zip vars [n..] f (CoreVar x) = CoreVar $ show $ lookupJust x rens f (CoreLet binds x) = CoreLet [(show $ lookupJust a rens, b) | (a,b) <- binds] x f x = x -- algorithm: find each let , give it the number x , being its first variable -- pass all free variables at that point removeLets :: CoreFunc -> [CoreFunc] removeLets (CoreFunc name args body2) = res where body = mapOverCore g body2 where g (CoreLet [x] y) = CoreLet [x] y g (CoreLet (x:xs) y) = CoreLet [x] $ g $ CoreLet xs y g x = x res = CoreFunc name args (use body) : map gen lets lets = [x | x@(CoreLet{}) <- allCore body] gen (CoreLet binds body) = CoreFunc (name ++ "#" ++ fst (head binds)) free (use body) where free = freeVars body use x = mapOverCore f x where f (CoreLet binds body) = CoreApp (CoreFun (name ++ "#" ++ fst (head binds))) (map g free) where free = freeVars body g x = case lookup x binds of Just y -> y Nothing -> CoreVar x f x = x freeVars :: CoreExpr -> [String] freeVars x = nub $ f x where f (CoreLet bind x) = (f x ++ concatMap (f . snd) bind) \\ map fst bind f (CoreCase on alts) = f on ++ concatMap g alts f (CoreVar x) = [x] f x = concatMap f $ getChildrenCore x g (lhs,rhs) = f rhs \\ f lhs
null
https://raw.githubusercontent.com/ndmitchell/supero/a8b16ea90862e2c021bb139d7a7e9a83700b43b2/Dead/version1/Convert.hs
haskell
number the variables as appropriate algorithm: pass all free variables at that point
module Convert(convert, drop1mod) where import Type import Safe import Yhc.Core import Data.List import Data.Play import qualified Data.Map as Map import qualified Data.Set as Set convert :: Core -> Prog convert core = Prog (Map.fromList [(funcName x, x) | x <- concat fs]) where (n,fs) = mapAccumL convertFunc 0 $ coreFuncs $ fixPrims $ drop1mod core fixPrims :: Core -> Core fixPrims core = core{coreFuncs = mapUnderCore usePrim norm} where (prim,norm) = partition (isPrim . coreFuncBody) (coreFuncs core) prims = Set.fromList (map coreFuncName prim) usePrim (CoreFun x) | x `Set.member` prims = CorePrim x usePrim x = x isPrim (CorePos _ x) = isPrim x isPrim (CoreApp x []) = isPrim x isPrim (CoreVar x) = x == "primitive" isPrim _ = False drop1mod :: Core -> Core drop1mod (Core name imports datas funcs) = Core name imports (map g datas) (concatMap h funcs) where f x = case break (== '.') x of (_,"") -> x (_,_:xs) -> xs g (CoreData name free args) = CoreData (f name) free (map g2 args) g2 (CoreCtor name items) = CoreCtor (f name) items h (CoreFunc name args body) | name == "main" = [] | otherwise = [CoreFunc (f name) args (mapOverCore h2 body)] h2 (CoreFun x) = CoreFun $ f x h2 (CoreCon x) = CoreCon $ f x h2 x = x convertFunc :: Int -> CoreFunc -> (Int, [Func]) convertFunc n x = (n2, map f funcs2) where (n2,args2,expr2) = freshFree (coreFuncArgs x) (coreFuncBody x) n funcs2 = removeLets (CoreFunc (coreFuncName x) (map show args2) expr2) f (CoreFunc name args body) = Func name [FuncAlt 0 (map (Var . read) args) (convertExpr body)] convertExpr :: CoreExpr -> Expr convertExpr x = case x of CorePos _ x -> f x CoreCase x xs -> Case (f x) [(f a, f b) | (a,b) <- xs] CoreVar x -> Var $ read x CoreApp x xs -> Apply (f x) (fs xs) CoreCon x -> Ctr x CoreFun x -> Fun x CorePrim x -> Prim x CoreStr x -> Const $ ConstStr x CoreInt x -> Const $ ConstInt x CoreInteger x -> Const $ ConstInteger x CoreChr x -> Const $ ConstChr x _ -> error $ "Convert.convertExpr: " ++ show x where f = convertExpr fs = map f freshFree :: [String] -> CoreExpr -> Int -> (Int, [Int], CoreExpr) freshFree args x n = (n+nvars, map (`lookupJust` rens) args, mapOverCore f x) where nvars = length vars vars = nub $ args ++ [i | CoreVar i <- allCore x] rens = zip vars [n..] f (CoreVar x) = CoreVar $ show $ lookupJust x rens f (CoreLet binds x) = CoreLet [(show $ lookupJust a rens, b) | (a,b) <- binds] x f x = x find each let , give it the number x , being its first variable removeLets :: CoreFunc -> [CoreFunc] removeLets (CoreFunc name args body2) = res where body = mapOverCore g body2 where g (CoreLet [x] y) = CoreLet [x] y g (CoreLet (x:xs) y) = CoreLet [x] $ g $ CoreLet xs y g x = x res = CoreFunc name args (use body) : map gen lets lets = [x | x@(CoreLet{}) <- allCore body] gen (CoreLet binds body) = CoreFunc (name ++ "#" ++ fst (head binds)) free (use body) where free = freeVars body use x = mapOverCore f x where f (CoreLet binds body) = CoreApp (CoreFun (name ++ "#" ++ fst (head binds))) (map g free) where free = freeVars body g x = case lookup x binds of Just y -> y Nothing -> CoreVar x f x = x freeVars :: CoreExpr -> [String] freeVars x = nub $ f x where f (CoreLet bind x) = (f x ++ concatMap (f . snd) bind) \\ map fst bind f (CoreCase on alts) = f on ++ concatMap g alts f (CoreVar x) = [x] f x = concatMap f $ getChildrenCore x g (lhs,rhs) = f rhs \\ f lhs
82828e77e0b913d11c18b8213c19d4e87c373ca96f445c81908bdac343c2d16b
burz/Feval
EFAST.hs
# LANGUAGE FlexibleInstances # # LANGUAGE DeriveFunctor # module FVL.EFAST ( Expr(..) ) where import FVL.Algebra data Expr a = CInt Integer | CBool Bool | CVar String | Add a a | Sub a a | Mul a a | Div a a | Mod a a | And a a | Or a a | Not a | Equal a a | Less a a | LessEq a a | Great a a | GreatEq a a | Empty | Cons a a | If a a a | Function String a | Appl a a | Let String [String] a a | Semi a a | Case a a String String a deriving Functor showCons' :: Fix Expr -> [Fix Expr] showCons' (Fx (x `Cons` y)) = x : showCons' y showCons' e = [e] showCons :: Fix Expr -> Fix Expr -> String showCons x y = "[" ++ (foldr combine (show x) (showCons' y)) ++ "]" where combine (Fx Empty) b = b combine a b = b ++ ", " ++ show a instance Show (Fix Expr) where show (Fx (CInt n)) = show n show (Fx (CBool b)) = show b show (Fx (CVar s)) = s show (Fx (x `Add` y)) = show x ++ " + " ++ show y show (Fx (x `Sub` y)) = show x ++ " - " ++ show y show (Fx (x `Mul` y)) = show x ++ " * " ++ show y show (Fx (x `Div` y)) = show x ++ " / " ++ show y show (Fx (x `Mod` y)) = show x ++ " % " ++ show y show (Fx (x `And` y)) = show x ++ " && " ++ show y show (Fx (x `Or` y)) = show x ++ " || " ++ show y show (Fx (Not x)) = "!" ++ (case x of (Fx (CBool b)) -> show b (Fx (CVar s)) -> s _ -> "(" ++ show x ++ ")") show (Fx (x `Equal` y)) = show x ++ " = " ++ show y show (Fx (x `Less` y)) = show x ++ " < " ++ show y show (Fx (x `LessEq` y)) = show x ++ " <= " ++ show y show (Fx (x `Great` y)) = show x ++ " > " ++ show y show (Fx (x `GreatEq` y)) = show x ++ " >= " ++ show y show (Fx Empty) = "[]" show (Fx (x `Cons` y)) = showCons x y show (Fx (If p x y)) = "If " ++ show p ++ " Then " ++ show x ++ " Else " ++ show y show (Fx (Function x p)) = "Function " ++ x ++ " -> " ++ show p show (Fx (Appl f x)) = (case f of (Fx (CInt n)) -> show n ++ " " (Fx (CBool b)) -> show b ++ " " (Fx (CVar s)) -> s ++ " " (Fx (Appl _ _)) -> show f ++ " " _ -> "(" ++ show f ++ ") ") ++ (case x of (Fx (CInt n)) -> show n (Fx (CBool b)) -> show b (Fx (CVar s)) -> s (Fx (Appl _ _)) -> show x _ -> "(" ++ show x ++ ")") show (Fx (Let f a p e)) = "Let " ++ f ++ show_args ++ " = " ++ show p ++ " In " ++ show e where show_args = foldr (\x s -> " " ++ x ++ s) "" a show (Fx (Case p x s t y)) = "Case " ++ show x ++ " Of [] -> " ++ show x ++ " | (" ++ s ++ ", " ++ t ++ ") -> " ++ show y
null
https://raw.githubusercontent.com/burz/Feval/2e73b2bdc755ac103c0a3b97ad794a2d638986c5/FVL/EFAST.hs
haskell
# LANGUAGE FlexibleInstances # # LANGUAGE DeriveFunctor # module FVL.EFAST ( Expr(..) ) where import FVL.Algebra data Expr a = CInt Integer | CBool Bool | CVar String | Add a a | Sub a a | Mul a a | Div a a | Mod a a | And a a | Or a a | Not a | Equal a a | Less a a | LessEq a a | Great a a | GreatEq a a | Empty | Cons a a | If a a a | Function String a | Appl a a | Let String [String] a a | Semi a a | Case a a String String a deriving Functor showCons' :: Fix Expr -> [Fix Expr] showCons' (Fx (x `Cons` y)) = x : showCons' y showCons' e = [e] showCons :: Fix Expr -> Fix Expr -> String showCons x y = "[" ++ (foldr combine (show x) (showCons' y)) ++ "]" where combine (Fx Empty) b = b combine a b = b ++ ", " ++ show a instance Show (Fix Expr) where show (Fx (CInt n)) = show n show (Fx (CBool b)) = show b show (Fx (CVar s)) = s show (Fx (x `Add` y)) = show x ++ " + " ++ show y show (Fx (x `Sub` y)) = show x ++ " - " ++ show y show (Fx (x `Mul` y)) = show x ++ " * " ++ show y show (Fx (x `Div` y)) = show x ++ " / " ++ show y show (Fx (x `Mod` y)) = show x ++ " % " ++ show y show (Fx (x `And` y)) = show x ++ " && " ++ show y show (Fx (x `Or` y)) = show x ++ " || " ++ show y show (Fx (Not x)) = "!" ++ (case x of (Fx (CBool b)) -> show b (Fx (CVar s)) -> s _ -> "(" ++ show x ++ ")") show (Fx (x `Equal` y)) = show x ++ " = " ++ show y show (Fx (x `Less` y)) = show x ++ " < " ++ show y show (Fx (x `LessEq` y)) = show x ++ " <= " ++ show y show (Fx (x `Great` y)) = show x ++ " > " ++ show y show (Fx (x `GreatEq` y)) = show x ++ " >= " ++ show y show (Fx Empty) = "[]" show (Fx (x `Cons` y)) = showCons x y show (Fx (If p x y)) = "If " ++ show p ++ " Then " ++ show x ++ " Else " ++ show y show (Fx (Function x p)) = "Function " ++ x ++ " -> " ++ show p show (Fx (Appl f x)) = (case f of (Fx (CInt n)) -> show n ++ " " (Fx (CBool b)) -> show b ++ " " (Fx (CVar s)) -> s ++ " " (Fx (Appl _ _)) -> show f ++ " " _ -> "(" ++ show f ++ ") ") ++ (case x of (Fx (CInt n)) -> show n (Fx (CBool b)) -> show b (Fx (CVar s)) -> s (Fx (Appl _ _)) -> show x _ -> "(" ++ show x ++ ")") show (Fx (Let f a p e)) = "Let " ++ f ++ show_args ++ " = " ++ show p ++ " In " ++ show e where show_args = foldr (\x s -> " " ++ x ++ s) "" a show (Fx (Case p x s t y)) = "Case " ++ show x ++ " Of [] -> " ++ show x ++ " | (" ++ s ++ ", " ++ t ++ ") -> " ++ show y
77b6f5d96b6d03fde15f427ee2661d134b439266ca2d47054e04cecbcb2ff9c6
ocaml-flambda/ocaml-jst
user_error5.ml
TEST ocamlc_byte_exit_status = " 2 " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * check - ocamlc.byte - output ocamlc_byte_exit_status = "2" * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) What happens if the user tries to write one of the ocaml - jst extensions in terms of extension nodes but messes up ? In practice we do n't expect to ever see these errors , but one never knows ( and a bug in our desugaring could cause them ) . The let - binding is named after the constructor in [ extensions.ml ] representing this particular error . terms of extension nodes but messes up? In practice we don't expect to ever see these errors, but one never knows (and a bug in our desugaring could cause them). The let-binding is named after the constructor in [extensions.ml] representing this particular error. *) We can not use an expect - test here , because these are essentially parsing errors . The expect - test infrastructure uses Ast_mapper to prepare its input , and the call to Ast_mapper fails with a bogus extension setup , because it tries to decode extensions . We thus have this error and others like it in separate files , because the " compile and test output " infrastructure reports only one error at a time . errors. The expect-test infrastructure uses Ast_mapper to prepare its input, and the call to Ast_mapper fails with a bogus extension setup, because it tries to decode extensions. We thus have this error and others like it in separate files, because the "compile and test output" infrastructure reports only one error at a time. *) let _unnamed_extension = [%extension] ();; Line 1 , characters 25 - 40 : 1 | let _ unnamed_extension = [ % extension ] ( ) ; ; ^^^^^^^^^^^^^^^ Error : Can not have an extension node named [ % extension ] Line 1, characters 25-40: 1 | let _unnamed_extension = [%extension] ();; ^^^^^^^^^^^^^^^ Error: Cannot have an extension node named [%extension] *)
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/b1f0cf9f9114128db609bdd5a1edfda1e3144a30/testsuite/tests/jst-modular-extensions/user_error5.ml
ocaml
TEST ocamlc_byte_exit_status = " 2 " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * check - ocamlc.byte - output ocamlc_byte_exit_status = "2" * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) What happens if the user tries to write one of the ocaml - jst extensions in terms of extension nodes but messes up ? In practice we do n't expect to ever see these errors , but one never knows ( and a bug in our desugaring could cause them ) . The let - binding is named after the constructor in [ extensions.ml ] representing this particular error . terms of extension nodes but messes up? In practice we don't expect to ever see these errors, but one never knows (and a bug in our desugaring could cause them). The let-binding is named after the constructor in [extensions.ml] representing this particular error. *) We can not use an expect - test here , because these are essentially parsing errors . The expect - test infrastructure uses Ast_mapper to prepare its input , and the call to Ast_mapper fails with a bogus extension setup , because it tries to decode extensions . We thus have this error and others like it in separate files , because the " compile and test output " infrastructure reports only one error at a time . errors. The expect-test infrastructure uses Ast_mapper to prepare its input, and the call to Ast_mapper fails with a bogus extension setup, because it tries to decode extensions. We thus have this error and others like it in separate files, because the "compile and test output" infrastructure reports only one error at a time. *) let _unnamed_extension = [%extension] ();; Line 1 , characters 25 - 40 : 1 | let _ unnamed_extension = [ % extension ] ( ) ; ; ^^^^^^^^^^^^^^^ Error : Can not have an extension node named [ % extension ] Line 1, characters 25-40: 1 | let _unnamed_extension = [%extension] ();; ^^^^^^^^^^^^^^^ Error: Cannot have an extension node named [%extension] *)
1ef7af6dd1f2ade2baf3931c2d4508745d9674e305c67eee9b9dd8fa3e917919
locusmath/locus
object.clj
(ns locus.algebra.groupoid.element.object (:require [locus.set.logic.core.set :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.copresheaf.quiver.permutable.object :refer :all] [locus.algebra.category.core.object :refer :all] [locus.algebra.category.element.object :refer :all] [locus.algebra.category.core.morphism :refer :all] [locus.algebra.groupoid.core.object :refer :all] [locus.set.quiver.structure.core.protocols :refer :all]) (:import (locus.algebra.category.element.object CategoryObject) (locus.algebra.groupoid.core.object Groupoid))) Morphisms in a groupoid ; The difference between morphisms in a groupoid and morphisms in a more general ; category is that groupoid morphisms always implement the invertible interface, ; which takes a morphism in a groupoid to its corresponding inverse. (deftype GroupoidMorphism [groupoid morphism] Element (parent [this] groupoid) SectionElement (tag [this] 0) (member [this] morphism) IdentifiableInstance (unwrap [this] (list (tag this) (member this))) AbstractMorphism (source-object [this] (CategoryObject. groupoid (source-element groupoid morphism))) (target-object [this] (CategoryObject. groupoid (target-element groupoid morphism))) Invertible (inv [this] (GroupoidMorphism. groupoid (invert-morphism groupoid morphism)))) (derive GroupoidMorphism :locus.set.logic.structure.protocols/element) (defmethod wrap :locus.set.copresheaf.structure.core.protocols/groupoid [groupoid [i v]] (cond (= i 0) (GroupoidMorphism. groupoid v) (= i 1) (CategoryObject. groupoid v))) Composobality of groupoid morphisms (defmethod compose* GroupoidMorphism [a b] (let [^Groupoid groupoid (.groupoid a)] (->GroupoidMorphism groupoid ((.func groupoid) (list (.morphism a) (.morphism b)))))) ; Ontology of morphism elements of groupoids (defn groupoid-morphism? [element] (= (type element) GroupoidMorphism))
null
https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/algebra/groupoid/element/object.clj
clojure
The difference between morphisms in a groupoid and morphisms in a more general category is that groupoid morphisms always implement the invertible interface, which takes a morphism in a groupoid to its corresponding inverse. Ontology of morphism elements of groupoids
(ns locus.algebra.groupoid.element.object (:require [locus.set.logic.core.set :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.copresheaf.quiver.permutable.object :refer :all] [locus.algebra.category.core.object :refer :all] [locus.algebra.category.element.object :refer :all] [locus.algebra.category.core.morphism :refer :all] [locus.algebra.groupoid.core.object :refer :all] [locus.set.quiver.structure.core.protocols :refer :all]) (:import (locus.algebra.category.element.object CategoryObject) (locus.algebra.groupoid.core.object Groupoid))) Morphisms in a groupoid (deftype GroupoidMorphism [groupoid morphism] Element (parent [this] groupoid) SectionElement (tag [this] 0) (member [this] morphism) IdentifiableInstance (unwrap [this] (list (tag this) (member this))) AbstractMorphism (source-object [this] (CategoryObject. groupoid (source-element groupoid morphism))) (target-object [this] (CategoryObject. groupoid (target-element groupoid morphism))) Invertible (inv [this] (GroupoidMorphism. groupoid (invert-morphism groupoid morphism)))) (derive GroupoidMorphism :locus.set.logic.structure.protocols/element) (defmethod wrap :locus.set.copresheaf.structure.core.protocols/groupoid [groupoid [i v]] (cond (= i 0) (GroupoidMorphism. groupoid v) (= i 1) (CategoryObject. groupoid v))) Composobality of groupoid morphisms (defmethod compose* GroupoidMorphism [a b] (let [^Groupoid groupoid (.groupoid a)] (->GroupoidMorphism groupoid ((.func groupoid) (list (.morphism a) (.morphism b)))))) (defn groupoid-morphism? [element] (= (type element) GroupoidMorphism))
8885ecdb701e3e25b00c9e422d930c0685fd1ef0642147b08c171f69936775d0
ocaml-gospel/gospel
PairingHeap.mli
(**************************************************************************) (* *) VOCaL -- A Verified OCaml Library (* *) Copyright ( c ) 2020 The VOCaL Project (* *) This software is free software , distributed under the MIT license (* (as described in file LICENSE enclosed). *) (**************************************************************************) module Make (X : sig FIXME : use ComparableType . S instead type t (*@ function cmp: t -> t -> int *) (*@ axiom is_pre_order: Order.is_pre_order cmp *) val compare : t -> t -> int (*@ r = compare x y ensures r = cmp x y *) end) : sig type elt = X.t type t (*@ model bag : elt bag *) val empty : unit -> t @ h = empty ( ) ensures Bag.cardinal h.bag = 0 ensures forall x. Bag.occurrences x h.bag = 0 ensures Bag.cardinal h.bag = 0 ensures forall x. Bag.occurrences x h.bag = 0 *) val is_empty : t -> bool (*@ b = is_empty h ensures b <-> Bag.is_empty h.bag *) val merge : t -> t -> t @ h = merge h1 h2 ensures Bag.cardinal h.bag = Bag.cardinal h1.bag + Bag.cardinal h2.bag ensures forall x. Bag.occurrences x h.bag = Bag.occurrences x h1.bag + Bag.occurrences x h2.bag ensures Bag.cardinal h.bag = Bag.cardinal h1.bag + Bag.cardinal h2.bag ensures forall x. Bag.occurrences x h.bag = Bag.occurrences x h1.bag + Bag.occurrences x h2.bag *) val insert : elt -> t -> t @ h ' = insert x h ensures Bag.occurrences x h'.bag = Bag.occurrences x h.bag + 1 ensures forall y. y < > x - > Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag + 1 ensures Bag.occurrences x h'.bag = Bag.occurrences x h.bag + 1 ensures forall y. y <> x -> Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag + 1 *) @ predicate mem ( x : elt ) ( h : t ) = Bag.occurrences x h.bag > 0 @ predicate is_minimum ( x : elt ) ( h : t ) = h /\ forall > X.cmp x e < = 0 mem x h /\ forall e. mem e h -> X.cmp x e <= 0 *) (*@ function minimum (h: t) : elt *) @ axiom min_def : forall h. 0 < Bag.cardinal h.bag - > is_minimum ( minimum h ) h val find_min : t -> elt @ x = find_min h requires Bag.cardinal h.bag > 0 ensures x = minimum h requires Bag.cardinal h.bag > 0 ensures x = minimum h *) val delete_min : t -> t @ h ' = requires Bag.cardinal h.bag > 0 ensures let x = minimum h in Bag.occurrences x h'.bag = Bag.occurrences x h.bag - 1 ensures forall y. y < > minimum h - > Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag - 1 requires Bag.cardinal h.bag > 0 ensures let x = minimum h in Bag.occurrences x h'.bag = Bag.occurrences x h.bag - 1 ensures forall y. y <> minimum h -> Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag - 1 *) end (* {gospel_expected| [0] OK |gospel_expected} *)
null
https://raw.githubusercontent.com/ocaml-gospel/gospel/bd213d7fdfaf224666acb413efc49f872251bca7/test/vocal/PairingHeap.mli
ocaml
************************************************************************ (as described in file LICENSE enclosed). ************************************************************************ @ function cmp: t -> t -> int @ axiom is_pre_order: Order.is_pre_order cmp @ r = compare x y ensures r = cmp x y @ model bag : elt bag @ b = is_empty h ensures b <-> Bag.is_empty h.bag @ function minimum (h: t) : elt {gospel_expected| [0] OK |gospel_expected}
VOCaL -- A Verified OCaml Library Copyright ( c ) 2020 The VOCaL Project This software is free software , distributed under the MIT license module Make (X : sig FIXME : use ComparableType . S instead type t val compare : t -> t -> int end) : sig type elt = X.t type t val empty : unit -> t @ h = empty ( ) ensures Bag.cardinal h.bag = 0 ensures forall x. Bag.occurrences x h.bag = 0 ensures Bag.cardinal h.bag = 0 ensures forall x. Bag.occurrences x h.bag = 0 *) val is_empty : t -> bool val merge : t -> t -> t @ h = merge h1 h2 ensures Bag.cardinal h.bag = Bag.cardinal h1.bag + Bag.cardinal h2.bag ensures forall x. Bag.occurrences x h.bag = Bag.occurrences x h1.bag + Bag.occurrences x h2.bag ensures Bag.cardinal h.bag = Bag.cardinal h1.bag + Bag.cardinal h2.bag ensures forall x. Bag.occurrences x h.bag = Bag.occurrences x h1.bag + Bag.occurrences x h2.bag *) val insert : elt -> t -> t @ h ' = insert x h ensures Bag.occurrences x h'.bag = Bag.occurrences x h.bag + 1 ensures forall y. y < > x - > Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag + 1 ensures Bag.occurrences x h'.bag = Bag.occurrences x h.bag + 1 ensures forall y. y <> x -> Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag + 1 *) @ predicate mem ( x : elt ) ( h : t ) = Bag.occurrences x h.bag > 0 @ predicate is_minimum ( x : elt ) ( h : t ) = h /\ forall > X.cmp x e < = 0 mem x h /\ forall e. mem e h -> X.cmp x e <= 0 *) @ axiom min_def : forall h. 0 < Bag.cardinal h.bag - > is_minimum ( minimum h ) h val find_min : t -> elt @ x = find_min h requires Bag.cardinal h.bag > 0 ensures x = minimum h requires Bag.cardinal h.bag > 0 ensures x = minimum h *) val delete_min : t -> t @ h ' = requires Bag.cardinal h.bag > 0 ensures let x = minimum h in Bag.occurrences x h'.bag = Bag.occurrences x h.bag - 1 ensures forall y. y < > minimum h - > Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag - 1 requires Bag.cardinal h.bag > 0 ensures let x = minimum h in Bag.occurrences x h'.bag = Bag.occurrences x h.bag - 1 ensures forall y. y <> minimum h -> Bag.occurrences y h'.bag = Bag.occurrences y h.bag ensures Bag.cardinal h'.bag = Bag.cardinal h.bag - 1 *) end
07ba18dce601f8117bdebc517f424a2fc67ec092e7be0f97b2f65783c4434507
minoki/haskell-floating-point
RoundToIntegralSpec.hs
module RoundToIntegralSpec where import Data.Proxy import Numeric.Floating.IEEE import Numeric.Floating.IEEE.Internal import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck hiding (classify) import Util prop_roundToIntegral :: (RealFloat a, Show a) => Proxy a -> a -> Property prop_roundToIntegral _ x = isFinite x ==> let tiesToEven = round' x tiesToEvenInt = round x :: Integer tiesToAway = roundAway' x tiesToAwayInt = roundAway x :: Integer towardPositive = ceiling' x towardPositiveInt = ceiling x :: Integer towardNegative = floor' x towardNegativeInt = floor x :: Integer towardZero = truncate' x towardZeroInt = truncate x :: Integer sameInteger f i = round f === i .&&. f === fromInteger i in conjoin [ counterexample "tiesToEven" $ isFinite tiesToEven .&&. sameInteger tiesToEven tiesToEvenInt , counterexample "tiesToAway" $ isFinite tiesToAway .&&. sameInteger tiesToAway tiesToAwayInt , counterexample "towardPositive" $ isFinite towardPositive .&&. sameInteger towardPositive towardPositiveInt , counterexample "towardNegative" $ isFinite towardNegative .&&. sameInteger towardNegative towardNegativeInt , counterexample "towardZero" $ isFinite towardZero .&&. sameInteger towardZero towardZeroInt , counterexample "towardNegative <= original value" $ towardNegative <= x , counterexample "towardNegative <= tiesToEven" $ towardNegative <= tiesToEven , counterexample "towardNegative <= tiesToAway" $ towardNegative <= tiesToAway , counterexample "towardNegative <= towardPositive" $ towardNegative <= towardPositive , counterexample "towardNegative <= towardZero" $ towardNegative <= towardZero , counterexample "original value <= towardPositive" $ x <= towardPositive , counterexample "tiesToEven <= towardPositive" $ tiesToEven <= towardPositive , counterexample "tiesToAway <= towardPositive" $ tiesToAway <= towardPositive , counterexample "towardZero <= towardPositive" $ towardZero <= towardPositive , counterexample "abs towardZero <= abs (original value)" $ abs towardZero <= abs x , counterexample "abs towardZero <= abs tiesToEven" $ abs towardZero <= abs tiesToEven , counterexample "abs towardZero <= abs tiesToAway" $ abs towardZero <= abs tiesToAway , counterexample "abs towardZero <= abs towardPositive" $ abs towardZero <= abs towardPositive , counterexample "abs towardZero <= abs towardNegative" $ abs towardZero <= abs towardNegative ] data RoundResult a = RoundResult { resultTiesToEven :: a , resultTiesToAway :: a , resultTowardPositive :: a , resultTowardNegative :: a , resultTowardZero :: a } checkBehavior :: RealFloat a => Proxy a -> a -> RoundResult a -> RoundResult Integer -> Spec checkBehavior _ x result resultI = do it "tiesToEven" $ round' x `sameFloatP` resultTiesToEven result it "tiesToEven (Integer)" $ round x `shouldBe` resultTiesToEven resultI it "tiesToAway" $ roundAway' x `sameFloatP` resultTiesToAway result it "tiesToAway (Integer)" $ roundAway x `shouldBe` resultTiesToAway resultI it "ceiling" $ ceiling' x `sameFloatP` resultTowardPositive result it "ceiling (Integer)" $ ceiling x `shouldBe` resultTowardPositive resultI it "floor" $ floor' x `sameFloatP` resultTowardNegative result it "floor (Integer)" $ floor x `shouldBe` resultTowardNegative resultI it "truncate" $ truncate' x `sameFloatP` resultTowardZero result it "truncate (Integer)" $ truncate x `shouldBe` resultTowardZero resultI checkCases :: RealFloat a => Proxy a -> Spec checkCases proxy = do describe "0.5" $ checkBehavior proxy 0.5 RoundResult { resultTiesToEven = 0.0 , resultTiesToAway = 1.0 , resultTowardPositive = 1.0 , resultTowardNegative = 0.0 , resultTowardZero = 0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = 1 , resultTowardPositive = 1 , resultTowardNegative = 0 , resultTowardZero = 0 } describe "0.25" $ checkBehavior proxy 0.25 RoundResult { resultTiesToEven = 0.0 , resultTiesToAway = 0.0 , resultTowardPositive = 1.0 , resultTowardNegative = 0.0 , resultTowardZero = 0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = 0 , resultTowardPositive = 1 , resultTowardNegative = 0 , resultTowardZero = 0 } describe "-0.25" $ checkBehavior proxy (-0.25) RoundResult { resultTiesToEven = -0.0 , resultTiesToAway = -0.0 , resultTowardPositive = -0.0 , resultTowardNegative = -1.0 , resultTowardZero = -0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = 0 , resultTowardPositive = 0 , resultTowardNegative = -1 , resultTowardZero = 0 } describe "-0.5" $ checkBehavior proxy (-0.5) RoundResult { resultTiesToEven = -0.0 , resultTiesToAway = -1.0 , resultTowardPositive = -0.0 , resultTowardNegative = -1.0 , resultTowardZero = -0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = -1 , resultTowardPositive = 0 , resultTowardNegative = -1 , resultTowardZero = 0 } describe "4.5" $ checkBehavior proxy 4.5 RoundResult { resultTiesToEven = 4.0 , resultTiesToAway = 5.0 , resultTowardPositive = 5.0 , resultTowardNegative = 4.0 , resultTowardZero = 4.0 } RoundResult { resultTiesToEven = 4 , resultTiesToAway = 5 , resultTowardPositive = 5 , resultTowardNegative = 4 , resultTowardZero = 4 } describe "-5.5" $ checkBehavior proxy (-5.5) RoundResult { resultTiesToEven = -6.0 , resultTiesToAway = -6.0 , resultTowardPositive = -5.0 , resultTowardNegative = -6.0 , resultTowardZero = -5.0 } RoundResult { resultTiesToEven = -6 , resultTiesToAway = -6 , resultTowardPositive = -5 , resultTowardNegative = -6 , resultTowardZero = -5 } describe "-6.5" $ checkBehavior proxy (-6.5) RoundResult { resultTiesToEven = -6.0 , resultTiesToAway = -7.0 , resultTowardPositive = -6.0 , resultTowardNegative = -7.0 , resultTowardZero = -6.0 } RoundResult { resultTiesToEven = -6 , resultTiesToAway = -7 , resultTowardPositive = -6 , resultTowardNegative = -7 , resultTowardZero = -6 } # NOINLINE spec # spec :: Spec spec = do describe "Double" $ do let proxy :: Proxy Double proxy = Proxy prop "roundToIntegral" $ prop_roundToIntegral proxy checkCases proxy describe "Float" $ do let proxy :: Proxy Double proxy = Proxy prop "roundToIntegral" $ prop_roundToIntegral proxy checkCases proxy
null
https://raw.githubusercontent.com/minoki/haskell-floating-point/7d7bb31bb2b07c637a5eaeda92fc622566e9b141/fp-ieee/test/RoundToIntegralSpec.hs
haskell
module RoundToIntegralSpec where import Data.Proxy import Numeric.Floating.IEEE import Numeric.Floating.IEEE.Internal import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck hiding (classify) import Util prop_roundToIntegral :: (RealFloat a, Show a) => Proxy a -> a -> Property prop_roundToIntegral _ x = isFinite x ==> let tiesToEven = round' x tiesToEvenInt = round x :: Integer tiesToAway = roundAway' x tiesToAwayInt = roundAway x :: Integer towardPositive = ceiling' x towardPositiveInt = ceiling x :: Integer towardNegative = floor' x towardNegativeInt = floor x :: Integer towardZero = truncate' x towardZeroInt = truncate x :: Integer sameInteger f i = round f === i .&&. f === fromInteger i in conjoin [ counterexample "tiesToEven" $ isFinite tiesToEven .&&. sameInteger tiesToEven tiesToEvenInt , counterexample "tiesToAway" $ isFinite tiesToAway .&&. sameInteger tiesToAway tiesToAwayInt , counterexample "towardPositive" $ isFinite towardPositive .&&. sameInteger towardPositive towardPositiveInt , counterexample "towardNegative" $ isFinite towardNegative .&&. sameInteger towardNegative towardNegativeInt , counterexample "towardZero" $ isFinite towardZero .&&. sameInteger towardZero towardZeroInt , counterexample "towardNegative <= original value" $ towardNegative <= x , counterexample "towardNegative <= tiesToEven" $ towardNegative <= tiesToEven , counterexample "towardNegative <= tiesToAway" $ towardNegative <= tiesToAway , counterexample "towardNegative <= towardPositive" $ towardNegative <= towardPositive , counterexample "towardNegative <= towardZero" $ towardNegative <= towardZero , counterexample "original value <= towardPositive" $ x <= towardPositive , counterexample "tiesToEven <= towardPositive" $ tiesToEven <= towardPositive , counterexample "tiesToAway <= towardPositive" $ tiesToAway <= towardPositive , counterexample "towardZero <= towardPositive" $ towardZero <= towardPositive , counterexample "abs towardZero <= abs (original value)" $ abs towardZero <= abs x , counterexample "abs towardZero <= abs tiesToEven" $ abs towardZero <= abs tiesToEven , counterexample "abs towardZero <= abs tiesToAway" $ abs towardZero <= abs tiesToAway , counterexample "abs towardZero <= abs towardPositive" $ abs towardZero <= abs towardPositive , counterexample "abs towardZero <= abs towardNegative" $ abs towardZero <= abs towardNegative ] data RoundResult a = RoundResult { resultTiesToEven :: a , resultTiesToAway :: a , resultTowardPositive :: a , resultTowardNegative :: a , resultTowardZero :: a } checkBehavior :: RealFloat a => Proxy a -> a -> RoundResult a -> RoundResult Integer -> Spec checkBehavior _ x result resultI = do it "tiesToEven" $ round' x `sameFloatP` resultTiesToEven result it "tiesToEven (Integer)" $ round x `shouldBe` resultTiesToEven resultI it "tiesToAway" $ roundAway' x `sameFloatP` resultTiesToAway result it "tiesToAway (Integer)" $ roundAway x `shouldBe` resultTiesToAway resultI it "ceiling" $ ceiling' x `sameFloatP` resultTowardPositive result it "ceiling (Integer)" $ ceiling x `shouldBe` resultTowardPositive resultI it "floor" $ floor' x `sameFloatP` resultTowardNegative result it "floor (Integer)" $ floor x `shouldBe` resultTowardNegative resultI it "truncate" $ truncate' x `sameFloatP` resultTowardZero result it "truncate (Integer)" $ truncate x `shouldBe` resultTowardZero resultI checkCases :: RealFloat a => Proxy a -> Spec checkCases proxy = do describe "0.5" $ checkBehavior proxy 0.5 RoundResult { resultTiesToEven = 0.0 , resultTiesToAway = 1.0 , resultTowardPositive = 1.0 , resultTowardNegative = 0.0 , resultTowardZero = 0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = 1 , resultTowardPositive = 1 , resultTowardNegative = 0 , resultTowardZero = 0 } describe "0.25" $ checkBehavior proxy 0.25 RoundResult { resultTiesToEven = 0.0 , resultTiesToAway = 0.0 , resultTowardPositive = 1.0 , resultTowardNegative = 0.0 , resultTowardZero = 0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = 0 , resultTowardPositive = 1 , resultTowardNegative = 0 , resultTowardZero = 0 } describe "-0.25" $ checkBehavior proxy (-0.25) RoundResult { resultTiesToEven = -0.0 , resultTiesToAway = -0.0 , resultTowardPositive = -0.0 , resultTowardNegative = -1.0 , resultTowardZero = -0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = 0 , resultTowardPositive = 0 , resultTowardNegative = -1 , resultTowardZero = 0 } describe "-0.5" $ checkBehavior proxy (-0.5) RoundResult { resultTiesToEven = -0.0 , resultTiesToAway = -1.0 , resultTowardPositive = -0.0 , resultTowardNegative = -1.0 , resultTowardZero = -0.0 } RoundResult { resultTiesToEven = 0 , resultTiesToAway = -1 , resultTowardPositive = 0 , resultTowardNegative = -1 , resultTowardZero = 0 } describe "4.5" $ checkBehavior proxy 4.5 RoundResult { resultTiesToEven = 4.0 , resultTiesToAway = 5.0 , resultTowardPositive = 5.0 , resultTowardNegative = 4.0 , resultTowardZero = 4.0 } RoundResult { resultTiesToEven = 4 , resultTiesToAway = 5 , resultTowardPositive = 5 , resultTowardNegative = 4 , resultTowardZero = 4 } describe "-5.5" $ checkBehavior proxy (-5.5) RoundResult { resultTiesToEven = -6.0 , resultTiesToAway = -6.0 , resultTowardPositive = -5.0 , resultTowardNegative = -6.0 , resultTowardZero = -5.0 } RoundResult { resultTiesToEven = -6 , resultTiesToAway = -6 , resultTowardPositive = -5 , resultTowardNegative = -6 , resultTowardZero = -5 } describe "-6.5" $ checkBehavior proxy (-6.5) RoundResult { resultTiesToEven = -6.0 , resultTiesToAway = -7.0 , resultTowardPositive = -6.0 , resultTowardNegative = -7.0 , resultTowardZero = -6.0 } RoundResult { resultTiesToEven = -6 , resultTiesToAway = -7 , resultTowardPositive = -6 , resultTowardNegative = -7 , resultTowardZero = -6 } # NOINLINE spec # spec :: Spec spec = do describe "Double" $ do let proxy :: Proxy Double proxy = Proxy prop "roundToIntegral" $ prop_roundToIntegral proxy checkCases proxy describe "Float" $ do let proxy :: Proxy Double proxy = Proxy prop "roundToIntegral" $ prop_roundToIntegral proxy checkCases proxy
240235642a13d7802d676c1cd2bb7544ecf767556a333adf8616615e220f1fcf
tamarin-prover/tamarin-prover
Definitions.hs
-- | Copyright : ( c ) 2010 - 2012 , -- License : GPL v3 (see LICENSE) -- Maintainer : < > -- -- Term Equalities, Matching Problems, and Subterm Rules. module Term.Rewriting.Definitions ( -- * Equalities Equal (..) , evalEqual -- * Matching problems , Match(..) , flattenMatch , matchWith , matchOnlyIf -- * Rewriting rules , RRule(..) ) where import Control.Arrow ( (***) ) import Control . Applicative import Extension . Data . Monoid import Data . Foldable import Data . ---------------------------------------------------------------------- -- Equalities, matching problems, and rewriting rules ---------------------------------------------------------------------- -- | An equality. data Equal a = Equal { eqLHS :: a, eqRHS :: a } deriving (Eq, Show) | True iff the two sides of the equality are equal with respect to their ' ' instance . evalEqual :: Eq a => Equal a -> Bool evalEqual (Equal l r) = l == r instance Functor Equal where fmap f (Equal lhs rhs) = Equal (f lhs) (f rhs) instance Semigroup a => Semigroup (Equal a) where (Equal l1 r1) <> (Equal l2 r2) = Equal (l1 <> l2) (r1 <> r2) instance Monoid a => Monoid (Equal a) where mempty = Equal mempty mempty instance Foldable Equal where foldMap f (Equal l r) = f l `mappend` f r instance Traversable Equal where traverse f (Equal l r) = Equal <$> f l <*> f r instance Applicative Equal where pure x = Equal x x (Equal fl fr) <*> (Equal l r) = Equal (fl l) (fr r) -- | Matching problems. Use the 'Monoid' instance to compose matching -- problems. data Match a = NoMatch -- ^ No matcher exists. | DelayedMatches [(a,a)] -- ^ A bunch of delayed (term,pattern) pairs. instance Eq a => Eq (Match a) where x == y = flattenMatch x == flattenMatch y instance Show a => Show (Match a) where show = show . flattenMatch Smart constructors --------------------- -- | Ensure that matching only succeeds if the condition holds. matchOnlyIf :: Bool -> Match a matchOnlyIf False = NoMatch matchOnlyIf True = mempty -- | Match a term with a pattern. matchWith :: a -- ^ Term -> a -- ^ Pattern -> Match a -- ^ Matching problem. matchWith t p = DelayedMatches [(t, p)] -- Destructors -------------- -- | Flatten a matching problem to a list of (term,pattern) pairs. If no -- matcher exists, then 'Nothing' is returned. flattenMatch :: Match a -> Maybe [(a, a)] flattenMatch NoMatch = Nothing flattenMatch (DelayedMatches ms) = Just ms -- Instances ------------ instance Functor Match where fmap _ NoMatch = NoMatch fmap f (DelayedMatches ms) = DelayedMatches (fmap (f *** f) ms) instance Semigroup (Match a) where NoMatch <> _ = NoMatch _ <> NoMatch = NoMatch DelayedMatches ms1 <> DelayedMatches ms2 = DelayedMatches (ms1 <> ms2) instance Monoid (Match a) where mempty = DelayedMatches [] instance Foldable Match where foldMap _ NoMatch = mempty foldMap f (DelayedMatches ms) = foldMap (\(t, p) -> f t <> f p) ms instance Traversable Match where traverse _ NoMatch = pure NoMatch traverse f (DelayedMatches ms) = DelayedMatches <$> traverse (\(t, p) -> (,) <$> f t <*> f p) ms instance Applicative Match where pure x = MatchWith x x ( MatchWith ft fp ) < * > ( MatchWith t p ) = MatchWith ( ft t ) ( fp p ) instance Applicative Match where pure x = MatchWith x x (MatchWith ft fp) <*> (MatchWith t p) = MatchWith (ft t) (fp p) -} -- | A rewrite rule. data RRule a = RRule a a deriving (Show, Ord, Eq) instance Functor RRule where fmap f (RRule lhs rhs) = RRule (f lhs) (f rhs) instance Monoid a => Semigroup (RRule a) where (RRule l1 r1) <> (RRule l2 r2) = RRule (l1 <> l2) (r1 <> r2) instance Monoid a => Monoid (RRule a) where mempty = RRule mempty mempty instance Foldable RRule where foldMap f (RRule l r) = f l `mappend` f r instance Traversable RRule where traverse f (RRule l r) = RRule <$> f l <*> f r instance Applicative RRule where pure x = RRule x x (RRule fl fr) <*> (RRule l r) = RRule (fl l) (fr r)
null
https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/c78c7afd3b93b52dd4d2884952ec0fc273832a0d/lib/term/src/Term/Rewriting/Definitions.hs
haskell
| License : GPL v3 (see LICENSE) Term Equalities, Matching Problems, and Subterm Rules. * Equalities * Matching problems * Rewriting rules -------------------------------------------------------------------- Equalities, matching problems, and rewriting rules -------------------------------------------------------------------- | An equality. | Matching problems. Use the 'Monoid' instance to compose matching problems. ^ No matcher exists. ^ A bunch of delayed (term,pattern) pairs. ------------------- | Ensure that matching only succeeds if the condition holds. | Match a term with a pattern. ^ Term ^ Pattern ^ Matching problem. Destructors ------------ | Flatten a matching problem to a list of (term,pattern) pairs. If no matcher exists, then 'Nothing' is returned. Instances ---------- | A rewrite rule.
Copyright : ( c ) 2010 - 2012 , Maintainer : < > module Term.Rewriting.Definitions ( Equal (..) , evalEqual , Match(..) , flattenMatch , matchWith , matchOnlyIf , RRule(..) ) where import Control.Arrow ( (***) ) import Control . Applicative import Extension . Data . Monoid import Data . Foldable import Data . data Equal a = Equal { eqLHS :: a, eqRHS :: a } deriving (Eq, Show) | True iff the two sides of the equality are equal with respect to their ' ' instance . evalEqual :: Eq a => Equal a -> Bool evalEqual (Equal l r) = l == r instance Functor Equal where fmap f (Equal lhs rhs) = Equal (f lhs) (f rhs) instance Semigroup a => Semigroup (Equal a) where (Equal l1 r1) <> (Equal l2 r2) = Equal (l1 <> l2) (r1 <> r2) instance Monoid a => Monoid (Equal a) where mempty = Equal mempty mempty instance Foldable Equal where foldMap f (Equal l r) = f l `mappend` f r instance Traversable Equal where traverse f (Equal l r) = Equal <$> f l <*> f r instance Applicative Equal where pure x = Equal x x (Equal fl fr) <*> (Equal l r) = Equal (fl l) (fr r) data Match a = NoMatch | DelayedMatches [(a,a)] instance Eq a => Eq (Match a) where x == y = flattenMatch x == flattenMatch y instance Show a => Show (Match a) where show = show . flattenMatch Smart constructors matchOnlyIf :: Bool -> Match a matchOnlyIf False = NoMatch matchOnlyIf True = mempty matchWith t p = DelayedMatches [(t, p)] flattenMatch :: Match a -> Maybe [(a, a)] flattenMatch NoMatch = Nothing flattenMatch (DelayedMatches ms) = Just ms instance Functor Match where fmap _ NoMatch = NoMatch fmap f (DelayedMatches ms) = DelayedMatches (fmap (f *** f) ms) instance Semigroup (Match a) where NoMatch <> _ = NoMatch _ <> NoMatch = NoMatch DelayedMatches ms1 <> DelayedMatches ms2 = DelayedMatches (ms1 <> ms2) instance Monoid (Match a) where mempty = DelayedMatches [] instance Foldable Match where foldMap _ NoMatch = mempty foldMap f (DelayedMatches ms) = foldMap (\(t, p) -> f t <> f p) ms instance Traversable Match where traverse _ NoMatch = pure NoMatch traverse f (DelayedMatches ms) = DelayedMatches <$> traverse (\(t, p) -> (,) <$> f t <*> f p) ms instance Applicative Match where pure x = MatchWith x x ( MatchWith ft fp ) < * > ( MatchWith t p ) = MatchWith ( ft t ) ( fp p ) instance Applicative Match where pure x = MatchWith x x (MatchWith ft fp) <*> (MatchWith t p) = MatchWith (ft t) (fp p) -} data RRule a = RRule a a deriving (Show, Ord, Eq) instance Functor RRule where fmap f (RRule lhs rhs) = RRule (f lhs) (f rhs) instance Monoid a => Semigroup (RRule a) where (RRule l1 r1) <> (RRule l2 r2) = RRule (l1 <> l2) (r1 <> r2) instance Monoid a => Monoid (RRule a) where mempty = RRule mempty mempty instance Foldable RRule where foldMap f (RRule l r) = f l `mappend` f r instance Traversable RRule where traverse f (RRule l r) = RRule <$> f l <*> f r instance Applicative RRule where pure x = RRule x x (RRule fl fr) <*> (RRule l r) = RRule (fl l) (fr r)
4674102d0b2357b675f0ffe30ac995d12b45cc22304235daf24925aa3de740ab
borkdude/dynaload
dynaload.cljc
(ns borkdude.dynaload #?(:cljs (:require-macros [borkdude.dynaload :refer [dynaload if-bb]]))) (defmacro if-bb [then else] (if #?(:clj (System/getProperty "babashka.version") :cljs false) then else)) (if-bb #?(:clj (defn ->LazyVar [f _] (let [cached (volatile! nil)] (reify clojure.lang.IDeref (deref [_this] (if-not (nil? @cached) cached (let [x (f)] (when-not (nil? x) (vreset! cached x)) x))) clojure.lang.IFn (invoke [this] (@this)) (invoke [this a] (@this a)) (invoke [this a b] (@this a b)) (invoke [this a b c] (@this a b c)) (invoke [this a b c d] (@this a b c d)) (invoke [this a b c d e] (@this a b c d e)) (invoke [this a b c d e f] (@this a b c d e f)) (invoke [this a b c d e f g] (@this a b c d e f g)) (invoke [this a b c d e f g h] (@this a b c d e f g h)) (invoke [this a b c d e f g h i] (@this a b c d e f g h i)) (invoke [this a b c d e f g h i j] (@this a b c d e f g h i j)) (invoke [this a b c d e f g h i j k] (@this a b c d e f g h i j k)) (invoke [this a b c d e f g h i j k l] (@this a b c d e f g h i j k l)) (invoke [this a b c d e f g h i j k l m] (@this a b c d e f g h i j k l m)) (invoke [this a b c d e f g h i j k l m n] (@this a b c d e f g h i j k l m n)) (invoke [this a b c d e f g h i j k l m n o] (@this a b c d e f g h i j k l m n o)) (invoke [this a b c d e f g h i j k l m n o p] (@this a b c d e f g h i j k l m n o p)) (invoke [this a b c d e f g h i j k l m n o p q] (@this a b c d e f g h i j k l m n o p q)) (invoke [this a b c d e f g h i j k l m n o p q r] (@this a b c d e f g h i j k l m n o p q r)) (invoke [this a b c d e f g h i j k l m n o p q r s] (@this a b c d e f g h i j k l m n o p q r s)) ;; for some reason not working yet in bb #_(invoke [this a b c d e f g h i j k l m n o p q r s t] (@this a b c d e f g h i j k l m n o p q r s t)) #_(invoke [this a b c d e f g h i j k l m n o p q r s t rest] (apply @this a b c d e f g h i j k l m n o p q r s t rest)) (applyTo [this args] (apply @this args))))) :cljs nil) #?(:org.babashka/nbb nil :default (deftype LazyVar #?(:clj [f ^:volatile-mutable cached] :cljs [f ^:mutable cached]) #?(:clj clojure.lang.IDeref :cljs IDeref) (#?(:clj deref :cljs -deref) [_this] (if-not (nil? cached) cached (let [x (f)] (when-not (nil? x) (set! cached x)) x))) #?(:clj clojure.lang.IFn :cljs IFn) (#?(:clj invoke :cljs -invoke) [this] (@this)) (#?(:clj invoke :cljs -invoke) [this a] (@this a)) (#?(:clj invoke :cljs -invoke) [this a b] (@this a b)) (#?(:clj invoke :cljs -invoke) [this a b c] (@this a b c)) (#?(:clj invoke :cljs -invoke) [this a b c d] (@this a b c d)) (#?(:clj invoke :cljs -invoke) [this a b c d e] (@this a b c d e)) (#?(:clj invoke :cljs -invoke) [this a b c d e f] (@this a b c d e f)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g] (@this a b c d e f g)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h] (@this a b c d e f g h)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i] (@this a b c d e f g h i)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j] (@this a b c d e f g h i j)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k] (@this a b c d e f g h i j k)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l] (@this a b c d e f g h i j k l)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m] (@this a b c d e f g h i j k l m)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n] (@this a b c d e f g h i j k l m n)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o] (@this a b c d e f g h i j k l m n o)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p] (@this a b c d e f g h i j k l m n o p)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q] (@this a b c d e f g h i j k l m n o p q)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r] (@this a b c d e f g h i j k l m n o p q r)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r s] (@this a b c d e f g h i j k l m n o p q r s)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r s t] (@this a b c d e f g h i j k l m n o p q r s t)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r s t rest] (apply @this a b c d e f g h i j k l m n o p q r s t rest)) #?(:clj (applyTo [this args] (apply @this args)))))) (defmacro ? [& {:keys [cljs clj]}] (if (contains? &env '&env) `(if (:ns ~'&env) ~cljs ~clj) (if #?(:clj (:ns &env) :cljs true) cljs clj))) #?(:clj (def resolve-at-compile-time? (= "true" (System/getProperty "borkdude.dynaload.aot")))) #?(:clj (defonce ^:private dynalock (Object.))) #?(:clj (defmacro ^:private locking2 "Executes exprs in an implicit do, while holding the monitor of x. Will release the monitor of x in all circumstances." {:added "1.0"} [x & body] #?(:bb `(locking ~x ~body) :default `(let [lockee# ~x] (try (let [locklocal# lockee#] (monitor-enter locklocal#) (try ~@body (finally (monitor-exit locklocal#))))))))) #?(:clj (def resolve* (if resolve-at-compile-time? (constantly nil) (fn [sym] (let [ns (namespace sym)] (assert ns) (try (locking2 dynalock (require (symbol ns))) (catch Exception _ nil)) (resolve sym)))))) (defmacro dynaload ([s] `(dynaload ~s {})) ([[_quote s] opts] #?(:org.babashka/nbb `(let [d# (delay (or (resolve '~s) (if-let [e# (find ~opts :default)] (val e#) (throw (ex-info (str "Var " '~s " does not exist, " (namespace '~s) " never required") {})))))] (fn ([] (@d#)) ([a0] (@d# a0)) ([a0 a1] (@d# a0 a1)) ([a0 a1 a2] (@d# a0 a1 a2)) ([a0 a1 a2 a3] (@d# a0 a1 a2 a3)) ([a0 a1 a2 a3 a4] (@d# a0 a1 a2 a3 a4)) ([a0 a1 a2 a3 a4 & args] (apply @d# a0 a1 a2 a3 a4 args)))) :default #_{:clj-kondo/ignore[:redundant-let]} (let [#?@(:clj [resolved-at-compile-time (when resolve-at-compile-time? (resolve s))])] `(->LazyVar (fn [] (? :clj (if-let [v# (or #?(:clj ~resolved-at-compile-time) (resolve* '~s))] v# (if-let [e# (find ~opts :default)] (val e#) (throw (ex-info (str "Var " '~s " does not exist, " (namespace '~s) " never required") {})))) :cljs (if (cljs.core/exists? ~s) ~(vary-meta s assoc :cljs.analyzer/no-resolve true) (if-let [e# (find ~opts :default)] (val e#) (throw (js/Error. (str "Var " '~s " does not exist, " (namespace '~s) " never required"))))))) nil)))))
null
https://raw.githubusercontent.com/borkdude/dynaload/71eb9281dd8716b48995fe69845753575fc25c39/src/borkdude/dynaload.cljc
clojure
for some reason not working yet in bb
(ns borkdude.dynaload #?(:cljs (:require-macros [borkdude.dynaload :refer [dynaload if-bb]]))) (defmacro if-bb [then else] (if #?(:clj (System/getProperty "babashka.version") :cljs false) then else)) (if-bb #?(:clj (defn ->LazyVar [f _] (let [cached (volatile! nil)] (reify clojure.lang.IDeref (deref [_this] (if-not (nil? @cached) cached (let [x (f)] (when-not (nil? x) (vreset! cached x)) x))) clojure.lang.IFn (invoke [this] (@this)) (invoke [this a] (@this a)) (invoke [this a b] (@this a b)) (invoke [this a b c] (@this a b c)) (invoke [this a b c d] (@this a b c d)) (invoke [this a b c d e] (@this a b c d e)) (invoke [this a b c d e f] (@this a b c d e f)) (invoke [this a b c d e f g] (@this a b c d e f g)) (invoke [this a b c d e f g h] (@this a b c d e f g h)) (invoke [this a b c d e f g h i] (@this a b c d e f g h i)) (invoke [this a b c d e f g h i j] (@this a b c d e f g h i j)) (invoke [this a b c d e f g h i j k] (@this a b c d e f g h i j k)) (invoke [this a b c d e f g h i j k l] (@this a b c d e f g h i j k l)) (invoke [this a b c d e f g h i j k l m] (@this a b c d e f g h i j k l m)) (invoke [this a b c d e f g h i j k l m n] (@this a b c d e f g h i j k l m n)) (invoke [this a b c d e f g h i j k l m n o] (@this a b c d e f g h i j k l m n o)) (invoke [this a b c d e f g h i j k l m n o p] (@this a b c d e f g h i j k l m n o p)) (invoke [this a b c d e f g h i j k l m n o p q] (@this a b c d e f g h i j k l m n o p q)) (invoke [this a b c d e f g h i j k l m n o p q r] (@this a b c d e f g h i j k l m n o p q r)) (invoke [this a b c d e f g h i j k l m n o p q r s] (@this a b c d e f g h i j k l m n o p q r s)) #_(invoke [this a b c d e f g h i j k l m n o p q r s t] (@this a b c d e f g h i j k l m n o p q r s t)) #_(invoke [this a b c d e f g h i j k l m n o p q r s t rest] (apply @this a b c d e f g h i j k l m n o p q r s t rest)) (applyTo [this args] (apply @this args))))) :cljs nil) #?(:org.babashka/nbb nil :default (deftype LazyVar #?(:clj [f ^:volatile-mutable cached] :cljs [f ^:mutable cached]) #?(:clj clojure.lang.IDeref :cljs IDeref) (#?(:clj deref :cljs -deref) [_this] (if-not (nil? cached) cached (let [x (f)] (when-not (nil? x) (set! cached x)) x))) #?(:clj clojure.lang.IFn :cljs IFn) (#?(:clj invoke :cljs -invoke) [this] (@this)) (#?(:clj invoke :cljs -invoke) [this a] (@this a)) (#?(:clj invoke :cljs -invoke) [this a b] (@this a b)) (#?(:clj invoke :cljs -invoke) [this a b c] (@this a b c)) (#?(:clj invoke :cljs -invoke) [this a b c d] (@this a b c d)) (#?(:clj invoke :cljs -invoke) [this a b c d e] (@this a b c d e)) (#?(:clj invoke :cljs -invoke) [this a b c d e f] (@this a b c d e f)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g] (@this a b c d e f g)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h] (@this a b c d e f g h)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i] (@this a b c d e f g h i)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j] (@this a b c d e f g h i j)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k] (@this a b c d e f g h i j k)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l] (@this a b c d e f g h i j k l)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m] (@this a b c d e f g h i j k l m)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n] (@this a b c d e f g h i j k l m n)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o] (@this a b c d e f g h i j k l m n o)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p] (@this a b c d e f g h i j k l m n o p)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q] (@this a b c d e f g h i j k l m n o p q)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r] (@this a b c d e f g h i j k l m n o p q r)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r s] (@this a b c d e f g h i j k l m n o p q r s)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r s t] (@this a b c d e f g h i j k l m n o p q r s t)) (#?(:clj invoke :cljs -invoke) [this a b c d e f g h i j k l m n o p q r s t rest] (apply @this a b c d e f g h i j k l m n o p q r s t rest)) #?(:clj (applyTo [this args] (apply @this args)))))) (defmacro ? [& {:keys [cljs clj]}] (if (contains? &env '&env) `(if (:ns ~'&env) ~cljs ~clj) (if #?(:clj (:ns &env) :cljs true) cljs clj))) #?(:clj (def resolve-at-compile-time? (= "true" (System/getProperty "borkdude.dynaload.aot")))) #?(:clj (defonce ^:private dynalock (Object.))) #?(:clj (defmacro ^:private locking2 "Executes exprs in an implicit do, while holding the monitor of x. Will release the monitor of x in all circumstances." {:added "1.0"} [x & body] #?(:bb `(locking ~x ~body) :default `(let [lockee# ~x] (try (let [locklocal# lockee#] (monitor-enter locklocal#) (try ~@body (finally (monitor-exit locklocal#))))))))) #?(:clj (def resolve* (if resolve-at-compile-time? (constantly nil) (fn [sym] (let [ns (namespace sym)] (assert ns) (try (locking2 dynalock (require (symbol ns))) (catch Exception _ nil)) (resolve sym)))))) (defmacro dynaload ([s] `(dynaload ~s {})) ([[_quote s] opts] #?(:org.babashka/nbb `(let [d# (delay (or (resolve '~s) (if-let [e# (find ~opts :default)] (val e#) (throw (ex-info (str "Var " '~s " does not exist, " (namespace '~s) " never required") {})))))] (fn ([] (@d#)) ([a0] (@d# a0)) ([a0 a1] (@d# a0 a1)) ([a0 a1 a2] (@d# a0 a1 a2)) ([a0 a1 a2 a3] (@d# a0 a1 a2 a3)) ([a0 a1 a2 a3 a4] (@d# a0 a1 a2 a3 a4)) ([a0 a1 a2 a3 a4 & args] (apply @d# a0 a1 a2 a3 a4 args)))) :default #_{:clj-kondo/ignore[:redundant-let]} (let [#?@(:clj [resolved-at-compile-time (when resolve-at-compile-time? (resolve s))])] `(->LazyVar (fn [] (? :clj (if-let [v# (or #?(:clj ~resolved-at-compile-time) (resolve* '~s))] v# (if-let [e# (find ~opts :default)] (val e#) (throw (ex-info (str "Var " '~s " does not exist, " (namespace '~s) " never required") {})))) :cljs (if (cljs.core/exists? ~s) ~(vary-meta s assoc :cljs.analyzer/no-resolve true) (if-let [e# (find ~opts :default)] (val e#) (throw (js/Error. (str "Var " '~s " does not exist, " (namespace '~s) " never required"))))))) nil)))))
7b8cd6a82b559ba957a5cd5fa78166d925acec56fd9f16f932f6fdea6c915352
dbuenzli/brr
brr_ocaml_poke_ui.mli
--------------------------------------------------------------------------- Copyright ( c ) 2020 The brr programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2020 The brr programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) (** Interactive toplevel HTML interface for poke objects. *) open Brr * { 1 : storage Persistent storage } * Persistent storage . Basic interface to abstract over { ! Brr_io . Storage } and { { : -US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension storage } . Basic interface to abstract over {!Brr_io.Storage} and {{:-US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension storage}. *) module Store : sig type t (** The type for persistent storage. *) val create : get:(Jstr.t -> Jstr.t option Fut.or_error) -> set:(Jstr.t -> Jstr.t -> unit Fut.or_error) -> t (** [store] is a store with given [get] and [set] functions. *) val page : ?key_prefix:Jstr.t -> Brr_io.Storage.t -> t (** [local_store] is a store that uses {!Brr_io.Storage.local}, with keys prefixed by [key_prefix] (defaults to ["ocaml-repl-"]). *) val webext : ?key_prefix:Jstr.t -> unit -> t * [ webext_store ] is a store using the { { : -US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension } storage . The [ " storage " ] premission must be added to the manifest . {{:-US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension} storage. The ["storage"] premission must be added to the manifest. *) val get : t -> Jstr.t -> Jstr.t option Fut.or_error (** [get s k] is the value of key [k] in [s] (if any). *) val set : t -> Jstr.t -> Jstr.t -> unit Fut.or_error (** [set s k v] sets the value of [k] in [s] to [v]. *) end * { 1 : prompt_history Prompt history } (** Prompt history data structure. *) module History : sig type t (** The type for prompt histories. *) val v : prev:Jstr.t list -> t (** [v ~prev] initializes the toplevel with previous entries [prev] (later elements are older). *) val empty : t (** [empty] is an empty history. *) val entries : t -> Jstr.t list (** [entries h] are all the entries in the history. *) val add : t -> Jstr.t -> t (** [add h e] makes adds entry [v] to history. *) val restart : t -> t (** [restart] *) val prev : t -> Jstr.t -> (t * Jstr.t) option (** [prev h current] makes [current] the next entry of the resulting history and returns the previous entry of [h] (if any). *) val next : t -> Jstr.t -> (t * Jstr.t) option (** [next h current] makes [current] the previous entry of the resulting history and returns the next entry of [h] (if any). *) val to_string : sep:Jstr.t -> t -> Jstr.t (** [to_string ~sep t] is a string with the entries of [t] separated by {e lines} that contain [sep]. *) val of_string : sep:Jstr.t -> Jstr.t -> t (** [of_string ~sep s] is history from [s] assumed to be entries seperated by {e lines} that contain [sep]. *) end * { 1 : toplevel Toplevel user interface } type t (** The type for representing a toplevel user interface over a poke object. *) val create : ?store:Store.t -> El.t -> t Fut.or_error (** [create ~store view] creates a toplevel interface using the children of the [view] element whose content model should be flow content. [view]'s children are erased and the class [.ocaml-ui] is set on element. [store] is used to store the toplevel history and user settings. *) type output_kind = [ `Past_input | `Reply | `Warning | `Error | `Info | `Announce ] (** The type for specifiyng kinds of output messages. *) val output : t -> kind:output_kind -> El.t list -> unit * [ output r ~kind msg ] outputs message [ msg ] with [ kind ] to the user interface . user interface. *) val run : ?drop_target:Ev.target -> ?buttons:El.t list -> t -> Brr_ocaml_poke.t -> unit * [ run t poke ~drop_target ~buttons ] runs the toplevel with poke object [ poke ] . [ buttons ] are prepended to the buttons panel . [ drop_target ] is the target on which ml files can be droped ( defaults to the view ) . object [poke]. [buttons] are prepended to the buttons panel. [drop_target] is the target on which ml files can be droped (defaults to the view). *) --------------------------------------------------------------------------- Copyright ( c ) 2020 The brr programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2020 The brr programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/brr/3d1a0edd964a1ddfbf2be515fc3a3803d27ad707/src/ocaml_poke_ui/brr_ocaml_poke_ui.mli
ocaml
* Interactive toplevel HTML interface for poke objects. * The type for persistent storage. * [store] is a store with given [get] and [set] functions. * [local_store] is a store that uses {!Brr_io.Storage.local}, with keys prefixed by [key_prefix] (defaults to ["ocaml-repl-"]). * [get s k] is the value of key [k] in [s] (if any). * [set s k v] sets the value of [k] in [s] to [v]. * Prompt history data structure. * The type for prompt histories. * [v ~prev] initializes the toplevel with previous entries [prev] (later elements are older). * [empty] is an empty history. * [entries h] are all the entries in the history. * [add h e] makes adds entry [v] to history. * [restart] * [prev h current] makes [current] the next entry of the resulting history and returns the previous entry of [h] (if any). * [next h current] makes [current] the previous entry of the resulting history and returns the next entry of [h] (if any). * [to_string ~sep t] is a string with the entries of [t] separated by {e lines} that contain [sep]. * [of_string ~sep s] is history from [s] assumed to be entries seperated by {e lines} that contain [sep]. * The type for representing a toplevel user interface over a poke object. * [create ~store view] creates a toplevel interface using the children of the [view] element whose content model should be flow content. [view]'s children are erased and the class [.ocaml-ui] is set on element. [store] is used to store the toplevel history and user settings. * The type for specifiyng kinds of output messages.
--------------------------------------------------------------------------- Copyright ( c ) 2020 The brr programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2020 The brr programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open Brr * { 1 : storage Persistent storage } * Persistent storage . Basic interface to abstract over { ! Brr_io . Storage } and { { : -US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension storage } . Basic interface to abstract over {!Brr_io.Storage} and {{:-US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension storage}. *) module Store : sig type t val create : get:(Jstr.t -> Jstr.t option Fut.or_error) -> set:(Jstr.t -> Jstr.t -> unit Fut.or_error) -> t val page : ?key_prefix:Jstr.t -> Brr_io.Storage.t -> t val webext : ?key_prefix:Jstr.t -> unit -> t * [ webext_store ] is a store using the { { : -US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension } storage . The [ " storage " ] premission must be added to the manifest . {{:-US/docs/Mozilla/Add-ons/WebExtensions/API/storage}Web extension} storage. The ["storage"] premission must be added to the manifest. *) val get : t -> Jstr.t -> Jstr.t option Fut.or_error val set : t -> Jstr.t -> Jstr.t -> unit Fut.or_error end * { 1 : prompt_history Prompt history } module History : sig type t val v : prev:Jstr.t list -> t val empty : t val entries : t -> Jstr.t list val add : t -> Jstr.t -> t val restart : t -> t val prev : t -> Jstr.t -> (t * Jstr.t) option val next : t -> Jstr.t -> (t * Jstr.t) option val to_string : sep:Jstr.t -> t -> Jstr.t val of_string : sep:Jstr.t -> Jstr.t -> t end * { 1 : toplevel Toplevel user interface } type t val create : ?store:Store.t -> El.t -> t Fut.or_error type output_kind = [ `Past_input | `Reply | `Warning | `Error | `Info | `Announce ] val output : t -> kind:output_kind -> El.t list -> unit * [ output r ~kind msg ] outputs message [ msg ] with [ kind ] to the user interface . user interface. *) val run : ?drop_target:Ev.target -> ?buttons:El.t list -> t -> Brr_ocaml_poke.t -> unit * [ run t poke ~drop_target ~buttons ] runs the toplevel with poke object [ poke ] . [ buttons ] are prepended to the buttons panel . [ drop_target ] is the target on which ml files can be droped ( defaults to the view ) . object [poke]. [buttons] are prepended to the buttons panel. [drop_target] is the target on which ml files can be droped (defaults to the view). *) --------------------------------------------------------------------------- Copyright ( c ) 2020 The brr programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2020 The brr programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
ba6853bc2772968da952f1ed293f80aab24822cf49c0c2c040159252b72fcfe2
ghc/ghc
Types.hs
{-# LANGUAGE DerivingStrategies #-} # LANGUAGE ExistentialQuantification # {-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE PatternSynonyms #-} ( c ) The University of Glasgow 2006 - 2012 ( c ) The GRASP Project , Glasgow University , 1992 - 2002 (c) The University of Glasgow 2006-2012 (c) The GRASP Project, Glasgow University, 1992-2002 -} -- | Various types used during typechecking. -- Please see " . Utils . Monad " as well for operations on these types . You probably -- want to import it, instead of this module. -- All the monads exported here are built on top of the same IOEnv monad . The -- monad functions like a Reader monad in the way it passes the environment -- around. This is done to allow the environment to be manipulated in a stack -- like fashion when entering expressions... etc. -- -- For state that is global and should be returned at the end (e.g not part of the stack mechanism ) , you should use a TcRef (= IORef ) to store them . module GHC.Tc.Types( TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module TcRef, -- The environment types Env(..), TcGblEnv(..), TcLclEnv(..), setLclEnvTcLevel, getLclEnvTcLevel, setLclEnvLoc, getLclEnvLoc, lclEnvInGeneratedCode, IfGblEnv(..), IfLclEnv(..), tcVisibleOrphanMods, RewriteEnv(..), -- Frontend types (shouldn't really be here) FrontendResult(..), types ErrCtxt, pushErrCtxt, pushErrCtxtSameOrigin, ImportAvails(..), emptyImportAvails, plusImportAvails, WhereFrom(..), mkModDeps, Typechecker types TcTypeEnv, TcBinderStack, TcBinder(..), TcTyThing(..), tcTyThingTyCon_maybe, PromotionErr(..), IdBindingInfo(..), ClosedTypeId, RhsNames, IsGroupClosed(..), SelfBootInfo(..), bootExports, tcTyThingCategory, pprTcTyThingCategory, peCategory, pprPECategory, CompleteMatch, CompleteMatches, -- Template Haskell ThStage(..), SpliceType(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage, ThLevel, impLevel, outerLevel, thLevel, ForeignSrcLang(..), THDocs, DocLoc(..), ThBindEnv, Arrows ArrowCtxt(..), TcSigInfo TcSigFun, TcSigInfo(..), TcIdSigInfo(..), TcIdSigInst(..), TcPatSynInfo(..), isPartialSig, hasCompleteSig, -- Misc other types TcId, TcIdSet, NameShape(..), removeBindingShadowing, getPlatform, Constraint solver plugins TcPlugin(..), TcPluginSolveResult(TcPluginContradiction, TcPluginOk, ..), TcPluginRewriteResult(..), TcPluginSolver, TcPluginRewriter, TcPluginM(runTcPluginM), unsafeTcPluginTcM, -- Defaulting plugin DefaultingPlugin(..), DefaultingProposal(..), FillDefaulting, DefaultingPluginResult, -- Role annotations RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv, lookupRoleAnnot, getRoleAnnots, Linting lintGblEnv, -- Diagnostics TcRnMessage ) where import GHC.Prelude import GHC.Platform import GHC.Driver.Env import GHC.Driver.Config.Core.Lint import GHC.Driver.Session import {-# SOURCE #-} GHC.Driver.Hooks import GHC.Hs import GHC.Tc.Utils.TcType import GHC.Tc.Types.Constraint import GHC.Tc.Types.Origin import GHC.Tc.Types.Evidence import {-# SOURCE #-} GHC.Tc.Errors.Hole.FitTypes ( HoleFitPlugin ) import GHC.Tc.Errors.Types import GHC.Core.Reduction ( Reduction(..) ) import GHC.Core.Type import GHC.Core.TyCon ( TyCon, tyConKind ) import GHC.Core.PatSyn ( PatSyn ) import GHC.Core.Lint ( lintAxioms ) import GHC.Core.UsageEnv import GHC.Core.InstEnv import GHC.Core.FamInstEnv import GHC.Core.Predicate import GHC.Types.Id ( idType, idName ) import GHC.Types.Fixity.Env import GHC.Types.Annotations import GHC.Types.CompleteMatch import GHC.Types.Name.Reader import GHC.Types.Name import GHC.Types.Name.Env import GHC.Types.Name.Set import GHC.Types.Avail import GHC.Types.Var import GHC.Types.Var.Env import GHC.Types.TypeEnv import GHC.Types.TyThing import GHC.Types.SourceFile import GHC.Types.SrcLoc import GHC.Types.Var.Set import GHC.Types.Unique.FM import GHC.Types.Basic import GHC.Types.CostCentre.State import GHC.Types.HpcInfo import GHC.Types.ConInfo (ConFieldEnv) import GHC.Data.IOEnv import GHC.Data.Bag import GHC.Data.List.SetOps import GHC.Unit import GHC.Unit.Module.Warnings import GHC.Unit.Module.Deps import GHC.Unit.Module.ModDetails import GHC.Utils.Error import GHC.Utils.Outputable import GHC.Utils.Fingerprint import GHC.Utils.Misc import GHC.Utils.Panic import GHC.Utils.Logger import GHC.Builtin.Names ( isUnboundName ) import Data.Set ( Set ) import qualified Data.Set as S import Data.Dynamic ( Dynamic ) import Data.Map ( Map ) import Data.Typeable ( TypeRep ) import Data.Maybe ( mapMaybe ) import GHCi.Message import GHCi.RemoteTypes import qualified Language.Haskell.TH as TH import GHC.Driver.Env.KnotVars import GHC.Linker.Types | A ' NameShape ' is a substitution on ' Name 's that can be used -- to refine the identities of a hole while we are renaming interfaces ( see " GHC.Iface . Rename " ) . Specifically , a ' NameShape ' for ' ns_module_name ' , defines a mapping from @{A.T}@ -- (for some 'OccName' @T@) to some arbitrary other 'Name'. -- The most intriguing thing about a ' NameShape ' , however , is how it 's constructed . A ' NameShape ' is * implied * by the exported ' AvailInfo 's of the implementor of an interface : if an implementor of signature @\<H>@ exports , you implicitly define a substitution from @{H.T}@ to @M.T@. So a ' NameShape ' is computed from the list of ' AvailInfo 's that are exported -- by the implementation of a module, or successively merged -- together by the export lists of signatures which are joining -- together. -- -- It's not the most obvious way to go about doing this, but it -- does seem to work! -- NB : Ca n't boot this and put it in NameShape because then we start pulling in too many DynFlags things . data NameShape = NameShape { ns_mod_name :: ModuleName, ns_exports :: [AvailInfo], ns_map :: OccEnv Name } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Standard monad definition for TcRn All the combinators for the monad can be found in . Utils . Monad * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The monad itself has to be defined here , because it is mentioned by ErrCtxt ************************************************************************ * * Standard monad definition for TcRn All the combinators for the monad can be found in GHC.Tc.Utils.Monad * * ************************************************************************ The monad itself has to be defined here, because it is mentioned by ErrCtxt -} type TcRnIf a b = IOEnv (Env a b) type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference Iface stuff type IfG = IfM () -- Top level type IfL = IfM IfLclEnv -- Nested -- TcRn is the type-checking and renaming monad: the main monad that -- most type-checking takes place in. The global environment is -- 'TcGblEnv', which tracks all of the top-level type-checking -- information we've accumulated while checking a module, while the local environment is ' TcLclEnv ' , which tracks local information as -- we move inside expressions. -- | Historical "renaming monad" (now it's just 'TcRn'). type RnM = TcRn -- | Historical "type-checking monad" (now it's just 'TcRn'). type TcM = TcRn -- We 'stack' these envs through the Reader like monad infrastructure -- as we move into an expression (although the change is focused in the lcl type ) . data Env gbl lcl = Env { env_top :: !HscEnv, -- Top-level stuff that never changes -- Includes all info about imported things BangPattern is to fix leak , see # 15111 env_um :: {-# UNPACK #-} !Char, -- Mask for Uniques env_gbl :: gbl, -- Info about things defined at the top level -- of the module being compiled env_lcl :: lcl -- Nested stuff; changes as we go into } instance ContainsDynFlags (Env gbl lcl) where extractDynFlags env = hsc_dflags (env_top env) instance ContainsHooks (Env gbl lcl) where extractHooks env = hsc_hooks (env_top env) instance ContainsLogger (Env gbl lcl) where extractLogger env = hsc_logger (env_top env) instance ContainsModule gbl => ContainsModule (Env gbl lcl) where extractModule env = extractModule (env_gbl env) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * RewriteEnv * The rewriting environment * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ************************************************************************ * * * RewriteEnv * The rewriting environment * * ************************************************************************ -} | A ' RewriteEnv ' carries the necessary context for performing rewrites -- (i.e. type family reductions and following filled-in metavariables) -- in the solver. data RewriteEnv = RE { re_loc :: !CtLoc -- ^ In which context are we rewriting? -- -- Type-checking plugins might want to use this location information -- when emitting new Wanted constraints when rewriting type family -- applications. This ensures that such Wanted constraints will, -- when unsolved, give rise to error messages with the -- correct source location. Within GHC , we use this field to keep track of reduction depth . See Note [ ] in . Solver . Rewrite . , re_flavour :: !CtFlavour , re_eq_rel :: !EqRel -- ^ At what role are we rewriting? -- See Note [ Rewriter EqRels ] in . Solver . Rewrite ^ See Note [ rewrite ] } RewriteEnv is mostly used in @GHC.Tc . Solver . Rewrite@ , but it is defined -- here so that it can also be passed to rewriting plugins. See the ' tcPluginRewrite ' field of ' ' . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The interface environments Used when dealing with IfaceDecls * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ************************************************************************ * * The interface environments Used when dealing with IfaceDecls * * ************************************************************************ -} data IfGblEnv = IfGblEnv { -- Some information about where this environment came from; -- useful for debugging. if_doc :: SDoc, -- The type environment for the module being compiled, -- in case the interface refers back to it via a reference that -- was originally a hi-boot file. -- We need the module name so we can test when it's appropriate -- to look in this env. -- See Note [Tying the knot] in GHC.IfaceToCore if_rec_types :: (KnotVars (IfG TypeEnv)) -- Allows a read effect, so it can be in a mutable variable ; c.f . handling the external package type env -- Nothing => interactive stuff, no loops possible } data IfLclEnv = IfLclEnv { The module for the current IfaceDecl -- So if we see f = \x -> x it means M.f = \x - > x , where M is the if_mod NB : This is a semantic module , see -- Note [Identity versus semantic module] if_mod :: !Module, Whether or not the IfaceDecl came from a boot -- file or not; we'll use this to choose between NoUnfolding and BootUnfolding if_boot :: IsBootInterface, -- The field is used only for error reporting if ( say ) there 's a error in it if_loc :: SDoc, -- Where the interface came from: .hi file , or GHCi state , or ext core -- plus which bit is currently being examined if_nsubst :: Maybe NameShape, -- This field is used to make sure "implicit" declarations -- (anything that cannot be exported in mi_exports) get -- wired up correctly in typecheckIfacesForMerging. Most of the time it 's @Nothing@. See Note [ Resolving never - exported Names ] -- in GHC.IfaceToCore. if_implicits_env :: Maybe TypeEnv, if_tv_env :: FastStringEnv TyVar, -- Nested tyvar bindings if_id_env :: FastStringEnv Id -- Nested id binding } {- ************************************************************************ * * Global typechecker environment * * ************************************************************************ -} | ' ' describes the result of running the frontend of a Haskell module . Currently one always gets a ' FrontendTypecheck ' , since running the -- frontend involves typechecking a program. hs-sig merges are not handled here. -- This data type really should be in GHC.Driver . Env , but it needs -- to have a TcGblEnv which is only defined here. data FrontendResult = FrontendTypecheck TcGblEnv -- Note [Identity versus semantic module] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- When typechecking an hsig file, it is convenient to keep track of two different " this module " identifiers : -- -- - The IDENTITY module is simply thisPackage + the module -- name; i.e. it uniquely *identifies* the interface file -- we're compiling. For example, p[A=<A>]:A is an -- identity module identifying the requirement named A -- from library p. -- - The SEMANTIC module , which is the actual module that -- this signature is intended to represent (e.g. if -- we have a identity module p[A=base:Data.IORef]:A, -- then the semantic module is base:Data.IORef) -- -- Which one should you use? -- -- - In the desugarer and later phases of compilation, -- identity and semantic modules coincide, since we never compile -- signatures (we just generate blank object files for -- hsig files.) -- -- A corollary of this is that the following invariant holds at any point -- past desugaring, -- -- if I have a Module, this_mod, in hand representing the module -- currently being compiled, then moduleUnit this_mod = = thisPackage dflags -- -- - For any code involving Names, we want semantic modules. See lookupIfaceTop in GHC.Iface . Env , mkIface and addFingerprints in GHC.Iface.{Make , Recomp } , and tcLookupGlobal in . Utils . Env -- -- - When reading interfaces, we want the identity module to -- identify the specific interface we want (such interfaces -- should never be loaded into the EPS). However, if a hole module < A > is requested , we look for A.hi in the home library we are compiling . ( See GHC.Iface . Load . ) Similarly , in GHC.Rename . Names we check for self - imports using -- identity modules, to allow signatures to import their implementor. -- -- - For recompilation avoidance, you want the identity module, -- since that will actually say the specific interface you -- want to track (and recompile if it changes) -- | 'TcGblEnv' describes the top-level of the module at the point at which the typechecker is finished work . -- It is this structure that is handed on to the desugarer -- For state that needs to be updated during the typechecking -- phase and returned at end, use a 'TcRef' (= 'IORef'). data TcGblEnv = TcGblEnv { tcg_mod :: Module, -- ^ Module being compiled tcg_semantic_mod :: Module, -- ^ If a signature, the backing module -- See also Note [Identity versus semantic module] tcg_src :: HscSource, ^ What kind of module ( regular , hs - boot , hsig ) ^ Top level envt ; used during renaming tcg_default :: Maybe [Type], ^ Types used for defaulting . @Nothing@ = > no @default@ tcg_fix_env :: FixityEnv, -- ^ Just for things in this module tcg_con_env :: ConFieldEnv, -- ^ Just for things in this module -- For information on why this is necessary, see Note [Local constructor info in the renamer] -- See Note [The interactive package] in "GHC.Runtime.Context" tcg_type_env :: TypeEnv, -- ^ Global type env for the module we are compiling now. All -- TyCons and Classes (for this module) end up in here right away, -- along with their derived constructors, selectors. -- ( Ids defined in this module start in the local envt , though they -- move to the global envt during zonking) -- NB : for what " things in this module " means , see -- Note [The interactive package] in "GHC.Runtime.Context" tcg_type_env_var :: KnotVars (IORef TypeEnv), -- Used only to initialise the interface-file -- typechecker in initIfaceTcRn, so that it can see stuff -- bound in this module when dealing with hi-boot recursions -- Updated at intervals (e.g. after dealing with types and classes) tcg_inst_env :: !InstEnv, -- ^ Instance envt for all /home-package/ modules; Includes the dfuns in tcg_insts NB . BangPattern is to fix a leak , see # 15111 tcg_fam_inst_env :: !FamInstEnv, -- ^ Ditto for family instances NB . BangPattern is to fix a leak , see # 15111 tcg_ann_env :: AnnEnv, -- ^ And for annotations -- Now a bunch of things about this module that are simply -- accumulated, but never consulted until the end. -- Nevertheless, it's convenient to accumulate them along -- with the rest of the info from this module. tcg_exports :: [AvailInfo], -- ^ What is exported tcg_imports :: ImportAvails, -- ^ Information about what was imported from where, including things bound in this module . Also store Safe Haskell info -- here about transitive trusted package requirements. -- -- There are not many uses of this field, so you can grep for -- all them. -- The ImportAvails records information about the following -- things: -- 1 . All of the modules you directly imported ( tcRnImports ) 2 . The orphans ( only ! ) of all imported modules in a GHCi -- session (runTcInteractive) 3 . The module that instantiated a signature 4 . Each of the signatures that merged in -- -- It is used in the following ways: -- - imp_orphs is used to determine what orphan modules should be -- visible in the context (tcVisibleOrphanMods) -- - imp_finsts is used to determine what family instances should -- be visible (tcExtendLocalFamInstEnv) -- - To resolve the meaning of the export list of a module -- (tcRnExports) - imp_mods is used to compute usage info ( mkIfaceTc , ) - imp_trust_own_pkg is used for Safe Haskell in interfaces ( mkIfaceTc , as well as in " GHC.Driver . Main " ) -- - To create the Dependencies field in interface (mkDependencies) These three fields track unused bindings and imports -- See Note [Tracking unused binding and imports] tcg_dus :: DefUses, tcg_used_gres :: TcRef [GlobalRdrElt], tcg_keep :: TcRef NameSet, tcg_th_used :: TcRef Bool, ^ @True@ \<= > Template Haskell syntax used . -- -- We need this so that we can generate a dependency on the Template Haskell package , because the desugarer is going -- to emit loads of references to TH symbols. The reference -- is implicit rather than explicit, so we have to zap a -- mutable variable. tcg_th_splice_used :: TcRef Bool, ^ @True@ \<= > A Template Haskell splice was used . -- Splices disable recompilation avoidance ( see # 481 ) tcg_th_needed_deps :: TcRef ([Linkable], PkgsLoaded), -- ^ The set of runtime dependencies required by this module -- See Note [Object File Dependencies] tcg_dfun_n :: TcRef OccSet, ^ Allows us to choose unique DFun names . tcg_merged :: [(Module, Fingerprint)], -- ^ The requirements we merged with; we always have to recompile -- if any of these changed. -- The next fields accumulate the payload of the module -- The binds, rules and foreign-decl fields are collected initially in un - zonked form and are finally zonked in tcRnSrcDecls tcg_rn_exports :: Maybe [(LIE GhcRn, Avails)], -- Nothing <=> no explicit export list -- Is always Nothing if we don't want to retain renamed -- exports. -- If present contains each renamed export list item -- together with its exported names. tcg_rn_imports :: [LImportDecl GhcRn], -- Keep the renamed imports regardless. They are not -- voluminous and are needed if you want to report unused imports tcg_rn_decls :: Maybe (HsGroup GhcRn), ^ Renamed decls , maybe . @Nothing@ \<= > Do n't retain renamed -- decls. tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile tcg_th_topdecls :: TcRef [LHsDecl GhcPs], -- ^ Top-level declarations from addTopDecls tcg_th_foreign_files :: TcRef [(ForeignSrcLang, FilePath)], ^ Foreign files emitted from TH . tcg_th_topnames :: TcRef NameSet, -- ^ Exact names bound in top-level declarations in tcg_th_topdecls tcg_th_modfinalizers :: TcRef [(TcLclEnv, ThModFinalizers)], -- ^ Template Haskell module finalizers. -- -- They can use particular local environments. tcg_th_coreplugins :: TcRef [String], ^ Core plugins added by Template Haskell code . tcg_th_state :: TcRef (Map TypeRep Dynamic), tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))), -- ^ Template Haskell state tcg_th_docs :: TcRef THDocs, ^ Docs added in Template Haskell via @putDoc@. tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings -- Things defined in this module, or (in GHCi) -- in the declarations for a single GHCi command. -- For the latter, see Note [The interactive package] in GHC.Runtime . Context I d for $ trModule : : GHC.Unit . Module for which every module has a top - level defn -- except in GHCi in which case we have Nothing tcg_binds :: LHsBinds GhcTc, -- Value bindings in this module tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature ... for imported Ids tcg_warns :: (Warnings GhcRn), -- ...Warnings and deprecations tcg_anns :: [Annotation], -- ...Annotations tcg_tcs :: [TyCon], -- ...TyCons and Classes ... Top - level names that * lack * a signature tcg_insts :: [ClsInst], -- ...Instances tcg_fam_insts :: [FamInst], -- ...Family instances tcg_rules :: [LRuleDecl GhcTc], -- ...Rules tcg_fords :: [LForeignDecl GhcTc], -- ...Foreign import & exports tcg_patsyns :: [PatSyn], -- ...Pattern synonyms ^ Maybe header docs ^ @True@ if any part of the -- prog uses hpc instrumentation. NB . BangPattern is to fix a leak , see # 15111 tcg_self_boot :: SelfBootInfo, -- ^ Whether this module has a -- corresponding hi-boot file ^ The Name of the main -- function, if this module is -- the main module. tcg_safe_infer :: TcRef Bool, -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)? -- See Note [Safe Haskell Overlapping Instances Implementation], -- although this is used for more than just that failure case. tcg_safe_infer_reasons :: TcRef (Messages TcRnMessage), -- ^ Unreported reasons why tcg_safe_infer is False. -- INVARIANT: If this Messages is non-empty, then tcg_safe_infer is False. -- It may be that tcg_safe_infer is False but this is empty, if no reasons are supplied ( # 19714 ) , or if those reasons have already been -- reported by GHC.Driver.Main.markUnsafeInfer tcg_tc_plugin_solvers :: [TcPluginSolver], -- ^ A list of user-defined type-checking plugins for constraint solving. tcg_tc_plugin_rewriters :: UniqFM TyCon [TcPluginRewriter], -- ^ A collection of all the user-defined type-checking plugins for rewriting type family applications , collated by their type family ' 's . tcg_defaulting_plugins :: [FillDefaulting], -- ^ A list of user-defined plugins for type defaulting plugins. tcg_hf_plugins :: [HoleFitPlugin], -- ^ A list of user-defined plugins for hole fit suggestions. tcg_top_loc :: RealSrcSpan, ^ The RealSrcSpan this module came from tcg_static_wc :: TcRef WantedConstraints, -- ^ Wanted constraints of static forms. -- See Note [Constraints in static forms]. tcg_complete_matches :: !CompleteMatches, -- ^ Tracking indices for cost centre annotations tcg_cc_st :: TcRef CostCentreState, tcg_next_wrapper_num :: TcRef (ModuleEnv Int) ^ See Note [ Generating fresh names for FFI wrappers ] } NB : topModIdentity , not topModSemantic ! -- Definition sites of orphan identities will be identity modules, not semantic -- modules. -- Note [Constraints in static forms] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- When a static form produces constraints like -- f : : StaticPtr ( Bool - > String ) -- f = static show -- -- we collect them in tcg_static_wc and resolve them at the end -- of type checking. They need to be resolved separately because -- we don't want to resolve them in the context of the enclosing -- expression. Consider -- -- g :: Show a => StaticPtr (a -> String) -- g = static show -- -- If the @Show a0@ constraint that the body of the static form produces was -- resolved in the context of the enclosing expression, then the body of the -- static form wouldn't be closed because the Show dictionary would come from -- g's context instead of coming from the top level. tcVisibleOrphanMods :: TcGblEnv -> ModuleSet tcVisibleOrphanMods tcg_env = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env)) instance ContainsModule TcGblEnv where extractModule env = tcg_semantic_mod env data SelfBootInfo = NoSelfBoot -- No corresponding hi-boot file | SelfBoot { sb_mds :: ModDetails -- There was a hi-boot file, defining these TyCons , -- What is sb_tcs used for? See Note [Extra dependencies from .hs-boot files] in GHC.Rename . Module bootExports :: SelfBootInfo -> NameSet bootExports boot = case boot of NoSelfBoot -> emptyNameSet SelfBoot { sb_mds = mds} -> let exports = md_exports mds in availsToNameSet exports Note [ Tracking unused binding and imports ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We gather three sorts of usage information * tcg_dus : : ( defs / uses ) Records what is defined in this module and what is used . Records * defined * Names ( local , top - level ) and * used * Names ( local or imported ) Used ( a ) to report " defined but not used " ( see GHC.Rename . ) ( b ) to generate version - tracking usage info in interface files ( see GHC.Iface . Make.mkUsedNames ) This usage info is mainly gathered by the renamer 's gathering of free - variables * tcg_used_gres : : TcRef [ GlobalRdrElt ] Records occurrences of imported entities . Used only to report unused import declarations Records each * occurrence * an * imported * ( not locally - defined ) entity . The occurrence is recorded by keeping a GlobalRdrElt for it . These is not the GRE that is in the GlobalRdrEnv ; rather it is recorded * after * the filtering done by pickGREs . So it reflect /how that occurrence is in scope/. See Note [ GRE filtering ] in RdrName . * : : TcRef NameSet Records names of the type constructors , data constructors , and Ids that are used by the constraint solver . The typechecker may use find that some imported or locally - defined things are used , even though they do not appear to be mentioned in the source code : ( a ) The to / from functions for generic data types ( b ) Top - level variables appearing free in the RHS of an orphan rule ( c ) Top - level variables appearing free in a TH bracket See Note [ Keeping things alive for Template Haskell ] in GHC.Rename . Splice ( d ) The data constructor of a newtype that is used to solve a Coercible instance ( e.g. # 10347 ) . Example module T10347 ( N , mkN ) where import Data . Coerce newtype N a = mkN : : Int - > N a mkN = coerce Then we wish to record ` ` as used , since it is ( morally ) used to perform the coercion in ` mkN ` . To do so , the Coercible solver updates 's TcRef whenever it encounters a use of ` coerce ` that crosses newtype boundaries . ( e ) Record fields that are used to solve HasField constraints ( see Note [ Unused name reporting and HasField ] in . Instance . Class ) The field is used in two distinct ways : * Desugar.addExportFlagsAndRules . Where things like ( a - c ) are locally defined , we should give them an Exported flag , so that the simplifier does not discard them as dead code , and so that they are exposed in the interface file ( but not to export to the user ) . * GHC.Rename . Names.reportUnusedNames . Where newtype data constructors like ( d ) are imported , we do n't want to report them as unused . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The local typechecker environment * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note [ The Global - Env / Local - Env story ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During type checking , we keep in the tcg_type_env * All types and classes * All Ids derived from types and classes ( constructors , selectors ) At the end of type checking , we zonk the local bindings , and as we do so we add to the tcg_type_env * Locally defined top - level Ids Why ? Because they are now Ids not TcIds . This final GlobalEnv is a ) fed back ( via the knot ) to typechecking the unfoldings of interface signatures b ) used in the ModDetails of this module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We gather three sorts of usage information * tcg_dus :: DefUses (defs/uses) Records what is defined in this module and what is used. Records *defined* Names (local, top-level) and *used* Names (local or imported) Used (a) to report "defined but not used" (see GHC.Rename.Names.reportUnusedNames) (b) to generate version-tracking usage info in interface files (see GHC.Iface.Make.mkUsedNames) This usage info is mainly gathered by the renamer's gathering of free-variables * tcg_used_gres :: TcRef [GlobalRdrElt] Records occurrences of imported entities. Used only to report unused import declarations Records each *occurrence* an *imported* (not locally-defined) entity. The occurrence is recorded by keeping a GlobalRdrElt for it. These is not the GRE that is in the GlobalRdrEnv; rather it is recorded *after* the filtering done by pickGREs. So it reflect /how that occurrence is in scope/. See Note [GRE filtering] in RdrName. * tcg_keep :: TcRef NameSet Records names of the type constructors, data constructors, and Ids that are used by the constraint solver. The typechecker may use find that some imported or locally-defined things are used, even though they do not appear to be mentioned in the source code: (a) The to/from functions for generic data types (b) Top-level variables appearing free in the RHS of an orphan rule (c) Top-level variables appearing free in a TH bracket See Note [Keeping things alive for Template Haskell] in GHC.Rename.Splice (d) The data constructor of a newtype that is used to solve a Coercible instance (e.g. #10347). Example module T10347 (N, mkN) where import Data.Coerce newtype N a = MkN Int mkN :: Int -> N a mkN = coerce Then we wish to record `MkN` as used, since it is (morally) used to perform the coercion in `mkN`. To do so, the Coercible solver updates tcg_keep's TcRef whenever it encounters a use of `coerce` that crosses newtype boundaries. (e) Record fields that are used to solve HasField constraints (see Note [Unused name reporting and HasField] in GHC.Tc.Instance.Class) The tcg_keep field is used in two distinct ways: * Desugar.addExportFlagsAndRules. Where things like (a-c) are locally defined, we should give them an Exported flag, so that the simplifier does not discard them as dead code, and so that they are exposed in the interface file (but not to export to the user). * GHC.Rename.Names.reportUnusedNames. Where newtype data constructors like (d) are imported, we don't want to report them as unused. ************************************************************************ * * The local typechecker environment * * ************************************************************************ Note [The Global-Env/Local-Env story] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During type checking, we keep in the tcg_type_env * All types and classes * All Ids derived from types and classes (constructors, selectors) At the end of type checking, we zonk the local bindings, and as we do so we add to the tcg_type_env * Locally defined top-level Ids Why? Because they are now Ids not TcIds. This final GlobalEnv is a) fed back (via the knot) to typechecking the unfoldings of interface signatures b) used in the ModDetails of this module -} data TcLclEnv -- Changes as we move inside an expression Discarded after / rename ; not passed on to desugarer = TcLclEnv { tcl_loc :: RealSrcSpan, -- Source span tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top tcl_in_gen_code :: Bool, -- See Note [Rebindable syntax and HsExpansion] tcl_tclvl :: TcLevel, Template Haskell context tcl_th_bndrs :: ThBindEnv, -- and binder info The ThBindEnv records the TH binding level of in - scope Names -- defined in this module (not imported) -- We can't put this info in the TypeEnv because it's needed -- (and extended) in the renamer, for untyped splices tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context Local name -- Maintained during renaming, of course, but also during -- type checking, solely so that when renaming a Template-Haskell -- splice we have the right environment for the renamer. -- Does * not * include global name envt ; may shadow it -- Includes both ordinary variables and type variables; they are kept distinct because tyvar have a different occurrence constructor ( Name . TvOcc ) -- We still need the unsullied global name env so that -- we can look up record field names tcl_env :: TcTypeEnv, -- The local type environment: Ids and defined in this module tcl_usage :: TcRef UsageEnv, -- Required multiplicity of bindings is accumulated here. tcl_bndrs :: TcBinderStack, -- Used for reporting relevant bindings, -- and for tidying types tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints tcl_errs :: TcRef (Messages TcRnMessage) -- Place to accumulate diagnostics } setLclEnvTcLevel :: TcLclEnv -> TcLevel -> TcLclEnv setLclEnvTcLevel env lvl = env { tcl_tclvl = lvl } getLclEnvTcLevel :: TcLclEnv -> TcLevel getLclEnvTcLevel = tcl_tclvl setLclEnvLoc :: TcLclEnv -> RealSrcSpan -> TcLclEnv setLclEnvLoc env loc = env { tcl_loc = loc } getLclEnvLoc :: TcLclEnv -> RealSrcSpan getLclEnvLoc = tcl_loc lclEnvInGeneratedCode :: TcLclEnv -> Bool lclEnvInGeneratedCode = tcl_in_gen_code type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, SDoc)) Monadic so that we have a chance -- to deal with bound type variables just before error -- message construction : True < = > this is a landmark context ; do not -- discard it when trimming for display -- These are here to avoid module loops: one might expect them in . Types . Constraint , but they refer to ErrCtxt which refers to TcM. -- Easier to just keep these definitions here, alongside TcM. pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc pushErrCtxt o err loc@(CtLoc { ctl_env = lcl }) = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } } pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc -- Just add information w/o updating the origin! pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl }) = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } } type TcTypeEnv = NameEnv TcTyThing type ThBindEnv = NameEnv (TopLevelFlag, ThLevel) -- Domain = all Ids bound in this module (ie not imported) The TopLevelFlag tells if the binding is syntactically top level . -- We need to know this, because the cross-stage persistence story allows -- cross-stage at arbitrary types if the Id is bound at top level. -- -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being bound at top level ! See Note [ Template Haskell levels ] in . Gen. Splice Note [ Given Insts ] ~~~~~~~~~~~~~~~~~~ Because of GADTs , we have to pass inwards the Insts provided by type signatures and existential contexts . Consider data T a where { T1 : : b - > b - > T [ b ] } f : : Eq a = > T a - > Bool f ( T1 x y ) = [ x]==[y ] The constructor T1 binds an existential variable ' b ' , and we need [ b ] . Well , we have it , because a refines to Eq [ b ] , but we can only spot that if we pass it inwards . ~~~~~~~~~~~~~~~~~~ Because of GADTs, we have to pass inwards the Insts provided by type signatures and existential contexts. Consider data T a where { T1 :: b -> b -> T [b] } f :: Eq a => T a -> Bool f (T1 x y) = [x]==[y] The constructor T1 binds an existential variable 'b', and we need Eq [b]. Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we pass it inwards. -} -- | Type alias for 'IORef'; the convention is we'll use this for mutable bits of data in ' TcGblEnv ' which are updated during typechecking and -- returned at the end. type TcRef a = IORef a ToDo : when should I refer to it as a ' TcId ' instead of an ' I d ' ? type TcId = Id type TcIdSet = IdSet --------------------------- -- The TcBinderStack --------------------------- type TcBinderStack = [TcBinder] -- This is a stack of locally-bound ids and tyvars, -- innermost on top Used only in error reporting ( relevantBindings in TcError ) , -- and in tidying -- We can't use the tcl_env type environment, because it doesn't -- keep track of the nesting order data TcBinder = TcIdBndr TcId TopLevelFlag -- Tells whether the binding is syntactically top-level -- (The monomorphic Ids for a recursive group count -- as not-top-level for this purpose.) | TcIdBndr_ExpType -- Variant that allows the type to be specified as an ExpType Name ExpType TopLevelFlag | TcTvBndr -- e.g. case x of P (y::a) -> blah Name -- We bind the lexical name "a" to the type of y, TyVar -- which might be an utterly different (perhaps -- existential) tyvar instance Outputable TcBinder where ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl) ppr (TcIdBndr_ExpType id _ top_lvl) = ppr id <> brackets (ppr top_lvl) ppr (TcTvBndr name tv) = ppr name <+> ppr tv instance HasOccName TcBinder where occName (TcIdBndr id _) = occName (idName id) occName (TcIdBndr_ExpType name _ _) = occName name occName (TcTvBndr name _) = occName name fixes # 12177 -- Builds up a list of bindings whose OccName has not been seen before -- i.e., If ys = removeBindingShadowing xs -- then -- - ys is obtained from xs by deleting some elements - ys has no duplicate OccNames - The first duplicated OccName in xs is retained in ys -- Overloaded so that it can be used for both GlobalRdrElt in typed-hole -- substitutions and TcBinder when looking for relevant bindings. removeBindingShadowing :: HasOccName a => [a] -> [a] removeBindingShadowing bindings = reverse $ fst $ foldl (\(bindingAcc, seenNames) binding -> if occName binding `elemOccSet` seenNames -- if we've seen it then (bindingAcc, seenNames) -- skip it else (binding:bindingAcc, extendOccSet seenNames (occName binding))) ([], emptyOccSet) bindings -- | Get target platform getPlatform :: TcRnIf a b Platform getPlatform = targetPlatform <$> getDynFlags --------------------------- Template Haskell stages and levels --------------------------- data SpliceType = Typed | Untyped data ThStage -- See Note [Template Haskell state diagram] and Note [ Template Haskell levels ] in . Gen. Splice -- Start at: Comp -- At bracket: wrap current stage in Brack At splice : currently : return to previous stage currently Comp / Splice : compile and run = Splice SpliceType -- Inside a top-level splice -- This code will be run *at compile time*; -- the result replaces the splice -- Binding level = 0 | RunSplice (TcRef [ForeignRef (TH.Q ())]) -- Set when running a splice, i.e. NOT when renaming or typechecking the Haskell code for the splice . See Note [ RunSplice ThLevel ] . -- -- Contains a list of mod finalizers collected while executing the splice. -- -- 'addModFinalizer' inserts finalizers here, and from here they are taken to construct an @HsSpliced@ annotation for untyped splices . See Note [ Delaying modFinalizers in untyped splices ] in GHC.Rename . Splice . -- -- For typed splices, the typechecker takes finalizers from here and -- inserts them in the list of finalizers in the global environment. -- See Note [ Collecting modFinalizers in typed splices ] in " . Gen. Splice " . | Comp -- Ordinary Haskell code Binding level = 1 | Brack -- Inside brackets ThStage -- Enclosing stage PendingStuff data PendingStuff = RnPendingUntyped -- Renaming the inside of an *untyped* bracket (TcRef [PendingRnSplice]) -- Pending splices in here | RnPendingTyped -- Renaming the inside of a *typed* bracket | TcPending -- Typechecking the inside of a typed bracket (TcRef [PendingTcSplice]) -- Accumulate pending splices here (TcRef WantedConstraints) -- and type constraints here QuoteWrapper -- A type variable and evidence variable -- for the overall monad of -- the bracket. Splices are checked -- against this monad. The evidence -- variable is used for desugaring -- `lift`. topStage, topAnnStage, topSpliceStage :: ThStage topStage = Comp topAnnStage = Splice Untyped topSpliceStage = Splice Untyped instance Outputable ThStage where ppr (Splice _) = text "Splice" ppr (RunSplice _) = text "RunSplice" ppr Comp = text "Comp" ppr (Brack s _) = text "Brack" <> parens (ppr s) type ThLevel = Int NB : see Note [ Template Haskell levels ] in . Gen. Splice when going inside a bracket , -- decremented when going inside a splice NB : ThLevel is one greater than the ' n ' in Fig 2 of the original " Template meta - programming for " paper impLevel, outerLevel :: ThLevel impLevel = 0 -- Imported things; they can be used inside a top level splice outerLevel = 1 -- Things defined outside brackets thLevel :: ThStage -> ThLevel thLevel (Splice _) = 0 thLevel Comp = 1 thLevel (Brack s _) = thLevel s + 1 thLevel (RunSplice _) = panic "thLevel: called when running a splice" -- See Note [RunSplice ThLevel]. Note [ RunSplice ThLevel ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ' RunSplice ' stage is set when executing a splice , and only when running a splice . In particular it is not set when the splice is renamed or typechecked . ' RunSplice ' is needed to provide a reference where ' addModFinalizer ' can insert the finalizer ( see Note [ Delaying modFinalizers in untyped splices ] ) , and ' addModFinalizer ' runs when doing Q things . Therefore , It does n't make sense to set ' RunSplice ' when renaming or typechecking the splice , where ' Splice ' , ' Brack ' or ' Comp ' are used instead . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The 'RunSplice' stage is set when executing a splice, and only when running a splice. In particular it is not set when the splice is renamed or typechecked. 'RunSplice' is needed to provide a reference where 'addModFinalizer' can insert the finalizer (see Note [Delaying modFinalizers in untyped splices]), and 'addModFinalizer' runs when doing Q things. Therefore, It doesn't make sense to set 'RunSplice' when renaming or typechecking the splice, where 'Splice', 'Brack' or 'Comp' are used instead. -} --------------------------- -- Arrow-notation context --------------------------- Note [ Escaping the arrow scope ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In arrow notation , a variable bound by a proc ( or enclosed let / kappa ) is not in scope to the left of an arrow tail ( - < ) or the head of ( | .. | ) . For example proc x - > ( e1 - < e2 ) Here , x is not in scope in e1 , but it is in scope in e2 . This can get a bit complicated : let x = 3 in proc y - > ( proc z - > e1 ) - < e2 Here , x and z are in scope in e1 , but y is not . We implement this by recording the environment when passing a proc ( using newArrowScope ) , and returning to that ( using escapeArrowScope ) on the left of - < and the head of ( | .. | ) . All this can be dealt with by the * renamer * . But the type checker needs to be involved too . Example ( arrowfail001 ) class a where foo : : a - > ( ) data Bar = forall a. Foo a = > Bar a get : : Bar - > ( ) get = proc x - > case x of Bar a - > foo - < a Here the call of ' foo ' gives rise to a ( Foo a ) constraint that should not be captured by the pattern match on ' Bar ' . Rather it should join the constraints from further out . So we must capture the constraint bag from further out in the ArrowCtxt that we push inwards . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In arrow notation, a variable bound by a proc (or enclosed let/kappa) is not in scope to the left of an arrow tail (-<) or the head of (|..|). For example proc x -> (e1 -< e2) Here, x is not in scope in e1, but it is in scope in e2. This can get a bit complicated: let x = 3 in proc y -> (proc z -> e1) -< e2 Here, x and z are in scope in e1, but y is not. We implement this by recording the environment when passing a proc (using newArrowScope), and returning to that (using escapeArrowScope) on the left of -< and the head of (|..|). All this can be dealt with by the *renamer*. But the type checker needs to be involved too. Example (arrowfail001) class Foo a where foo :: a -> () data Bar = forall a. Foo a => Bar a get :: Bar -> () get = proc x -> case x of Bar a -> foo -< a Here the call of 'foo' gives rise to a (Foo a) constraint that should not be captured by the pattern match on 'Bar'. Rather it should join the constraints from further out. So we must capture the constraint bag from further out in the ArrowCtxt that we push inwards. -} data ArrowCtxt -- Note [Escaping the arrow scope] = NoArrowCtxt | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints) --------------------------- -- TcTyThing --------------------------- -- | A typecheckable thing available in a local context. Could be -- 'AGlobal' 'TyThing', but also lexically scoped variables, etc. -- See "GHC.Tc.Utils.Env" for how to retrieve a 'TyThing' given a 'Name'. data TcTyThing = AGlobal TyThing -- Used only in the return type of a lookup | ATcId -- Ids defined in this module; may not be fully zonked { tct_id :: TcId , tct_info :: IdBindingInfo -- See Note [Meaning of IdBindingInfo] } | ATyVar Name TcTyVar -- See Note [Type variables in the type environment] | ATcTyCon TyCon -- Used temporarily, during kind checking, for the -- tycons and classes in this recursive group The is always a TcTyCon . Its kind -- can be a mono-kind or a poly-kind; in TcTyClsDcls see -- Note [Type checking recursive type and class declarations] | APromotionErr PromotionErr | Matches on either a global ' ' or a ' TcTyCon ' . tcTyThingTyCon_maybe :: TcTyThing -> Maybe TyCon tcTyThingTyCon_maybe (AGlobal (ATyCon tc)) = Just tc tcTyThingTyCon_maybe (ATcTyCon tc_tc) = Just tc_tc tcTyThingTyCon_maybe _ = Nothing instance Outputable TcTyThing where -- Debugging only ppr (AGlobal g) = ppr g ppr elt@(ATcId {}) = text "Identifier" <> brackets (ppr (tct_id elt) <> dcolon <> ppr (varType (tct_id elt)) <> comma <+> ppr (tct_info elt)) ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv <+> dcolon <+> ppr (varType tv) ppr (ATcTyCon tc) = text "ATcTyCon" <+> ppr tc <+> dcolon <+> ppr (tyConKind tc) ppr (APromotionErr err) = text "APromotionErr" <+> ppr err -- | IdBindingInfo describes how an Id is bound. -- -- It is used for the following purposes: a ) for static forms in ' . Gen. Expr.checkClosedInStaticForm ' and -- b) to figure out when a nested binding can be generalised, in ' . Gen. ' . -- data IdBindingInfo -- See Note [Meaning of IdBindingInfo] = NotLetBound | ClosedLet | NonClosedLet RhsNames -- Used for (static e) checks only ClosedTypeId -- Used for generalisation checks -- and for (static e) checks -- | IsGroupClosed describes a group of mutually-recursive bindings data IsGroupClosed = IsGroupClosed (NameEnv RhsNames) -- Free var info for the RHS of each binding in the group -- Used only for (static e) checks ClosedTypeId -- True <=> all the free vars of the group are imported or ClosedLet or NonClosedLet with ClosedTypeId = True . In particular , no tyvars , no NotLetBound Names of variables , mentioned on the RHS of a definition , that are not Global or ClosedLet type ClosedTypeId = Bool -- See Note [Meaning of IdBindingInfo] Note [ Meaning of IdBindingInfo ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NotLetBound means that the I d is not let - bound ( e.g. it is bound in a lambda - abstraction or in a case pattern ) ClosedLet means that - The I d is let - bound , - Any free term variables are also Global or ClosedLet - Its type has no free variables ( NB : a top - level binding subject to the MR might have free vars in its type ) These ClosedLets can definitely be floated to top level ; and we may need to do so for static forms . Property : ClosedLet is equivalent to NonClosedLet emptyNameSet True ( NonClosedLet ( fvs::RhsNames ) ( cl::ClosedTypeId ) ) means that - The I d is let - bound - The fvs::RhsNames contains the free names of the RHS , excluding Global and ClosedLet ones . - For the ClosedTypeId field see Note [ Bindings with closed types : ClosedTypeId ] For ( static e ) to be valid , we need for every ' x ' free in ' e ' , that x 's binding is floatable to the top level . Specifically : * x 's RhsNames must be empty * x 's type has no free variables See Note [ Grand plan for static forms ] in " GHC.Iface . Tidy . StaticPtrTable " . This test is made in . Gen. Expr.checkClosedInStaticForm . Actually knowing x 's RhsNames ( rather than just its emptiness or otherwise ) is just so we can produce better error messages Note [ Bindings with closed types : ClosedTypeId ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = let ys = map not ys in ... Can we generalise ' g ' under the OutsideIn algorithm ? Yes , because all g 's free variables are top - level ; that is they themselves have no free type variables , and it is the type variables in the environment that makes things tricky for OutsideIn generalisation . Here 's the invariant : If an I d has ClosedTypeId = True ( in its IdBindingInfo ) , then the I d 's type is /definitely/ closed ( has no free type variables ) . Specifically , a ) The I d 's actual type is closed ( has no free tyvars ) b ) Either the I d has a ( closed ) user - supplied type signature or all its free variables are Global / ClosedLet or NonClosedLet with ClosedTypeId = True . In particular , none are NotLetBound . Why is ( b ) needed ? Consider \x . ( x : : Int , let y = x+1 in ... ) Initially x::alpha . If we happen to typecheck the ' let ' before the ( ) , y 's type will have a free tyvar ; but if the other way round it wo n't . So we treat any let - bound variable with a free non - let - bound variable as not ClosedTypeId , regardless of what the free vars of its type actually are . But if it has a signature , all is well : \x . ... ( let { y::Int ; y = x+1 } in let { v = y+2 } in ... ) ... Here the signature on ' v ' makes ' y ' a ClosedTypeId , so we can generalise ' v ' . Note that : * A top - level binding may not have ClosedTypeId = True , if it suffers from the MR * A nested binding may be closed ( eg ' g ' in the example we started with ) . Indeed , that 's the point ; whether a function is defined at top level or nested is orthogonal to the question of whether or not it is closed . * A binding may be non - closed because it mentions a lexically scoped * type variable * Eg f : : forall a. blah f x = let y = ... ( y::a ) ... Under OutsideIn we are free to generalise an I d all of whose free variables have ClosedTypeId = True ( or imported ) . This is an extension compared to the paper on OutsideIn , which used " top - level " as a proxy for " closed " . ( It 's not a good proxy anyway -- the MR can make a top - level binding with a free type variable . ) Note [ Type variables in the type environment ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The type environment has a binding for each lexically - scoped type variable that is in scope . For example f : : forall a. a - > a f x = ( x : : a ) g1 : : [ a ] - > a g1 ( ys : : [ b ] ) = head ys : : b g2 : : [ Int ] - > Int g2 ( ys : : [ c ] ) = head ys : : c * The forall'd variable ' a ' in the signature scopes over f 's RHS . * The pattern - bound type variable ' b ' in ' g1 ' scopes over g1 's RHS ; note that it is bound to a skolem ' a ' which is not itself lexically in scope . * The pattern - bound type variable ' c ' in ' ' is bound to Int ; that is , pattern - bound type variables can stand for arbitrary types . ( see GHC proposal # 128 " Allow ScopedTypeVariables to refer to types " -proposals/ghc-proposals/pull/128 , and the paper " Type variables in patterns " , Haskell Symposium 2018 . This is implemented by the constructor ATyVar Name TcTyVar in the type environment . * The Name is the name of the original , lexically scoped type variable * The TcTyVar is sometimes a skolem ( like in ' f ' ) , and sometimes a unification variable ( like in ' g1 ' , ' ' ) . We never zonk the type environment so in the latter case it always stays as a unification variable , although that variable may be later unified with a type ( such as Int in ' ' ) . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NotLetBound means that the Id is not let-bound (e.g. it is bound in a lambda-abstraction or in a case pattern) ClosedLet means that - The Id is let-bound, - Any free term variables are also Global or ClosedLet - Its type has no free variables (NB: a top-level binding subject to the MR might have free vars in its type) These ClosedLets can definitely be floated to top level; and we may need to do so for static forms. Property: ClosedLet is equivalent to NonClosedLet emptyNameSet True (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that - The Id is let-bound - The fvs::RhsNames contains the free names of the RHS, excluding Global and ClosedLet ones. - For the ClosedTypeId field see Note [Bindings with closed types: ClosedTypeId] For (static e) to be valid, we need for every 'x' free in 'e', that x's binding is floatable to the top level. Specifically: * x's RhsNames must be empty * x's type has no free variables See Note [Grand plan for static forms] in "GHC.Iface.Tidy.StaticPtrTable". This test is made in GHC.Tc.Gen.Expr.checkClosedInStaticForm. Actually knowing x's RhsNames (rather than just its emptiness or otherwise) is just so we can produce better error messages Note [Bindings with closed types: ClosedTypeId] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = let g ys = map not ys in ... Can we generalise 'g' under the OutsideIn algorithm? Yes, because all g's free variables are top-level; that is they themselves have no free type variables, and it is the type variables in the environment that makes things tricky for OutsideIn generalisation. Here's the invariant: If an Id has ClosedTypeId=True (in its IdBindingInfo), then the Id's type is /definitely/ closed (has no free type variables). Specifically, a) The Id's actual type is closed (has no free tyvars) b) Either the Id has a (closed) user-supplied type signature or all its free variables are Global/ClosedLet or NonClosedLet with ClosedTypeId=True. In particular, none are NotLetBound. Why is (b) needed? Consider \x. (x :: Int, let y = x+1 in ...) Initially x::alpha. If we happen to typecheck the 'let' before the (x::Int), y's type will have a free tyvar; but if the other way round it won't. So we treat any let-bound variable with a free non-let-bound variable as not ClosedTypeId, regardless of what the free vars of its type actually are. But if it has a signature, all is well: \x. ...(let { y::Int; y = x+1 } in let { v = y+2 } in ...)... Here the signature on 'v' makes 'y' a ClosedTypeId, so we can generalise 'v'. Note that: * A top-level binding may not have ClosedTypeId=True, if it suffers from the MR * A nested binding may be closed (eg 'g' in the example we started with). Indeed, that's the point; whether a function is defined at top level or nested is orthogonal to the question of whether or not it is closed. * A binding may be non-closed because it mentions a lexically scoped *type variable* Eg f :: forall a. blah f x = let g y = ...(y::a)... Under OutsideIn we are free to generalise an Id all of whose free variables have ClosedTypeId=True (or imported). This is an extension compared to the JFP paper on OutsideIn, which used "top-level" as a proxy for "closed". (It's not a good proxy anyway -- the MR can make a top-level binding with a free type variable.) Note [Type variables in the type environment] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The type environment has a binding for each lexically-scoped type variable that is in scope. For example f :: forall a. a -> a f x = (x :: a) g1 :: [a] -> a g1 (ys :: [b]) = head ys :: b g2 :: [Int] -> Int g2 (ys :: [c]) = head ys :: c * The forall'd variable 'a' in the signature scopes over f's RHS. * The pattern-bound type variable 'b' in 'g1' scopes over g1's RHS; note that it is bound to a skolem 'a' which is not itself lexically in scope. * The pattern-bound type variable 'c' in 'g2' is bound to Int; that is, pattern-bound type variables can stand for arbitrary types. (see GHC proposal #128 "Allow ScopedTypeVariables to refer to types" -proposals/ghc-proposals/pull/128, and the paper "Type variables in patterns", Haskell Symposium 2018. This is implemented by the constructor ATyVar Name TcTyVar in the type environment. * The Name is the name of the original, lexically scoped type variable * The TcTyVar is sometimes a skolem (like in 'f'), and sometimes a unification variable (like in 'g1', 'g2'). We never zonk the type environment so in the latter case it always stays as a unification variable, although that variable may be later unified with a type (such as Int in 'g2'). -} instance Outputable IdBindingInfo where ppr NotLetBound = text "NotLetBound" ppr ClosedLet = text "TopLevelLet" ppr (NonClosedLet fvs closed_type) = text "TopLevelLet" <+> ppr fvs <+> ppr closed_type -------------- pprTcTyThingCategory :: TcTyThing -> SDoc pprTcTyThingCategory = text . capitalise . tcTyThingCategory tcTyThingCategory :: TcTyThing -> String tcTyThingCategory (AGlobal thing) = tyThingCategory thing tcTyThingCategory (ATyVar {}) = "type variable" tcTyThingCategory (ATcId {}) = "local identifier" tcTyThingCategory (ATcTyCon {}) = "local tycon" tcTyThingCategory (APromotionErr pe) = peCategory pe {- ************************************************************************ * * Operations over ImportAvails * * ************************************************************************ -} mkModDeps :: Set (UnitId, ModuleNameWithIsBoot) -> InstalledModuleEnv ModuleNameWithIsBoot mkModDeps deps = S.foldl' add emptyInstalledModuleEnv deps where add env (uid, elt) = extendInstalledModuleEnv env (mkModule uid (gwib_mod elt)) elt plusModDeps :: InstalledModuleEnv ModuleNameWithIsBoot -> InstalledModuleEnv ModuleNameWithIsBoot -> InstalledModuleEnv ModuleNameWithIsBoot plusModDeps = plusInstalledModuleEnv plus_mod_dep where plus_mod_dep r1@(GWIB { gwib_mod = m1, gwib_isBoot = boot1 }) r2@(GWIB {gwib_mod = m2, gwib_isBoot = boot2}) | assertPpr (m1 == m2) ((ppr m1 <+> ppr m2) $$ (ppr (boot1 == IsBoot) <+> ppr (boot2 == IsBoot))) boot1 == IsBoot = r2 | otherwise = r1 -- If either side can "see" a non-hi-boot interface, use that Reusing existing tuples saves 10 % of allocations on test -- perf/compiler/MultiLayerModules emptyImportAvails :: ImportAvails emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv, imp_direct_dep_mods = emptyInstalledModuleEnv, imp_dep_direct_pkgs = S.empty, imp_sig_mods = [], imp_trust_pkgs = S.empty, imp_trust_own_pkg = False, imp_boot_mods = emptyInstalledModuleEnv, imp_orphs = [], imp_finsts = [] } | Union two ImportAvails -- -- This function is a key part of Import handling, basically for each import we create a separate ImportAvails structure -- and then union them all together with this function. plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails plusImportAvails (ImportAvails { imp_mods = mods1, imp_direct_dep_mods = ddmods1, imp_dep_direct_pkgs = ddpkgs1, imp_boot_mods = srs1, imp_sig_mods = sig_mods1, imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1, imp_orphs = orphs1, imp_finsts = finsts1 }) (ImportAvails { imp_mods = mods2, imp_direct_dep_mods = ddmods2, imp_dep_direct_pkgs = ddpkgs2, imp_boot_mods = srcs2, imp_sig_mods = sig_mods2, imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2, imp_orphs = orphs2, imp_finsts = finsts2 }) = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2, imp_direct_dep_mods = ddmods1 `plusModDeps` ddmods2, imp_dep_direct_pkgs = ddpkgs1 `S.union` ddpkgs2, imp_trust_pkgs = tpkgs1 `S.union` tpkgs2, imp_trust_own_pkg = tself1 || tself2, imp_boot_mods = srs1 `plusModDeps` srcs2, imp_sig_mods = unionListsOrd sig_mods1 sig_mods2, imp_orphs = unionListsOrd orphs1 orphs2, imp_finsts = unionListsOrd finsts1 finsts2 } {- ************************************************************************ * * \subsection{Where from} * * ************************************************************************ The @WhereFrom@ type controls where the renamer looks for an interface file -} data WhereFrom = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-}) | ImportBySystem -- Non user import. | ImportByPlugin -- Importing a plugin; See Note [ Care with plugin imports ] in GHC.Iface . Load instance Outputable WhereFrom where ppr (ImportByUser IsBoot) = text "{- SOURCE -}" ppr (ImportByUser NotBoot) = empty ppr ImportBySystem = text "{- SYSTEM -}" ppr ImportByPlugin = text "{- PLUGIN -}" {- ********************************************************************* * * Type signatures * * ********************************************************************* -} -- These data types need to be here only because GHC.Tc . Solver uses them , and . Solver is fairly -- low down in the module hierarchy type TcSigFun = Name -> Maybe TcSigInfo data TcSigInfo = TcIdSig TcIdSigInfo | TcPatSynSig TcPatSynInfo data TcIdSigInfo -- See Note [Complete and partial type signatures] = CompleteSig -- A complete signature with no wildcards, -- so the complete polymorphic type is known. { sig_bndr :: TcId -- The polymorphic Id with that type , sig_ctxt :: UserTypeCtxt -- In the case of type-class default methods, the Name in the FunSigCtxt is not the same -- as the TcId; the former is 'op', while the -- latter is '$dmop' or some such , sig_loc :: SrcSpan -- Location of the type signature } A partial type signature ( i.e. includes one or more -- wildcards). In this case it doesn't make sense to give -- the polymorphic Id, because we are going to /infer/ its -- type, so we can't make the polymorphic Id ab-initio { psig_name :: Name -- Name of the function; used when report wildcards , psig_hs_ty :: LHsSigWcType GhcRn -- The original partial signature in HsSyn form , sig_ctxt :: UserTypeCtxt , sig_loc :: SrcSpan -- Location of the type signature } Note [ Complete and partial type signatures ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A type signature is partial when it contains one or more wildcards (= type holes ) . The wildcard can either be : * A ( type ) wildcard occurring in sig_theta or sig_tau . These are stored in sig_wcs . f : : Bool - > _ g : : Eq _ a = > _ a - > _ a - > Bool * Or an extra - constraints wildcard , stored in sig_cts : h : : ( a , _ ) = > a - > a A type signature is a complete type signature when there are no wildcards in the type signature , i.e. iff sig_wcs is empty and sig_extra_cts is Nothing . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A type signature is partial when it contains one or more wildcards (= type holes). The wildcard can either be: * A (type) wildcard occurring in sig_theta or sig_tau. These are stored in sig_wcs. f :: Bool -> _ g :: Eq _a => _a -> _a -> Bool * Or an extra-constraints wildcard, stored in sig_cts: h :: (Num a, _) => a -> a A type signature is a complete type signature when there are no wildcards in the type signature, i.e. iff sig_wcs is empty and sig_extra_cts is Nothing. -} data TcIdSigInst = TISI { sig_inst_sig :: TcIdSigInfo , sig_inst_skols :: [(Name, InvisTVBinder)] -- Instantiated type and kind variables, TyVarTvs -- The Name is the Name that the renamer chose; but the may come from instantiating -- the type and hence have a different unique. -- No need to keep track of whether they are truly lexically -- scoped because the renamer has named them uniquely See Note [ Binding scoped type variables ] in . Gen. -- NB : The order of sig_inst_skols is irrelevant for a CompleteSig , but for a PartialSig see -- Note [Quantified variables in partial type signatures] , sig_inst_theta :: TcThetaType -- Instantiated theta. In the case of a PartialSig , sig_theta does not include -- the extra-constraints wildcard , sig_inst_tau :: TcSigmaType -- Instantiated tau -- See Note [sig_inst_tau may be polymorphic] -- Relevant for partial signature only , sig_inst_wcs :: [(Name, TcTyVar)] -- Like sig_inst_skols, but for /named/ wildcards (_a etc). -- The named wildcards scope over the binding, and hence -- their Names may appear in type signatures in the binding , sig_inst_wcx :: Maybe TcType -- Extra-constraints wildcard to fill in, if any -- If this exists, it is surely of the form (meta_tv |> co) -- (where the co might be reflexive). This is filled in only from the return value of . Gen. } Note [ sig_inst_tau may be polymorphic ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note that " sig_inst_tau " might actually be a polymorphic type , if the original function had a signature like forall a. Eq a = > forall b. Ord b = > .... But that 's ok : tcMatchesFun ( called by tcRhs ) can deal with that It happens , too ! See Note [ Polymorphic methods ] in . TyCl . Class . Note [ Quantified variables in partial type signatures ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f : : forall a b. _ - > a - > _ - > b f ( x , y ) p q = q Then we expect f 's final type to be f : : forall { x , y } . forall a b. ( x , y ) - > a - > b - > b Note that x , y are Inferred , and ca n't be use for visible type application ( VTA ) . But a , b are Specified , and remain Specified in the final type , so we can use VTA for them . ( Exception : if it turns out that a 's kind mentions b we need to reorder them with scopedSort . ) The sig_inst_skols of the TISI from a partial signature records that original order , and is used to get the variables of f 's final type in the correct order . Note [ Wildcards in partial signatures ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wildcards in psig_wcs may stand for a type mentioning the universally - quantified tyvars of psig_ty E.g. f : : forall a. _ - > a f x = x We get sig_inst_skols = [ a ] sig_inst_tau = _ 22 - > a sig_inst_wcs = [ _ 22 ] and _ 22 in the end is unified with the type ' a ' Moreover the kind of a wildcard in sig_inst_wcs may mention the universally - quantified tyvars sig_inst_skols e.g. f : : t a - > t _ Here we get sig_inst_skols = [ k :* , ( t::k - > * ) , ( a::k ) ] sig_inst_tau = t a - > t _ 22 sig_inst_wcs = [ _ 22::k ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note that "sig_inst_tau" might actually be a polymorphic type, if the original function had a signature like forall a. Eq a => forall b. Ord b => .... But that's ok: tcMatchesFun (called by tcRhs) can deal with that It happens, too! See Note [Polymorphic methods] in GHC.Tc.TyCl.Class. Note [Quantified variables in partial type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a b. _ -> a -> _ -> b f (x,y) p q = q Then we expect f's final type to be f :: forall {x,y}. forall a b. (x,y) -> a -> b -> b Note that x,y are Inferred, and can't be use for visible type application (VTA). But a,b are Specified, and remain Specified in the final type, so we can use VTA for them. (Exception: if it turns out that a's kind mentions b we need to reorder them with scopedSort.) The sig_inst_skols of the TISI from a partial signature records that original order, and is used to get the variables of f's final type in the correct order. Note [Wildcards in partial signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wildcards in psig_wcs may stand for a type mentioning the universally-quantified tyvars of psig_ty E.g. f :: forall a. _ -> a f x = x We get sig_inst_skols = [a] sig_inst_tau = _22 -> a sig_inst_wcs = [_22] and _22 in the end is unified with the type 'a' Moreover the kind of a wildcard in sig_inst_wcs may mention the universally-quantified tyvars sig_inst_skols e.g. f :: t a -> t _ Here we get sig_inst_skols = [k:*, (t::k ->*), (a::k)] sig_inst_tau = t a -> t _22 sig_inst_wcs = [ _22::k ] -} data TcPatSynInfo = TPSI { patsig_name :: Name, patsig_implicit_bndrs :: [InvisTVBinder], -- Implicitly-bound kind vars (Inferred) and -- implicitly-bound type vars (Specified) See Note [ The pattern - synonym signature splitting rule ] in . TyCl . PatSyn patsig_univ_bndrs :: [InvisTVBinder], -- Bound by explicit user forall patsig_req :: TcThetaType, patsig_ex_bndrs :: [InvisTVBinder], -- Bound by explicit user forall patsig_prov :: TcThetaType, patsig_body_ty :: TcSigmaType } instance Outputable TcSigInfo where ppr (TcIdSig idsi) = ppr idsi ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi instance Outputable TcIdSigInfo where ppr (CompleteSig { sig_bndr = bndr }) = ppr bndr <+> dcolon <+> ppr (idType bndr) ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty }) = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty instance Outputable TcIdSigInst where ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols , sig_inst_theta = theta, sig_inst_tau = tau }) = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ]) instance Outputable TcPatSynInfo where ppr (TPSI{ patsig_name = name}) = ppr name isPartialSig :: TcIdSigInst -> Bool isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True isPartialSig _ = False -- | No signature or a partial signature hasCompleteSig :: TcSigFun -> Name -> Bool hasCompleteSig sig_fn name = case sig_fn name of Just (TcIdSig (CompleteSig {})) -> True _ -> False {- Constraint Solver Plugins ------------------------- -} -- | The @solve@ function of a type-checking plugin takes in Given -- and Wanted constraints, and should return a 'TcPluginSolveResult' -- indicating which Wanted constraints it could solve, or whether any are -- insoluble. type TcPluginSolver = EvBindsVar -> [Ct] -- ^ Givens ^ -> TcPluginM TcPluginSolveResult -- | For rewriting type family applications, a type-checking plugin provides a function of this type for each type family ' ' . -- -- The function is provided with the current set of Given constraints, together -- with the arguments to the type family. -- The type family application will always be fully saturated. type TcPluginRewriter = RewriteEnv -- ^ Rewriter environment -> [Ct] -- ^ Givens -> [TcType] -- ^ type family arguments -> TcPluginM TcPluginRewriteResult -- | 'TcPluginM' is the monad in which type-checking plugins operate. newtype TcPluginM a = TcPluginM { runTcPluginM :: TcM a } deriving newtype (Functor, Applicative, Monad, MonadFail) -- | This function provides an escape for direct access to the ' ` monad . It should not be used lightly , and -- the provided 'TcPluginM' API should be favoured instead. unsafeTcPluginTcM :: TcM a -> TcPluginM a unsafeTcPluginTcM = TcPluginM data TcPlugin = forall s. TcPlugin { tcPluginInit :: TcPluginM s -- ^ Initialize plugin, when entering type-checker. , tcPluginSolve :: s -> TcPluginSolver -- ^ Solve some constraints. -- This function will be invoked at two points in the constraint solving -- process: once to simplify Given constraints, and once to solve Wanted constraints . In the first case ( and only in the first case ) , -- no Wanted constraints will be passed to the plugin. -- -- The plugin can either return a contradiction, -- or specify that it has solved some constraints (with evidence), -- and possibly emit additional constraints. These returned constraints must be Givens in the first case , and in the second . -- -- Use @ \\ _ _ _ _ -> pure $ TcPluginOk [] [] @ if your plugin -- does not provide this functionality. , tcPluginRewrite :: s -> UniqFM TyCon TcPluginRewriter -- ^ Rewrite saturated type family applications. -- -- The plugin is expected to supply a mapping from type family names to rewriting functions . For each type family ' ' , the plugin should -- provide a function which takes in the given constraints and arguments -- of a saturated type family application, and return a possible rewriting. -- See 'TcPluginRewriter' for the expected shape of such a function. -- -- Use @ \\ _ -> emptyUFM @ if your plugin does not provide this functionality. , tcPluginStop :: s -> TcPluginM () -- ^ Clean up after the plugin, when exiting the type-checker. } -- | The plugin found a contradiction. -- The returned constraints are removed from the inert set, -- and recorded as insoluble. -- -- The returned list of constraints should never be empty. pattern TcPluginContradiction :: [Ct] -> TcPluginSolveResult pattern TcPluginContradiction insols = TcPluginSolveResult { tcPluginInsolubleCts = insols , tcPluginSolvedCts = [] , tcPluginNewCts = [] } -- | The plugin has not found any contradictions, -- The first field is for constraints that were solved . The second field contains new work , that should be processed by -- the constraint solver. pattern TcPluginOk :: [(EvTerm, Ct)] -> [Ct] -> TcPluginSolveResult pattern TcPluginOk solved new = TcPluginSolveResult { tcPluginInsolubleCts = [] , tcPluginSolvedCts = solved , tcPluginNewCts = new } -- | Result of running a solver plugin. data TcPluginSolveResult = TcPluginSolveResult { -- | Insoluble constraints found by the plugin. -- -- These constraints will be added to the inert set, -- and reported as insoluble to the user. tcPluginInsolubleCts :: [Ct] -- | Solved constraints, together with their evidence. -- -- These are removed from the inert set, and the -- evidence for them is recorded. , tcPluginSolvedCts :: [(EvTerm, Ct)] -- | New constraints that the plugin wishes to emit. -- -- These will be added to the work list. , tcPluginNewCts :: [Ct] } data TcPluginRewriteResult = -- | The plugin does not rewrite the type family application. TcPluginNoRewrite -- | The plugin rewrites the type family application -- providing a rewriting together with evidence: a 'Reduction', -- which contains the rewritten type together with a 'Coercion' -- whose right-hand-side type is the rewritten type. -- -- The plugin can also emit additional Wanted constraints. | TcPluginRewriteTo { tcPluginReduction :: !Reduction , tcRewriterNewWanteds :: [Ct] } -- | A collection of candidate default types for a type variable. data DefaultingProposal = DefaultingProposal { deProposalTyVar :: TcTyVar -- ^ The type variable to default. , deProposalCandidates :: [Type] -- ^ Candidate types to default the type variable to. , deProposalCts :: [Ct] -- ^ The constraints against which defaults are checked. } instance Outputable DefaultingProposal where ppr p = text "DefaultingProposal" <+> ppr (deProposalTyVar p) <+> ppr (deProposalCandidates p) <+> ppr (deProposalCts p) type DefaultingPluginResult = [DefaultingProposal] type FillDefaulting = WantedConstraints -> TcPluginM DefaultingPluginResult -- | A plugin for controlling defaulting. data DefaultingPlugin = forall s. DefaultingPlugin { dePluginInit :: TcPluginM s -- ^ Initialize plugin, when entering type-checker. , dePluginRun :: s -> FillDefaulting -- ^ Default some types , dePluginStop :: s -> TcPluginM () -- ^ Clean up after the plugin, when exiting the type-checker. } {- ********************************************************************* * * Role annotations * * ********************************************************************* -} type RoleAnnotEnv = NameEnv (LRoleAnnotDecl GhcRn) mkRoleAnnotEnv :: [LRoleAnnotDecl GhcRn] -> RoleAnnotEnv mkRoleAnnotEnv role_annot_decls = mkNameEnv [ (name, ra_decl) | ra_decl <- role_annot_decls , let name = roleAnnotDeclName (unLoc ra_decl) , not (isUnboundName name) ] -- Some of the role annots will be unbound; -- we don't wish to include these emptyRoleAnnotEnv :: RoleAnnotEnv emptyRoleAnnotEnv = emptyNameEnv lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl GhcRn) lookupRoleAnnot = lookupNameEnv getRoleAnnots :: [Name] -> RoleAnnotEnv -> [LRoleAnnotDecl GhcRn] getRoleAnnots bndrs role_env = mapMaybe (lookupRoleAnnot role_env) bndrs {- ********************************************************************* * * Linting a TcGblEnv * * ********************************************************************* -} -- | Check the 'TcGblEnv' for consistency. Currently, only checks -- axioms, but should check other aspects, too. lintGblEnv :: Logger -> DynFlags -> TcGblEnv -> TcM () lintGblEnv logger dflags tcg_env = TODO empty list means no extra in scope from GHCi , is this correct ? liftIO $ lintAxioms logger (initLintConfig dflags []) (text "TcGblEnv axioms") axioms where axioms = typeEnvCoAxioms (tcg_type_env tcg_env) | This is a mirror of Template Haskell 's DocLoc , but the TH names are resolved to GHC names . data DocLoc = DeclDoc Name | ArgDoc Name Int | InstDoc Name | ModuleDoc deriving (Eq, Ord) | The current collection of docs that has built up via -- putDoc. type THDocs = Map DocLoc (HsDoc GhcRn)
null
https://raw.githubusercontent.com/ghc/ghc/f70a0239490ebea25e50c61c01f945d8df41e92f/compiler/GHC/Tc/Types.hs
haskell
# LANGUAGE DerivingStrategies # # LANGUAGE GADTs # # LANGUAGE PatternSynonyms # | Various types used during typechecking. want to import it, instead of this module. monad functions like a Reader monad in the way it passes the environment around. This is done to allow the environment to be manipulated in a stack like fashion when entering expressions... etc. For state that is global and should be returned at the end (e.g not part The monad is opaque outside this module The environment types Frontend types (shouldn't really be here) Template Haskell Misc other types Defaulting plugin Role annotations Diagnostics # SOURCE # # SOURCE # to refine the identities of a hole while we are renaming interfaces (for some 'OccName' @T@) to some arbitrary other 'Name'. by the implementation of a module, or successively merged together by the export lists of signatures which are joining together. It's not the most obvious way to go about doing this, but it does seem to work! Type inference Top level Nested TcRn is the type-checking and renaming monad: the main monad that most type-checking takes place in. The global environment is 'TcGblEnv', which tracks all of the top-level type-checking information we've accumulated while checking a module, while the we move inside expressions. | Historical "renaming monad" (now it's just 'TcRn'). | Historical "type-checking monad" (now it's just 'TcRn'). We 'stack' these envs through the Reader like monad infrastructure as we move into an expression (although the change is focused in Top-level stuff that never changes Includes all info about imported things # UNPACK # Mask for Uniques Info about things defined at the top level of the module being compiled Nested stuff; changes as we go into (i.e. type family reductions and following filled-in metavariables) in the solver. ^ In which context are we rewriting? Type-checking plugins might want to use this location information when emitting new Wanted constraints when rewriting type family applications. This ensures that such Wanted constraints will, when unsolved, give rise to error messages with the correct source location. ^ At what role are we rewriting? here so that it can also be passed to rewriting plugins. Some information about where this environment came from; useful for debugging. The type environment for the module being compiled, in case the interface refers back to it via a reference that was originally a hi-boot file. We need the module name so we can test when it's appropriate to look in this env. See Note [Tying the knot] in GHC.IfaceToCore Allows a read effect, so it can be in a mutable Nothing => interactive stuff, no loops possible So if we see f = \x -> x Note [Identity versus semantic module] file or not; we'll use this to choose between The field is used only for error reporting Where the interface came from: plus which bit is currently being examined This field is used to make sure "implicit" declarations (anything that cannot be exported in mi_exports) get wired up correctly in typecheckIfacesForMerging. Most in GHC.IfaceToCore. Nested tyvar bindings Nested id binding ************************************************************************ * * Global typechecker environment * * ************************************************************************ frontend involves typechecking a program. hs-sig merges are not handled here. to have a TcGblEnv which is only defined here. Note [Identity versus semantic module] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking an hsig file, it is convenient to keep track - The IDENTITY module is simply thisPackage + the module name; i.e. it uniquely *identifies* the interface file we're compiling. For example, p[A=<A>]:A is an identity module identifying the requirement named A from library p. this signature is intended to represent (e.g. if we have a identity module p[A=base:Data.IORef]:A, then the semantic module is base:Data.IORef) Which one should you use? - In the desugarer and later phases of compilation, identity and semantic modules coincide, since we never compile signatures (we just generate blank object files for hsig files.) A corollary of this is that the following invariant holds at any point past desugaring, if I have a Module, this_mod, in hand representing the module currently being compiled, - For any code involving Names, we want semantic modules. - When reading interfaces, we want the identity module to identify the specific interface we want (such interfaces should never be loaded into the EPS). However, if a identity modules, to allow signatures to import their implementor. - For recompilation avoidance, you want the identity module, since that will actually say the specific interface you want to track (and recompile if it changes) | 'TcGblEnv' describes the top-level of the module at the It is this structure that is handed on to the desugarer For state that needs to be updated during the typechecking phase and returned at end, use a 'TcRef' (= 'IORef'). ^ Module being compiled ^ If a signature, the backing module See also Note [Identity versus semantic module] ^ Just for things in this module ^ Just for things in this module For information on why this is necessary, see Note [Local constructor info in the renamer] See Note [The interactive package] in "GHC.Runtime.Context" ^ Global type env for the module we are compiling now. All TyCons and Classes (for this module) end up in here right away, along with their derived constructors, selectors. move to the global envt during zonking) Note [The interactive package] in "GHC.Runtime.Context" Used only to initialise the interface-file typechecker in initIfaceTcRn, so that it can see stuff bound in this module when dealing with hi-boot recursions Updated at intervals (e.g. after dealing with types and classes) ^ Instance envt for all /home-package/ modules; ^ Ditto for family instances ^ And for annotations Now a bunch of things about this module that are simply accumulated, but never consulted until the end. Nevertheless, it's convenient to accumulate them along with the rest of the info from this module. ^ What is exported ^ Information about what was imported from where, including here about transitive trusted package requirements. There are not many uses of this field, so you can grep for all them. things: session (runTcInteractive) It is used in the following ways: - imp_orphs is used to determine what orphan modules should be visible in the context (tcVisibleOrphanMods) - imp_finsts is used to determine what family instances should be visible (tcExtendLocalFamInstEnv) - To resolve the meaning of the export list of a module (tcRnExports) - To create the Dependencies field in interface (mkDependencies) See Note [Tracking unused binding and imports] We need this so that we can generate a dependency on the to emit loads of references to TH symbols. The reference is implicit rather than explicit, so we have to zap a mutable variable. ^ The set of runtime dependencies required by this module See Note [Object File Dependencies] ^ The requirements we merged with; we always have to recompile if any of these changed. The next fields accumulate the payload of the module The binds, rules and foreign-decl fields are collected Nothing <=> no explicit export list Is always Nothing if we don't want to retain renamed exports. If present contains each renamed export list item together with its exported names. Keep the renamed imports regardless. They are not voluminous and are needed if you want to report unused imports decls. ^ dependencies from addDependentFile ^ Top-level declarations from addTopDecls ^ Exact names bound in top-level declarations in tcg_th_topdecls ^ Template Haskell module finalizers. They can use particular local environments. ^ Template Haskell state Top-level evidence bindings Things defined in this module, or (in GHCi) in the declarations for a single GHCi command. For the latter, see Note [The interactive package] in except in GHCi in which case we have Nothing Value bindings in this module ...Top-level names that *lack* a signature ...Warnings and deprecations ...Annotations ...TyCons and Classes ...Instances ...Family instances ...Rules ...Foreign import & exports ...Pattern synonyms prog uses hpc instrumentation. ^ Whether this module has a corresponding hi-boot file function, if this module is the main module. ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)? See Note [Safe Haskell Overlapping Instances Implementation], although this is used for more than just that failure case. ^ Unreported reasons why tcg_safe_infer is False. INVARIANT: If this Messages is non-empty, then tcg_safe_infer is False. It may be that tcg_safe_infer is False but this is empty, if no reasons reported by GHC.Driver.Main.markUnsafeInfer ^ A list of user-defined type-checking plugins for constraint solving. ^ A collection of all the user-defined type-checking plugins for rewriting ^ A list of user-defined plugins for type defaulting plugins. ^ A list of user-defined plugins for hole fit suggestions. ^ Wanted constraints of static forms. See Note [Constraints in static forms]. ^ Tracking indices for cost centre annotations Definition sites of orphan identities will be identity modules, not semantic modules. Note [Constraints in static forms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When a static form produces constraints like f = static show we collect them in tcg_static_wc and resolve them at the end of type checking. They need to be resolved separately because we don't want to resolve them in the context of the enclosing expression. Consider g :: Show a => StaticPtr (a -> String) g = static show If the @Show a0@ constraint that the body of the static form produces was resolved in the context of the enclosing expression, then the body of the static form wouldn't be closed because the Show dictionary would come from g's context instead of coming from the top level. No corresponding hi-boot file There was a hi-boot file, What is sb_tcs used for? See Note [Extra dependencies from .hs-boot files] Changes as we move inside an expression Source span Error context, innermost on top See Note [Rebindable syntax and HsExpansion] and binder info defined in this module (not imported) We can't put this info in the TypeEnv because it's needed (and extended) in the renamer, for untyped splices Arrow-notation context Maintained during renaming, of course, but also during type checking, solely so that when renaming a Template-Haskell splice we have the right environment for the renamer. Includes both ordinary variables and type variables; We still need the unsullied global name env so that we can look up record field names The local type environment: Required multiplicity of bindings is accumulated here. Used for reporting relevant bindings, and for tidying types Place to accumulate type constraints Place to accumulate diagnostics to deal with bound type variables just before error message construction discard it when trimming for display These are here to avoid module loops: one might expect them Easier to just keep these definitions here, alongside TcM. Just add information w/o updating the origin! Domain = all Ids bound in this module (ie not imported) We need to know this, because the cross-stage persistence story allows cross-stage at arbitrary types if the Id is bound at top level. Nota bene: a ThLevel of 'outerLevel' is *not* the same as being | Type alias for 'IORef'; the convention is we'll use this for mutable returned at the end. ------------------------- The TcBinderStack ------------------------- This is a stack of locally-bound ids and tyvars, innermost on top and in tidying We can't use the tcl_env type environment, because it doesn't keep track of the nesting order Tells whether the binding is syntactically top-level (The monomorphic Ids for a recursive group count as not-top-level for this purpose.) Variant that allows the type to be specified as e.g. case x of P (y::a) -> blah We bind the lexical name "a" to the type of y, which might be an utterly different (perhaps existential) tyvar Builds up a list of bindings whose OccName has not been seen before i.e., If ys = removeBindingShadowing xs then - ys is obtained from xs by deleting some elements Overloaded so that it can be used for both GlobalRdrElt in typed-hole substitutions and TcBinder when looking for relevant bindings. if we've seen it skip it | Get target platform ------------------------- ------------------------- See Note [Template Haskell state diagram] Start at: Comp At bracket: wrap current stage in Brack Inside a top-level splice This code will be run *at compile time*; the result replaces the splice Binding level = 0 Set when running a splice, i.e. NOT when renaming or typechecking the Contains a list of mod finalizers collected while executing the splice. 'addModFinalizer' inserts finalizers here, and from here they are taken For typed splices, the typechecker takes finalizers from here and inserts them in the list of finalizers in the global environment. Ordinary Haskell code Inside brackets Enclosing stage Renaming the inside of an *untyped* bracket Pending splices in here Renaming the inside of a *typed* bracket Typechecking the inside of a typed bracket Accumulate pending splices here and type constraints here A type variable and evidence variable for the overall monad of the bracket. Splices are checked against this monad. The evidence variable is used for desugaring `lift`. decremented when going inside a splice Imported things; they can be used inside a top level splice Things defined outside brackets See Note [RunSplice ThLevel]. ------------------------- Arrow-notation context ------------------------- Note [Escaping the arrow scope] ------------------------- TcTyThing ------------------------- | A typecheckable thing available in a local context. Could be 'AGlobal' 'TyThing', but also lexically scoped variables, etc. See "GHC.Tc.Utils.Env" for how to retrieve a 'TyThing' given a 'Name'. Used only in the return type of a lookup Ids defined in this module; may not be fully zonked See Note [Meaning of IdBindingInfo] See Note [Type variables in the type environment] Used temporarily, during kind checking, for the tycons and classes in this recursive group can be a mono-kind or a poly-kind; in TcTyClsDcls see Note [Type checking recursive type and class declarations] Debugging only | IdBindingInfo describes how an Id is bound. It is used for the following purposes: b) to figure out when a nested binding can be generalised, See Note [Meaning of IdBindingInfo] Used for (static e) checks only Used for generalisation checks and for (static e) checks | IsGroupClosed describes a group of mutually-recursive bindings Free var info for the RHS of each binding in the group Used only for (static e) checks True <=> all the free vars of the group are See Note [Meaning of IdBindingInfo] the MR can make the MR can make ------------ ************************************************************************ * * Operations over ImportAvails * * ************************************************************************ If either side can "see" a non-hi-boot interface, use that perf/compiler/MultiLayerModules This function is a key part of Import handling, basically and then union them all together with this function. ************************************************************************ * * \subsection{Where from} * * ************************************************************************ The @WhereFrom@ type controls where the renamer looks for an interface file Ordinary user import (perhaps {-# SOURCE #-}) Non user import. Importing a plugin; ********************************************************************* * * Type signatures * * ********************************************************************* These data types need to be here only because low down in the module hierarchy See Note [Complete and partial type signatures] A complete signature with no wildcards, so the complete polymorphic type is known. The polymorphic Id with that type In the case of type-class default methods, as the TcId; the former is 'op', while the latter is '$dmop' or some such Location of the type signature wildcards). In this case it doesn't make sense to give the polymorphic Id, because we are going to /infer/ its type, so we can't make the polymorphic Id ab-initio Name of the function; used when report wildcards The original partial signature in Location of the type signature Instantiated type and kind variables, TyVarTvs The Name is the Name that the renamer chose; the type and hence have a different unique. No need to keep track of whether they are truly lexically scoped because the renamer has named them uniquely Note [Quantified variables in partial type signatures] Instantiated theta. In the case of a the extra-constraints wildcard Instantiated tau See Note [sig_inst_tau may be polymorphic] Relevant for partial signature only Like sig_inst_skols, but for /named/ wildcards (_a etc). The named wildcards scope over the binding, and hence their Names may appear in type signatures in the binding Extra-constraints wildcard to fill in, if any If this exists, it is surely of the form (meta_tv |> co) (where the co might be reflexive). This is filled in Implicitly-bound kind vars (Inferred) and implicitly-bound type vars (Specified) Bound by explicit user forall Bound by explicit user forall | No signature or a partial signature Constraint Solver Plugins ------------------------- | The @solve@ function of a type-checking plugin takes in Given and Wanted constraints, and should return a 'TcPluginSolveResult' indicating which Wanted constraints it could solve, or whether any are insoluble. ^ Givens | For rewriting type family applications, a type-checking plugin provides The function is provided with the current set of Given constraints, together with the arguments to the type family. The type family application will always be fully saturated. ^ Rewriter environment ^ Givens ^ type family arguments | 'TcPluginM' is the monad in which type-checking plugins operate. | This function provides an escape for direct access to the provided 'TcPluginM' API should be favoured instead. ^ Initialize plugin, when entering type-checker. ^ Solve some constraints. process: once to simplify Given constraints, and once to solve no Wanted constraints will be passed to the plugin. The plugin can either return a contradiction, or specify that it has solved some constraints (with evidence), and possibly emit additional constraints. These returned constraints Use @ \\ _ _ _ _ -> pure $ TcPluginOk [] [] @ if your plugin does not provide this functionality. ^ Rewrite saturated type family applications. The plugin is expected to supply a mapping from type family names to provide a function which takes in the given constraints and arguments of a saturated type family application, and return a possible rewriting. See 'TcPluginRewriter' for the expected shape of such a function. Use @ \\ _ -> emptyUFM @ if your plugin does not provide this functionality. ^ Clean up after the plugin, when exiting the type-checker. | The plugin found a contradiction. The returned constraints are removed from the inert set, and recorded as insoluble. The returned list of constraints should never be empty. | The plugin has not found any contradictions, the constraint solver. | Result of running a solver plugin. | Insoluble constraints found by the plugin. These constraints will be added to the inert set, and reported as insoluble to the user. | Solved constraints, together with their evidence. These are removed from the inert set, and the evidence for them is recorded. | New constraints that the plugin wishes to emit. These will be added to the work list. | The plugin does not rewrite the type family application. | The plugin rewrites the type family application providing a rewriting together with evidence: a 'Reduction', which contains the rewritten type together with a 'Coercion' whose right-hand-side type is the rewritten type. The plugin can also emit additional Wanted constraints. | A collection of candidate default types for a type variable. ^ The type variable to default. ^ Candidate types to default the type variable to. ^ The constraints against which defaults are checked. | A plugin for controlling defaulting. ^ Initialize plugin, when entering type-checker. ^ Default some types ^ Clean up after the plugin, when exiting the type-checker. ********************************************************************* * * Role annotations * * ********************************************************************* Some of the role annots will be unbound; we don't wish to include these ********************************************************************* * * Linting a TcGblEnv * * ********************************************************************* | Check the 'TcGblEnv' for consistency. Currently, only checks axioms, but should check other aspects, too. putDoc.
# LANGUAGE ExistentialQuantification # # LANGUAGE GeneralizedNewtypeDeriving # ( c ) The University of Glasgow 2006 - 2012 ( c ) The GRASP Project , Glasgow University , 1992 - 2002 (c) The University of Glasgow 2006-2012 (c) The GRASP Project, Glasgow University, 1992-2002 -} Please see " . Utils . Monad " as well for operations on these types . You probably All the monads exported here are built on top of the same IOEnv monad . The of the stack mechanism ) , you should use a TcRef (= IORef ) to store them . module GHC.Tc.Types( TcRef, Env(..), TcGblEnv(..), TcLclEnv(..), setLclEnvTcLevel, getLclEnvTcLevel, setLclEnvLoc, getLclEnvLoc, lclEnvInGeneratedCode, IfGblEnv(..), IfLclEnv(..), tcVisibleOrphanMods, RewriteEnv(..), FrontendResult(..), types ErrCtxt, pushErrCtxt, pushErrCtxtSameOrigin, ImportAvails(..), emptyImportAvails, plusImportAvails, WhereFrom(..), mkModDeps, Typechecker types TcTypeEnv, TcBinderStack, TcBinder(..), TcTyThing(..), tcTyThingTyCon_maybe, PromotionErr(..), IdBindingInfo(..), ClosedTypeId, RhsNames, IsGroupClosed(..), SelfBootInfo(..), bootExports, tcTyThingCategory, pprTcTyThingCategory, peCategory, pprPECategory, CompleteMatch, CompleteMatches, ThStage(..), SpliceType(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage, ThLevel, impLevel, outerLevel, thLevel, ForeignSrcLang(..), THDocs, DocLoc(..), ThBindEnv, Arrows ArrowCtxt(..), TcSigInfo TcSigFun, TcSigInfo(..), TcIdSigInfo(..), TcIdSigInst(..), TcPatSynInfo(..), isPartialSig, hasCompleteSig, TcId, TcIdSet, NameShape(..), removeBindingShadowing, getPlatform, Constraint solver plugins TcPlugin(..), TcPluginSolveResult(TcPluginContradiction, TcPluginOk, ..), TcPluginRewriteResult(..), TcPluginSolver, TcPluginRewriter, TcPluginM(runTcPluginM), unsafeTcPluginTcM, DefaultingPlugin(..), DefaultingProposal(..), FillDefaulting, DefaultingPluginResult, RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv, lookupRoleAnnot, getRoleAnnots, Linting lintGblEnv, TcRnMessage ) where import GHC.Prelude import GHC.Platform import GHC.Driver.Env import GHC.Driver.Config.Core.Lint import GHC.Driver.Session import GHC.Hs import GHC.Tc.Utils.TcType import GHC.Tc.Types.Constraint import GHC.Tc.Types.Origin import GHC.Tc.Types.Evidence import GHC.Tc.Errors.Types import GHC.Core.Reduction ( Reduction(..) ) import GHC.Core.Type import GHC.Core.TyCon ( TyCon, tyConKind ) import GHC.Core.PatSyn ( PatSyn ) import GHC.Core.Lint ( lintAxioms ) import GHC.Core.UsageEnv import GHC.Core.InstEnv import GHC.Core.FamInstEnv import GHC.Core.Predicate import GHC.Types.Id ( idType, idName ) import GHC.Types.Fixity.Env import GHC.Types.Annotations import GHC.Types.CompleteMatch import GHC.Types.Name.Reader import GHC.Types.Name import GHC.Types.Name.Env import GHC.Types.Name.Set import GHC.Types.Avail import GHC.Types.Var import GHC.Types.Var.Env import GHC.Types.TypeEnv import GHC.Types.TyThing import GHC.Types.SourceFile import GHC.Types.SrcLoc import GHC.Types.Var.Set import GHC.Types.Unique.FM import GHC.Types.Basic import GHC.Types.CostCentre.State import GHC.Types.HpcInfo import GHC.Types.ConInfo (ConFieldEnv) import GHC.Data.IOEnv import GHC.Data.Bag import GHC.Data.List.SetOps import GHC.Unit import GHC.Unit.Module.Warnings import GHC.Unit.Module.Deps import GHC.Unit.Module.ModDetails import GHC.Utils.Error import GHC.Utils.Outputable import GHC.Utils.Fingerprint import GHC.Utils.Misc import GHC.Utils.Panic import GHC.Utils.Logger import GHC.Builtin.Names ( isUnboundName ) import Data.Set ( Set ) import qualified Data.Set as S import Data.Dynamic ( Dynamic ) import Data.Map ( Map ) import Data.Typeable ( TypeRep ) import Data.Maybe ( mapMaybe ) import GHCi.Message import GHCi.RemoteTypes import qualified Language.Haskell.TH as TH import GHC.Driver.Env.KnotVars import GHC.Linker.Types | A ' NameShape ' is a substitution on ' Name 's that can be used ( see " GHC.Iface . Rename " ) . Specifically , a ' NameShape ' for ' ns_module_name ' , defines a mapping from @{A.T}@ The most intriguing thing about a ' NameShape ' , however , is how it 's constructed . A ' NameShape ' is * implied * by the exported ' AvailInfo 's of the implementor of an interface : if an implementor of signature @\<H>@ exports , you implicitly define a substitution from @{H.T}@ to @M.T@. So a ' NameShape ' is computed from the list of ' AvailInfo 's that are exported NB : Ca n't boot this and put it in NameShape because then we start pulling in too many DynFlags things . data NameShape = NameShape { ns_mod_name :: ModuleName, ns_exports :: [AvailInfo], ns_map :: OccEnv Name } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Standard monad definition for TcRn All the combinators for the monad can be found in . Utils . Monad * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The monad itself has to be defined here , because it is mentioned by ErrCtxt ************************************************************************ * * Standard monad definition for TcRn All the combinators for the monad can be found in GHC.Tc.Utils.Monad * * ************************************************************************ The monad itself has to be defined here, because it is mentioned by ErrCtxt -} type TcRnIf a b = IOEnv (Env a b) Iface stuff local environment is ' TcLclEnv ' , which tracks local information as type RnM = TcRn type TcM = TcRn the lcl type ) . data Env gbl lcl = Env { BangPattern is to fix leak , see # 15111 } instance ContainsDynFlags (Env gbl lcl) where extractDynFlags env = hsc_dflags (env_top env) instance ContainsHooks (Env gbl lcl) where extractHooks env = hsc_hooks (env_top env) instance ContainsLogger (Env gbl lcl) where extractLogger env = hsc_logger (env_top env) instance ContainsModule gbl => ContainsModule (Env gbl lcl) where extractModule env = extractModule (env_gbl env) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * RewriteEnv * The rewriting environment * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ************************************************************************ * * * RewriteEnv * The rewriting environment * * ************************************************************************ -} | A ' RewriteEnv ' carries the necessary context for performing rewrites data RewriteEnv = RE { re_loc :: !CtLoc Within GHC , we use this field to keep track of reduction depth . See Note [ ] in . Solver . Rewrite . , re_flavour :: !CtFlavour , re_eq_rel :: !EqRel See Note [ Rewriter EqRels ] in . Solver . Rewrite ^ See Note [ rewrite ] } RewriteEnv is mostly used in @GHC.Tc . Solver . Rewrite@ , but it is defined See the ' tcPluginRewrite ' field of ' ' . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The interface environments Used when dealing with IfaceDecls * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ************************************************************************ * * The interface environments Used when dealing with IfaceDecls * * ************************************************************************ -} data IfGblEnv = IfGblEnv { if_doc :: SDoc, if_rec_types :: (KnotVars (IfG TypeEnv)) variable ; c.f . handling the external package type env } data IfLclEnv = IfLclEnv { The module for the current IfaceDecl it means M.f = \x - > x , where M is the if_mod NB : This is a semantic module , see if_mod :: !Module, Whether or not the IfaceDecl came from a boot NoUnfolding and BootUnfolding if_boot :: IsBootInterface, if ( say ) there 's a error in it if_loc :: SDoc, .hi file , or GHCi state , or ext core if_nsubst :: Maybe NameShape, of the time it 's @Nothing@. See Note [ Resolving never - exported Names ] if_implicits_env :: Maybe TypeEnv, } | ' ' describes the result of running the frontend of a Haskell module . Currently one always gets a ' FrontendTypecheck ' , since running the This data type really should be in GHC.Driver . Env , but it needs data FrontendResult = FrontendTypecheck TcGblEnv of two different " this module " identifiers : - The SEMANTIC module , which is the actual module that then moduleUnit this_mod = = thisPackage dflags See lookupIfaceTop in GHC.Iface . Env , mkIface and addFingerprints in GHC.Iface.{Make , Recomp } , and tcLookupGlobal in . Utils . Env hole module < A > is requested , we look for A.hi in the home library we are compiling . ( See GHC.Iface . Load . ) Similarly , in GHC.Rename . Names we check for self - imports using point at which the typechecker is finished work . data TcGblEnv = TcGblEnv { tcg_src :: HscSource, ^ What kind of module ( regular , hs - boot , hsig ) ^ Top level envt ; used during renaming tcg_default :: Maybe [Type], ^ Types used for defaulting . @Nothing@ = > no @default@ tcg_con_env :: ConFieldEnv, tcg_type_env :: TypeEnv, ( Ids defined in this module start in the local envt , though they NB : for what " things in this module " means , see tcg_type_env_var :: KnotVars (IORef TypeEnv), tcg_inst_env :: !InstEnv, Includes the dfuns in tcg_insts NB . BangPattern is to fix a leak , see # 15111 NB . BangPattern is to fix a leak , see # 15111 tcg_imports :: ImportAvails, things bound in this module . Also store Safe Haskell info The ImportAvails records information about the following 1 . All of the modules you directly imported ( tcRnImports ) 2 . The orphans ( only ! ) of all imported modules in a GHCi 3 . The module that instantiated a signature 4 . Each of the signatures that merged in - imp_mods is used to compute usage info ( mkIfaceTc , ) - imp_trust_own_pkg is used for Safe Haskell in interfaces ( mkIfaceTc , as well as in " GHC.Driver . Main " ) These three fields track unused bindings and imports tcg_dus :: DefUses, tcg_used_gres :: TcRef [GlobalRdrElt], tcg_keep :: TcRef NameSet, tcg_th_used :: TcRef Bool, ^ @True@ \<= > Template Haskell syntax used . Template Haskell package , because the desugarer is going tcg_th_splice_used :: TcRef Bool, ^ @True@ \<= > A Template Haskell splice was used . Splices disable recompilation avoidance ( see # 481 ) tcg_th_needed_deps :: TcRef ([Linkable], PkgsLoaded), tcg_dfun_n :: TcRef OccSet, ^ Allows us to choose unique DFun names . tcg_merged :: [(Module, Fingerprint)], initially in un - zonked form and are finally zonked in tcRnSrcDecls tcg_rn_exports :: Maybe [(LIE GhcRn, Avails)], tcg_rn_imports :: [LImportDecl GhcRn], tcg_rn_decls :: Maybe (HsGroup GhcRn), ^ Renamed decls , maybe . @Nothing@ \<= > Do n't retain renamed tcg_th_topdecls :: TcRef [LHsDecl GhcPs], tcg_th_foreign_files :: TcRef [(ForeignSrcLang, FilePath)], ^ Foreign files emitted from TH . tcg_th_topnames :: TcRef NameSet, tcg_th_modfinalizers :: TcRef [(TcLclEnv, ThModFinalizers)], tcg_th_coreplugins :: TcRef [String], ^ Core plugins added by Template Haskell code . tcg_th_state :: TcRef (Map TypeRep Dynamic), tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))), tcg_th_docs :: TcRef THDocs, ^ Docs added in Template Haskell via @putDoc@. GHC.Runtime . Context I d for $ trModule : : GHC.Unit . Module for which every module has a top - level defn ... for imported Ids ... Top - level names that * lack * a signature ^ Maybe header docs ^ @True@ if any part of the NB . BangPattern is to fix a leak , see # 15111 ^ The Name of the main tcg_safe_infer :: TcRef Bool, tcg_safe_infer_reasons :: TcRef (Messages TcRnMessage), are supplied ( # 19714 ) , or if those reasons have already been tcg_tc_plugin_solvers :: [TcPluginSolver], tcg_tc_plugin_rewriters :: UniqFM TyCon [TcPluginRewriter], type family applications , collated by their type family ' 's . tcg_defaulting_plugins :: [FillDefaulting], tcg_hf_plugins :: [HoleFitPlugin], tcg_top_loc :: RealSrcSpan, ^ The RealSrcSpan this module came from tcg_static_wc :: TcRef WantedConstraints, tcg_complete_matches :: !CompleteMatches, tcg_cc_st :: TcRef CostCentreState, tcg_next_wrapper_num :: TcRef (ModuleEnv Int) ^ See Note [ Generating fresh names for FFI wrappers ] } NB : topModIdentity , not topModSemantic ! f : : StaticPtr ( Bool - > String ) tcVisibleOrphanMods :: TcGblEnv -> ModuleSet tcVisibleOrphanMods tcg_env = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env)) instance ContainsModule TcGblEnv where extractModule env = tcg_semantic_mod env data SelfBootInfo | SelfBoot defining these TyCons , in GHC.Rename . Module bootExports :: SelfBootInfo -> NameSet bootExports boot = case boot of NoSelfBoot -> emptyNameSet SelfBoot { sb_mds = mds} -> let exports = md_exports mds in availsToNameSet exports Note [ Tracking unused binding and imports ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We gather three sorts of usage information * tcg_dus : : ( defs / uses ) Records what is defined in this module and what is used . Records * defined * Names ( local , top - level ) and * used * Names ( local or imported ) Used ( a ) to report " defined but not used " ( see GHC.Rename . ) ( b ) to generate version - tracking usage info in interface files ( see GHC.Iface . Make.mkUsedNames ) This usage info is mainly gathered by the renamer 's gathering of free - variables * tcg_used_gres : : TcRef [ GlobalRdrElt ] Records occurrences of imported entities . Used only to report unused import declarations Records each * occurrence * an * imported * ( not locally - defined ) entity . The occurrence is recorded by keeping a GlobalRdrElt for it . These is not the GRE that is in the GlobalRdrEnv ; rather it is recorded * after * the filtering done by pickGREs . So it reflect /how that occurrence is in scope/. See Note [ GRE filtering ] in RdrName . * : : TcRef NameSet Records names of the type constructors , data constructors , and Ids that are used by the constraint solver . The typechecker may use find that some imported or locally - defined things are used , even though they do not appear to be mentioned in the source code : ( a ) The to / from functions for generic data types ( b ) Top - level variables appearing free in the RHS of an orphan rule ( c ) Top - level variables appearing free in a TH bracket See Note [ Keeping things alive for Template Haskell ] in GHC.Rename . Splice ( d ) The data constructor of a newtype that is used to solve a Coercible instance ( e.g. # 10347 ) . Example module T10347 ( N , mkN ) where import Data . Coerce newtype N a = mkN : : Int - > N a mkN = coerce Then we wish to record ` ` as used , since it is ( morally ) used to perform the coercion in ` mkN ` . To do so , the Coercible solver updates 's TcRef whenever it encounters a use of ` coerce ` that crosses newtype boundaries . ( e ) Record fields that are used to solve HasField constraints ( see Note [ Unused name reporting and HasField ] in . Instance . Class ) The field is used in two distinct ways : * Desugar.addExportFlagsAndRules . Where things like ( a - c ) are locally defined , we should give them an Exported flag , so that the simplifier does not discard them as dead code , and so that they are exposed in the interface file ( but not to export to the user ) . * GHC.Rename . Names.reportUnusedNames . Where newtype data constructors like ( d ) are imported , we do n't want to report them as unused . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The local typechecker environment * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note [ The Global - Env / Local - Env story ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During type checking , we keep in the tcg_type_env * All types and classes * All Ids derived from types and classes ( constructors , selectors ) At the end of type checking , we zonk the local bindings , and as we do so we add to the tcg_type_env * Locally defined top - level Ids Why ? Because they are now Ids not TcIds . This final GlobalEnv is a ) fed back ( via the knot ) to typechecking the unfoldings of interface signatures b ) used in the ModDetails of this module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We gather three sorts of usage information * tcg_dus :: DefUses (defs/uses) Records what is defined in this module and what is used. Records *defined* Names (local, top-level) and *used* Names (local or imported) Used (a) to report "defined but not used" (see GHC.Rename.Names.reportUnusedNames) (b) to generate version-tracking usage info in interface files (see GHC.Iface.Make.mkUsedNames) This usage info is mainly gathered by the renamer's gathering of free-variables * tcg_used_gres :: TcRef [GlobalRdrElt] Records occurrences of imported entities. Used only to report unused import declarations Records each *occurrence* an *imported* (not locally-defined) entity. The occurrence is recorded by keeping a GlobalRdrElt for it. These is not the GRE that is in the GlobalRdrEnv; rather it is recorded *after* the filtering done by pickGREs. So it reflect /how that occurrence is in scope/. See Note [GRE filtering] in RdrName. * tcg_keep :: TcRef NameSet Records names of the type constructors, data constructors, and Ids that are used by the constraint solver. The typechecker may use find that some imported or locally-defined things are used, even though they do not appear to be mentioned in the source code: (a) The to/from functions for generic data types (b) Top-level variables appearing free in the RHS of an orphan rule (c) Top-level variables appearing free in a TH bracket See Note [Keeping things alive for Template Haskell] in GHC.Rename.Splice (d) The data constructor of a newtype that is used to solve a Coercible instance (e.g. #10347). Example module T10347 (N, mkN) where import Data.Coerce newtype N a = MkN Int mkN :: Int -> N a mkN = coerce Then we wish to record `MkN` as used, since it is (morally) used to perform the coercion in `mkN`. To do so, the Coercible solver updates tcg_keep's TcRef whenever it encounters a use of `coerce` that crosses newtype boundaries. (e) Record fields that are used to solve HasField constraints (see Note [Unused name reporting and HasField] in GHC.Tc.Instance.Class) The tcg_keep field is used in two distinct ways: * Desugar.addExportFlagsAndRules. Where things like (a-c) are locally defined, we should give them an Exported flag, so that the simplifier does not discard them as dead code, and so that they are exposed in the interface file (but not to export to the user). * GHC.Rename.Names.reportUnusedNames. Where newtype data constructors like (d) are imported, we don't want to report them as unused. ************************************************************************ * * The local typechecker environment * * ************************************************************************ Note [The Global-Env/Local-Env story] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During type checking, we keep in the tcg_type_env * All types and classes * All Ids derived from types and classes (constructors, selectors) At the end of type checking, we zonk the local bindings, and as we do so we add to the tcg_type_env * Locally defined top-level Ids Why? Because they are now Ids not TcIds. This final GlobalEnv is a) fed back (via the knot) to typechecking the unfoldings of interface signatures b) used in the ModDetails of this module -} Discarded after / rename ; not passed on to desugarer = TcLclEnv { tcl_tclvl :: TcLevel, Template Haskell context The ThBindEnv records the TH binding level of in - scope Names Local name Does * not * include global name envt ; may shadow it they are kept distinct because tyvar have a different occurrence constructor ( Name . TvOcc ) Ids and defined in this module } setLclEnvTcLevel :: TcLclEnv -> TcLevel -> TcLclEnv setLclEnvTcLevel env lvl = env { tcl_tclvl = lvl } getLclEnvTcLevel :: TcLclEnv -> TcLevel getLclEnvTcLevel = tcl_tclvl setLclEnvLoc :: TcLclEnv -> RealSrcSpan -> TcLclEnv setLclEnvLoc env loc = env { tcl_loc = loc } getLclEnvLoc :: TcLclEnv -> RealSrcSpan getLclEnvLoc = tcl_loc lclEnvInGeneratedCode :: TcLclEnv -> Bool lclEnvInGeneratedCode = tcl_in_gen_code type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, SDoc)) Monadic so that we have a chance : True < = > this is a landmark context ; do not in . Types . Constraint , but they refer to ErrCtxt which refers to TcM. pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc pushErrCtxt o err loc@(CtLoc { ctl_env = lcl }) = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } } pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl }) = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } } type TcTypeEnv = NameEnv TcTyThing type ThBindEnv = NameEnv (TopLevelFlag, ThLevel) The TopLevelFlag tells if the binding is syntactically top level . bound at top level ! See Note [ Template Haskell levels ] in . Gen. Splice Note [ Given Insts ] ~~~~~~~~~~~~~~~~~~ Because of GADTs , we have to pass inwards the Insts provided by type signatures and existential contexts . Consider data T a where { T1 : : b - > b - > T [ b ] } f : : Eq a = > T a - > Bool f ( T1 x y ) = [ x]==[y ] The constructor T1 binds an existential variable ' b ' , and we need [ b ] . Well , we have it , because a refines to Eq [ b ] , but we can only spot that if we pass it inwards . ~~~~~~~~~~~~~~~~~~ Because of GADTs, we have to pass inwards the Insts provided by type signatures and existential contexts. Consider data T a where { T1 :: b -> b -> T [b] } f :: Eq a => T a -> Bool f (T1 x y) = [x]==[y] The constructor T1 binds an existential variable 'b', and we need Eq [b]. Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we pass it inwards. -} bits of data in ' TcGblEnv ' which are updated during typechecking and type TcRef a = IORef a ToDo : when should I refer to it as a ' TcId ' instead of an ' I d ' ? type TcId = Id type TcIdSet = IdSet type TcBinderStack = [TcBinder] Used only in error reporting ( relevantBindings in TcError ) , data TcBinder = TcIdBndr TcId an ExpType Name ExpType TopLevelFlag instance Outputable TcBinder where ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl) ppr (TcIdBndr_ExpType id _ top_lvl) = ppr id <> brackets (ppr top_lvl) ppr (TcTvBndr name tv) = ppr name <+> ppr tv instance HasOccName TcBinder where occName (TcIdBndr id _) = occName (idName id) occName (TcIdBndr_ExpType name _ _) = occName name occName (TcTvBndr name _) = occName name fixes # 12177 - ys has no duplicate OccNames - The first duplicated OccName in xs is retained in ys removeBindingShadowing :: HasOccName a => [a] -> [a] removeBindingShadowing bindings = reverse $ fst $ foldl (\(bindingAcc, seenNames) binding -> else (binding:bindingAcc, extendOccSet seenNames (occName binding))) ([], emptyOccSet) bindings getPlatform :: TcRnIf a b Platform getPlatform = targetPlatform <$> getDynFlags Template Haskell stages and levels data SpliceType = Typed | Untyped and Note [ Template Haskell levels ] in . Gen. Splice At splice : currently : return to previous stage currently Comp / Splice : compile and run | RunSplice (TcRef [ForeignRef (TH.Q ())]) Haskell code for the splice . See Note [ RunSplice ThLevel ] . to construct an @HsSpliced@ annotation for untyped splices . See Note [ Delaying modFinalizers in untyped splices ] in GHC.Rename . Splice . See Note [ Collecting modFinalizers in typed splices ] in " . Gen. Splice " . Binding level = 1 PendingStuff data PendingStuff topStage, topAnnStage, topSpliceStage :: ThStage topStage = Comp topAnnStage = Splice Untyped topSpliceStage = Splice Untyped instance Outputable ThStage where ppr (Splice _) = text "Splice" ppr (RunSplice _) = text "RunSplice" ppr Comp = text "Comp" ppr (Brack s _) = text "Brack" <> parens (ppr s) type ThLevel = Int NB : see Note [ Template Haskell levels ] in . Gen. Splice when going inside a bracket , NB : ThLevel is one greater than the ' n ' in Fig 2 of the original " Template meta - programming for " paper impLevel, outerLevel :: ThLevel thLevel :: ThStage -> ThLevel thLevel (Splice _) = 0 thLevel Comp = 1 thLevel (Brack s _) = thLevel s + 1 thLevel (RunSplice _) = panic "thLevel: called when running a splice" Note [ RunSplice ThLevel ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ' RunSplice ' stage is set when executing a splice , and only when running a splice . In particular it is not set when the splice is renamed or typechecked . ' RunSplice ' is needed to provide a reference where ' addModFinalizer ' can insert the finalizer ( see Note [ Delaying modFinalizers in untyped splices ] ) , and ' addModFinalizer ' runs when doing Q things . Therefore , It does n't make sense to set ' RunSplice ' when renaming or typechecking the splice , where ' Splice ' , ' Brack ' or ' Comp ' are used instead . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The 'RunSplice' stage is set when executing a splice, and only when running a splice. In particular it is not set when the splice is renamed or typechecked. 'RunSplice' is needed to provide a reference where 'addModFinalizer' can insert the finalizer (see Note [Delaying modFinalizers in untyped splices]), and 'addModFinalizer' runs when doing Q things. Therefore, It doesn't make sense to set 'RunSplice' when renaming or typechecking the splice, where 'Splice', 'Brack' or 'Comp' are used instead. -} Note [ Escaping the arrow scope ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In arrow notation , a variable bound by a proc ( or enclosed let / kappa ) is not in scope to the left of an arrow tail ( - < ) or the head of ( | .. | ) . For example proc x - > ( e1 - < e2 ) Here , x is not in scope in e1 , but it is in scope in e2 . This can get a bit complicated : let x = 3 in proc y - > ( proc z - > e1 ) - < e2 Here , x and z are in scope in e1 , but y is not . We implement this by recording the environment when passing a proc ( using newArrowScope ) , and returning to that ( using escapeArrowScope ) on the left of - < and the head of ( | .. | ) . All this can be dealt with by the * renamer * . But the type checker needs to be involved too . Example ( arrowfail001 ) class a where foo : : a - > ( ) data Bar = forall a. Foo a = > Bar a get : : Bar - > ( ) get = proc x - > case x of Bar a - > foo - < a Here the call of ' foo ' gives rise to a ( Foo a ) constraint that should not be captured by the pattern match on ' Bar ' . Rather it should join the constraints from further out . So we must capture the constraint bag from further out in the ArrowCtxt that we push inwards . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In arrow notation, a variable bound by a proc (or enclosed let/kappa) is not in scope to the left of an arrow tail (-<) or the head of (|..|). For example proc x -> (e1 -< e2) Here, x is not in scope in e1, but it is in scope in e2. This can get a bit complicated: let x = 3 in proc y -> (proc z -> e1) -< e2 Here, x and z are in scope in e1, but y is not. We implement this by recording the environment when passing a proc (using newArrowScope), and returning to that (using escapeArrowScope) on the left of -< and the head of (|..|). All this can be dealt with by the *renamer*. But the type checker needs to be involved too. Example (arrowfail001) class Foo a where foo :: a -> () data Bar = forall a. Foo a => Bar a get :: Bar -> () get = proc x -> case x of Bar a -> foo -< a Here the call of 'foo' gives rise to a (Foo a) constraint that should not be captured by the pattern match on 'Bar'. Rather it should join the constraints from further out. So we must capture the constraint bag from further out in the ArrowCtxt that we push inwards. -} = NoArrowCtxt | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints) data TcTyThing { tct_id :: TcId } The is always a TcTyCon . Its kind | APromotionErr PromotionErr | Matches on either a global ' ' or a ' TcTyCon ' . tcTyThingTyCon_maybe :: TcTyThing -> Maybe TyCon tcTyThingTyCon_maybe (AGlobal (ATyCon tc)) = Just tc tcTyThingTyCon_maybe (ATcTyCon tc_tc) = Just tc_tc tcTyThingTyCon_maybe _ = Nothing ppr (AGlobal g) = ppr g ppr elt@(ATcId {}) = text "Identifier" <> brackets (ppr (tct_id elt) <> dcolon <> ppr (varType (tct_id elt)) <> comma <+> ppr (tct_info elt)) ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv <+> dcolon <+> ppr (varType tv) ppr (ATcTyCon tc) = text "ATcTyCon" <+> ppr tc <+> dcolon <+> ppr (tyConKind tc) ppr (APromotionErr err) = text "APromotionErr" <+> ppr err a ) for static forms in ' . Gen. Expr.checkClosedInStaticForm ' and in ' . Gen. ' . = NotLetBound | ClosedLet | NonClosedLet data IsGroupClosed = IsGroupClosed imported or ClosedLet or NonClosedLet with ClosedTypeId = True . In particular , no tyvars , no NotLetBound Names of variables , mentioned on the RHS of a definition , that are not Global or ClosedLet type ClosedTypeId = Bool Note [ Meaning of IdBindingInfo ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NotLetBound means that the I d is not let - bound ( e.g. it is bound in a lambda - abstraction or in a case pattern ) ClosedLet means that - The I d is let - bound , - Any free term variables are also Global or ClosedLet - Its type has no free variables ( NB : a top - level binding subject to the MR might have free vars in its type ) These ClosedLets can definitely be floated to top level ; and we may need to do so for static forms . Property : ClosedLet is equivalent to NonClosedLet emptyNameSet True ( NonClosedLet ( fvs::RhsNames ) ( cl::ClosedTypeId ) ) means that - The I d is let - bound - The fvs::RhsNames contains the free names of the RHS , excluding Global and ClosedLet ones . - For the ClosedTypeId field see Note [ Bindings with closed types : ClosedTypeId ] For ( static e ) to be valid , we need for every ' x ' free in ' e ' , that x 's binding is floatable to the top level . Specifically : * x 's RhsNames must be empty * x 's type has no free variables See Note [ Grand plan for static forms ] in " GHC.Iface . Tidy . StaticPtrTable " . This test is made in . Gen. Expr.checkClosedInStaticForm . Actually knowing x 's RhsNames ( rather than just its emptiness or otherwise ) is just so we can produce better error messages Note [ Bindings with closed types : ClosedTypeId ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = let ys = map not ys in ... Can we generalise ' g ' under the OutsideIn algorithm ? Yes , because all g 's free variables are top - level ; that is they themselves have no free type variables , and it is the type variables in the environment that makes things tricky for OutsideIn generalisation . Here 's the invariant : If an I d has ClosedTypeId = True ( in its IdBindingInfo ) , then the I d 's type is /definitely/ closed ( has no free type variables ) . Specifically , a ) The I d 's actual type is closed ( has no free tyvars ) b ) Either the I d has a ( closed ) user - supplied type signature or all its free variables are Global / ClosedLet or NonClosedLet with ClosedTypeId = True . In particular , none are NotLetBound . Why is ( b ) needed ? Consider \x . ( x : : Int , let y = x+1 in ... ) Initially x::alpha . If we happen to typecheck the ' let ' before the ( ) , y 's type will have a free tyvar ; but if the other way round it wo n't . So we treat any let - bound variable with a free non - let - bound variable as not ClosedTypeId , regardless of what the free vars of its type actually are . But if it has a signature , all is well : \x . ... ( let { y::Int ; y = x+1 } in let { v = y+2 } in ... ) ... Here the signature on ' v ' makes ' y ' a ClosedTypeId , so we can generalise ' v ' . Note that : * A top - level binding may not have ClosedTypeId = True , if it suffers from the MR * A nested binding may be closed ( eg ' g ' in the example we started with ) . Indeed , that 's the point ; whether a function is defined at top level or nested is orthogonal to the question of whether or not it is closed . * A binding may be non - closed because it mentions a lexically scoped * type variable * Eg f : : forall a. blah f x = let y = ... ( y::a ) ... Under OutsideIn we are free to generalise an I d all of whose free variables have ClosedTypeId = True ( or imported ) . This is an extension compared to the paper on OutsideIn , which used " top - level " as a a top - level binding with a free type variable . ) Note [ Type variables in the type environment ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The type environment has a binding for each lexically - scoped type variable that is in scope . For example f : : forall a. a - > a f x = ( x : : a ) g1 : : [ a ] - > a g1 ( ys : : [ b ] ) = head ys : : b g2 : : [ Int ] - > Int g2 ( ys : : [ c ] ) = head ys : : c * The forall'd variable ' a ' in the signature scopes over f 's RHS . * The pattern - bound type variable ' b ' in ' g1 ' scopes over g1 's RHS ; note that it is bound to a skolem ' a ' which is not itself lexically in scope . * The pattern - bound type variable ' c ' in ' ' is bound to Int ; that is , pattern - bound type variables can stand for arbitrary types . ( see GHC proposal # 128 " Allow ScopedTypeVariables to refer to types " -proposals/ghc-proposals/pull/128 , and the paper " Type variables in patterns " , Haskell Symposium 2018 . This is implemented by the constructor ATyVar Name TcTyVar in the type environment . * The Name is the name of the original , lexically scoped type variable * The TcTyVar is sometimes a skolem ( like in ' f ' ) , and sometimes a unification variable ( like in ' g1 ' , ' ' ) . We never zonk the type environment so in the latter case it always stays as a unification variable , although that variable may be later unified with a type ( such as Int in ' ' ) . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NotLetBound means that the Id is not let-bound (e.g. it is bound in a lambda-abstraction or in a case pattern) ClosedLet means that - The Id is let-bound, - Any free term variables are also Global or ClosedLet - Its type has no free variables (NB: a top-level binding subject to the MR might have free vars in its type) These ClosedLets can definitely be floated to top level; and we may need to do so for static forms. Property: ClosedLet is equivalent to NonClosedLet emptyNameSet True (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that - The Id is let-bound - The fvs::RhsNames contains the free names of the RHS, excluding Global and ClosedLet ones. - For the ClosedTypeId field see Note [Bindings with closed types: ClosedTypeId] For (static e) to be valid, we need for every 'x' free in 'e', that x's binding is floatable to the top level. Specifically: * x's RhsNames must be empty * x's type has no free variables See Note [Grand plan for static forms] in "GHC.Iface.Tidy.StaticPtrTable". This test is made in GHC.Tc.Gen.Expr.checkClosedInStaticForm. Actually knowing x's RhsNames (rather than just its emptiness or otherwise) is just so we can produce better error messages Note [Bindings with closed types: ClosedTypeId] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = let g ys = map not ys in ... Can we generalise 'g' under the OutsideIn algorithm? Yes, because all g's free variables are top-level; that is they themselves have no free type variables, and it is the type variables in the environment that makes things tricky for OutsideIn generalisation. Here's the invariant: If an Id has ClosedTypeId=True (in its IdBindingInfo), then the Id's type is /definitely/ closed (has no free type variables). Specifically, a) The Id's actual type is closed (has no free tyvars) b) Either the Id has a (closed) user-supplied type signature or all its free variables are Global/ClosedLet or NonClosedLet with ClosedTypeId=True. In particular, none are NotLetBound. Why is (b) needed? Consider \x. (x :: Int, let y = x+1 in ...) Initially x::alpha. If we happen to typecheck the 'let' before the (x::Int), y's type will have a free tyvar; but if the other way round it won't. So we treat any let-bound variable with a free non-let-bound variable as not ClosedTypeId, regardless of what the free vars of its type actually are. But if it has a signature, all is well: \x. ...(let { y::Int; y = x+1 } in let { v = y+2 } in ...)... Here the signature on 'v' makes 'y' a ClosedTypeId, so we can generalise 'v'. Note that: * A top-level binding may not have ClosedTypeId=True, if it suffers from the MR * A nested binding may be closed (eg 'g' in the example we started with). Indeed, that's the point; whether a function is defined at top level or nested is orthogonal to the question of whether or not it is closed. * A binding may be non-closed because it mentions a lexically scoped *type variable* Eg f :: forall a. blah f x = let g y = ...(y::a)... Under OutsideIn we are free to generalise an Id all of whose free variables have ClosedTypeId=True (or imported). This is an extension compared to the JFP paper on OutsideIn, which used "top-level" as a a top-level binding with a free type variable.) Note [Type variables in the type environment] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The type environment has a binding for each lexically-scoped type variable that is in scope. For example f :: forall a. a -> a f x = (x :: a) g1 :: [a] -> a g1 (ys :: [b]) = head ys :: b g2 :: [Int] -> Int g2 (ys :: [c]) = head ys :: c * The forall'd variable 'a' in the signature scopes over f's RHS. * The pattern-bound type variable 'b' in 'g1' scopes over g1's RHS; note that it is bound to a skolem 'a' which is not itself lexically in scope. * The pattern-bound type variable 'c' in 'g2' is bound to Int; that is, pattern-bound type variables can stand for arbitrary types. (see GHC proposal #128 "Allow ScopedTypeVariables to refer to types" -proposals/ghc-proposals/pull/128, and the paper "Type variables in patterns", Haskell Symposium 2018. This is implemented by the constructor ATyVar Name TcTyVar in the type environment. * The Name is the name of the original, lexically scoped type variable * The TcTyVar is sometimes a skolem (like in 'f'), and sometimes a unification variable (like in 'g1', 'g2'). We never zonk the type environment so in the latter case it always stays as a unification variable, although that variable may be later unified with a type (such as Int in 'g2'). -} instance Outputable IdBindingInfo where ppr NotLetBound = text "NotLetBound" ppr ClosedLet = text "TopLevelLet" ppr (NonClosedLet fvs closed_type) = text "TopLevelLet" <+> ppr fvs <+> ppr closed_type pprTcTyThingCategory :: TcTyThing -> SDoc pprTcTyThingCategory = text . capitalise . tcTyThingCategory tcTyThingCategory :: TcTyThing -> String tcTyThingCategory (AGlobal thing) = tyThingCategory thing tcTyThingCategory (ATyVar {}) = "type variable" tcTyThingCategory (ATcId {}) = "local identifier" tcTyThingCategory (ATcTyCon {}) = "local tycon" tcTyThingCategory (APromotionErr pe) = peCategory pe mkModDeps :: Set (UnitId, ModuleNameWithIsBoot) -> InstalledModuleEnv ModuleNameWithIsBoot mkModDeps deps = S.foldl' add emptyInstalledModuleEnv deps where add env (uid, elt) = extendInstalledModuleEnv env (mkModule uid (gwib_mod elt)) elt plusModDeps :: InstalledModuleEnv ModuleNameWithIsBoot -> InstalledModuleEnv ModuleNameWithIsBoot -> InstalledModuleEnv ModuleNameWithIsBoot plusModDeps = plusInstalledModuleEnv plus_mod_dep where plus_mod_dep r1@(GWIB { gwib_mod = m1, gwib_isBoot = boot1 }) r2@(GWIB {gwib_mod = m2, gwib_isBoot = boot2}) | assertPpr (m1 == m2) ((ppr m1 <+> ppr m2) $$ (ppr (boot1 == IsBoot) <+> ppr (boot2 == IsBoot))) boot1 == IsBoot = r2 | otherwise = r1 Reusing existing tuples saves 10 % of allocations on test emptyImportAvails :: ImportAvails emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv, imp_direct_dep_mods = emptyInstalledModuleEnv, imp_dep_direct_pkgs = S.empty, imp_sig_mods = [], imp_trust_pkgs = S.empty, imp_trust_own_pkg = False, imp_boot_mods = emptyInstalledModuleEnv, imp_orphs = [], imp_finsts = [] } | Union two ImportAvails for each import we create a separate ImportAvails structure plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails plusImportAvails (ImportAvails { imp_mods = mods1, imp_direct_dep_mods = ddmods1, imp_dep_direct_pkgs = ddpkgs1, imp_boot_mods = srs1, imp_sig_mods = sig_mods1, imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1, imp_orphs = orphs1, imp_finsts = finsts1 }) (ImportAvails { imp_mods = mods2, imp_direct_dep_mods = ddmods2, imp_dep_direct_pkgs = ddpkgs2, imp_boot_mods = srcs2, imp_sig_mods = sig_mods2, imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2, imp_orphs = orphs2, imp_finsts = finsts2 }) = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2, imp_direct_dep_mods = ddmods1 `plusModDeps` ddmods2, imp_dep_direct_pkgs = ddpkgs1 `S.union` ddpkgs2, imp_trust_pkgs = tpkgs1 `S.union` tpkgs2, imp_trust_own_pkg = tself1 || tself2, imp_boot_mods = srs1 `plusModDeps` srcs2, imp_sig_mods = unionListsOrd sig_mods1 sig_mods2, imp_orphs = unionListsOrd orphs1 orphs2, imp_finsts = unionListsOrd finsts1 finsts2 } data WhereFrom See Note [ Care with plugin imports ] in GHC.Iface . Load instance Outputable WhereFrom where ppr (ImportByUser IsBoot) = text "{- SOURCE -}" ppr (ImportByUser NotBoot) = empty ppr ImportBySystem = text "{- SYSTEM -}" ppr ImportByPlugin = text "{- PLUGIN -}" GHC.Tc . Solver uses them , and . Solver is fairly type TcSigFun = Name -> Maybe TcSigInfo data TcSigInfo = TcIdSig TcIdSigInfo | TcPatSynSig TcPatSynInfo the Name in the FunSigCtxt is not the same } A partial type signature ( i.e. includes one or more HsSyn form , sig_ctxt :: UserTypeCtxt } Note [ Complete and partial type signatures ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A type signature is partial when it contains one or more wildcards (= type holes ) . The wildcard can either be : * A ( type ) wildcard occurring in sig_theta or sig_tau . These are stored in sig_wcs . f : : Bool - > _ g : : Eq _ a = > _ a - > _ a - > Bool * Or an extra - constraints wildcard , stored in sig_cts : h : : ( a , _ ) = > a - > a A type signature is a complete type signature when there are no wildcards in the type signature , i.e. iff sig_wcs is empty and sig_extra_cts is Nothing . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A type signature is partial when it contains one or more wildcards (= type holes). The wildcard can either be: * A (type) wildcard occurring in sig_theta or sig_tau. These are stored in sig_wcs. f :: Bool -> _ g :: Eq _a => _a -> _a -> Bool * Or an extra-constraints wildcard, stored in sig_cts: h :: (Num a, _) => a -> a A type signature is a complete type signature when there are no wildcards in the type signature, i.e. iff sig_wcs is empty and sig_extra_cts is Nothing. -} data TcIdSigInst = TISI { sig_inst_sig :: TcIdSigInfo , sig_inst_skols :: [(Name, InvisTVBinder)] but the may come from instantiating See Note [ Binding scoped type variables ] in . Gen. NB : The order of sig_inst_skols is irrelevant for a CompleteSig , but for a PartialSig see , sig_inst_theta :: TcThetaType PartialSig , sig_theta does not include , sig_inst_wcs :: [(Name, TcTyVar)] , sig_inst_wcx :: Maybe TcType only from the return value of . Gen. } Note [ sig_inst_tau may be polymorphic ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note that " sig_inst_tau " might actually be a polymorphic type , if the original function had a signature like forall a. Eq a = > forall b. Ord b = > .... But that 's ok : tcMatchesFun ( called by tcRhs ) can deal with that It happens , too ! See Note [ Polymorphic methods ] in . TyCl . Class . Note [ Quantified variables in partial type signatures ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f : : forall a b. _ - > a - > _ - > b f ( x , y ) p q = q Then we expect f 's final type to be f : : forall { x , y } . forall a b. ( x , y ) - > a - > b - > b Note that x , y are Inferred , and ca n't be use for visible type application ( VTA ) . But a , b are Specified , and remain Specified in the final type , so we can use VTA for them . ( Exception : if it turns out that a 's kind mentions b we need to reorder them with scopedSort . ) The sig_inst_skols of the TISI from a partial signature records that original order , and is used to get the variables of f 's final type in the correct order . Note [ Wildcards in partial signatures ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wildcards in psig_wcs may stand for a type mentioning the universally - quantified tyvars of psig_ty E.g. f : : forall a. _ - > a f x = x We get sig_inst_skols = [ a ] sig_inst_tau = _ 22 - > a sig_inst_wcs = [ _ 22 ] and _ 22 in the end is unified with the type ' a ' Moreover the kind of a wildcard in sig_inst_wcs may mention the universally - quantified tyvars sig_inst_skols e.g. f : : t a - > t _ Here we get sig_inst_skols = [ k :* , ( t::k - > * ) , ( a::k ) ] sig_inst_tau = t a - > t _ 22 sig_inst_wcs = [ _ 22::k ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note that "sig_inst_tau" might actually be a polymorphic type, if the original function had a signature like forall a. Eq a => forall b. Ord b => .... But that's ok: tcMatchesFun (called by tcRhs) can deal with that It happens, too! See Note [Polymorphic methods] in GHC.Tc.TyCl.Class. Note [Quantified variables in partial type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a b. _ -> a -> _ -> b f (x,y) p q = q Then we expect f's final type to be f :: forall {x,y}. forall a b. (x,y) -> a -> b -> b Note that x,y are Inferred, and can't be use for visible type application (VTA). But a,b are Specified, and remain Specified in the final type, so we can use VTA for them. (Exception: if it turns out that a's kind mentions b we need to reorder them with scopedSort.) The sig_inst_skols of the TISI from a partial signature records that original order, and is used to get the variables of f's final type in the correct order. Note [Wildcards in partial signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The wildcards in psig_wcs may stand for a type mentioning the universally-quantified tyvars of psig_ty E.g. f :: forall a. _ -> a f x = x We get sig_inst_skols = [a] sig_inst_tau = _22 -> a sig_inst_wcs = [_22] and _22 in the end is unified with the type 'a' Moreover the kind of a wildcard in sig_inst_wcs may mention the universally-quantified tyvars sig_inst_skols e.g. f :: t a -> t _ Here we get sig_inst_skols = [k:*, (t::k ->*), (a::k)] sig_inst_tau = t a -> t _22 sig_inst_wcs = [ _22::k ] -} data TcPatSynInfo = TPSI { patsig_name :: Name, See Note [ The pattern - synonym signature splitting rule ] in . TyCl . PatSyn patsig_req :: TcThetaType, patsig_prov :: TcThetaType, patsig_body_ty :: TcSigmaType } instance Outputable TcSigInfo where ppr (TcIdSig idsi) = ppr idsi ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi instance Outputable TcIdSigInfo where ppr (CompleteSig { sig_bndr = bndr }) = ppr bndr <+> dcolon <+> ppr (idType bndr) ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty }) = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty instance Outputable TcIdSigInst where ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols , sig_inst_theta = theta, sig_inst_tau = tau }) = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ]) instance Outputable TcPatSynInfo where ppr (TPSI{ patsig_name = name}) = ppr name isPartialSig :: TcIdSigInst -> Bool isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True isPartialSig _ = False hasCompleteSig :: TcSigFun -> Name -> Bool hasCompleteSig sig_fn name = case sig_fn name of Just (TcIdSig (CompleteSig {})) -> True _ -> False type TcPluginSolver = EvBindsVar ^ -> TcPluginM TcPluginSolveResult a function of this type for each type family ' ' . type TcPluginRewriter -> TcPluginM TcPluginRewriteResult newtype TcPluginM a = TcPluginM { runTcPluginM :: TcM a } deriving newtype (Functor, Applicative, Monad, MonadFail) the ' ` monad . It should not be used lightly , and unsafeTcPluginTcM :: TcM a -> TcPluginM a unsafeTcPluginTcM = TcPluginM data TcPlugin = forall s. TcPlugin { tcPluginInit :: TcPluginM s , tcPluginSolve :: s -> TcPluginSolver This function will be invoked at two points in the constraint solving Wanted constraints . In the first case ( and only in the first case ) , must be Givens in the first case , and in the second . , tcPluginRewrite :: s -> UniqFM TyCon TcPluginRewriter rewriting functions . For each type family ' ' , the plugin should , tcPluginStop :: s -> TcPluginM () } pattern TcPluginContradiction :: [Ct] -> TcPluginSolveResult pattern TcPluginContradiction insols = TcPluginSolveResult { tcPluginInsolubleCts = insols , tcPluginSolvedCts = [] , tcPluginNewCts = [] } The first field is for constraints that were solved . The second field contains new work , that should be processed by pattern TcPluginOk :: [(EvTerm, Ct)] -> [Ct] -> TcPluginSolveResult pattern TcPluginOk solved new = TcPluginSolveResult { tcPluginInsolubleCts = [] , tcPluginSolvedCts = solved , tcPluginNewCts = new } data TcPluginSolveResult = TcPluginSolveResult tcPluginInsolubleCts :: [Ct] , tcPluginSolvedCts :: [(EvTerm, Ct)] , tcPluginNewCts :: [Ct] } data TcPluginRewriteResult = TcPluginNoRewrite | TcPluginRewriteTo { tcPluginReduction :: !Reduction , tcRewriterNewWanteds :: [Ct] } data DefaultingProposal = DefaultingProposal { deProposalTyVar :: TcTyVar , deProposalCandidates :: [Type] , deProposalCts :: [Ct] } instance Outputable DefaultingProposal where ppr p = text "DefaultingProposal" <+> ppr (deProposalTyVar p) <+> ppr (deProposalCandidates p) <+> ppr (deProposalCts p) type DefaultingPluginResult = [DefaultingProposal] type FillDefaulting = WantedConstraints -> TcPluginM DefaultingPluginResult data DefaultingPlugin = forall s. DefaultingPlugin { dePluginInit :: TcPluginM s , dePluginRun :: s -> FillDefaulting , dePluginStop :: s -> TcPluginM () } type RoleAnnotEnv = NameEnv (LRoleAnnotDecl GhcRn) mkRoleAnnotEnv :: [LRoleAnnotDecl GhcRn] -> RoleAnnotEnv mkRoleAnnotEnv role_annot_decls = mkNameEnv [ (name, ra_decl) | ra_decl <- role_annot_decls , let name = roleAnnotDeclName (unLoc ra_decl) , not (isUnboundName name) ] emptyRoleAnnotEnv :: RoleAnnotEnv emptyRoleAnnotEnv = emptyNameEnv lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl GhcRn) lookupRoleAnnot = lookupNameEnv getRoleAnnots :: [Name] -> RoleAnnotEnv -> [LRoleAnnotDecl GhcRn] getRoleAnnots bndrs role_env = mapMaybe (lookupRoleAnnot role_env) bndrs lintGblEnv :: Logger -> DynFlags -> TcGblEnv -> TcM () lintGblEnv logger dflags tcg_env = TODO empty list means no extra in scope from GHCi , is this correct ? liftIO $ lintAxioms logger (initLintConfig dflags []) (text "TcGblEnv axioms") axioms where axioms = typeEnvCoAxioms (tcg_type_env tcg_env) | This is a mirror of Template Haskell 's DocLoc , but the TH names are resolved to GHC names . data DocLoc = DeclDoc Name | ArgDoc Name Int | InstDoc Name | ModuleDoc deriving (Eq, Ord) | The current collection of docs that has built up via type THDocs = Map DocLoc (HsDoc GhcRn)
bf4053494a23e59c1e224af45e94b30fb26ee673da8346554c543189ab2e6fa8
fragnix/fragnix
BaseOrphanInstances.hs
module BaseOrphanInstances where f :: Double -> String f = show g :: [Double] g = enumFromTo 0.0 1.0
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/quick/BaseOrphanInstances/BaseOrphanInstances.hs
haskell
module BaseOrphanInstances where f :: Double -> String f = show g :: [Double] g = enumFromTo 0.0 1.0