_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
|
---|---|---|---|---|---|---|---|---|
146500ded2707db4ff232ba31c903a6c40534cbc0ff8475db3e900f7eb0cee3e | Helium4Haskell/helium | TypeBug4.hs | module TypeBug4 where
sp :: ([a] -> Int -> String) -> [a] -> String
sp k l | length k < max length k (max.map(length l)) = k : sp k : " "
| True = k
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/simple/typeerrors/Examples/TypeBug4.hs | haskell | module TypeBug4 where
sp :: ([a] -> Int -> String) -> [a] -> String
sp k l | length k < max length k (max.map(length l)) = k : sp k : " "
| True = k
|
|
a676740c375fcaa550c19b9fa1e9dfc85d76199cb186aa0861ffae0af03f4dd4 | reborg/clojure-essential-reference | 2.clj | < 1 >
;; #{1 4 3 2} | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sets/set/2.clj | clojure | #{1 4 3 2} | < 1 > |
7e68b18aed59cf185fb51de569877065fba65ea79e9a490a57e37604653872cc | tomjridge/kv-hash | test2.ml | (** Test executable *)
module X = Kv_hash.Nv_map_ii.Test2()
| null | https://raw.githubusercontent.com/tomjridge/kv-hash/9854f6d992f5c30ab9fdad614ba16684d3bbd082/test/test2.ml | ocaml | * Test executable |
module X = Kv_hash.Nv_map_ii.Test2()
|
a481a0e55be27331bb7384f5afbaf84dcbc21e5f8f6a4d12a45cb5c473040463 | vyorkin/tiger | ex1_1b.ml | open Base
type key = string
type 'a tree =
| Leaf
| Tree of ('a tree) * key * 'a * ('a tree)
let rec insert t k v =
let open Base.Poly in
match t with
| Leaf -> Tree (Leaf, k, v, Leaf)
| Tree (l, k', v', r) ->
if k < k' then Tree (insert l k v, k', v', r)
else if k > k' then Tree (l, k', v', insert r k v)
else Tree (l, k, v, r)
let rec lookup t k =
let open Base.Poly in
match t with
| Leaf -> None
| Tree (l, k', v, r) ->
if k = k' then Some v
else if k < k' then lookup l k
else lookup r k
let t1 = insert (insert (insert (insert Leaf "i" 4) "p" 3) "s" 2) "t" 1
| null | https://raw.githubusercontent.com/vyorkin/tiger/54dd179c1cd291df42f7894abce3ee9064e18def/chapter1/ex1_1b.ml | ocaml | open Base
type key = string
type 'a tree =
| Leaf
| Tree of ('a tree) * key * 'a * ('a tree)
let rec insert t k v =
let open Base.Poly in
match t with
| Leaf -> Tree (Leaf, k, v, Leaf)
| Tree (l, k', v', r) ->
if k < k' then Tree (insert l k v, k', v', r)
else if k > k' then Tree (l, k', v', insert r k v)
else Tree (l, k, v, r)
let rec lookup t k =
let open Base.Poly in
match t with
| Leaf -> None
| Tree (l, k', v, r) ->
if k = k' then Some v
else if k < k' then lookup l k
else lookup r k
let t1 = insert (insert (insert (insert Leaf "i" 4) "p" 3) "s" 2) "t" 1
|
|
f2b7a48b7b6026860e9d12d8768048fbcd0fb4bc0e7eb6c5fe61f70c2588ba58 | calyau/maxima | mring.lisp | A Maxima ring structure
Copyright ( C ) 2005 , 2007 ,
Barton Willis
Department of Mathematics
University of Nebraska at Kearney
;; Kearney NE 68847
;;
;; This source code is licensed under the terms of the Lisp Lesser
GNU Public License ( LLGPL ) . The LLGPL consists of a preamble , published
by Franz Inc. ( ) , and the GNU
Library General Public License ( LGPL ) , version 2 , or ( at your option )
;; any later version. When the preamble conflicts with the LGPL,
;; the preamble takes precedence.
;; This library is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for details .
You should have received a copy of the GNU Library General Public
;; License along with this library; if not, write to the
Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor ,
Boston , MA 02110 - 1301 , USA .
;; Let's have version numbers 1,2,3,...
(eval-when (:compile-toplevel :load-toplevel :execute)
($put '$mring 1 '$version))
;; (1) In maxima-grobner.lisp, there is a structure 'ring.'
( 2 ) Some functions in this structure , for example ' great ' might
;; not be defined for a ring; when this is the case, a function
;; can signal an error.
( 3 ) Floating point addition is n't associative ; so a mring need n't
;; be a ring. But a mring is 'close' to being a ring.
;; Description of the mring fields:
(defstruct mring
name
coerce-to-lisp-float
abs
great
add
div
rdiv
reciprocal
mult
sub
negate
psqrt
add-id
mult-id
fzerop
adjoint
maxima-to-mring
mring-to-maxima)
(eval-when
#-gcl (:compile-toplevel :load-toplevel :execute)
#+gcl (compile load eval)
(defmvar $%mrings `((mlist) $floatfield $complexfield $rationalfield $crering
$generalring $bigfloatfield $runningerror $noncommutingring ))
(defvar *gf-rings* '(gf-coeff-ring gf-ring ef-ring)) )
(defun $require_ring (ringname pos fun)
(if (or ($member ringname $%mrings) (member ringname *gf-rings*))
(get ringname 'ring)
(merror (intl:gettext "The ~:M argument of the function '~:M' must be the name of a ring") pos fun)))
(defparameter *floatfield*
(make-mring
:name '$floatfield
:coerce-to-lisp-float #'cl:identity
:abs #'abs
:great #'>
:add #'+
:div #'/
:rdiv #'/
:reciprocal #'/
:mult #'*
:sub #'-
:negate #'-
:psqrt #'(lambda (s) (if (>= s 0) (cl:sqrt s) nil))
:add-id #'(lambda () 0.0)
:mult-id #'(lambda () 1.0)
:fzerop #'(lambda (s) (< (abs s) (* 4 flonum-epsilon)))
:adjoint #'cl:identity
:mring-to-maxima #'cl:identity
:maxima-to-mring #'(lambda (s)
(setq s ($float s))
(if (floatp s) s (merror "Unable to convert ~:M to a long float" s)))))
(setf (get '$floatfield 'ring) *floatfield*)
(defparameter *complexfield*
(make-mring
:name '$complexfield
:coerce-to-lisp-float #'cl:identity
:abs #'abs
:great #'>
:add #'+
:div #'/
:rdiv #'/
:reciprocal #'/
:mult #'*
:sub #'-
:negate #'-
:psqrt #'(lambda (s) (if (and (= 0 (imagpart s)) (>= (realpart s) 0)) (cl:sqrt s) nil))
:add-id #'(lambda () 0.0)
:mult-id #'(lambda () 1.0)
:fzerop #'(lambda (s) (< (abs s) (* 4 flonum-epsilon)))
:adjoint #'cl:conjugate
was
:maxima-to-mring #'(lambda (s)
(progn
(setq s (coerce-expr-to-clcomplex ($rectform (meval s))))
(if (complexp s)
s
(merror "Unable to convert ~:M to a complex long float" s))))))
(defun coerce-expr-to-clcomplex (s)
(complex (funcall (coerce-float-fun ($realpart s))) (funcall (coerce-float-fun ($imagpart s)))))
(setf (get '$complexfield 'ring) *complexfield*)
(defparameter *rationalfield*
(make-mring
:name '$rationalfield
:coerce-to-lisp-float #'(lambda (s) ($float s))
:abs #'abs
:great #'>
:add #'+
:div #'/
:rdiv #'/
:reciprocal #'/
:mult #'*
:sub #'-
:negate #'-
:psqrt #'(lambda (s) (let ((x))
(cond ((>= s 0)
(setq x (isqrt (numerator s)))
(setq x (/ x (isqrt (denominator s))))
(if (= s (* x x)) x nil))
(t nil))))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (= s 0))
:adjoint #'cl:identity
:mring-to-maxima #'(lambda (s) (simplify `((rat) ,(numerator s) ,(denominator s))))
:maxima-to-mring
#'(lambda (s)
(if (or (floatp s) ($bfloatp s)) (setq s ($rationalize s)))
(if ($ratnump s) (if (integerp s) s (/ ($num s) ($denom s)))
(merror "Unable to convert ~:M to a rational number" s)))))
(setf (get '$rationalfield 'ring) *rationalfield*)
(defparameter *crering*
(make-mring
:name '$crering
:coerce-to-lisp-float nil
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'(lambda (a b) (declare (ignore a)) (eq t (meqp b 0)))
:add #'add
:div #'div
:rdiv #'div
:reciprocal #'(lambda (s) (div 1 s))
:mult #'mult
:sub #'sub
:negate #'(lambda (s) (mult -1 s))
:psqrt #'(lambda (s) (if (member (csign ($ratdisrep s)) `($pos $pz $zero)) (take '(%sqrt) s) nil))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (eq t (meqp s 0)))
:adjoint #'(lambda (s) (take '($conjugate) s))
:mring-to-maxima #'(lambda (s) s)
:maxima-to-mring #'(lambda (s) ($rat s))))
(setf (get '$crering 'ring) *crering*)
(defparameter *generalring*
(make-mring
:name '$generalring
:coerce-to-lisp-float nil
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'(lambda (a b) (declare (ignore a)) (eq t (meqp b 0)))
:add #'(lambda (a b) (add a b))
:div #'(lambda (a b) (div a b))
:rdiv #'(lambda (a b) (div a b))
:reciprocal #'(lambda (s) (div 1 s))
:mult #'(lambda (a b) (mult a b))
:sub #'(lambda (a b) (sub a b))
:negate #'(lambda (a) (mult -1 a))
:psqrt #'(lambda (s) (if (member (csign s) `($pos $pz $zero)) (take '(%sqrt) s) nil))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (eq t (meqp (sratsimp s) 0)))
:adjoint #'(lambda (s) (take '($conjugate) s))
:mring-to-maxima #'(lambda (s) s)
:maxima-to-mring #'(lambda (s) s)))
(setf (get '$generalring 'ring) *generalring*)
(defparameter *bigfloatfield*
(make-mring
:name '$bigfloatfield
:coerce-to-lisp-float #'(lambda (s)
(setq s ($rectform ($float s)))
(complex ($realpart s) ($imagpart s)))
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'mgrp
:add #'(lambda (a b) ($rectform (add a b)))
:div #'(lambda (a b) ($rectform (div a b)))
:rdiv #'(lambda (a b) ($rectform (div a b)))
:reciprocal #'(lambda (s) (div 1 s))
:mult #'(lambda (a b) ($rectform (mult a b)))
:sub #'(lambda (a b) ($rectform (sub a b)))
:negate #'(lambda (a) (mult -1 a))
:psqrt #'(lambda (s) (if (mlsp s 0) nil (take '(%sqrt) s)))
:add-id #'(lambda () bigfloatzero)
:mult-id #'(lambda () bigfloatone)
:fzerop #'(lambda (s) (like s bigfloatzero))
:adjoint #'cl:identity
:mring-to-maxima #'(lambda (s) s)
:maxima-to-mring #'(lambda (s)
(setq s ($rectform ($bfloat s)))
(if (or (eq s '$%i) (complex-number-p s 'bigfloat-or-number-p)) s
(merror "Unable to convert matrix entry to a big float")))))
(setf (get '$bigfloatfield 'ring) *bigfloatfield*)
;; --- *gf-rings* --- (used by src/numth.lisp) ------------------------------ ;;
;; ;;
(defparameter *gf-coeff-ring*
(make-mring
:name 'gf-coeff-ring
:coerce-to-lisp-float nil
:abs #'gf-cmod
:great #'(lambda (a b) (declare (ignore a)) (null b))
:add #'gf-cplus-b
:div #'(lambda (a b) (gf-ctimes a (gf-cinv b)))
:rdiv #'(lambda (a b) (gf-ctimes a (gf-cinv b)))
:reciprocal #'gf-cinv
:mult #'gf-ctimes
:sub #'(lambda (a b) (gf-cplus-b a (gf-cminus-b b)))
:negate #'gf-cminus-b
:psqrt #'(lambda (a) (let ((rs (zn-nrt a 2 *gf-char*))) (when rs (car rs))))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (= 0 s))
:adjoint nil
:mring-to-maxima #'cl:identity
:maxima-to-mring #'cl:identity ))
;;
(setf (get 'gf-coeff-ring 'ring) *gf-coeff-ring*)
;;
(defparameter *gf-ring*
(make-mring
:name 'gf-ring
:coerce-to-lisp-float nil
:abs #'gf-mod
:great #'(lambda (a b) (declare (ignore a)) (null b))
:add #'gf-plus
:div #'(lambda (a b) (gf-times a (gf-inv b *gf-red*) *gf-red*))
:rdiv #'(lambda (a b) (gf-times a (gf-inv b *gf-red*) *gf-red*))
:reciprocal #'(lambda (a) (gf-inv a *gf-red*))
:mult #'(lambda (a b) (gf-times a b *gf-red*))
:sub #'(lambda (a b) (gf-plus a (gf-minus b)))
:negate #'gf-minus
:psqrt #'(lambda (a)
(let ((rs (gf-nrt-exit (gf-nrt a 2 *gf-red* *gf-ord*))))
(when rs (cadr rs)) ))
:add-id #'(lambda () nil)
:mult-id #'(lambda () '(0 1))
:fzerop #'(lambda (s) (null s))
:adjoint nil
:mring-to-maxima #'gf-x2p
:maxima-to-mring #'gf-p2x ))
;;
(setf (get 'gf-ring 'ring) *gf-ring*)
;;
(defparameter *ef-ring*
(make-mring
:name 'ef-ring
:coerce-to-lisp-float nil
:abs #'gf-mod
:great #'(lambda (a b) (declare (ignore a)) (null b))
:add #'gf-plus
:div #'(lambda (a b) (gf-times a (gf-inv b *ef-red*) *ef-red*))
:rdiv #'(lambda (a b) (gf-times a (gf-inv b *ef-red*) *ef-red*))
:reciprocal #'(lambda (a) (gf-inv a *ef-red*))
:mult #'(lambda (a b) (gf-times a b *ef-red*))
:sub #'(lambda (a b) (gf-plus a (gf-minus b)))
:negate #'gf-minus
:psqrt #'(lambda (a)
(let ((rs (gf-nrt-exit (gf-nrt a 2 *ef-red* *ef-ord*))))
(when rs (cadr rs)) ))
:add-id #'(lambda () nil)
:mult-id #'(lambda () '(0 1))
:fzerop #'(lambda (s) (null s))
:adjoint nil
:mring-to-maxima #'gf-x2p
:maxima-to-mring #'gf-p2x ))
(setf (get 'ef-ring 'ring) *ef-ring*)
;; ;;
;; -------------------------------------------------------------------------- ;;
(defun fp-abs (a)
(list (abs (first a)) (second a)))
(defun fp+ (a b)
(cond ((= (first a) 0.0) b)
((= (first b) 0.0) a)
(t
(let ((s (+ (first a) (first b))))
(if (= 0.0 s) (merror "floating point divide by zero"))
(list s (ceiling (+ 1
(abs (/ (* (first a) (second a)) s))
(abs (/ (* (first b) (second b)) s)))))))))
(defun fp- (a b)
(cond ((= (first a) 0.0) (list (- (first b)) (second b)))
((= (first b) 0.0) a)
(t
(let ((s (- (first a) (first b))))
(if (= 0.0 s) (merror "floating point divide by zero"))
(list s (ceiling (+ 1
(abs (/ (* (first a) (second a)) s))
(abs (/ (* (first b) (second b)) s)))))))))
(defun fp* (a b)
(if (or (= (first a) 0.0) (= (first b) 0.0)) (list 0.0 0)
(list (* (first a) (first b)) (+ 1 (second a) (second b)))))
(defun fp/ (a b)
(if (= (first a) 0) (list 0.0 0)
(list (/ (first a) (first b)) (+ 1 (second a) (second b)))))
(defun $addmatrices(fn &rest m)
(mfuncall '$apply '$matrixmap `((mlist) ,fn ,@m)))
(defparameter *runningerror*
(make-mring
:name '$runningerror
:coerce-to-lisp-float #'(lambda (s) (if (consp s) (first s) s))
:abs #'fp-abs
:great #'(lambda (a b) (> (first a) (first b)))
:add #'fp+
:div #'fp/
:rdiv #'fp/
:reciprocal #'(lambda (s) (fp/ (list 1 0) s))
:mult #'fp*
:sub #'fp-
:negate #'(lambda (s) (list (- (first s)) (second s)))
:psqrt #'(lambda (s) (if (> (first s) 0) (list (cl:sqrt (first s)) (+ 1 (second s))) nil))
:add-id #'(lambda () (list 0 0))
:mult-id #'(lambda () (list 1 0))
:fzerop #'(lambda (s) (like (first s) 0))
:adjoint #'cl:identity
:mring-to-maxima #'(lambda (s) `((mlist) ,@s))
:maxima-to-mring #'(lambda (s) (if ($listp s) (cdr s) (list ($float s) 1)))))
(setf (get '$runningerror 'ring) *runningerror*)
(defparameter *noncommutingring*
(make-mring
:name '$noncommutingring
:coerce-to-lisp-float nil
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'(lambda (a b) (declare (ignore a)) (eq t (meqp b 0)))
:add #'(lambda (a b) (add a b))
:div #'(lambda (a b) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(setq b (if ($matrixp b) ($invert_by_lu b '$noncommutingring)
(take '(mncexpt) b -1)))
(take '(mnctimes) a b))))
:rdiv #'(lambda (a b) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(setq b (if ($matrixp b) ($invert_by_lu b '$noncommutingring)
(take '(mncexpt) b -1)))
(take '(mnctimes) b a))))
:reciprocal #'(lambda (s) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(if ($matrixp s) ($invert_by_lu s '$noncommutingring)
(take '(mncexpt) s -1)))))
:mult #'(lambda (a b) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(take '(mnctimes) a b))))
:sub #'(lambda (a b) (sub a b))
:negate #'(lambda (a) (mult -1 a))
:add-id #'(lambda () 0)
:psqrt #'(lambda (s) (take '(%sqrt) s))
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (eq t (meqp s 0)))
:adjoint #'(lambda (s) ($transpose (take '($conjugate) s)))
:mring-to-maxima #'cl:identity
:maxima-to-mring #'cl:identity))
(setf (get '$noncommutingring 'ring) *noncommutingring*)
(defun ring-eval (e fld)
(let ((fadd (mring-add fld))
(fnegate (mring-negate fld))
(fmult (mring-mult fld))
(fdiv (mring-div fld))
(fabs (mring-abs fld))
(fconvert (mring-maxima-to-mring fld)))
(cond ((or ($numberp e) (symbolp e))
(funcall fconvert (meval e)))
;; I don't think an empty sum or product is possible here. If it is, append
;; the appropriate initial-value to reduce. Using the :inital-value isn't
;; a problem, but (fp* (a b) (1 0)) --> (a (+ b 1)). A better value is
;; (fp* (a b) (1 0)) --> (a b).
((op-equalp e 'mplus)
(reduce fadd (mapcar #'(lambda (s) (ring-eval s fld)) (margs e)) :from-end t))
((op-equalp e 'mminus)
(funcall fnegate (ring-eval (first (margs e)) fld)))
((op-equalp e 'mtimes)
(reduce fmult (mapcar #'(lambda (s) (ring-eval s fld)) (margs e)) :from-end t))
((op-equalp e 'mquotient)
(funcall fdiv (ring-eval (first (margs e)) fld)(ring-eval (second (margs e)) fld)))
((op-equalp e 'mabs) (funcall fabs (ring-eval (first (margs e)) fld)))
((and (or (eq (mring-name fld) '$floatfield) (eq (mring-name fld) '$complexfield))
(consp e) (consp (car e)) (gethash (mop e) *flonum-op*))
(apply (gethash (mop e) *flonum-op*) (mapcar #'(lambda (s) (ring-eval s fld)) (margs e))))
(t (merror "Unable to evaluate ~:M in the ring '~:M'" e (mring-name fld))))))
(defmspec $ringeval (e)
(let ((fld (get (or (car (member (nth 2 e) $%mrings)) '$generalring) 'ring)))
(funcall (mring-mring-to-maxima fld) (ring-eval (nth 1 e) fld))))
| null | https://raw.githubusercontent.com/calyau/maxima/9352a3f5c22b9b5d0b367fddeb0185c53d7f4d02/share/linearalgebra/mring.lisp | lisp | Kearney NE 68847
This source code is licensed under the terms of the Lisp Lesser
any later version. When the preamble conflicts with the LGPL,
the preamble takes precedence.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
License along with this library; if not, write to the
Let's have version numbers 1,2,3,...
(1) In maxima-grobner.lisp, there is a structure 'ring.'
not be defined for a ring; when this is the case, a function
can signal an error.
so a mring need n't
be a ring. But a mring is 'close' to being a ring.
Description of the mring fields:
--- *gf-rings* --- (used by src/numth.lisp) ------------------------------ ;;
;;
;;
-------------------------------------------------------------------------- ;;
I don't think an empty sum or product is possible here. If it is, append
the appropriate initial-value to reduce. Using the :inital-value isn't
a problem, but (fp* (a b) (1 0)) --> (a (+ b 1)). A better value is
(fp* (a b) (1 0)) --> (a b). | A Maxima ring structure
Copyright ( C ) 2005 , 2007 ,
Barton Willis
Department of Mathematics
University of Nebraska at Kearney
GNU Public License ( LLGPL ) . The LLGPL consists of a preamble , published
by Franz Inc. ( ) , and the GNU
Library General Public License ( LGPL ) , version 2 , or ( at your option )
Library General Public License for details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor ,
Boston , MA 02110 - 1301 , USA .
(eval-when (:compile-toplevel :load-toplevel :execute)
($put '$mring 1 '$version))
( 2 ) Some functions in this structure , for example ' great ' might
(defstruct mring
name
coerce-to-lisp-float
abs
great
add
div
rdiv
reciprocal
mult
sub
negate
psqrt
add-id
mult-id
fzerop
adjoint
maxima-to-mring
mring-to-maxima)
(eval-when
#-gcl (:compile-toplevel :load-toplevel :execute)
#+gcl (compile load eval)
(defmvar $%mrings `((mlist) $floatfield $complexfield $rationalfield $crering
$generalring $bigfloatfield $runningerror $noncommutingring ))
(defvar *gf-rings* '(gf-coeff-ring gf-ring ef-ring)) )
(defun $require_ring (ringname pos fun)
(if (or ($member ringname $%mrings) (member ringname *gf-rings*))
(get ringname 'ring)
(merror (intl:gettext "The ~:M argument of the function '~:M' must be the name of a ring") pos fun)))
(defparameter *floatfield*
(make-mring
:name '$floatfield
:coerce-to-lisp-float #'cl:identity
:abs #'abs
:great #'>
:add #'+
:div #'/
:rdiv #'/
:reciprocal #'/
:mult #'*
:sub #'-
:negate #'-
:psqrt #'(lambda (s) (if (>= s 0) (cl:sqrt s) nil))
:add-id #'(lambda () 0.0)
:mult-id #'(lambda () 1.0)
:fzerop #'(lambda (s) (< (abs s) (* 4 flonum-epsilon)))
:adjoint #'cl:identity
:mring-to-maxima #'cl:identity
:maxima-to-mring #'(lambda (s)
(setq s ($float s))
(if (floatp s) s (merror "Unable to convert ~:M to a long float" s)))))
(setf (get '$floatfield 'ring) *floatfield*)
(defparameter *complexfield*
(make-mring
:name '$complexfield
:coerce-to-lisp-float #'cl:identity
:abs #'abs
:great #'>
:add #'+
:div #'/
:rdiv #'/
:reciprocal #'/
:mult #'*
:sub #'-
:negate #'-
:psqrt #'(lambda (s) (if (and (= 0 (imagpart s)) (>= (realpart s) 0)) (cl:sqrt s) nil))
:add-id #'(lambda () 0.0)
:mult-id #'(lambda () 1.0)
:fzerop #'(lambda (s) (< (abs s) (* 4 flonum-epsilon)))
:adjoint #'cl:conjugate
was
:maxima-to-mring #'(lambda (s)
(progn
(setq s (coerce-expr-to-clcomplex ($rectform (meval s))))
(if (complexp s)
s
(merror "Unable to convert ~:M to a complex long float" s))))))
(defun coerce-expr-to-clcomplex (s)
(complex (funcall (coerce-float-fun ($realpart s))) (funcall (coerce-float-fun ($imagpart s)))))
(setf (get '$complexfield 'ring) *complexfield*)
(defparameter *rationalfield*
(make-mring
:name '$rationalfield
:coerce-to-lisp-float #'(lambda (s) ($float s))
:abs #'abs
:great #'>
:add #'+
:div #'/
:rdiv #'/
:reciprocal #'/
:mult #'*
:sub #'-
:negate #'-
:psqrt #'(lambda (s) (let ((x))
(cond ((>= s 0)
(setq x (isqrt (numerator s)))
(setq x (/ x (isqrt (denominator s))))
(if (= s (* x x)) x nil))
(t nil))))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (= s 0))
:adjoint #'cl:identity
:mring-to-maxima #'(lambda (s) (simplify `((rat) ,(numerator s) ,(denominator s))))
:maxima-to-mring
#'(lambda (s)
(if (or (floatp s) ($bfloatp s)) (setq s ($rationalize s)))
(if ($ratnump s) (if (integerp s) s (/ ($num s) ($denom s)))
(merror "Unable to convert ~:M to a rational number" s)))))
(setf (get '$rationalfield 'ring) *rationalfield*)
(defparameter *crering*
(make-mring
:name '$crering
:coerce-to-lisp-float nil
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'(lambda (a b) (declare (ignore a)) (eq t (meqp b 0)))
:add #'add
:div #'div
:rdiv #'div
:reciprocal #'(lambda (s) (div 1 s))
:mult #'mult
:sub #'sub
:negate #'(lambda (s) (mult -1 s))
:psqrt #'(lambda (s) (if (member (csign ($ratdisrep s)) `($pos $pz $zero)) (take '(%sqrt) s) nil))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (eq t (meqp s 0)))
:adjoint #'(lambda (s) (take '($conjugate) s))
:mring-to-maxima #'(lambda (s) s)
:maxima-to-mring #'(lambda (s) ($rat s))))
(setf (get '$crering 'ring) *crering*)
(defparameter *generalring*
(make-mring
:name '$generalring
:coerce-to-lisp-float nil
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'(lambda (a b) (declare (ignore a)) (eq t (meqp b 0)))
:add #'(lambda (a b) (add a b))
:div #'(lambda (a b) (div a b))
:rdiv #'(lambda (a b) (div a b))
:reciprocal #'(lambda (s) (div 1 s))
:mult #'(lambda (a b) (mult a b))
:sub #'(lambda (a b) (sub a b))
:negate #'(lambda (a) (mult -1 a))
:psqrt #'(lambda (s) (if (member (csign s) `($pos $pz $zero)) (take '(%sqrt) s) nil))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (eq t (meqp (sratsimp s) 0)))
:adjoint #'(lambda (s) (take '($conjugate) s))
:mring-to-maxima #'(lambda (s) s)
:maxima-to-mring #'(lambda (s) s)))
(setf (get '$generalring 'ring) *generalring*)
(defparameter *bigfloatfield*
(make-mring
:name '$bigfloatfield
:coerce-to-lisp-float #'(lambda (s)
(setq s ($rectform ($float s)))
(complex ($realpart s) ($imagpart s)))
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'mgrp
:add #'(lambda (a b) ($rectform (add a b)))
:div #'(lambda (a b) ($rectform (div a b)))
:rdiv #'(lambda (a b) ($rectform (div a b)))
:reciprocal #'(lambda (s) (div 1 s))
:mult #'(lambda (a b) ($rectform (mult a b)))
:sub #'(lambda (a b) ($rectform (sub a b)))
:negate #'(lambda (a) (mult -1 a))
:psqrt #'(lambda (s) (if (mlsp s 0) nil (take '(%sqrt) s)))
:add-id #'(lambda () bigfloatzero)
:mult-id #'(lambda () bigfloatone)
:fzerop #'(lambda (s) (like s bigfloatzero))
:adjoint #'cl:identity
:mring-to-maxima #'(lambda (s) s)
:maxima-to-mring #'(lambda (s)
(setq s ($rectform ($bfloat s)))
(if (or (eq s '$%i) (complex-number-p s 'bigfloat-or-number-p)) s
(merror "Unable to convert matrix entry to a big float")))))
(setf (get '$bigfloatfield 'ring) *bigfloatfield*)
(defparameter *gf-coeff-ring*
(make-mring
:name 'gf-coeff-ring
:coerce-to-lisp-float nil
:abs #'gf-cmod
:great #'(lambda (a b) (declare (ignore a)) (null b))
:add #'gf-cplus-b
:div #'(lambda (a b) (gf-ctimes a (gf-cinv b)))
:rdiv #'(lambda (a b) (gf-ctimes a (gf-cinv b)))
:reciprocal #'gf-cinv
:mult #'gf-ctimes
:sub #'(lambda (a b) (gf-cplus-b a (gf-cminus-b b)))
:negate #'gf-cminus-b
:psqrt #'(lambda (a) (let ((rs (zn-nrt a 2 *gf-char*))) (when rs (car rs))))
:add-id #'(lambda () 0)
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (= 0 s))
:adjoint nil
:mring-to-maxima #'cl:identity
:maxima-to-mring #'cl:identity ))
(setf (get 'gf-coeff-ring 'ring) *gf-coeff-ring*)
(defparameter *gf-ring*
(make-mring
:name 'gf-ring
:coerce-to-lisp-float nil
:abs #'gf-mod
:great #'(lambda (a b) (declare (ignore a)) (null b))
:add #'gf-plus
:div #'(lambda (a b) (gf-times a (gf-inv b *gf-red*) *gf-red*))
:rdiv #'(lambda (a b) (gf-times a (gf-inv b *gf-red*) *gf-red*))
:reciprocal #'(lambda (a) (gf-inv a *gf-red*))
:mult #'(lambda (a b) (gf-times a b *gf-red*))
:sub #'(lambda (a b) (gf-plus a (gf-minus b)))
:negate #'gf-minus
:psqrt #'(lambda (a)
(let ((rs (gf-nrt-exit (gf-nrt a 2 *gf-red* *gf-ord*))))
(when rs (cadr rs)) ))
:add-id #'(lambda () nil)
:mult-id #'(lambda () '(0 1))
:fzerop #'(lambda (s) (null s))
:adjoint nil
:mring-to-maxima #'gf-x2p
:maxima-to-mring #'gf-p2x ))
(setf (get 'gf-ring 'ring) *gf-ring*)
(defparameter *ef-ring*
(make-mring
:name 'ef-ring
:coerce-to-lisp-float nil
:abs #'gf-mod
:great #'(lambda (a b) (declare (ignore a)) (null b))
:add #'gf-plus
:div #'(lambda (a b) (gf-times a (gf-inv b *ef-red*) *ef-red*))
:rdiv #'(lambda (a b) (gf-times a (gf-inv b *ef-red*) *ef-red*))
:reciprocal #'(lambda (a) (gf-inv a *ef-red*))
:mult #'(lambda (a b) (gf-times a b *ef-red*))
:sub #'(lambda (a b) (gf-plus a (gf-minus b)))
:negate #'gf-minus
:psqrt #'(lambda (a)
(let ((rs (gf-nrt-exit (gf-nrt a 2 *ef-red* *ef-ord*))))
(when rs (cadr rs)) ))
:add-id #'(lambda () nil)
:mult-id #'(lambda () '(0 1))
:fzerop #'(lambda (s) (null s))
:adjoint nil
:mring-to-maxima #'gf-x2p
:maxima-to-mring #'gf-p2x ))
(setf (get 'ef-ring 'ring) *ef-ring*)
(defun fp-abs (a)
(list (abs (first a)) (second a)))
(defun fp+ (a b)
(cond ((= (first a) 0.0) b)
((= (first b) 0.0) a)
(t
(let ((s (+ (first a) (first b))))
(if (= 0.0 s) (merror "floating point divide by zero"))
(list s (ceiling (+ 1
(abs (/ (* (first a) (second a)) s))
(abs (/ (* (first b) (second b)) s)))))))))
(defun fp- (a b)
(cond ((= (first a) 0.0) (list (- (first b)) (second b)))
((= (first b) 0.0) a)
(t
(let ((s (- (first a) (first b))))
(if (= 0.0 s) (merror "floating point divide by zero"))
(list s (ceiling (+ 1
(abs (/ (* (first a) (second a)) s))
(abs (/ (* (first b) (second b)) s)))))))))
(defun fp* (a b)
(if (or (= (first a) 0.0) (= (first b) 0.0)) (list 0.0 0)
(list (* (first a) (first b)) (+ 1 (second a) (second b)))))
(defun fp/ (a b)
(if (= (first a) 0) (list 0.0 0)
(list (/ (first a) (first b)) (+ 1 (second a) (second b)))))
(defun $addmatrices(fn &rest m)
(mfuncall '$apply '$matrixmap `((mlist) ,fn ,@m)))
(defparameter *runningerror*
(make-mring
:name '$runningerror
:coerce-to-lisp-float #'(lambda (s) (if (consp s) (first s) s))
:abs #'fp-abs
:great #'(lambda (a b) (> (first a) (first b)))
:add #'fp+
:div #'fp/
:rdiv #'fp/
:reciprocal #'(lambda (s) (fp/ (list 1 0) s))
:mult #'fp*
:sub #'fp-
:negate #'(lambda (s) (list (- (first s)) (second s)))
:psqrt #'(lambda (s) (if (> (first s) 0) (list (cl:sqrt (first s)) (+ 1 (second s))) nil))
:add-id #'(lambda () (list 0 0))
:mult-id #'(lambda () (list 1 0))
:fzerop #'(lambda (s) (like (first s) 0))
:adjoint #'cl:identity
:mring-to-maxima #'(lambda (s) `((mlist) ,@s))
:maxima-to-mring #'(lambda (s) (if ($listp s) (cdr s) (list ($float s) 1)))))
(setf (get '$runningerror 'ring) *runningerror*)
(defparameter *noncommutingring*
(make-mring
:name '$noncommutingring
:coerce-to-lisp-float nil
:abs #'(lambda (s) (simplify (mfuncall '$cabs s)))
:great #'(lambda (a b) (declare (ignore a)) (eq t (meqp b 0)))
:add #'(lambda (a b) (add a b))
:div #'(lambda (a b) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(setq b (if ($matrixp b) ($invert_by_lu b '$noncommutingring)
(take '(mncexpt) b -1)))
(take '(mnctimes) a b))))
:rdiv #'(lambda (a b) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(setq b (if ($matrixp b) ($invert_by_lu b '$noncommutingring)
(take '(mncexpt) b -1)))
(take '(mnctimes) b a))))
:reciprocal #'(lambda (s) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(if ($matrixp s) ($invert_by_lu s '$noncommutingring)
(take '(mncexpt) s -1)))))
:mult #'(lambda (a b) (progn
(let (($matrix_element_mult ".")
($matrix_element_transpose '$transpose))
(take '(mnctimes) a b))))
:sub #'(lambda (a b) (sub a b))
:negate #'(lambda (a) (mult -1 a))
:add-id #'(lambda () 0)
:psqrt #'(lambda (s) (take '(%sqrt) s))
:mult-id #'(lambda () 1)
:fzerop #'(lambda (s) (eq t (meqp s 0)))
:adjoint #'(lambda (s) ($transpose (take '($conjugate) s)))
:mring-to-maxima #'cl:identity
:maxima-to-mring #'cl:identity))
(setf (get '$noncommutingring 'ring) *noncommutingring*)
(defun ring-eval (e fld)
(let ((fadd (mring-add fld))
(fnegate (mring-negate fld))
(fmult (mring-mult fld))
(fdiv (mring-div fld))
(fabs (mring-abs fld))
(fconvert (mring-maxima-to-mring fld)))
(cond ((or ($numberp e) (symbolp e))
(funcall fconvert (meval e)))
((op-equalp e 'mplus)
(reduce fadd (mapcar #'(lambda (s) (ring-eval s fld)) (margs e)) :from-end t))
((op-equalp e 'mminus)
(funcall fnegate (ring-eval (first (margs e)) fld)))
((op-equalp e 'mtimes)
(reduce fmult (mapcar #'(lambda (s) (ring-eval s fld)) (margs e)) :from-end t))
((op-equalp e 'mquotient)
(funcall fdiv (ring-eval (first (margs e)) fld)(ring-eval (second (margs e)) fld)))
((op-equalp e 'mabs) (funcall fabs (ring-eval (first (margs e)) fld)))
((and (or (eq (mring-name fld) '$floatfield) (eq (mring-name fld) '$complexfield))
(consp e) (consp (car e)) (gethash (mop e) *flonum-op*))
(apply (gethash (mop e) *flonum-op*) (mapcar #'(lambda (s) (ring-eval s fld)) (margs e))))
(t (merror "Unable to evaluate ~:M in the ring '~:M'" e (mring-name fld))))))
(defmspec $ringeval (e)
(let ((fld (get (or (car (member (nth 2 e) $%mrings)) '$generalring) 'ring)))
(funcall (mring-mring-to-maxima fld) (ring-eval (nth 1 e) fld))))
|
52a34dfa9c22ca4094b957b885402766eeac48f674df89e1a702c9473ae49f4c | gebi/jungerl | etest.erl | %%% File : test.erl
%%% Author : <>
%%% Description : small eintl test
Created : 9 Sep 2003 by < >
-module(etest).
-compile(export_all).
-include("../include/eintl.hrl").
-import(eintl, [gettext/1, dcgettext/3]).
start() ->
start("sv_SE").
start(Locale) ->
LocaleDir = filename:join([code:lib_dir(intl), "test", "locale"]),
eintl:start(),
eintl:setlocale(messages, Locale),
eintl:bindtextdomain("test", LocaleDir),
eintl:textdomain("test"),
eintl:bind_textdomain_codeset("test", "ISO-8859-1"),
ok.
t1() ->
io:format(?_("Hello world\n"), []),
io:format(?_("Bend over\n"), []),
io:format(?N_("This is translated later\n"), []).
t2() ->
io:put_chars(eintl:gettext("You got mail\n")),
io:put_chars(eintl:ngettext("You got one mail\n", "You got mail\n",
15)),
io:put_chars(eintl:dgettext("test", "You got virus\n")),
io:put_chars(eintl:dngettext("test", "You got one virus\n",
"You got plenty of viruses\n",
20)),
io:format(eintl:dcgettext("test", "You got a ~w coin\n",messages),
[40]),
io:format(eintl:dcngettext("test", "You got a ~w coin\n",
"You got tons of ~w\n", 30, messages),
[1000]).
t3() ->
io:put_chars(gettext("You got mail\n")),
io:format(dcgettext("test", "You got a ~w coin\n",messages),
[40]).
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/intl/test/etest.erl | erlang | File : test.erl
Author : <>
Description : small eintl test | Created : 9 Sep 2003 by < >
-module(etest).
-compile(export_all).
-include("../include/eintl.hrl").
-import(eintl, [gettext/1, dcgettext/3]).
start() ->
start("sv_SE").
start(Locale) ->
LocaleDir = filename:join([code:lib_dir(intl), "test", "locale"]),
eintl:start(),
eintl:setlocale(messages, Locale),
eintl:bindtextdomain("test", LocaleDir),
eintl:textdomain("test"),
eintl:bind_textdomain_codeset("test", "ISO-8859-1"),
ok.
t1() ->
io:format(?_("Hello world\n"), []),
io:format(?_("Bend over\n"), []),
io:format(?N_("This is translated later\n"), []).
t2() ->
io:put_chars(eintl:gettext("You got mail\n")),
io:put_chars(eintl:ngettext("You got one mail\n", "You got mail\n",
15)),
io:put_chars(eintl:dgettext("test", "You got virus\n")),
io:put_chars(eintl:dngettext("test", "You got one virus\n",
"You got plenty of viruses\n",
20)),
io:format(eintl:dcgettext("test", "You got a ~w coin\n",messages),
[40]),
io:format(eintl:dcngettext("test", "You got a ~w coin\n",
"You got tons of ~w\n", 30, messages),
[1000]).
t3() ->
io:put_chars(gettext("You got mail\n")),
io:format(dcgettext("test", "You got a ~w coin\n",messages),
[40]).
|
1a1cec50f68267969a43aeba36161452092215fa350c7fc74550df8608323a7e | witan-org/witan | test.ml | (*************************************************************************)
This file is part of Witan .
(* *)
Copyright ( C ) 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
( Institut National de Recherche en Informatique et en
(* Automatique) *)
CNRS ( Centre national de la recherche scientifique )
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It 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. *)
(* *)
(* See the GNU Lesser General Public License version 2.1 *)
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(*************************************************************************)
let () =
(* let solver = Witan_core.Egraph.new_t () in *)
let d = Witan_core . Egraph .
(* Witan_theories_bool.Bool.th_register solver; *)
Format.printf "All tests OK ! (total: 0)@."
| null | https://raw.githubusercontent.com/witan-org/witan/d26f9f810fc34bf44daccb91f71ad3258eb62037/src/tests/test.ml | ocaml | ***********************************************************************
alternatives)
Automatique)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
See the GNU Lesser General Public License version 2.1
***********************************************************************
let solver = Witan_core.Egraph.new_t () in
Witan_theories_bool.Bool.th_register solver; | This file is part of Witan .
Copyright ( C ) 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
( Institut National de Recherche en Informatique et en
CNRS ( Centre national de la recherche scientifique )
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
let () =
let d = Witan_core . Egraph .
Format.printf "All tests OK ! (total: 0)@."
|
a7577dafd4164b1e4fed986602aa281e776c95c58b21cc02afa7da54aade8108 | tolysz/ghcjs-stack | InstalledPackageInfo.hs | # LANGUAGE DeriveGeneric #
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.InstalledPackageInfo
Copyright : ( c ) The University of Glasgow 2004
--
-- Maintainer :
-- Portability : portable
--
This is the information about an /installed/ package that
-- is communicated to the @ghc-pkg@ program in order to register
-- a package. @ghc-pkg@ now consumes this package format (as of version
6.4 ) . This is specific to GHC at the moment .
--
-- The @.cabal@ file format is for describing a package that is not yet
-- installed. It has a lot of flexibility, like conditionals and dependency
-- ranges. As such, that format is not at all suitable for describing a package
-- that has already been built and installed. By the time we get to that stage,
-- we have resolved all conditionals and resolved dependency version
-- constraints to exact versions of dependent packages. So, this module defines
-- the 'InstalledPackageInfo' data structure that contains all the info we keep
-- about an installed package. There is a parser and pretty printer. The
-- textual format is rather simpler than the @.cabal@ format: there are no
-- sections, for example.
-- This module is meant to be local-only to Distribution...
module Distribution.InstalledPackageInfo (
InstalledPackageInfo(..),
installedComponentId,
installedPackageId,
OriginalModule(..), ExposedModule(..),
ParseResult(..), PError(..), PWarning,
emptyInstalledPackageInfo,
parseInstalledPackageInfo,
showInstalledPackageInfo,
showInstalledPackageInfoField,
showSimpleInstalledPackageInfoField,
fieldsInstalledPackageInfo,
) where
import Distribution.ParseUtils
import Distribution.License
import Distribution.Package hiding (installedUnitId, installedPackageId)
import qualified Distribution.Package as Package
import Distribution.ModuleName
import Distribution.Version
import Distribution.Text
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.Binary
import Text.PrettyPrint as Disp
import Data.Maybe (fromMaybe)
import GHC.Generics (Generic)
-- -----------------------------------------------------------------------------
-- The InstalledPackageInfo type
For BC reasons , we continue to name this record an InstalledPackageInfo ;
-- but it would more accurately be called an InstalledUnitInfo with Backpack
data InstalledPackageInfo
= InstalledPackageInfo {
-- these parts are exactly the same as PackageDescription
sourcePackageId :: PackageId,
installedUnitId :: UnitId,
compatPackageKey :: String,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
synopsis :: String,
description :: String,
category :: String,
-- these parts are required by an installed package only:
abiHash :: AbiHash,
exposed :: Bool,
exposedModules :: [ExposedModule],
hiddenModules :: [ModuleName],
trusted :: Bool,
importDirs :: [FilePath],
libraryDirs :: [FilePath],
dataDir :: FilePath,
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries:: [String], -- overrides extraLibraries for GHCi
includeDirs :: [FilePath],
includes :: [String],
depends :: [UnitId],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath],
pkgRoot :: Maybe FilePath
}
deriving (Eq, Generic, Read, Show)
installedComponentId :: InstalledPackageInfo -> ComponentId
installedComponentId ipi = case installedUnitId ipi of
SimpleUnitId cid -> cid
{-# DEPRECATED installedPackageId "Use installedUnitId instead" #-}
| Backwards compatibility with Cabal pre-1.24 .
installedPackageId :: InstalledPackageInfo -> UnitId
installedPackageId = installedUnitId
instance Binary InstalledPackageInfo
instance Package.Package InstalledPackageInfo where
packageId = sourcePackageId
instance Package.HasUnitId InstalledPackageInfo where
installedUnitId = installedUnitId
instance Package.PackageInstalled InstalledPackageInfo where
installedDepends = depends
emptyInstalledPackageInfo :: InstalledPackageInfo
emptyInstalledPackageInfo
= InstalledPackageInfo {
sourcePackageId = PackageIdentifier (PackageName "") (Version [] []),
installedUnitId = mkUnitId "",
compatPackageKey = "",
license = UnspecifiedLicense,
copyright = "",
maintainer = "",
author = "",
stability = "",
homepage = "",
pkgUrl = "",
synopsis = "",
description = "",
category = "",
abiHash = AbiHash "",
exposed = False,
exposedModules = [],
hiddenModules = [],
trusted = False,
importDirs = [],
libraryDirs = [],
dataDir = "",
hsLibraries = [],
extraLibraries = [],
extraGHCiLibraries= [],
includeDirs = [],
includes = [],
depends = [],
ccOptions = [],
ldOptions = [],
frameworkDirs = [],
frameworks = [],
haddockInterfaces = [],
haddockHTMLs = [],
pkgRoot = Nothing
}
-- -----------------------------------------------------------------------------
-- Exposed modules
data OriginalModule
= OriginalModule {
originalPackageId :: UnitId,
originalModuleName :: ModuleName
}
deriving (Generic, Eq, Read, Show)
data ExposedModule
= ExposedModule {
exposedName :: ModuleName,
exposedReexport :: Maybe OriginalModule
}
deriving (Eq, Generic, Read, Show)
instance Text OriginalModule where
disp (OriginalModule ipi m) =
disp ipi <> Disp.char ':' <> disp m
parse = do
ipi <- parse
_ <- Parse.char ':'
m <- parse
return (OriginalModule ipi m)
instance Text ExposedModule where
disp (ExposedModule m reexport) =
Disp.sep [ disp m
, case reexport of
Just m' -> Disp.sep [Disp.text "from", disp m']
Nothing -> Disp.empty
]
parse = do
m <- parseModuleNameQ
Parse.skipSpaces
reexport <- Parse.option Nothing $ do
_ <- Parse.string "from"
Parse.skipSpaces
fmap Just parse
return (ExposedModule m reexport)
instance Binary OriginalModule
instance Binary ExposedModule
-- To maintain backwards-compatibility, we accept both comma/non-comma
-- separated variants of this field. You SHOULD use the comma syntax if you
-- use any new functions, although actually it's unambiguous due to a quirk
-- of the fact that modules must start with capital letters.
showExposedModules :: [ExposedModule] -> Disp.Doc
showExposedModules xs
| all isExposedModule xs = fsep (map disp xs)
| otherwise = fsep (Disp.punctuate comma (map disp xs))
where isExposedModule (ExposedModule _ Nothing) = True
isExposedModule _ = False
parseExposedModules :: Parse.ReadP r [ExposedModule]
parseExposedModules = parseOptCommaList parse
-- -----------------------------------------------------------------------------
-- Parsing
parseInstalledPackageInfo :: String -> ParseResult InstalledPackageInfo
parseInstalledPackageInfo =
parseFieldsFlat (fieldsInstalledPackageInfo ++ deprecatedFieldDescrs)
emptyInstalledPackageInfo
-- -----------------------------------------------------------------------------
-- Pretty-printing
showInstalledPackageInfo :: InstalledPackageInfo -> String
showInstalledPackageInfo = showFields fieldsInstalledPackageInfo
showInstalledPackageInfoField :: String -> Maybe (InstalledPackageInfo -> String)
showInstalledPackageInfoField = showSingleNamedField fieldsInstalledPackageInfo
showSimpleInstalledPackageInfoField :: String -> Maybe (InstalledPackageInfo -> String)
showSimpleInstalledPackageInfoField = showSimpleSingleNamedField fieldsInstalledPackageInfo
-- -----------------------------------------------------------------------------
-- Description of the fields, for parsing/printing
fieldsInstalledPackageInfo :: [FieldDescr InstalledPackageInfo]
fieldsInstalledPackageInfo = basicFieldDescrs ++ installedFieldDescrs
basicFieldDescrs :: [FieldDescr InstalledPackageInfo]
basicFieldDescrs =
[ simpleField "name"
disp parsePackageNameQ
packageName (\name pkg -> pkg{sourcePackageId=(sourcePackageId pkg){pkgName=name}})
, simpleField "version"
disp parseOptVersion
packageVersion (\ver pkg -> pkg{sourcePackageId=(sourcePackageId pkg){pkgVersion=ver}})
, simpleField "id"
disp parse
installedUnitId (\pk pkg -> pkg{installedUnitId=pk})
NB : parse these as component IDs
, simpleField "key"
(disp . ComponentId) (fmap (\(ComponentId s) -> s) parse)
compatPackageKey (\pk pkg -> pkg{compatPackageKey=pk})
, simpleField "license"
disp parseLicenseQ
license (\l pkg -> pkg{license=l})
, simpleField "copyright"
showFreeText parseFreeText
copyright (\val pkg -> pkg{copyright=val})
, simpleField "maintainer"
showFreeText parseFreeText
maintainer (\val pkg -> pkg{maintainer=val})
, simpleField "stability"
showFreeText parseFreeText
stability (\val pkg -> pkg{stability=val})
, simpleField "homepage"
showFreeText parseFreeText
homepage (\val pkg -> pkg{homepage=val})
, simpleField "package-url"
showFreeText parseFreeText
pkgUrl (\val pkg -> pkg{pkgUrl=val})
, simpleField "synopsis"
showFreeText parseFreeText
synopsis (\val pkg -> pkg{synopsis=val})
, simpleField "description"
showFreeText parseFreeText
description (\val pkg -> pkg{description=val})
, simpleField "category"
showFreeText parseFreeText
category (\val pkg -> pkg{category=val})
, simpleField "author"
showFreeText parseFreeText
author (\val pkg -> pkg{author=val})
]
installedFieldDescrs :: [FieldDescr InstalledPackageInfo]
installedFieldDescrs = [
boolField "exposed"
exposed (\val pkg -> pkg{exposed=val})
, simpleField "exposed-modules"
showExposedModules parseExposedModules
exposedModules (\xs pkg -> pkg{exposedModules=xs})
, listField "hidden-modules"
disp parseModuleNameQ
hiddenModules (\xs pkg -> pkg{hiddenModules=xs})
, simpleField "abi"
disp parse
abiHash (\abi pkg -> pkg{abiHash=abi})
, boolField "trusted"
trusted (\val pkg -> pkg{trusted=val})
, listField "import-dirs"
showFilePath parseFilePathQ
importDirs (\xs pkg -> pkg{importDirs=xs})
, listField "library-dirs"
showFilePath parseFilePathQ
libraryDirs (\xs pkg -> pkg{libraryDirs=xs})
, simpleField "data-dir"
showFilePath (parseFilePathQ Parse.<++ return "")
dataDir (\val pkg -> pkg{dataDir=val})
, listField "hs-libraries"
showFilePath parseTokenQ
hsLibraries (\xs pkg -> pkg{hsLibraries=xs})
, listField "extra-libraries"
showToken parseTokenQ
extraLibraries (\xs pkg -> pkg{extraLibraries=xs})
, listField "extra-ghci-libraries"
showToken parseTokenQ
extraGHCiLibraries (\xs pkg -> pkg{extraGHCiLibraries=xs})
, listField "include-dirs"
showFilePath parseFilePathQ
includeDirs (\xs pkg -> pkg{includeDirs=xs})
, listField "includes"
showFilePath parseFilePathQ
includes (\xs pkg -> pkg{includes=xs})
, listField "depends"
disp parse
depends (\xs pkg -> pkg{depends=xs})
, listField "cc-options"
showToken parseTokenQ
ccOptions (\path pkg -> pkg{ccOptions=path})
, listField "ld-options"
showToken parseTokenQ
ldOptions (\path pkg -> pkg{ldOptions=path})
, listField "framework-dirs"
showFilePath parseFilePathQ
frameworkDirs (\xs pkg -> pkg{frameworkDirs=xs})
, listField "frameworks"
showToken parseTokenQ
frameworks (\xs pkg -> pkg{frameworks=xs})
, listField "haddock-interfaces"
showFilePath parseFilePathQ
haddockInterfaces (\xs pkg -> pkg{haddockInterfaces=xs})
, listField "haddock-html"
showFilePath parseFilePathQ
haddockHTMLs (\xs pkg -> pkg{haddockHTMLs=xs})
, simpleField "pkgroot"
(const Disp.empty) parseFilePathQ
(fromMaybe "" . pkgRoot) (\xs pkg -> pkg{pkgRoot=Just xs})
]
deprecatedFieldDescrs :: [FieldDescr InstalledPackageInfo]
deprecatedFieldDescrs = [
listField "hugs-options"
showToken parseTokenQ
(const []) (const id)
]
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal-next/Cabal/Distribution/InstalledPackageInfo.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.InstalledPackageInfo
Maintainer :
Portability : portable
is communicated to the @ghc-pkg@ program in order to register
a package. @ghc-pkg@ now consumes this package format (as of version
The @.cabal@ file format is for describing a package that is not yet
installed. It has a lot of flexibility, like conditionals and dependency
ranges. As such, that format is not at all suitable for describing a package
that has already been built and installed. By the time we get to that stage,
we have resolved all conditionals and resolved dependency version
constraints to exact versions of dependent packages. So, this module defines
the 'InstalledPackageInfo' data structure that contains all the info we keep
about an installed package. There is a parser and pretty printer. The
textual format is rather simpler than the @.cabal@ format: there are no
sections, for example.
This module is meant to be local-only to Distribution...
-----------------------------------------------------------------------------
The InstalledPackageInfo type
but it would more accurately be called an InstalledUnitInfo with Backpack
these parts are exactly the same as PackageDescription
these parts are required by an installed package only:
overrides extraLibraries for GHCi
# DEPRECATED installedPackageId "Use installedUnitId instead" #
-----------------------------------------------------------------------------
Exposed modules
To maintain backwards-compatibility, we accept both comma/non-comma
separated variants of this field. You SHOULD use the comma syntax if you
use any new functions, although actually it's unambiguous due to a quirk
of the fact that modules must start with capital letters.
-----------------------------------------------------------------------------
Parsing
-----------------------------------------------------------------------------
Pretty-printing
-----------------------------------------------------------------------------
Description of the fields, for parsing/printing | # LANGUAGE DeriveGeneric #
Copyright : ( c ) The University of Glasgow 2004
This is the information about an /installed/ package that
6.4 ) . This is specific to GHC at the moment .
module Distribution.InstalledPackageInfo (
InstalledPackageInfo(..),
installedComponentId,
installedPackageId,
OriginalModule(..), ExposedModule(..),
ParseResult(..), PError(..), PWarning,
emptyInstalledPackageInfo,
parseInstalledPackageInfo,
showInstalledPackageInfo,
showInstalledPackageInfoField,
showSimpleInstalledPackageInfoField,
fieldsInstalledPackageInfo,
) where
import Distribution.ParseUtils
import Distribution.License
import Distribution.Package hiding (installedUnitId, installedPackageId)
import qualified Distribution.Package as Package
import Distribution.ModuleName
import Distribution.Version
import Distribution.Text
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.Binary
import Text.PrettyPrint as Disp
import Data.Maybe (fromMaybe)
import GHC.Generics (Generic)
For BC reasons , we continue to name this record an InstalledPackageInfo ;
data InstalledPackageInfo
= InstalledPackageInfo {
sourcePackageId :: PackageId,
installedUnitId :: UnitId,
compatPackageKey :: String,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
synopsis :: String,
description :: String,
category :: String,
abiHash :: AbiHash,
exposed :: Bool,
exposedModules :: [ExposedModule],
hiddenModules :: [ModuleName],
trusted :: Bool,
importDirs :: [FilePath],
libraryDirs :: [FilePath],
dataDir :: FilePath,
hsLibraries :: [String],
extraLibraries :: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [UnitId],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath],
pkgRoot :: Maybe FilePath
}
deriving (Eq, Generic, Read, Show)
installedComponentId :: InstalledPackageInfo -> ComponentId
installedComponentId ipi = case installedUnitId ipi of
SimpleUnitId cid -> cid
| Backwards compatibility with Cabal pre-1.24 .
installedPackageId :: InstalledPackageInfo -> UnitId
installedPackageId = installedUnitId
instance Binary InstalledPackageInfo
instance Package.Package InstalledPackageInfo where
packageId = sourcePackageId
instance Package.HasUnitId InstalledPackageInfo where
installedUnitId = installedUnitId
instance Package.PackageInstalled InstalledPackageInfo where
installedDepends = depends
emptyInstalledPackageInfo :: InstalledPackageInfo
emptyInstalledPackageInfo
= InstalledPackageInfo {
sourcePackageId = PackageIdentifier (PackageName "") (Version [] []),
installedUnitId = mkUnitId "",
compatPackageKey = "",
license = UnspecifiedLicense,
copyright = "",
maintainer = "",
author = "",
stability = "",
homepage = "",
pkgUrl = "",
synopsis = "",
description = "",
category = "",
abiHash = AbiHash "",
exposed = False,
exposedModules = [],
hiddenModules = [],
trusted = False,
importDirs = [],
libraryDirs = [],
dataDir = "",
hsLibraries = [],
extraLibraries = [],
extraGHCiLibraries= [],
includeDirs = [],
includes = [],
depends = [],
ccOptions = [],
ldOptions = [],
frameworkDirs = [],
frameworks = [],
haddockInterfaces = [],
haddockHTMLs = [],
pkgRoot = Nothing
}
data OriginalModule
= OriginalModule {
originalPackageId :: UnitId,
originalModuleName :: ModuleName
}
deriving (Generic, Eq, Read, Show)
data ExposedModule
= ExposedModule {
exposedName :: ModuleName,
exposedReexport :: Maybe OriginalModule
}
deriving (Eq, Generic, Read, Show)
instance Text OriginalModule where
disp (OriginalModule ipi m) =
disp ipi <> Disp.char ':' <> disp m
parse = do
ipi <- parse
_ <- Parse.char ':'
m <- parse
return (OriginalModule ipi m)
instance Text ExposedModule where
disp (ExposedModule m reexport) =
Disp.sep [ disp m
, case reexport of
Just m' -> Disp.sep [Disp.text "from", disp m']
Nothing -> Disp.empty
]
parse = do
m <- parseModuleNameQ
Parse.skipSpaces
reexport <- Parse.option Nothing $ do
_ <- Parse.string "from"
Parse.skipSpaces
fmap Just parse
return (ExposedModule m reexport)
instance Binary OriginalModule
instance Binary ExposedModule
showExposedModules :: [ExposedModule] -> Disp.Doc
showExposedModules xs
| all isExposedModule xs = fsep (map disp xs)
| otherwise = fsep (Disp.punctuate comma (map disp xs))
where isExposedModule (ExposedModule _ Nothing) = True
isExposedModule _ = False
parseExposedModules :: Parse.ReadP r [ExposedModule]
parseExposedModules = parseOptCommaList parse
parseInstalledPackageInfo :: String -> ParseResult InstalledPackageInfo
parseInstalledPackageInfo =
parseFieldsFlat (fieldsInstalledPackageInfo ++ deprecatedFieldDescrs)
emptyInstalledPackageInfo
showInstalledPackageInfo :: InstalledPackageInfo -> String
showInstalledPackageInfo = showFields fieldsInstalledPackageInfo
showInstalledPackageInfoField :: String -> Maybe (InstalledPackageInfo -> String)
showInstalledPackageInfoField = showSingleNamedField fieldsInstalledPackageInfo
showSimpleInstalledPackageInfoField :: String -> Maybe (InstalledPackageInfo -> String)
showSimpleInstalledPackageInfoField = showSimpleSingleNamedField fieldsInstalledPackageInfo
fieldsInstalledPackageInfo :: [FieldDescr InstalledPackageInfo]
fieldsInstalledPackageInfo = basicFieldDescrs ++ installedFieldDescrs
basicFieldDescrs :: [FieldDescr InstalledPackageInfo]
basicFieldDescrs =
[ simpleField "name"
disp parsePackageNameQ
packageName (\name pkg -> pkg{sourcePackageId=(sourcePackageId pkg){pkgName=name}})
, simpleField "version"
disp parseOptVersion
packageVersion (\ver pkg -> pkg{sourcePackageId=(sourcePackageId pkg){pkgVersion=ver}})
, simpleField "id"
disp parse
installedUnitId (\pk pkg -> pkg{installedUnitId=pk})
NB : parse these as component IDs
, simpleField "key"
(disp . ComponentId) (fmap (\(ComponentId s) -> s) parse)
compatPackageKey (\pk pkg -> pkg{compatPackageKey=pk})
, simpleField "license"
disp parseLicenseQ
license (\l pkg -> pkg{license=l})
, simpleField "copyright"
showFreeText parseFreeText
copyright (\val pkg -> pkg{copyright=val})
, simpleField "maintainer"
showFreeText parseFreeText
maintainer (\val pkg -> pkg{maintainer=val})
, simpleField "stability"
showFreeText parseFreeText
stability (\val pkg -> pkg{stability=val})
, simpleField "homepage"
showFreeText parseFreeText
homepage (\val pkg -> pkg{homepage=val})
, simpleField "package-url"
showFreeText parseFreeText
pkgUrl (\val pkg -> pkg{pkgUrl=val})
, simpleField "synopsis"
showFreeText parseFreeText
synopsis (\val pkg -> pkg{synopsis=val})
, simpleField "description"
showFreeText parseFreeText
description (\val pkg -> pkg{description=val})
, simpleField "category"
showFreeText parseFreeText
category (\val pkg -> pkg{category=val})
, simpleField "author"
showFreeText parseFreeText
author (\val pkg -> pkg{author=val})
]
installedFieldDescrs :: [FieldDescr InstalledPackageInfo]
installedFieldDescrs = [
boolField "exposed"
exposed (\val pkg -> pkg{exposed=val})
, simpleField "exposed-modules"
showExposedModules parseExposedModules
exposedModules (\xs pkg -> pkg{exposedModules=xs})
, listField "hidden-modules"
disp parseModuleNameQ
hiddenModules (\xs pkg -> pkg{hiddenModules=xs})
, simpleField "abi"
disp parse
abiHash (\abi pkg -> pkg{abiHash=abi})
, boolField "trusted"
trusted (\val pkg -> pkg{trusted=val})
, listField "import-dirs"
showFilePath parseFilePathQ
importDirs (\xs pkg -> pkg{importDirs=xs})
, listField "library-dirs"
showFilePath parseFilePathQ
libraryDirs (\xs pkg -> pkg{libraryDirs=xs})
, simpleField "data-dir"
showFilePath (parseFilePathQ Parse.<++ return "")
dataDir (\val pkg -> pkg{dataDir=val})
, listField "hs-libraries"
showFilePath parseTokenQ
hsLibraries (\xs pkg -> pkg{hsLibraries=xs})
, listField "extra-libraries"
showToken parseTokenQ
extraLibraries (\xs pkg -> pkg{extraLibraries=xs})
, listField "extra-ghci-libraries"
showToken parseTokenQ
extraGHCiLibraries (\xs pkg -> pkg{extraGHCiLibraries=xs})
, listField "include-dirs"
showFilePath parseFilePathQ
includeDirs (\xs pkg -> pkg{includeDirs=xs})
, listField "includes"
showFilePath parseFilePathQ
includes (\xs pkg -> pkg{includes=xs})
, listField "depends"
disp parse
depends (\xs pkg -> pkg{depends=xs})
, listField "cc-options"
showToken parseTokenQ
ccOptions (\path pkg -> pkg{ccOptions=path})
, listField "ld-options"
showToken parseTokenQ
ldOptions (\path pkg -> pkg{ldOptions=path})
, listField "framework-dirs"
showFilePath parseFilePathQ
frameworkDirs (\xs pkg -> pkg{frameworkDirs=xs})
, listField "frameworks"
showToken parseTokenQ
frameworks (\xs pkg -> pkg{frameworks=xs})
, listField "haddock-interfaces"
showFilePath parseFilePathQ
haddockInterfaces (\xs pkg -> pkg{haddockInterfaces=xs})
, listField "haddock-html"
showFilePath parseFilePathQ
haddockHTMLs (\xs pkg -> pkg{haddockHTMLs=xs})
, simpleField "pkgroot"
(const Disp.empty) parseFilePathQ
(fromMaybe "" . pkgRoot) (\xs pkg -> pkg{pkgRoot=Just xs})
]
deprecatedFieldDescrs :: [FieldDescr InstalledPackageInfo]
deprecatedFieldDescrs = [
listField "hugs-options"
showToken parseTokenQ
(const []) (const id)
]
|
1e8fb4645e5a48bccae352e7bc99d154cbc20b3ffec189ba7f2cf4a17274e4e2 | google/lisp-koans | multiple-values.lisp | Copyright 2013 Google Inc.
;;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; -2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
In Lisp , it is possible for a function to return more than one value .
;;; This is distinct from returning a list or structure of values.
(define-test multiple-values
(let ((x (floor 3/2))
;; The macro MULTIPLE-VALUE-LIST returns a list of all values returned
;; by a Lisp form.
(y (multiple-value-list (floor 3/2))))
(assert-equal x 1)
(assert-equal y '(1 1/2)))
(assert-equal '(24 3/4) (multiple-value-list (floor 99/4))))
(defun next-fib (a b)
;; The function VALUES allows returning multiple values.
(values b (+ a b)))
(define-test binding-and-setting-multiple-values
;; The macro MULTIPLE-VALUE-BIND is like LET, except it binds the variables
listed in its first argument to the values returned by the form that is its
second argument .
(multiple-value-bind (x y) (next-fib 3 5)
(let ((result (* x y)))
(assert-equal 40 result)))
SETF can also set multiple values if a VALUES form is provided as a place .
(let (x y)
(setf (values x y) (next-fib 5 8))
(assert-equal '(8 13) (list x y))))
| null | https://raw.githubusercontent.com/google/lisp-koans/df5e58dc88429ef0ff202d0b45c21ce572144ba8/koans-solved/multiple-values.lisp | lisp |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This is distinct from returning a list or structure of values.
The macro MULTIPLE-VALUE-LIST returns a list of all values returned
by a Lisp form.
The function VALUES allows returning multiple values.
The macro MULTIPLE-VALUE-BIND is like LET, except it binds the variables | Copyright 2013 Google Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
In Lisp , it is possible for a function to return more than one value .
(define-test multiple-values
(let ((x (floor 3/2))
(y (multiple-value-list (floor 3/2))))
(assert-equal x 1)
(assert-equal y '(1 1/2)))
(assert-equal '(24 3/4) (multiple-value-list (floor 99/4))))
(defun next-fib (a b)
(values b (+ a b)))
(define-test binding-and-setting-multiple-values
listed in its first argument to the values returned by the form that is its
second argument .
(multiple-value-bind (x y) (next-fib 3 5)
(let ((result (* x y)))
(assert-equal 40 result)))
SETF can also set multiple values if a VALUES form is provided as a place .
(let (x y)
(setf (values x y) (next-fib 5 8))
(assert-equal '(8 13) (list x y))))
|
6c18a72da38fcf792b03fd6982647ae921d2236801b78f7d4b2193b98ec23128 | launchdarkly/haskell-server-sdk | DataSource.hs | module Spec.DataSource (allTests) where
import Test.HUnit
allTests :: Test
allTests =
TestList []
| null | https://raw.githubusercontent.com/launchdarkly/haskell-server-sdk/b8642084591733e620dfc5c1598409be7cc40a63/test/Spec/DataSource.hs | haskell | module Spec.DataSource (allTests) where
import Test.HUnit
allTests :: Test
allTests =
TestList []
|
|
d681103a0f6a37affcbf9f2b98aefec530264c327cc66d4c0f556aa988c895e3 | AccelerationNet/collectors | collectors.lisp | ;; -*- lisp -*-
(cl:defpackage :collectors-signals
(:export
;; signals and restarts
#:aggregating #:skip #:new-value #:value #:aggregator #:after-values
#:done-aggregating #:aggregate))
(cl:defpackage :collectors
(:use :cl :cl-user :collectors-signals)
(:export
#:collect-at-end
#:append-at-end
#:make-simple-collector
#:make-simple-appender
#:make-simple-collector-to-place
#:make-simple-appender-to-place
#:with-collector
#:with-collector-output
#:with-collectors
#:make-collector
#:with-alist-output
#:collecting
#:make-pusher
#:with-reducer
#:make-reducer
#:with-appender
#:with-appender-output
#:make-appender
#:appending
#:with-string-builder
#:with-string-builder-output
#:make-string-builder
#:with-mapping-collector
#:with-mapping-appender
#:make-formatter
#:with-formatter
#:with-formatter-output
#:operate
#:deoperate
))
(in-package :collectors)
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-condition collectors-signals:aggregating ()
((collectors-signals:value
:accessor collectors-signals:value
:initarg :value :initform nil)
(collectors-signals:aggregator
:accessor collectors-signals:aggregator
:initarg :aggregator :initform nil)))
(define-condition collectors-signals:done-aggregating ()
((collectors-signals:after-values
:accessor collectors-signals:after-values
:initarg :after-values :initform nil)
(collectors-signals:aggregate
:accessor collectors-signals:aggregate
:initarg :aggregate :initform nil)
(collectors-signals:aggregator
:accessor collectors-signals:aggregator
:initarg :aggregator :initform nil)))
(defmacro with-signal-context ((value after-values aggregator) &body body)
(alexandria:with-unique-names (new-value)
`(with-simple-restart
(collectors-signals:skip "Skip aggregating ~A into ~A" ,value ,aggregator)
(restart-case (signal 'aggregating :value ,value :aggregator ,aggregator)
(collectors-signals:new-value (,new-value)
:report "Aggregate a new value instead"
(setf ,value ,new-value)))
(prog1 (progn ,@body)
(signal 'done-aggregating :after-values ,after-values :aggregator ,aggregator))))))
(defmacro collect-at-end (head-place tail-place values-place)
"Macros to ease efficient collection at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place c)))))
(defmacro collect-at-end-with-signals (head-place tail-place values-place
aggregator-place post-values-place)
"Macros to ease efficient collection at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(with-signal-context (,a ,post-values-place ,aggregator-place)
(let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place c)
)))))
(defmacro append-at-end (head-place tail-place values-place)
"Macros to ease efficient collection (with appending) at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(typecase ,a
(list (collect-at-end ,head-place ,tail-place ,a))
(t (let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place (last c))))))))
(defmacro append-at-end-with-signals (head-place tail-place values-place
aggregator-place post-values-place)
"Macros to ease efficient collection (with appending) at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(with-signal-context (,a ,post-values-place ,aggregator-place)
(typecase ,a
(list (collect-at-end-with-signals
,head-place ,tail-place ,a ,aggregator-place ,post-values-place))
(t (let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place (last c)))))))))
(defmacro make-simple-collector-to-place (place)
(alexandria:with-unique-names (tail)
`(progn
(setf ,place (alexandria:ensure-list ,place))
(let* ((,tail (last ,place)))
(lambda (&rest values)
(collect-at-end ,place ,tail values)
,place)))))
(defun make-simple-collector (&optional initial-value)
"A fastest possible, fewest frills collector suitable to places where efficiency matters"
(let ((head initial-value))
(make-simple-collector-to-place head)))
(defmacro make-simple-appender-to-place (place)
"A fastest possible, fewest frills collector suitable to places where efficiency matters
that appends any values that re lists"
(alexandria:with-unique-names (tail)
`(progn
(setf ,place (alexandria:ensure-list ,place))
(let ((,tail (last ,place)))
(lambda (&rest values)
(append-at-end ,place ,tail values)
,place)))))
(defun make-simple-appender (&optional initial-value)
"A fastest possible, fewest frills collector suitable to places where efficiency matters
that appends any values that re lists"
(let ((head initial-value))
(make-simple-appender-to-place head)))
(defclass value-aggregator (closer-mop:funcallable-standard-object)
((initial-value :accessor initial-value :initarg :initial-value :initform nil)
(place-setter :accessor place-setter :initarg :place-setter :initform nil)
(value :accessor value :initarg :value :initform nil))
(:metaclass closer-mop:funcallable-standard-class))
(defclass list-aggregator (value-aggregator)
((collect-nil? :accessor collect-nil? :initarg :collect-nil? :initform t
:documentation "Should we collect nil into our results")
(new-only-test :accessor new-only-test :initarg :new-only-test :initform nil
:documentation "If supplied with a new-only-test, we will verify that we
have not already collected this item before collecting again")
(new-only-key :accessor new-only-key :initarg :new-only-key :initform nil))
(:metaclass closer-mop:funcallable-standard-class))
(defclass collector (list-aggregator)
((tail :accessor tail :initarg :tail :initform nil))
(:documentation "Create a collector function.
A Collector function will collect, into a list, all the values
passed to it in the order in which they were passed. If the
callector function is called without arguments it returns the
current list of values.")
(:metaclass closer-mop:funcallable-standard-class))
(defclass reducer (value-aggregator)
((operation :accessor operation :initarg :operation :initform nil))
(:metaclass closer-mop:funcallable-standard-class)
(:documentation
"Create a function which, starting with INITIAL-VALUE, reduces
any other values into a single final value.
OPERATION will be called with two values: the current value and
the new value, in that order. OPERATION should return exactly one
value.
The reducing function can be called with n arguments which will
be applied to OPERATION one after the other (left to right) and
will return the new value.
If the reducing function is called with no arguments it will
return the current value.
Example:
(setf r (make-reducer #'+ 5))
(funcall r 0) => 5
(funcall r 1 2) => 8
(funcall r) => 8"))
(defclass pusher (list-aggregator)
()
(:metaclass closer-mop:funcallable-standard-class))
(defclass appender (collector)
()
(:documentation "Create an appender function.
An Appender will append any arguments into a list, all the values
passed to it in the order in which they were passed. If the
appender function is called without arguments it returns the
current list of values.")
(:metaclass closer-mop:funcallable-standard-class))
(defclass string-formatter (value-aggregator)
((delimiter :accessor delimiter :initarg :delimiter :initform nil)
(has-written? :accessor has-written? :initarg :has-written? :initform nil)
(output-stream :accessor output-stream :initarg :output-stream :initform nil)
(pretty? :accessor pretty? :initarg :pretty? :initform nil))
(:metaclass closer-mop:funcallable-standard-class)
(:documentation
"Create a string formatter collector function.
creates a (lambda &optional format-string &rest args) and collects these in a list
When called with no args, returns the concatenated (with delimiter) results
binds *print-pretty* to nil
"))
(defclass string-builder (string-formatter)
((ignore-empty-strings-and-nil?
:accessor ignore-empty-strings-and-nil? :initarg :ignore-empty-strings-and-nil? :initform t))
(:metaclass closer-mop:funcallable-standard-class)
(:documentation
"Create a function that will build up a string for you
Each call to the function with arguments appends those arguments to the string
with an optional delimiter between them.
if ignore-empty-strings-and-nil is true neither empty strings nor nil will be
printed to the stream
A call to the function with no arguments returns the output string"))
;;;; * Reducing and Collecting
;;;; ** Reducing
;; ACL was throwing errors about this not being finalized (seems odd) re github #3
;;
;; Fix it by: -archive.com//msg00169.html
(closer-mop:ensure-finalized (find-class 'closer-mop:standard-object))
(closer-mop:ensure-finalized (find-class 'closer-mop:standard-class))
(closer-mop:ensure-finalized (find-class 'closer-mop:funcallable-standard-object))
(closer-mop:ensure-finalized (find-class 'closer-mop:funcallable-standard-class))
(defmethod initialize-instance :after ((o value-aggregator) &key &allow-other-keys)
(setf (value o) (typecase (initial-value o)
(list (copy-list (initial-value o)))
(t (initial-value o))))
(closer-mop:set-funcallable-instance-function
o (lambda (&rest values) (operate o values))))
(defgeneric should-aggregate? (aggregator value)
(:method ((o value-aggregator) v) (declare (ignore v)) t)
(:documentation "Should we aggregate a given value into our collection"))
(defgeneric deoperate (aggregator values &key test key)
(:documentation "Undo the aggregation operation of an aggregator and list of values")
(:method :after ((o value-aggregator) values &key test key
&aux (value (value o)))
(declare (ignore values test key))
(dolist (ps (alexandria:ensure-list (place-setter o)))
(funcall ps value))))
(defgeneric operate (aggregator values)
(:documentation "Perform the aggregation operation on the aggregator for the values")
(:method :around ((o value-aggregator) values
&aux (places (alexandria:ensure-list (place-setter o))))
(declare (ignore values))
(handler-bind
((aggregating
(lambda (c)
(when (eql o (aggregator c))
(unless (should-aggregate? (aggregator c) (value c))
(invoke-restart 'skip)))))
(done-aggregating
(lambda (c)
(when (eql o (aggregator c))
(dolist (p places)
(funcall p (value o)))))))
(call-next-method)
(value o))))
(defmethod operate ((o reducer) values)
(dolist (v (alexandria:ensure-list values))
(with-signal-context (v (value o) o)
(setf (value o)
(if (value o)
(funcall (operation o) (value o) v)
v)))))
reducing is the act of taking values , two at a time , and
;;;; combining them, with the aid of a reducing function, into a
;;;; single final value.
(defun make-reducer (function &key initial-value place-setter)
(make-instance 'reducer :initial-value initial-value :place-setter place-setter
:operation function))
(defmacro with-reducer ((name function &key (initial-value nil) place)
&body body)
"Locally bind NAME to a reducing function. The arguments
FUNCTION and INITIAL-VALUE are passed directly to MAKE-REDUCER."
(alexandria:with-unique-names (reducer)
`(let ((,reducer (make-reducer ,function
:initial-value (or ,initial-value ,place)
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items) (apply ,reducer items)))
,@body))))
(defmethod should-aggregate? ((o list-aggregator) v)
(and (or (collect-nil? o) v)
(or (null (new-only-test o))
(null (member v (value o)
:test #'new-only-test
:key (or (new-only-key o) #'identity))))))
(defun make-pusher (&key initial-value collect-nil place-setter)
(make-instance
'pusher
:initial-value initial-value
:collect-nil? collect-nil
:place-setter place-setter))
(defmethod %push ((o list-aggregator) values)
(dolist (v (alexandria:ensure-list values))
(with-signal-context (v (value o) o)
(push v (value o))
(when (and (typep o 'collector) (null (tail o)))
(setf (tail o) (value o)))))
(value o))
(defmethod %pop-n ((o list-aggregator) &optional (n 1))
(let* ((head (value o))
(len (length head)))
(cond
((>= n len)
(setf (value o) nil)
(when (typep o 'collector)
(setf (tail o) nil)))
(t (let ((lastcons (nthcdr (- n 1) head)))
(setf (value o) (cdr lastcons)
(cdr lastcons) nil))))
(if (= 1 n)
(car head)
head)))
(defmethod %unenqueue-n ((o list-aggregator) &optional (n 1))
(let* ((head (value o))
(len (length head))
(div (- len (+ 1 n)))
(rtn (cond
((plusp div)
(let* ((c (nthcdr div head))
(rtn (cdr c)))
(setf (cdr c) nil)
(when (typep o 'collector)
(setf (tail o) c))
rtn))
(t
(setf (value o) nil)
(when (typep o 'collector)
(setf (tail o) nil))
head))))
(if (= 1 n)
(car rtn)
rtn)))
(defmethod %enqueue ((o list-aggregator) values
&aux (last (last (value o))))
(collect-at-end-with-signals
(value o) last values o (value o))
(value o))
(defmethod %enqueue ((o collector) values)
(collect-at-end-with-signals
(value o) (tail o) values o (value o))
(value o))
(defmethod operate ((o pusher) values)
(%push o values))
(defmethod initialize-instance :after ((o collector) &key &allow-other-keys)
(setf (tail o) (last (value o))))
(defmethod operate ((o collector) values)
(%enqueue o values))
(defmethod deoperate ((o list-aggregator) to-remove
&key test key
&aux prev)
(setf to-remove (alexandria:ensure-list to-remove))
(loop for cons on (value o)
for (this . next) = cons
do (if (null (member (funcall (or key #'identity) this)
to-remove
:test (or test #'eql)))
;; not to remove
(setf prev cons)
(cond
remove first elt
((null prev)
(setf (value o) next))
;; remove last elt
((null next)
(setf (cdr prev) nil
(tail o) prev))
;; remove from middle of the list
(t (setf (cdr prev) next)))))
(value o))
(defun make-collector (&key initial-value (collect-nil t) place-setter)
;; by using this head cons cell we can simplify the loop body
(make-instance 'collector
:initial-value initial-value :collect-nil? collect-nil
:place-setter place-setter))
(defmethod operate ((o appender) values)
(append-at-end-with-signals (value o) (tail o) values o (values o)))
(defun make-appender (&key initial-value place-setter)
(make-instance 'appender :initial-value initial-value :place-setter place-setter))
(defmacro with-appender ((name &key initial-value place) &body body)
"Bind NAME to a collector function and execute BODY. If
FROM-END is true the collector will actually be a pusher, (see
MAKE-PUSHER), otherwise NAME will be bound to a collector,
(see MAKE-COLLECTOR).
(with-appender (app)
(app '(1 2))
(app '(2 3))
(app '(3 4))
(app)) => (1 2 2 3 3 4)
"
(alexandria:with-unique-names (appender)
`(let ((,appender (make-appender
:initial-value (or ,initial-value ,place)
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items) (apply ,appender items)))
,@body))))
(defmacro with-appender-output ((name &key initial-value place) &body body)
"Same as with-appender, but this form returns the collected values
automatically
"
`(with-appender (,name :initial-value ,initial-value :place ,place)
,@body (,name)))
(defmacro with-collector ((name &key place (collect-nil T) initial-value from-end) &body body)
"Bind NAME to a collector function and execute BODY. If
FROM-END is true the collector will actually be a pusher, (see
MAKE-PUSHER), otherwise NAME will be bound to a collector,
(see MAKE-COLLECTOR).
(with-collector (col)
(col 1)
(col 2)
(col 3)
(col)) => (1 2 3)
"
`(let ((,name (,(if from-end
'make-pusher
'make-collector)
:initial-value (or ,initial-value ,place)
:collect-nil ,collect-nil
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items) (operate ,name items))
(,(symbol-munger:english->lisp-symbol `(push ,name))
(&rest items)
(%push ,name items))
(,(symbol-munger:english->lisp-symbol `(pop ,name))
(&optional (n 1))
(%pop-n ,name n))
(,(symbol-munger:english->lisp-symbol `(enqueue ,name))
(&rest items)
(%enqueue ,name items))
(,(symbol-munger:english->lisp-symbol `(unenqueue ,name))
(&optional (n 1))
(%unenqueue-n ,name n))
)
,@body)))
(defmacro with-collector-output ((name &key (collect-nil t) initial-value from-end place)
&body body)
`(with-collector (,name :collect-nil ,collect-nil
:initial-value ,initial-value
:from-end ,from-end
:place ,place)
,@body
(,name)))
(defmacro with-alist ((name &key place (collect-nil T) initial-value from-end) &body body)
`(let ((,name (,(if from-end
'make-pusher
'make-collector)
:initial-value (or ,initial-value ,place)
:collect-nil ,collect-nil
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items)
(loop for (k v) on items by #'cddr
do (operate ,name (list (cons k v))))
(value ,name)))
,@body)))
(defmacro with-alist-output ((name &key (collect-nil t) initial-value from-end place)
&body body)
`(with-alist (,name :collect-nil ,collect-nil
:initial-value ,initial-value
:from-end ,from-end
:place ,place)
,@body
(,name)))
(defmacro with-collectors (names &body body)
"Bind multiple collectors. Each element of NAMES should be a
list as per WITH-COLLECTOR's first orgument."
(if names
`(with-collector ,(alexandria:ensure-list (car names))
(with-collectors ,(cdr names) ,@body))
`(progn ,@body)))
(defmethod initialize-instance :after ((o string-formatter) &key &allow-other-keys)
(when (and (delimiter o) (not (stringp (delimiter o))))
(setf (delimiter o) (princ-to-string (delimiter o))))
(when (initial-value o)
(setf (has-written? o) t)
(when (output-stream o)
(write-string (initial-value o) (output-stream o)))))
(defmethod operate ((o string-formatter) values)
(setf values (alexandria:ensure-list values))
(when values
(let* ((*print-pretty* (pretty? o))
(new-part (format nil "~@[~@?~]~?" (when (has-written? o) (delimiter o))
(first values) (rest values))))
(setf (has-written? o) t)
(setf (value o) (concatenate 'string (value o) new-part))
(when (output-stream o)
(write-string new-part (output-stream o))))))
(defun make-formatter (&key delimiter stream pretty)
"Create a string formatter collector function.
creates a (lambda &optional format-string &rest args) and collects these in a list
When called with no args, returns the concatenated (with delimiter) results
binds *print-pretty* to nil "
(make-instance 'string-formatter :delimiter delimiter :output-stream stream :pretty? pretty ))
(defmacro with-formatter ((name &key delimiter stream pretty) &body body)
"A macro makes a function with name for body that is a string formatter
see make-formatter"
(alexandria:with-unique-names (fn-sym)
`(let ((,fn-sym (make-formatter :delimiter ,delimiter :stream ,stream
:pretty ,pretty)))
(flet ((,name (&rest args) (apply ,fn-sym args)))
,@body))))
(defmacro with-formatter-output ((name &key delimiter stream pretty) &body body)
"A macro makes a function with name for body that is a string formatter
see make-formatter.
This form returns the result of that formatter"
`(with-formatter (,name :delimiter ,delimiter :stream ,stream :pretty ,pretty)
,@body
(,name)))
(defmethod should-aggregate? ((o string-builder) v
&aux (collect-empty? (not (ignore-empty-strings-and-nil? o))))
(or collect-empty?
(and v (or (not (stringp v))
(plusp (length v))))))
(defmethod operate ((o string-builder) values
&aux
(delimiter (delimiter o))
(out (output-stream o))
(*print-pretty* (pretty? o)))
(setf values (alexandria:ensure-list values))
(dolist (v values)
(with-signal-context (v (value o) o)
(setf v (typecase v
(string v)
(t (princ-to-string v))))
(cond
((and delimiter (has-written? o))
(when out
(write-string delimiter out)
(write-string v out))
(setf (value o) (concatenate 'string (value o) delimiter v)))
((has-written? o)
(when out (write-string v out))
(setf (value o) (concatenate 'string (value o) v)))
(t
(when out (write-string v out))
(setf (value o) v)))
(setf (has-written? o) t))))
(defun make-string-builder (&key delimiter ignore-empty-strings-and-nil stream)
(make-instance 'string-builder
:output-stream stream
:delimiter delimiter
:ignore-empty-strings-and-nil? ignore-empty-strings-and-nil))
(defmacro with-string-builder ((name &key delimiter
(ignore-empty-strings-and-nil t)
stream)
&body body)
"A macro that creates a string builder with name in scope during the
duration of the env"
(alexandria:with-unique-names (it items)
`(let ((,it (make-string-builder
:delimiter ,delimiter
:ignore-empty-strings-and-nil ,ignore-empty-strings-and-nil
:stream ,stream)))
(declare (type function ,it))
(flet ((,name (&rest ,items)
(declare (dynamic-extent ,items)) (apply ,it ,items)))
,@body))))
(defmacro with-string-builder-output ((name &key delimiter (ignore-empty-strings-and-nil t)
stream)
&body body)
"A macro that creates a string builder with name in scope during the
duration of the env, the form returns the string that is built"
`(with-string-builder (,name :delimiter ,delimiter
:stream ,stream
:ignore-empty-strings-and-nil ,ignore-empty-strings-and-nil)
,@body
(,name)))
(defun mapping-aggregation-context (body-fn &key aggregator map-fn)
(handler-bind
((aggregating
(lambda (c)
(when (eql aggregator (aggregator c))
(invoke-restart 'new-value (funcall map-fn (value c)))))))
(funcall body-fn)))
(defmacro map-aggregation ((aggregator fn-spec) &body body)
`(mapping-aggregation-context
(lambda () ,@body)
:aggregator ,aggregator
:map-fn ,fn-spec))
;;;; Mapping collectors
(defmacro with-mapping-collector ((name fn-args &body fn-body)
&body body)
"Like a with-collector, but instead of a name we take a function spec
if you call the resultant function with no arguments, you get the
collection so far
if you call it with arguments the results of calling your function spec are
collected
(with-mapping-collector (col (x) (* 2 x))
(col 1)
(col 2)
(col 3)
(col)) => (2 4 6)
"
(alexandria:with-unique-names (col flet-args)
`(let ((,col (make-collector)))
(map-aggregation (,col (lambda ,fn-args ,@fn-body))
(flet ((,name (&rest ,flet-args) (apply ,col ,flet-args)))
,@body)))))
(defmacro with-mapping-appender ((name fn-args &body fn-body)
&body body)
"Like a with-appender, but instead of a name we take a function spec
calling the function will appen
(with-mapping-appender (app (l) (mapcar #'(lambda (x) (* 2 x)) l))
(app '(1 2))
(app '(2 3))
(app '(3 4))
(app)) => (2 4 4 6 6 8)
"
(alexandria:with-unique-names (col flet-args)
`(let ((,col (make-appender)))
(map-aggregation (,col (lambda ,fn-args ,@fn-body))
(flet ((,name (&rest ,flet-args) (apply ,col ,flet-args)))
,@body)))))
(defmacro collecting ((arg list) &body body)
"A mapping collecting macro for operating on elements of a list
(similar to (mapcar (lambda (,arg) ,@body) list), but using a collector
so all signals are in place)"
`(with-collector-output (output)
(dolist (,arg (alexandria:ensure-list ,list))
(restart-case
(output (progn ,@body))
(skip () "Skip this element"))
)))
(defmacro appending ((arg list) &body body)
"A mapping collecting macro for operating on elements of a list
(similar to (mapcan (lambda (,arg) ,@body) list), but using a collector
so all signals are in place)"
`(with-appender-output (output)
(dolist (,arg (alexandria:ensure-list ,list))
(restart-case
(output (progn ,@body))
(skip () "Skip this element")))))
Copyright ( c ) 2002 - 2006 ,
2011 , Acceleration.net
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
- Neither the name of , nor , nor the names
;; of its contributors may be used to endorse or promote products
;; derived from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| null | https://raw.githubusercontent.com/AccelerationNet/collectors/426a143bfdd3fd6c91329e1d8077c4f654d2459b/collectors.lisp | lisp | -*- lisp -*-
signals and restarts
* Reducing and Collecting
** Reducing
ACL was throwing errors about this not being finalized (seems odd) re github #3
Fix it by: -archive.com//msg00169.html
combining them, with the aid of a reducing function, into a
single final value.
not to remove
remove last elt
remove from middle of the list
by using this head cons cell we can simplify the loop body
Mapping collectors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
(cl:defpackage :collectors-signals
(:export
#:aggregating #:skip #:new-value #:value #:aggregator #:after-values
#:done-aggregating #:aggregate))
(cl:defpackage :collectors
(:use :cl :cl-user :collectors-signals)
(:export
#:collect-at-end
#:append-at-end
#:make-simple-collector
#:make-simple-appender
#:make-simple-collector-to-place
#:make-simple-appender-to-place
#:with-collector
#:with-collector-output
#:with-collectors
#:make-collector
#:with-alist-output
#:collecting
#:make-pusher
#:with-reducer
#:make-reducer
#:with-appender
#:with-appender-output
#:make-appender
#:appending
#:with-string-builder
#:with-string-builder-output
#:make-string-builder
#:with-mapping-collector
#:with-mapping-appender
#:make-formatter
#:with-formatter
#:with-formatter-output
#:operate
#:deoperate
))
(in-package :collectors)
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-condition collectors-signals:aggregating ()
((collectors-signals:value
:accessor collectors-signals:value
:initarg :value :initform nil)
(collectors-signals:aggregator
:accessor collectors-signals:aggregator
:initarg :aggregator :initform nil)))
(define-condition collectors-signals:done-aggregating ()
((collectors-signals:after-values
:accessor collectors-signals:after-values
:initarg :after-values :initform nil)
(collectors-signals:aggregate
:accessor collectors-signals:aggregate
:initarg :aggregate :initform nil)
(collectors-signals:aggregator
:accessor collectors-signals:aggregator
:initarg :aggregator :initform nil)))
(defmacro with-signal-context ((value after-values aggregator) &body body)
(alexandria:with-unique-names (new-value)
`(with-simple-restart
(collectors-signals:skip "Skip aggregating ~A into ~A" ,value ,aggregator)
(restart-case (signal 'aggregating :value ,value :aggregator ,aggregator)
(collectors-signals:new-value (,new-value)
:report "Aggregate a new value instead"
(setf ,value ,new-value)))
(prog1 (progn ,@body)
(signal 'done-aggregating :after-values ,after-values :aggregator ,aggregator))))))
(defmacro collect-at-end (head-place tail-place values-place)
"Macros to ease efficient collection at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place c)))))
(defmacro collect-at-end-with-signals (head-place tail-place values-place
aggregator-place post-values-place)
"Macros to ease efficient collection at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(with-signal-context (,a ,post-values-place ,aggregator-place)
(let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place c)
)))))
(defmacro append-at-end (head-place tail-place values-place)
"Macros to ease efficient collection (with appending) at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(typecase ,a
(list (collect-at-end ,head-place ,tail-place ,a))
(t (let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place (last c))))))))
(defmacro append-at-end-with-signals (head-place tail-place values-place
aggregator-place post-values-place)
"Macros to ease efficient collection (with appending) at the end of a list"
(alexandria:with-unique-names (a)
`(dolist (,a ,values-place)
(with-signal-context (,a ,post-values-place ,aggregator-place)
(typecase ,a
(list (collect-at-end-with-signals
,head-place ,tail-place ,a ,aggregator-place ,post-values-place))
(t (let ((c (cons ,a nil)))
(when (null ,head-place) (setf ,head-place c))
(unless (null ,tail-place) (setf (cdr ,tail-place) c))
(setf ,tail-place (last c)))))))))
(defmacro make-simple-collector-to-place (place)
(alexandria:with-unique-names (tail)
`(progn
(setf ,place (alexandria:ensure-list ,place))
(let* ((,tail (last ,place)))
(lambda (&rest values)
(collect-at-end ,place ,tail values)
,place)))))
(defun make-simple-collector (&optional initial-value)
"A fastest possible, fewest frills collector suitable to places where efficiency matters"
(let ((head initial-value))
(make-simple-collector-to-place head)))
(defmacro make-simple-appender-to-place (place)
"A fastest possible, fewest frills collector suitable to places where efficiency matters
that appends any values that re lists"
(alexandria:with-unique-names (tail)
`(progn
(setf ,place (alexandria:ensure-list ,place))
(let ((,tail (last ,place)))
(lambda (&rest values)
(append-at-end ,place ,tail values)
,place)))))
(defun make-simple-appender (&optional initial-value)
"A fastest possible, fewest frills collector suitable to places where efficiency matters
that appends any values that re lists"
(let ((head initial-value))
(make-simple-appender-to-place head)))
(defclass value-aggregator (closer-mop:funcallable-standard-object)
((initial-value :accessor initial-value :initarg :initial-value :initform nil)
(place-setter :accessor place-setter :initarg :place-setter :initform nil)
(value :accessor value :initarg :value :initform nil))
(:metaclass closer-mop:funcallable-standard-class))
(defclass list-aggregator (value-aggregator)
((collect-nil? :accessor collect-nil? :initarg :collect-nil? :initform t
:documentation "Should we collect nil into our results")
(new-only-test :accessor new-only-test :initarg :new-only-test :initform nil
:documentation "If supplied with a new-only-test, we will verify that we
have not already collected this item before collecting again")
(new-only-key :accessor new-only-key :initarg :new-only-key :initform nil))
(:metaclass closer-mop:funcallable-standard-class))
(defclass collector (list-aggregator)
((tail :accessor tail :initarg :tail :initform nil))
(:documentation "Create a collector function.
A Collector function will collect, into a list, all the values
passed to it in the order in which they were passed. If the
callector function is called without arguments it returns the
current list of values.")
(:metaclass closer-mop:funcallable-standard-class))
(defclass reducer (value-aggregator)
((operation :accessor operation :initarg :operation :initform nil))
(:metaclass closer-mop:funcallable-standard-class)
(:documentation
"Create a function which, starting with INITIAL-VALUE, reduces
any other values into a single final value.
OPERATION will be called with two values: the current value and
the new value, in that order. OPERATION should return exactly one
value.
The reducing function can be called with n arguments which will
be applied to OPERATION one after the other (left to right) and
will return the new value.
If the reducing function is called with no arguments it will
return the current value.
Example:
(setf r (make-reducer #'+ 5))
(funcall r 0) => 5
(funcall r 1 2) => 8
(funcall r) => 8"))
(defclass pusher (list-aggregator)
()
(:metaclass closer-mop:funcallable-standard-class))
(defclass appender (collector)
()
(:documentation "Create an appender function.
An Appender will append any arguments into a list, all the values
passed to it in the order in which they were passed. If the
appender function is called without arguments it returns the
current list of values.")
(:metaclass closer-mop:funcallable-standard-class))
(defclass string-formatter (value-aggregator)
((delimiter :accessor delimiter :initarg :delimiter :initform nil)
(has-written? :accessor has-written? :initarg :has-written? :initform nil)
(output-stream :accessor output-stream :initarg :output-stream :initform nil)
(pretty? :accessor pretty? :initarg :pretty? :initform nil))
(:metaclass closer-mop:funcallable-standard-class)
(:documentation
"Create a string formatter collector function.
creates a (lambda &optional format-string &rest args) and collects these in a list
When called with no args, returns the concatenated (with delimiter) results
binds *print-pretty* to nil
"))
(defclass string-builder (string-formatter)
((ignore-empty-strings-and-nil?
:accessor ignore-empty-strings-and-nil? :initarg :ignore-empty-strings-and-nil? :initform t))
(:metaclass closer-mop:funcallable-standard-class)
(:documentation
"Create a function that will build up a string for you
Each call to the function with arguments appends those arguments to the string
with an optional delimiter between them.
if ignore-empty-strings-and-nil is true neither empty strings nor nil will be
printed to the stream
A call to the function with no arguments returns the output string"))
(closer-mop:ensure-finalized (find-class 'closer-mop:standard-object))
(closer-mop:ensure-finalized (find-class 'closer-mop:standard-class))
(closer-mop:ensure-finalized (find-class 'closer-mop:funcallable-standard-object))
(closer-mop:ensure-finalized (find-class 'closer-mop:funcallable-standard-class))
(defmethod initialize-instance :after ((o value-aggregator) &key &allow-other-keys)
(setf (value o) (typecase (initial-value o)
(list (copy-list (initial-value o)))
(t (initial-value o))))
(closer-mop:set-funcallable-instance-function
o (lambda (&rest values) (operate o values))))
(defgeneric should-aggregate? (aggregator value)
(:method ((o value-aggregator) v) (declare (ignore v)) t)
(:documentation "Should we aggregate a given value into our collection"))
(defgeneric deoperate (aggregator values &key test key)
(:documentation "Undo the aggregation operation of an aggregator and list of values")
(:method :after ((o value-aggregator) values &key test key
&aux (value (value o)))
(declare (ignore values test key))
(dolist (ps (alexandria:ensure-list (place-setter o)))
(funcall ps value))))
(defgeneric operate (aggregator values)
(:documentation "Perform the aggregation operation on the aggregator for the values")
(:method :around ((o value-aggregator) values
&aux (places (alexandria:ensure-list (place-setter o))))
(declare (ignore values))
(handler-bind
((aggregating
(lambda (c)
(when (eql o (aggregator c))
(unless (should-aggregate? (aggregator c) (value c))
(invoke-restart 'skip)))))
(done-aggregating
(lambda (c)
(when (eql o (aggregator c))
(dolist (p places)
(funcall p (value o)))))))
(call-next-method)
(value o))))
(defmethod operate ((o reducer) values)
(dolist (v (alexandria:ensure-list values))
(with-signal-context (v (value o) o)
(setf (value o)
(if (value o)
(funcall (operation o) (value o) v)
v)))))
reducing is the act of taking values , two at a time , and
(defun make-reducer (function &key initial-value place-setter)
(make-instance 'reducer :initial-value initial-value :place-setter place-setter
:operation function))
(defmacro with-reducer ((name function &key (initial-value nil) place)
&body body)
"Locally bind NAME to a reducing function. The arguments
FUNCTION and INITIAL-VALUE are passed directly to MAKE-REDUCER."
(alexandria:with-unique-names (reducer)
`(let ((,reducer (make-reducer ,function
:initial-value (or ,initial-value ,place)
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items) (apply ,reducer items)))
,@body))))
(defmethod should-aggregate? ((o list-aggregator) v)
(and (or (collect-nil? o) v)
(or (null (new-only-test o))
(null (member v (value o)
:test #'new-only-test
:key (or (new-only-key o) #'identity))))))
(defun make-pusher (&key initial-value collect-nil place-setter)
(make-instance
'pusher
:initial-value initial-value
:collect-nil? collect-nil
:place-setter place-setter))
(defmethod %push ((o list-aggregator) values)
(dolist (v (alexandria:ensure-list values))
(with-signal-context (v (value o) o)
(push v (value o))
(when (and (typep o 'collector) (null (tail o)))
(setf (tail o) (value o)))))
(value o))
(defmethod %pop-n ((o list-aggregator) &optional (n 1))
(let* ((head (value o))
(len (length head)))
(cond
((>= n len)
(setf (value o) nil)
(when (typep o 'collector)
(setf (tail o) nil)))
(t (let ((lastcons (nthcdr (- n 1) head)))
(setf (value o) (cdr lastcons)
(cdr lastcons) nil))))
(if (= 1 n)
(car head)
head)))
(defmethod %unenqueue-n ((o list-aggregator) &optional (n 1))
(let* ((head (value o))
(len (length head))
(div (- len (+ 1 n)))
(rtn (cond
((plusp div)
(let* ((c (nthcdr div head))
(rtn (cdr c)))
(setf (cdr c) nil)
(when (typep o 'collector)
(setf (tail o) c))
rtn))
(t
(setf (value o) nil)
(when (typep o 'collector)
(setf (tail o) nil))
head))))
(if (= 1 n)
(car rtn)
rtn)))
(defmethod %enqueue ((o list-aggregator) values
&aux (last (last (value o))))
(collect-at-end-with-signals
(value o) last values o (value o))
(value o))
(defmethod %enqueue ((o collector) values)
(collect-at-end-with-signals
(value o) (tail o) values o (value o))
(value o))
(defmethod operate ((o pusher) values)
(%push o values))
(defmethod initialize-instance :after ((o collector) &key &allow-other-keys)
(setf (tail o) (last (value o))))
(defmethod operate ((o collector) values)
(%enqueue o values))
(defmethod deoperate ((o list-aggregator) to-remove
&key test key
&aux prev)
(setf to-remove (alexandria:ensure-list to-remove))
(loop for cons on (value o)
for (this . next) = cons
do (if (null (member (funcall (or key #'identity) this)
to-remove
:test (or test #'eql)))
(setf prev cons)
(cond
remove first elt
((null prev)
(setf (value o) next))
((null next)
(setf (cdr prev) nil
(tail o) prev))
(t (setf (cdr prev) next)))))
(value o))
(defun make-collector (&key initial-value (collect-nil t) place-setter)
(make-instance 'collector
:initial-value initial-value :collect-nil? collect-nil
:place-setter place-setter))
(defmethod operate ((o appender) values)
(append-at-end-with-signals (value o) (tail o) values o (values o)))
(defun make-appender (&key initial-value place-setter)
(make-instance 'appender :initial-value initial-value :place-setter place-setter))
(defmacro with-appender ((name &key initial-value place) &body body)
"Bind NAME to a collector function and execute BODY. If
FROM-END is true the collector will actually be a pusher, (see
MAKE-PUSHER), otherwise NAME will be bound to a collector,
(see MAKE-COLLECTOR).
(with-appender (app)
(app '(1 2))
(app '(2 3))
(app '(3 4))
(app)) => (1 2 2 3 3 4)
"
(alexandria:with-unique-names (appender)
`(let ((,appender (make-appender
:initial-value (or ,initial-value ,place)
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items) (apply ,appender items)))
,@body))))
(defmacro with-appender-output ((name &key initial-value place) &body body)
"Same as with-appender, but this form returns the collected values
automatically
"
`(with-appender (,name :initial-value ,initial-value :place ,place)
,@body (,name)))
(defmacro with-collector ((name &key place (collect-nil T) initial-value from-end) &body body)
"Bind NAME to a collector function and execute BODY. If
FROM-END is true the collector will actually be a pusher, (see
MAKE-PUSHER), otherwise NAME will be bound to a collector,
(see MAKE-COLLECTOR).
(with-collector (col)
(col 1)
(col 2)
(col 3)
(col)) => (1 2 3)
"
`(let ((,name (,(if from-end
'make-pusher
'make-collector)
:initial-value (or ,initial-value ,place)
:collect-nil ,collect-nil
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items) (operate ,name items))
(,(symbol-munger:english->lisp-symbol `(push ,name))
(&rest items)
(%push ,name items))
(,(symbol-munger:english->lisp-symbol `(pop ,name))
(&optional (n 1))
(%pop-n ,name n))
(,(symbol-munger:english->lisp-symbol `(enqueue ,name))
(&rest items)
(%enqueue ,name items))
(,(symbol-munger:english->lisp-symbol `(unenqueue ,name))
(&optional (n 1))
(%unenqueue-n ,name n))
)
,@body)))
(defmacro with-collector-output ((name &key (collect-nil t) initial-value from-end place)
&body body)
`(with-collector (,name :collect-nil ,collect-nil
:initial-value ,initial-value
:from-end ,from-end
:place ,place)
,@body
(,name)))
(defmacro with-alist ((name &key place (collect-nil T) initial-value from-end) &body body)
`(let ((,name (,(if from-end
'make-pusher
'make-collector)
:initial-value (or ,initial-value ,place)
:collect-nil ,collect-nil
:place-setter ,(when place `(lambda (new) (setf ,place new))))))
(flet ((,name (&rest items)
(loop for (k v) on items by #'cddr
do (operate ,name (list (cons k v))))
(value ,name)))
,@body)))
(defmacro with-alist-output ((name &key (collect-nil t) initial-value from-end place)
&body body)
`(with-alist (,name :collect-nil ,collect-nil
:initial-value ,initial-value
:from-end ,from-end
:place ,place)
,@body
(,name)))
(defmacro with-collectors (names &body body)
"Bind multiple collectors. Each element of NAMES should be a
list as per WITH-COLLECTOR's first orgument."
(if names
`(with-collector ,(alexandria:ensure-list (car names))
(with-collectors ,(cdr names) ,@body))
`(progn ,@body)))
(defmethod initialize-instance :after ((o string-formatter) &key &allow-other-keys)
(when (and (delimiter o) (not (stringp (delimiter o))))
(setf (delimiter o) (princ-to-string (delimiter o))))
(when (initial-value o)
(setf (has-written? o) t)
(when (output-stream o)
(write-string (initial-value o) (output-stream o)))))
(defmethod operate ((o string-formatter) values)
(setf values (alexandria:ensure-list values))
(when values
(let* ((*print-pretty* (pretty? o))
(new-part (format nil "~@[~@?~]~?" (when (has-written? o) (delimiter o))
(first values) (rest values))))
(setf (has-written? o) t)
(setf (value o) (concatenate 'string (value o) new-part))
(when (output-stream o)
(write-string new-part (output-stream o))))))
(defun make-formatter (&key delimiter stream pretty)
"Create a string formatter collector function.
creates a (lambda &optional format-string &rest args) and collects these in a list
When called with no args, returns the concatenated (with delimiter) results
binds *print-pretty* to nil "
(make-instance 'string-formatter :delimiter delimiter :output-stream stream :pretty? pretty ))
(defmacro with-formatter ((name &key delimiter stream pretty) &body body)
"A macro makes a function with name for body that is a string formatter
see make-formatter"
(alexandria:with-unique-names (fn-sym)
`(let ((,fn-sym (make-formatter :delimiter ,delimiter :stream ,stream
:pretty ,pretty)))
(flet ((,name (&rest args) (apply ,fn-sym args)))
,@body))))
(defmacro with-formatter-output ((name &key delimiter stream pretty) &body body)
"A macro makes a function with name for body that is a string formatter
see make-formatter.
This form returns the result of that formatter"
`(with-formatter (,name :delimiter ,delimiter :stream ,stream :pretty ,pretty)
,@body
(,name)))
(defmethod should-aggregate? ((o string-builder) v
&aux (collect-empty? (not (ignore-empty-strings-and-nil? o))))
(or collect-empty?
(and v (or (not (stringp v))
(plusp (length v))))))
(defmethod operate ((o string-builder) values
&aux
(delimiter (delimiter o))
(out (output-stream o))
(*print-pretty* (pretty? o)))
(setf values (alexandria:ensure-list values))
(dolist (v values)
(with-signal-context (v (value o) o)
(setf v (typecase v
(string v)
(t (princ-to-string v))))
(cond
((and delimiter (has-written? o))
(when out
(write-string delimiter out)
(write-string v out))
(setf (value o) (concatenate 'string (value o) delimiter v)))
((has-written? o)
(when out (write-string v out))
(setf (value o) (concatenate 'string (value o) v)))
(t
(when out (write-string v out))
(setf (value o) v)))
(setf (has-written? o) t))))
(defun make-string-builder (&key delimiter ignore-empty-strings-and-nil stream)
(make-instance 'string-builder
:output-stream stream
:delimiter delimiter
:ignore-empty-strings-and-nil? ignore-empty-strings-and-nil))
(defmacro with-string-builder ((name &key delimiter
(ignore-empty-strings-and-nil t)
stream)
&body body)
"A macro that creates a string builder with name in scope during the
duration of the env"
(alexandria:with-unique-names (it items)
`(let ((,it (make-string-builder
:delimiter ,delimiter
:ignore-empty-strings-and-nil ,ignore-empty-strings-and-nil
:stream ,stream)))
(declare (type function ,it))
(flet ((,name (&rest ,items)
(declare (dynamic-extent ,items)) (apply ,it ,items)))
,@body))))
(defmacro with-string-builder-output ((name &key delimiter (ignore-empty-strings-and-nil t)
stream)
&body body)
"A macro that creates a string builder with name in scope during the
duration of the env, the form returns the string that is built"
`(with-string-builder (,name :delimiter ,delimiter
:stream ,stream
:ignore-empty-strings-and-nil ,ignore-empty-strings-and-nil)
,@body
(,name)))
(defun mapping-aggregation-context (body-fn &key aggregator map-fn)
(handler-bind
((aggregating
(lambda (c)
(when (eql aggregator (aggregator c))
(invoke-restart 'new-value (funcall map-fn (value c)))))))
(funcall body-fn)))
(defmacro map-aggregation ((aggregator fn-spec) &body body)
`(mapping-aggregation-context
(lambda () ,@body)
:aggregator ,aggregator
:map-fn ,fn-spec))
(defmacro with-mapping-collector ((name fn-args &body fn-body)
&body body)
"Like a with-collector, but instead of a name we take a function spec
if you call the resultant function with no arguments, you get the
collection so far
if you call it with arguments the results of calling your function spec are
collected
(with-mapping-collector (col (x) (* 2 x))
(col 1)
(col 2)
(col 3)
(col)) => (2 4 6)
"
(alexandria:with-unique-names (col flet-args)
`(let ((,col (make-collector)))
(map-aggregation (,col (lambda ,fn-args ,@fn-body))
(flet ((,name (&rest ,flet-args) (apply ,col ,flet-args)))
,@body)))))
(defmacro with-mapping-appender ((name fn-args &body fn-body)
&body body)
"Like a with-appender, but instead of a name we take a function spec
calling the function will appen
(with-mapping-appender (app (l) (mapcar #'(lambda (x) (* 2 x)) l))
(app '(1 2))
(app '(2 3))
(app '(3 4))
(app)) => (2 4 4 6 6 8)
"
(alexandria:with-unique-names (col flet-args)
`(let ((,col (make-appender)))
(map-aggregation (,col (lambda ,fn-args ,@fn-body))
(flet ((,name (&rest ,flet-args) (apply ,col ,flet-args)))
,@body)))))
(defmacro collecting ((arg list) &body body)
"A mapping collecting macro for operating on elements of a list
(similar to (mapcar (lambda (,arg) ,@body) list), but using a collector
so all signals are in place)"
`(with-collector-output (output)
(dolist (,arg (alexandria:ensure-list ,list))
(restart-case
(output (progn ,@body))
(skip () "Skip this element"))
)))
(defmacro appending ((arg list) &body body)
"A mapping collecting macro for operating on elements of a list
(similar to (mapcan (lambda (,arg) ,@body) list), but using a collector
so all signals are in place)"
`(with-appender-output (output)
(dolist (,arg (alexandria:ensure-list ,list))
(restart-case
(output (progn ,@body))
(skip () "Skip this element")))))
Copyright ( c ) 2002 - 2006 ,
2011 , Acceleration.net
- Neither the name of , nor , nor the names
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
b877f0093b4dd0c57cca0c569ae781a621fff0c995b716f2370df2c11042c70d | ocamllabs/ocaml-modular-implicits | testfork.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, 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 .
(* *)
(***********************************************************************)
(* POSIX threads and fork() *)
let compute_thread c = ignore c
while true do
print_char c ; flush stdout ;
for i = 1 to 100000 do ignore(ref [ ] ) done
done
while true do
print_char c; flush stdout;
for i = 1 to 100000 do ignore(ref []) done
done
*)
let main () =
ignore(Thread.create compute_thread '1');
Thread.delay 1.0;
print_string "Forking..."; print_newline();
match Unix.fork() with
| 0 ->
Thread.delay 0.5;
print_string "In child..."; print_newline();
Gc.minor();
print_string "Child did minor GC."; print_newline();
ignore(Thread.create compute_thread '2');
Thread.delay 1.0;
print_string "Child is exiting."; print_newline();
exit 0
| pid ->
print_string "In parent..."; print_newline();
Thread.delay 4.0;
print_string "Parent is exiting."; print_newline();
exit 0
let _ = main()
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/lib-systhreads/testfork.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
POSIX threads and fork() | , 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 .
let compute_thread c = ignore c
while true do
print_char c ; flush stdout ;
for i = 1 to 100000 do ignore(ref [ ] ) done
done
while true do
print_char c; flush stdout;
for i = 1 to 100000 do ignore(ref []) done
done
*)
let main () =
ignore(Thread.create compute_thread '1');
Thread.delay 1.0;
print_string "Forking..."; print_newline();
match Unix.fork() with
| 0 ->
Thread.delay 0.5;
print_string "In child..."; print_newline();
Gc.minor();
print_string "Child did minor GC."; print_newline();
ignore(Thread.create compute_thread '2');
Thread.delay 1.0;
print_string "Child is exiting."; print_newline();
exit 0
| pid ->
print_string "In parent..."; print_newline();
Thread.delay 4.0;
print_string "Parent is exiting."; print_newline();
exit 0
let _ = main()
|
4377b85a0918c7f31891f557d749159f0cae216696b23955a5d1671f5b2f3c1f | atgreen/lisp-openshift | regex-class.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
$ Header : /usr / local / cvsrep / cl - ppcre / regex - class.lisp , v 1.44 2009/10/28 07:36:15 edi Exp $
;;; This file defines the REGEX class. REGEX objects are used to
;;; represent the (transformed) parse trees internally
Copyright ( c ) 2002 - 2009 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-ppcre)
(defclass regex ()
()
(:documentation "The REGEX base class. All other classes inherit
from this one."))
(defclass seq (regex)
((elements :initarg :elements
:accessor elements
:type cons
:documentation "A list of REGEX objects."))
(:documentation "SEQ objects represents sequences of regexes.
\(Like \"ab\" is the sequence of \"a\" and \"b\".)"))
(defclass alternation (regex)
((choices :initarg :choices
:accessor choices
:type cons
:documentation "A list of REGEX objects"))
(:documentation "ALTERNATION objects represent alternations of
regexes. \(Like \"a|b\" ist the alternation of \"a\" or \"b\".)"))
(defclass lookahead (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive."))
(:documentation "LOOKAHEAD objects represent look-ahead assertions."))
(defclass lookbehind (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive.")
(len :initarg :len
:accessor len
:type fixnum
:documentation "The \(fixed) length of the enclosed regex."))
(:documentation "LOOKBEHIND objects represent look-behind assertions."))
(defclass repetition (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX that's repeated.")
(greedyp :initarg :greedyp
:reader greedyp
:documentation "Whether the repetition is greedy.")
(minimum :initarg :minimum
:accessor minimum
:type fixnum
:documentation "The minimal number of repetitions.")
(maximum :initarg :maximum
:accessor maximum
:documentation "The maximal number of repetitions.
Can be NIL for unbounded.")
(min-len :initarg :min-len
:reader min-len
:documentation "The minimal length of the enclosed regex.")
(len :initarg :len
:reader len
:documentation "The length of the enclosed regex. NIL if
unknown.")
(min-rest :initform 0
:accessor min-rest
:type fixnum
:documentation "The minimal number of characters which
must appear after this repetition.")
(contains-register-p :initarg :contains-register-p
:reader contains-register-p
:documentation "Whether the regex contains a
register."))
(:documentation "REPETITION objects represent repetitions of regexes."))
(defclass register (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex.")
(num :initarg :num
:reader num
:type fixnum
:documentation "The number of this register, starting from 0.
This is the index into *REGS-START* and *REGS-END*.")
(name :initarg :name
:reader name
:documentation "Name of this register or NIL."))
(:documentation "REGISTER objects represent register groups."))
(defclass standalone (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex."))
(:documentation "A standalone regular expression."))
(defclass back-reference (regex)
((num :initarg :num
:accessor num
:type fixnum
:documentation "The number of the register this
reference refers to.")
(name :initarg :name
:accessor name
:documentation "The name of the register this
reference refers to or NIL.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "Whether we check
case-insensitively."))
(:documentation "BACK-REFERENCE objects represent backreferences."))
(defclass char-class (regex)
((test-function :initarg :test-function
:reader test-function
:type (or function symbol nil)
:documentation "A unary function \(accepting a
character) which stands in for the character class and does the work
of checking whether a character belongs to the class."))
(:documentation "CHAR-CLASS objects represent character classes."))
(defclass str (regex)
((str :initarg :str
:accessor str
:type string
:documentation "The actual string.")
(len :initform 0
:accessor len
:type fixnum
:documentation "The length of the string.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "If we match case-insensitively.")
(offset :initform nil
:accessor offset
:documentation "Offset from the left of the whole
parse tree. The first regex has offset 0. NIL if unknown, i.e. behind
a variable-length regex.")
(skip :initform nil
:initarg :skip
:accessor skip
:documentation "If we can avoid testing for this
string because the SCAN function has done this already.")
(start-of-end-string-p :initform nil
:accessor start-of-end-string-p
:documentation "If this is the unique
STR which starts END-STRING (a slot of MATCHER)."))
(:documentation "STR objects represent string."))
(defclass anchor (regex)
((startp :initarg :startp
:reader startp
:documentation "Whether this is a \"start anchor\".")
(multi-line-p :initarg :multi-line-p
:initform nil
:reader multi-line-p
:documentation "Whether we're in multi-line mode,
i.e. whether each #\\Newline is surrounded by anchors.")
(no-newline-p :initarg :no-newline-p
:initform nil
:reader no-newline-p
:documentation "Whether we ignore #\\Newline at the end."))
(:documentation "ANCHOR objects represent anchors like \"^\" or \"$\"."))
(defclass everything (regex)
((single-line-p :initarg :single-line-p
:reader single-line-p
:documentation "Whether we're in single-line mode,
i.e. whether we also match #\\Newline."))
(:documentation "EVERYTHING objects represent regexes matching
\"everything\", i.e. dots."))
(defclass word-boundary (regex)
((negatedp :initarg :negatedp
:reader negatedp
:documentation "Whether we mean the opposite,
i.e. no word-boundary."))
(:documentation "WORD-BOUNDARY objects represent word-boundary assertions."))
(defclass branch (regex)
((test :initarg :test
:accessor test
:documentation "The test of this branch, one of
LOOKAHEAD, LOOKBEHIND, or a number.")
(then-regex :initarg :then-regex
:accessor then-regex
:documentation "The regex that's to be matched if the
test succeeds.")
(else-regex :initarg :else-regex
:initform (make-instance 'void)
:accessor else-regex
:documentation "The regex that's to be matched if the
test fails."))
(:documentation "BRANCH objects represent Perl's conditional regular
expressions."))
(defclass filter (regex)
((fn :initarg :fn
:accessor fn
:type (or function symbol)
:documentation "The user-defined function.")
(len :initarg :len
:reader len
:documentation "The fixed length of this filter or NIL."))
(:documentation "FILTER objects represent arbitrary functions
defined by the user."))
(defclass void (regex)
()
(:documentation "VOID objects represent empty regular expressions."))
(defmethod initialize-instance :after ((str str) &rest init-args)
(declare #.*standard-optimize-settings*)
(declare (ignore init-args))
"Automatically computes the length of a STR after initialization."
(let ((str-slot (slot-value str 'str)))
(unless (typep str-slot
#-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string)
(setf (slot-value str 'str)
(coerce str-slot
#-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string))))
(setf (len str) (length (str str))))
| null | https://raw.githubusercontent.com/atgreen/lisp-openshift/40235286bd3c6a61cab9f5af883d9ed9befba849/quicklisp/dists/quicklisp/software/cl-ppcre-2.0.3/regex-class.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
This file defines the REGEX class. REGEX objects are used to
represent the (transformed) parse trees internally
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | $ Header : /usr / local / cvsrep / cl - ppcre / regex - class.lisp , v 1.44 2009/10/28 07:36:15 edi Exp $
Copyright ( c ) 2002 - 2009 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-ppcre)
(defclass regex ()
()
(:documentation "The REGEX base class. All other classes inherit
from this one."))
(defclass seq (regex)
((elements :initarg :elements
:accessor elements
:type cons
:documentation "A list of REGEX objects."))
(:documentation "SEQ objects represents sequences of regexes.
\(Like \"ab\" is the sequence of \"a\" and \"b\".)"))
(defclass alternation (regex)
((choices :initarg :choices
:accessor choices
:type cons
:documentation "A list of REGEX objects"))
(:documentation "ALTERNATION objects represent alternations of
regexes. \(Like \"a|b\" ist the alternation of \"a\" or \"b\".)"))
(defclass lookahead (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive."))
(:documentation "LOOKAHEAD objects represent look-ahead assertions."))
(defclass lookbehind (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive.")
(len :initarg :len
:accessor len
:type fixnum
:documentation "The \(fixed) length of the enclosed regex."))
(:documentation "LOOKBEHIND objects represent look-behind assertions."))
(defclass repetition (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX that's repeated.")
(greedyp :initarg :greedyp
:reader greedyp
:documentation "Whether the repetition is greedy.")
(minimum :initarg :minimum
:accessor minimum
:type fixnum
:documentation "The minimal number of repetitions.")
(maximum :initarg :maximum
:accessor maximum
:documentation "The maximal number of repetitions.
Can be NIL for unbounded.")
(min-len :initarg :min-len
:reader min-len
:documentation "The minimal length of the enclosed regex.")
(len :initarg :len
:reader len
:documentation "The length of the enclosed regex. NIL if
unknown.")
(min-rest :initform 0
:accessor min-rest
:type fixnum
:documentation "The minimal number of characters which
must appear after this repetition.")
(contains-register-p :initarg :contains-register-p
:reader contains-register-p
:documentation "Whether the regex contains a
register."))
(:documentation "REPETITION objects represent repetitions of regexes."))
(defclass register (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex.")
(num :initarg :num
:reader num
:type fixnum
:documentation "The number of this register, starting from 0.
This is the index into *REGS-START* and *REGS-END*.")
(name :initarg :name
:reader name
:documentation "Name of this register or NIL."))
(:documentation "REGISTER objects represent register groups."))
(defclass standalone (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex."))
(:documentation "A standalone regular expression."))
(defclass back-reference (regex)
((num :initarg :num
:accessor num
:type fixnum
:documentation "The number of the register this
reference refers to.")
(name :initarg :name
:accessor name
:documentation "The name of the register this
reference refers to or NIL.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "Whether we check
case-insensitively."))
(:documentation "BACK-REFERENCE objects represent backreferences."))
(defclass char-class (regex)
((test-function :initarg :test-function
:reader test-function
:type (or function symbol nil)
:documentation "A unary function \(accepting a
character) which stands in for the character class and does the work
of checking whether a character belongs to the class."))
(:documentation "CHAR-CLASS objects represent character classes."))
(defclass str (regex)
((str :initarg :str
:accessor str
:type string
:documentation "The actual string.")
(len :initform 0
:accessor len
:type fixnum
:documentation "The length of the string.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "If we match case-insensitively.")
(offset :initform nil
:accessor offset
:documentation "Offset from the left of the whole
parse tree. The first regex has offset 0. NIL if unknown, i.e. behind
a variable-length regex.")
(skip :initform nil
:initarg :skip
:accessor skip
:documentation "If we can avoid testing for this
string because the SCAN function has done this already.")
(start-of-end-string-p :initform nil
:accessor start-of-end-string-p
:documentation "If this is the unique
STR which starts END-STRING (a slot of MATCHER)."))
(:documentation "STR objects represent string."))
(defclass anchor (regex)
((startp :initarg :startp
:reader startp
:documentation "Whether this is a \"start anchor\".")
(multi-line-p :initarg :multi-line-p
:initform nil
:reader multi-line-p
:documentation "Whether we're in multi-line mode,
i.e. whether each #\\Newline is surrounded by anchors.")
(no-newline-p :initarg :no-newline-p
:initform nil
:reader no-newline-p
:documentation "Whether we ignore #\\Newline at the end."))
(:documentation "ANCHOR objects represent anchors like \"^\" or \"$\"."))
(defclass everything (regex)
((single-line-p :initarg :single-line-p
:reader single-line-p
:documentation "Whether we're in single-line mode,
i.e. whether we also match #\\Newline."))
(:documentation "EVERYTHING objects represent regexes matching
\"everything\", i.e. dots."))
(defclass word-boundary (regex)
((negatedp :initarg :negatedp
:reader negatedp
:documentation "Whether we mean the opposite,
i.e. no word-boundary."))
(:documentation "WORD-BOUNDARY objects represent word-boundary assertions."))
(defclass branch (regex)
((test :initarg :test
:accessor test
:documentation "The test of this branch, one of
LOOKAHEAD, LOOKBEHIND, or a number.")
(then-regex :initarg :then-regex
:accessor then-regex
:documentation "The regex that's to be matched if the
test succeeds.")
(else-regex :initarg :else-regex
:initform (make-instance 'void)
:accessor else-regex
:documentation "The regex that's to be matched if the
test fails."))
(:documentation "BRANCH objects represent Perl's conditional regular
expressions."))
(defclass filter (regex)
((fn :initarg :fn
:accessor fn
:type (or function symbol)
:documentation "The user-defined function.")
(len :initarg :len
:reader len
:documentation "The fixed length of this filter or NIL."))
(:documentation "FILTER objects represent arbitrary functions
defined by the user."))
(defclass void (regex)
()
(:documentation "VOID objects represent empty regular expressions."))
(defmethod initialize-instance :after ((str str) &rest init-args)
(declare #.*standard-optimize-settings*)
(declare (ignore init-args))
"Automatically computes the length of a STR after initialization."
(let ((str-slot (slot-value str 'str)))
(unless (typep str-slot
#-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string)
(setf (slot-value str 'str)
(coerce str-slot
#-:lispworks 'simple-string
#+:lispworks 'lw:simple-text-string))))
(setf (len str) (length (str str))))
|
787983286309421f56e2145cfa4dcdf8e32be3f1a8a4f720a06d5808af217389 | ppaml-op3/insomnia | MatchSigs.hs | -- | Semantic signature matching
≤ ∃αs . Σ ' ↑ τs ⇝ f
--
-- The concrete signature on the left is said to match the abstract
-- signature on the right if we can find some types τs (such that Γ ⊢
-- τ : κₐ ) such that Γ ⊢ Σ ≤ Σ'[τs/αs] ⇝ f (where this latter
-- judgment is signature subtyping. The difference is that matching
is concerned with finding the concrete types in the LHS that stand
for the abstract types in the RHS , while subtyping is about width
-- and depth subtyping of records).
--
The " F - ing modules " journal paper gives a decidable algorithm
" lookup_αs(Σ , ' ) ↑ τs " for signature matching in Section 5.2 . The
-- algorithm is complete provided that all the signatures in Γ are
valid and the signature ∃αs . Σ ' is explicit ( see paper for
-- definitions of explicitness and validity). It is a theorem that
-- the lookup algorithm finds the τs that satisfy the matching
-- judgment.
--
-- The lookup algorithm for a single variable α is essentially: if Σ
is TypeSem τ and Σ ' are both and ' is in fact ( FV
-- α) then return τ. Otherwise we only care about Σ' that is a record
-- (because functors (and models) close over their abstract variables
due to generativity ): we pick out the set of fields common to Σ and ' and
-- nondeterministically guess which of them will succeed in looking up α.
--
-- In the implementation below, we look for all the variables at once,
-- and instead of non-deterministically guessing, we thread a "looking
-- for" set of variables in a state monad and write out τ,α pairs when
-- we find something appropriate.
# LANGUAGE FlexibleContexts #
module FOmega.MatchSigs where
import Control.Monad.State
import Control.Monad.Writer
import qualified Data.Set as S
import qualified Data.Map as M
import Unbound.Generics.LocallyNameless (LFresh (..))
import qualified Unbound.Generics.LocallyNameless as U
import FOmega.Syntax
import FOmega.SemanticSig
type MatchPairs = Endo [(TyVar, Type)]
type LookingSet = S.Set TyVar
type M m = WriterT MatchPairs (StateT LookingSet m)
-- | Consider the judgment Γ ⊢ Σ ≤ ∃αs.Σ' ↑ τs ⇝ f . This function
' matchSubst ' takes Σ and ∃αs . Σ ' and returns Σ'[τs / αs ] and τs . Where Γ⊢ τ : κₐ
matchSubst :: (MonadPlus m, LFresh m) => SemanticSig -> AbstractSig -> m (SemanticSig, [Type])
matchSubst lhs (AbstractSig bnd) =
U.lunbind bnd $ \(tvks, rhs) -> do
let alphas = map fst tvks
runMatch lookupMatch lhs (alphas, rhs)
matchSubsts :: (MonadPlus m, LFresh m) => [SemanticSig] -> ([TyVar], [SemanticSig]) -> m ([SemanticSig], [Type])
matchSubsts ls ars =
runMatch (zipWithM_ lookupMatch) ls ars
runMatch :: (MonadPlus m, LFresh m, U.Subst Type b, Show a, Show b)
=> (a -> b -> M m ())
-> a
-> ([TyVar], b)
-> m (b, [Type])
runMatch comp lhs (alphas, rhs) = do
let lookingFor = S.fromList alphas
(w, notFound) <- runStateT (execWriterT (comp lhs rhs)) lookingFor
unless (S.null notFound) $
fail ("signature matching could not instantiate abstract variables " ++ show notFound
++ " among " ++ show lhs
++ " ≤ " ++ show rhs)
let subst = appEndo w []
ans = (rhs, map TV alphas)
return $ U.substs subst ans
lookupMatch :: Monad m => SemanticSig -> SemanticSig -> M m ()
lookupMatch (TypeSem tau _k1) (TypeSem (TV a) _k2) = do
goodMatch tau a
lookupMatch (DataSem d _ _) (TypeSem (TV a) _) = do
goodMatch (TV d) a
lookupMatch (DataSem d _ _) (DataSem a _ _) = do
goodMatch (TV d) a
lookupMatch (ModSem fs1) (ModSem fs2) = do
let commonFields = intersectFields fs1 fs2
mapM_ (uncurry lookupMatch) commonFields
lookupMatch _ _ = return ()
goodMatch :: Monad m => Type -> TyVar -> M m ()
goodMatch tau a = do
looking <- gets (S.member a)
when looking $ do
modify (S.delete a)
tell $ Endo ((a,tau) :)
intersectFields :: [(Field, a)] -> [(Field, b)] -> [(a,b)]
intersectFields fs1 fs2 = let
m1 = M.fromList fs1
m2 = M.fromList fs2
i = M.intersectionWith (\x y -> (x, y)) m1 m2
in M.elems i
| null | https://raw.githubusercontent.com/ppaml-op3/insomnia/5fc6eb1d554e8853d2fc929a957c7edce9e8867d/src/FOmega/MatchSigs.hs | haskell | | Semantic signature matching
The concrete signature on the left is said to match the abstract
signature on the right if we can find some types τs (such that Γ ⊢
τ : κₐ ) such that Γ ⊢ Σ ≤ Σ'[τs/αs] ⇝ f (where this latter
judgment is signature subtyping. The difference is that matching
and depth subtyping of records).
algorithm is complete provided that all the signatures in Γ are
definitions of explicitness and validity). It is a theorem that
the lookup algorithm finds the τs that satisfy the matching
judgment.
The lookup algorithm for a single variable α is essentially: if Σ
α) then return τ. Otherwise we only care about Σ' that is a record
(because functors (and models) close over their abstract variables
nondeterministically guess which of them will succeed in looking up α.
In the implementation below, we look for all the variables at once,
and instead of non-deterministically guessing, we thread a "looking
for" set of variables in a state monad and write out τ,α pairs when
we find something appropriate.
| Consider the judgment Γ ⊢ Σ ≤ ∃αs.Σ' ↑ τs ⇝ f . This function | ≤ ∃αs . Σ ' ↑ τs ⇝ f
is concerned with finding the concrete types in the LHS that stand
for the abstract types in the RHS , while subtyping is about width
The " F - ing modules " journal paper gives a decidable algorithm
" lookup_αs(Σ , ' ) ↑ τs " for signature matching in Section 5.2 . The
valid and the signature ∃αs . Σ ' is explicit ( see paper for
is TypeSem τ and Σ ' are both and ' is in fact ( FV
due to generativity ): we pick out the set of fields common to Σ and ' and
# LANGUAGE FlexibleContexts #
module FOmega.MatchSigs where
import Control.Monad.State
import Control.Monad.Writer
import qualified Data.Set as S
import qualified Data.Map as M
import Unbound.Generics.LocallyNameless (LFresh (..))
import qualified Unbound.Generics.LocallyNameless as U
import FOmega.Syntax
import FOmega.SemanticSig
type MatchPairs = Endo [(TyVar, Type)]
type LookingSet = S.Set TyVar
type M m = WriterT MatchPairs (StateT LookingSet m)
' matchSubst ' takes Σ and ∃αs . Σ ' and returns Σ'[τs / αs ] and τs . Where Γ⊢ τ : κₐ
matchSubst :: (MonadPlus m, LFresh m) => SemanticSig -> AbstractSig -> m (SemanticSig, [Type])
matchSubst lhs (AbstractSig bnd) =
U.lunbind bnd $ \(tvks, rhs) -> do
let alphas = map fst tvks
runMatch lookupMatch lhs (alphas, rhs)
matchSubsts :: (MonadPlus m, LFresh m) => [SemanticSig] -> ([TyVar], [SemanticSig]) -> m ([SemanticSig], [Type])
matchSubsts ls ars =
runMatch (zipWithM_ lookupMatch) ls ars
runMatch :: (MonadPlus m, LFresh m, U.Subst Type b, Show a, Show b)
=> (a -> b -> M m ())
-> a
-> ([TyVar], b)
-> m (b, [Type])
runMatch comp lhs (alphas, rhs) = do
let lookingFor = S.fromList alphas
(w, notFound) <- runStateT (execWriterT (comp lhs rhs)) lookingFor
unless (S.null notFound) $
fail ("signature matching could not instantiate abstract variables " ++ show notFound
++ " among " ++ show lhs
++ " ≤ " ++ show rhs)
let subst = appEndo w []
ans = (rhs, map TV alphas)
return $ U.substs subst ans
lookupMatch :: Monad m => SemanticSig -> SemanticSig -> M m ()
lookupMatch (TypeSem tau _k1) (TypeSem (TV a) _k2) = do
goodMatch tau a
lookupMatch (DataSem d _ _) (TypeSem (TV a) _) = do
goodMatch (TV d) a
lookupMatch (DataSem d _ _) (DataSem a _ _) = do
goodMatch (TV d) a
lookupMatch (ModSem fs1) (ModSem fs2) = do
let commonFields = intersectFields fs1 fs2
mapM_ (uncurry lookupMatch) commonFields
lookupMatch _ _ = return ()
goodMatch :: Monad m => Type -> TyVar -> M m ()
goodMatch tau a = do
looking <- gets (S.member a)
when looking $ do
modify (S.delete a)
tell $ Endo ((a,tau) :)
intersectFields :: [(Field, a)] -> [(Field, b)] -> [(a,b)]
intersectFields fs1 fs2 = let
m1 = M.fromList fs1
m2 = M.fromList fs2
i = M.intersectionWith (\x y -> (x, y)) m1 m2
in M.elems i
|
00281c9948c2823cc220608d5f9c34aee38d5433340a346ad98a35b4d266c2d1 | yallop/ocaml-reex | reex_match.ml |
* Copyright ( c ) 2022 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2022 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
open Reex_deriv
module Cm = Charmatch.Make(Charset)
module CharsetSet = Set.Make(Charset)
type options = { match_type: [`table | `ranges]; null_optimization: bool; }
let default_options = { match_type = `table; null_optimization = true }
let all_empty l = List.for_all (fun (x,_) -> Reex.(equal x empty)) l
let deriv_all c l = List.map (fun (t,rhs) -> (deriv c t, rhs)) l
let charsetset_filtermap : (Charset.t -> 'a option) -> CharsetSet.t -> 'a list =
fun f css -> List.filter_map f (CharsetSet.elements css)
let ifmem options e cases =
Cm.ifmem ~options:{ match_type = options.match_type } e cases
let char_match_index options
: string code -> int code -> int code -> (Charset.t * 'a code) list -> eof:'a code -> 'a code =
fun s i len cases ~eof ->
.< if .~i = .~len then .~eof
else .~(ifmem options .<String.unsafe_get .~s .~i>. cases) >.
let char_match_index' options
: string code -> int code -> int code -> (Charset.t * 'a code) list -> eof:'a code -> 'a code =
fun s i len cases ~eof ->
(* As char_match_index, but with an optimization. Instead of testing for end-of-string initially
if i = n then .~eof else
match s.[i] with
| ...
incorporate the end-of-string test into the match:
match s.[i] with
| '\000' -> if .~i = .~len then .~eof else ...
| ...
This works because OCaml represents strings with a terminating nil for C interoperability. *)
let cases' =
List.fold_left
(fun cases' (lhs, rhs) ->
if Charset.mem '\000' lhs then
let lhs' = Charset.remove '\000' lhs in
if rhs == eof then (lhs, rhs) :: cases'
else if Charset.is_empty lhs' then ((lhs, .< if .~i = .~len then .~eof else .~rhs>.) :: cases')
else ((Charset.singleton '\000', .< if .~i = .~len then .~eof else .~rhs>.) :: (lhs', rhs) :: cases')
else (lhs, rhs) :: cases') [] cases in
match cases' with (* Also skip the match altogether if there's just one exhaustive case *)
| [cs, rhs] when Charset.cardinal cs = 256 -> rhs
| cases' -> ifmem options .<String.unsafe_get .~s .~i>. cases'
let char_match options s i len cases ~eof =
(if options.null_optimization then char_match_index' else char_match_index)
options s i len cases ~eof
let matchk_ ?(options=default_options) self (indexes, fallback) =
.< fun start ~index:i ~prev ~len s ->
.~(let eof = match List.find (fun (x,_) -> nullable x) indexes with
| exception Not_found -> (fallback .<start>. ~index:.<prev>. ~len:.<len>. .<s>.)
| (_,rhs) -> (rhs .<start>. ~index:.<i>. ~len:.<len>. .<s>.) in
char_match options .<s>. .<i>. .<len>. ~eof @@ charsetset_filtermap
(fun ss -> match Charset.choose_opt ss with
| None -> None
| Some c'' -> let indexes' = deriv_all c'' indexes in
let prev, fallback = (* Do we have a new match? *)
match List.find (fun (x,_) -> nullable x) indexes' with
| exception Not_found -> .<prev>., fallback
| (_, rhs) -> .< i+1 >., rhs
in
Some (ss, if all_empty indexes' then eof
else .< .~(self (indexes', fallback)) start ~index:(i + 1) ~prev:.~prev ~len s >.))
(capproxes (List.map fst indexes))) >.
let match_ ?options i x ?(otherwise = .<failwith "no match" >.) cases =
let fallback _ ~index:_ ~len:_ _ = otherwise in
let equal (xs, fx) (ys, fy) = List.for_all2 (fun (x,_) (y,_) -> Reex.equal x y) xs ys && fx == fy in
Letrec.letrec ~equal (matchk_ ?options)
(fun self -> .< .~(self (cases, fallback)) .~i ~index:.~i ~prev:0 ~len:(String.length .~x) .~x >.)
| null | https://raw.githubusercontent.com/yallop/ocaml-reex/94eea88bb06be5e295627f437d7a585bd9d9b0a6/lib/reex_match.ml | ocaml | As char_match_index, but with an optimization. Instead of testing for end-of-string initially
if i = n then .~eof else
match s.[i] with
| ...
incorporate the end-of-string test into the match:
match s.[i] with
| '\000' -> if .~i = .~len then .~eof else ...
| ...
This works because OCaml represents strings with a terminating nil for C interoperability.
Also skip the match altogether if there's just one exhaustive case
Do we have a new match? |
* Copyright ( c ) 2022 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2022 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
open Reex_deriv
module Cm = Charmatch.Make(Charset)
module CharsetSet = Set.Make(Charset)
type options = { match_type: [`table | `ranges]; null_optimization: bool; }
let default_options = { match_type = `table; null_optimization = true }
let all_empty l = List.for_all (fun (x,_) -> Reex.(equal x empty)) l
let deriv_all c l = List.map (fun (t,rhs) -> (deriv c t, rhs)) l
let charsetset_filtermap : (Charset.t -> 'a option) -> CharsetSet.t -> 'a list =
fun f css -> List.filter_map f (CharsetSet.elements css)
let ifmem options e cases =
Cm.ifmem ~options:{ match_type = options.match_type } e cases
let char_match_index options
: string code -> int code -> int code -> (Charset.t * 'a code) list -> eof:'a code -> 'a code =
fun s i len cases ~eof ->
.< if .~i = .~len then .~eof
else .~(ifmem options .<String.unsafe_get .~s .~i>. cases) >.
let char_match_index' options
: string code -> int code -> int code -> (Charset.t * 'a code) list -> eof:'a code -> 'a code =
fun s i len cases ~eof ->
let cases' =
List.fold_left
(fun cases' (lhs, rhs) ->
if Charset.mem '\000' lhs then
let lhs' = Charset.remove '\000' lhs in
if rhs == eof then (lhs, rhs) :: cases'
else if Charset.is_empty lhs' then ((lhs, .< if .~i = .~len then .~eof else .~rhs>.) :: cases')
else ((Charset.singleton '\000', .< if .~i = .~len then .~eof else .~rhs>.) :: (lhs', rhs) :: cases')
else (lhs, rhs) :: cases') [] cases in
| [cs, rhs] when Charset.cardinal cs = 256 -> rhs
| cases' -> ifmem options .<String.unsafe_get .~s .~i>. cases'
let char_match options s i len cases ~eof =
(if options.null_optimization then char_match_index' else char_match_index)
options s i len cases ~eof
let matchk_ ?(options=default_options) self (indexes, fallback) =
.< fun start ~index:i ~prev ~len s ->
.~(let eof = match List.find (fun (x,_) -> nullable x) indexes with
| exception Not_found -> (fallback .<start>. ~index:.<prev>. ~len:.<len>. .<s>.)
| (_,rhs) -> (rhs .<start>. ~index:.<i>. ~len:.<len>. .<s>.) in
char_match options .<s>. .<i>. .<len>. ~eof @@ charsetset_filtermap
(fun ss -> match Charset.choose_opt ss with
| None -> None
| Some c'' -> let indexes' = deriv_all c'' indexes in
match List.find (fun (x,_) -> nullable x) indexes' with
| exception Not_found -> .<prev>., fallback
| (_, rhs) -> .< i+1 >., rhs
in
Some (ss, if all_empty indexes' then eof
else .< .~(self (indexes', fallback)) start ~index:(i + 1) ~prev:.~prev ~len s >.))
(capproxes (List.map fst indexes))) >.
let match_ ?options i x ?(otherwise = .<failwith "no match" >.) cases =
let fallback _ ~index:_ ~len:_ _ = otherwise in
let equal (xs, fx) (ys, fy) = List.for_all2 (fun (x,_) (y,_) -> Reex.equal x y) xs ys && fx == fy in
Letrec.letrec ~equal (matchk_ ?options)
(fun self -> .< .~(self (cases, fallback)) .~i ~index:.~i ~prev:0 ~len:(String.length .~x) .~x >.)
|
b8e47d2a0b7d8d489f792dea15b9de099b49cb0e5df72f0b228c20d3e8c475f8 | DeepSec-prover/deepsec | display_ui.ml | (**************************************************************************)
(* *)
DeepSec
(* *)
, project PESTO ,
, project PESTO ,
, project PESTO ,
(* *)
Copyright ( C ) INRIA 2017 - 2020
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU General Public License version 3.0 as described in the
(* file LICENSE *)
(* *)
(**************************************************************************)
open Term
open Types
open Types_ui
open Display
(*** Specific print_text for dealing with return ***)
let print_text =
let previous_size = ref 0 in
let f return newline str =
let size = String.length str in
if return
then
let diff = !previous_size - size in
if diff > 0
then print_string ("\x0d"^str^(String.make (diff+10) ' '))
else print_string ("\x0d"^str^(String.make 10 ' '))
else print_string str;
if newline
then print_string "\n";
if newline
then previous_size := 0
else previous_size := size;
flush stdout
in
f
(*** Display ***)
let display_with_tab n str =
let rec print_tab = function
| 0 -> ""
| n -> " "^(print_tab (n-1))
in
(print_tab n) ^ str ^"\n"
let display_position pos = Printf.sprintf "%d[%s]" pos.js_index (display_list string_of_int "," pos.js_args)
let display_transition = function
| JAOutput(r,pos) -> Printf.sprintf "out(%s,%s)" (Recipe.display Terminal r) (display_position pos)
| JAInput(r,r',pos) -> Printf.sprintf "in(%s,%s,%s)" (Recipe.display Terminal r) (Recipe.display Terminal r') (display_position pos)
| JAEaves(r,pos_out,pos_in) -> Printf.sprintf "eav(%s,%s,%s)" (Recipe.display Terminal r) (display_position pos_out) (display_position pos_in)
| JAComm(pos_out,pos_in) -> Printf.sprintf "comm(%s,%s)" (display_position pos_out) (display_position pos_in)
| JABang(n,pos) -> Printf.sprintf "bang(%d,%s)" n (display_position pos)
| JATau pos -> Printf.sprintf "tau(%s)" (display_position pos)
| JAChoice(pos,b) -> Printf.sprintf "choice(%s,%b)" (display_position pos) b
let rec display_pattern = function
| JPEquality t -> Printf.sprintf "=%s" (Term.display Terminal t)
| JPTuple(_,args) -> Printf.sprintf "%s%s%s" (langle Terminal) (display_list display_pattern "," args) (rangle Terminal)
| JPVar(x,_) -> Variable.display Terminal x
let rec display_process tab = function
| JNil -> (display_with_tab tab "Nil")
| JOutput(ch,t,p,pos) ->
let str = Printf.sprintf "{%s} out(%s,%s);" (display_position pos) (Term.display Terminal ch) (Term.display Terminal t) in
(display_with_tab tab str) ^ (display_process tab p)
| JInput(ch,pat,p,pos) ->
let str = Printf.sprintf "{%s} in(%s,%s);" (display_position pos) (Term.display Terminal ch) (display_pattern pat) in
(display_with_tab tab str) ^ (display_process tab p)
| JIfThenElse(t1,t2,pthen,JNil,pos) ->
let str = Printf.sprintf "{%s} if %s = %s then" (display_position pos) (Term.display Terminal t1) (Term.display Terminal t2) in
let str_then = display_process tab pthen in
(display_with_tab tab str) ^ str_then
| JIfThenElse(t1,t2,pthen,pelse,pos) ->
let str = Printf.sprintf "{%s} if %s = %s then" (display_position pos) (Term.display Terminal t1) (Term.display Terminal t2) in
let str_then = display_process (tab+1) pthen in
let str_else = display_process (tab+1) pelse in
let str_neg = "else" in
(display_with_tab tab str) ^ str_then ^ (display_with_tab tab str_neg) ^ str_else
| JLet(pat,t,pthen,JNil,pos) ->
let str = Printf.sprintf "{%s} let %s = %s in" (display_position pos) (display_pattern pat) (Term.display Terminal t) in
let str_then = display_process tab pthen in
(display_with_tab tab str) ^ str_then
| JLet(pat,t,pthen,pelse,pos) ->
let str = Printf.sprintf "{%s} let %s = %s in" (display_position pos) (display_pattern pat) (Term.display Terminal t) in
let str_then = display_process (tab+1) pthen in
let str_else = display_process (tab+1) pelse in
let str_neg = "else" in
(display_with_tab tab str) ^ str_then ^ (display_with_tab tab str_neg) ^ str_else
| JNew(n,_,p,pos) ->
let str = Printf.sprintf "{%s} new %s;" (display_position pos) (Name.display Terminal n) in
(display_with_tab tab str) ^ (display_process tab p)
| JPar p_list ->
(display_with_tab tab "(") ^
(display_list (display_process (tab+1)) (display_with_tab tab ") | (") p_list) ^
(display_with_tab tab ")")
| JBang(n,p,pos) ->
(display_with_tab tab (Printf.sprintf "{%s} !^%d" (display_position pos) n)) ^
(display_process tab p)
| JChoice(p1,p2,pos) ->
let str_1 = display_process (tab+1) p1 in
let str_2 = display_process (tab+1) p2 in
let str_plus = Printf.sprintf "{%s} +" (display_position pos) in
str_1 ^ (display_with_tab tab str_plus) ^ str_2
let display_association assoc =
let display_args id args = Printf.sprintf "%d[%s]" id (display_list string_of_int "," args) in
Printf.sprintf "Association (size = %d):\n%s\n%s\n%s\n%s\n%s\n"
assoc.std.size
("Symbols: "^(display_list (fun (f,n) -> Printf.sprintf "%s->%s" (Symbol.display Terminal f) (display_args n [])) "," assoc.std.symbols))
("Names: "^(display_list (fun (f,n) -> Printf.sprintf "%s->%s" (Name.display Terminal f) (display_args n [])) "," assoc.std.names))
("Variables: "^(display_list (fun (f,n) -> Printf.sprintf "%s->%s" (Variable.display Terminal f) (display_args n [])) "," assoc.std.variables))
("Repl Names: "^(display_list (fun (f,(n,args)) -> Printf.sprintf "%s->%s" (Name.display Terminal f) (display_args n args)) "," assoc.repl.repl_names))
("Repl Variables: "^(display_list (fun (f,(n,args)) -> Printf.sprintf "%s->%s" (Variable.display Terminal f) (display_args n args)) "," assoc.repl.repl_variables))
(** Display Verification Result **)
let display_verification_result result =
if !Config.running_api
then ()
else
let display_transitions trace =
let display_one_transition ax = function
| AOutput(r_ch,_) ->
incr ax;
Printf.sprintf "out(%s,ax_%d)" (Recipe.display ~display_context:false Terminal r_ch) !ax
| AInput(r_ch,r_t,_) -> Printf.sprintf "in(%s,%s)" (Recipe.display ~display_context:false Terminal r_ch) (Recipe.display ~display_context:false Terminal r_t)
| AEaves(r_ch,_,_) ->
incr ax;
Printf.sprintf "eav(%s,ax_%d)" (Recipe.display ~display_context:false Terminal r_ch) !ax
| _ -> Config.internal_error "[display_ui.ml >> display_verification_result] Unexpected transition."
in
let trace' = List.filter (function AOutput _ | AInput _ | AEaves _ -> true | _ -> false) trace in
if trace' = []
then varepsilon Terminal
else
begin
let ax = ref 0 in
let first = display_one_transition ax (List.hd trace') in
List.fold_left (fun acc trans ->
acc ^ ";" ^ (display_one_transition ax trans)
) first (List.tl trace')
end
in
match result with
| RTrace_Equivalence (Some (is_left,trace)) | RSession_Equivalence (Some (is_left,trace)) ->
print_text true true (Printf.sprintf "The following attack trace has been found on the %s process: %s"
(if is_left then "1st" else "2nd")
(display_transitions trace)
)
| RTrace_Inclusion (Some trace) | RSession_Inclusion (Some trace) ->
print_text true true (Printf.sprintf "The following attack trace has been found: %s"
(display_transitions trace)
)
| _ -> ()
(*** Record atomic data ***)
let record_name assoc_ref n =
if not (List.exists (fun (n',_) -> n == n') (!assoc_ref).names)
then
let i = !assoc_ref.size in
assoc_ref := { !assoc_ref with size = i + 1; names = (n,i)::(!assoc_ref).names }
let record_symbol assoc_ref f =
if not (List.exists (fun (f',_) -> f == f') (!assoc_ref).symbols)
then
let i = !assoc_ref.size in
assoc_ref := { !assoc_ref with size = i + 1; symbols = (f,i)::(!assoc_ref).symbols }
let record_variable assoc_ref x =
if not (List.exists (fun (x',_) -> x == x') (!assoc_ref).variables)
then
let i = !assoc_ref.size in
assoc_ref := { !assoc_ref with size = i + 1; variables = (x,i)::(!assoc_ref).variables }
let rec record_from_term assoc_ref = function
| Var x -> record_variable assoc_ref x
| Name n -> record_name assoc_ref n
| Func(f,args) ->
record_symbol assoc_ref f;
List.iter (record_from_term assoc_ref) args
let rec record_from_pattern assoc_ref = function
| PatEquality t -> record_from_term assoc_ref t
| PatTuple(f,args) ->
record_symbol assoc_ref f;
List.iter (record_from_pattern assoc_ref) args
| PatVar x -> record_variable assoc_ref x
let record_from_category assoc_ref = function
| Tuple | Constructor -> ()
| Destructor rw_rules ->
List.iter (fun (lhs,rhs) ->
record_from_term assoc_ref rhs;
List.iter (record_from_term assoc_ref) lhs
) rw_rules
let record_from_full_symbol assoc_ref f =
record_symbol assoc_ref f;
record_from_category assoc_ref f.cat
let record_from_signature assoc_ref =
let setting = Symbol.get_settings () in
List.iter (record_from_full_symbol assoc_ref) setting.Symbol.all_c;
List.iter (fun (_,proj_l) ->
List.iter (record_from_full_symbol assoc_ref) proj_l
) setting.Symbol.all_p;
List.iter (record_from_full_symbol assoc_ref) setting.Symbol.all_d
Within bang , we only record the first process
let rec record_from_process assoc_ref = function
| Nil -> ()
| Output(ch,t,p,_) ->
record_from_term assoc_ref ch;
record_from_term assoc_ref t;
record_from_process assoc_ref p
| Input(ch,pat,p,_) ->
record_from_term assoc_ref ch;
record_from_pattern assoc_ref pat;
record_from_process assoc_ref p
| IfThenElse(t1,t2,p1,p2,_) ->
record_from_term assoc_ref t1;
record_from_term assoc_ref t2;
record_from_process assoc_ref p1;
record_from_process assoc_ref p2
| Let(pat,t,p1,p2,_) ->
record_from_term assoc_ref t;
record_from_pattern assoc_ref pat;
record_from_process assoc_ref p1;
record_from_process assoc_ref p2
| New(n,p,_) ->
record_name assoc_ref n;
record_from_process assoc_ref p
| Par p_list -> List.iter (record_from_process assoc_ref) p_list
| Bang([],_) -> Config.internal_error "[display_ui.ml >> record_from_process] Bang should at least contain one process."
| Bang(p::_,_) -> record_from_process assoc_ref p
| Choice(p1,p2,_) ->
record_from_process assoc_ref p1;
record_from_process assoc_ref p2
(*** Retrieving id of atomic data ***)
let get_name_id assoc n = match List.assq_opt n assoc.std.names with
| Some i -> i, []
| None ->
match List.assq_opt n assoc.repl.repl_names with
| Some (i,args) -> i,args
| None -> Config.internal_error (Printf.sprintf "[display_ui.ml >> get_name_id] Cannot find the name %s" (Name.display Terminal n))
let get_symbol_id assoc f = List.assq f assoc.std.symbols
let get_variable_id assoc x = match List.assq_opt x assoc.std.variables with
| Some i -> i, []
| None ->
match List.assq_opt x assoc.repl.repl_variables with
| Some (i,args) -> i,args
| None -> Config.internal_error (Printf.sprintf "[display_ui.ml >> get_variable_id] Cannot find the variable %s" (Variable.display Terminal x))
(*** Display of Json ***)
let rec display_json = function
| JString str -> "\""^str^"\""
| JBool b -> string_of_bool b
| JInt i -> string_of_int i
| JNull -> "null"
| JObject args ->
let args_str =
Display.display_list (fun (label,json) ->
Printf.sprintf "\"%s\":%s" label (display_json json)
) "," args
in
Printf.sprintf "{%s}" args_str
| JList json_l ->
Printf.sprintf "[%s]" (Display.display_list display_json "," json_l)
(*** Transformation of type to json ***)
let of_option (obj_list:(string*json) list) (f_op:'a -> json) label = function
| None -> obj_list
| Some a -> (label,f_op a)::obj_list
let of_int i = JInt i
let of_string str = JString (String.escaped str)
(* Basic types *)
let reg_proj = Str.regexp "proj_{\\([0-9]+\\),\\([0-9]+\\)}"
let of_name assoc n =
let (id,args) = get_name_id assoc n in
if args = []
then JObject [ "type", JString "Atomic"; "id", JInt id]
else JObject [ "type", JString "Atomic"; "id", JInt id; "bang", JList (List.map of_int args)]
let rec of_term assoc = function
| Var v ->
let (id,args) = get_variable_id assoc v in
if args = []
then JObject [ "type", JString "Atomic"; "id", JInt id]
else JObject [ "type", JString "Atomic"; "id", JInt id; "bang", JList (List.map of_int args)]
| Name n -> of_name assoc n
| Func({ represents = AttackerPublicName i; _},[]) when i >= 0 ->
JObject [ "type", JString "Attacker"; "label", JString ("#n_"^(string_of_int i)) ]
| Func({ represents = AttackerPublicName _; label_s = str; _},[]) ->
JObject [ "type", JString "Attacker"; "label", JString str ]
| Func(f,[]) ->
let id = get_symbol_id assoc f in
JObject [ "type", JString "Function"; "symbol", JInt id ]
| Func(f,args) when f.cat = Tuple ->
JObject [
"type", JString "Tuple";
"args", JList (List.map (of_term assoc) args)
]
| Func(f,args) ->
let id = get_symbol_id assoc f in
JObject [
"type", JString "Function";
"symbol", JInt id;
"args", JList (List.map (of_term assoc) args)
]
let rec of_recipe assoc = function
| CRFunc(_,r) -> of_recipe assoc r
| RFunc({ represents = AttackerPublicName i; _},[]) when i >= 0 ->
JObject [ "type", JString "Attacker"; "label", JString ("#n_"^(string_of_int i)) ]
| RFunc({ represents = AttackerPublicName _; label_s = str; _},[]) ->
JObject [ "type", JString "Attacker"; "label", JString str ]
| RFunc(f,[]) ->
let id = get_symbol_id assoc f in
JObject [ "type", JString "Function"; "symbol", JInt id ]
| RFunc(f,[r]) when Str.string_match reg_proj f.label_s 0 ->
let i1 = Str.matched_group 1 f.label_s in
let i2 = Str.matched_group 2 f.label_s in
JObject [
"type", JString "Proj";
"ith", JInt (int_of_string i1);
"arity_tuple", JInt (int_of_string i2);
"arg", of_recipe assoc r
]
| RFunc(f,args) when f.cat = Tuple ->
JObject [
"type", JString "Tuple";
"args", JList (List.map (of_recipe assoc) args)
]
| RFunc(f,args) ->
let id = get_symbol_id assoc f in
JObject [
"type", JString "Function";
"symbol", JInt id;
"args", JList (List.map (of_recipe assoc) args)
]
| Axiom i -> JObject [ "type", JString "Axiom"; "id", JInt i ]
| _ -> Config.internal_error "[interface.ml >> of_recipe] We should only display closed recipe."
let rec of_json_pattern assoc = function
| JPVar (v,id_rec) ->
let (id,args) = get_variable_id assoc v in
if id <> id_rec
then Config.internal_error "[display_ui.ml >> of_json_pattern] The recorded id and obtained id should be equal.";
if args = []
then JObject [ "type", JString "Atomic"; "id", JInt id]
else JObject [ "type", JString "Atomic"; "id", JInt id; "bang", JList (List.map of_int args)]
| JPEquality t -> JObject [ "type", JString "Equality"; "term", of_term assoc t]
| JPTuple(_,[]) -> Config.internal_error "[display_ui.ml >> of_json_pattern] Tuples cannot be of arity 0."
| JPTuple(_,args) ->
JObject [
"type", JString "Tuple";
"args", JList (List.map (of_json_pattern assoc) args)
]
let of_rewrite_rule assoc (lhs,rhs) =
JObject [ "lhs", JList (List.map (of_term assoc) lhs); "rhs", of_term assoc rhs]
let of_category assoc = function
| Tuple -> JObject ["type",JString "Tuple"]
| Constructor -> JObject ["type",JString "Constructor"]
| Destructor rw_rules ->
let projection_info = match rw_rules with
| [[Func({ cat = Tuple; _ } as f,args)], x] ->
let rec all_distinct_vars prev_vars = function
| [] -> true
| Var x::_ when List.memq x prev_vars -> false
| Var x::q -> all_distinct_vars (x::prev_vars) q
| _ -> false
in
let rec find_proj_number i = function
| [] -> raise Not_found
| y::_ when Term.is_equal x y -> i
| _::q -> find_proj_number (i+1) q
in
begin
try
if not (all_distinct_vars [] args)
then raise Not_found
else Some(get_symbol_id assoc f,find_proj_number 1 args)
with Not_found -> None
end
| _ -> None
in
match projection_info with
| None -> JObject [ "type", JString "Destructor"; "rewrite_rules", JList (List.map (of_rewrite_rule assoc) rw_rules)]
| Some(id_tuple,id_proj) ->
JObject [ "type", JString "Projection"; "tuple", JInt id_tuple; "projection_nb", JInt id_proj; "rewrite_rules", JList (List.map (of_rewrite_rule assoc) rw_rules)]
let of_position pos =
JObject [ "index", JInt pos.js_index; "args", JList (List.map (fun i -> JInt i) pos.js_args)]
(* Traces and processes *)
let of_json_process assoc proc =
let rec add_nil p label l =
if p = JNil
then l
else (label,explore p)::l
and explore = function
| JNil -> JObject [ "type", JNull ]
| JOutput(ch,t,p,pos) ->
let proc = add_nil p "process" [] in
JObject ([
"type", JString "Output";
"channel", of_term assoc ch;
"term", of_term assoc t;
"position", of_position pos
]@proc)
| JInput(ch,pat,p,pos) ->
let proc = add_nil p "process" [] in
JObject ([
"type", JString "Input";
"channel", of_term assoc ch;
"pattern", of_json_pattern assoc pat;
"position", of_position pos
]@proc)
| JIfThenElse(t1,t2,p1,p2,pos) ->
let procs = add_nil p1 "process_then" (add_nil p2 "process_else" []) in
JObject ([
"type", JString "IfThenElse";
"term1", of_term assoc t1;
"term2", of_term assoc t2;
"position", of_position pos
]@procs)
| JLet(pat,t,p1,p2,pos) ->
let procs = add_nil p1 "process_then" (add_nil p2 "process_else" []) in
JObject ([
"type", JString "LetInElse";
"pattern", of_json_pattern assoc pat;
"term", of_term assoc t;
"position", of_position pos
]@procs)
| JNew(n,_,p,pos) ->
let proc = add_nil p "process" [] in
let (id,args) = get_name_id assoc n in
let jlist =
if args = []
then [ "type", JString "New"; "name", JInt id; "position", of_position pos]
else [ "type", JString "New"; "name", JInt id; "bang", JList (List.map of_int args); "position", of_position pos]
in
JObject(jlist@proc)
| JPar p_list ->
JObject [
"type", JString "Par";
"process_list", JList (List.map explore p_list)
]
| JBang(i,p,pos) ->
let proc = add_nil p "process" [] in
JObject ([
"type", JString "Bang";
"multiplicity", JInt i;
"position", of_position pos
]@proc)
| JChoice(p1,p2,pos) ->
let procs = add_nil p1 "process1" (add_nil p2 "process2" []) in
JObject ([
"type", JString "Choice";
"position", of_position pos
]@procs)
in
explore proc
let of_transition assoc = function
| JAOutput(r,pos) ->
JObject [
"type", JString "output";
"channel", of_recipe assoc r;
"position", of_position pos
]
| JAInput(r_ch,r_t,pos) ->
JObject [
"type", JString "input";
"channel", of_recipe assoc r_ch;
"term", of_recipe assoc r_t;
"position", of_position pos
]
| JAComm(pos_out,pos_in) ->
JObject [
"type", JString "comm";
"input_position", of_position pos_in;
"output_position", of_position pos_out;
]
| JAEaves(r,pos_out,pos_in) ->
JObject [
"type", JString "eavesdrop";
"channel", of_recipe assoc r;
"input_position", of_position pos_in;
"output_position", of_position pos_out;
]
| JABang(n,pos) ->
JObject [
"type", JString "bang";
"position", of_position pos;
"nb_process_unfolded", JInt n
]
| JATau pos ->
JObject [
"type", JString "tau";
"position", of_position pos
]
| JAChoice(pos,choose_left) ->
if choose_left
then
JObject [
"type", JString "choice";
"position", of_position pos;
"choose_left", JBool true
]
else
JObject [
"type", JString "choice";
"position", of_position pos
]
let of_attack_trace assoc att_trace =
JObject [ "index_process", JInt att_trace.id_proc; "action_sequence", JList (List.map (of_transition assoc) att_trace.transitions) ]
Atomic data and association
let of_atomic_name n =
JObject [ "type", JString "Name"; "label", JString n.label_n; "index", JInt n.index_n ]
let of_atomic_symbol assoc f =
let jlist = [
"type", JString "Symbol";
"label", JString f.label_s;
"index", JInt f.index_s;
"arity", JInt f.arity;
"category", of_category assoc f.cat;
"representation", JString (match f.represents with UserName -> "UserName" | UserDefined -> "UserDefined" | _ -> "Attacker")
]
in
if f.public
then JObject (("is_public", JBool f.public)::jlist)
else JObject jlist
let of_atomic_variable x =
let jlist = [
"type", JString "Variable";
"label", JString x.label;
"index", JInt x.index
]
in
match x.quantifier with
| Free -> JObject (("free",JBool true)::jlist)
| Existential -> JObject jlist
| _ -> Config.internal_error "[display_ui.ml >> of_atomic_variable] Variables should not be universal."
let of_meta () =
let setting = Symbol.get_settings () in
JObject [
"number_symbols", JInt setting.Symbol.nb_symb;
"number_attacker_names", JInt setting.Symbol.nb_a;
"number_variables", JInt (Variable.get_counter ());
"number_names", JInt (Name.get_counter ())
]
let of_atomic_association assoc =
let tab_json = Array.make assoc.std.size JNull in
List.iter (fun (n,id) -> tab_json.(id) <- of_atomic_name n) assoc.std.names;
List.iter (fun (x,id) -> tab_json.(id) <- of_atomic_variable x) assoc.std.variables;
List.iter (fun (f,id) -> tab_json.(id) <- of_atomic_symbol assoc f) assoc.std.symbols;
JList (Array.to_list tab_json)
let of_atomic_data assoc =
JObject [
"meta", of_meta ();
"data", of_atomic_association assoc
]
(* Query result *)
let string_of_memory mem =
if mem / 1000000000 <> 0
then (string_of_int (mem / 1000000000))^"GB"
else if mem / 1000000 <> 0
then (string_of_int (mem / 1000000))^"MB"
else if mem / 1000 <> 0
then (string_of_int (mem / 1000))^"KB"
else (string_of_int mem)^" B"
let of_semantics = function
| Private -> JString "private"
| Eavesdrop -> JString "eavesdrop"
| Classic -> JString "classic"
let of_equivalence_type = function
| Trace_Equivalence -> JString "trace_equiv"
| Trace_Inclusion -> JString "trace_incl"
| Session_Equivalence -> JString "session_equiv"
| Session_Inclusion -> JString "session_incl"
let of_progression jlist = function
| PNot_defined -> jlist
| PSingleCore prog ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
("progression",JObject [ "round", JInt 0; label,obj ])::jlist
| PDistributed(round,prog) ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
("progression", JObject [ "round", JInt round; label,obj ])::jlist
(* We assume here that the association within [query_res]
contains at least the function symbols of the signature. *)
let of_query_result query_res =
let std_assoc = query_res.association in
let assoc = { std = std_assoc; repl = { repl_names = []; repl_variables = []}} in
let jlist1 = [
"atomic_data", of_atomic_data assoc;
"batch_file", JString query_res.q_batch_file;
"run_file", JString query_res.q_run_file;
"index", JInt query_res.q_index;
"semantics", of_semantics query_res.semantics;
"processes", JList (List.map (of_json_process assoc) query_res.processes);
"type", of_equivalence_type query_res.query_type
]
in
let jlist2 = of_option jlist1 of_int "start_time" query_res.q_start_time in
let jlist3 = of_option jlist2 of_int "end_time" query_res.q_end_time in
let jlist4 = match query_res.q_status with
| QCompleted att_trace_op ->
of_option (("status",JString "completed")::jlist3) (of_attack_trace assoc) "attack_trace" att_trace_op
| QIn_progress -> ("status",JString "in_progress")::jlist3
| QCanceled -> ("status",JString "canceled")::jlist3
| QInternal_error err -> ("status", JString "internal_error")::("error_msg", JString err)::jlist3
| QWaiting -> ("status",JString "waiting")::jlist3
in
let jlist5 = of_progression jlist4 query_res.progression in
let jlist6 =
if query_res.memory = 0
then jlist5
else ("memory",JInt query_res.memory)::jlist5
in
JObject jlist6
(* Run result *)
let of_run_batch_status json_list = function
| RBInternal_error err -> ("status", JString "internal_error")::("error_msg",JString err)::json_list
| RBCompleted -> ("status", JString "completed")::json_list
| RBIn_progress -> ("status", JString "in_progress")::json_list
| RBCanceled -> ("status", JString "canceled")::json_list
| RBWaiting -> ("status", JString "waiting")::json_list
let of_run_result run_res =
let jlist1 = [ "batch_file", JString run_res.r_batch_file ] in
let jlist2 = of_run_batch_status jlist1 run_res.r_status in
let jlist3 = of_option jlist2 of_string "input_file" run_res.input_file in
let jlist4 = of_option jlist3 of_string "input_str" run_res.input_str in
let jlist5 = of_option jlist4 of_int "start_time" run_res.r_start_time in
let jlist6 = of_option jlist5 of_int "end_time" run_res.r_end_time in
let jlist7 = of_option jlist6 (fun str_l -> JList (List.map of_string str_l)) "query_files" run_res.query_result_files in
let jlist8 = of_option jlist7 (fun qres_l -> JList (List.map of_query_result qres_l)) "query_results" run_res.query_results in
let jlist9 =
if run_res.warnings <> []
then ("warnings", JList (List.map of_string run_res.warnings))::jlist8
else jlist8
in
JObject jlist9
(* Batch result *)
let of_batch_options opt_list =
JObject (List.fold_left (fun acc options -> match options with
| Nb_jobs None -> ("nb_jobs", JString "auto")::acc
| Nb_jobs (Some n) -> ("nb_jobs", JInt n)::acc
| Round_timer n -> ("round_timer", JInt n)::acc
| Default_semantics sem -> ("default_semantics", of_semantics sem)::acc
| Distant_workers dist_l ->
let value =
List.map (fun (host,path,nb_opt) -> match nb_opt with
| None -> JObject [ "host", JString host; "path", JString path; "workers", JString "auto" ]
| Some nb -> JObject [ "host", JString host; "path", JString path; "workers", JInt nb ]
) dist_l
in
("distant_workers", JList value)::acc
| Distributed None -> ("distributed", JString "auto")::acc
| Distributed Some b -> ("distributed", JBool b)::acc
| Local_workers None -> ("local_workers", JString "auto")::acc
| Local_workers (Some n) -> ("local_workers", JInt n)::acc
| POR b -> ("por", JBool b)::acc
| Title s -> ("title", JString s)::acc
| _ -> acc
) [] opt_list)
let of_batch_result batch_res =
let title = ref None in
List.iter (function
| Title str -> title := Some str
| _ -> ()
) batch_res.command_options;
if !title = None
then
List.iter (function
| Title str -> title := Some str
| _ -> ()
) batch_res.command_options_cmp;
let jlist1 = [
"pid", JInt batch_res.pid;
"ocaml_version", JString batch_res.ocaml_version;
"deepsec_version", JString batch_res.deepsec_version;
"git_branch", JString batch_res.git_branch;
"git_hash", JString batch_res.git_hash;
"command_options", of_batch_options batch_res.command_options;
"computed_options", of_batch_options batch_res.command_options_cmp
]
in
let jlist2 = of_option jlist1 (fun str_l -> JList (List.map of_string str_l)) "run_files" batch_res.run_result_files in
let jlist3 = of_option jlist2 (fun res_l -> JList (List.map of_run_result res_l)) "run_results" batch_res.run_results in
let jlist4 = of_option jlist3 of_int "import_date" batch_res.import_date in
let jlist5 = of_run_batch_status jlist4 batch_res.b_status in
let jlist6 = of_option jlist5 of_int "start_time" batch_res.b_start_time in
let jlist7 = of_option jlist6 of_int "end_time" batch_res.b_end_time in
let jlist8 = of_option jlist7 of_string "title" !title in
let jlist9 = if batch_res.debug then ("debug", JBool true)::jlist8 else jlist8 in
JObject jlist9
(* Simulator *)
let of_available_transition assoc = function
| AVDirect(r_ch,r_t_op,lock) ->
let jlist1 = [ "locked", JBool lock ] in
let jlist2 = of_option jlist1 (of_recipe assoc) "recipe_term" r_t_op in
let jlist3 = ("type", JString "direct")::("recipe_channel", of_recipe assoc r_ch)::jlist2 in
JObject jlist3
| AVEavesdrop r -> JObject [ "type", JString "eavesdrop"; "recipe_channel", of_recipe assoc r]
| AVComm -> JObject [ "type", JString "comm" ]
let of_available_action assoc = function
| AV_output(pos,ch,tau_pos,av_trans) ->
JObject [
"type", JString "output";
"channel", of_term assoc ch;
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos);
"transitions", JList (List.map (of_available_transition assoc) av_trans)
]
| AV_input(pos,ch,tau_pos,av_trans) ->
JObject [
"type", JString "input";
"channel", of_term assoc ch;
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos);
"transitions", JList (List.map (of_available_transition assoc) av_trans)
]
| AV_bang(pos,n,tau_pos) ->
JObject [
"type", JString "bang";
"max_unfolding", JInt n;
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos)
]
| AV_choice(pos,tau_pos) ->
JObject [
"type", JString "choice";
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos)
]
| AV_tau pos ->
JObject [
"type", JString "tau";
"position", of_position pos
]
let of_status_static_equivalence assoc = function
| Static_equivalent -> JObject [ "status", JString "equivalent" ]
| Witness_message (r,t,id_proc) ->
JObject [
"status", JString "non_equivalent_message";
"recipe", of_recipe assoc r;
"term", of_term assoc t;
"process_id", JInt id_proc
]
| Witness_equality(r1,r2,t_eq,t1,t2,id_proc) ->
JObject [
"status", JString "non_equivalent_equality";
"recipe1", of_recipe assoc r1;
"recipe2", of_recipe assoc r2;
"term_equal", of_term assoc t_eq;
"term1", of_term assoc t1;
"term2", of_term assoc t2;
"process_id", JInt id_proc
]
(* Output commands *)
let of_output_command = function
(* Errors *)
| Init_internal_error (err,b) -> JObject [ "command", JString "init_error"; "is_internal", JBool b; "error_msg", JString (String.escaped err) ]
| Batch_internal_error err -> JObject [ "command", JString "batch_internal_error"; "error_msg", JString (String.escaped err) ]
| User_error (err_list,host_err) ->
JObject [
"command", JString "user_error";
"error_runs", JList (List.map (fun (err_msg,file,warnings) ->
JObject [ "error_msg", JString err_msg; "file", JString file; "warnings", JList (List.map of_string warnings) ]
) err_list);
"error_hosts", JList (List.map (fun (host,err_msgs) ->
JObject [ "host", JString host; "error_msgs", JList (List.map of_string err_msgs)]
) host_err)
]
| Query_internal_error (_,file) ->
JObject [
"command", JString "query_internal_error";
"file", JString file
]
| Send_Configuration ->
JObject [
"command", JString "config";
"version", JString Config.version;
"result_files_path", JString !Config.path_database
]
(* Started *)
| Batch_started(str,warnings) ->
JObject [
"command", JString "batch_started";
"file", JString str;
"warning_runs", JList (List.map (fun (file,_,warns) -> JObject [ "file", JString file; "warnings", JList (List.map of_string warns)]) warnings)
]
| Run_started(str,_) -> JObject [ "command", JString "run_started"; "file", JString str ]
| Query_started(str,_) -> JObject [ "command", JString "query_started"; "file", JString str ]
(* Ended *)
| Batch_ended (str,_) ->
JObject [ "command", JString "batch_ended"; "file", JString str ]
| Run_ended(str,_) ->
JObject [ "command", JString "run_ended"; "file", JString str ]
| Query_ended(str,_,_,_,_,_) -> JObject [ "command", JString "query_ended"; "file", JString str ]
| Progression(_,_,PNot_defined,_) -> Config.internal_error "[display_ui.ml >> of_output_command] Unexpected progression"
| Progression(_,_,PSingleCore prog,json) ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
JObject [ "command", JString "query_progression"; "round", JInt 0; label,obj; "file", JString json ]
| Progression(_,_,PDistributed(round,prog),json) ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
JObject [ "command", JString "query_progression"; "round", JInt round; label,obj; "file", JString json ]
| Query_canceled file -> JObject [ "command", JString "query_ended"; "file", JString file ]
| Run_canceled file -> JObject [ "command", JString "run_ended"; "file", JString file ]
| Batch_canceled file -> JObject [ "command", JString "batch_ended"; "file", JString file ]
(* Simulator: Generic command *)
| SCurrent_step_displayed (assoc,conf,priv_names,step,id_proc_op) ->
let jlist = of_option [] of_int "process_id" id_proc_op in
JObject ([
"command", JString "current_step_displayed";
"process", of_json_process assoc conf.process;
"frame", JList (List.map (of_term assoc) conf.frame);
"names", JList (List.map (of_name assoc) priv_names);
"current_action_id", JInt step
] @ jlist)
| SCurrent_step_user(assoc,conf,priv_names,new_trans,all_actions,default_actions,status_equiv_op,id_proc) ->
let jlist1 = of_option [] (of_status_static_equivalence assoc) "status_equiv" status_equiv_op in
let available_actions =
JObject [
"all", JList (List.map (of_available_action assoc) all_actions);
"default", JList (List.map (of_available_action assoc) default_actions)
]
in
let jlist2 =
[
"command", JString "current_step_user";
"process_id", JInt id_proc;
"process", of_json_process assoc conf.process;
"frame", JList (List.map (of_term assoc) conf.frame);
"names", JList (List.map (of_name assoc) priv_names);
"available_actions", available_actions
] @ jlist1
in
if new_trans = []
then JObject jlist2
else JObject (("new_actions", JList (List.map (of_transition assoc) new_trans))::jlist2)
| SFound_equivalent_trace(assoc,trans_list) ->
JObject [
"command", JString "found_equivalent_trace";
"action_sequence", JList (List.map (of_transition assoc) trans_list)
]
| SUser_error str -> JObject [ "command", JString "user_error"; "error_msg", JString str ]
let print_output_command = function
(* Errors *)
| Init_internal_error (err,false) ->
Printf.printf "\n%s: %s\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Error") err
| Init_internal_error (err,true)
| Batch_internal_error err
| Query_internal_error (err,_)->
Printf.printf "\n%s: %s\nPlease report the bug to with the input file and output\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Internal Error") err
| User_error (err_list,host_err) ->
List.iter (fun (err_msg,file,warnings) ->
Printf.printf "\n%s on file %s:\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Error") file;
Printf.printf " %s\n" err_msg;
if warnings <> []
then
begin
Printf.printf "\n%s on file %s:\n%!" (Display.coloured_terminal_text Yellow [Bold] "Warnings") file;
List.iter (fun str -> Printf.printf " %s\n%!" str) warnings
end
) err_list;
List.iter (fun (host,err_msgs) ->
Printf.printf "\n%s with distant server %s:\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Error") host;
List.iter (fun err ->
Printf.printf " %s\n%!" err
) err_msgs
) host_err
(* Started *)
| Batch_started(_,warning_runs) ->
Printf.printf "\nStarting verification...\n";
List.iter (fun (_,file,warnings) ->
if warnings <> []
then
begin
Printf.printf "\n%s on file %s:\n" (Display.coloured_terminal_text Yellow [Bold] "Warnings") file;
List.iter (fun str -> Printf.printf " %s\n" str) warnings
end
) warning_runs
| Run_started(_,name_dps) -> Printf.printf "\nStarting verification of %s...\n%!" name_dps
| Query_started(_,index) ->
if not !Config.quiet
then print_text false false (Printf.sprintf "Verifying query %d..." index)
(* Ended *)
| Batch_ended (_,status) ->
if status = RBCompleted
then Printf.printf "Verification complete.\n%!"
else if status = RBCanceled
then Printf.printf "\n%s\n%!" (coloured_terminal_text Red [Bold] "Verification canceled !")
| Run_ended _ -> ()
| Query_ended(_,status,index,time,memory,qtype) ->
let display_result text =
print_text true true (Printf.sprintf "Result query %d: %s. Verified in %s using %s of memory." index text (Display.mkRuntime time) (string_of_memory memory))
in
begin match status, qtype with
| QCompleted None, Trace_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Green [Bold] "trace equivalent"))
| QCompleted None, Trace_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Green [Bold] "trace included"))
| QCompleted None, Session_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Green [Bold] "session equivalent"))
| QCompleted None, Session_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Green [Bold] "session included"))
| QCompleted _, Trace_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Red [Bold] "not trace equivalent"))
| QCompleted _, Trace_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Red [Bold] "not trace included"))
| QCompleted _, Session_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Red [Bold] "not session equivalent"))
| QCompleted _, Session_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Red [Bold] "not session included"))
| _ -> ()
end
| Progression(_,_,PNot_defined,_) -> Config.internal_error "[display_ui.ml >> print_output_command] Unexpected progression"
| Progression(index,time,PSingleCore prog,_) ->
if not !Config.quiet
then
begin match prog with
| PVerif(percent,jobs) ->
let text = Printf.sprintf "Verifying query %d... [jobs verification: %d%% (%d jobs remaning); run time: %s]" index percent jobs (Display.mkRuntime time) in
print_text true false text
| PGeneration(jobs,min_jobs) ->
let text = Printf.sprintf "Verifying query %d... [jobs generation: %d; minimum nb of jobs required: %d; run time: %s]" index jobs min_jobs (Display.mkRuntime time) in
print_text true false text
end
| Progression(index,time,PDistributed(round, prog),_) ->
if not !Config.quiet
then
begin
match prog with
| PVerif(percent,jobs) ->
let text = Printf.sprintf "Verifying query %d... [round %d jobs verification:: %d%% (%d jobs remaning); run time: %s]" index round percent jobs (Display.mkRuntime time) in
print_text true false text
| PGeneration(jobs,min_jobs) ->
let text = Printf.sprintf "Verifying query %d... [round %d jobs generation: %d; minimum nb of jobs required: %d; run time: %s]" index round jobs min_jobs (Display.mkRuntime time) in
print_text true false text
end
| Query_canceled _
| Run_canceled _ -> Config.internal_error "[print_output_command] Should not occur"
| Batch_canceled _ -> Printf.printf "\n%s\n" (coloured_terminal_text Red [Bold] "Verification canceled !")
(* Simulator: Display_of_traces *)
| SCurrent_step_displayed _
| SCurrent_step_user _
| SFound_equivalent_trace _
| SUser_error _
| Send_Configuration -> Config.internal_error "[print_output_command] Should not occur in command mode."
(* Sending command *)
let keep_sending = ref true
let send_command json_str =
try
if !keep_sending
then
begin
output_string stdout (json_str^"\n");
flush stdout
end
with
| End_of_file ->
Config.log Config.Distribution (fun () -> "[display_ui.ml >> send_command] End of file caught");
keep_sending := false
| Sys_error _ ->
Config.log Config.Distribution (fun () -> "[display_ui.ml >> send_command] Sys_error caught");
keep_sending := false
let send_output_command out_cmd =
if !Config.running_api
then send_command (display_json (of_output_command out_cmd))
else print_output_command out_cmd
| null | https://raw.githubusercontent.com/DeepSec-prover/deepsec/8ddc45ec79de5ec49810302ea7da32d3dc9f46e4/Source/interface/display_ui.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of
file LICENSE
************************************************************************
** Specific print_text for dealing with return **
** Display **
* Display Verification Result *
** Record atomic data **
** Retrieving id of atomic data **
** Display of Json **
** Transformation of type to json **
Basic types
Traces and processes
Query result
We assume here that the association within [query_res]
contains at least the function symbols of the signature.
Run result
Batch result
Simulator
Output commands
Errors
Started
Ended
Simulator: Generic command
Errors
Started
Ended
Simulator: Display_of_traces
Sending command | DeepSec
, project PESTO ,
, project PESTO ,
, project PESTO ,
Copyright ( C ) INRIA 2017 - 2020
the GNU General Public License version 3.0 as described in the
open Term
open Types
open Types_ui
open Display
let print_text =
let previous_size = ref 0 in
let f return newline str =
let size = String.length str in
if return
then
let diff = !previous_size - size in
if diff > 0
then print_string ("\x0d"^str^(String.make (diff+10) ' '))
else print_string ("\x0d"^str^(String.make 10 ' '))
else print_string str;
if newline
then print_string "\n";
if newline
then previous_size := 0
else previous_size := size;
flush stdout
in
f
let display_with_tab n str =
let rec print_tab = function
| 0 -> ""
| n -> " "^(print_tab (n-1))
in
(print_tab n) ^ str ^"\n"
let display_position pos = Printf.sprintf "%d[%s]" pos.js_index (display_list string_of_int "," pos.js_args)
let display_transition = function
| JAOutput(r,pos) -> Printf.sprintf "out(%s,%s)" (Recipe.display Terminal r) (display_position pos)
| JAInput(r,r',pos) -> Printf.sprintf "in(%s,%s,%s)" (Recipe.display Terminal r) (Recipe.display Terminal r') (display_position pos)
| JAEaves(r,pos_out,pos_in) -> Printf.sprintf "eav(%s,%s,%s)" (Recipe.display Terminal r) (display_position pos_out) (display_position pos_in)
| JAComm(pos_out,pos_in) -> Printf.sprintf "comm(%s,%s)" (display_position pos_out) (display_position pos_in)
| JABang(n,pos) -> Printf.sprintf "bang(%d,%s)" n (display_position pos)
| JATau pos -> Printf.sprintf "tau(%s)" (display_position pos)
| JAChoice(pos,b) -> Printf.sprintf "choice(%s,%b)" (display_position pos) b
let rec display_pattern = function
| JPEquality t -> Printf.sprintf "=%s" (Term.display Terminal t)
| JPTuple(_,args) -> Printf.sprintf "%s%s%s" (langle Terminal) (display_list display_pattern "," args) (rangle Terminal)
| JPVar(x,_) -> Variable.display Terminal x
let rec display_process tab = function
| JNil -> (display_with_tab tab "Nil")
| JOutput(ch,t,p,pos) ->
let str = Printf.sprintf "{%s} out(%s,%s);" (display_position pos) (Term.display Terminal ch) (Term.display Terminal t) in
(display_with_tab tab str) ^ (display_process tab p)
| JInput(ch,pat,p,pos) ->
let str = Printf.sprintf "{%s} in(%s,%s);" (display_position pos) (Term.display Terminal ch) (display_pattern pat) in
(display_with_tab tab str) ^ (display_process tab p)
| JIfThenElse(t1,t2,pthen,JNil,pos) ->
let str = Printf.sprintf "{%s} if %s = %s then" (display_position pos) (Term.display Terminal t1) (Term.display Terminal t2) in
let str_then = display_process tab pthen in
(display_with_tab tab str) ^ str_then
| JIfThenElse(t1,t2,pthen,pelse,pos) ->
let str = Printf.sprintf "{%s} if %s = %s then" (display_position pos) (Term.display Terminal t1) (Term.display Terminal t2) in
let str_then = display_process (tab+1) pthen in
let str_else = display_process (tab+1) pelse in
let str_neg = "else" in
(display_with_tab tab str) ^ str_then ^ (display_with_tab tab str_neg) ^ str_else
| JLet(pat,t,pthen,JNil,pos) ->
let str = Printf.sprintf "{%s} let %s = %s in" (display_position pos) (display_pattern pat) (Term.display Terminal t) in
let str_then = display_process tab pthen in
(display_with_tab tab str) ^ str_then
| JLet(pat,t,pthen,pelse,pos) ->
let str = Printf.sprintf "{%s} let %s = %s in" (display_position pos) (display_pattern pat) (Term.display Terminal t) in
let str_then = display_process (tab+1) pthen in
let str_else = display_process (tab+1) pelse in
let str_neg = "else" in
(display_with_tab tab str) ^ str_then ^ (display_with_tab tab str_neg) ^ str_else
| JNew(n,_,p,pos) ->
let str = Printf.sprintf "{%s} new %s;" (display_position pos) (Name.display Terminal n) in
(display_with_tab tab str) ^ (display_process tab p)
| JPar p_list ->
(display_with_tab tab "(") ^
(display_list (display_process (tab+1)) (display_with_tab tab ") | (") p_list) ^
(display_with_tab tab ")")
| JBang(n,p,pos) ->
(display_with_tab tab (Printf.sprintf "{%s} !^%d" (display_position pos) n)) ^
(display_process tab p)
| JChoice(p1,p2,pos) ->
let str_1 = display_process (tab+1) p1 in
let str_2 = display_process (tab+1) p2 in
let str_plus = Printf.sprintf "{%s} +" (display_position pos) in
str_1 ^ (display_with_tab tab str_plus) ^ str_2
let display_association assoc =
let display_args id args = Printf.sprintf "%d[%s]" id (display_list string_of_int "," args) in
Printf.sprintf "Association (size = %d):\n%s\n%s\n%s\n%s\n%s\n"
assoc.std.size
("Symbols: "^(display_list (fun (f,n) -> Printf.sprintf "%s->%s" (Symbol.display Terminal f) (display_args n [])) "," assoc.std.symbols))
("Names: "^(display_list (fun (f,n) -> Printf.sprintf "%s->%s" (Name.display Terminal f) (display_args n [])) "," assoc.std.names))
("Variables: "^(display_list (fun (f,n) -> Printf.sprintf "%s->%s" (Variable.display Terminal f) (display_args n [])) "," assoc.std.variables))
("Repl Names: "^(display_list (fun (f,(n,args)) -> Printf.sprintf "%s->%s" (Name.display Terminal f) (display_args n args)) "," assoc.repl.repl_names))
("Repl Variables: "^(display_list (fun (f,(n,args)) -> Printf.sprintf "%s->%s" (Variable.display Terminal f) (display_args n args)) "," assoc.repl.repl_variables))
let display_verification_result result =
if !Config.running_api
then ()
else
let display_transitions trace =
let display_one_transition ax = function
| AOutput(r_ch,_) ->
incr ax;
Printf.sprintf "out(%s,ax_%d)" (Recipe.display ~display_context:false Terminal r_ch) !ax
| AInput(r_ch,r_t,_) -> Printf.sprintf "in(%s,%s)" (Recipe.display ~display_context:false Terminal r_ch) (Recipe.display ~display_context:false Terminal r_t)
| AEaves(r_ch,_,_) ->
incr ax;
Printf.sprintf "eav(%s,ax_%d)" (Recipe.display ~display_context:false Terminal r_ch) !ax
| _ -> Config.internal_error "[display_ui.ml >> display_verification_result] Unexpected transition."
in
let trace' = List.filter (function AOutput _ | AInput _ | AEaves _ -> true | _ -> false) trace in
if trace' = []
then varepsilon Terminal
else
begin
let ax = ref 0 in
let first = display_one_transition ax (List.hd trace') in
List.fold_left (fun acc trans ->
acc ^ ";" ^ (display_one_transition ax trans)
) first (List.tl trace')
end
in
match result with
| RTrace_Equivalence (Some (is_left,trace)) | RSession_Equivalence (Some (is_left,trace)) ->
print_text true true (Printf.sprintf "The following attack trace has been found on the %s process: %s"
(if is_left then "1st" else "2nd")
(display_transitions trace)
)
| RTrace_Inclusion (Some trace) | RSession_Inclusion (Some trace) ->
print_text true true (Printf.sprintf "The following attack trace has been found: %s"
(display_transitions trace)
)
| _ -> ()
let record_name assoc_ref n =
if not (List.exists (fun (n',_) -> n == n') (!assoc_ref).names)
then
let i = !assoc_ref.size in
assoc_ref := { !assoc_ref with size = i + 1; names = (n,i)::(!assoc_ref).names }
let record_symbol assoc_ref f =
if not (List.exists (fun (f',_) -> f == f') (!assoc_ref).symbols)
then
let i = !assoc_ref.size in
assoc_ref := { !assoc_ref with size = i + 1; symbols = (f,i)::(!assoc_ref).symbols }
let record_variable assoc_ref x =
if not (List.exists (fun (x',_) -> x == x') (!assoc_ref).variables)
then
let i = !assoc_ref.size in
assoc_ref := { !assoc_ref with size = i + 1; variables = (x,i)::(!assoc_ref).variables }
let rec record_from_term assoc_ref = function
| Var x -> record_variable assoc_ref x
| Name n -> record_name assoc_ref n
| Func(f,args) ->
record_symbol assoc_ref f;
List.iter (record_from_term assoc_ref) args
let rec record_from_pattern assoc_ref = function
| PatEquality t -> record_from_term assoc_ref t
| PatTuple(f,args) ->
record_symbol assoc_ref f;
List.iter (record_from_pattern assoc_ref) args
| PatVar x -> record_variable assoc_ref x
let record_from_category assoc_ref = function
| Tuple | Constructor -> ()
| Destructor rw_rules ->
List.iter (fun (lhs,rhs) ->
record_from_term assoc_ref rhs;
List.iter (record_from_term assoc_ref) lhs
) rw_rules
let record_from_full_symbol assoc_ref f =
record_symbol assoc_ref f;
record_from_category assoc_ref f.cat
let record_from_signature assoc_ref =
let setting = Symbol.get_settings () in
List.iter (record_from_full_symbol assoc_ref) setting.Symbol.all_c;
List.iter (fun (_,proj_l) ->
List.iter (record_from_full_symbol assoc_ref) proj_l
) setting.Symbol.all_p;
List.iter (record_from_full_symbol assoc_ref) setting.Symbol.all_d
Within bang , we only record the first process
let rec record_from_process assoc_ref = function
| Nil -> ()
| Output(ch,t,p,_) ->
record_from_term assoc_ref ch;
record_from_term assoc_ref t;
record_from_process assoc_ref p
| Input(ch,pat,p,_) ->
record_from_term assoc_ref ch;
record_from_pattern assoc_ref pat;
record_from_process assoc_ref p
| IfThenElse(t1,t2,p1,p2,_) ->
record_from_term assoc_ref t1;
record_from_term assoc_ref t2;
record_from_process assoc_ref p1;
record_from_process assoc_ref p2
| Let(pat,t,p1,p2,_) ->
record_from_term assoc_ref t;
record_from_pattern assoc_ref pat;
record_from_process assoc_ref p1;
record_from_process assoc_ref p2
| New(n,p,_) ->
record_name assoc_ref n;
record_from_process assoc_ref p
| Par p_list -> List.iter (record_from_process assoc_ref) p_list
| Bang([],_) -> Config.internal_error "[display_ui.ml >> record_from_process] Bang should at least contain one process."
| Bang(p::_,_) -> record_from_process assoc_ref p
| Choice(p1,p2,_) ->
record_from_process assoc_ref p1;
record_from_process assoc_ref p2
let get_name_id assoc n = match List.assq_opt n assoc.std.names with
| Some i -> i, []
| None ->
match List.assq_opt n assoc.repl.repl_names with
| Some (i,args) -> i,args
| None -> Config.internal_error (Printf.sprintf "[display_ui.ml >> get_name_id] Cannot find the name %s" (Name.display Terminal n))
let get_symbol_id assoc f = List.assq f assoc.std.symbols
let get_variable_id assoc x = match List.assq_opt x assoc.std.variables with
| Some i -> i, []
| None ->
match List.assq_opt x assoc.repl.repl_variables with
| Some (i,args) -> i,args
| None -> Config.internal_error (Printf.sprintf "[display_ui.ml >> get_variable_id] Cannot find the variable %s" (Variable.display Terminal x))
let rec display_json = function
| JString str -> "\""^str^"\""
| JBool b -> string_of_bool b
| JInt i -> string_of_int i
| JNull -> "null"
| JObject args ->
let args_str =
Display.display_list (fun (label,json) ->
Printf.sprintf "\"%s\":%s" label (display_json json)
) "," args
in
Printf.sprintf "{%s}" args_str
| JList json_l ->
Printf.sprintf "[%s]" (Display.display_list display_json "," json_l)
let of_option (obj_list:(string*json) list) (f_op:'a -> json) label = function
| None -> obj_list
| Some a -> (label,f_op a)::obj_list
let of_int i = JInt i
let of_string str = JString (String.escaped str)
let reg_proj = Str.regexp "proj_{\\([0-9]+\\),\\([0-9]+\\)}"
let of_name assoc n =
let (id,args) = get_name_id assoc n in
if args = []
then JObject [ "type", JString "Atomic"; "id", JInt id]
else JObject [ "type", JString "Atomic"; "id", JInt id; "bang", JList (List.map of_int args)]
let rec of_term assoc = function
| Var v ->
let (id,args) = get_variable_id assoc v in
if args = []
then JObject [ "type", JString "Atomic"; "id", JInt id]
else JObject [ "type", JString "Atomic"; "id", JInt id; "bang", JList (List.map of_int args)]
| Name n -> of_name assoc n
| Func({ represents = AttackerPublicName i; _},[]) when i >= 0 ->
JObject [ "type", JString "Attacker"; "label", JString ("#n_"^(string_of_int i)) ]
| Func({ represents = AttackerPublicName _; label_s = str; _},[]) ->
JObject [ "type", JString "Attacker"; "label", JString str ]
| Func(f,[]) ->
let id = get_symbol_id assoc f in
JObject [ "type", JString "Function"; "symbol", JInt id ]
| Func(f,args) when f.cat = Tuple ->
JObject [
"type", JString "Tuple";
"args", JList (List.map (of_term assoc) args)
]
| Func(f,args) ->
let id = get_symbol_id assoc f in
JObject [
"type", JString "Function";
"symbol", JInt id;
"args", JList (List.map (of_term assoc) args)
]
let rec of_recipe assoc = function
| CRFunc(_,r) -> of_recipe assoc r
| RFunc({ represents = AttackerPublicName i; _},[]) when i >= 0 ->
JObject [ "type", JString "Attacker"; "label", JString ("#n_"^(string_of_int i)) ]
| RFunc({ represents = AttackerPublicName _; label_s = str; _},[]) ->
JObject [ "type", JString "Attacker"; "label", JString str ]
| RFunc(f,[]) ->
let id = get_symbol_id assoc f in
JObject [ "type", JString "Function"; "symbol", JInt id ]
| RFunc(f,[r]) when Str.string_match reg_proj f.label_s 0 ->
let i1 = Str.matched_group 1 f.label_s in
let i2 = Str.matched_group 2 f.label_s in
JObject [
"type", JString "Proj";
"ith", JInt (int_of_string i1);
"arity_tuple", JInt (int_of_string i2);
"arg", of_recipe assoc r
]
| RFunc(f,args) when f.cat = Tuple ->
JObject [
"type", JString "Tuple";
"args", JList (List.map (of_recipe assoc) args)
]
| RFunc(f,args) ->
let id = get_symbol_id assoc f in
JObject [
"type", JString "Function";
"symbol", JInt id;
"args", JList (List.map (of_recipe assoc) args)
]
| Axiom i -> JObject [ "type", JString "Axiom"; "id", JInt i ]
| _ -> Config.internal_error "[interface.ml >> of_recipe] We should only display closed recipe."
let rec of_json_pattern assoc = function
| JPVar (v,id_rec) ->
let (id,args) = get_variable_id assoc v in
if id <> id_rec
then Config.internal_error "[display_ui.ml >> of_json_pattern] The recorded id and obtained id should be equal.";
if args = []
then JObject [ "type", JString "Atomic"; "id", JInt id]
else JObject [ "type", JString "Atomic"; "id", JInt id; "bang", JList (List.map of_int args)]
| JPEquality t -> JObject [ "type", JString "Equality"; "term", of_term assoc t]
| JPTuple(_,[]) -> Config.internal_error "[display_ui.ml >> of_json_pattern] Tuples cannot be of arity 0."
| JPTuple(_,args) ->
JObject [
"type", JString "Tuple";
"args", JList (List.map (of_json_pattern assoc) args)
]
let of_rewrite_rule assoc (lhs,rhs) =
JObject [ "lhs", JList (List.map (of_term assoc) lhs); "rhs", of_term assoc rhs]
let of_category assoc = function
| Tuple -> JObject ["type",JString "Tuple"]
| Constructor -> JObject ["type",JString "Constructor"]
| Destructor rw_rules ->
let projection_info = match rw_rules with
| [[Func({ cat = Tuple; _ } as f,args)], x] ->
let rec all_distinct_vars prev_vars = function
| [] -> true
| Var x::_ when List.memq x prev_vars -> false
| Var x::q -> all_distinct_vars (x::prev_vars) q
| _ -> false
in
let rec find_proj_number i = function
| [] -> raise Not_found
| y::_ when Term.is_equal x y -> i
| _::q -> find_proj_number (i+1) q
in
begin
try
if not (all_distinct_vars [] args)
then raise Not_found
else Some(get_symbol_id assoc f,find_proj_number 1 args)
with Not_found -> None
end
| _ -> None
in
match projection_info with
| None -> JObject [ "type", JString "Destructor"; "rewrite_rules", JList (List.map (of_rewrite_rule assoc) rw_rules)]
| Some(id_tuple,id_proj) ->
JObject [ "type", JString "Projection"; "tuple", JInt id_tuple; "projection_nb", JInt id_proj; "rewrite_rules", JList (List.map (of_rewrite_rule assoc) rw_rules)]
let of_position pos =
JObject [ "index", JInt pos.js_index; "args", JList (List.map (fun i -> JInt i) pos.js_args)]
let of_json_process assoc proc =
let rec add_nil p label l =
if p = JNil
then l
else (label,explore p)::l
and explore = function
| JNil -> JObject [ "type", JNull ]
| JOutput(ch,t,p,pos) ->
let proc = add_nil p "process" [] in
JObject ([
"type", JString "Output";
"channel", of_term assoc ch;
"term", of_term assoc t;
"position", of_position pos
]@proc)
| JInput(ch,pat,p,pos) ->
let proc = add_nil p "process" [] in
JObject ([
"type", JString "Input";
"channel", of_term assoc ch;
"pattern", of_json_pattern assoc pat;
"position", of_position pos
]@proc)
| JIfThenElse(t1,t2,p1,p2,pos) ->
let procs = add_nil p1 "process_then" (add_nil p2 "process_else" []) in
JObject ([
"type", JString "IfThenElse";
"term1", of_term assoc t1;
"term2", of_term assoc t2;
"position", of_position pos
]@procs)
| JLet(pat,t,p1,p2,pos) ->
let procs = add_nil p1 "process_then" (add_nil p2 "process_else" []) in
JObject ([
"type", JString "LetInElse";
"pattern", of_json_pattern assoc pat;
"term", of_term assoc t;
"position", of_position pos
]@procs)
| JNew(n,_,p,pos) ->
let proc = add_nil p "process" [] in
let (id,args) = get_name_id assoc n in
let jlist =
if args = []
then [ "type", JString "New"; "name", JInt id; "position", of_position pos]
else [ "type", JString "New"; "name", JInt id; "bang", JList (List.map of_int args); "position", of_position pos]
in
JObject(jlist@proc)
| JPar p_list ->
JObject [
"type", JString "Par";
"process_list", JList (List.map explore p_list)
]
| JBang(i,p,pos) ->
let proc = add_nil p "process" [] in
JObject ([
"type", JString "Bang";
"multiplicity", JInt i;
"position", of_position pos
]@proc)
| JChoice(p1,p2,pos) ->
let procs = add_nil p1 "process1" (add_nil p2 "process2" []) in
JObject ([
"type", JString "Choice";
"position", of_position pos
]@procs)
in
explore proc
let of_transition assoc = function
| JAOutput(r,pos) ->
JObject [
"type", JString "output";
"channel", of_recipe assoc r;
"position", of_position pos
]
| JAInput(r_ch,r_t,pos) ->
JObject [
"type", JString "input";
"channel", of_recipe assoc r_ch;
"term", of_recipe assoc r_t;
"position", of_position pos
]
| JAComm(pos_out,pos_in) ->
JObject [
"type", JString "comm";
"input_position", of_position pos_in;
"output_position", of_position pos_out;
]
| JAEaves(r,pos_out,pos_in) ->
JObject [
"type", JString "eavesdrop";
"channel", of_recipe assoc r;
"input_position", of_position pos_in;
"output_position", of_position pos_out;
]
| JABang(n,pos) ->
JObject [
"type", JString "bang";
"position", of_position pos;
"nb_process_unfolded", JInt n
]
| JATau pos ->
JObject [
"type", JString "tau";
"position", of_position pos
]
| JAChoice(pos,choose_left) ->
if choose_left
then
JObject [
"type", JString "choice";
"position", of_position pos;
"choose_left", JBool true
]
else
JObject [
"type", JString "choice";
"position", of_position pos
]
let of_attack_trace assoc att_trace =
JObject [ "index_process", JInt att_trace.id_proc; "action_sequence", JList (List.map (of_transition assoc) att_trace.transitions) ]
Atomic data and association
let of_atomic_name n =
JObject [ "type", JString "Name"; "label", JString n.label_n; "index", JInt n.index_n ]
let of_atomic_symbol assoc f =
let jlist = [
"type", JString "Symbol";
"label", JString f.label_s;
"index", JInt f.index_s;
"arity", JInt f.arity;
"category", of_category assoc f.cat;
"representation", JString (match f.represents with UserName -> "UserName" | UserDefined -> "UserDefined" | _ -> "Attacker")
]
in
if f.public
then JObject (("is_public", JBool f.public)::jlist)
else JObject jlist
let of_atomic_variable x =
let jlist = [
"type", JString "Variable";
"label", JString x.label;
"index", JInt x.index
]
in
match x.quantifier with
| Free -> JObject (("free",JBool true)::jlist)
| Existential -> JObject jlist
| _ -> Config.internal_error "[display_ui.ml >> of_atomic_variable] Variables should not be universal."
let of_meta () =
let setting = Symbol.get_settings () in
JObject [
"number_symbols", JInt setting.Symbol.nb_symb;
"number_attacker_names", JInt setting.Symbol.nb_a;
"number_variables", JInt (Variable.get_counter ());
"number_names", JInt (Name.get_counter ())
]
let of_atomic_association assoc =
let tab_json = Array.make assoc.std.size JNull in
List.iter (fun (n,id) -> tab_json.(id) <- of_atomic_name n) assoc.std.names;
List.iter (fun (x,id) -> tab_json.(id) <- of_atomic_variable x) assoc.std.variables;
List.iter (fun (f,id) -> tab_json.(id) <- of_atomic_symbol assoc f) assoc.std.symbols;
JList (Array.to_list tab_json)
let of_atomic_data assoc =
JObject [
"meta", of_meta ();
"data", of_atomic_association assoc
]
let string_of_memory mem =
if mem / 1000000000 <> 0
then (string_of_int (mem / 1000000000))^"GB"
else if mem / 1000000 <> 0
then (string_of_int (mem / 1000000))^"MB"
else if mem / 1000 <> 0
then (string_of_int (mem / 1000))^"KB"
else (string_of_int mem)^" B"
let of_semantics = function
| Private -> JString "private"
| Eavesdrop -> JString "eavesdrop"
| Classic -> JString "classic"
let of_equivalence_type = function
| Trace_Equivalence -> JString "trace_equiv"
| Trace_Inclusion -> JString "trace_incl"
| Session_Equivalence -> JString "session_equiv"
| Session_Inclusion -> JString "session_incl"
let of_progression jlist = function
| PNot_defined -> jlist
| PSingleCore prog ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
("progression",JObject [ "round", JInt 0; label,obj ])::jlist
| PDistributed(round,prog) ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
("progression", JObject [ "round", JInt round; label,obj ])::jlist
let of_query_result query_res =
let std_assoc = query_res.association in
let assoc = { std = std_assoc; repl = { repl_names = []; repl_variables = []}} in
let jlist1 = [
"atomic_data", of_atomic_data assoc;
"batch_file", JString query_res.q_batch_file;
"run_file", JString query_res.q_run_file;
"index", JInt query_res.q_index;
"semantics", of_semantics query_res.semantics;
"processes", JList (List.map (of_json_process assoc) query_res.processes);
"type", of_equivalence_type query_res.query_type
]
in
let jlist2 = of_option jlist1 of_int "start_time" query_res.q_start_time in
let jlist3 = of_option jlist2 of_int "end_time" query_res.q_end_time in
let jlist4 = match query_res.q_status with
| QCompleted att_trace_op ->
of_option (("status",JString "completed")::jlist3) (of_attack_trace assoc) "attack_trace" att_trace_op
| QIn_progress -> ("status",JString "in_progress")::jlist3
| QCanceled -> ("status",JString "canceled")::jlist3
| QInternal_error err -> ("status", JString "internal_error")::("error_msg", JString err)::jlist3
| QWaiting -> ("status",JString "waiting")::jlist3
in
let jlist5 = of_progression jlist4 query_res.progression in
let jlist6 =
if query_res.memory = 0
then jlist5
else ("memory",JInt query_res.memory)::jlist5
in
JObject jlist6
let of_run_batch_status json_list = function
| RBInternal_error err -> ("status", JString "internal_error")::("error_msg",JString err)::json_list
| RBCompleted -> ("status", JString "completed")::json_list
| RBIn_progress -> ("status", JString "in_progress")::json_list
| RBCanceled -> ("status", JString "canceled")::json_list
| RBWaiting -> ("status", JString "waiting")::json_list
let of_run_result run_res =
let jlist1 = [ "batch_file", JString run_res.r_batch_file ] in
let jlist2 = of_run_batch_status jlist1 run_res.r_status in
let jlist3 = of_option jlist2 of_string "input_file" run_res.input_file in
let jlist4 = of_option jlist3 of_string "input_str" run_res.input_str in
let jlist5 = of_option jlist4 of_int "start_time" run_res.r_start_time in
let jlist6 = of_option jlist5 of_int "end_time" run_res.r_end_time in
let jlist7 = of_option jlist6 (fun str_l -> JList (List.map of_string str_l)) "query_files" run_res.query_result_files in
let jlist8 = of_option jlist7 (fun qres_l -> JList (List.map of_query_result qres_l)) "query_results" run_res.query_results in
let jlist9 =
if run_res.warnings <> []
then ("warnings", JList (List.map of_string run_res.warnings))::jlist8
else jlist8
in
JObject jlist9
let of_batch_options opt_list =
JObject (List.fold_left (fun acc options -> match options with
| Nb_jobs None -> ("nb_jobs", JString "auto")::acc
| Nb_jobs (Some n) -> ("nb_jobs", JInt n)::acc
| Round_timer n -> ("round_timer", JInt n)::acc
| Default_semantics sem -> ("default_semantics", of_semantics sem)::acc
| Distant_workers dist_l ->
let value =
List.map (fun (host,path,nb_opt) -> match nb_opt with
| None -> JObject [ "host", JString host; "path", JString path; "workers", JString "auto" ]
| Some nb -> JObject [ "host", JString host; "path", JString path; "workers", JInt nb ]
) dist_l
in
("distant_workers", JList value)::acc
| Distributed None -> ("distributed", JString "auto")::acc
| Distributed Some b -> ("distributed", JBool b)::acc
| Local_workers None -> ("local_workers", JString "auto")::acc
| Local_workers (Some n) -> ("local_workers", JInt n)::acc
| POR b -> ("por", JBool b)::acc
| Title s -> ("title", JString s)::acc
| _ -> acc
) [] opt_list)
let of_batch_result batch_res =
let title = ref None in
List.iter (function
| Title str -> title := Some str
| _ -> ()
) batch_res.command_options;
if !title = None
then
List.iter (function
| Title str -> title := Some str
| _ -> ()
) batch_res.command_options_cmp;
let jlist1 = [
"pid", JInt batch_res.pid;
"ocaml_version", JString batch_res.ocaml_version;
"deepsec_version", JString batch_res.deepsec_version;
"git_branch", JString batch_res.git_branch;
"git_hash", JString batch_res.git_hash;
"command_options", of_batch_options batch_res.command_options;
"computed_options", of_batch_options batch_res.command_options_cmp
]
in
let jlist2 = of_option jlist1 (fun str_l -> JList (List.map of_string str_l)) "run_files" batch_res.run_result_files in
let jlist3 = of_option jlist2 (fun res_l -> JList (List.map of_run_result res_l)) "run_results" batch_res.run_results in
let jlist4 = of_option jlist3 of_int "import_date" batch_res.import_date in
let jlist5 = of_run_batch_status jlist4 batch_res.b_status in
let jlist6 = of_option jlist5 of_int "start_time" batch_res.b_start_time in
let jlist7 = of_option jlist6 of_int "end_time" batch_res.b_end_time in
let jlist8 = of_option jlist7 of_string "title" !title in
let jlist9 = if batch_res.debug then ("debug", JBool true)::jlist8 else jlist8 in
JObject jlist9
let of_available_transition assoc = function
| AVDirect(r_ch,r_t_op,lock) ->
let jlist1 = [ "locked", JBool lock ] in
let jlist2 = of_option jlist1 (of_recipe assoc) "recipe_term" r_t_op in
let jlist3 = ("type", JString "direct")::("recipe_channel", of_recipe assoc r_ch)::jlist2 in
JObject jlist3
| AVEavesdrop r -> JObject [ "type", JString "eavesdrop"; "recipe_channel", of_recipe assoc r]
| AVComm -> JObject [ "type", JString "comm" ]
let of_available_action assoc = function
| AV_output(pos,ch,tau_pos,av_trans) ->
JObject [
"type", JString "output";
"channel", of_term assoc ch;
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos);
"transitions", JList (List.map (of_available_transition assoc) av_trans)
]
| AV_input(pos,ch,tau_pos,av_trans) ->
JObject [
"type", JString "input";
"channel", of_term assoc ch;
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos);
"transitions", JList (List.map (of_available_transition assoc) av_trans)
]
| AV_bang(pos,n,tau_pos) ->
JObject [
"type", JString "bang";
"max_unfolding", JInt n;
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos)
]
| AV_choice(pos,tau_pos) ->
JObject [
"type", JString "choice";
"position", of_position pos;
"tau_positions", JList (List.map of_position tau_pos)
]
| AV_tau pos ->
JObject [
"type", JString "tau";
"position", of_position pos
]
let of_status_static_equivalence assoc = function
| Static_equivalent -> JObject [ "status", JString "equivalent" ]
| Witness_message (r,t,id_proc) ->
JObject [
"status", JString "non_equivalent_message";
"recipe", of_recipe assoc r;
"term", of_term assoc t;
"process_id", JInt id_proc
]
| Witness_equality(r1,r2,t_eq,t1,t2,id_proc) ->
JObject [
"status", JString "non_equivalent_equality";
"recipe1", of_recipe assoc r1;
"recipe2", of_recipe assoc r2;
"term_equal", of_term assoc t_eq;
"term1", of_term assoc t1;
"term2", of_term assoc t2;
"process_id", JInt id_proc
]
let of_output_command = function
| Init_internal_error (err,b) -> JObject [ "command", JString "init_error"; "is_internal", JBool b; "error_msg", JString (String.escaped err) ]
| Batch_internal_error err -> JObject [ "command", JString "batch_internal_error"; "error_msg", JString (String.escaped err) ]
| User_error (err_list,host_err) ->
JObject [
"command", JString "user_error";
"error_runs", JList (List.map (fun (err_msg,file,warnings) ->
JObject [ "error_msg", JString err_msg; "file", JString file; "warnings", JList (List.map of_string warnings) ]
) err_list);
"error_hosts", JList (List.map (fun (host,err_msgs) ->
JObject [ "host", JString host; "error_msgs", JList (List.map of_string err_msgs)]
) host_err)
]
| Query_internal_error (_,file) ->
JObject [
"command", JString "query_internal_error";
"file", JString file
]
| Send_Configuration ->
JObject [
"command", JString "config";
"version", JString Config.version;
"result_files_path", JString !Config.path_database
]
| Batch_started(str,warnings) ->
JObject [
"command", JString "batch_started";
"file", JString str;
"warning_runs", JList (List.map (fun (file,_,warns) -> JObject [ "file", JString file; "warnings", JList (List.map of_string warns)]) warnings)
]
| Run_started(str,_) -> JObject [ "command", JString "run_started"; "file", JString str ]
| Query_started(str,_) -> JObject [ "command", JString "query_started"; "file", JString str ]
| Batch_ended (str,_) ->
JObject [ "command", JString "batch_ended"; "file", JString str ]
| Run_ended(str,_) ->
JObject [ "command", JString "run_ended"; "file", JString str ]
| Query_ended(str,_,_,_,_,_) -> JObject [ "command", JString "query_ended"; "file", JString str ]
| Progression(_,_,PNot_defined,_) -> Config.internal_error "[display_ui.ml >> of_output_command] Unexpected progression"
| Progression(_,_,PSingleCore prog,json) ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
JObject [ "command", JString "query_progression"; "round", JInt 0; label,obj; "file", JString json ]
| Progression(_,_,PDistributed(round,prog),json) ->
let (label,obj) = match prog with
| PVerif(percent,jobs) -> ("verification",JObject [ "percent", JInt percent; "jobs_remaining", JInt jobs ])
| PGeneration(jobs,min_jobs) -> ("generation", JObject [ "minimum_jobs", JInt min_jobs; "jobs_created", JInt jobs ])
in
JObject [ "command", JString "query_progression"; "round", JInt round; label,obj; "file", JString json ]
| Query_canceled file -> JObject [ "command", JString "query_ended"; "file", JString file ]
| Run_canceled file -> JObject [ "command", JString "run_ended"; "file", JString file ]
| Batch_canceled file -> JObject [ "command", JString "batch_ended"; "file", JString file ]
| SCurrent_step_displayed (assoc,conf,priv_names,step,id_proc_op) ->
let jlist = of_option [] of_int "process_id" id_proc_op in
JObject ([
"command", JString "current_step_displayed";
"process", of_json_process assoc conf.process;
"frame", JList (List.map (of_term assoc) conf.frame);
"names", JList (List.map (of_name assoc) priv_names);
"current_action_id", JInt step
] @ jlist)
| SCurrent_step_user(assoc,conf,priv_names,new_trans,all_actions,default_actions,status_equiv_op,id_proc) ->
let jlist1 = of_option [] (of_status_static_equivalence assoc) "status_equiv" status_equiv_op in
let available_actions =
JObject [
"all", JList (List.map (of_available_action assoc) all_actions);
"default", JList (List.map (of_available_action assoc) default_actions)
]
in
let jlist2 =
[
"command", JString "current_step_user";
"process_id", JInt id_proc;
"process", of_json_process assoc conf.process;
"frame", JList (List.map (of_term assoc) conf.frame);
"names", JList (List.map (of_name assoc) priv_names);
"available_actions", available_actions
] @ jlist1
in
if new_trans = []
then JObject jlist2
else JObject (("new_actions", JList (List.map (of_transition assoc) new_trans))::jlist2)
| SFound_equivalent_trace(assoc,trans_list) ->
JObject [
"command", JString "found_equivalent_trace";
"action_sequence", JList (List.map (of_transition assoc) trans_list)
]
| SUser_error str -> JObject [ "command", JString "user_error"; "error_msg", JString str ]
let print_output_command = function
| Init_internal_error (err,false) ->
Printf.printf "\n%s: %s\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Error") err
| Init_internal_error (err,true)
| Batch_internal_error err
| Query_internal_error (err,_)->
Printf.printf "\n%s: %s\nPlease report the bug to with the input file and output\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Internal Error") err
| User_error (err_list,host_err) ->
List.iter (fun (err_msg,file,warnings) ->
Printf.printf "\n%s on file %s:\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Error") file;
Printf.printf " %s\n" err_msg;
if warnings <> []
then
begin
Printf.printf "\n%s on file %s:\n%!" (Display.coloured_terminal_text Yellow [Bold] "Warnings") file;
List.iter (fun str -> Printf.printf " %s\n%!" str) warnings
end
) err_list;
List.iter (fun (host,err_msgs) ->
Printf.printf "\n%s with distant server %s:\n%!" (Display.coloured_terminal_text Red [Underline;Bold] "Error") host;
List.iter (fun err ->
Printf.printf " %s\n%!" err
) err_msgs
) host_err
| Batch_started(_,warning_runs) ->
Printf.printf "\nStarting verification...\n";
List.iter (fun (_,file,warnings) ->
if warnings <> []
then
begin
Printf.printf "\n%s on file %s:\n" (Display.coloured_terminal_text Yellow [Bold] "Warnings") file;
List.iter (fun str -> Printf.printf " %s\n" str) warnings
end
) warning_runs
| Run_started(_,name_dps) -> Printf.printf "\nStarting verification of %s...\n%!" name_dps
| Query_started(_,index) ->
if not !Config.quiet
then print_text false false (Printf.sprintf "Verifying query %d..." index)
| Batch_ended (_,status) ->
if status = RBCompleted
then Printf.printf "Verification complete.\n%!"
else if status = RBCanceled
then Printf.printf "\n%s\n%!" (coloured_terminal_text Red [Bold] "Verification canceled !")
| Run_ended _ -> ()
| Query_ended(_,status,index,time,memory,qtype) ->
let display_result text =
print_text true true (Printf.sprintf "Result query %d: %s. Verified in %s using %s of memory." index text (Display.mkRuntime time) (string_of_memory memory))
in
begin match status, qtype with
| QCompleted None, Trace_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Green [Bold] "trace equivalent"))
| QCompleted None, Trace_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Green [Bold] "trace included"))
| QCompleted None, Session_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Green [Bold] "session equivalent"))
| QCompleted None, Session_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Green [Bold] "session included"))
| QCompleted _, Trace_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Red [Bold] "not trace equivalent"))
| QCompleted _, Trace_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Red [Bold] "not trace included"))
| QCompleted _, Session_Equivalence -> display_result (Printf.sprintf "The two processes are %s" (Display.coloured_terminal_text Red [Bold] "not session equivalent"))
| QCompleted _, Session_Inclusion -> display_result (Printf.sprintf "Process 1 is %s in process 2" (Display.coloured_terminal_text Red [Bold] "not session included"))
| _ -> ()
end
| Progression(_,_,PNot_defined,_) -> Config.internal_error "[display_ui.ml >> print_output_command] Unexpected progression"
| Progression(index,time,PSingleCore prog,_) ->
if not !Config.quiet
then
begin match prog with
| PVerif(percent,jobs) ->
let text = Printf.sprintf "Verifying query %d... [jobs verification: %d%% (%d jobs remaning); run time: %s]" index percent jobs (Display.mkRuntime time) in
print_text true false text
| PGeneration(jobs,min_jobs) ->
let text = Printf.sprintf "Verifying query %d... [jobs generation: %d; minimum nb of jobs required: %d; run time: %s]" index jobs min_jobs (Display.mkRuntime time) in
print_text true false text
end
| Progression(index,time,PDistributed(round, prog),_) ->
if not !Config.quiet
then
begin
match prog with
| PVerif(percent,jobs) ->
let text = Printf.sprintf "Verifying query %d... [round %d jobs verification:: %d%% (%d jobs remaning); run time: %s]" index round percent jobs (Display.mkRuntime time) in
print_text true false text
| PGeneration(jobs,min_jobs) ->
let text = Printf.sprintf "Verifying query %d... [round %d jobs generation: %d; minimum nb of jobs required: %d; run time: %s]" index round jobs min_jobs (Display.mkRuntime time) in
print_text true false text
end
| Query_canceled _
| Run_canceled _ -> Config.internal_error "[print_output_command] Should not occur"
| Batch_canceled _ -> Printf.printf "\n%s\n" (coloured_terminal_text Red [Bold] "Verification canceled !")
| SCurrent_step_displayed _
| SCurrent_step_user _
| SFound_equivalent_trace _
| SUser_error _
| Send_Configuration -> Config.internal_error "[print_output_command] Should not occur in command mode."
let keep_sending = ref true
let send_command json_str =
try
if !keep_sending
then
begin
output_string stdout (json_str^"\n");
flush stdout
end
with
| End_of_file ->
Config.log Config.Distribution (fun () -> "[display_ui.ml >> send_command] End of file caught");
keep_sending := false
| Sys_error _ ->
Config.log Config.Distribution (fun () -> "[display_ui.ml >> send_command] Sys_error caught");
keep_sending := false
let send_output_command out_cmd =
if !Config.running_api
then send_command (display_json (of_output_command out_cmd))
else print_output_command out_cmd
|
7f27bccd95b3d67a297f059330dd7a9efe1caa748d68dd680b4f3933482182f0 | jimcrayne/jhc | tc165.hs | # OPTIONS -dcore - lint
Fails GHC 5.04.2 with -dcore - lint
-- The issue ariseswhen you have a method that
-- constrains a class variable
module Test where
class C a where
f :: (Eq a) => a
instance C () where
f = f
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/regress/tests/1_typecheck/2_pass/ghc/tc165.hs | haskell | The issue ariseswhen you have a method that
constrains a class variable | # OPTIONS -dcore - lint
Fails GHC 5.04.2 with -dcore - lint
module Test where
class C a where
f :: (Eq a) => a
instance C () where
f = f
|
7f46e39f133fa7d742d29ff7af588c505907532d5638e9f9799913999a7b9e0f | ocaml-flambda/flambda-backend | dont_unbox_exn.ml | exception FoundAt of int
external opaque : 'a -> 'a = "%opaque"
external raise : exn -> 'a = "%raise"
let test () =
try
if opaque false then raise (FoundAt (if opaque false then 1 else 2));
0
with FoundAt i -> i
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/92dbdba868235321a48916b8f1bb3f04ee884d3f/middle_end/flambda2/tests/ref_to_var/dont_unbox_exn.ml | ocaml | exception FoundAt of int
external opaque : 'a -> 'a = "%opaque"
external raise : exn -> 'a = "%raise"
let test () =
try
if opaque false then raise (FoundAt (if opaque false then 1 else 2));
0
with FoundAt i -> i
|
|
e58cb4617395bcb1d5f5042745b87f86823b09bb1ab48b89428d7b85d4ca9821 | Workiva/eva | clojure_test_ext.clj | Copyright 2015 - 2019 Workiva Inc.
;;
;; Licensed under the Eclipse Public License 1.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -1.0.php
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns eva.test.clojure-test-ext
"Provides extensions to clojure.test"
(:require [clojure.test :refer :all]))
;; Allows you to test for an exception along with its cause.
This is particularly useful when dealing with ExecutionExceptions :
;;
;; ```
;; (is (thrown-with-cause? ExecutionException IllegalArgumentException
@(future ( throw ( IllegalArgumentException . ) )
;; ```
(defmethod assert-expr 'thrown-with-cause? [msg form]
(let [outer-klass (nth form 1)
inner-klass (nth form 2)
body (nthnext form 3)]
`(try ~@body
(do-report {:type :fail, :message ~msg
:expected '~form :actual nil})
(catch ~outer-klass e#
(if (instance? ~inner-klass (.getCause e#))
(do-report {:type :pass, :message ~msg
:expected '~form, :actual (.getCause e#)})
(do-report {:type :fail, :message ~msg,
:expected '~form, :actual (.getCause e#)}))
(.getCause e#)))))
| null | https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/core/test/eva/test/clojure_test_ext.clj | clojure |
Licensed under the Eclipse Public License 1.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-1.0.php
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.
Allows you to test for an exception along with its cause.
```
(is (thrown-with-cause? ExecutionException IllegalArgumentException
``` | Copyright 2015 - 2019 Workiva Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
(ns eva.test.clojure-test-ext
"Provides extensions to clojure.test"
(:require [clojure.test :refer :all]))
This is particularly useful when dealing with ExecutionExceptions :
@(future ( throw ( IllegalArgumentException . ) )
(defmethod assert-expr 'thrown-with-cause? [msg form]
(let [outer-klass (nth form 1)
inner-klass (nth form 2)
body (nthnext form 3)]
`(try ~@body
(do-report {:type :fail, :message ~msg
:expected '~form :actual nil})
(catch ~outer-klass e#
(if (instance? ~inner-klass (.getCause e#))
(do-report {:type :pass, :message ~msg
:expected '~form, :actual (.getCause e#)})
(do-report {:type :fail, :message ~msg,
:expected '~form, :actual (.getCause e#)}))
(.getCause e#)))))
|
1109dd0415c4410a969f1cbbadb8f8af339228ebe74813da4679a5020f87e86a | fogfish/datum | tree_SUITE.erl | %%
Copyright ( c ) 2017 ,
%% All Rights Reserved.
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
-module(tree_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("datum/include/datum.hrl").
-compile({parse_transform, category}).
-compile({no_auto_import,[apply/2]}).
%%
%% common test
-export([
all/0
,groups/0
,init_per_suite/1
,end_per_suite/1
,init_per_group/2
,end_per_group/2
]).
-export([
new/1,
empty/1,
append/1,
insert/1,
lookup/1,
remove/1,
has/1,
keys/1,
apply/1,
build/1,
drop/1,
dropwhile/1,
filter/1,
foreach/1,
map/1,
split/1,
splitwhile/1,
take/1,
takewhile/1,
% fold/1,
% foldl/1,
% foldr/1,
% unfold/1,
min/1,
max/1
]).
%%%----------------------------------------------------------------------------
%%%
%%% suite
%%%
%%%----------------------------------------------------------------------------
all() ->
[
{group, bst},
{group, rbtree}
].
groups() ->
[
{bst, [parallel],
[new, empty,
append, insert, lookup, remove, has, keys, apply,
build, drop, dropwhile, filter, foreach, map, split, splitwhile, take, takewhile,
fold , foldl , foldr , unfold , min , ] } ,
min, max]},
{rbtree, [parallel],
[new, empty,
append, insert, lookup, remove, has, keys, apply,
build, drop, dropwhile, filter, foreach, map, split, splitwhile, take, takewhile,
fold , foldl , foldr , unfold , min , ] }
min, max]}
].
%%%----------------------------------------------------------------------------
%%%
%%% init
%%%
%%%----------------------------------------------------------------------------
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
%%
%%
init_per_group(Type, Config) ->
[{type, Type}|Config].
end_per_group(_, _Config) ->
ok.
%%%----------------------------------------------------------------------------
%%%
%%% tree primitives
%%%
%%%----------------------------------------------------------------------------
-define(LENGTH, 100).
new(Config) ->
Type = ?config(type, Config),
tree = erlang:element(1, Type:new()).
empty(Config) ->
Type = ?config(type, Config),
?tree() = Type:new().
append(Config) ->
Type = ?config(type, Config),
[{1,1}] = Type:list(Type:append({1,1}, Type:new())).
insert(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Lens = fun({Key, Val}, Acc) -> Type:insert(Key, Val, Acc) end,
Tree = lists:foldl(Lens, Type:new(), List),
lists:foreach(
fun({Key, Val}) ->
Val = Type:lookup(Key, Tree)
end,
shuffle(List)
).
lookup(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
undefined = Type:lookup(any, Tree),
lists:foreach(
fun({Key, Val}) ->
Val = Type:lookup(Key, Tree)
end,
shuffle(List)
).
remove(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
Tree = Type:remove(any, Tree),
Empty= Type:new(),
Empty= lists:foldl(
fun({Key, _}, Acc) ->
Type:remove(Key, Acc)
end,
Tree,
shuffle(List)
).
has(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
undefined = Type:lookup(any, Tree),
lists:foreach(
fun({Key, _}) ->
true = Type:has(Key, Tree)
end,
shuffle(List)
).
keys(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
Keys = lists:sort([Key || {Key, _} <- List]),
Keys = Type:keys(Tree).
apply(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree0= Type:build(List),
Tree1= lists:foldl(
fun({Key, Val}, Acc) ->
Type:apply(Key, fun(X) -> X - Val end, Acc)
end,
Tree0,
shuffle(List)
),
0 = Type:foldl(fun({_, X}, Acc) -> Acc + X end, 0, Tree1).
build(Config) ->
Type = ?config(type, Config),
Tree = Type:build([{2, b}, {1, a}, {3, c}]),
[{1, a}, {2, b}, {3, c}] = Type:list(Tree).
drop(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:drop(N, Type:build(List)),
Keys = lists:seq(N + 1, ?LENGTH),
Keys = Type:keys(Tree).
dropwhile(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:dropwhile(fun({Key, _}) -> Key =< N end, Type:build(List)),
Keys = lists:seq(N + 1, ?LENGTH),
Keys = Type:keys(Tree).
filter(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:filter(fun({Key, _}) -> Key =< N end, Type:build(List)),
Keys = lists:seq(1, N),
Keys = Type:keys(Tree).
%%
foreach(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
ok = Type:foreach(fun(X) -> X end, Type:build(List)).
%%
map(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:map(fun({_, _}) -> 0 end, Type:build(List)),
0 = Type:foldl(fun({_, X}, Acc) -> Acc + X end, 0, Tree).
%%
split(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
{TreeA, TreeB} = Type:split(N, Type:build(List)),
KeyA = lists:seq(1, N),
KeyA = Type:keys(TreeA),
KeyB = lists:seq(N + 1, ?LENGTH),
KeyB = Type:keys(TreeB).
%%
splitwhile(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
{TreeA, TreeB} = Type:splitwhile(fun({Key, _}) -> Key =< N end, Type:build(List)),
KeyA = lists:seq(1, N),
KeyA = Type:keys(TreeA),
KeyB = lists:seq(N + 1, ?LENGTH),
KeyB = Type:keys(TreeB).
%%
take(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:take(N, Type:build(List)),
Keys = lists:seq(1, N),
Keys = Type:keys(Tree).
%%
takewhile(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:takewhile(fun({Key, _}) -> Key =< N end, Type:build(List)),
Keys = lists:seq(1, N),
Keys = Type:keys(Tree).
%%
min(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
Tree = Type:build(List),
Min = lists:min(List),
Min = Type:min(Tree).
%%
max(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
Tree = Type:build(List),
Max = lists:max(List),
Max = Type:max(Tree).
%%%----------------------------------------------------------------------------
%%%
%%% private
%%%
%%%----------------------------------------------------------------------------
%%
randseq(0) ->
[];
randseq(N) ->
[{rand:uniform(1 bsl 32), N} | randseq(N - 1)].
seq(0) ->
[];
seq(N) ->
[{N, N} | seq(N - 1)].
%%
shuffle(List) ->
[Y || {_, Y} <- lists:keysort(1, [{rand:uniform(), X} || X <- List])].
| null | https://raw.githubusercontent.com/fogfish/datum/f5e8f0b5deb8b74d6febe046333dbb4f38b086d8/test/tree_SUITE.erl | erlang |
All Rights Reserved.
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.
common test
fold/1,
foldl/1,
foldr/1,
unfold/1,
----------------------------------------------------------------------------
suite
----------------------------------------------------------------------------
----------------------------------------------------------------------------
init
----------------------------------------------------------------------------
----------------------------------------------------------------------------
tree primitives
----------------------------------------------------------------------------
----------------------------------------------------------------------------
private
----------------------------------------------------------------------------
| Copyright ( c ) 2017 ,
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(tree_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("datum/include/datum.hrl").
-compile({parse_transform, category}).
-compile({no_auto_import,[apply/2]}).
-export([
all/0
,groups/0
,init_per_suite/1
,end_per_suite/1
,init_per_group/2
,end_per_group/2
]).
-export([
new/1,
empty/1,
append/1,
insert/1,
lookup/1,
remove/1,
has/1,
keys/1,
apply/1,
build/1,
drop/1,
dropwhile/1,
filter/1,
foreach/1,
map/1,
split/1,
splitwhile/1,
take/1,
takewhile/1,
min/1,
max/1
]).
all() ->
[
{group, bst},
{group, rbtree}
].
groups() ->
[
{bst, [parallel],
[new, empty,
append, insert, lookup, remove, has, keys, apply,
build, drop, dropwhile, filter, foreach, map, split, splitwhile, take, takewhile,
fold , foldl , foldr , unfold , min , ] } ,
min, max]},
{rbtree, [parallel],
[new, empty,
append, insert, lookup, remove, has, keys, apply,
build, drop, dropwhile, filter, foreach, map, split, splitwhile, take, takewhile,
fold , foldl , foldr , unfold , min , ] }
min, max]}
].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(Type, Config) ->
[{type, Type}|Config].
end_per_group(_, _Config) ->
ok.
-define(LENGTH, 100).
new(Config) ->
Type = ?config(type, Config),
tree = erlang:element(1, Type:new()).
empty(Config) ->
Type = ?config(type, Config),
?tree() = Type:new().
append(Config) ->
Type = ?config(type, Config),
[{1,1}] = Type:list(Type:append({1,1}, Type:new())).
insert(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Lens = fun({Key, Val}, Acc) -> Type:insert(Key, Val, Acc) end,
Tree = lists:foldl(Lens, Type:new(), List),
lists:foreach(
fun({Key, Val}) ->
Val = Type:lookup(Key, Tree)
end,
shuffle(List)
).
lookup(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
undefined = Type:lookup(any, Tree),
lists:foreach(
fun({Key, Val}) ->
Val = Type:lookup(Key, Tree)
end,
shuffle(List)
).
remove(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
Tree = Type:remove(any, Tree),
Empty= Type:new(),
Empty= lists:foldl(
fun({Key, _}, Acc) ->
Type:remove(Key, Acc)
end,
Tree,
shuffle(List)
).
has(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
undefined = Type:lookup(any, Tree),
lists:foreach(
fun({Key, _}) ->
true = Type:has(Key, Tree)
end,
shuffle(List)
).
keys(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:build(List),
Keys = lists:sort([Key || {Key, _} <- List]),
Keys = Type:keys(Tree).
apply(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree0= Type:build(List),
Tree1= lists:foldl(
fun({Key, Val}, Acc) ->
Type:apply(Key, fun(X) -> X - Val end, Acc)
end,
Tree0,
shuffle(List)
),
0 = Type:foldl(fun({_, X}, Acc) -> Acc + X end, 0, Tree1).
build(Config) ->
Type = ?config(type, Config),
Tree = Type:build([{2, b}, {1, a}, {3, c}]),
[{1, a}, {2, b}, {3, c}] = Type:list(Tree).
drop(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:drop(N, Type:build(List)),
Keys = lists:seq(N + 1, ?LENGTH),
Keys = Type:keys(Tree).
dropwhile(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:dropwhile(fun({Key, _}) -> Key =< N end, Type:build(List)),
Keys = lists:seq(N + 1, ?LENGTH),
Keys = Type:keys(Tree).
filter(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:filter(fun({Key, _}) -> Key =< N end, Type:build(List)),
Keys = lists:seq(1, N),
Keys = Type:keys(Tree).
foreach(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
ok = Type:foreach(fun(X) -> X end, Type:build(List)).
map(Config) ->
Type = ?config(type, Config),
List = randseq(?LENGTH),
Tree = Type:map(fun({_, _}) -> 0 end, Type:build(List)),
0 = Type:foldl(fun({_, X}, Acc) -> Acc + X end, 0, Tree).
split(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
{TreeA, TreeB} = Type:split(N, Type:build(List)),
KeyA = lists:seq(1, N),
KeyA = Type:keys(TreeA),
KeyB = lists:seq(N + 1, ?LENGTH),
KeyB = Type:keys(TreeB).
splitwhile(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
{TreeA, TreeB} = Type:splitwhile(fun({Key, _}) -> Key =< N end, Type:build(List)),
KeyA = lists:seq(1, N),
KeyA = Type:keys(TreeA),
KeyB = lists:seq(N + 1, ?LENGTH),
KeyB = Type:keys(TreeB).
take(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:take(N, Type:build(List)),
Keys = lists:seq(1, N),
Keys = Type:keys(Tree).
takewhile(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
N = rand:uniform(?LENGTH),
Tree = Type:takewhile(fun({Key, _}) -> Key =< N end, Type:build(List)),
Keys = lists:seq(1, N),
Keys = Type:keys(Tree).
min(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
Tree = Type:build(List),
Min = lists:min(List),
Min = Type:min(Tree).
max(Config) ->
Type = ?config(type, Config),
List = shuffle(seq(?LENGTH)),
Tree = Type:build(List),
Max = lists:max(List),
Max = Type:max(Tree).
randseq(0) ->
[];
randseq(N) ->
[{rand:uniform(1 bsl 32), N} | randseq(N - 1)].
seq(0) ->
[];
seq(N) ->
[{N, N} | seq(N - 1)].
shuffle(List) ->
[Y || {_, Y} <- lists:keysort(1, [{rand:uniform(), X} || X <- List])].
|
cdde6dc22095b87f3bae22f471d866216579df56121089475307beea82b0342a | 2garryn/esli | esli_web.erl | %%% ---------------------------------------------------------------
%%% File : esli_web.erl
Author :
Description : " loop"-file for MochiWeb
%%% ---------------------------------------------------------------
-module(esli_web).
-include("esli.hrl").
-export([start/0, loop/2]).
-define(REQUEST_TIMEOUT, 3000).
start() ->
DocRoot = esli_conf:get_config(docroot),
ets:new(clients_ip, [duplicate_bag,
public,
named_table]),
Loop = fun (Req) ->
?MODULE:loop(Req,DocRoot)
end,
WebConfig = esli_conf:get_config(web),
mochiweb_http:start([{name, ?MODULE},
{loop, Loop} | WebConfig]).
loop(Req, DocRoot) ->
"/" ++ Path = Req:get(path),
try
proceed_method(Path, Req, DocRoot)
catch
Type:What ->
Report = ["web request failed",
{path, Path},
{type, Type}, {what, What},
{trace, erlang:get_stacktrace()}],
error_logger:error_report(Report),
server_error(Req)
end.
%%%
%%% functions to make "nice" and readable code
%%%
proceed_method(Path, Req, DocRoot) ->
proceed_method2(Req:get(method), Path, Req, DocRoot).
proceed_method2('GET', Path, Req, DocRoot) ->
proceed_get_path(Path, Req, DocRoot);
proceed_method2('HEAD', Path, Req, DocRoot) ->
proceed_get_path(Path, Req, DocRoot);
proceed_method2('POST',Path, Req, DocRoot) ->
proceed_post_path(Path, Req, DocRoot);
proceed_method2(_, _Path, Req, _DocRoot) ->
bad_request(Req).
%%% Start short link proceeding
proceed_get_path("favicon.ico", Req, _DocRoot) ->
not_found(Req);
proceed_get_path([], Req, DocRoot) ->
index_file(Req, DocRoot);
proceed_get_path(Path, Req, DocRoot) ->
case is_users_file(Path, DocRoot) of
true ->
proceed_file(Path, Req, DocRoot);
false ->
proceed_short_link(Path, Req, DocRoot)
end.
proceed_short_link(Path, Req, DocRoot) when length(Path) =:= ?MAX_LENGTH ->
get_full_link(esli_checker:check_short(Path), Path, Req, DocRoot);
proceed_short_link(_Path, Req, DocRoot) ->
not_found_file(Req, DocRoot).
get_full_link(true, Path, Req, DocRoot) ->
try esli:get_full_link(Path) of
{full_link, Fl} ->
Req:respond({301,[{"Location",Fl}], []});
{error, 404} ->
not_found_file(Req, DocRoot);
{error, 501} ->
server_error_file(Req, DocRoot)
catch
_:_ ->
server_error_file(Req, DocRoot)
end;
get_full_link(false, _Path, Req, DocRoot) ->
not_found_file(Req, DocRoot).
proceed_file(Path, Req, DocRoot) ->
Req:serve_file(Path, DocRoot).
%%% Stop short link proceeding. Full link is got
%%% Start full link proceeding
proceed_post_path("create", Req, DocRoot) ->
Ip = Req:get(peer),
case ets:member(clients_ip, Ip) of
true ->
Req:respond({423, [], ""});
false ->
ets:insert(clients_ip, {Ip}),
timer:apply_after(?REQUEST_TIMEOUT, ets, delete, [clients_ip, Ip]),
Link = binary_to_list(Req:recv_body()),
get_short_link(esli_checker:check_and_update_full(Link), Req, DocRoot)
end;
proceed_post_path(_, Req, _DocRoot) ->
bad_request(Req).
get_short_link({true, UpdatedLink}, Req, _DocRoot) ->
try esli:get_short_link(UpdatedLink) of
{short_link, SLink} ->
Req:ok({"text/html",[], [esli_conf:get_config(domain) ++ "/" ++ SLink]});
{error, 501} ->
server_error(Req)
catch
_:_ ->
server_error(Req)
end;
get_short_link(false, Req, _DocRoot) ->
bad_request(Req).
%%% Stop full link proceeding. short link is here
%%% Helpers for answer
index_file(Req, DocRoot) ->
Req:serve_file("index.html", DocRoot).
not_found_file(Req, DocRoot) ->
Req:serve_file("not_found.html", DocRoot).
server_error_file(Req, DocRoot) ->
Req:serve_file("server_error.html", DocRoot).
not_found(Req) ->
Req:respond({404, [], ""}).
server_error(Req) ->
Req:respond({501, [], "server_error"}).
bad_request(Req) ->
Req:respond({400, [], "bad_request"}).
is_users_file(Path, DocRoot) ->
filelib:is_file(filename:join(DocRoot, Path)).
| null | https://raw.githubusercontent.com/2garryn/esli/6e48337b066bb230813317dcda613993c2929684/apps/esli/src/esli_web.erl | erlang | ---------------------------------------------------------------
File : esli_web.erl
---------------------------------------------------------------
functions to make "nice" and readable code
Start short link proceeding
Stop short link proceeding. Full link is got
Start full link proceeding
Stop full link proceeding. short link is here
Helpers for answer | Author :
Description : " loop"-file for MochiWeb
-module(esli_web).
-include("esli.hrl").
-export([start/0, loop/2]).
-define(REQUEST_TIMEOUT, 3000).
start() ->
DocRoot = esli_conf:get_config(docroot),
ets:new(clients_ip, [duplicate_bag,
public,
named_table]),
Loop = fun (Req) ->
?MODULE:loop(Req,DocRoot)
end,
WebConfig = esli_conf:get_config(web),
mochiweb_http:start([{name, ?MODULE},
{loop, Loop} | WebConfig]).
loop(Req, DocRoot) ->
"/" ++ Path = Req:get(path),
try
proceed_method(Path, Req, DocRoot)
catch
Type:What ->
Report = ["web request failed",
{path, Path},
{type, Type}, {what, What},
{trace, erlang:get_stacktrace()}],
error_logger:error_report(Report),
server_error(Req)
end.
proceed_method(Path, Req, DocRoot) ->
proceed_method2(Req:get(method), Path, Req, DocRoot).
proceed_method2('GET', Path, Req, DocRoot) ->
proceed_get_path(Path, Req, DocRoot);
proceed_method2('HEAD', Path, Req, DocRoot) ->
proceed_get_path(Path, Req, DocRoot);
proceed_method2('POST',Path, Req, DocRoot) ->
proceed_post_path(Path, Req, DocRoot);
proceed_method2(_, _Path, Req, _DocRoot) ->
bad_request(Req).
proceed_get_path("favicon.ico", Req, _DocRoot) ->
not_found(Req);
proceed_get_path([], Req, DocRoot) ->
index_file(Req, DocRoot);
proceed_get_path(Path, Req, DocRoot) ->
case is_users_file(Path, DocRoot) of
true ->
proceed_file(Path, Req, DocRoot);
false ->
proceed_short_link(Path, Req, DocRoot)
end.
proceed_short_link(Path, Req, DocRoot) when length(Path) =:= ?MAX_LENGTH ->
get_full_link(esli_checker:check_short(Path), Path, Req, DocRoot);
proceed_short_link(_Path, Req, DocRoot) ->
not_found_file(Req, DocRoot).
get_full_link(true, Path, Req, DocRoot) ->
try esli:get_full_link(Path) of
{full_link, Fl} ->
Req:respond({301,[{"Location",Fl}], []});
{error, 404} ->
not_found_file(Req, DocRoot);
{error, 501} ->
server_error_file(Req, DocRoot)
catch
_:_ ->
server_error_file(Req, DocRoot)
end;
get_full_link(false, _Path, Req, DocRoot) ->
not_found_file(Req, DocRoot).
proceed_file(Path, Req, DocRoot) ->
Req:serve_file(Path, DocRoot).
proceed_post_path("create", Req, DocRoot) ->
Ip = Req:get(peer),
case ets:member(clients_ip, Ip) of
true ->
Req:respond({423, [], ""});
false ->
ets:insert(clients_ip, {Ip}),
timer:apply_after(?REQUEST_TIMEOUT, ets, delete, [clients_ip, Ip]),
Link = binary_to_list(Req:recv_body()),
get_short_link(esli_checker:check_and_update_full(Link), Req, DocRoot)
end;
proceed_post_path(_, Req, _DocRoot) ->
bad_request(Req).
get_short_link({true, UpdatedLink}, Req, _DocRoot) ->
try esli:get_short_link(UpdatedLink) of
{short_link, SLink} ->
Req:ok({"text/html",[], [esli_conf:get_config(domain) ++ "/" ++ SLink]});
{error, 501} ->
server_error(Req)
catch
_:_ ->
server_error(Req)
end;
get_short_link(false, Req, _DocRoot) ->
bad_request(Req).
index_file(Req, DocRoot) ->
Req:serve_file("index.html", DocRoot).
not_found_file(Req, DocRoot) ->
Req:serve_file("not_found.html", DocRoot).
server_error_file(Req, DocRoot) ->
Req:serve_file("server_error.html", DocRoot).
not_found(Req) ->
Req:respond({404, [], ""}).
server_error(Req) ->
Req:respond({501, [], "server_error"}).
bad_request(Req) ->
Req:respond({400, [], "bad_request"}).
is_users_file(Path, DocRoot) ->
filelib:is_file(filename:join(DocRoot, Path)).
|
02350c9cbe23a6765741abeb63afeda7a19b199bc57915819ec7a783cd9e6bf4 | mikeizbicki/HLearn | History.hs | -- | All optimization algorithms get run within the "History" monad provided in this module.
-- This monad lets us thread user-defined debugging code throughout our optimization procedures.
-- Most optimization libraries don't include significant debugging features because of the runtime overhead.
-- That's not a problem for us, however.
-- When you run a "History" monad with no debugging information (e.g. by using "evalHistory"), then no runtime penalty is incurred.
GHC / is able to optimize everything into tight , efficient loops .
-- You only pay for the overhead that you actually use.
module HLearn.History
(
-- * The History Monad
History
, History_
-- , History__
, runHistory
, evalHistory
, traceHistory
, traceAllHistory
, NoCxt
, ValidCxt
-- ** Reporting tools
, Report (..)
, beginFunction
, report
, withMsg
, withMsgIO
, iterate
, currentItr
-- *** stop conditions
, StopCondition
, maxIterations
, stopBelow
, mulTolerance
, fx1grows
, noProgress
-- * Display Functions
, DisplayFunction
-- ** Display each iteration
, dispIteration
, dispIteration_
, infoString
, infoDiffTime
, infoType
, infoItr
-- ** Display at the end
, summaryTable
-- ** Consider only some iterations
, DisplayFilter
, displayFilter
, maxReportLevel
-- * data membership classes
, Has_x1 (..)
, Has_fx1 (..)
)
where
import qualified Prelude as P
import Control.Monad.Identity hiding (Functor (..), Monad(..), join, forM_)
import Control.Monad.Reader hiding (Functor (..), Monad(..), join, forM_)
import Control.Monad.State.Strict hiding (Functor (..), Monad(..), join, forM_)
import Control.Monad.Trans hiding (Functor (..), Monad(..))
import Numeric
import System.CPUTime
import System.IO
import System.IO.Unsafe
import Unsafe.Coerce
import SubHask
import SubHask.Algebra.Container
import SubHask.Compatibility.Containers
-------------------------------------------------------------------------------
-- FIXME:
-- This class is obsolete and should be deleted.
-- It should be hard to do, I'm just tired right now and don't want to do the refactoring.
class (Typeable a, Show a) => Optimizable a
instance (Typeable a, Show a) => Optimizable a
-------------------------------------------------------------------------------
-- |
--
-- FIXME: Is there a way to store times in "Int"s rather than "Integer"s for more efficiency?
type CPUTime = Integer
-- | This data type stores information about each step in our optimization routines.
--
-- FIXME:
-- Is there a better name for this?
data Report = Report
{ cpuTimeStart :: !CPUTime
, cpuTimeDiff :: !CPUTime
, numReports :: {-#UNPACK#-}!Int
, reportLevel :: {-#UNPACK#-}!Int
}
deriving Show
mkMutable [t| Report |]
-------------------------------------------------------------------------------
-- display functions
| When running a " History " monad , there are three times we might need to perform IO actions : the beginning , middle , and end .
This type just wraps all three of those functions into a single type .
data DisplayFunction_ cxt s = DisplayFunction
{ startDisplayFunction :: IO ()
, stepDisplayFunction :: forall a. cxt a => Report -> s -> a -> (s, IO ())
, stopDisplayFunction :: s -> IO ()
}
type DisplayFunction = DisplayFunction_ Optimizable
mkMutable [t| forall cxt s. DisplayFunction_ cxt s |]
instance Semigroup s => Semigroup (DisplayFunction_ cxt s) where
df1+df2 = DisplayFunction
(startDisplayFunction df1+startDisplayFunction df2)
(stepDisplayFunction df1 +stepDisplayFunction df2 )
(stopDisplayFunction df1 +stopDisplayFunction df2 )
instance Monoid s => Monoid (DisplayFunction_ cxt s) where
zero = DisplayFunction zero zero zero
----------------------------------------
-- filtering
-- | Functions of this type are used to prevent the "stepDisplayFunction" from being called in certain situaations.
type DisplayFilter = forall a. Optimizable a => Report -> a -> Bool
displayFilter :: Monoid s => DisplayFilter -> DisplayFunction s -> DisplayFunction s
displayFilter f df = df
{ stepDisplayFunction = \r s a -> if f r a
then stepDisplayFunction df r s a
else (zero, return ())
}
maxReportLevel :: Int -> DisplayFilter
maxReportLevel n r _ = reportLevel r <= n
----------------------------------------
-- summary table
-- | Functions of this type are used as parameters to the "dispIteration_" function.
type DisplayInfo = forall a. Optimizable a => Report -> a -> String
-- | After each step in the optimization completes, print a single line describing what happened.
dispIteration :: Monoid s => DisplayFunction s
dispIteration = dispIteration_ (infoItr + infoType + infoDiffTime)
-- | A more general version of "dispIteration" that let's you specify what information to display.
dispIteration_ :: forall s. Monoid s => DisplayInfo -> DisplayFunction s
dispIteration_ f = DisplayFunction zero g zero
where
-- type signature needed for -XImpredicativeTypes
g :: forall a. Optimizable a => Report -> s -> a -> (s, IO () )
g r s a = (zero, putStrLn $ (concat $ P.replicate (reportLevel r) " - ") ++ f r a)
| Pretty - print a " CPUTime " .
showTime :: CPUTime -> String
showTime t = showEFloat (Just $ len-4-4) (fromIntegral t * 1e-12 :: Double) "" ++ " sec"
where
len=12
-- | Print a raw string.
infoString :: String -> DisplayInfo
infoString = const . const
-- | Print the time used to complete the step.
infoDiffTime :: DisplayInfo
infoDiffTime r _ = "; " ++ showTime (cpuTimeDiff r)
-- | Print the name of the optimization step.
infoType :: DisplayInfo
infoType _ a = "; "++if typeRep [a] == typeRep [""]
then P.init $ P.tail $ show a
else show a
else P.head $ P.words $ show $ typeRep [ a ]
-- | Print the current iteration of the optimization.
infoItr :: DisplayInfo
infoItr r _ = "; "++show (numReports r)
----------------------------------------
-- summary table
| Contains all the information that might get displayed by " summaryTable " .
--
-- FIXME:
-- There's a lot more information that could be included.
We could make " summaryTable " take parameters describing which elements to actually calculate / display .
data CountInfo = CountInfo
{ numcalls :: Int
, tottime :: Integer
}
deriving Show
type instance Logic CountInfo = Bool
instance Eq_ CountInfo where
ci1==ci2 = numcalls ci1 == numcalls ci2
&& tottime ci1 == tottime ci2
avetime :: CountInfo -> Integer
avetime = round (fromIntegral tottime / fromIntegral numcalls :: CountInfo -> Double)
| Call " " with this " DisplayFunction " to get a table summarizing the optimization .
-- This does not affect output during the optimization itself, only at the end.
summaryTable :: DisplayFunction (Map' (Lexical String) CountInfo)
summaryTable = DisplayFunction zero step stop
where
-- type signature needed for -XImpredicativeTypes
step :: forall a. Optimizable a
=> Report
-> Map' (Lexical String) CountInfo
-> a
-> ( Map' (Lexical String) CountInfo, IO () )
step r s a = (insertAt k ci s, return ())
where
t = typeRep (Proxy::Proxy a)
k = Lexical $ if t == typeRep (Proxy::Proxy String)
then unsafeCoerce a
else P.head $ P.words $ show t
ci0 = case lookup k s of
Just x -> x
Nothing -> CountInfo
{ numcalls = 0
, tottime = 0
}
ci = ci0
{ numcalls = numcalls ci0+1
, tottime = tottime ci0+cpuTimeDiff r
}
stop :: Map' (Lexical String) CountInfo -> IO ()
stop m = do
let hline = putStrLn $ " " ++ P.replicate (maxlen_name+maxlen_count+maxlen_time+10) '-'
hline
putStrLn $ " | " ++ padString title_name maxlen_name
++ " | " ++ padString title_count maxlen_count
++ " | " ++ padString title_time maxlen_time
++ " | "
hline
forM_ (toIxList m) $ \(k,ci) -> do
putStrLn $ " | " ++ padString (unLexical k ) maxlen_name
++ " | " ++ padString (show $ numcalls ci) maxlen_count
++ " | " ++ padString (showTime $ tottime ci) maxlen_time
++ " | "
hline
where
title_name = "report name"
title_count = "number of calls"
title_time = "average time per call"
maxlen_name = maximum $ length title_name:(map (length . fst) $ toIxList m)
maxlen_count = maximum $ length title_count:(map (length . show . numcalls . snd) $ toIxList m)
maxlen_time = maximum $ length title_time: (map (length . showTime . tottime . snd) $ toIxList m)
padString :: String -> Int -> String
padString a i = P.take i $ a ++ P.repeat ' '
-------------------------------------------------
-- | Every type is an instance of "NoCxt".
-- When running a "History" monad, we must always assign a value to the "cxt" variable.
-- Use "NoCxt" when you don't want to enforce any constraints.
class NoCxt a
instance NoCxt a
| Applies the cxt to construct the needed constraints .
type ValidCxt (cxt :: * -> Constraint) a =
( cxt String
, cxt a
, cxt (Scalar a)
)
-- | A (sometimes) more convenient version of "History_"
type History cxt a = forall s. ValidCxt cxt a => History_ cxt s a
| This monad internally requires -XImpredicativeTypes to thread our " DisplayFunction " throughout the code .
newtype History_ cxt s a = History
( ReaderT
( DisplayFunction_ cxt s )
( StateT
(s,[Report])
-- ( StateT
-- s
IO
-- )
)
a
)
mkMutable [t| forall cxt s a. History_ cxt s a |]
-- | Run the "History" computation without any debugging information.
-- This is the most efficient way to run an optimization.
# INLINABLE evalHistory #
evalHistory :: History_ NoCxt () a -> a
evalHistory = unsafePerformIO . runHistory zero
-- | Run the "History" computation with a small amount of debugging information.
# INLINABLE traceHistory #
traceHistory :: Optimizable a => History_ Optimizable () a -> a
traceHistory = unsafePerformIO . runHistory (displayFilter (maxReportLevel 2) dispIteration)
-- | Run the "History" computation with a lot of debugging information.
# INLINABLE traceAllHistory #
traceAllHistory :: Optimizable a => History_ Optimizable () a -> a
traceAllHistory = unsafePerformIO . runHistory dispIteration
-- | Specify the amount of debugging information to run the "History" computation with.
{-# INLINABLE runHistory #-}
runHistory :: forall cxt s a. (cxt a, Monoid s) => DisplayFunction_ cxt s -> History_ cxt s a -> IO a
runHistory df (History hist) = {-# SCC runHistory #-} do
time <- getCPUTime
let startReport = Report
{ cpuTimeStart = time
, cpuTimeDiff = 0
, numReports = 0
, reportLevel = 0
}
startDisplayFunction df
-- the nasty type signature below is needed for -XImpredicativeTypes
(a, (s,_)) <- runStateT
( (runReaderT :: forall m. ReaderT (DisplayFunction_ cxt s) m a -> DisplayFunction_ cxt s -> m a )
hist
df
)
(zero, [startReport])
stopDisplayFunction df s
return a
-- | You should call this function everytime your "History" computation enters a new phase.
-- For iterative algorithms, you should probably call this function once per loop.
--
-- This is a convenient wrapper around the "report" and "collectReports" functions.
# INLINABLE beginFunction #
beginFunction :: cxt String => String -> History_ cxt s a -> History_ cxt s a
beginFunction b ha = collectReports $ do
report b
collectReports ha
-- | Register the parameter of type @a@ as being important for debugging information.
-- This creates a new "Report" and automatically runs the appropriate "stepDisplayFunction".
# INLINABLE report #
report :: forall cxt s a. cxt a => a -> History_ cxt s a
# SCC report #
time <- liftIO getCPUTime
(s0, prevReport:xs) <- get
let newReport = Report
{ cpuTimeStart = time
, cpuTimeDiff = time - cpuTimeStart prevReport
, numReports = numReports prevReport+1
, reportLevel = reportLevel prevReport
}
get our DisplayFunction and call it
-- the cumbersome type signature is required for -XImpredicativeTypes
(f::DisplayFunction_ cxt s) <-
(ask :: ReaderT (DisplayFunction_ cxt s) (StateT (s, [Report]) IO) (DisplayFunction_ cxt s))
let (s1,io) = stepDisplayFunction f newReport s0 a
put $ (s1, newReport:xs)
liftIO io
return a
-- | Group all of the "Reports" that happen in the given computation together.
-- You probably don't need to call this function directly, and instead should call "beginFunction".
# INLINABLE collectReports #
collectReports :: History_ cxt s a -> History_ cxt s a
# SCC collectReports #
mkLevel
a <- hist
rmLevel
return a
where
mkLevel = do
(s, prevReport:xs) <- get
time <- liftIO getCPUTime
let newReport = Report
{ cpuTimeStart = time
, cpuTimeDiff = 0
, numReports = -1
, reportLevel = reportLevel prevReport+1
}
put $ (s, newReport:prevReport:xs)
rmLevel = do
(s, newReport:xs) <- get
put (s,xs)
# INLINABLE currentItr #
currentItr :: History cxt Int
currentItr = History $ do
(_ , x:_) <- get
return $ numReports x
---------------------------------------
withMsg :: (cxt String, NFData a) => String -> a -> History_ cxt s a
withMsg msg a = withMsgIO msg (return a)
withMsgIO :: (cxt String, NFData a) => String -> IO a -> History_ cxt s a
withMsgIO msg ioa = do
a <- History $ liftIO ioa
report $ deepseq a $ msg
return a
-------------------------------------------------------------------------------
-- algebra
---------------------------------------
-- monad hierarchy
instance Functor Hask (History_ cxt s) where
fmap f (History s) = History (fmap f s)
instance Then (History_ cxt s) where
(>>) = haskThen
instance Monad Hask (History_ cxt s) where
return_ a = History $ return_ a
join (History s) = History $ join (fmap (\(History s)->s) s)
---------------------------------------
-- math hierarchy
type instance Scalar (History_ cxt s a) = Scalar a
instance Semigroup a => Semigroup (History_ cxt s a) where
ha1 + ha2 = do
a1 <- ha1
a2 <- ha2
return $ a1+a2
instance Cancellative a => Cancellative (History_ cxt s a) where
ha1 - ha2 = do
a1 <- ha1
a2 <- ha2
return $ a1-a2
instance Monoid a => Monoid (History_ cxt s a) where
zero = return zero
instance Group a => Group (History_ cxt s a) where
negate ha = do
a <- ha
return $ negate a
---------------------------------------
-- comparison hierarchy
type instance Logic (History_ cxt s a) = History_ cxt s (Logic a)
instance Eq_ a => Eq_ (History_ cxt s a) where
a==b = do
a' <- a
b' <- b
return $ a'==b'
instance POrd_ a => POrd_ (History_ cxt s a) where
# INLINABLE inf #
inf a b = do
a' <- a
b' <- b
return $ inf a' b'
instance Lattice_ a => Lattice_ (History_ cxt s a) where
# INLINABLE sup #
sup a b = do
a' <- a
b' <- b
return $ sup a' b'
instance MinBound_ a => MinBound_ (History_ cxt s a) where
minBound = return $ minBound
instance Bounded a => Bounded (History_ cxt s a) where
maxBound = return $ maxBound
instance Heyting a => Heyting (History_ cxt s a) where
(==>) a b = do
a' <- a
b' <- b
return $ a' ==> b'
instance Complemented a => Complemented (History_ cxt s a) where
not a = do
a' <- a
return $ not a'
instance Boolean a => Boolean (History_ cxt s a)
-------------------------------------------------------------------------------
-- iteration
| This function is similar in spirit to the @while@ loop of imperative languages like
-- The advantage is the "DisplayFunction"s from the "History" monad get automatically (and efficiently!) threaded throughout our computation.
-- "iterate" is particularly useful for implementing iterative optimization algorithms.
# INLINABLE iterate #
iterate :: forall cxt a. cxt a
=> (a -> History cxt a) -- ^ step function
-> StopCondition a -- ^ stop conditions
-> a -- ^ start parameters
-> History cxt a -- ^ result
# SCC iterate #
report opt0
opt1 <- step opt0
go opt0 opt1
where
go prevopt curopt = {-# SCC iterate_go #-} do
report curopt
done <- stop prevopt curopt
if done
then return curopt
else do
opt' <- step curopt
go curopt opt'
---------------------------------------
class Has_x1 opt v where x1 :: opt v -> v
class Has_fx1 opt v where fx1 :: opt v -> Scalar v
---------------------------------------
-- stop conditions
-- | Functions of this type determine whether the "iterate" function should keep looping or stop.
type StopCondition a = forall cxt. cxt a => a -> a -> forall s. History_ cxt s Bool
-- | Stop iterating after the specified number of iterations.
This number is typically set fairly high ( at least one hundred , possibly in the millions ) .
-- It should probably be used on all optimizations to prevent poorly converging optimizations taking forever.
maxIterations :: Int {- ^ max number of iterations -} -> StopCondition a
maxIterations i _ _ = History $ do
(_ , x:_) <- get
return $ numReports x >= i
-- | Stop the optimization as soon as our function is below the given threshold.
stopBelow ::
( Has_fx1 opt v
, Ord (Scalar v)
) => Scalar v
-> StopCondition (opt v)
stopBelow threshold _ opt = return $ (fx1 opt) < threshold
-- | Stop the iteration when successive function evaluations are within a given distance of each other.
-- On "well behaved" problems, this means our optimization has converged.
mulTolerance ::
( BoundedField (Scalar v)
, Has_fx1 opt v
) => Scalar v -- ^ tolerance
-> StopCondition (opt v)
# SCC multiplicativeTollerance #
return $ (fx1 prevopt) /= infinity && left < right
where
left = 2*abs (fx1 curopt - fx1 prevopt)
right = tol*(abs (fx1 curopt) + abs (fx1 prevopt) + 1e-18)
-- | Stop the optimization if our function value has grown between iterations
fx1grows :: ( Has_fx1 opt v , Ord (Scalar v) ) => StopCondition (opt v)
fx1grows opt0 opt1 = return $ fx1 opt0 < fx1 opt1
-- | Stop the optimization if our function value has stopped decreasing
noProgress :: Eq (opt v) => StopCondition (opt v)
noProgress opt0 opt1 = return $ opt0 == opt1
| null | https://raw.githubusercontent.com/mikeizbicki/HLearn/c6c0f5e7593be3867f20c56c79b998e7d7ded9fc/src/HLearn/History.hs | haskell | | All optimization algorithms get run within the "History" monad provided in this module.
This monad lets us thread user-defined debugging code throughout our optimization procedures.
Most optimization libraries don't include significant debugging features because of the runtime overhead.
That's not a problem for us, however.
When you run a "History" monad with no debugging information (e.g. by using "evalHistory"), then no runtime penalty is incurred.
You only pay for the overhead that you actually use.
* The History Monad
, History__
** Reporting tools
*** stop conditions
* Display Functions
** Display each iteration
** Display at the end
** Consider only some iterations
* data membership classes
-----------------------------------------------------------------------------
FIXME:
This class is obsolete and should be deleted.
It should be hard to do, I'm just tired right now and don't want to do the refactoring.
-----------------------------------------------------------------------------
|
FIXME: Is there a way to store times in "Int"s rather than "Integer"s for more efficiency?
| This data type stores information about each step in our optimization routines.
FIXME:
Is there a better name for this?
#UNPACK#
#UNPACK#
-----------------------------------------------------------------------------
display functions
--------------------------------------
filtering
| Functions of this type are used to prevent the "stepDisplayFunction" from being called in certain situaations.
--------------------------------------
summary table
| Functions of this type are used as parameters to the "dispIteration_" function.
| After each step in the optimization completes, print a single line describing what happened.
| A more general version of "dispIteration" that let's you specify what information to display.
type signature needed for -XImpredicativeTypes
| Print a raw string.
| Print the time used to complete the step.
| Print the name of the optimization step.
| Print the current iteration of the optimization.
--------------------------------------
summary table
FIXME:
There's a lot more information that could be included.
This does not affect output during the optimization itself, only at the end.
type signature needed for -XImpredicativeTypes
-----------------------------------------------
| Every type is an instance of "NoCxt".
When running a "History" monad, we must always assign a value to the "cxt" variable.
Use "NoCxt" when you don't want to enforce any constraints.
| A (sometimes) more convenient version of "History_"
( StateT
s
)
| Run the "History" computation without any debugging information.
This is the most efficient way to run an optimization.
| Run the "History" computation with a small amount of debugging information.
| Run the "History" computation with a lot of debugging information.
| Specify the amount of debugging information to run the "History" computation with.
# INLINABLE runHistory #
# SCC runHistory #
the nasty type signature below is needed for -XImpredicativeTypes
| You should call this function everytime your "History" computation enters a new phase.
For iterative algorithms, you should probably call this function once per loop.
This is a convenient wrapper around the "report" and "collectReports" functions.
| Register the parameter of type @a@ as being important for debugging information.
This creates a new "Report" and automatically runs the appropriate "stepDisplayFunction".
the cumbersome type signature is required for -XImpredicativeTypes
| Group all of the "Reports" that happen in the given computation together.
You probably don't need to call this function directly, and instead should call "beginFunction".
-------------------------------------
-----------------------------------------------------------------------------
algebra
-------------------------------------
monad hierarchy
-------------------------------------
math hierarchy
-------------------------------------
comparison hierarchy
-----------------------------------------------------------------------------
iteration
The advantage is the "DisplayFunction"s from the "History" monad get automatically (and efficiently!) threaded throughout our computation.
"iterate" is particularly useful for implementing iterative optimization algorithms.
^ step function
^ stop conditions
^ start parameters
^ result
# SCC iterate_go #
-------------------------------------
-------------------------------------
stop conditions
| Functions of this type determine whether the "iterate" function should keep looping or stop.
| Stop iterating after the specified number of iterations.
It should probably be used on all optimizations to prevent poorly converging optimizations taking forever.
^ max number of iterations
| Stop the optimization as soon as our function is below the given threshold.
| Stop the iteration when successive function evaluations are within a given distance of each other.
On "well behaved" problems, this means our optimization has converged.
^ tolerance
| Stop the optimization if our function value has grown between iterations
| Stop the optimization if our function value has stopped decreasing | GHC / is able to optimize everything into tight , efficient loops .
module HLearn.History
(
History
, History_
, runHistory
, evalHistory
, traceHistory
, traceAllHistory
, NoCxt
, ValidCxt
, Report (..)
, beginFunction
, report
, withMsg
, withMsgIO
, iterate
, currentItr
, StopCondition
, maxIterations
, stopBelow
, mulTolerance
, fx1grows
, noProgress
, DisplayFunction
, dispIteration
, dispIteration_
, infoString
, infoDiffTime
, infoType
, infoItr
, summaryTable
, DisplayFilter
, displayFilter
, maxReportLevel
, Has_x1 (..)
, Has_fx1 (..)
)
where
import qualified Prelude as P
import Control.Monad.Identity hiding (Functor (..), Monad(..), join, forM_)
import Control.Monad.Reader hiding (Functor (..), Monad(..), join, forM_)
import Control.Monad.State.Strict hiding (Functor (..), Monad(..), join, forM_)
import Control.Monad.Trans hiding (Functor (..), Monad(..))
import Numeric
import System.CPUTime
import System.IO
import System.IO.Unsafe
import Unsafe.Coerce
import SubHask
import SubHask.Algebra.Container
import SubHask.Compatibility.Containers
class (Typeable a, Show a) => Optimizable a
instance (Typeable a, Show a) => Optimizable a
type CPUTime = Integer
data Report = Report
{ cpuTimeStart :: !CPUTime
, cpuTimeDiff :: !CPUTime
}
deriving Show
mkMutable [t| Report |]
| When running a " History " monad , there are three times we might need to perform IO actions : the beginning , middle , and end .
This type just wraps all three of those functions into a single type .
data DisplayFunction_ cxt s = DisplayFunction
{ startDisplayFunction :: IO ()
, stepDisplayFunction :: forall a. cxt a => Report -> s -> a -> (s, IO ())
, stopDisplayFunction :: s -> IO ()
}
type DisplayFunction = DisplayFunction_ Optimizable
mkMutable [t| forall cxt s. DisplayFunction_ cxt s |]
instance Semigroup s => Semigroup (DisplayFunction_ cxt s) where
df1+df2 = DisplayFunction
(startDisplayFunction df1+startDisplayFunction df2)
(stepDisplayFunction df1 +stepDisplayFunction df2 )
(stopDisplayFunction df1 +stopDisplayFunction df2 )
instance Monoid s => Monoid (DisplayFunction_ cxt s) where
zero = DisplayFunction zero zero zero
type DisplayFilter = forall a. Optimizable a => Report -> a -> Bool
displayFilter :: Monoid s => DisplayFilter -> DisplayFunction s -> DisplayFunction s
displayFilter f df = df
{ stepDisplayFunction = \r s a -> if f r a
then stepDisplayFunction df r s a
else (zero, return ())
}
maxReportLevel :: Int -> DisplayFilter
maxReportLevel n r _ = reportLevel r <= n
type DisplayInfo = forall a. Optimizable a => Report -> a -> String
dispIteration :: Monoid s => DisplayFunction s
dispIteration = dispIteration_ (infoItr + infoType + infoDiffTime)
dispIteration_ :: forall s. Monoid s => DisplayInfo -> DisplayFunction s
dispIteration_ f = DisplayFunction zero g zero
where
g :: forall a. Optimizable a => Report -> s -> a -> (s, IO () )
g r s a = (zero, putStrLn $ (concat $ P.replicate (reportLevel r) " - ") ++ f r a)
| Pretty - print a " CPUTime " .
showTime :: CPUTime -> String
showTime t = showEFloat (Just $ len-4-4) (fromIntegral t * 1e-12 :: Double) "" ++ " sec"
where
len=12
infoString :: String -> DisplayInfo
infoString = const . const
infoDiffTime :: DisplayInfo
infoDiffTime r _ = "; " ++ showTime (cpuTimeDiff r)
infoType :: DisplayInfo
infoType _ a = "; "++if typeRep [a] == typeRep [""]
then P.init $ P.tail $ show a
else show a
else P.head $ P.words $ show $ typeRep [ a ]
infoItr :: DisplayInfo
infoItr r _ = "; "++show (numReports r)
| Contains all the information that might get displayed by " summaryTable " .
We could make " summaryTable " take parameters describing which elements to actually calculate / display .
data CountInfo = CountInfo
{ numcalls :: Int
, tottime :: Integer
}
deriving Show
type instance Logic CountInfo = Bool
instance Eq_ CountInfo where
ci1==ci2 = numcalls ci1 == numcalls ci2
&& tottime ci1 == tottime ci2
avetime :: CountInfo -> Integer
avetime = round (fromIntegral tottime / fromIntegral numcalls :: CountInfo -> Double)
| Call " " with this " DisplayFunction " to get a table summarizing the optimization .
summaryTable :: DisplayFunction (Map' (Lexical String) CountInfo)
summaryTable = DisplayFunction zero step stop
where
step :: forall a. Optimizable a
=> Report
-> Map' (Lexical String) CountInfo
-> a
-> ( Map' (Lexical String) CountInfo, IO () )
step r s a = (insertAt k ci s, return ())
where
t = typeRep (Proxy::Proxy a)
k = Lexical $ if t == typeRep (Proxy::Proxy String)
then unsafeCoerce a
else P.head $ P.words $ show t
ci0 = case lookup k s of
Just x -> x
Nothing -> CountInfo
{ numcalls = 0
, tottime = 0
}
ci = ci0
{ numcalls = numcalls ci0+1
, tottime = tottime ci0+cpuTimeDiff r
}
stop :: Map' (Lexical String) CountInfo -> IO ()
stop m = do
let hline = putStrLn $ " " ++ P.replicate (maxlen_name+maxlen_count+maxlen_time+10) '-'
hline
putStrLn $ " | " ++ padString title_name maxlen_name
++ " | " ++ padString title_count maxlen_count
++ " | " ++ padString title_time maxlen_time
++ " | "
hline
forM_ (toIxList m) $ \(k,ci) -> do
putStrLn $ " | " ++ padString (unLexical k ) maxlen_name
++ " | " ++ padString (show $ numcalls ci) maxlen_count
++ " | " ++ padString (showTime $ tottime ci) maxlen_time
++ " | "
hline
where
title_name = "report name"
title_count = "number of calls"
title_time = "average time per call"
maxlen_name = maximum $ length title_name:(map (length . fst) $ toIxList m)
maxlen_count = maximum $ length title_count:(map (length . show . numcalls . snd) $ toIxList m)
maxlen_time = maximum $ length title_time: (map (length . showTime . tottime . snd) $ toIxList m)
padString :: String -> Int -> String
padString a i = P.take i $ a ++ P.repeat ' '
class NoCxt a
instance NoCxt a
| Applies the cxt to construct the needed constraints .
type ValidCxt (cxt :: * -> Constraint) a =
( cxt String
, cxt a
, cxt (Scalar a)
)
type History cxt a = forall s. ValidCxt cxt a => History_ cxt s a
| This monad internally requires -XImpredicativeTypes to thread our " DisplayFunction " throughout the code .
newtype History_ cxt s a = History
( ReaderT
( DisplayFunction_ cxt s )
( StateT
(s,[Report])
IO
)
a
)
mkMutable [t| forall cxt s a. History_ cxt s a |]
# INLINABLE evalHistory #
evalHistory :: History_ NoCxt () a -> a
evalHistory = unsafePerformIO . runHistory zero
# INLINABLE traceHistory #
traceHistory :: Optimizable a => History_ Optimizable () a -> a
traceHistory = unsafePerformIO . runHistory (displayFilter (maxReportLevel 2) dispIteration)
# INLINABLE traceAllHistory #
traceAllHistory :: Optimizable a => History_ Optimizable () a -> a
traceAllHistory = unsafePerformIO . runHistory dispIteration
runHistory :: forall cxt s a. (cxt a, Monoid s) => DisplayFunction_ cxt s -> History_ cxt s a -> IO a
time <- getCPUTime
let startReport = Report
{ cpuTimeStart = time
, cpuTimeDiff = 0
, numReports = 0
, reportLevel = 0
}
startDisplayFunction df
(a, (s,_)) <- runStateT
( (runReaderT :: forall m. ReaderT (DisplayFunction_ cxt s) m a -> DisplayFunction_ cxt s -> m a )
hist
df
)
(zero, [startReport])
stopDisplayFunction df s
return a
# INLINABLE beginFunction #
beginFunction :: cxt String => String -> History_ cxt s a -> History_ cxt s a
beginFunction b ha = collectReports $ do
report b
collectReports ha
# INLINABLE report #
report :: forall cxt s a. cxt a => a -> History_ cxt s a
# SCC report #
time <- liftIO getCPUTime
(s0, prevReport:xs) <- get
let newReport = Report
{ cpuTimeStart = time
, cpuTimeDiff = time - cpuTimeStart prevReport
, numReports = numReports prevReport+1
, reportLevel = reportLevel prevReport
}
get our DisplayFunction and call it
(f::DisplayFunction_ cxt s) <-
(ask :: ReaderT (DisplayFunction_ cxt s) (StateT (s, [Report]) IO) (DisplayFunction_ cxt s))
let (s1,io) = stepDisplayFunction f newReport s0 a
put $ (s1, newReport:xs)
liftIO io
return a
# INLINABLE collectReports #
collectReports :: History_ cxt s a -> History_ cxt s a
# SCC collectReports #
mkLevel
a <- hist
rmLevel
return a
where
mkLevel = do
(s, prevReport:xs) <- get
time <- liftIO getCPUTime
let newReport = Report
{ cpuTimeStart = time
, cpuTimeDiff = 0
, numReports = -1
, reportLevel = reportLevel prevReport+1
}
put $ (s, newReport:prevReport:xs)
rmLevel = do
(s, newReport:xs) <- get
put (s,xs)
# INLINABLE currentItr #
currentItr :: History cxt Int
currentItr = History $ do
(_ , x:_) <- get
return $ numReports x
withMsg :: (cxt String, NFData a) => String -> a -> History_ cxt s a
withMsg msg a = withMsgIO msg (return a)
withMsgIO :: (cxt String, NFData a) => String -> IO a -> History_ cxt s a
withMsgIO msg ioa = do
a <- History $ liftIO ioa
report $ deepseq a $ msg
return a
instance Functor Hask (History_ cxt s) where
fmap f (History s) = History (fmap f s)
instance Then (History_ cxt s) where
(>>) = haskThen
instance Monad Hask (History_ cxt s) where
return_ a = History $ return_ a
join (History s) = History $ join (fmap (\(History s)->s) s)
type instance Scalar (History_ cxt s a) = Scalar a
instance Semigroup a => Semigroup (History_ cxt s a) where
ha1 + ha2 = do
a1 <- ha1
a2 <- ha2
return $ a1+a2
instance Cancellative a => Cancellative (History_ cxt s a) where
ha1 - ha2 = do
a1 <- ha1
a2 <- ha2
return $ a1-a2
instance Monoid a => Monoid (History_ cxt s a) where
zero = return zero
instance Group a => Group (History_ cxt s a) where
negate ha = do
a <- ha
return $ negate a
type instance Logic (History_ cxt s a) = History_ cxt s (Logic a)
instance Eq_ a => Eq_ (History_ cxt s a) where
a==b = do
a' <- a
b' <- b
return $ a'==b'
instance POrd_ a => POrd_ (History_ cxt s a) where
# INLINABLE inf #
inf a b = do
a' <- a
b' <- b
return $ inf a' b'
instance Lattice_ a => Lattice_ (History_ cxt s a) where
# INLINABLE sup #
sup a b = do
a' <- a
b' <- b
return $ sup a' b'
instance MinBound_ a => MinBound_ (History_ cxt s a) where
minBound = return $ minBound
instance Bounded a => Bounded (History_ cxt s a) where
maxBound = return $ maxBound
instance Heyting a => Heyting (History_ cxt s a) where
(==>) a b = do
a' <- a
b' <- b
return $ a' ==> b'
instance Complemented a => Complemented (History_ cxt s a) where
not a = do
a' <- a
return $ not a'
instance Boolean a => Boolean (History_ cxt s a)
| This function is similar in spirit to the @while@ loop of imperative languages like
# INLINABLE iterate #
iterate :: forall cxt a. cxt a
# SCC iterate #
report opt0
opt1 <- step opt0
go opt0 opt1
where
report curopt
done <- stop prevopt curopt
if done
then return curopt
else do
opt' <- step curopt
go curopt opt'
class Has_x1 opt v where x1 :: opt v -> v
class Has_fx1 opt v where fx1 :: opt v -> Scalar v
type StopCondition a = forall cxt. cxt a => a -> a -> forall s. History_ cxt s Bool
This number is typically set fairly high ( at least one hundred , possibly in the millions ) .
maxIterations i _ _ = History $ do
(_ , x:_) <- get
return $ numReports x >= i
stopBelow ::
( Has_fx1 opt v
, Ord (Scalar v)
) => Scalar v
-> StopCondition (opt v)
stopBelow threshold _ opt = return $ (fx1 opt) < threshold
mulTolerance ::
( BoundedField (Scalar v)
, Has_fx1 opt v
-> StopCondition (opt v)
# SCC multiplicativeTollerance #
return $ (fx1 prevopt) /= infinity && left < right
where
left = 2*abs (fx1 curopt - fx1 prevopt)
right = tol*(abs (fx1 curopt) + abs (fx1 prevopt) + 1e-18)
fx1grows :: ( Has_fx1 opt v , Ord (Scalar v) ) => StopCondition (opt v)
fx1grows opt0 opt1 = return $ fx1 opt0 < fx1 opt1
noProgress :: Eq (opt v) => StopCondition (opt v)
noProgress opt0 opt1 = return $ opt0 == opt1
|
e7668b3421436bd2e3eff7751269c6e6b4ba3794a8b5c6b27abf2f1965aed1c6 | cmsc430/www | types.rkt | #lang racket
(provide (all-defined-out))
;; type Value =
;; | Integer
;; | Boolean
;; type Bits = Integer
(define int-shift 1)
(define type-int #b0)
(define type-bool #b1)
(define val-true #b01)
(define val-false #b11)
;; Bits -> Value
(define (bits->value b)
(cond [(= type-int (bitwise-and b #b1))
(arithmetic-shift b (- int-shift))]
[(= b val-true) #t]
[(= b val-false) #f]
[else (error "invalid bits")]))
;; Value -> Bits
(define (value->bits v)
(match v
[(? integer?) (arithmetic-shift v int-shift)]
[#t val-true]
[#f val-false]))
| null | https://raw.githubusercontent.com/cmsc430/www/d7635145c85ef168a05d15be8d565084e49e0f0f/langs/dupe/types.rkt | racket | type Value =
| Integer
| Boolean
type Bits = Integer
Bits -> Value
Value -> Bits | #lang racket
(provide (all-defined-out))
(define int-shift 1)
(define type-int #b0)
(define type-bool #b1)
(define val-true #b01)
(define val-false #b11)
(define (bits->value b)
(cond [(= type-int (bitwise-and b #b1))
(arithmetic-shift b (- int-shift))]
[(= b val-true) #t]
[(= b val-false) #f]
[else (error "invalid bits")]))
(define (value->bits v)
(match v
[(? integer?) (arithmetic-shift v int-shift)]
[#t val-true]
[#f val-false]))
|
dd7ca243251c2bb3754450134885cabcfa3bbca4dd460a6cf95a989fd79a23d4 | sph-mn/sph-lib | scm-format.scm | (import (sph string) (sph)
(sph other) (sph alist) (sph list) (srfi srfi-1) (sph hashtable) (sph lang scm-format) (sph test))
(define c scm-format-default-config)
(hashtables-set! c (q format) (q indent-string) "--")
(define (test-scm-format in exp)
(let*
( (config-format
(if (length-greater-one? in)
(ht-create (q format) (alist->hashtable (list->alist (last in)))) #f))
(res (scm-format (first in) 0 config-format)))
(if (equal? res exp) exp (pass (l (res) (display (string-replace-char res #\- #\space))) res))))
(define library-form
(q
(library (scm format test)
(export
(rename this-i-a-test this-i-another-test)
a
b
c)
(import
(srfi srfi-1)
(sph pattern synthetical)
(sph storage record)))))
(execute-tests-quasiquote
(scm-format
;multiple leading parenthesis spacing
(((let ((a001001001 1) (b001001001 2)) a-relatively-long-string) (max-chars-per-line 17)))
"(let\n--(-(a001001001 1)\n----(b001001001 2))\n--a-relatively-long-string)"
;general nesting
((1 2 ((+ 3 4)))) "(1 2 ((+ 3 4)))"
;double parenthesis
((1 ((2))) (max-chars-per-line 4)) "(1\n--(\n----(2)))"
;start\middle exprs limit
((1 2 3 4 5) (max-exprs-per-line-start 2 max-exprs-per-line-middle 2 max-exprs-per-line-end 0))
"(1 2\n--3 4\n--5)"
;max-line-chars
((111 133 22 1 222) (max-chars-per-line 4)) "(111\n--133\n--22\n--1 222)"
(;this is a testcomment
)
";this is a testcomment"
(#;(this is a testcomment
comment line 2
comment line 3))
"#;(this is a testcomment\n-comment line 2\n-comment line 3)"
( ( (#;(this is a testcomment
comment line 2
comment line 3))))
"( ( #;(this is a testcomment\n------comment line 2\n------comment line 3)))"
((lambda (var-1 var-2 var-3 var-4) body-1 body-2 body-3))
"(lambda (var-1 var-2 var-3 var-4) body-1 body-2 body-3)" ((unquote library-form))
"(library (scm format test)\n--(export\n----(rename this-i-a-test this-i-another-test)\n----a\n----b\n----c)\n--(import\n----(srfi srfi-1)\n----(sph pattern syntactical)\n----(sph storage record)))"
control chars in strings
((display "\n\t")) "(display \"\\n\\t\")"
( (lambda ()
"a
b
c")
(indent-string " "))
"(lambda ()\n \"a\n b\n c\")")) | null | https://raw.githubusercontent.com/sph-mn/sph-lib/c7daf74f42d6bd1304f49c2fef89dcd6dd94fdc9/other/manual-tests/scm-format.scm | scheme | multiple leading parenthesis spacing
general nesting
double parenthesis
start\middle exprs limit
max-line-chars
this is a testcomment
(this is a testcomment
(this is a testcomment | (import (sph string) (sph)
(sph other) (sph alist) (sph list) (srfi srfi-1) (sph hashtable) (sph lang scm-format) (sph test))
(define c scm-format-default-config)
(hashtables-set! c (q format) (q indent-string) "--")
(define (test-scm-format in exp)
(let*
( (config-format
(if (length-greater-one? in)
(ht-create (q format) (alist->hashtable (list->alist (last in)))) #f))
(res (scm-format (first in) 0 config-format)))
(if (equal? res exp) exp (pass (l (res) (display (string-replace-char res #\- #\space))) res))))
(define library-form
(q
(library (scm format test)
(export
(rename this-i-a-test this-i-another-test)
a
b
c)
(import
(srfi srfi-1)
(sph pattern synthetical)
(sph storage record)))))
(execute-tests-quasiquote
(scm-format
(((let ((a001001001 1) (b001001001 2)) a-relatively-long-string) (max-chars-per-line 17)))
"(let\n--(-(a001001001 1)\n----(b001001001 2))\n--a-relatively-long-string)"
((1 2 ((+ 3 4)))) "(1 2 ((+ 3 4)))"
((1 ((2))) (max-chars-per-line 4)) "(1\n--(\n----(2)))"
((1 2 3 4 5) (max-exprs-per-line-start 2 max-exprs-per-line-middle 2 max-exprs-per-line-end 0))
"(1 2\n--3 4\n--5)"
((111 133 22 1 222) (max-chars-per-line 4)) "(111\n--133\n--22\n--1 222)"
)
";this is a testcomment"
comment line 2
comment line 3))
"#;(this is a testcomment\n-comment line 2\n-comment line 3)"
comment line 2
comment line 3))))
"( ( #;(this is a testcomment\n------comment line 2\n------comment line 3)))"
((lambda (var-1 var-2 var-3 var-4) body-1 body-2 body-3))
"(lambda (var-1 var-2 var-3 var-4) body-1 body-2 body-3)" ((unquote library-form))
"(library (scm format test)\n--(export\n----(rename this-i-a-test this-i-another-test)\n----a\n----b\n----c)\n--(import\n----(srfi srfi-1)\n----(sph pattern syntactical)\n----(sph storage record)))"
control chars in strings
((display "\n\t")) "(display \"\\n\\t\")"
( (lambda ()
"a
b
c")
(indent-string " "))
"(lambda ()\n \"a\n b\n c\")")) |
56d3c5965df7172e6d76e70f4ef252d964d2ad7f85cc6bece0e2050706b5cab7 | LPCIC/matita | index.ml |
||M|| This file is part of HELM , an Hypertextual , Electronic
||A|| Library of Mathematics , developed at the Computer Science
||T|| Department , University of Bologna , Italy .
||I||
||T|| HELM is free software ; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or ( at your option ) any later version .
\ / This software is distributed as is , NO WARRANTY .
V _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
||M|| This file is part of HELM, an Hypertextual, Electronic
||A|| Library of Mathematics, developed at the Computer Science
||T|| Department, University of Bologna, Italy.
||I||
||T|| HELM is free software; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or (at your option) any later version.
\ / This software is distributed as is, NO WARRANTY.
V_______________________________________________________________ *)
$ I d : index.ml 11696 2011 - 11 - 21 09:42:44Z asperti $
module Index(B : Orderings.Blob) = struct
module U = FoUtils.Utils(B)
module Unif = FoUnif.Founif(B)
module Pp = Pp.Pp(B)
module ClauseOT =
struct
type t = Terms.direction * B.t Terms.unit_clause
let compare (d1,uc1) (d2,uc2) =
let c = Pervasives.compare d1 d2 in
if c <> 0 then c else U.compare_unit_clause uc1 uc2
;;
end
module ClauseSet :
Set.S with type elt = Terms.direction * B.t Terms.unit_clause
= Set.Make(ClauseOT)
open Discrimination_tree
module FotermIndexable : Indexable with
type constant_name = B.t and
type input = B.t Terms.foterm
=
struct
type input = B.t Terms.foterm
type constant_name = B.t
let path_string_of =
let rec aux arity = function
| Terms.Leaf a -> [Constant (a, arity)]
| Terms.Var i -> (* assert (arity = 0); *) [Variable]
(* FIXME : should this be allowed or not ?
| Terms.Node (Terms.Var _::_) ->
assert false *)
| Terms.Node ([] | [ _ ] ) -> assert false
(* FIXME : if we can have a variable we can also have a term
| Terms.Node (Terms.Node _::_) as t -> assert false *)
| Terms.Node (hd::tl) ->
aux (List.length tl) hd @ List.flatten (List.map (aux 0) tl)
in
aux 0
;;
let compare e1 e2 =
match e1,e2 with
| Constant (a1,ar1), Constant (a2,ar2) ->
let c = B.compare a1 a2 in
if c <> 0 then c else Pervasives.compare ar1 ar2
| Variable, Variable -> 0
| Constant _, Variable -> ~-1
| Variable, Constant _ -> 1
| Proposition, _ | _, Proposition
| Datatype, _ | _, Datatype
| Dead, _ | _, Dead
| Bound _, _ | _, Bound _ -> assert false
;;
let string_of_path l = String.concat "." (List.map (fun _ -> "*") l) ;;
end
module DT : DiscriminationTree with
type constant_name = B.t and
type input = B.t Terms.foterm and
type data = ClauseSet.elt and
type dataset = ClauseSet.t
= Make(FotermIndexable)(ClauseSet)
let process op t = function
| (_,Terms.Equation (l,_,_,Terms.Gt),_,_) as c ->
op t l (Terms.Left2Right, c)
| (_,Terms.Equation (_,r,_,Terms.Lt),_,_) as c ->
op t r (Terms.Right2Left, c)
| (_,Terms.Equation (l,r,_,Terms.Incomparable),vl,_) as c ->
op (op t l (Terms.Left2Right, c))
r (Terms.Right2Left, c)
| (_,Terms.Equation (l,r,_,Terms.Invertible),vl,_) as c ->
op t l (Terms.Left2Right, c)
| (_,Terms.Equation (_,r,_,Terms.Eq),_,_) -> assert false
| (_,Terms.Predicate p,_,_) as c ->
op t p (Terms.Nodir, c)
;;
let index_unit_clause =
process DT.index
let remove_unit_clause =
process DT.remove_index
let fold = DT.fold
let elems index =
DT.fold index (fun _ dataset acc -> ClauseSet.union dataset acc)
ClauseSet.empty
type active_set = B.t Terms.unit_clause list * DT.t
end
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/ng_paramodulation/index.ml | ocaml | assert (arity = 0);
FIXME : should this be allowed or not ?
| Terms.Node (Terms.Var _::_) ->
assert false
FIXME : if we can have a variable we can also have a term
| Terms.Node (Terms.Node _::_) as t -> assert false |
||M|| This file is part of HELM , an Hypertextual , Electronic
||A|| Library of Mathematics , developed at the Computer Science
||T|| Department , University of Bologna , Italy .
||I||
||T|| HELM is free software ; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or ( at your option ) any later version .
\ / This software is distributed as is , NO WARRANTY .
V _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
||M|| This file is part of HELM, an Hypertextual, Electronic
||A|| Library of Mathematics, developed at the Computer Science
||T|| Department, University of Bologna, Italy.
||I||
||T|| HELM is free software; you can redistribute it and/or
||A|| modify it under the terms of the GNU General Public License
\ / version 2 or (at your option) any later version.
\ / This software is distributed as is, NO WARRANTY.
V_______________________________________________________________ *)
$ I d : index.ml 11696 2011 - 11 - 21 09:42:44Z asperti $
module Index(B : Orderings.Blob) = struct
module U = FoUtils.Utils(B)
module Unif = FoUnif.Founif(B)
module Pp = Pp.Pp(B)
module ClauseOT =
struct
type t = Terms.direction * B.t Terms.unit_clause
let compare (d1,uc1) (d2,uc2) =
let c = Pervasives.compare d1 d2 in
if c <> 0 then c else U.compare_unit_clause uc1 uc2
;;
end
module ClauseSet :
Set.S with type elt = Terms.direction * B.t Terms.unit_clause
= Set.Make(ClauseOT)
open Discrimination_tree
module FotermIndexable : Indexable with
type constant_name = B.t and
type input = B.t Terms.foterm
=
struct
type input = B.t Terms.foterm
type constant_name = B.t
let path_string_of =
let rec aux arity = function
| Terms.Leaf a -> [Constant (a, arity)]
| Terms.Node ([] | [ _ ] ) -> assert false
| Terms.Node (hd::tl) ->
aux (List.length tl) hd @ List.flatten (List.map (aux 0) tl)
in
aux 0
;;
let compare e1 e2 =
match e1,e2 with
| Constant (a1,ar1), Constant (a2,ar2) ->
let c = B.compare a1 a2 in
if c <> 0 then c else Pervasives.compare ar1 ar2
| Variable, Variable -> 0
| Constant _, Variable -> ~-1
| Variable, Constant _ -> 1
| Proposition, _ | _, Proposition
| Datatype, _ | _, Datatype
| Dead, _ | _, Dead
| Bound _, _ | _, Bound _ -> assert false
;;
let string_of_path l = String.concat "." (List.map (fun _ -> "*") l) ;;
end
module DT : DiscriminationTree with
type constant_name = B.t and
type input = B.t Terms.foterm and
type data = ClauseSet.elt and
type dataset = ClauseSet.t
= Make(FotermIndexable)(ClauseSet)
let process op t = function
| (_,Terms.Equation (l,_,_,Terms.Gt),_,_) as c ->
op t l (Terms.Left2Right, c)
| (_,Terms.Equation (_,r,_,Terms.Lt),_,_) as c ->
op t r (Terms.Right2Left, c)
| (_,Terms.Equation (l,r,_,Terms.Incomparable),vl,_) as c ->
op (op t l (Terms.Left2Right, c))
r (Terms.Right2Left, c)
| (_,Terms.Equation (l,r,_,Terms.Invertible),vl,_) as c ->
op t l (Terms.Left2Right, c)
| (_,Terms.Equation (_,r,_,Terms.Eq),_,_) -> assert false
| (_,Terms.Predicate p,_,_) as c ->
op t p (Terms.Nodir, c)
;;
let index_unit_clause =
process DT.index
let remove_unit_clause =
process DT.remove_index
let fold = DT.fold
let elems index =
DT.fold index (fun _ dataset acc -> ClauseSet.union dataset acc)
ClauseSet.empty
type active_set = B.t Terms.unit_clause list * DT.t
end
|
e8238475f7be75d31d11f8a4df1e35c847a1532264964b169cd7a87dd05e0010 | cj1128/sicp-review | prime.scm | (define (smallest-divisor n) (find-divisor n 2))
(define (find-divisor n test)
(cond
((> (square test) n) n)
((divides? test n) test)
(else (find-divisor n (+ test 1)))))
(define (divides? a b) (= (remainder b a) 0))
(define (prime? n) (= n (smallest-divisor n)))
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-1/1.2/prime.scm | scheme | (define (smallest-divisor n) (find-divisor n 2))
(define (find-divisor n test)
(cond
((> (square test) n) n)
((divides? test n) test)
(else (find-divisor n (+ test 1)))))
(define (divides? a b) (= (remainder b a) 0))
(define (prime? n) (= n (smallest-divisor n)))
|
|
2ae297eff54285e753e71c63eb8b8bfd59a80ceb8f117e9315e823862874edca | kpreid/e-on-cl | vat.lisp | Copyright 2005 - 2007 , under the terms of the MIT X license
found at ................
(in-package :e.elib)
;;; *VAT* is declared in ref.lisp.
(defun call-with-turn (body vat &key (label t))
"Execute the 'body' thunk, as a turn in the given vat."
(assert label)
(when (vat-in-turn vat)
(error "~S is already executing a turn, ~S, so turn ~S may not execute" vat (vat-in-turn vat) label))
(unless (or (null *vat*)
(eq *vat* vat))
(error "there is already a current vat, ~S, so ~S may not execute a turn" *vat* vat))
(unwind-protect
(let ((*vat* vat)
(*runner* (vat-runner vat)))
(setf (vat-in-turn vat) label)
(take-turn-serial body))
(setf (vat-in-turn vat) nil)))
(defmacro with-turn ((&rest args) &body body)
"Execute the body, as a turn in the given vat."
`(call-with-turn (lambda () ,@body) ,@args))
(defclass vat ()
((runner :initarg :runner
:initform (error "no runner specified in vat creation")
:accessor vat-runner
:type runner)
(in-turn :initform nil
:accessor vat-in-turn
:type t
:documentation "Whether some type of top-level turn is currently being executed in this vat; if not NIL, is a label for the turn. Used for consistency checking.")
(safe-scope :accessor vat-safe-scope)
(label :initarg :label
:initform nil
:type (or null string)
:reader label)
(vat-log-id :reader vat-log-id)
(turn-serial-counter :initform 0
:type (integer 0)
:accessor turn-serial-counter)
(sugar-cache :initform (make-hash-table :test #'equal)
:type hash-table
:reader sugar-cache
:documentation "Experimental: For looking up objects which are sugar-delegates for objects shared between vats.")
(e.rune::incorporated-files :initform nil
:type list
:accessor e.rune::incorporated-files)
(vat-comm-handler :accessor vat-comm-handler)))
(defmethod initialize-instance :after ((vat vat) &rest initargs)
(declare (ignore initargs))
(let ((*vat* vat))
(setf (slot-value vat 'vat-log-id) (make-vat-log-id (label vat))
(vat-safe-scope vat) (e.knot:make-safe-scope)
(vat-comm-handler vat) (make-comm-handler-promise vat))))
(defmethod print-object ((vat vat) stream)
(print-unreadable-object (vat stream :type t :identity t)
(format stream "~S~:[~; (in turn)~]"
(label vat)
(vat-in-turn vat))))
(defmethod enqueue-turn ((vat vat) function)
(enqueue-turn (vat-runner vat)
(lambda ()
(call-with-turn function vat :label "basic turn")))
(values))
(defmethod vr-add-io-handler ((vat vat) target direction function)
(vr-add-io-handler (vat-runner vat)
target
direction
(lambda (target*)
(assert (eql target target*) () "buh?")
(with-turn (vat :label (format nil "IO handler ~A for ~A"
function
target))
(funcall (ref-shorten function) target*)))))
(declaim (inline queue-send-either))
(defun queue-send-either (rec mverb args resolver)
(assert (eq (ref-state rec) 'near) () "inconsistency: send default case was called with a non-NEAR receiver, ~S" rec)
(let ((id (log-unique-id)))
(log-event '("org.ref_send.log.Sent" "org.ref_send.log.Event")
`((message . ,id)))
(enqueue-turn *vat* (lambda ()
(log-event '("org.ref_send.log.Got" "org.ref_send.log.Event")
`((message . ,id)))
(e. resolver |resolve|
(handler-case-with-backtrace
(apply #'e-call-dispatch rec mverb args)
(error (problem backtrace)
XXX using e printing routines here is invoking objects outside a proper turn ; do one of :
( a ) CL print instead
( b ) make printing the error done in yet another turn ( possible object's - print - representation - has - changed problem )
(efuncall e.knot:+sys-trace+ (format nil "problem in send ~A <- ~A ~A: ~A" (e-quote rec) (symbol-name mverb) (e-quote (coerce args 'vector)) problem))
(make-unconnected-ref (transform-condition-for-e-catch problem :backtrace backtrace)))))))))
(defmethod e-send-dispatch (rec mverb &rest args)
(assert (eq (ref-state rec) 'near) () "inconsistency: e-send-dispatch default case was called with a non-NEAR receiver")
(multiple-value-bind (promise resolver) (make-promise)
(queue-send-either rec mverb args resolver)
promise))
(defmethod e-send-only-dispatch (rec mverb &rest args)
(queue-send-either rec mverb args +dummy-resolver+)
nil)
(defmethod enqueue-timed ((vat vat) time func)
(enqueue-timed (vat-runner vat) time
(lambda ()
;; XXX future improvement: human-formatted time
(call-with-turn func vat :label (format nil "~A at time ~A" func time)))))
(defun establish-vat (&rest initargs &key label &allow-other-keys)
(assert (null *vat*))
(assert (null *runner*))
(setf *runner* (make-runner-for-this-thread :label label))
(setf *vat* (apply #'make-instance 'vat :runner *runner* initargs)))
| null | https://raw.githubusercontent.com/kpreid/e-on-cl/f93d188051c66db0ad4ff150bd73b838f7bc25ed/lisp/vat.lisp | lisp | *VAT* is declared in ref.lisp.
do one of :
XXX future improvement: human-formatted time | Copyright 2005 - 2007 , under the terms of the MIT X license
found at ................
(in-package :e.elib)
(defun call-with-turn (body vat &key (label t))
"Execute the 'body' thunk, as a turn in the given vat."
(assert label)
(when (vat-in-turn vat)
(error "~S is already executing a turn, ~S, so turn ~S may not execute" vat (vat-in-turn vat) label))
(unless (or (null *vat*)
(eq *vat* vat))
(error "there is already a current vat, ~S, so ~S may not execute a turn" *vat* vat))
(unwind-protect
(let ((*vat* vat)
(*runner* (vat-runner vat)))
(setf (vat-in-turn vat) label)
(take-turn-serial body))
(setf (vat-in-turn vat) nil)))
(defmacro with-turn ((&rest args) &body body)
"Execute the body, as a turn in the given vat."
`(call-with-turn (lambda () ,@body) ,@args))
(defclass vat ()
((runner :initarg :runner
:initform (error "no runner specified in vat creation")
:accessor vat-runner
:type runner)
(in-turn :initform nil
:accessor vat-in-turn
:type t
:documentation "Whether some type of top-level turn is currently being executed in this vat; if not NIL, is a label for the turn. Used for consistency checking.")
(safe-scope :accessor vat-safe-scope)
(label :initarg :label
:initform nil
:type (or null string)
:reader label)
(vat-log-id :reader vat-log-id)
(turn-serial-counter :initform 0
:type (integer 0)
:accessor turn-serial-counter)
(sugar-cache :initform (make-hash-table :test #'equal)
:type hash-table
:reader sugar-cache
:documentation "Experimental: For looking up objects which are sugar-delegates for objects shared between vats.")
(e.rune::incorporated-files :initform nil
:type list
:accessor e.rune::incorporated-files)
(vat-comm-handler :accessor vat-comm-handler)))
(defmethod initialize-instance :after ((vat vat) &rest initargs)
(declare (ignore initargs))
(let ((*vat* vat))
(setf (slot-value vat 'vat-log-id) (make-vat-log-id (label vat))
(vat-safe-scope vat) (e.knot:make-safe-scope)
(vat-comm-handler vat) (make-comm-handler-promise vat))))
(defmethod print-object ((vat vat) stream)
(print-unreadable-object (vat stream :type t :identity t)
(format stream "~S~:[~; (in turn)~]"
(label vat)
(vat-in-turn vat))))
(defmethod enqueue-turn ((vat vat) function)
(enqueue-turn (vat-runner vat)
(lambda ()
(call-with-turn function vat :label "basic turn")))
(values))
(defmethod vr-add-io-handler ((vat vat) target direction function)
(vr-add-io-handler (vat-runner vat)
target
direction
(lambda (target*)
(assert (eql target target*) () "buh?")
(with-turn (vat :label (format nil "IO handler ~A for ~A"
function
target))
(funcall (ref-shorten function) target*)))))
(declaim (inline queue-send-either))
(defun queue-send-either (rec mverb args resolver)
(assert (eq (ref-state rec) 'near) () "inconsistency: send default case was called with a non-NEAR receiver, ~S" rec)
(let ((id (log-unique-id)))
(log-event '("org.ref_send.log.Sent" "org.ref_send.log.Event")
`((message . ,id)))
(enqueue-turn *vat* (lambda ()
(log-event '("org.ref_send.log.Got" "org.ref_send.log.Event")
`((message . ,id)))
(e. resolver |resolve|
(handler-case-with-backtrace
(apply #'e-call-dispatch rec mverb args)
(error (problem backtrace)
( a ) CL print instead
( b ) make printing the error done in yet another turn ( possible object's - print - representation - has - changed problem )
(efuncall e.knot:+sys-trace+ (format nil "problem in send ~A <- ~A ~A: ~A" (e-quote rec) (symbol-name mverb) (e-quote (coerce args 'vector)) problem))
(make-unconnected-ref (transform-condition-for-e-catch problem :backtrace backtrace)))))))))
(defmethod e-send-dispatch (rec mverb &rest args)
(assert (eq (ref-state rec) 'near) () "inconsistency: e-send-dispatch default case was called with a non-NEAR receiver")
(multiple-value-bind (promise resolver) (make-promise)
(queue-send-either rec mverb args resolver)
promise))
(defmethod e-send-only-dispatch (rec mverb &rest args)
(queue-send-either rec mverb args +dummy-resolver+)
nil)
(defmethod enqueue-timed ((vat vat) time func)
(enqueue-timed (vat-runner vat) time
(lambda ()
(call-with-turn func vat :label (format nil "~A at time ~A" func time)))))
(defun establish-vat (&rest initargs &key label &allow-other-keys)
(assert (null *vat*))
(assert (null *runner*))
(setf *runner* (make-runner-for-this-thread :label label))
(setf *vat* (apply #'make-instance 'vat :runner *runner* initargs)))
|
a032ebe34d16d01a988dd76c6174a59faacd04085f63157c0396367026d31072 | mbutterick/beautiful-racket | lexer.rkt | #lang br
(require brag/support)
(define-lex-abbrev digits (:+ (char-set "0123456789")))
(define-lex-abbrev reserved-terms (:or "print" "goto" "end" "+" ":" ";" "let" "=" "input" "-" "*" "/" "^" "mod" "(" ")" "if" "then" "else" "<" ">" "<>" "and" "or" "not" "gosub" "return" "for" "to" "step" "next"))
(define basic-lexer
(lexer-srcloc
["\n" (token 'NEWLINE lexeme)]
[whitespace (token lexeme #:skip? #t)]
[(from/stop-before "rem" "\n") (token 'REM lexeme)]
[reserved-terms (token lexeme lexeme)]
[(:seq alphabetic (:* (:or alphabetic numeric "$")))
(token 'ID (string->symbol lexeme))]
[digits (token 'INTEGER (string->number lexeme))]
[(:or (:seq (:? digits) "." digits)
(:seq digits "."))
(token 'DECIMAL (string->number lexeme))]
[(:or (from/to "\"" "\"") (from/to "'" "'"))
(token 'STRING
(substring lexeme
1 (sub1 (string-length lexeme))))]))
(provide basic-lexer) | null | https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/basic-demo-2/lexer.rkt | racket | #lang br
(require brag/support)
(define-lex-abbrev digits (:+ (char-set "0123456789")))
(define-lex-abbrev reserved-terms (:or "print" "goto" "end" "+" ":" ";" "let" "=" "input" "-" "*" "/" "^" "mod" "(" ")" "if" "then" "else" "<" ">" "<>" "and" "or" "not" "gosub" "return" "for" "to" "step" "next"))
(define basic-lexer
(lexer-srcloc
["\n" (token 'NEWLINE lexeme)]
[whitespace (token lexeme #:skip? #t)]
[(from/stop-before "rem" "\n") (token 'REM lexeme)]
[reserved-terms (token lexeme lexeme)]
[(:seq alphabetic (:* (:or alphabetic numeric "$")))
(token 'ID (string->symbol lexeme))]
[digits (token 'INTEGER (string->number lexeme))]
[(:or (:seq (:? digits) "." digits)
(:seq digits "."))
(token 'DECIMAL (string->number lexeme))]
[(:or (from/to "\"" "\"") (from/to "'" "'"))
(token 'STRING
(substring lexeme
1 (sub1 (string-length lexeme))))]))
(provide basic-lexer) |
|
19e37eb99c5ed7c55a445fe239f1adb4729c5494c60cfe46174fddbf383f8be4 | ethercrow/lightstep-haskell | TestPropagation.hs | {-# LANGUAGE OverloadedStrings #-}
module TestPropagation where
import Control.Lens
import Data.Function
import Data.ProtoLens.Message (defMessage)
import Data.Word
import LightStep.Propagation
import Test.Tasty.HUnit
import Text.Printf
prop_u64_roundtrip :: Word64 -> Bool
prop_u64_roundtrip x =
Just x == decode_u64 (encode_u64 x)
prop_text_propagator_roundtrip :: Word64 -> Word64 -> Bool
prop_text_propagator_roundtrip tid sid =
let c =
defMessage
& traceId .~ tid
& spanId .~ sid
p = textPropagator
in Just c == extract p (inject p c)
prop_b3_propagator_roundtrip :: Word64 -> Word64 -> Bool
prop_b3_propagator_roundtrip tid sid =
let c =
defMessage
& traceId .~ tid
& spanId .~ sid
p = b3Propagator
in Just c == extract p (inject p c)
| null | https://raw.githubusercontent.com/ethercrow/lightstep-haskell/f447fd37a6c53dcd38c32c53f71a71386f3e425a/unit-test/TestPropagation.hs | haskell | # LANGUAGE OverloadedStrings # |
module TestPropagation where
import Control.Lens
import Data.Function
import Data.ProtoLens.Message (defMessage)
import Data.Word
import LightStep.Propagation
import Test.Tasty.HUnit
import Text.Printf
prop_u64_roundtrip :: Word64 -> Bool
prop_u64_roundtrip x =
Just x == decode_u64 (encode_u64 x)
prop_text_propagator_roundtrip :: Word64 -> Word64 -> Bool
prop_text_propagator_roundtrip tid sid =
let c =
defMessage
& traceId .~ tid
& spanId .~ sid
p = textPropagator
in Just c == extract p (inject p c)
prop_b3_propagator_roundtrip :: Word64 -> Word64 -> Bool
prop_b3_propagator_roundtrip tid sid =
let c =
defMessage
& traceId .~ tid
& spanId .~ sid
p = b3Propagator
in Just c == extract p (inject p c)
|
1cb348253b461c63303d386cf48b86b322edffa93d4b3466573a073bc3fe84be | ivanperez-keera/dunai | SamplingMonad.hs | {-# LANGUAGE CPP #-}
# LANGUAGE ExistentialQuantification #
module Control.Monad.SamplingMonad where
import Control.Monad.TaggingMonad
import Data.Monoid
import Data.Maybe.Util
#if MIN_VERSION_base(4,9,0)
import Data.Semigroup as Sem
#endif
type SamplingMonad t a = TaggingMonad (NextSample t) a
data NextSample a = Ord a => NextSample { unNext :: Maybe a }
#if MIN_VERSION_base(4,9,0)
instance Ord a => Semigroup (NextSample a) where
(NextSample x) <> (NextSample y) = NextSample $ mergeMaybe min x y
#endif
instance Ord a => Monoid (NextSample a) where
mempty = NextSample Nothing
#if !(MIN_VERSION_base(4,9,0))
mappend (NextSample x) (NextSample y) = NextSample $ mergeMaybe min x y
#elif !(MIN_VERSION_base(4,11,0))
-- this is redundant starting with base-4.11 / GHC 8.4
if you want to avoid CPP , you can define ` mappend = ( < > ) ` unconditionally
mappend = (Sem.<>)
#endif
| null | https://raw.githubusercontent.com/ivanperez-keera/dunai/99091c3391c0ba15e9075579e0b73c5660e994c2/dunai-examples/taggingmonad/Control/Monad/SamplingMonad.hs | haskell | # LANGUAGE CPP #
this is redundant starting with base-4.11 / GHC 8.4 | # LANGUAGE ExistentialQuantification #
module Control.Monad.SamplingMonad where
import Control.Monad.TaggingMonad
import Data.Monoid
import Data.Maybe.Util
#if MIN_VERSION_base(4,9,0)
import Data.Semigroup as Sem
#endif
type SamplingMonad t a = TaggingMonad (NextSample t) a
data NextSample a = Ord a => NextSample { unNext :: Maybe a }
#if MIN_VERSION_base(4,9,0)
instance Ord a => Semigroup (NextSample a) where
(NextSample x) <> (NextSample y) = NextSample $ mergeMaybe min x y
#endif
instance Ord a => Monoid (NextSample a) where
mempty = NextSample Nothing
#if !(MIN_VERSION_base(4,9,0))
mappend (NextSample x) (NextSample y) = NextSample $ mergeMaybe min x y
#elif !(MIN_VERSION_base(4,11,0))
if you want to avoid CPP , you can define ` mappend = ( < > ) ` unconditionally
mappend = (Sem.<>)
#endif
|
276d0283fba9d3871758f08713bc7439423ee2642e8bc5b7f60d4da92e9c004f | alexandergunnarson/quantum | core.cljc | (ns quantum.untyped.core.core
(:require
#?@(:clj
[[environ.core :as env]])
[cuerdas.core :as str+]
[quantum.untyped.core.type.predicates :as utpred
:refer [with-metable? metable?]]))
;; ===== Environment ===== ;;
(def lang #?(:clj :clj :cljs :cljs))
#?(:clj
(defn pid []
(->> (java.lang.management.ManagementFactory/getRuntimeMXBean)
(.getName))))
#?(:clj
(binding [*out* *err*]
(when-not (= (:print-pid? env/env) "false") (println "PID:" (pid)))
(when-not (= (:print-java-version? env/env) "false") (println "Java version:" (System/getProperty "java.version")))
(flush)))
;; ===== Compilation ===== ;;
(defonce externs? (atom true))
= = = = = = = = = ; ;
(defonce *registered-components (atom {}))
;; ===== Miscellaneous ===== ;;
(defn >sentinel [] #?(:clj (Object.) :cljs #js {}))
(def >object >sentinel)
; ===== COLLECTIONS =====
(defn seq=
([a b] (seq= a b =))
([a b eq-f]
(boolean
(when (or (sequential? b) #?(:clj (instance? java.util.List b)
:cljs (list? b)))
(loop [a (seq a) b (seq b)]
(when (identical? (nil? a) (nil? b))
(or (nil? a)
(when (eq-f (first a) (first b))
(recur (next a) (next b))))))))))
(defn code=
"Ensures that two pieces of code are equivalent.
This means ensuring that seqs, vectors, and maps are only allowed to be compared with
each other, and that metadata is equivalent."
[code0 code1]
(if (metable? code0)
(and (metable? code1)
(= (meta code0) (meta code1))
(cond (seq? code0) (and (seq? code1) (seq= code0 code1 code=))
(vector? code0) (and (vector? code1) (seq= (seq code0) (seq code1) code=))
(map? code0) (and (map? code1) (seq= (seq code0) (seq code1) code=))
:else (= code0 code1)))
(and (not (metable? code1))
(= code0 code1))))
;; From `quantum.untyped.core.form.evaluate` — used below in `defalias`
(defn cljs-env?
"Given an &env from a macro, tells whether it is expanding into CLJS."
{:from ""}
[env]
(boolean (:ns env)))
(defn case-env|matches? [env k]
(case k
TODO should make this branching
:cljs (cljs-env? env)
:clr (throw (ex-info "TODO: Conditional compilation for CLR not supported" {:platform :clr}))
(throw (ex-info "Conditional compilation for platform not supported" {:platform k}))))
#?(:clj
(defmacro case-env*
"Conditionally compiles depending on the supplied environment (e.g. CLJ, CLJS, CLR)."
{:usage `(defmacro abcde [a]
(case-env* &env :clj `(+ ~a 2) :cljs `(+ ~a 1) `(+ ~a 3)))
:todo {0 "Not sure how CLJ environment would be differentiated from others"}}
([env]
`(throw (ex-info "Compilation unhandled for environment" {:env ~env})))
([env v] v)
([env k v & kvs]
`(let [env# ~env]
(if (case-env|matches? env# ~k)
~v
(case-env* env# ~@kvs))))))
#?(:clj
(defmacro case-env
"Conditionally compiles depending on the supplied environment (e.g. CLJ, CLJS, CLR)."
{:usage `(defmacro abcde [a]
(case-env :clj `(+ ~a 2) :cljs `(+ ~a 1) `(+ ~a 3)))}
([& args] `(case-env* ~'&env ~@args))))
;; From `quantum.untyped.core.vars` — used below in `walk`
(def update-meta vary-meta)
(defn merge-meta-from [to from] (update-meta to merge (meta from)))
(defn replace-meta-from [to from] (with-meta to (meta from)))
#?(:clj (defn defalias* [^clojure.lang.Var orig-var ns-name- var-name]
(let [;; to avoid warnings
var-name' (with-meta var-name (-> orig-var meta (select-keys [:dynamic])))
^clojure.lang.Var var-
(if (.hasRoot orig-var)
(intern ns-name- var-name' @orig-var)
(intern ns-name- var-name'))]
;; because this doesn't always get set correctly
(cond-> var-
(.isDynamic orig-var)
(doto (.setDynamic))))))
#?(:clj
(defmacro defalias
"Defines an alias for a var: a new var with the same root binding (if
any) and similar metadata. The metadata of the alias is its initial
metadata (as provided by def) merged into the metadata of the original."
{:attribution 'clojure.contrib.def/defalias
:contributors ["Alex Gunnarson"]}
([orig]
`(defalias ~(symbol (name orig)) ~orig))
([name orig]
`(doto ~(case-env
:clj `(defalias* (var ~orig) '~(ns-name *ns*) '~name)
:cljs `(def ~name (-> ~orig var deref)))
(alter-meta! merge (meta (var ~orig)))))
([name orig doc]
(list `defalias (with-meta name (assoc (meta name) :doc doc)) orig))))
#?(:clj
(defmacro defaliases'
"`defalias`es multiple vars ->`names` in the given namespace ->`ns`."
[ns- & names]
`(do ~@(for [name- names]
`(defalias ~name- ~(symbol (name ns-) (name name-)))))))
#?(:clj
(defmacro defaliases
"`defalias`es multiple vars ->`names` in the given namespace alias ->`alias`."
[alias- & names]
(let [ns-sym (if-let [resolved (get (ns-aliases *ns*) alias-)]
(ns-name resolved)
alias-)]
`(defaliases' ~ns-sym ~@names))))
;; From `quantum.untyped.core.collections.tree` — used in `quantum.untyped.core.macros`
(defn walk
"Like `clojure.walk`, but ensures preservation of metadata."
[inner outer form]
(cond
(list? form) (outer (replace-meta-from (apply list (map inner form)) form))
#?@(:clj [(map-entry? form) (outer (replace-meta-from (vec (map inner form)) form))])
(seq? form) (outer (replace-meta-from (doall (map inner form)) form))
(record? form) (outer (replace-meta-from (reduce (fn [r x] (conj r (inner x))) form form) form))
(coll? form) (outer (replace-meta-from (into (empty form) (map inner form)) form))
:else (outer form)))
(defn postwalk [f form] (walk (partial postwalk f) f form))
(defn prewalk [f form] (walk (partial prewalk f) identity (f form)))
;; From `quantum.untyped.core.log` — used to log namespaces
#?(:cljs (enable-console-print!))
(defrecord
^{:doc "This is a record and not a map because it's quicker
to check the default levels (member access: O(1)) than
it would be with a hash-map (O(log32(n)))."}
LoggingLevels
[warn user alert info inspect debug macro-expand trace env])
(defonce *log-levels
(atom (map->LoggingLevels
(zipmap #{:always :error :warn :ns} (repeat true)))))
(defonce *outs
(atom #?(:clj (if-let [out-path (or (System/getProperty "quantum.core.log:out-file")
(System/getProperty "quantum.core.log|out-file"))]
(let [_ (binding [*out* *err*] (println "Logging to" out-path))
fos (-> out-path
(java.io.FileOutputStream. )
(java.io.OutputStreamWriter.)
(java.io.BufferedWriter. ))]
(fn [] [*err* fos]))
(fn [] [*err*])) ; in order to not print to file
:cljs (fn [] [*out*]))))
(defn print-ns-name-to-outs! [ns-name-]
(doseq [out (@*outs)] (binding [*out* out] (println lang ":" "loading namespace" ns-name-) (flush)))
ns-name-)
#?(:clj
(defmacro log-this-ns []
`(if (get @*log-levels :ns) (print-ns-name-to-outs! '~(ns-name *ns*)) true)))
;; From `quantum.untyped.core.string`
#?(:clj
(defmacro istr
"'Interpolated string.' Accepts one or more strings; emits a `str` invocation that
concatenates the string data and evaluated expressions contained
within that argument. Evaluation is controlled using ~{} and ~()
forms. The former is used for simple value replacement using
clojure.core/str; the latter can be used to embed the results of
arbitrary function invocation into the produced string.
Examples:
user=> (def v 30.5)
#'user/v
user=> (istr \"This trial required ~{v}ml of solution.\")
\"This trial required 30.5ml of solution.\"
user=> (istr \"There are ~(int v) days in November.\")
\"There are 30 days in November.\"
user=> (def m {:a [1 2 3]})
#'user/m
user=> (istr \"The total for your order is $~(->> m :a (apply +)).\")
\"The total for your order is $6.\"
user=> (istr \"Just split a long interpolated string up into ~(-> m :a (get 0)), \"
\"~(-> m :a (get 1)), or even ~(-> m :a (get 2)) separate strings \"
\"if you don't want a << expression to end up being e.g. ~(* 4 (int v)) \"
\"columns wide.\")
\"Just split a long interpolated string up into 1, 2, or even 3 separate strings if you don't want a << expression to end up being e.g. 120 columns wide.\"
Note that quotes surrounding string literals within ~() forms must be
escaped."
[& args] `(str+/istr ~@args)))
| null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src-untyped/quantum/untyped/core/core.cljc | clojure | ===== Environment ===== ;;
===== Compilation ===== ;;
;
===== Miscellaneous ===== ;;
===== COLLECTIONS =====
From `quantum.untyped.core.form.evaluate` — used below in `defalias`
From `quantum.untyped.core.vars` — used below in `walk`
to avoid warnings
because this doesn't always get set correctly
From `quantum.untyped.core.collections.tree` — used in `quantum.untyped.core.macros`
From `quantum.untyped.core.log` — used to log namespaces
in order to not print to file
From `quantum.untyped.core.string`
emits a `str` invocation that
the latter can be used to embed the results of | (ns quantum.untyped.core.core
(:require
#?@(:clj
[[environ.core :as env]])
[cuerdas.core :as str+]
[quantum.untyped.core.type.predicates :as utpred
:refer [with-metable? metable?]]))
(def lang #?(:clj :clj :cljs :cljs))
#?(:clj
(defn pid []
(->> (java.lang.management.ManagementFactory/getRuntimeMXBean)
(.getName))))
#?(:clj
(binding [*out* *err*]
(when-not (= (:print-pid? env/env) "false") (println "PID:" (pid)))
(when-not (= (:print-java-version? env/env) "false") (println "Java version:" (System/getProperty "java.version")))
(flush)))
(defonce externs? (atom true))
(defonce *registered-components (atom {}))
(defn >sentinel [] #?(:clj (Object.) :cljs #js {}))
(def >object >sentinel)
(defn seq=
([a b] (seq= a b =))
([a b eq-f]
(boolean
(when (or (sequential? b) #?(:clj (instance? java.util.List b)
:cljs (list? b)))
(loop [a (seq a) b (seq b)]
(when (identical? (nil? a) (nil? b))
(or (nil? a)
(when (eq-f (first a) (first b))
(recur (next a) (next b))))))))))
(defn code=
"Ensures that two pieces of code are equivalent.
This means ensuring that seqs, vectors, and maps are only allowed to be compared with
each other, and that metadata is equivalent."
[code0 code1]
(if (metable? code0)
(and (metable? code1)
(= (meta code0) (meta code1))
(cond (seq? code0) (and (seq? code1) (seq= code0 code1 code=))
(vector? code0) (and (vector? code1) (seq= (seq code0) (seq code1) code=))
(map? code0) (and (map? code1) (seq= (seq code0) (seq code1) code=))
:else (= code0 code1)))
(and (not (metable? code1))
(= code0 code1))))
(defn cljs-env?
"Given an &env from a macro, tells whether it is expanding into CLJS."
{:from ""}
[env]
(boolean (:ns env)))
(defn case-env|matches? [env k]
(case k
TODO should make this branching
:cljs (cljs-env? env)
:clr (throw (ex-info "TODO: Conditional compilation for CLR not supported" {:platform :clr}))
(throw (ex-info "Conditional compilation for platform not supported" {:platform k}))))
#?(:clj
(defmacro case-env*
"Conditionally compiles depending on the supplied environment (e.g. CLJ, CLJS, CLR)."
{:usage `(defmacro abcde [a]
(case-env* &env :clj `(+ ~a 2) :cljs `(+ ~a 1) `(+ ~a 3)))
:todo {0 "Not sure how CLJ environment would be differentiated from others"}}
([env]
`(throw (ex-info "Compilation unhandled for environment" {:env ~env})))
([env v] v)
([env k v & kvs]
`(let [env# ~env]
(if (case-env|matches? env# ~k)
~v
(case-env* env# ~@kvs))))))
#?(:clj
(defmacro case-env
"Conditionally compiles depending on the supplied environment (e.g. CLJ, CLJS, CLR)."
{:usage `(defmacro abcde [a]
(case-env :clj `(+ ~a 2) :cljs `(+ ~a 1) `(+ ~a 3)))}
([& args] `(case-env* ~'&env ~@args))))
(def update-meta vary-meta)
(defn merge-meta-from [to from] (update-meta to merge (meta from)))
(defn replace-meta-from [to from] (with-meta to (meta from)))
#?(:clj (defn defalias* [^clojure.lang.Var orig-var ns-name- var-name]
var-name' (with-meta var-name (-> orig-var meta (select-keys [:dynamic])))
^clojure.lang.Var var-
(if (.hasRoot orig-var)
(intern ns-name- var-name' @orig-var)
(intern ns-name- var-name'))]
(cond-> var-
(.isDynamic orig-var)
(doto (.setDynamic))))))
#?(:clj
(defmacro defalias
"Defines an alias for a var: a new var with the same root binding (if
any) and similar metadata. The metadata of the alias is its initial
metadata (as provided by def) merged into the metadata of the original."
{:attribution 'clojure.contrib.def/defalias
:contributors ["Alex Gunnarson"]}
([orig]
`(defalias ~(symbol (name orig)) ~orig))
([name orig]
`(doto ~(case-env
:clj `(defalias* (var ~orig) '~(ns-name *ns*) '~name)
:cljs `(def ~name (-> ~orig var deref)))
(alter-meta! merge (meta (var ~orig)))))
([name orig doc]
(list `defalias (with-meta name (assoc (meta name) :doc doc)) orig))))
#?(:clj
(defmacro defaliases'
"`defalias`es multiple vars ->`names` in the given namespace ->`ns`."
[ns- & names]
`(do ~@(for [name- names]
`(defalias ~name- ~(symbol (name ns-) (name name-)))))))
#?(:clj
(defmacro defaliases
"`defalias`es multiple vars ->`names` in the given namespace alias ->`alias`."
[alias- & names]
(let [ns-sym (if-let [resolved (get (ns-aliases *ns*) alias-)]
(ns-name resolved)
alias-)]
`(defaliases' ~ns-sym ~@names))))
(defn walk
"Like `clojure.walk`, but ensures preservation of metadata."
[inner outer form]
(cond
(list? form) (outer (replace-meta-from (apply list (map inner form)) form))
#?@(:clj [(map-entry? form) (outer (replace-meta-from (vec (map inner form)) form))])
(seq? form) (outer (replace-meta-from (doall (map inner form)) form))
(record? form) (outer (replace-meta-from (reduce (fn [r x] (conj r (inner x))) form form) form))
(coll? form) (outer (replace-meta-from (into (empty form) (map inner form)) form))
:else (outer form)))
(defn postwalk [f form] (walk (partial postwalk f) f form))
(defn prewalk [f form] (walk (partial prewalk f) identity (f form)))
#?(:cljs (enable-console-print!))
(defrecord
^{:doc "This is a record and not a map because it's quicker
to check the default levels (member access: O(1)) than
it would be with a hash-map (O(log32(n)))."}
LoggingLevels
[warn user alert info inspect debug macro-expand trace env])
(defonce *log-levels
(atom (map->LoggingLevels
(zipmap #{:always :error :warn :ns} (repeat true)))))
(defonce *outs
(atom #?(:clj (if-let [out-path (or (System/getProperty "quantum.core.log:out-file")
(System/getProperty "quantum.core.log|out-file"))]
(let [_ (binding [*out* *err*] (println "Logging to" out-path))
fos (-> out-path
(java.io.FileOutputStream. )
(java.io.OutputStreamWriter.)
(java.io.BufferedWriter. ))]
(fn [] [*err* fos]))
:cljs (fn [] [*out*]))))
(defn print-ns-name-to-outs! [ns-name-]
(doseq [out (@*outs)] (binding [*out* out] (println lang ":" "loading namespace" ns-name-) (flush)))
ns-name-)
#?(:clj
(defmacro log-this-ns []
`(if (get @*log-levels :ns) (print-ns-name-to-outs! '~(ns-name *ns*)) true)))
#?(:clj
(defmacro istr
concatenates the string data and evaluated expressions contained
within that argument. Evaluation is controlled using ~{} and ~()
forms. The former is used for simple value replacement using
arbitrary function invocation into the produced string.
Examples:
user=> (def v 30.5)
#'user/v
user=> (istr \"This trial required ~{v}ml of solution.\")
\"This trial required 30.5ml of solution.\"
user=> (istr \"There are ~(int v) days in November.\")
\"There are 30 days in November.\"
user=> (def m {:a [1 2 3]})
#'user/m
user=> (istr \"The total for your order is $~(->> m :a (apply +)).\")
\"The total for your order is $6.\"
user=> (istr \"Just split a long interpolated string up into ~(-> m :a (get 0)), \"
\"~(-> m :a (get 1)), or even ~(-> m :a (get 2)) separate strings \"
\"if you don't want a << expression to end up being e.g. ~(* 4 (int v)) \"
\"columns wide.\")
\"Just split a long interpolated string up into 1, 2, or even 3 separate strings if you don't want a << expression to end up being e.g. 120 columns wide.\"
Note that quotes surrounding string literals within ~() forms must be
escaped."
[& args] `(str+/istr ~@args)))
|
e1f029c4cea42b0e63ce6fe310a80e86e5e9bc9510a870815308dda5d4ae9e49 | namenu/advent-of-code | day11.clj | --- Day 11 : Space Police ---
(ns aoc.year2019.day11
(:require [aoc.util :refer [input cart->polar]]
[aoc.year2019.intcode :refer :all]))
(defn move [{:keys [pos dir] :as robot}]
(let [[x y] pos
[dx dy] dir]
(assoc robot :pos [(+ x dx) (+ y dy)])))
(defn turn [{:keys [dir] :as robot} lr]
(let [[dx dy] dir]
(if (zero? lr)
(assoc robot :dir [(- dy) dx])
(assoc robot :dir [dy (- dx)]))))
(defn read-panel [panels pos]
(or (get panels pos) 0))
(def panels (atom {}))
(def robot (atom {:pos [0 0]
:dir [0 1]
:buffer nil}))
(defn reset-state []
(reset! panels {})
(reset! robot {:pos [0 0]
:dir [0 1]
:buffer nil}))
(defn input-fn []
;(prn "input cb")
(read-panel @panels (:pos @robot)))
(defn output-fn [output]
;(prn "output cb" output)
(if-let [color (:buffer @robot)]
(do
(swap! panels assoc (:pos @robot) color)
(swap! robot turn output)
(swap! robot move)
(swap! robot assoc :buffer nil))
(swap! robot assoc :buffer output)))
pt.1
(let [in (input 2019 11)
state (-> (input->machine in)
(assoc :input-fn input-fn)
(assoc :output-fn output-fn))
]
(reset-state)
(swap! panels assoc [0 0] 1)
(run state)
(prn (count @panels))
(doseq [y (range 5 -10 -1)]
(let [s (map (fn [x]
(if (zero? (read-panel @panels [x y]))
"◾️"
"▫️️️️"))
(range -5 50))]
(println (apply str s)))))
| null | https://raw.githubusercontent.com/namenu/advent-of-code/83f8cf05931f814dab76696bf46fec1bb1276fac/2019/clojure/src/aoc/year2019/day11.clj | clojure | (prn "input cb")
(prn "output cb" output) | --- Day 11 : Space Police ---
(ns aoc.year2019.day11
(:require [aoc.util :refer [input cart->polar]]
[aoc.year2019.intcode :refer :all]))
(defn move [{:keys [pos dir] :as robot}]
(let [[x y] pos
[dx dy] dir]
(assoc robot :pos [(+ x dx) (+ y dy)])))
(defn turn [{:keys [dir] :as robot} lr]
(let [[dx dy] dir]
(if (zero? lr)
(assoc robot :dir [(- dy) dx])
(assoc robot :dir [dy (- dx)]))))
(defn read-panel [panels pos]
(or (get panels pos) 0))
(def panels (atom {}))
(def robot (atom {:pos [0 0]
:dir [0 1]
:buffer nil}))
(defn reset-state []
(reset! panels {})
(reset! robot {:pos [0 0]
:dir [0 1]
:buffer nil}))
(defn input-fn []
(read-panel @panels (:pos @robot)))
(defn output-fn [output]
(if-let [color (:buffer @robot)]
(do
(swap! panels assoc (:pos @robot) color)
(swap! robot turn output)
(swap! robot move)
(swap! robot assoc :buffer nil))
(swap! robot assoc :buffer output)))
pt.1
(let [in (input 2019 11)
state (-> (input->machine in)
(assoc :input-fn input-fn)
(assoc :output-fn output-fn))
]
(reset-state)
(swap! panels assoc [0 0] 1)
(run state)
(prn (count @panels))
(doseq [y (range 5 -10 -1)]
(let [s (map (fn [x]
(if (zero? (read-panel @panels [x y]))
"◾️"
"▫️️️️"))
(range -5 50))]
(println (apply str s)))))
|
c4f7c5fcc02ea12ea3b9f3fda074e39871a5a2e61976cdff5bf29dbdae5d719c | aggieben/weblocks | html-template.lisp |
(in-package :weblocks)
(export '(html-template with-widget-header render-widget-body))
(defwidget html-template (widget)
((tp :accessor tp :initform nil)
(src :type string :accessor src :initarg :src :initform nil)
(file :type pathname :accessor file :initarg :file :initform nil)
(vars :type list :accessor vars :initarg :vars :initform nil))
(:documentation "Models a HTML-TEMPLATE from a file."))
(defmethod initialize-instance :after ((obj html-template) &rest args)
(unless (or (file obj) (src obj)
(error "You need to specify either a template file (initarg :FILE) or a template
string (initarg :SRC) when creating a HTML-TEMPLATE widget.")))
(setf (tp obj) (html-template:create-template-printer (or (src obj)
(pathname (file obj))))))
(defmethod with-widget-header ((widget html-template) body-fn &rest args)
(apply body-fn widget args))
(defmethod render-widget-body ((widget html-template) &rest args)
(html-template:fill-and-print-template (tp widget) (vars widget)
:stream *weblocks-output-stream*))
| null | https://raw.githubusercontent.com/aggieben/weblocks/8d86be6a4fff8dde0b94181ba60d0dca2cbd9e25/contrib/lpolzer/html-template.lisp | lisp |
(in-package :weblocks)
(export '(html-template with-widget-header render-widget-body))
(defwidget html-template (widget)
((tp :accessor tp :initform nil)
(src :type string :accessor src :initarg :src :initform nil)
(file :type pathname :accessor file :initarg :file :initform nil)
(vars :type list :accessor vars :initarg :vars :initform nil))
(:documentation "Models a HTML-TEMPLATE from a file."))
(defmethod initialize-instance :after ((obj html-template) &rest args)
(unless (or (file obj) (src obj)
(error "You need to specify either a template file (initarg :FILE) or a template
string (initarg :SRC) when creating a HTML-TEMPLATE widget.")))
(setf (tp obj) (html-template:create-template-printer (or (src obj)
(pathname (file obj))))))
(defmethod with-widget-header ((widget html-template) body-fn &rest args)
(apply body-fn widget args))
(defmethod render-widget-body ((widget html-template) &rest args)
(html-template:fill-and-print-template (tp widget) (vars widget)
:stream *weblocks-output-stream*))
|
|
1fac9cb41dd6637e74975c2079dffa8013831067f73a702f25d0386354392358 | edsko/ChinesePodAPI | String.hs | -- | Utility functions on strings
module Servant.ChinesePod.Util.String (
explode
, dropBOM
, trim
, lowercase
) where
import Data.Char
| Split a string at the specified
explode :: Char -> String -> [String]
explode needle = go
where
go :: String -> [String]
go haystack = case break (== needle) haystack of
(xs, "") -> [xs]
(xs, _needle':haystack') -> xs : go haystack'
-- | Drop unicode BOM character if present
dropBOM :: String -> String
dropBOM ('\65279':str) = str
dropBOM str = str
-- | Trim whitespace
trim :: String -> String
trim = rtrim . ltrim
where
ltrim, rtrim :: String -> String
ltrim = dropWhile isSpace
rtrim = reverse . ltrim . reverse
-- | Map every character to lowercase
lowercase :: String -> String
lowercase = map toLower
| null | https://raw.githubusercontent.com/edsko/ChinesePodAPI/f77ebfd55286316c4a54c42c195d5a51b4a0e4cd/src/Servant/ChinesePod/Util/String.hs | haskell | | Utility functions on strings
| Drop unicode BOM character if present
| Trim whitespace
| Map every character to lowercase | module Servant.ChinesePod.Util.String (
explode
, dropBOM
, trim
, lowercase
) where
import Data.Char
| Split a string at the specified
explode :: Char -> String -> [String]
explode needle = go
where
go :: String -> [String]
go haystack = case break (== needle) haystack of
(xs, "") -> [xs]
(xs, _needle':haystack') -> xs : go haystack'
dropBOM :: String -> String
dropBOM ('\65279':str) = str
dropBOM str = str
trim :: String -> String
trim = rtrim . ltrim
where
ltrim, rtrim :: String -> String
ltrim = dropWhile isSpace
rtrim = reverse . ltrim . reverse
lowercase :: String -> String
lowercase = map toLower
|
b06f8975ee8e60884691c85b859ba6fe81fe213fe7d6d3fa7522bcd9e0ca7eac | RichiH/git-annex | HashObject.hs | git hash - object interface
-
- Copyright 2011 - 2014 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2011-2014 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE CPP #
module Git.HashObject where
import Common
import Git
import Git.Sha
import Git.Command
import Git.Types
import qualified Utility.CoProcess as CoProcess
import Utility.Tmp
type HashObjectHandle = CoProcess.CoProcessHandle
hashObjectStart :: Repo -> IO HashObjectHandle
hashObjectStart = gitCoProcessStart True
[ Param "hash-object"
, Param "-w"
, Param "--stdin-paths"
, Param "--no-filters"
]
hashObjectStop :: HashObjectHandle -> IO ()
hashObjectStop = CoProcess.stop
{- Injects a file into git, returning the Sha of the object. -}
hashFile :: HashObjectHandle -> FilePath -> IO Sha
hashFile h file = CoProcess.query h send receive
where
send to = hPutStrLn to =<< absPath file
receive from = getSha "hash-object" $ hGetLine from
{- Injects a blob into git. Unfortunately, the current git-hash-object
- interface does not allow batch hashing without using temp files. -}
hashBlob :: HashObjectHandle -> String -> IO Sha
hashBlob h s = withTmpFile "hash" $ \tmp tmph -> do
#ifdef mingw32_HOST_OS
hSetNewlineMode tmph noNewlineTranslation
#endif
hPutStr tmph s
hClose tmph
hashFile h tmp
Injects some content into git , returning its Sha .
-
- Avoids using a tmp file , but runs a new hash - object command each
- time called .
-
- Avoids using a tmp file, but runs a new hash-object command each
- time called. -}
hashObject :: ObjectType -> String -> Repo -> IO Sha
hashObject objtype content = hashObject' objtype (flip hPutStr content)
hashObject' :: ObjectType -> (Handle -> IO ()) -> Repo -> IO Sha
hashObject' objtype writer repo = getSha subcmd $
pipeWriteRead (map Param params) (Just writer) repo
where
subcmd = "hash-object"
params = [subcmd, "-t", show objtype, "-w", "--stdin", "--no-filters"]
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Git/HashObject.hs | haskell | Injects a file into git, returning the Sha of the object.
Injects a blob into git. Unfortunately, the current git-hash-object
- interface does not allow batch hashing without using temp files. | git hash - object interface
-
- Copyright 2011 - 2014 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2011-2014 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE CPP #
module Git.HashObject where
import Common
import Git
import Git.Sha
import Git.Command
import Git.Types
import qualified Utility.CoProcess as CoProcess
import Utility.Tmp
type HashObjectHandle = CoProcess.CoProcessHandle
hashObjectStart :: Repo -> IO HashObjectHandle
hashObjectStart = gitCoProcessStart True
[ Param "hash-object"
, Param "-w"
, Param "--stdin-paths"
, Param "--no-filters"
]
hashObjectStop :: HashObjectHandle -> IO ()
hashObjectStop = CoProcess.stop
hashFile :: HashObjectHandle -> FilePath -> IO Sha
hashFile h file = CoProcess.query h send receive
where
send to = hPutStrLn to =<< absPath file
receive from = getSha "hash-object" $ hGetLine from
hashBlob :: HashObjectHandle -> String -> IO Sha
hashBlob h s = withTmpFile "hash" $ \tmp tmph -> do
#ifdef mingw32_HOST_OS
hSetNewlineMode tmph noNewlineTranslation
#endif
hPutStr tmph s
hClose tmph
hashFile h tmp
Injects some content into git , returning its Sha .
-
- Avoids using a tmp file , but runs a new hash - object command each
- time called .
-
- Avoids using a tmp file, but runs a new hash-object command each
- time called. -}
hashObject :: ObjectType -> String -> Repo -> IO Sha
hashObject objtype content = hashObject' objtype (flip hPutStr content)
hashObject' :: ObjectType -> (Handle -> IO ()) -> Repo -> IO Sha
hashObject' objtype writer repo = getSha subcmd $
pipeWriteRead (map Param params) (Just writer) repo
where
subcmd = "hash-object"
params = [subcmd, "-t", show objtype, "-w", "--stdin", "--no-filters"]
|
9985fdc07b2265a5e56709454e8d6f2820f4e2abb0da97e6ce0a62bb28124a22 | fizruk/fpconf-2017-talk | Main.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Main where
import Data.Aeson
import GHC.Generics
import GHCJS.Marshal
import Miso.String
import Miso (App(..), startApp, defaultEvents, noEff, onClick)
import Miso.AFrame
import Miso.AFrame.Core
-- ==========================================================
Шаг 1 .
-- ==========================================================
step1 :: IO ()
step1 = startHtmlOnlyApp $
scene [] []
-- ==========================================================
-- Шаг 2. Красный куб
-- ==========================================================
step2 :: IO ()
step2 = startHtmlOnlyApp $
scene []
[
box defaultBoxAttrs { boxColor = Just "red" }
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
]
-- ==========================================================
Шаг 3 . ( интеграция внешней компоненты )
-- ==========================================================
data Env = Env
{ preset :: MisoString
, numDressing :: Int
} deriving (Generic, ToJSON)
instance ToJSVal Env where toJSVal = toJSVal . toJSON
environment :: Env -> Component action
environment = foreignComponent "environment"
step3 :: IO ()
step3 = startHtmlOnlyApp $
scene []
[
box defaultBoxAttrs { boxColor = Just "red" }
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
-- ==========================================================
-- Шаг 4. Текстура
-- ==========================================================
step4 :: IO ()
step4 = startHtmlOnlyApp $
scene []
[
box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just ""
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
-- ==========================================================
-- Шаг 5. Система управления ассетами
-- ==========================================================
step5 :: IO ()
step5 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
-- ==========================================================
-- Шаг 6. Анимация
-- ==========================================================
step6 :: IO ()
step6 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ]
[
animation "position" Nothing (Vec3 0 5 (-5)) defaultAnimationAttrs
{ animationDirection = Just AnimationAlternate
, animationDur = Just 2000
, animationRepeat = Indefinite
}
]
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
-- ==========================================================
-- Шаг 7. Взаимодействие
-- ==========================================================
step7 :: IO ()
step7 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ]
[
animation "scale" Nothing (Vec3 2.3 2.3 2.3) defaultAnimationAttrs
{ animationBegin = Just "mouseenter"
, animationDur = Just 300
}
, animation "scale" Nothing (Vec3 2 2 2) defaultAnimationAttrs
{ animationBegin = Just "mouseleave"
, animationDur = Just 300
}
, animation "rotation" Nothing (Vec3 360 405 45) defaultAnimationAttrs
{ animationBegin = Just "click"
, animationDur = Just 2000
}
]
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
, camera defaultCameraAttrs []
[
cursor defaultCursorAttrs [] []
]
]
-- ==========================================================
-- Шаг 8. Текст
-- ==========================================================
step8 :: IO ()
step8 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ]
[
animation "scale" Nothing (Vec3 2.3 2.3 2.3) defaultAnimationAttrs
{ animationBegin = Just "mouseenter"
, animationDur = Just 300
}
, animation "scale" Nothing (Vec3 2 2 2) defaultAnimationAttrs
{ animationBegin = Just "mouseleave"
, animationDur = Just 300
}
, animation "rotation" Nothing (Vec3 360 405 45) defaultAnimationAttrs
{ animationBegin = Just "click"
, animationDur = Just 2000
}
]
, text "Hello, world!" defaultTextAttrs
{ textColor = Just (ColorName "black")
}
[ position (Vec3 (-0.9) 0.2 (-3))
, scale (Vec3 1.5 1.5 1.5) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
, camera defaultCameraAttrs []
[
cursor defaultCursorAttrs [] []
]
]
-- ==========================================================
Шаг 9 . Miso + A - Frame
-- ==========================================================
data Model = Model
{ modelText :: MisoString
, modelPhrases :: [MisoString]
} deriving (Eq)
data Action
= NextPhrase
| Reset
step9 :: IO ()
step9 = startApp App {..}
where
initialAction = Reset
mountPoint = Nothing
events = defaultEvents
subs = []
model = Model "Click the box!" $
[ "You did it! Now click once again :)"
, "Not bad! Click more?"
, "Ok, I think that's enough."
, "Really, stop clicking on the box."
, "Ok. Let's play the repeating game."
]
update Reset _ = noEff model
update NextPhrase m = case modelPhrases m of
[] -> noEff model
(new : rest) -> noEff m
{ modelText = new
, modelPhrases = rest
}
view Model{..} =
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2)
, onClick NextPhrase ]
[
animation "scale" Nothing (Vec3 2.3 2.3 2.3) defaultAnimationAttrs
{ animationBegin = Just "mouseenter"
, animationDur = Just 300
}
, animation "scale" Nothing (Vec3 2 2 2) defaultAnimationAttrs
{ animationBegin = Just "mouseleave"
, animationDur = Just 300
}
, animation "rotation" Nothing (Vec3 360 405 45) defaultAnimationAttrs
{ animationBegin = Just "click"
, animationDur = Just 2000
}
]
, text modelText defaultTextAttrs
{ textColor = Just (ColorName "black")
, textAlign = Just TextAlignmentCenter
}
[ position (Vec3 0 0.2 (-3))
, scale (Vec3 1.5 1.5 1.5) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
, camera defaultCameraAttrs []
[
cursor defaultCursorAttrs [] []
]
]
main :: IO ()
main = step9
| null | https://raw.githubusercontent.com/fizruk/fpconf-2017-talk/604d14b6a081d4f5fb25acde7fe9783be250e11d/miso-aframe-demo/src/Main.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
==========================================================
==========================================================
==========================================================
Шаг 2. Красный куб
==========================================================
==========================================================
==========================================================
==========================================================
Шаг 4. Текстура
==========================================================
==========================================================
Шаг 5. Система управления ассетами
==========================================================
==========================================================
Шаг 6. Анимация
==========================================================
==========================================================
Шаг 7. Взаимодействие
==========================================================
==========================================================
Шаг 8. Текст
==========================================================
==========================================================
========================================================== | # LANGUAGE DeriveGeneric #
# LANGUAGE RecordWildCards #
module Main where
import Data.Aeson
import GHC.Generics
import GHCJS.Marshal
import Miso.String
import Miso (App(..), startApp, defaultEvents, noEff, onClick)
import Miso.AFrame
import Miso.AFrame.Core
Шаг 1 .
step1 :: IO ()
step1 = startHtmlOnlyApp $
scene [] []
step2 :: IO ()
step2 = startHtmlOnlyApp $
scene []
[
box defaultBoxAttrs { boxColor = Just "red" }
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
]
Шаг 3 . ( интеграция внешней компоненты )
data Env = Env
{ preset :: MisoString
, numDressing :: Int
} deriving (Generic, ToJSON)
instance ToJSVal Env where toJSVal = toJSVal . toJSON
environment :: Env -> Component action
environment = foreignComponent "environment"
step3 :: IO ()
step3 = startHtmlOnlyApp $
scene []
[
box defaultBoxAttrs { boxColor = Just "red" }
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
step4 :: IO ()
step4 = startHtmlOnlyApp $
scene []
[
box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just ""
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
step5 :: IO ()
step5 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
step6 :: IO ()
step6 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ]
[
animation "position" Nothing (Vec3 0 5 (-5)) defaultAnimationAttrs
{ animationDirection = Just AnimationAlternate
, animationDur = Just 2000
, animationRepeat = Indefinite
}
]
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
]
step7 :: IO ()
step7 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ]
[
animation "scale" Nothing (Vec3 2.3 2.3 2.3) defaultAnimationAttrs
{ animationBegin = Just "mouseenter"
, animationDur = Just 300
}
, animation "scale" Nothing (Vec3 2 2 2) defaultAnimationAttrs
{ animationBegin = Just "mouseleave"
, animationDur = Just 300
}
, animation "rotation" Nothing (Vec3 360 405 45) defaultAnimationAttrs
{ animationBegin = Just "click"
, animationDur = Just 2000
}
]
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
, camera defaultCameraAttrs []
[
cursor defaultCursorAttrs [] []
]
]
step8 :: IO ()
step8 = startHtmlOnlyApp $
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2) ]
[
animation "scale" Nothing (Vec3 2.3 2.3 2.3) defaultAnimationAttrs
{ animationBegin = Just "mouseenter"
, animationDur = Just 300
}
, animation "scale" Nothing (Vec3 2 2 2) defaultAnimationAttrs
{ animationBegin = Just "mouseleave"
, animationDur = Just 300
}
, animation "rotation" Nothing (Vec3 360 405 45) defaultAnimationAttrs
{ animationBegin = Just "click"
, animationDur = Just 2000
}
]
, text "Hello, world!" defaultTextAttrs
{ textColor = Just (ColorName "black")
}
[ position (Vec3 (-0.9) 0.2 (-3))
, scale (Vec3 1.5 1.5 1.5) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
, camera defaultCameraAttrs []
[
cursor defaultCursorAttrs [] []
]
]
Шаг 9 . Miso + A - Frame
data Model = Model
{ modelText :: MisoString
, modelPhrases :: [MisoString]
} deriving (Eq)
data Action
= NextPhrase
| Reset
step9 :: IO ()
step9 = startApp App {..}
where
initialAction = Reset
mountPoint = Nothing
events = defaultEvents
subs = []
model = Model "Click the box!" $
[ "You did it! Now click once again :)"
, "Not bad! Click more?"
, "Ok, I think that's enough."
, "Really, stop clicking on the box."
, "Ok. Let's play the repeating game."
]
update Reset _ = noEff model
update NextPhrase m = case modelPhrases m of
[] -> noEff model
(new : rest) -> noEff m
{ modelText = new
, modelPhrases = rest
}
view Model{..} =
scene []
[
assets Nothing
[
img "boxTexture" ""
]
, box defaultBoxAttrs
{ boxColor = Just "red"
, boxSrc = Just "#boxTexture"
}
[ position (Vec3 0 2 (-5))
, rotation (Vec3 0 45 45)
, scale (Vec3 2 2 2)
, onClick NextPhrase ]
[
animation "scale" Nothing (Vec3 2.3 2.3 2.3) defaultAnimationAttrs
{ animationBegin = Just "mouseenter"
, animationDur = Just 300
}
, animation "scale" Nothing (Vec3 2 2 2) defaultAnimationAttrs
{ animationBegin = Just "mouseleave"
, animationDur = Just 300
}
, animation "rotation" Nothing (Vec3 360 405 45) defaultAnimationAttrs
{ animationBegin = Just "click"
, animationDur = Just 2000
}
]
, text modelText defaultTextAttrs
{ textColor = Just (ColorName "black")
, textAlign = Just TextAlignmentCenter
}
[ position (Vec3 0 0.2 (-3))
, scale (Vec3 1.5 1.5 1.5) ] []
, entity
[ environment Env
{ preset = "forest"
, numDressing = 500
}
] []
, camera defaultCameraAttrs []
[
cursor defaultCursorAttrs [] []
]
]
main :: IO ()
main = step9
|
cde2c44d55e39aa0a60bea3e18a04789f3ec397170310f05565445bf60a30986 | weyrick/roadsend-php | utils.scm | ;; ***** BEGIN LICENSE BLOCK *****
Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 Roadsend , Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation ; 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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
;; ***** END LICENSE BLOCK *****
(module utils
(extern
(include "limits.h")
(include "stdlib.h")
(include "stdio.h")
(macro c-path-max::int "PATH_MAX") )
(import
(grass "grasstable.scm")
(opaque-math "opaque-math-binding.scm")
(php-types "php-types.scm"))
(extern
in 3.0c , 's flush - output - port is not binary safe on string ports ,
and in recent versions it no longer resets the position to 0
(flush-string-port/bin::bstring (::output-port) "strport_bin_flush")
(c-strpos::int (::bstring ::bstring ::int ::int) "re_strpos"))
(export
(string-subst::bstring text::bstring old::bstring new::bstring . rest)
(strstr-idxs haystack::bstring needle::bstring case-sensitive::bbool)
(pcc-strpos::bint haystack::bstring needle::bstring offset::bint case-sensitive::bbool)
(hashtable-copy hash)
(undollar str)
(vector-swap! v a b)
(escape-path path)
(normalize-path loc)
(append-paths a b . rest)
(merge-pathnames absolute::bstring relative::bstring)
( copy - file )
(util-realpath path::bstring)
(re-string-split split-on str)
(char-position char str)
(get-tokens-from-string regular-grammar astring)
(get-tokens regular-grammar input-port)
(inline gcar arg)
(inline gcdr arg)
(append-strings strings)
(string->integer/base str base)
(garbage->number/base str base)
(string->number/base str::bstring base floatify?::bbool stop-at-garbage?::bbool)
(fill-indexed-prop obj settor list-of-values)
(symbol-downcase sym)
(numeric-string? str)
(hex-string->flonum str)
(walk-dag first-node generate-list-of-next-nodes frobber-to-apply)
(least-power-of-2-greater-than x)
(strip-string-prefix str prefix)
(uniq lst)
(unique-strings list-of-strings)
(sublist-copy lst start end)
(y-or-n-p prompt)
(pathname-relative? pathname::bstring)
(windows->unix-path p::bstring)
( walk - dag - breadth - first first - node generate - list - of - next - nodes frobber - to - apply )
(loc-line location)
(loc-file location)
(safety-ext)
(make-tmpfile-name dir pref)
(pcc-file-separator)
(force-trailing-/ p)))
a version of php 's str_replace
(define (string-subst::bstring text::bstring old::bstring new::bstring . rest)
(let ((new-len (string-length new))
(old-len (string-length old)))
(if (and (=fx 1 new-len) (=fx 1 old-len))
one character replacements
(let ((result (string-replace text
(string-ref old 0)
(string-ref new 0))))
(if (null? rest)
result
(apply string-subst result rest)))
; string replacements
(multiple-value-bind (num-matches matches) (strstr-idxs text old #t)
(if (=fx num-matches 0)
(if (null? rest)
text
(apply string-subst text rest))
(let* ((text-len (string-length text))
(new-buf-size (cond ((=fx new-len old-len) text-len)
((<fx new-len old-len) (-fx text-len
(*fx (-fx old-len new-len) num-matches)))
((>fx new-len old-len) (+fx text-len
(*fx (-fx new-len old-len) num-matches)))))
(result (make-string new-buf-size)))
(let loop ((o-text 0)
(o-result 0)
(i 0))
(if (=fx i num-matches)
; no more matches, copy ending if we have it
(when (<fx o-text text-len)
(blit-string! text o-text result o-result (-fx text-len o-text)))
; copy match
(let ((copy-len (-fx (vector-ref matches i) o-text)))
; fill before match
(when (>fx copy-len 0)
(blit-string! text o-text result o-result copy-len))
; fill replacement
(blit-string! new 0 result (+fx o-result copy-len) new-len)
; next match
(loop (+fx (vector-ref matches i) old-len)
(+fx o-result (+fx new-len copy-len))
(+fx i 1)))))
(if (null? rest)
result
(apply string-subst result rest))))))))
(define (pcc-strpos::bint haystack::bstring needle::bstring offset::bint case-sensitive::bbool)
(if (and (<fx offset (string-length haystack))
(>=fx offset 0)
(>fx (string-length needle) 0)
(>fx (string-length haystack) 0))
(c-strpos haystack needle offset (if case-sensitive 1 0))
-1))
(define (strstr-idxs haystack::bstring needle::bstring case-sensitive::bbool)
(let ((matches (make-vector 10))
(vsize 10)
(pages 1)
(num-matches 0)
(c-cs (if case-sensitive 1 0))
(text-len (string-length haystack))
(old-len (string-length needle)))
(let loop ((offset 0))
(when (<fx offset text-len)
(let ((match-i (c-strpos haystack needle offset c-cs)))
(when (>=fx match-i 0)
; do we need to expand our vector?
(when (=fx num-matches vsize)
(set! pages (+fx 1 pages))
(set! vsize (+fx vsize (*fx pages vsize)))
(set! matches (copy-vector matches vsize)))
(vector-set! matches num-matches match-i)
(set! num-matches (+fx num-matches 1))
(loop (+fx match-i old-len))))))
(values num-matches matches)))
(define (make-tmpfile-name dir prefix)
(let* ((alphabet (list->vector '(0 1 2 3 4 5 6 7 8 9
A B C D E F G H I
J K L M N O P Q R
S T U V W X Y Z
a b c d e f g h i
j k l m n o p q r
s t u v w x y z
)))
(the-date (current-date))
(pick-char (lambda ()
(let ((c (vector-ref alphabet (random (vector-length alphabet)))))
(if (number? c)
(number->string c)
(symbol->string c))))))
(string-append
dir
(string (pcc-file-separator))
prefix
(number->string (date-second the-date))
(pick-char)
(pick-char)
(number->string (date-minute the-date))
(pick-char)
(pick-char))))
(define (windows->unix-path p::bstring)
(string-case p
;; just z: becomes just /z/
((: alpha ":")
(string-append "/" (the-substring 0 1) "/"))
replace z:\ with /z/
((: alpha #\: #\\ (* all))
(string-append "/" (the-substring 0 1)
"/" (windows->unix-path (the-substring 3 (the-length)))))
;; replace \ with /
(else
(pregexp-replace* "\\\\" p "/"))))
(define (y-or-n-p prompt)
(let loop ()
(display* #\newline prompt)
(string-case (read-line)
((or "y" "yes") #t)
((or "n" "no") #f)
(else (print "Please enter yes or no.")
(loop)))))
(define (vector-swap! v a b)
(when (not (= a b))
(let ((c (vector-ref v a))
(d (vector-ref v b)))
;(print "a " a " b " b " c " c " d " d)
(vector-set! v a d)
(vector-set! v b c))))
(define (escape-path path)
"escape a path e.g. for use on a commandline"
; (pregexp-replace* " "
; (pregexp-replace* "\\\\" path "/")
; "\\\\ "))
(string-append
"\"" ;(pregexp-replace*
;" "
(pregexp-replace* "\\\\" path "/")
;"\\\\ ")
"\""))
(define (input-fill-string! port s)
(let ((len::int (string-length s))
(s::string s))
(pragma::int "fread($1, 1, $2, BINARY_PORT( $3 ).file)"
s
len
port)))
(define (util-realpath path::bstring)
(cond-expand
(PCC_MINGW
(if (pathname-relative? path)
(merge-pathnames (string-append (pwd) "\\")
path)
(let ((p (merge-pathnames (string-append path "\\") "")))
(substring p 0 (- (string-length p) 1)))))
(else
(let* ((pathbuf::string (make-string c-path-max))
(path::string path)
(the-realpath::string (pragma::string "realpath($1, $2)"
path pathbuf)))
(if (string-ptr-null? the-realpath)
path
the-realpath)))))
(define (get-tokens regular-grammar input-port)
"this will show you the tokens on a port with rg lexer"
(let ((alist '()))
(do ((toker (read/rp regular-grammar input-port)
(read/rp regular-grammar input-port)))
((eof-object? toker))
(set! alist (cons toker alist)))
(reverse! alist)))
(define (get-tokens-from-string regular-grammar astring)
"this will show you the tokens in a string with rg lexer"
(with-input-from-string astring
(lambda ()
(get-tokens regular-grammar (current-input-port)))))
return either a list of the two parts , or # f if split - on was n't
;; present. split-on should be a character, not a string.
(define (re-string-split split-on str)
(let ((pos (char-position split-on str)))
(if pos
(list (substring str 0 pos)
(substring str (+ pos 1) (string-length str)))
#f)))
(define (char-position char str)
(let ((len (string-length str)))
(let loop ((c 0))
(if (>= c len)
#f
(if (char=? (string-ref str c) char)
c
(loop (+ c 1)))))))
(define *append-strings-port* (open-output-string))
(define (append-strings strings)
"return a new string that is the concatenation of strings"
(for-each (lambda (str) (display str *append-strings-port*))
strings)
(flush-string-port/bin *append-strings-port*))
;good car, good cdr
(define-inline (gcar arg) (if (null? arg) arg (car arg)))
(define-inline (gcdr arg) (if (null? arg) arg (cdr arg)))
(define *little-a* (char->integer #\a))
(define *big-a* (char->integer #\A))
(define *zero* (char->integer #\0))
(define (char->digit char)
"convert one character into a digit (number)"
(set! char (char->integer char))
(cond
((and (>= char *zero*)
(<= char (+ *zero* 9)))
(- char *zero*))
((and (>= char *little-a*)
(<= char (+ *little-a* 25)))
(+ 10 (- char *little-a*)))
((and (>= char *big-a*)
(<= char (+ *big-a* 25)))
(+ 10 (- char *big-a*)))
(else -1)))
(define (digit->char digit)
"convert one digit (number) into a character"
(let ((alphanums "0123456789abcdefghijklmnopqrstuvwxyz"))
(string-ref alphanums (modulo digit (string-length alphanums)))))
(define (string->integer/base str base)
"read a whole number from a string in any base"
(string->number/base str base #f #t))
(define (garbage->number/base str base)
"read a whole number from a string in any base, ignoring garbage"
(string->number/base str base #t #f))
(define (string->number/base str::bstring base floatify?::bbool stop-at-garbage?::bbool)
"read a whole number from a string in any base, approximating with
a float if an integer would overflow"
(let ((cutoff (floor (-elong (/elong *MAX-INT-SIZE-L* (fixnum->elong base)) (fixnum->elong base)))))
(let loop ((i 0)
(num 0))
(if (=fx i (string-length str))
num
(let ((digit (char->digit (string-ref str i))))
(if (or (<fx digit 0) (>=fx digit base))
(if stop-at-garbage?
;invalid digit: end of number.
num
(loop (+fx i 1) num))
(if (and floatify? (fixnum? num) (> num cutoff))
(loop i (fixnum->flonum num))
(loop (+fx i 1)
(+fx (*fx num base) digit)))))))))
(define (fill-indexed-prop obj settor list-of-values)
"utility to fill an indexed field of a bigloo object from a list of values"
(let ((i 0))
(for-each (lambda (val)
(settor obj i val)
(set! i (+ i 1)))
list-of-values)))
(define (symbol-downcase sym)
"make a symbol lower case"
(string->symbol (string-downcase (symbol->string sym))))
(define (numeric-string? str)
(if (and (string? str)
(> (string-length str) 0))
(let ((slen (string-length str))
(allow-dot #t))
(let loop ((i 0))
(if (< i slen)
(let ((ch (string-ref str i)))
(if (or (char-numeric? ch)
; negative
(and (= i 0)
(char=? (string-ref str 0) #\-)
(> slen 1))
; floating point
(and (char=? ch #\.)
allow-dot))
(begin
(if (char=? ch #\.)
(set! allow-dot #f))
(loop (+ i 1)))
#f))
#t)))
#f))
(define (hex-string->flonum str)
"convert a string representing a hex number into a bigloo flonum"
(let ((slen (string-length str))
(val 0.0))
(let loop ((i 0))
(if (< i slen)
(begin
(let ((tval (fixnum->flonum (string->integer (string (string-ref str i)) 16))))
(if (>fl val 0.0)
(set! val (+fl (*fl val 16.0) tval))
(set! val tval))
(loop (+ i 1))))))
val))
(define (walk-dag first-node generate-list-of-next-nodes frobber-to-apply)
(let ((seen (make-grasstable)))
(letrec ((visit-once (lambda (node)
(unless (grasstable-get seen node)
(grasstable-put! seen node #t)
(frobber-to-apply node)
(for-each visit-once
(generate-list-of-next-nodes node))))))
(visit-once first-node))))
(define (least-power-of-2-greater-than x)
"calculate the least power of 2 greater than x"
;bugs here? probably. can you find them? I bet not.
(set! x (-fx x 1))
(set! x (bit-or x (bit-rsh x 1)))
(set! x (bit-or x (bit-rsh x 2)))
(set! x (bit-or x (bit-rsh x 4)))
(set! x (bit-or x (bit-rsh x 8)))
(set! x (bit-or x (bit-rsh x 16)))
(+fx x 1))
; unsigned clp2(unsigned x) {
; x = x - 1;
x = x | ( x > > 1 ) ;
x = x | ( x > > 2 ) ;
x = x | ( x > > 4 ) ;
; x = x | (x >> 8);
x = x | ( x > > 16 ) ;
; return x + 1;
; }
(define (strip-string-prefix prefix str)
"if prefix matches the beginning of str, return str without it, otherwise
return str unchanged"
(let ((str-len (string-length str))
(prefix-len (string-length prefix)))
(if (and (<= prefix-len str-len)
(substring-at? str prefix 0))
(substring str prefix-len str-len)
str)))
;;;;PATH STUFF
(define *normalize-path-string-port* (open-output-string))
; /var/blah//baz//foo.php -> /var/blah/baz/foo.php
(define (normalize-path path)
"eliminate multiple adjacent slashes"
(let ((sep-seen? #f)
(out *normalize-path-string-port*)
(len (string-length path)))
(let loop ((i 0))
(when (<fx i len)
(let ((char (string-ref path i)))
(if (file-separator? char)
(unless sep-seen?
(display (pcc-file-separator) out)
(set! sep-seen? #t))
(begin
(display char out)
(set! sep-seen? #f))))
(loop (+fx i 1))))
(flush-string-port/bin out)))
(define (append-paths a b . rest)
; (print "append paths " a " " b " " rest)
"try to stick two or more strings together separated by slashes in
a sane way"
; (normalize-path (append-strings (cons a (cons b rest)))))
(cond
((zero? (string-length a))
(if (pair? rest)
(apply append-paths b rest)
b))
((zero? (string-length b))
(if (pair? rest)
(apply append-paths a rest)
a))
((not (file-separator? (string-ref a (- (string-length a) 1))))
(apply append-paths (string-append a (string (pcc-file-separator))) b rest))
((file-separator? (string-ref b 0))
(apply append-paths a (substring b 1 (string-length b)) rest))
(else
(if (pair? rest)
(apply append-paths (merge-pathnames a b) rest)
(merge-pathnames a b)))))
(define (pathname-relative? pathname::bstring)
(string-case pathname
((: "/" (* all)) #f)
((: alpha ":" (or "/" "\\") (* all)) #f)
(else #t)))
(define (file-separator? char)
(cond-expand
(PCC_MINGW
(or (char=? char #\/)
(char=? char #\\)))
(else
(char=? char #\/))))
(define (pcc-file-separator)
(cond-expand
the file - separator in bigloo on is still forward slash
(PCC_MINGW #\\)
(else #\/)))
(define (merge-pathnames absolute::bstring relative::bstring)
"merge an absolute path and a relative path, return the new path
for example: /foo/bar/baz + ../bling/zot = /foo/bling/zot"
; (print "merge-pathnames: attempting to merge absolute " absolute " with relative " relative)
(let ((absolute-len (string-length absolute))
(relative-len (string-length relative)))
;;we collect the new directory as a stack (reversed list) in pwd
(let ((pwd '())
;;the number of directories we've gone up past the root
;;in the absolute path
(past-root 0))
(let ((cd (lambda (dir)
;(print "cding to " dir)
(cond
((string=? dir "..") (if (null? pwd)
(set! past-root (+ past-root 1))
(set! pwd (gcdr pwd))))
((string=? dir ".") #t)
;; ignore empty directories resulting from double slashes
((string=? dir "") #t)
(else (set! pwd (cons dir pwd)))))))
cd up the absolute path , skipping a slash , if it starts with one
(let ((start (if (and (not (zero? absolute-len))
(file-separator? (string-ref absolute 0)))
1
0)))
(let loop ((left start)
(right start))
(when (<fx right absolute-len)
(if (file-separator? (string-ref absolute right))
(begin
(cd (substring absolute left right))
(loop (+fx right 1) (+fx right 1)))
(loop left (+fx right 1))))))
;cd up the relative path
(let loop ((left 0)
(right 0))
(if (<fx right relative-len)
(if (file-separator? (string-ref relative right))
(begin
(cd (substring relative left right))
(loop (+fx right 1) (+fx right 1)))
(loop left (+fx right 1)))
;; return the new path + the file part of the relative path
(with-output-to-string
(lambda ()
first , in case we went up past the root of the " absolute " path ,
;;tack on the appropriate number of ../'s
(do ((i 0 (+ i 1)))
((>= i past-root))
(display "..")
(display (pcc-file-separator)))
;;in case we didn't go past the root, and the left path is
;;absolute, generate an absolute path
(when (and (> absolute-len 0)
(file-separator? (string-ref absolute 0))
(= 0 past-root))
(display (pcc-file-separator)))
(for-each (lambda (p)
(display p)
(display (pcc-file-separator)))
(reverse pwd))
(display (substring relative left right))))))))))
(define (force-trailing-/ p)
;; add a terminating slash (file separator) if not there
(if (char=? (string-ref p (- (string-length p) 1))
(pcc-file-separator))
p
(string-append p (string (pcc-file-separator)))))
(define (uniq lst)
"return lst without any values that are eq? to each other"
(let ((u (make-grasstable)))
(for-each (lambda (e) (grasstable-put! u e #t)) lst)
(grasstable-key-list u)))
(define (unique-strings list-of-strings)
(let ((myhash (make-hashtable)))
(for-each (lambda (x) (hashtable-put! myhash x x)) list-of-strings)
(hashtable->list myhash)))
(define (sublist-copy lst start end)
"return a copy of the sublist of LST from START index to END index"
(let loop ((i start)
(old-list (list-tail lst (min start (length lst))))
(new-list '()))
(if (or (null? old-list) (>= i end))
(reverse new-list)
(loop (+ i 1)
(cdr old-list)
(cons (car old-list) new-list)))))
(define (loc-line location)
(car location))
(define (loc-file location)
(cdr location))
(define (safety-ext)
(cond-expand
(unsafe "_u")
(else "_s")))
(define (undollar str)
(let ((str (mkstr str)))
(if (char=? (string-ref str 0) #\$)
(substring str 1 (string-length str))
str)))
(define (hashtable-copy hash)
(let ((new-hash (make-hashtable (max 1 (hashtable-size hash)))))
(hashtable-for-each hash
(lambda (key val)
(hashtable-put! new-hash key val)))
new-hash))
| null | https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/utils.scm | scheme | ***** BEGIN LICENSE BLOCK *****
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 2.1
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
along with this program; if not, write to the Free Software
***** END LICENSE BLOCK *****
string replacements
no more matches, copy ending if we have it
copy match
fill before match
fill replacement
next match
do we need to expand our vector?
just z: becomes just /z/
replace \ with /
(print "a " a " b " b " c " c " d " d)
(pregexp-replace* " "
(pregexp-replace* "\\\\" path "/")
"\\\\ "))
(pregexp-replace*
" "
"\\\\ ")
present. split-on should be a character, not a string.
good car, good cdr
invalid digit: end of number.
negative
floating point
bugs here? probably. can you find them? I bet not.
unsigned clp2(unsigned x) {
x = x - 1;
x = x | (x >> 8);
return x + 1;
}
PATH STUFF
/var/blah//baz//foo.php -> /var/blah/baz/foo.php
(print "append paths " a " " b " " rest)
(normalize-path (append-strings (cons a (cons b rest)))))
(print "merge-pathnames: attempting to merge absolute " absolute " with relative " relative)
we collect the new directory as a stack (reversed list) in pwd
the number of directories we've gone up past the root
in the absolute path
(print "cding to " dir)
ignore empty directories resulting from double slashes
cd up the relative path
return the new path + the file part of the relative path
tack on the appropriate number of ../'s
in case we didn't go past the root, and the left path is
absolute, generate an absolute path
add a terminating slash (file separator) if not there | Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 Roadsend , Inc.
of the License , or ( at your option ) any later version .
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
(module utils
(extern
(include "limits.h")
(include "stdlib.h")
(include "stdio.h")
(macro c-path-max::int "PATH_MAX") )
(import
(grass "grasstable.scm")
(opaque-math "opaque-math-binding.scm")
(php-types "php-types.scm"))
(extern
in 3.0c , 's flush - output - port is not binary safe on string ports ,
and in recent versions it no longer resets the position to 0
(flush-string-port/bin::bstring (::output-port) "strport_bin_flush")
(c-strpos::int (::bstring ::bstring ::int ::int) "re_strpos"))
(export
(string-subst::bstring text::bstring old::bstring new::bstring . rest)
(strstr-idxs haystack::bstring needle::bstring case-sensitive::bbool)
(pcc-strpos::bint haystack::bstring needle::bstring offset::bint case-sensitive::bbool)
(hashtable-copy hash)
(undollar str)
(vector-swap! v a b)
(escape-path path)
(normalize-path loc)
(append-paths a b . rest)
(merge-pathnames absolute::bstring relative::bstring)
( copy - file )
(util-realpath path::bstring)
(re-string-split split-on str)
(char-position char str)
(get-tokens-from-string regular-grammar astring)
(get-tokens regular-grammar input-port)
(inline gcar arg)
(inline gcdr arg)
(append-strings strings)
(string->integer/base str base)
(garbage->number/base str base)
(string->number/base str::bstring base floatify?::bbool stop-at-garbage?::bbool)
(fill-indexed-prop obj settor list-of-values)
(symbol-downcase sym)
(numeric-string? str)
(hex-string->flonum str)
(walk-dag first-node generate-list-of-next-nodes frobber-to-apply)
(least-power-of-2-greater-than x)
(strip-string-prefix str prefix)
(uniq lst)
(unique-strings list-of-strings)
(sublist-copy lst start end)
(y-or-n-p prompt)
(pathname-relative? pathname::bstring)
(windows->unix-path p::bstring)
( walk - dag - breadth - first first - node generate - list - of - next - nodes frobber - to - apply )
(loc-line location)
(loc-file location)
(safety-ext)
(make-tmpfile-name dir pref)
(pcc-file-separator)
(force-trailing-/ p)))
a version of php 's str_replace
(define (string-subst::bstring text::bstring old::bstring new::bstring . rest)
(let ((new-len (string-length new))
(old-len (string-length old)))
(if (and (=fx 1 new-len) (=fx 1 old-len))
one character replacements
(let ((result (string-replace text
(string-ref old 0)
(string-ref new 0))))
(if (null? rest)
result
(apply string-subst result rest)))
(multiple-value-bind (num-matches matches) (strstr-idxs text old #t)
(if (=fx num-matches 0)
(if (null? rest)
text
(apply string-subst text rest))
(let* ((text-len (string-length text))
(new-buf-size (cond ((=fx new-len old-len) text-len)
((<fx new-len old-len) (-fx text-len
(*fx (-fx old-len new-len) num-matches)))
((>fx new-len old-len) (+fx text-len
(*fx (-fx new-len old-len) num-matches)))))
(result (make-string new-buf-size)))
(let loop ((o-text 0)
(o-result 0)
(i 0))
(if (=fx i num-matches)
(when (<fx o-text text-len)
(blit-string! text o-text result o-result (-fx text-len o-text)))
(let ((copy-len (-fx (vector-ref matches i) o-text)))
(when (>fx copy-len 0)
(blit-string! text o-text result o-result copy-len))
(blit-string! new 0 result (+fx o-result copy-len) new-len)
(loop (+fx (vector-ref matches i) old-len)
(+fx o-result (+fx new-len copy-len))
(+fx i 1)))))
(if (null? rest)
result
(apply string-subst result rest))))))))
(define (pcc-strpos::bint haystack::bstring needle::bstring offset::bint case-sensitive::bbool)
(if (and (<fx offset (string-length haystack))
(>=fx offset 0)
(>fx (string-length needle) 0)
(>fx (string-length haystack) 0))
(c-strpos haystack needle offset (if case-sensitive 1 0))
-1))
(define (strstr-idxs haystack::bstring needle::bstring case-sensitive::bbool)
(let ((matches (make-vector 10))
(vsize 10)
(pages 1)
(num-matches 0)
(c-cs (if case-sensitive 1 0))
(text-len (string-length haystack))
(old-len (string-length needle)))
(let loop ((offset 0))
(when (<fx offset text-len)
(let ((match-i (c-strpos haystack needle offset c-cs)))
(when (>=fx match-i 0)
(when (=fx num-matches vsize)
(set! pages (+fx 1 pages))
(set! vsize (+fx vsize (*fx pages vsize)))
(set! matches (copy-vector matches vsize)))
(vector-set! matches num-matches match-i)
(set! num-matches (+fx num-matches 1))
(loop (+fx match-i old-len))))))
(values num-matches matches)))
(define (make-tmpfile-name dir prefix)
(let* ((alphabet (list->vector '(0 1 2 3 4 5 6 7 8 9
A B C D E F G H I
J K L M N O P Q R
S T U V W X Y Z
a b c d e f g h i
j k l m n o p q r
s t u v w x y z
)))
(the-date (current-date))
(pick-char (lambda ()
(let ((c (vector-ref alphabet (random (vector-length alphabet)))))
(if (number? c)
(number->string c)
(symbol->string c))))))
(string-append
dir
(string (pcc-file-separator))
prefix
(number->string (date-second the-date))
(pick-char)
(pick-char)
(number->string (date-minute the-date))
(pick-char)
(pick-char))))
(define (windows->unix-path p::bstring)
(string-case p
((: alpha ":")
(string-append "/" (the-substring 0 1) "/"))
replace z:\ with /z/
((: alpha #\: #\\ (* all))
(string-append "/" (the-substring 0 1)
"/" (windows->unix-path (the-substring 3 (the-length)))))
(else
(pregexp-replace* "\\\\" p "/"))))
(define (y-or-n-p prompt)
(let loop ()
(display* #\newline prompt)
(string-case (read-line)
((or "y" "yes") #t)
((or "n" "no") #f)
(else (print "Please enter yes or no.")
(loop)))))
(define (vector-swap! v a b)
(when (not (= a b))
(let ((c (vector-ref v a))
(d (vector-ref v b)))
(vector-set! v a d)
(vector-set! v b c))))
(define (escape-path path)
"escape a path e.g. for use on a commandline"
(string-append
(pregexp-replace* "\\\\" path "/")
"\""))
(define (input-fill-string! port s)
(let ((len::int (string-length s))
(s::string s))
(pragma::int "fread($1, 1, $2, BINARY_PORT( $3 ).file)"
s
len
port)))
(define (util-realpath path::bstring)
(cond-expand
(PCC_MINGW
(if (pathname-relative? path)
(merge-pathnames (string-append (pwd) "\\")
path)
(let ((p (merge-pathnames (string-append path "\\") "")))
(substring p 0 (- (string-length p) 1)))))
(else
(let* ((pathbuf::string (make-string c-path-max))
(path::string path)
(the-realpath::string (pragma::string "realpath($1, $2)"
path pathbuf)))
(if (string-ptr-null? the-realpath)
path
the-realpath)))))
(define (get-tokens regular-grammar input-port)
"this will show you the tokens on a port with rg lexer"
(let ((alist '()))
(do ((toker (read/rp regular-grammar input-port)
(read/rp regular-grammar input-port)))
((eof-object? toker))
(set! alist (cons toker alist)))
(reverse! alist)))
(define (get-tokens-from-string regular-grammar astring)
"this will show you the tokens in a string with rg lexer"
(with-input-from-string astring
(lambda ()
(get-tokens regular-grammar (current-input-port)))))
return either a list of the two parts , or # f if split - on was n't
(define (re-string-split split-on str)
(let ((pos (char-position split-on str)))
(if pos
(list (substring str 0 pos)
(substring str (+ pos 1) (string-length str)))
#f)))
(define (char-position char str)
(let ((len (string-length str)))
(let loop ((c 0))
(if (>= c len)
#f
(if (char=? (string-ref str c) char)
c
(loop (+ c 1)))))))
(define *append-strings-port* (open-output-string))
(define (append-strings strings)
"return a new string that is the concatenation of strings"
(for-each (lambda (str) (display str *append-strings-port*))
strings)
(flush-string-port/bin *append-strings-port*))
(define-inline (gcar arg) (if (null? arg) arg (car arg)))
(define-inline (gcdr arg) (if (null? arg) arg (cdr arg)))
(define *little-a* (char->integer #\a))
(define *big-a* (char->integer #\A))
(define *zero* (char->integer #\0))
(define (char->digit char)
"convert one character into a digit (number)"
(set! char (char->integer char))
(cond
((and (>= char *zero*)
(<= char (+ *zero* 9)))
(- char *zero*))
((and (>= char *little-a*)
(<= char (+ *little-a* 25)))
(+ 10 (- char *little-a*)))
((and (>= char *big-a*)
(<= char (+ *big-a* 25)))
(+ 10 (- char *big-a*)))
(else -1)))
(define (digit->char digit)
"convert one digit (number) into a character"
(let ((alphanums "0123456789abcdefghijklmnopqrstuvwxyz"))
(string-ref alphanums (modulo digit (string-length alphanums)))))
(define (string->integer/base str base)
"read a whole number from a string in any base"
(string->number/base str base #f #t))
(define (garbage->number/base str base)
"read a whole number from a string in any base, ignoring garbage"
(string->number/base str base #t #f))
(define (string->number/base str::bstring base floatify?::bbool stop-at-garbage?::bbool)
"read a whole number from a string in any base, approximating with
a float if an integer would overflow"
(let ((cutoff (floor (-elong (/elong *MAX-INT-SIZE-L* (fixnum->elong base)) (fixnum->elong base)))))
(let loop ((i 0)
(num 0))
(if (=fx i (string-length str))
num
(let ((digit (char->digit (string-ref str i))))
(if (or (<fx digit 0) (>=fx digit base))
(if stop-at-garbage?
num
(loop (+fx i 1) num))
(if (and floatify? (fixnum? num) (> num cutoff))
(loop i (fixnum->flonum num))
(loop (+fx i 1)
(+fx (*fx num base) digit)))))))))
(define (fill-indexed-prop obj settor list-of-values)
"utility to fill an indexed field of a bigloo object from a list of values"
(let ((i 0))
(for-each (lambda (val)
(settor obj i val)
(set! i (+ i 1)))
list-of-values)))
(define (symbol-downcase sym)
"make a symbol lower case"
(string->symbol (string-downcase (symbol->string sym))))
(define (numeric-string? str)
(if (and (string? str)
(> (string-length str) 0))
(let ((slen (string-length str))
(allow-dot #t))
(let loop ((i 0))
(if (< i slen)
(let ((ch (string-ref str i)))
(if (or (char-numeric? ch)
(and (= i 0)
(char=? (string-ref str 0) #\-)
(> slen 1))
(and (char=? ch #\.)
allow-dot))
(begin
(if (char=? ch #\.)
(set! allow-dot #f))
(loop (+ i 1)))
#f))
#t)))
#f))
(define (hex-string->flonum str)
"convert a string representing a hex number into a bigloo flonum"
(let ((slen (string-length str))
(val 0.0))
(let loop ((i 0))
(if (< i slen)
(begin
(let ((tval (fixnum->flonum (string->integer (string (string-ref str i)) 16))))
(if (>fl val 0.0)
(set! val (+fl (*fl val 16.0) tval))
(set! val tval))
(loop (+ i 1))))))
val))
(define (walk-dag first-node generate-list-of-next-nodes frobber-to-apply)
(let ((seen (make-grasstable)))
(letrec ((visit-once (lambda (node)
(unless (grasstable-get seen node)
(grasstable-put! seen node #t)
(frobber-to-apply node)
(for-each visit-once
(generate-list-of-next-nodes node))))))
(visit-once first-node))))
(define (least-power-of-2-greater-than x)
"calculate the least power of 2 greater than x"
(set! x (-fx x 1))
(set! x (bit-or x (bit-rsh x 1)))
(set! x (bit-or x (bit-rsh x 2)))
(set! x (bit-or x (bit-rsh x 4)))
(set! x (bit-or x (bit-rsh x 8)))
(set! x (bit-or x (bit-rsh x 16)))
(+fx x 1))
(define (strip-string-prefix prefix str)
"if prefix matches the beginning of str, return str without it, otherwise
return str unchanged"
(let ((str-len (string-length str))
(prefix-len (string-length prefix)))
(if (and (<= prefix-len str-len)
(substring-at? str prefix 0))
(substring str prefix-len str-len)
str)))
(define *normalize-path-string-port* (open-output-string))
(define (normalize-path path)
"eliminate multiple adjacent slashes"
(let ((sep-seen? #f)
(out *normalize-path-string-port*)
(len (string-length path)))
(let loop ((i 0))
(when (<fx i len)
(let ((char (string-ref path i)))
(if (file-separator? char)
(unless sep-seen?
(display (pcc-file-separator) out)
(set! sep-seen? #t))
(begin
(display char out)
(set! sep-seen? #f))))
(loop (+fx i 1))))
(flush-string-port/bin out)))
(define (append-paths a b . rest)
"try to stick two or more strings together separated by slashes in
a sane way"
(cond
((zero? (string-length a))
(if (pair? rest)
(apply append-paths b rest)
b))
((zero? (string-length b))
(if (pair? rest)
(apply append-paths a rest)
a))
((not (file-separator? (string-ref a (- (string-length a) 1))))
(apply append-paths (string-append a (string (pcc-file-separator))) b rest))
((file-separator? (string-ref b 0))
(apply append-paths a (substring b 1 (string-length b)) rest))
(else
(if (pair? rest)
(apply append-paths (merge-pathnames a b) rest)
(merge-pathnames a b)))))
(define (pathname-relative? pathname::bstring)
(string-case pathname
((: "/" (* all)) #f)
((: alpha ":" (or "/" "\\") (* all)) #f)
(else #t)))
(define (file-separator? char)
(cond-expand
(PCC_MINGW
(or (char=? char #\/)
(char=? char #\\)))
(else
(char=? char #\/))))
(define (pcc-file-separator)
(cond-expand
the file - separator in bigloo on is still forward slash
(PCC_MINGW #\\)
(else #\/)))
(define (merge-pathnames absolute::bstring relative::bstring)
"merge an absolute path and a relative path, return the new path
for example: /foo/bar/baz + ../bling/zot = /foo/bling/zot"
(let ((absolute-len (string-length absolute))
(relative-len (string-length relative)))
(let ((pwd '())
(past-root 0))
(let ((cd (lambda (dir)
(cond
((string=? dir "..") (if (null? pwd)
(set! past-root (+ past-root 1))
(set! pwd (gcdr pwd))))
((string=? dir ".") #t)
((string=? dir "") #t)
(else (set! pwd (cons dir pwd)))))))
cd up the absolute path , skipping a slash , if it starts with one
(let ((start (if (and (not (zero? absolute-len))
(file-separator? (string-ref absolute 0)))
1
0)))
(let loop ((left start)
(right start))
(when (<fx right absolute-len)
(if (file-separator? (string-ref absolute right))
(begin
(cd (substring absolute left right))
(loop (+fx right 1) (+fx right 1)))
(loop left (+fx right 1))))))
(let loop ((left 0)
(right 0))
(if (<fx right relative-len)
(if (file-separator? (string-ref relative right))
(begin
(cd (substring relative left right))
(loop (+fx right 1) (+fx right 1)))
(loop left (+fx right 1)))
(with-output-to-string
(lambda ()
first , in case we went up past the root of the " absolute " path ,
(do ((i 0 (+ i 1)))
((>= i past-root))
(display "..")
(display (pcc-file-separator)))
(when (and (> absolute-len 0)
(file-separator? (string-ref absolute 0))
(= 0 past-root))
(display (pcc-file-separator)))
(for-each (lambda (p)
(display p)
(display (pcc-file-separator)))
(reverse pwd))
(display (substring relative left right))))))))))
(define (force-trailing-/ p)
(if (char=? (string-ref p (- (string-length p) 1))
(pcc-file-separator))
p
(string-append p (string (pcc-file-separator)))))
(define (uniq lst)
"return lst without any values that are eq? to each other"
(let ((u (make-grasstable)))
(for-each (lambda (e) (grasstable-put! u e #t)) lst)
(grasstable-key-list u)))
(define (unique-strings list-of-strings)
(let ((myhash (make-hashtable)))
(for-each (lambda (x) (hashtable-put! myhash x x)) list-of-strings)
(hashtable->list myhash)))
(define (sublist-copy lst start end)
"return a copy of the sublist of LST from START index to END index"
(let loop ((i start)
(old-list (list-tail lst (min start (length lst))))
(new-list '()))
(if (or (null? old-list) (>= i end))
(reverse new-list)
(loop (+ i 1)
(cdr old-list)
(cons (car old-list) new-list)))))
(define (loc-line location)
(car location))
(define (loc-file location)
(cdr location))
(define (safety-ext)
(cond-expand
(unsafe "_u")
(else "_s")))
(define (undollar str)
(let ((str (mkstr str)))
(if (char=? (string-ref str 0) #\$)
(substring str 1 (string-length str))
str)))
(define (hashtable-copy hash)
(let ((new-hash (make-hashtable (max 1 (hashtable-size hash)))))
(hashtable-for-each hash
(lambda (key val)
(hashtable-put! new-hash key val)))
new-hash))
|
292a2cde7395b8d93934a6951c9020d06a59077ce16032e2cb04810d9ee0a2df | sanjoy/Snippets | GenerateMatcher.hs | # LANGUAGE TemplateHaskell #
module GenerateMatcher(generateMatcher) where
import Language.Haskell.TH
generateMatcher :: String -> [String] -> Q [Dec]
generateMatcher name strs =
return [FunD (mkName name) (map thMagic strs ++ baseCase)]
where
thMagic str = Clause [transform str] (NormalB (ConE 'True)) []
baseCase = [Clause [WildP] (NormalB (ConE 'False)) []]
transform [] = ConP (mkName "[]") []
transform ('?':rest) =
let colon = mkName ":" in (InfixP WildP colon $ transform rest)
transform (x:rest) =
InfixP (LitP (CharL x)) (mkName ":") $ transform rest
| null | https://raw.githubusercontent.com/sanjoy/Snippets/76dcbff1da333b010662d42d0d235f614a882b87/GenerateMatcher.hs | haskell | # LANGUAGE TemplateHaskell #
module GenerateMatcher(generateMatcher) where
import Language.Haskell.TH
generateMatcher :: String -> [String] -> Q [Dec]
generateMatcher name strs =
return [FunD (mkName name) (map thMagic strs ++ baseCase)]
where
thMagic str = Clause [transform str] (NormalB (ConE 'True)) []
baseCase = [Clause [WildP] (NormalB (ConE 'False)) []]
transform [] = ConP (mkName "[]") []
transform ('?':rest) =
let colon = mkName ":" in (InfixP WildP colon $ transform rest)
transform (x:rest) =
InfixP (LitP (CharL x)) (mkName ":") $ transform rest
|
|
4ea50679afba8368309822df1cdef838be823abdd28263d6e653092e41771927 | sbcl/specializable | prototype-specializer.lisp | ;;;; prototype-specializer.lisp --- Unit tests for the prototype specializer.
;;;;
Copyright ( C ) 2013 , 2014
Copyright ( C ) 2014 , 2017 Jan Moringen
;;;;
Author : < >
Author : < >
(cl:in-package #:prototype-specializer.test)
Utilities
(defmacro with-prototype-generic-function ((name lambda-list &rest options)
&body body)
`(with-specializable-generic-function
(prototype-generic-function ,name ,lambda-list ,@options)
,@body))
;; Test suite
(in-suite :specializable.prototype-specializer)
(test print.smoke
(is (search ">/ROOT/" (princ-to-string /root/)))
(is (search "[" (princ-to-string (clone /root/)))))
(test clone.smoke
(is (typep (clone /root/) 'prototype-object))
(is (typep (clone (clone /root/)) 'prototype-object)))
(test delegation.smoke
(flet ((delegations (object)
(let ((delegations '()))
(map-delegations (lambda (delegation)
(push delegation delegations))
object)
delegations)))
(let ((object (clone /root/)))
(is (set-equal (list object) (delegations object)))
(add-delegation object /root/)
(is (set-equal (list object /root/) (delegations object)))
(remove-delegation object)
(is (set-equal (list object) (delegations object))))))
(test delegation.cycle
(let ((object (clone /root/))
(object2 (clone /root/))
(object3 (clone /root/)))
(signals delegation-cycle-error
(add-delegation /root/ /root/))
(signals delegation-cycle-error
(add-delegation object object))
(add-delegation object2 object)
(signals delegation-cycle-error
(add-delegation object2 object2))
(signals delegation-cycle-error
(add-delegation object object2))
(add-delegation object3 object2)
(signals delegation-cycle-error
(add-delegation object3 object3))
(signals delegation-cycle-error
(add-delegation object2 object3))
(signals delegation-cycle-error
(add-delegation object object3))))
(test defmethod.specializer-instance
"Test splicing a PROTOTYPE-OBJECT instance into a DEFMETHOD form."
;; (as opposed to a symbol naming such an instance in the lexical
;; environment)
(let ((object (clone /root/)))
(with-prototype-generic-function
(foo (bar))
(eval `(defmethod foo ((bar ,object)) :object))
(is (eq :object (foo object))))))
(test remove-method.smoke
(let ((object (clone /root/)))
(with-prototype-generic-function
(foo (bar)
(:let object object)
(:method ((bar /root/)))
(:method ((bar object)))
#+TODO-not-possible (:method ((bar integer)))
(:method ((bar (eql 5)))))
(dolist (method (sb-mop:generic-function-methods #'foo))
(finishes (remove-method #'foo method)))
(is (emptyp (sb-mop:generic-function-methods #'foo))))))
(test call-method.smoke
(let ((object (clone /root/)))
(with-prototype-generic-function
(foo (bar)
(:let object object)
(:method ((bar /root/))
:root)
(:method ((bar object))
:object)
(:method ((bar (eql 5)))
5))
(signals sb-pcl::no-applicable-method-error (foo :no-such-method))
(is (eq :root (foo /root/)))
(is (eq :object (foo object)))
(is (eq 5 (foo 5)))
;; Cloning should inherit roles.
(let ((object2 (clone object)))
(is (eq :object (foo object2)))))))
| null | https://raw.githubusercontent.com/sbcl/specializable/a08048ce874a2a8c58e4735d88de3bf3da0de052/test/prototype-specializer/prototype-specializer.lisp | lisp | prototype-specializer.lisp --- Unit tests for the prototype specializer.
Test suite
(as opposed to a symbol naming such an instance in the lexical
environment)
Cloning should inherit roles. | Copyright ( C ) 2013 , 2014
Copyright ( C ) 2014 , 2017 Jan Moringen
Author : < >
Author : < >
(cl:in-package #:prototype-specializer.test)
Utilities
(defmacro with-prototype-generic-function ((name lambda-list &rest options)
&body body)
`(with-specializable-generic-function
(prototype-generic-function ,name ,lambda-list ,@options)
,@body))
(in-suite :specializable.prototype-specializer)
(test print.smoke
(is (search ">/ROOT/" (princ-to-string /root/)))
(is (search "[" (princ-to-string (clone /root/)))))
(test clone.smoke
(is (typep (clone /root/) 'prototype-object))
(is (typep (clone (clone /root/)) 'prototype-object)))
(test delegation.smoke
(flet ((delegations (object)
(let ((delegations '()))
(map-delegations (lambda (delegation)
(push delegation delegations))
object)
delegations)))
(let ((object (clone /root/)))
(is (set-equal (list object) (delegations object)))
(add-delegation object /root/)
(is (set-equal (list object /root/) (delegations object)))
(remove-delegation object)
(is (set-equal (list object) (delegations object))))))
(test delegation.cycle
(let ((object (clone /root/))
(object2 (clone /root/))
(object3 (clone /root/)))
(signals delegation-cycle-error
(add-delegation /root/ /root/))
(signals delegation-cycle-error
(add-delegation object object))
(add-delegation object2 object)
(signals delegation-cycle-error
(add-delegation object2 object2))
(signals delegation-cycle-error
(add-delegation object object2))
(add-delegation object3 object2)
(signals delegation-cycle-error
(add-delegation object3 object3))
(signals delegation-cycle-error
(add-delegation object2 object3))
(signals delegation-cycle-error
(add-delegation object object3))))
(test defmethod.specializer-instance
"Test splicing a PROTOTYPE-OBJECT instance into a DEFMETHOD form."
(let ((object (clone /root/)))
(with-prototype-generic-function
(foo (bar))
(eval `(defmethod foo ((bar ,object)) :object))
(is (eq :object (foo object))))))
(test remove-method.smoke
(let ((object (clone /root/)))
(with-prototype-generic-function
(foo (bar)
(:let object object)
(:method ((bar /root/)))
(:method ((bar object)))
#+TODO-not-possible (:method ((bar integer)))
(:method ((bar (eql 5)))))
(dolist (method (sb-mop:generic-function-methods #'foo))
(finishes (remove-method #'foo method)))
(is (emptyp (sb-mop:generic-function-methods #'foo))))))
(test call-method.smoke
(let ((object (clone /root/)))
(with-prototype-generic-function
(foo (bar)
(:let object object)
(:method ((bar /root/))
:root)
(:method ((bar object))
:object)
(:method ((bar (eql 5)))
5))
(signals sb-pcl::no-applicable-method-error (foo :no-such-method))
(is (eq :root (foo /root/)))
(is (eq :object (foo object)))
(is (eq 5 (foo 5)))
(let ((object2 (clone object)))
(is (eq :object (foo object2)))))))
|
bd85dc718f5bd1790cbfb3b5b236e91b99f111236c83748f00e1d36a3a2ed099 | kseo/systemf | Spec.hs | import Language.LambdaCalculus
import qualified Data.ByteString.Lazy.Char8 as BS
import System.FilePath
import System.FilePath.Glob
import Test.Tasty
import Test.Tasty.Golden as G
main :: IO ()
main = do
paths <- listTestFiles
goldens <- mapM mkGoldenTest paths
defaultMain (testGroup "Tests" goldens)
listTestFiles :: IO [FilePath]
listTestFiles = globDir1 pat "test/tests"
where pat = compile "*.lc"
mkGoldenTest :: FilePath -> IO TestTree
mkGoldenTest path = do
let testName = takeBaseName path
let goldenPath = replaceExtension path ".golden"
return (goldenVsString testName goldenPath action)
where
action :: IO BS.ByteString
action = do
script <- readFile path
let actual = either id id (run script)
return (BS.pack actual)
| null | https://raw.githubusercontent.com/kseo/systemf/ea73fd42567adf2ddcd7bb60f11a66e10eebc154/test/Spec.hs | haskell | import Language.LambdaCalculus
import qualified Data.ByteString.Lazy.Char8 as BS
import System.FilePath
import System.FilePath.Glob
import Test.Tasty
import Test.Tasty.Golden as G
main :: IO ()
main = do
paths <- listTestFiles
goldens <- mapM mkGoldenTest paths
defaultMain (testGroup "Tests" goldens)
listTestFiles :: IO [FilePath]
listTestFiles = globDir1 pat "test/tests"
where pat = compile "*.lc"
mkGoldenTest :: FilePath -> IO TestTree
mkGoldenTest path = do
let testName = takeBaseName path
let goldenPath = replaceExtension path ".golden"
return (goldenVsString testName goldenPath action)
where
action :: IO BS.ByteString
action = do
script <- readFile path
let actual = either id id (run script)
return (BS.pack actual)
|
|
0940f173ef62481df7931823fb5be2a740469d7ce0c702e81badbcba1013adfd | racket/db | mysql.rkt | #lang racket/base
(require racket/contract/base
openssl
db/base
"private/mysql/main.rkt")
;; FIXME: Contracts duplicated at main.rkt
(provide/contract
[mysql-connect
(->* (#:user string?)
(#:database (or/c string? #f)
#:password (or/c string? (list/c 'hash string?) #f)
#:server (or/c string? #f)
#:port (or/c exact-positive-integer? #f)
#:socket (or/c path-string? 'guess #f)
#:allow-cleartext-password? boolean?
#:ssl (or/c 'yes 'no 'optional)
#:ssl-context ssl-client-context?
#:notice-handler (or/c 'output 'error output-port? procedure?)
#:debug? any/c)
connection?)]
[mysql-guess-socket-path
(-> path-string?)]
[mysql-password-hash
(-> string? string?)])
| null | https://raw.githubusercontent.com/racket/db/0336d2522a613e76ebf60705cea3be4c237c447e/db-lib/db/mysql.rkt | racket | FIXME: Contracts duplicated at main.rkt | #lang racket/base
(require racket/contract/base
openssl
db/base
"private/mysql/main.rkt")
(provide/contract
[mysql-connect
(->* (#:user string?)
(#:database (or/c string? #f)
#:password (or/c string? (list/c 'hash string?) #f)
#:server (or/c string? #f)
#:port (or/c exact-positive-integer? #f)
#:socket (or/c path-string? 'guess #f)
#:allow-cleartext-password? boolean?
#:ssl (or/c 'yes 'no 'optional)
#:ssl-context ssl-client-context?
#:notice-handler (or/c 'output 'error output-port? procedure?)
#:debug? any/c)
connection?)]
[mysql-guess-socket-path
(-> path-string?)]
[mysql-password-hash
(-> string? string?)])
|
d055c3b9b34236f1f9a620a6358747c6828d8f8050012e96aa571009381c5267 | MLstate/opalang | traverse.mli |
Copyright © 2011 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
*
.
This module provides all usual traverse functions and some higher - level ones
on any tree structure as long as we consider only one type of nodes
@author
@author
@author
Generic Ast Rewriter API.
This module provides all usual traverse functions and some higher-level ones
on any tree structure as long as we consider only one type of nodes
@author Louis Gesbert
@author Valentin Gatien-Baron
@author Mathieu Barbin
*)
open TraverseInterface
(* module type TRAVERSE_LIFT = *)
(* sig *)
foldmap : ( ' acc - > ' expr - > ' acc * ' expr ) - > ' acc - > ' code_elt - > ' acc * ' code_elt
(* end *)
(** Some Extensions *)
module Utils : sig
* A generalisation of the type needed in S
( ' a , ' at , ' bt , ' b ) sub
' a may be expressions where identifiers are strings
' b an expressions where identfiers are uniq
In that case , ( ' a,'a,'b,'b ) represents a function that deconstruct a string expression
into a - list of string expression
- a function that expects an ident expression list and build you the the ' original ' ident expression
DON'T LOOK at the types , it 's too scary
Instead take a look at the following example , where you build the subs_cons function for the expressions
of some ast :
let subs_cons e =
match e with
| Apply ( e1,e2 ) - >
( * ( e1,e2 ) is a pair of expression and you are currently treating
* expressions , you write exactly that :
('a, 'at, 'bt ,'b) sub
'a may be expressions where identifiers are strings
'b an expressions where identfiers are uniq
In that case, ('a,'a,'b,'b) represents a function that deconstruct a string expression
into a - list of string expression
- a function that expects an ident expression list and build you the the 'original' ident expression
DON'T LOOK at the types, it's too scary
Instead take a look at the following example, where you build the subs_cons function for the expressions
of some ast:
let subs_cons e =
match e with
| Apply (e1,e2) ->
(* (e1,e2) is a pair of expression and you are currently treating
* expressions, you write exactly that: *)
wrap (fun x -> Apply x) ((sub_2 sub_current sub_current) (e1,e2))
| Match pel ->
pel is a list of pattern * expr
* we just ignore the pattern since there is no expression inside them
* we stop the deconstruction on the expression , since it is was we are currently deconstructing
* we just ignore the pattern since there is no expression inside them
* we stop the deconstruction on the expression, since it is was we are currently deconstructing *)
wrap (fun x -> Match x) (sub_list (sub_2 sub_ignore sub_current) pel)
| _ -> ...
*)
type ('a, 'at, 'bt, 'b) sub = 'a -> ('bt list -> 'b) * 'at list
val sub_2 : ('a1, 'at, 'bt, 'b1) sub -> ('a2, 'at, 'bt, 'b2) sub -> ('a1 * 'a2, 'at, 'bt, 'b1 * 'b2) sub
val sub_3 : ('a1, 'at, 'bt, 'b1) sub -> ('a2, 'at, 'bt, 'b2) sub -> ('a3, 'at, 'bt, 'b3) sub -> ('a1 * 'a2 * 'a3, 'at, 'bt, 'b1 * 'b2 * 'b3) sub
val sub_4 : ('a1, 'at, 'bt, 'b1) sub -> ('a2, 'at, 'bt, 'b2) sub -> ('a3, 'at, 'bt, 'b3) sub -> ('a4, 'at, 'bt, 'b4) sub -> ('a1 * 'a2 * 'a3 * 'a4, 'at, 'bt, 'b1 * 'b2 * 'b3 * 'b4) sub
val sub_list : ('a, 'at, 'bt, 'b) sub -> ('a list, 'at, 'bt, 'b list) sub
val sub_option : ('a, 'at, 'bt, 'b) sub -> ('a option, 'at, 'bt, 'b option) sub
val sub_current : ('a, 'a, 'b, 'b) sub
val sub_ignore : ('a, _, _, 'a) sub
val wrap : ('a -> 'b) -> ('at list -> 'a) * 't list -> ('at list -> 'b) * 't list
end
HACK : tmp until we merge it into TRAVERSE_CORE for TraverseInterface ,
and rename it into TRAVERSE
and rename it into TRAVERSE *)
module type OLD_TRAVERSE =
sig
type 'p t constraint 'p = _ * _ * _
val traverse_iter : (('p t -> unit) -> 'p t -> unit) -> 'p t -> unit
val traverse_map : (('p t -> 'p t) -> 'p t -> 'p t) -> 'p t -> 'p t
val traverse_fold : (('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val traverse_foldmap : (('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val traverse_exists : (('p t -> bool) -> 'p t -> bool) -> 'p t -> bool
val traverse_forall : (('p t -> bool) -> 'p t -> bool) -> 'p t -> bool
val traverse_fold_context_down : (('env -> 'a -> 'p t -> 'a) -> 'env -> 'a -> 'p t -> 'a) -> 'env -> 'a -> 'p t -> 'a
val iter : ('p t -> unit) -> 'p t -> unit
val iter_up : ('p t -> unit) -> 'p t -> unit
val iter_down : ('p t -> unit) -> 'p t -> unit
val map : ('p t -> 'p t) -> 'p t -> 'p t
val map_up : ('p t -> 'p t) -> 'p t -> 'p t
val map_down : ('p t -> 'p t) -> 'p t -> 'p t
val fold : ('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val fold_up : ('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val fold_down : ('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val foldmap : ('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val foldmap_up : ('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val foldmap_down : ('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val exists : ('p t -> bool) -> 'p t -> bool
val exists_up : ('p t -> bool) -> 'p t -> bool
val exists_down : ('p t -> bool) -> 'p t -> bool
val find : ('p t -> bool) -> 'p t -> 'p t option
val find_up : ('p t -> bool) -> 'p t -> 'p t option
val find_down : ('p t -> bool) -> 'p t -> 'p t option
val findmap : ('p t -> 'a option) -> 'p t -> 'a option
val findmap_up : ('p t -> 'a option) -> 'p t -> 'a option
val findmap_down : ('p t -> 'a option) -> 'p t -> 'a option
(** traverse all the nodes of the tree in an unspecified order *)
val traverse_fold_right : (('b t -> 'a -> 'a) -> 'b t -> 'a -> 'a) -> 'b t -> 'a -> 'a
* [ fold_up_combine ? combine f acc0 t ] folds [ f ] from leaves with [ acc0 ] , combining
accumulators from sub - trees with [ combine ] before calling [ f ] .
Default value for combine is ( fun _ b - > b )
< ! > Be carefull be using this function without combine , lots of accs are lost
accumulators from sub-trees with [combine] before calling [f].
Default value for combine is (fun _ b -> b)
<!> Be carefull be using this function without combine, lots of accs are lost *)
val fold_up_combine : ?combine:('a -> 'a -> 'a) -> ('a -> 'b t -> 'a) -> 'a -> 'b t -> 'a
(** Folds all the nodes of the tree in an unspecified order *)
val fold_right_down : ('b t -> 'a -> 'a) -> 'b t -> 'a -> 'a
val foldmap_up_combine : ?combine:('a -> 'a -> 'a) -> ('a -> 'b t -> 'a * 'b t) -> 'a -> 'b t -> 'a * 'b t
(** Non-recursive versions, e.g. if you want to handle recursion yourself and have a default case *)
val map_nonrec : ('b t -> 'b t) -> 'b t -> 'b t
val fold_nonrec : ('a -> 'b t -> 'a) -> 'a -> 'b t -> 'a
val foldmap_nonrec : ('a -> 'b t -> 'a * 'b t) -> 'a -> 'b t -> 'a * 'b t
* Just because we had fun writing it . Do n't use as is , it 's probably very slow .
Applies the rewriting until fixpoint reached
Applies the rewriting until fixpoint reached *)
val map_down_fix : ('b t -> 'b t) -> 'b t -> 'b t
(** Additional functions that let you traverse the type 'c t when they are deep into an arbitrary structure 'b
as long as you provide the functions to unbuild/rebuild 'b into t lists *)
type ('b, 'c) sub = ('b, 'c t, 'c t , 'b) Utils.sub
val lift_iter_up : ('b,'c) sub -> ('c t -> unit) -> ('b -> unit)
val lift_iter_down : ('b,'c) sub -> ('c t -> unit) -> ('b -> unit)
val lift_map_up : ('b,'c) sub -> ('c t -> 'c t) -> ('b -> 'b)
val lift_map_down : ('b,'c) sub -> ('c t -> 'c t) -> ('b -> 'b)
(* like fold_map_up_for_real *)
val lift_fold_up_combine : ('b,'c) sub -> ?combine:('a -> 'a -> 'a) -> ('a -> 'c t -> 'a) -> ('a -> 'b -> 'a)
val lift_fold : ('b,'c) sub -> ('a -> 'c t -> 'a) -> ('a -> 'b -> 'a)
val lift_fold_right_down : ('b,'c) sub -> ('c t -> 'a -> 'a) -> ('b -> 'a -> 'a)
val lift_foldmap_up : ('b,'c) sub -> ('a -> 'c t -> 'a * 'c t) -> ('a -> 'b -> 'a * 'b)
val lift_foldmap_down : ('b,'c) sub -> ('a -> 'c t -> 'a * 'c t) -> ('a -> 'b -> 'a * 'b)
val lift_exists : ('b,'c) sub -> ('c t -> bool) -> ('b -> bool)
end
* { 6 First implementation }
(** Functor giving you the usual traverse functions *)
module Make (X : S) : OLD_TRAVERSE with type 'a t = 'a X.t
* Functor for map2 , fold2 , etc .
module MakePair (Fst : S) (Snd : S) : OLD_TRAVERSE with type 'a t = 'a Fst.t * 'a Snd.t
* { 6 Second implementation }
* For the second version ( S2 ) , you may do not want to write the optimised version of fold , map , iter
in this case you can use this unoptimzed constructors , to get them from the foldmap_children function
in this case you can use this unoptimzed constructors, to get them from the foldmap_children function *)
module Unoptimized :
sig
(** Simple recursion *)
type ('acc, 't, 't2) foldmap = ('acc -> 't -> 'acc * 't) -> 'acc -> 't2 -> 'acc * 't2
val iter : (unit, 't, 't2) foldmap -> ('t -> unit) -> 't2 -> unit
val map : (unit, 't, 't2) foldmap -> ('t -> 't) -> 't2 -> 't2
val fold : ('acc, 't, 't2) foldmap -> ('acc -> 't -> 'acc) -> 'acc -> 't2 -> 'acc
(** Mutual recursion *)
type ('acc, 'tA, 'tB) foldmapAB =
('acc -> 'tA -> 'acc * 'tA) ->
('acc -> 'tB -> 'acc * 'tB) ->
'acc -> 'tA -> 'acc * 'tA
val iterAB : (unit, 'tA, 'tB) foldmapAB -> ('tA -> unit) -> ('tB -> unit) -> 'tA -> unit
val mapAB : (unit, 'tA, 'tB) foldmapAB -> ('tA -> 'tA) -> ('tB -> 'tB) -> 'tA -> 'tA
val foldAB : ('acc, 'tA, 'tB) foldmapAB -> ('acc -> 'tA -> 'acc) -> ('acc -> 'tB -> 'acc) -> 'acc -> 'tA -> 'acc
end
open TraverseInterface
module Make2 (X : S2) : TRAVERSE with type 'a t = 'a X.t and type 'a container = 'a X.t
module MakeLift1
(Y : LIFT2)
(X : TRAVERSE with type 'a container = 'a Y.t and type 'a t = 'a Y.t)
: TRAVERSE with type 'a t = 'a X.t and type 'a container = 'a Y.container
module MakeLift2
(Y : LIFT2)
(X : TRAVERSE with type 'a container = 'a Y.t)
: TRAVERSE with type 'a t = 'a X.t and type 'a container = 'a Y.container
From there , you can build Box of Boxes with MakeBox
(* for example, for rewriting rules on a tuple of code, etc...*)
* { 6 Mutual Recursive Trees }
module MakeAB (AB : AB) : TRAVERSE_AB with type 'a tA = 'a AB.tA and type 'a tB = 'a AB.tB
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/ocamllib/libbase/traverse.mli | ocaml | module type TRAVERSE_LIFT =
sig
end
* Some Extensions
(e1,e2) is a pair of expression and you are currently treating
* expressions, you write exactly that:
* traverse all the nodes of the tree in an unspecified order
* Folds all the nodes of the tree in an unspecified order
* Non-recursive versions, e.g. if you want to handle recursion yourself and have a default case
* Additional functions that let you traverse the type 'c t when they are deep into an arbitrary structure 'b
as long as you provide the functions to unbuild/rebuild 'b into t lists
like fold_map_up_for_real
* Functor giving you the usual traverse functions
* Simple recursion
* Mutual recursion
for example, for rewriting rules on a tuple of code, etc... |
Copyright © 2011 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
*
.
This module provides all usual traverse functions and some higher - level ones
on any tree structure as long as we consider only one type of nodes
@author
@author
@author
Generic Ast Rewriter API.
This module provides all usual traverse functions and some higher-level ones
on any tree structure as long as we consider only one type of nodes
@author Louis Gesbert
@author Valentin Gatien-Baron
@author Mathieu Barbin
*)
open TraverseInterface
foldmap : ( ' acc - > ' expr - > ' acc * ' expr ) - > ' acc - > ' code_elt - > ' acc * ' code_elt
module Utils : sig
* A generalisation of the type needed in S
( ' a , ' at , ' bt , ' b ) sub
' a may be expressions where identifiers are strings
' b an expressions where identfiers are uniq
In that case , ( ' a,'a,'b,'b ) represents a function that deconstruct a string expression
into a - list of string expression
- a function that expects an ident expression list and build you the the ' original ' ident expression
DON'T LOOK at the types , it 's too scary
Instead take a look at the following example , where you build the subs_cons function for the expressions
of some ast :
let subs_cons e =
match e with
| Apply ( e1,e2 ) - >
( * ( e1,e2 ) is a pair of expression and you are currently treating
* expressions , you write exactly that :
('a, 'at, 'bt ,'b) sub
'a may be expressions where identifiers are strings
'b an expressions where identfiers are uniq
In that case, ('a,'a,'b,'b) represents a function that deconstruct a string expression
into a - list of string expression
- a function that expects an ident expression list and build you the the 'original' ident expression
DON'T LOOK at the types, it's too scary
Instead take a look at the following example, where you build the subs_cons function for the expressions
of some ast:
let subs_cons e =
match e with
| Apply (e1,e2) ->
wrap (fun x -> Apply x) ((sub_2 sub_current sub_current) (e1,e2))
| Match pel ->
pel is a list of pattern * expr
* we just ignore the pattern since there is no expression inside them
* we stop the deconstruction on the expression , since it is was we are currently deconstructing
* we just ignore the pattern since there is no expression inside them
* we stop the deconstruction on the expression, since it is was we are currently deconstructing *)
wrap (fun x -> Match x) (sub_list (sub_2 sub_ignore sub_current) pel)
| _ -> ...
*)
type ('a, 'at, 'bt, 'b) sub = 'a -> ('bt list -> 'b) * 'at list
val sub_2 : ('a1, 'at, 'bt, 'b1) sub -> ('a2, 'at, 'bt, 'b2) sub -> ('a1 * 'a2, 'at, 'bt, 'b1 * 'b2) sub
val sub_3 : ('a1, 'at, 'bt, 'b1) sub -> ('a2, 'at, 'bt, 'b2) sub -> ('a3, 'at, 'bt, 'b3) sub -> ('a1 * 'a2 * 'a3, 'at, 'bt, 'b1 * 'b2 * 'b3) sub
val sub_4 : ('a1, 'at, 'bt, 'b1) sub -> ('a2, 'at, 'bt, 'b2) sub -> ('a3, 'at, 'bt, 'b3) sub -> ('a4, 'at, 'bt, 'b4) sub -> ('a1 * 'a2 * 'a3 * 'a4, 'at, 'bt, 'b1 * 'b2 * 'b3 * 'b4) sub
val sub_list : ('a, 'at, 'bt, 'b) sub -> ('a list, 'at, 'bt, 'b list) sub
val sub_option : ('a, 'at, 'bt, 'b) sub -> ('a option, 'at, 'bt, 'b option) sub
val sub_current : ('a, 'a, 'b, 'b) sub
val sub_ignore : ('a, _, _, 'a) sub
val wrap : ('a -> 'b) -> ('at list -> 'a) * 't list -> ('at list -> 'b) * 't list
end
HACK : tmp until we merge it into TRAVERSE_CORE for TraverseInterface ,
and rename it into TRAVERSE
and rename it into TRAVERSE *)
module type OLD_TRAVERSE =
sig
type 'p t constraint 'p = _ * _ * _
val traverse_iter : (('p t -> unit) -> 'p t -> unit) -> 'p t -> unit
val traverse_map : (('p t -> 'p t) -> 'p t -> 'p t) -> 'p t -> 'p t
val traverse_fold : (('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val traverse_foldmap : (('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val traverse_exists : (('p t -> bool) -> 'p t -> bool) -> 'p t -> bool
val traverse_forall : (('p t -> bool) -> 'p t -> bool) -> 'p t -> bool
val traverse_fold_context_down : (('env -> 'a -> 'p t -> 'a) -> 'env -> 'a -> 'p t -> 'a) -> 'env -> 'a -> 'p t -> 'a
val iter : ('p t -> unit) -> 'p t -> unit
val iter_up : ('p t -> unit) -> 'p t -> unit
val iter_down : ('p t -> unit) -> 'p t -> unit
val map : ('p t -> 'p t) -> 'p t -> 'p t
val map_up : ('p t -> 'p t) -> 'p t -> 'p t
val map_down : ('p t -> 'p t) -> 'p t -> 'p t
val fold : ('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val fold_up : ('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val fold_down : ('a -> 'p t -> 'a) -> 'a -> 'p t -> 'a
val foldmap : ('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val foldmap_up : ('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val foldmap_down : ('a -> 'p t -> 'a * 'p t) -> 'a -> 'p t -> 'a * 'p t
val exists : ('p t -> bool) -> 'p t -> bool
val exists_up : ('p t -> bool) -> 'p t -> bool
val exists_down : ('p t -> bool) -> 'p t -> bool
val find : ('p t -> bool) -> 'p t -> 'p t option
val find_up : ('p t -> bool) -> 'p t -> 'p t option
val find_down : ('p t -> bool) -> 'p t -> 'p t option
val findmap : ('p t -> 'a option) -> 'p t -> 'a option
val findmap_up : ('p t -> 'a option) -> 'p t -> 'a option
val findmap_down : ('p t -> 'a option) -> 'p t -> 'a option
val traverse_fold_right : (('b t -> 'a -> 'a) -> 'b t -> 'a -> 'a) -> 'b t -> 'a -> 'a
* [ fold_up_combine ? combine f acc0 t ] folds [ f ] from leaves with [ acc0 ] , combining
accumulators from sub - trees with [ combine ] before calling [ f ] .
Default value for combine is ( fun _ b - > b )
< ! > Be carefull be using this function without combine , lots of accs are lost
accumulators from sub-trees with [combine] before calling [f].
Default value for combine is (fun _ b -> b)
<!> Be carefull be using this function without combine, lots of accs are lost *)
val fold_up_combine : ?combine:('a -> 'a -> 'a) -> ('a -> 'b t -> 'a) -> 'a -> 'b t -> 'a
val fold_right_down : ('b t -> 'a -> 'a) -> 'b t -> 'a -> 'a
val foldmap_up_combine : ?combine:('a -> 'a -> 'a) -> ('a -> 'b t -> 'a * 'b t) -> 'a -> 'b t -> 'a * 'b t
val map_nonrec : ('b t -> 'b t) -> 'b t -> 'b t
val fold_nonrec : ('a -> 'b t -> 'a) -> 'a -> 'b t -> 'a
val foldmap_nonrec : ('a -> 'b t -> 'a * 'b t) -> 'a -> 'b t -> 'a * 'b t
* Just because we had fun writing it . Do n't use as is , it 's probably very slow .
Applies the rewriting until fixpoint reached
Applies the rewriting until fixpoint reached *)
val map_down_fix : ('b t -> 'b t) -> 'b t -> 'b t
type ('b, 'c) sub = ('b, 'c t, 'c t , 'b) Utils.sub
val lift_iter_up : ('b,'c) sub -> ('c t -> unit) -> ('b -> unit)
val lift_iter_down : ('b,'c) sub -> ('c t -> unit) -> ('b -> unit)
val lift_map_up : ('b,'c) sub -> ('c t -> 'c t) -> ('b -> 'b)
val lift_map_down : ('b,'c) sub -> ('c t -> 'c t) -> ('b -> 'b)
val lift_fold_up_combine : ('b,'c) sub -> ?combine:('a -> 'a -> 'a) -> ('a -> 'c t -> 'a) -> ('a -> 'b -> 'a)
val lift_fold : ('b,'c) sub -> ('a -> 'c t -> 'a) -> ('a -> 'b -> 'a)
val lift_fold_right_down : ('b,'c) sub -> ('c t -> 'a -> 'a) -> ('b -> 'a -> 'a)
val lift_foldmap_up : ('b,'c) sub -> ('a -> 'c t -> 'a * 'c t) -> ('a -> 'b -> 'a * 'b)
val lift_foldmap_down : ('b,'c) sub -> ('a -> 'c t -> 'a * 'c t) -> ('a -> 'b -> 'a * 'b)
val lift_exists : ('b,'c) sub -> ('c t -> bool) -> ('b -> bool)
end
* { 6 First implementation }
module Make (X : S) : OLD_TRAVERSE with type 'a t = 'a X.t
* Functor for map2 , fold2 , etc .
module MakePair (Fst : S) (Snd : S) : OLD_TRAVERSE with type 'a t = 'a Fst.t * 'a Snd.t
* { 6 Second implementation }
* For the second version ( S2 ) , you may do not want to write the optimised version of fold , map , iter
in this case you can use this unoptimzed constructors , to get them from the foldmap_children function
in this case you can use this unoptimzed constructors, to get them from the foldmap_children function *)
module Unoptimized :
sig
type ('acc, 't, 't2) foldmap = ('acc -> 't -> 'acc * 't) -> 'acc -> 't2 -> 'acc * 't2
val iter : (unit, 't, 't2) foldmap -> ('t -> unit) -> 't2 -> unit
val map : (unit, 't, 't2) foldmap -> ('t -> 't) -> 't2 -> 't2
val fold : ('acc, 't, 't2) foldmap -> ('acc -> 't -> 'acc) -> 'acc -> 't2 -> 'acc
type ('acc, 'tA, 'tB) foldmapAB =
('acc -> 'tA -> 'acc * 'tA) ->
('acc -> 'tB -> 'acc * 'tB) ->
'acc -> 'tA -> 'acc * 'tA
val iterAB : (unit, 'tA, 'tB) foldmapAB -> ('tA -> unit) -> ('tB -> unit) -> 'tA -> unit
val mapAB : (unit, 'tA, 'tB) foldmapAB -> ('tA -> 'tA) -> ('tB -> 'tB) -> 'tA -> 'tA
val foldAB : ('acc, 'tA, 'tB) foldmapAB -> ('acc -> 'tA -> 'acc) -> ('acc -> 'tB -> 'acc) -> 'acc -> 'tA -> 'acc
end
open TraverseInterface
module Make2 (X : S2) : TRAVERSE with type 'a t = 'a X.t and type 'a container = 'a X.t
module MakeLift1
(Y : LIFT2)
(X : TRAVERSE with type 'a container = 'a Y.t and type 'a t = 'a Y.t)
: TRAVERSE with type 'a t = 'a X.t and type 'a container = 'a Y.container
module MakeLift2
(Y : LIFT2)
(X : TRAVERSE with type 'a container = 'a Y.t)
: TRAVERSE with type 'a t = 'a X.t and type 'a container = 'a Y.container
From there , you can build Box of Boxes with MakeBox
* { 6 Mutual Recursive Trees }
module MakeAB (AB : AB) : TRAVERSE_AB with type 'a tA = 'a AB.tA and type 'a tB = 'a AB.tB
|
982cedbbde3e9f32b2b361a970a83470975b0959525922694218962c7ce6d0ee | realark/vert | platformer-game-scene.lisp | (in-package :recurse.vert)
;;;; platformer-game-scene
(defparameter *default-gravity-acceleration-seconds* 500
"The default downward force of gravity in px/s/s")
@export-class
(defclass platformer-game-scene (game-scene physics-context-2d)
((gravity-vector :initarg :gravity-vector
:initform (make-acceleration-vector-seconds :y *default-gravity-acceleration-seconds*)
:reader gravity-vector
:documentation "Force and direction of gravity on movable objects"))
(:documentation "A 2d platformer map with gravity."))
@export
(defgeneric apply-gravity (kinematic-object vector2)
(:documentation "Apply a 2d gravity vector to an object")
(:method ((object kinematic-object) vector)
(declare (vector2 vector))
(log:trace "Applying gravity to ~A" object)
(apply-vector object vector)))
(defmethod found-object-to-update ((scene platformer-game-scene) (game-object kinematic-object))
(with-accessors ((gravity gravity-vector)) scene
(apply-gravity game-object gravity)))
| null | https://raw.githubusercontent.com/realark/vert/4cb88545abc60f1fba4a8604ce85e70cbd4764a2/src/plugins/platformer/platformer-game-scene.lisp | lisp | platformer-game-scene | (in-package :recurse.vert)
(defparameter *default-gravity-acceleration-seconds* 500
"The default downward force of gravity in px/s/s")
@export-class
(defclass platformer-game-scene (game-scene physics-context-2d)
((gravity-vector :initarg :gravity-vector
:initform (make-acceleration-vector-seconds :y *default-gravity-acceleration-seconds*)
:reader gravity-vector
:documentation "Force and direction of gravity on movable objects"))
(:documentation "A 2d platformer map with gravity."))
@export
(defgeneric apply-gravity (kinematic-object vector2)
(:documentation "Apply a 2d gravity vector to an object")
(:method ((object kinematic-object) vector)
(declare (vector2 vector))
(log:trace "Applying gravity to ~A" object)
(apply-vector object vector)))
(defmethod found-object-to-update ((scene platformer-game-scene) (game-object kinematic-object))
(with-accessors ((gravity gravity-vector)) scene
(apply-gravity game-object gravity)))
|
c1d3058a5644528116072945f612862a2d080e5c26e84e105872cbc60438f4bf | brendanhay/gogol | Patch.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . ContainerBuilder . Cloudbuild . Projects . Locations . GithubEnterpriseConfigs . Patch
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Update an association between a GCP project and a GitHub Enterprise server .
--
-- /See:/ <-build/docs/ Cloud Build API Reference> for @cloudbuild.projects.locations.githubEnterpriseConfigs.patch@.
module Gogol.ContainerBuilder.Cloudbuild.Projects.Locations.GithubEnterpriseConfigs.Patch
( -- * Resource
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatchResource,
-- ** Constructing a Request
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch (..),
newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch,
)
where
import Gogol.ContainerBuilder.Types
import qualified Gogol.Prelude as Core
-- | A resource alias for @cloudbuild.projects.locations.githubEnterpriseConfigs.patch@ method which the
-- 'CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch' request conforms to.
type CloudbuildProjectsLocationsGithubEnterpriseConfigsPatchResource =
"v1"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody '[Core.JSON] GitHubEnterpriseConfig
Core.:> Core.Patch '[Core.JSON] Operation
| Update an association between a GCP project and a GitHub Enterprise server .
--
-- /See:/ 'newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch' smart constructor.
data CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch = CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
| Optional . The full resource name for the GitHubEnterpriseConfig For example : \"projects\/{$project / id}\/githubEnterpriseConfigs\/{$config / id}\ "
name :: Core.Text,
-- | Multipart request metadata.
payload :: GitHubEnterpriseConfig,
-- | Update mask for the resource. If this is set, the server will only update the fields specified in the field mask. Otherwise, a full update of the mutable resource fields will be performed.
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch' with the minimum fields required to make a request.
newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch ::
| Optional . The full resource name for the GitHubEnterpriseConfig For example : \"projects\/{$project / id}\/githubEnterpriseConfigs\/{$config / id}\ " See ' name ' .
Core.Text ->
-- | Multipart request metadata. See 'payload'.
GitHubEnterpriseConfig ->
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch name payload =
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
payload = payload,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
where
type
Rs
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch =
Operation
type
Scopes
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch =
'[CloudPlatform'FullControl]
requestClient
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch {..} =
go
name
xgafv
accessToken
callback
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
containerBuilderService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatchResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-containerbuilder/gen/Gogol/ContainerBuilder/Cloudbuild/Projects/Locations/GithubEnterpriseConfigs/Patch.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
/See:/ <-build/docs/ Cloud Build API Reference> for @cloudbuild.projects.locations.githubEnterpriseConfigs.patch@.
* Resource
** Constructing a Request
| A resource alias for @cloudbuild.projects.locations.githubEnterpriseConfigs.patch@ method which the
'CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch' request conforms to.
/See:/ 'newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch' smart constructor.
| V1 error format.
| OAuth access token.
| Multipart request metadata.
| Update mask for the resource. If this is set, the server will only update the fields specified in the field mask. Otherwise, a full update of the mutable resource fields will be performed.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch' with the minimum fields required to make a request.
| Multipart request metadata. See 'payload'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . ContainerBuilder . Cloudbuild . Projects . Locations . GithubEnterpriseConfigs . Patch
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Update an association between a GCP project and a GitHub Enterprise server .
module Gogol.ContainerBuilder.Cloudbuild.Projects.Locations.GithubEnterpriseConfigs.Patch
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatchResource,
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch (..),
newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch,
)
where
import Gogol.ContainerBuilder.Types
import qualified Gogol.Prelude as Core
type CloudbuildProjectsLocationsGithubEnterpriseConfigsPatchResource =
"v1"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody '[Core.JSON] GitHubEnterpriseConfig
Core.:> Core.Patch '[Core.JSON] Operation
| Update an association between a GCP project and a GitHub Enterprise server .
data CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch = CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
| Optional . The full resource name for the GitHubEnterpriseConfig For example : \"projects\/{$project / id}\/githubEnterpriseConfigs\/{$config / id}\ "
name :: Core.Text,
payload :: GitHubEnterpriseConfig,
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch ::
| Optional . The full resource name for the GitHubEnterpriseConfig For example : \"projects\/{$project / id}\/githubEnterpriseConfigs\/{$config / id}\ " See ' name ' .
Core.Text ->
GitHubEnterpriseConfig ->
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
newCloudbuildProjectsLocationsGithubEnterpriseConfigsPatch name payload =
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
payload = payload,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch
where
type
Rs
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch =
Operation
type
Scopes
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch =
'[CloudPlatform'FullControl]
requestClient
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatch {..} =
go
name
xgafv
accessToken
callback
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
containerBuilderService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
CloudbuildProjectsLocationsGithubEnterpriseConfigsPatchResource
)
Core.mempty
|
4eb21474e9be96595e9c9e23e4dabb8461b7d1f5d151bbbb43b7ff78d91ff4f0 | trchopan/scheduled-blocks | PersistReportSpec.hs | module Application.PersistReportSpec where
import Test.Hspec ( Spec
, describe
, it
, shouldBe
)
spec :: Spec
spec = do
describe "persistReport" $ do
it "persist pass" $ do
(2 :: Integer) `shouldBe` (1 :: Integer)
| null | https://raw.githubusercontent.com/trchopan/scheduled-blocks/f79c4fb94f17d45ae9e6180a8cc9f9bcc5f16d34/test/Application/PersistReportSpec.hs | haskell | module Application.PersistReportSpec where
import Test.Hspec ( Spec
, describe
, it
, shouldBe
)
spec :: Spec
spec = do
describe "persistReport" $ do
it "persist pass" $ do
(2 :: Integer) `shouldBe` (1 :: Integer)
|
|
819855f5bcf9623eeab3bca5269b5ec2a26a99346d94a736541dcbb5bc5f9a9c | v0d1ch/plaid | Income.hs | module Data.Api.Income
( plaidGetIncome
) where
import Data.Common
plaidGetIncome
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> PlaidBody PlaidIncomeGet
-> m ByteString
plaidGetIncome body = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/income/get") body
| null | https://raw.githubusercontent.com/v0d1ch/plaid/c70dfe1064e06be0c56dc06384a7ff4ed0691019/Data/Api/Income.hs | haskell | module Data.Api.Income
( plaidGetIncome
) where
import Data.Common
plaidGetIncome
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> PlaidBody PlaidIncomeGet
-> m ByteString
plaidGetIncome body = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/income/get") body
|
|
c1c43c0186ae05271451021c0a53af0bdd63a9ddfbe4cabf255b995f367187e2 | hiroshi-unno/coar | variables.ml | open Core
module StringSet = Set.Make(String)
type t = StringSet.t
let empty = StringSet.empty
let union vars1 vars2 : t = StringSet.union vars1 vars2
let add var vars : t = StringSet.add vars var
let sub vars1 vars2 : t = StringSet.diff vars1 vars2
let inter vars1 vars2 : t = StringSet.inter vars1 vars2
let is_mem varname vars = StringSet.mem varname vars
let of_list varnames : t = StringSet.of_list varnames
let of_tvarset tvarset : t =
Set.Poly.to_list tvarset
|> List.map ~f:Ast.Ident.name_of_tvar
|> of_list
let of_varname varname: t = add varname empty
let to_list (vars: t) = StringSet.elements vars
let string_of (vars: t) = String.concat ~sep:", " @@ to_list vars
let is_empty vars: bool = StringSet.is_empty vars
| null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/c/variables.ml | ocaml | open Core
module StringSet = Set.Make(String)
type t = StringSet.t
let empty = StringSet.empty
let union vars1 vars2 : t = StringSet.union vars1 vars2
let add var vars : t = StringSet.add vars var
let sub vars1 vars2 : t = StringSet.diff vars1 vars2
let inter vars1 vars2 : t = StringSet.inter vars1 vars2
let is_mem varname vars = StringSet.mem varname vars
let of_list varnames : t = StringSet.of_list varnames
let of_tvarset tvarset : t =
Set.Poly.to_list tvarset
|> List.map ~f:Ast.Ident.name_of_tvar
|> of_list
let of_varname varname: t = add varname empty
let to_list (vars: t) = StringSet.elements vars
let string_of (vars: t) = String.concat ~sep:", " @@ to_list vars
let is_empty vars: bool = StringSet.is_empty vars
|
|
dab50f32604b76d27e62652dc03bd67156642b4d06e5ecae597beecc7c60f310 | dktr0/estuary | Reflex.hs | # LANGUAGE TypeFamilies , RankNTypes , OverloadedStrings #
module Estuary.Test.Reflex where
import Control.Concurrent.MVar
import Control.Concurrent.Async
import Control.Monad.IO.Class
import Data.Map
import Estuary.Test.Dom (findMatchingSelectorInDocument)
import GHCJS.DOM.Types (Element, HTMLDivElement, fromJSString)
import Reflex.Dom hiding (link)
import Reflex.Dynamic
-- renderSync renders the widget, waits for it to mount, and returns the container
-- element it was mounted in.
renderSync :: (forall x. Widget x ()) -> IO (HTMLDivElement)
renderSync widget = do
resultContainer <- newEmptyMVar
finishedRender <- async $ takeMVar resultContainer
link finishedRender -- any exceptions should be thrown here
mainWidgetInElementById "estuary-root" $ do
widget
(Just containerEl) <- liftIO $ findMatchingSelectorInDocument ("#estuary-root" :: String)
postBuildEv <- getPostBuild
performEvent_ $ ffor postBuildEv $ \_ -> liftIO $
putMVar resultContainer containerEl
wait finishedRender
-- renderSync_ renders the widget and waits for it to mount.
renderSync_ :: (forall x. Widget x ()) -> IO ()
renderSync_ widget = do
resultContainer <- newEmptyMVar
finishedRender <- async $ takeMVar resultContainer
link finishedRender -- any exceptions should be thrown here
mainWidgetInElementById "estuary-root" $ do
widget
postBuildEv <- getPostBuild
performEvent_ $ ffor postBuildEv $ \_ -> liftIO $ do
putMVar resultContainer ()
wait finishedRender
| null | https://raw.githubusercontent.com/dktr0/estuary/d4860cb61a7777d0b0a326ab6d8cb6e2d807e258/client/src/Estuary/test/Estuary/Test/Reflex.hs | haskell | renderSync renders the widget, waits for it to mount, and returns the container
element it was mounted in.
any exceptions should be thrown here
renderSync_ renders the widget and waits for it to mount.
any exceptions should be thrown here | # LANGUAGE TypeFamilies , RankNTypes , OverloadedStrings #
module Estuary.Test.Reflex where
import Control.Concurrent.MVar
import Control.Concurrent.Async
import Control.Monad.IO.Class
import Data.Map
import Estuary.Test.Dom (findMatchingSelectorInDocument)
import GHCJS.DOM.Types (Element, HTMLDivElement, fromJSString)
import Reflex.Dom hiding (link)
import Reflex.Dynamic
renderSync :: (forall x. Widget x ()) -> IO (HTMLDivElement)
renderSync widget = do
resultContainer <- newEmptyMVar
finishedRender <- async $ takeMVar resultContainer
mainWidgetInElementById "estuary-root" $ do
widget
(Just containerEl) <- liftIO $ findMatchingSelectorInDocument ("#estuary-root" :: String)
postBuildEv <- getPostBuild
performEvent_ $ ffor postBuildEv $ \_ -> liftIO $
putMVar resultContainer containerEl
wait finishedRender
renderSync_ :: (forall x. Widget x ()) -> IO ()
renderSync_ widget = do
resultContainer <- newEmptyMVar
finishedRender <- async $ takeMVar resultContainer
mainWidgetInElementById "estuary-root" $ do
widget
postBuildEv <- getPostBuild
performEvent_ $ ffor postBuildEv $ \_ -> liftIO $ do
putMVar resultContainer ()
wait finishedRender
|
a478fcf66cb8ae654eaa0c2e35e3e1d7dd97f98cdbe603c4615a0e0ac8b74b8b | fulcrologic/statecharts | assign_current_small_step_spec.cljc | (ns com.fulcrologic.statecharts.algorithms.v20150901.assign-current-small-step-spec
(:require
[com.fulcrologic.statecharts.chart :as chart]
[com.fulcrologic.statecharts.data-model.operations :as ops]
[com.fulcrologic.statecharts.elements
:refer [assign data-model on-entry parallel script state transition]]
[com.fulcrologic.statecharts.testing :as testing]
[fulcro-spec.core :refer [=> assertions specification]]))
(specification "test0"
(let [chart (chart/statechart {}
(data-model
{:expr {:x nil}})
(state {:id :a}
(on-entry {}
(assign {:location :x :expr -1})
(assign {:location :x :expr 99}))
(transition {:event :t
:target :b
:cond (fn [_ {:keys [x]}] (= x 99))}
(assign {:location :x :expr (fn [_ {:keys [x]}] (+ x 1))})))
(state {:id :b}
(on-entry {}
(script {:expr (fn script* [env {:keys [x]}]
[(ops/assign [:ROOT :x] (* 2 x))])}))
(transition {:target :c
:cond (fn [_ {:keys [x]}] (= 200 x))})
(transition {:target :f}))
(state {:id :c})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :c) => true)))
(specification "test1"
(let [chart (chart/statechart {}
(data-model
{:id :i})
(state {:id :a}
(transition {:target :b :event :t}
(assign {:location :i :expr 0})))
(state {:id :b}
(transition {:target :b
:cond (fn [_ {:keys [i]}] (< i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))}))
(transition {:target :c :cond (fn [_ {:keys [i]}] (= i 100))}))
(state {:id :c}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :c) => true)))
(specification "test2"
(let [chart (chart/statechart {}
(data-model
{:id :i})
(state {:id :a}
(transition {:target :b :event :t}
(assign {:location :i :expr 0})))
(state {:id :A}
(state {:id :b}
(transition {:target :c
:cond (fn [_ {:keys [i]}] (< i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))})))
(state {:id :c}
(transition {:target :b
:cond (fn [_ {:keys [i]}] (< i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))})))
(transition {:target :d :cond (fn [_ {:keys [i]}] (= i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (* 2 i))})))
(state {:id :d}
(transition {:target :e :cond (fn [_ {:keys [i]}] (= i 200))})
(transition {:target :f}))
(state {:id :e})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :e) => true)))
(specification "test3"
(let [chart (chart/statechart {}
(data-model
{:id :i})
(state {:id :a}
(transition {:target :p :event :t1}
(assign {:location :i :expr 0})))
(parallel {:id :p}
(state {:id :b :initial :b1}
(state {:id :b1}
(transition {:event :t2 :target :b2}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))})))
(state {:id :b2}))
(state {:id :c :initial :c1}
(state {:id :c1}
(transition {:event :t2 :target :c2}
(assign {:location :i :expr (fn [_ {:keys [i]}] (dec i))})))
(state {:id :c2}))
(transition {:event :t3 :target :d :cond (fn [_ {:keys [i]}] (= i 0))})
(transition {:event :t3 :target :f}))
(state {:id :d})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t1)
(assertions
(testing/in? env :b1) => true
(testing/in? env :c1) => true)
(testing/run-events! env :t2)
(assertions
(testing/in? env :b2) => true
(testing/in? env :c2) => true)
(testing/run-events! env :t3)
(assertions
(testing/in? env :d) => true)))
(specification "test4"
(let [chart (chart/statechart {}
(data-model
{:id :x})
(state {:id :a}
(on-entry {}
(assign {:location :x :expr 2}))
(transition {:event :t :target :b1}))
(state {:id :b}
(on-entry {}
(assign {:location :x :expr (fn [_ {:keys [x]}] (* x 3))}))
(state {:id :b1}
(on-entry {}
(assign {:location :x :expr (fn [_ {:keys [x]}] (* x 5))})))
(state {:id :b2}
(on-entry {}
(assign {:location :x :expr (fn [_ {:keys [x]}] (* x 7))})))
(transition {:target :c :cond (fn [_ {:keys [x]}] (= x 30))})
(transition {:target :f}))
(state {:id :c})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :c) => true)))
| null | https://raw.githubusercontent.com/fulcrologic/statecharts/9a081be7da28ba9f9e2f7cdca75d1be4c030e3e0/src/test/com/fulcrologic/statecharts/algorithms/v20150901/assign_current_small_step_spec.cljc | clojure | (ns com.fulcrologic.statecharts.algorithms.v20150901.assign-current-small-step-spec
(:require
[com.fulcrologic.statecharts.chart :as chart]
[com.fulcrologic.statecharts.data-model.operations :as ops]
[com.fulcrologic.statecharts.elements
:refer [assign data-model on-entry parallel script state transition]]
[com.fulcrologic.statecharts.testing :as testing]
[fulcro-spec.core :refer [=> assertions specification]]))
(specification "test0"
(let [chart (chart/statechart {}
(data-model
{:expr {:x nil}})
(state {:id :a}
(on-entry {}
(assign {:location :x :expr -1})
(assign {:location :x :expr 99}))
(transition {:event :t
:target :b
:cond (fn [_ {:keys [x]}] (= x 99))}
(assign {:location :x :expr (fn [_ {:keys [x]}] (+ x 1))})))
(state {:id :b}
(on-entry {}
(script {:expr (fn script* [env {:keys [x]}]
[(ops/assign [:ROOT :x] (* 2 x))])}))
(transition {:target :c
:cond (fn [_ {:keys [x]}] (= 200 x))})
(transition {:target :f}))
(state {:id :c})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :c) => true)))
(specification "test1"
(let [chart (chart/statechart {}
(data-model
{:id :i})
(state {:id :a}
(transition {:target :b :event :t}
(assign {:location :i :expr 0})))
(state {:id :b}
(transition {:target :b
:cond (fn [_ {:keys [i]}] (< i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))}))
(transition {:target :c :cond (fn [_ {:keys [i]}] (= i 100))}))
(state {:id :c}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :c) => true)))
(specification "test2"
(let [chart (chart/statechart {}
(data-model
{:id :i})
(state {:id :a}
(transition {:target :b :event :t}
(assign {:location :i :expr 0})))
(state {:id :A}
(state {:id :b}
(transition {:target :c
:cond (fn [_ {:keys [i]}] (< i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))})))
(state {:id :c}
(transition {:target :b
:cond (fn [_ {:keys [i]}] (< i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))})))
(transition {:target :d :cond (fn [_ {:keys [i]}] (= i 100))}
(assign {:location :i :expr (fn [_ {:keys [i]}] (* 2 i))})))
(state {:id :d}
(transition {:target :e :cond (fn [_ {:keys [i]}] (= i 200))})
(transition {:target :f}))
(state {:id :e})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :e) => true)))
(specification "test3"
(let [chart (chart/statechart {}
(data-model
{:id :i})
(state {:id :a}
(transition {:target :p :event :t1}
(assign {:location :i :expr 0})))
(parallel {:id :p}
(state {:id :b :initial :b1}
(state {:id :b1}
(transition {:event :t2 :target :b2}
(assign {:location :i :expr (fn [_ {:keys [i]}] (inc i))})))
(state {:id :b2}))
(state {:id :c :initial :c1}
(state {:id :c1}
(transition {:event :t2 :target :c2}
(assign {:location :i :expr (fn [_ {:keys [i]}] (dec i))})))
(state {:id :c2}))
(transition {:event :t3 :target :d :cond (fn [_ {:keys [i]}] (= i 0))})
(transition {:event :t3 :target :f}))
(state {:id :d})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t1)
(assertions
(testing/in? env :b1) => true
(testing/in? env :c1) => true)
(testing/run-events! env :t2)
(assertions
(testing/in? env :b2) => true
(testing/in? env :c2) => true)
(testing/run-events! env :t3)
(assertions
(testing/in? env :d) => true)))
(specification "test4"
(let [chart (chart/statechart {}
(data-model
{:id :x})
(state {:id :a}
(on-entry {}
(assign {:location :x :expr 2}))
(transition {:event :t :target :b1}))
(state {:id :b}
(on-entry {}
(assign {:location :x :expr (fn [_ {:keys [x]}] (* x 3))}))
(state {:id :b1}
(on-entry {}
(assign {:location :x :expr (fn [_ {:keys [x]}] (* x 5))})))
(state {:id :b2}
(on-entry {}
(assign {:location :x :expr (fn [_ {:keys [x]}] (* x 7))})))
(transition {:target :c :cond (fn [_ {:keys [x]}] (= x 30))})
(transition {:target :f}))
(state {:id :c})
(state {:id :f}))
env (testing/new-testing-env {:statechart chart
:mocking-options {:run-unmocked? true}} {})]
(testing/start! env)
(assertions
(testing/in? env :a) => true)
(testing/run-events! env :t)
(assertions
(testing/in? env :c) => true)))
|
|
504171f7eede11f309481095697cb86c2791c7a7644521df1bac86ecd48b8f59 | smart-chain-fr/tokenomia | Convert.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE TupleSections #
# LANGUAGE NumericUnderscores #
# LANGUAGE NamedFieldPuns #
module Tokenomia.ICO.Funds.Validation.CardanoCLI.Convert
( convertInvestorPlans) where
import Prelude hiding (round,print)
import Control.Monad.Reader hiding (ask)
import Control.Monad.Except
import Data.Set.Ordered as Set
import Data.List.NonEmpty as NEL
import Tokenomia.Common.Environment
import Data.Foldable
import Tokenomia.ICO.Funds.Validation.Investor.Command as Plan
import Tokenomia.ICO.Funds.Validation.ChildAddress.Types
import Tokenomia.Common.Error
import Tokenomia.ICO.Funds.Validation.Investor.Plan
import Tokenomia.ICO.Funds.Validation.CardanoCLI.Command as CardanoCLI
import Tokenomia.Wallet.ChildAddress.ChainIndex
import Data.Coerce
import Tokenomia.Wallet.ChildAddress.ChildAddressRef
import Tokenomia.Wallet.UTxO
import Tokenomia.Wallet.WalletUTxO
import Ledger.Ada as Ada
import Plutus.V2.Ledger.Api (TxOutRef)
import Tokenomia.Common.Datum
import Tokenomia.ICO.Round.Settings
import Tokenomia.ICO.Funds.Validation.CardanoCLI.Datum
convertInvestorPlans
:: ( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m)
=> RoundSettings
-> NonEmpty InvestorPlan
-> m [CardanoCLI.Command]
convertInvestorPlans settings addressFundsPlans = do
res <- mapM (convertInvestorPlan settings) addressFundsPlans
(return . Set.toAscList . unbiased ) $ fold (toBiasR <$> res)
toBiasR :: a -> Bias R a
toBiasR = coerce
convertInvestorPlan
:: ( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m)
=> RoundSettings -> InvestorPlan -> m (OSet CardanoCLI.Command)
convertInvestorPlan
settings
InvestorPlan {investorRef = WhiteListedInvestorRef {indexedAddress = IndexedAddress {..}}
, ..}
= do
sources <- queryUTxO childAddressRef
Set.fromList <$> mapM (convertCommand settings sources) (toAscList commands)
convertCommand
:: ( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m)
=> RoundSettings
-> [WalletUTxO]
-> Plan.Command
-> m CardanoCLI.Command
convertCommand RoundSettings { addresses = RoundAddresses {..},..} sources planCommand =
case (planCommand,nextRoundMaybe) of
( {investorRef = WhiteListedInvestorRef {..},..},Nothing )-> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
return
CardanoCLI.Refund { source = source
, refundAddress = paybackAddress
, adasToRefund = amountToReject
, receivedAt = receivedAt}
( {..}, Just NextRound {exchangeAddress = nextRoundExchangeAddress} ) -> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex investorRef)
return
CardanoCLI.MoveToNextRound { source = source
, adasToMove = amountToReject
, receivedAt = receivedAt
, datum = datumFile
, nextRoundExchangeAddress = nextRoundExchangeAddress}
( {investorRef = w@WhiteListedInvestorRef {..},..}, Nothing )-> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex w)
return
CardanoCLI.SendOnExchangeAddressAndPartiallyRefund
{ source = source
, refundAddress = paybackAddress
, adasToSendOnExchange = adasToSendOnExchange
, adasToRefund = amountToReject
, receivedAt = receivedAt
, datum = datumFile
, exchangeAddress = address exchange}
( {investorRef = w,..}, Just NextRound {exchangeAddress = nextRoundExchangeAddress} ) -> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex w)
return
CardanoCLI.SendOnExchangeAddressAndPartiallyMoveToNextRound
{ source = source
, adasToSendOnExchange = adasToSendOnExchange
, adasToMove = amountToReject
, receivedAt = receivedAt
, datum = datumFile
, nextRoundExchangeAddress = nextRoundExchangeAddress
, exchangeAddress = address exchange}
( {investorRef = w,..}, _) -> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex w)
return
CardanoCLI.SendOnExchangeAddress
{ source = source
, adasToSendOnExchange = adasToSendOnExchange
, receivedAt = receivedAt
, datum = datumFile
, exchangeAddress = address exchange}
findUTxOInCardanoCLI
:: (MonadError TokenomiaError m)
=> [WalletUTxO]
-> TxOutRef
-> Ada
-> m WalletUTxO
findUTxOInCardanoCLI utxos refGiven adas = do
let res = find (\WalletUTxO{utxo = UTxO {txOutRef = txOutRefFromSources,..}}
-> txOutRefFromSources == refGiven && value == Ada.toValue adas) utxos
case res of
Nothing -> throwError
(InconsistenciesBlockFrostVSLocalNode
$ "ref from BlockFrost with adas not found on cardano-cli" <> show refGiven)
Just w -> return w
| null | https://raw.githubusercontent.com/smart-chain-fr/tokenomia/01a6fdc97ccd9229a3fca1a821d0054f38a60e6b/src/Tokenomia/ICO/Funds/Validation/CardanoCLI/Convert.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE TupleSections #
# LANGUAGE NumericUnderscores #
# LANGUAGE NamedFieldPuns #
module Tokenomia.ICO.Funds.Validation.CardanoCLI.Convert
( convertInvestorPlans) where
import Prelude hiding (round,print)
import Control.Monad.Reader hiding (ask)
import Control.Monad.Except
import Data.Set.Ordered as Set
import Data.List.NonEmpty as NEL
import Tokenomia.Common.Environment
import Data.Foldable
import Tokenomia.ICO.Funds.Validation.Investor.Command as Plan
import Tokenomia.ICO.Funds.Validation.ChildAddress.Types
import Tokenomia.Common.Error
import Tokenomia.ICO.Funds.Validation.Investor.Plan
import Tokenomia.ICO.Funds.Validation.CardanoCLI.Command as CardanoCLI
import Tokenomia.Wallet.ChildAddress.ChainIndex
import Data.Coerce
import Tokenomia.Wallet.ChildAddress.ChildAddressRef
import Tokenomia.Wallet.UTxO
import Tokenomia.Wallet.WalletUTxO
import Ledger.Ada as Ada
import Plutus.V2.Ledger.Api (TxOutRef)
import Tokenomia.Common.Datum
import Tokenomia.ICO.Round.Settings
import Tokenomia.ICO.Funds.Validation.CardanoCLI.Datum
convertInvestorPlans
:: ( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m)
=> RoundSettings
-> NonEmpty InvestorPlan
-> m [CardanoCLI.Command]
convertInvestorPlans settings addressFundsPlans = do
res <- mapM (convertInvestorPlan settings) addressFundsPlans
(return . Set.toAscList . unbiased ) $ fold (toBiasR <$> res)
toBiasR :: a -> Bias R a
toBiasR = coerce
convertInvestorPlan
:: ( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m)
=> RoundSettings -> InvestorPlan -> m (OSet CardanoCLI.Command)
convertInvestorPlan
settings
InvestorPlan {investorRef = WhiteListedInvestorRef {indexedAddress = IndexedAddress {..}}
, ..}
= do
sources <- queryUTxO childAddressRef
Set.fromList <$> mapM (convertCommand settings sources) (toAscList commands)
convertCommand
:: ( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m)
=> RoundSettings
-> [WalletUTxO]
-> Plan.Command
-> m CardanoCLI.Command
convertCommand RoundSettings { addresses = RoundAddresses {..},..} sources planCommand =
case (planCommand,nextRoundMaybe) of
( {investorRef = WhiteListedInvestorRef {..},..},Nothing )-> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
return
CardanoCLI.Refund { source = source
, refundAddress = paybackAddress
, adasToRefund = amountToReject
, receivedAt = receivedAt}
( {..}, Just NextRound {exchangeAddress = nextRoundExchangeAddress} ) -> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex investorRef)
return
CardanoCLI.MoveToNextRound { source = source
, adasToMove = amountToReject
, receivedAt = receivedAt
, datum = datumFile
, nextRoundExchangeAddress = nextRoundExchangeAddress}
( {investorRef = w@WhiteListedInvestorRef {..},..}, Nothing )-> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex w)
return
CardanoCLI.SendOnExchangeAddressAndPartiallyRefund
{ source = source
, refundAddress = paybackAddress
, adasToSendOnExchange = adasToSendOnExchange
, adasToRefund = amountToReject
, receivedAt = receivedAt
, datum = datumFile
, exchangeAddress = address exchange}
( {investorRef = w,..}, Just NextRound {exchangeAddress = nextRoundExchangeAddress} ) -> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex w)
return
CardanoCLI.SendOnExchangeAddressAndPartiallyMoveToNextRound
{ source = source
, adasToSendOnExchange = adasToSendOnExchange
, adasToMove = amountToReject
, receivedAt = receivedAt
, datum = datumFile
, nextRoundExchangeAddress = nextRoundExchangeAddress
, exchangeAddress = address exchange}
( {investorRef = w,..}, _) -> do
source <- findUTxOInCardanoCLI sources txOutRef (Plan.getAdas c)
datumFile <- registerDatum
$ mkExchangeDatum receivedAt (getIndex w)
return
CardanoCLI.SendOnExchangeAddress
{ source = source
, adasToSendOnExchange = adasToSendOnExchange
, receivedAt = receivedAt
, datum = datumFile
, exchangeAddress = address exchange}
findUTxOInCardanoCLI
:: (MonadError TokenomiaError m)
=> [WalletUTxO]
-> TxOutRef
-> Ada
-> m WalletUTxO
findUTxOInCardanoCLI utxos refGiven adas = do
let res = find (\WalletUTxO{utxo = UTxO {txOutRef = txOutRefFromSources,..}}
-> txOutRefFromSources == refGiven && value == Ada.toValue adas) utxos
case res of
Nothing -> throwError
(InconsistenciesBlockFrostVSLocalNode
$ "ref from BlockFrost with adas not found on cardano-cli" <> show refGiven)
Just w -> return w
|
d6c0b43051f249c41a6a68926920b363b6090f03bcafcc905fd8f09190eebdca | mhuebert/maria | core.cljs | (ns lark.value-viewer.core
(:require [applied-science.js-interop :as j]
[chia.view :as v]
[chia.view.hiccup :as hiccup])
(:import [goog.async Deferred]))
(def space \u00A0)
(defn kind [thing]
(cond
(char? thing) :character
(false? thing) :false
(keyword? thing) :keyword
(seq? thing) :sequence
(list? thing) :list
(map? thing) :map
(var? thing) :var
(fn? thing) :function
(nil? thing) :nil
(number? thing) :number
(set? thing) :set
(string? thing) :string
(symbol? thing) :symbol
(true? thing) :true
(vector? thing) :vector
(object? thing) :object
(instance? Atom thing) :atom
:else nil))
(def ArrowPointingDown
[:svg {:fill "currentColor", :height "24", :view-box "0 0 24 24", :width "24", :xmlns ""}
[:path {:d "M7 10l5 5 5-5z"}]
[:path {:d "M0 0h24v24H0z", :fill "none"}]])
(def ArrowPointingUp
(-> ArrowPointingDown
(update-in [1 :style] assoc :transform "rotate(180deg)")))
(defn bracket-type [value]
(cond (vector? value) ["[" "]"]
(set? value) ["#{" "}"]
(map? value) ["{" "}"]
:else ["(" ")"]))
(defn wrap-value [[lb rb] value]
[:.inline-flex.items-stretch
[:.flex.items-start.nowrap lb]
[:div.v-top value]
[:.flex.items-end.nowrap rb]])
(extend-protocol hiccup/IElement
Keyword
(-to-element [this] (str this)))
(declare format-value)
(v/defclass display-deferred
{:view/did-mount (fn [{:keys [deferred view/state]}]
(doto ^js deferred
(.addCallback #(swap! state assoc :value %1))
(.addErrback #(swap! state assoc :error %))))}
[{:keys [view/state]}]
(let [{:keys [value error] :as s} @state]
[:div
[:.gray.i "goog.async.Deferred"]
[:.pv3 (cond (nil? s) [:.progress-indeterminate]
error (str error)
:else (or (some-> value (format-value)) [:.gray "Finished."]))]]))
(def expander-outter :.dib.bg-darken.ph2.pv1.mh1.br2)
(def inline-centered :.inline-flex.items-center)
(def ^:dynamic *format-depth-limit* 3)
(defn expanded? [{:keys [view/state]} depth]
(if (boolean? (:collection-expanded? @state))
(:collection-expanded? @state)
(and depth (< depth *format-depth-limit*))))
(defn toggle-depth [{:keys [view/state] :as this} depth label]
(let [is-expanded? (expanded? this depth)
class (if is-expanded?
"cursor-zoom-out hover-bg-darken "
"cursor-zoom-in gray hover-black")]
[:.dib {:class class
:on-click #(swap! state assoc :collection-expanded? (not is-expanded?))} label]))
(defn update-attrs [el f & args]
(if-not (vector? el)
el
(let [attrs? (map? (second el))]
(into [(el 0) (apply f (if attrs? (el 1) {}) args)]
(subvec el (if attrs? 2 1))))))
(defn ensure-keys [forms]
(let [seen #{}]
(map-indexed #(update-attrs %2 update :key (fn [k]
(if (or (nil? k) (contains? seen k))
%1
(do (swap! seen conj k)
k)))) forms)))
(defn map-with-keys [& args]
(ensure-keys (apply clojure.core/map args)))
(v/defclass format-collection
{:view/initial-state {:limit-n 20
:collection-expanded? nil}}
[{state :view/state :as this} depth value]
(let [{:keys [limit-n]} @state
[lb rb] (bracket-type value)
more? (= (count (take (inc limit-n) value)) (inc limit-n))
hover-class (if (even? depth) "hover-bg-darken" "hover-bg-lighten")]
(cond (empty? value)
(str space lb rb space)
(expanded? this depth) [:.inline-flex.items-stretch
{:class hover-class}
[:.flex.items-start.nowrap (if (empty? value) (str space lb)
(toggle-depth this depth (str space lb space)))]
[:div.v-top
(->> (take limit-n value)
(map-with-keys #(format-value (inc depth) %))
(interpose " "))]
(when more? [:.flex.items-end [expander-outter {:class "pointer"
:on-click #(swap! state update :limit-n + 20)} "…"]])
[:.flex.items-end.nowrap (str space rb space)]]
:else [:.inline-flex.items-center.gray.nowrap
{:class hover-class} (toggle-depth this depth (str space lb "…" rb space))])))
(v/defclass format-map
{:view/initial-state {:limit-n 20
:collection-expanded? nil}}
[{state :view/state :as this} depth value]
(let [{:keys [limit-n]} @state
[lb rb] (bracket-type value)
more? (= (count (take (inc limit-n) value)) (inc limit-n))
last-n (if more? limit-n (count value))
hover-class (if (even? depth) "hover-bg-darken" "hover-bg-lighten")]
(if (or (empty? value) (expanded? this depth))
[:table.relative.inline-flex.v-mid
{:class hover-class}
[:tbody
(or (some->> (seq (take limit-n value))
(map-indexed (fn [n [a b]]
[:tr
{:key n}
[:td.v-top.nowrap
(when (= n 0) (toggle-depth this depth (str space lb space)))]
[:td.v-top
(format-value (inc depth) a) space]
[:td.v-top
(format-value (inc depth) b)]
[:td.v-top.nowrap (when (= (inc n) last-n) (str space rb space))]])))
[:tr [:td.hover-bg-darken.nowrap (str space lb rb space)]])
(when more? [:tr [:td {:col-span 2}
[expander-outter {:on-click #(swap! state update :limit-n + 20)} [inline-centered "…"]]]])]]
[:.inline-flex.items-center.gray
{:class hover-class} (toggle-depth this depth (str space lb "…" rb space))])))
(v/defclass format-function
{:view/initial-state (fn [_ value] {:expanded? false})}
[{:keys [view/state]} value]
(let [{:keys [expanded?]} @state]
[:span
"Fun"
[expander-outter {:on-click #(swap! state update :expanded? not)}
[inline-centered [:span.o-50.mr1 (str "ƒ " (j/get value :name))]
(-> (if expanded? ArrowPointingUp
ArrowPointingDown)
(update 1 assoc :width 20 :height 20 :class "mln1 mrn1 o-50"))]
(when expanded?
(.toString value))]]))
(defprotocol IView
(view [this] "Returns a view for `this`"))
(v/defview format-value
([value] (format-value 1 value))
([depth value]
(when (> depth 200)
(prn value)
(throw (js/Error. "Format depth too deep!")))
(cond (v/element? value) value
(or (satisfies? hiccup/IElement value)
(and (vector? value)
(:hiccup (meta value)))) (hiccup/to-element value)
(satisfies? IView value) (format-value depth (view value))
:else
(case (kind value)
(:vector
:sequence
:set) [format-collection depth value]
:map [format-map depth value]
:var [:div
[:.o-50.mb2 (str value)]
[format-value depth @value]]
:nil "nil"
:function [format-function value]
:atom (wrap-value [[:span.gray.mr1 "#Atom"] nil]
(format-value depth (j/get value :state)))
(cond
(v/element? value) value
(instance? cljs.core/Namespace value) (str value)
(instance? Deferred value) (display-deferred {:deferred value})
:else (try (pr-str value)
(catch js/Error e
(do "error printing result"
(.log js/console e)
(prn (type value))
(prn :kind (kind value))
(.log js/console value)
(prn value)))))))))
| null | https://raw.githubusercontent.com/mhuebert/maria/dda46233bd618f2fc6dd3a412c4877ebaff1302a/editor/vendor/lark/value_viewer/core.cljs | clojure | (ns lark.value-viewer.core
(:require [applied-science.js-interop :as j]
[chia.view :as v]
[chia.view.hiccup :as hiccup])
(:import [goog.async Deferred]))
(def space \u00A0)
(defn kind [thing]
(cond
(char? thing) :character
(false? thing) :false
(keyword? thing) :keyword
(seq? thing) :sequence
(list? thing) :list
(map? thing) :map
(var? thing) :var
(fn? thing) :function
(nil? thing) :nil
(number? thing) :number
(set? thing) :set
(string? thing) :string
(symbol? thing) :symbol
(true? thing) :true
(vector? thing) :vector
(object? thing) :object
(instance? Atom thing) :atom
:else nil))
(def ArrowPointingDown
[:svg {:fill "currentColor", :height "24", :view-box "0 0 24 24", :width "24", :xmlns ""}
[:path {:d "M7 10l5 5 5-5z"}]
[:path {:d "M0 0h24v24H0z", :fill "none"}]])
(def ArrowPointingUp
(-> ArrowPointingDown
(update-in [1 :style] assoc :transform "rotate(180deg)")))
(defn bracket-type [value]
(cond (vector? value) ["[" "]"]
(set? value) ["#{" "}"]
(map? value) ["{" "}"]
:else ["(" ")"]))
(defn wrap-value [[lb rb] value]
[:.inline-flex.items-stretch
[:.flex.items-start.nowrap lb]
[:div.v-top value]
[:.flex.items-end.nowrap rb]])
(extend-protocol hiccup/IElement
Keyword
(-to-element [this] (str this)))
(declare format-value)
(v/defclass display-deferred
{:view/did-mount (fn [{:keys [deferred view/state]}]
(doto ^js deferred
(.addCallback #(swap! state assoc :value %1))
(.addErrback #(swap! state assoc :error %))))}
[{:keys [view/state]}]
(let [{:keys [value error] :as s} @state]
[:div
[:.gray.i "goog.async.Deferred"]
[:.pv3 (cond (nil? s) [:.progress-indeterminate]
error (str error)
:else (or (some-> value (format-value)) [:.gray "Finished."]))]]))
(def expander-outter :.dib.bg-darken.ph2.pv1.mh1.br2)
(def inline-centered :.inline-flex.items-center)
(def ^:dynamic *format-depth-limit* 3)
(defn expanded? [{:keys [view/state]} depth]
(if (boolean? (:collection-expanded? @state))
(:collection-expanded? @state)
(and depth (< depth *format-depth-limit*))))
(defn toggle-depth [{:keys [view/state] :as this} depth label]
(let [is-expanded? (expanded? this depth)
class (if is-expanded?
"cursor-zoom-out hover-bg-darken "
"cursor-zoom-in gray hover-black")]
[:.dib {:class class
:on-click #(swap! state assoc :collection-expanded? (not is-expanded?))} label]))
(defn update-attrs [el f & args]
(if-not (vector? el)
el
(let [attrs? (map? (second el))]
(into [(el 0) (apply f (if attrs? (el 1) {}) args)]
(subvec el (if attrs? 2 1))))))
(defn ensure-keys [forms]
(let [seen #{}]
(map-indexed #(update-attrs %2 update :key (fn [k]
(if (or (nil? k) (contains? seen k))
%1
(do (swap! seen conj k)
k)))) forms)))
(defn map-with-keys [& args]
(ensure-keys (apply clojure.core/map args)))
(v/defclass format-collection
{:view/initial-state {:limit-n 20
:collection-expanded? nil}}
[{state :view/state :as this} depth value]
(let [{:keys [limit-n]} @state
[lb rb] (bracket-type value)
more? (= (count (take (inc limit-n) value)) (inc limit-n))
hover-class (if (even? depth) "hover-bg-darken" "hover-bg-lighten")]
(cond (empty? value)
(str space lb rb space)
(expanded? this depth) [:.inline-flex.items-stretch
{:class hover-class}
[:.flex.items-start.nowrap (if (empty? value) (str space lb)
(toggle-depth this depth (str space lb space)))]
[:div.v-top
(->> (take limit-n value)
(map-with-keys #(format-value (inc depth) %))
(interpose " "))]
(when more? [:.flex.items-end [expander-outter {:class "pointer"
:on-click #(swap! state update :limit-n + 20)} "…"]])
[:.flex.items-end.nowrap (str space rb space)]]
:else [:.inline-flex.items-center.gray.nowrap
{:class hover-class} (toggle-depth this depth (str space lb "…" rb space))])))
(v/defclass format-map
{:view/initial-state {:limit-n 20
:collection-expanded? nil}}
[{state :view/state :as this} depth value]
(let [{:keys [limit-n]} @state
[lb rb] (bracket-type value)
more? (= (count (take (inc limit-n) value)) (inc limit-n))
last-n (if more? limit-n (count value))
hover-class (if (even? depth) "hover-bg-darken" "hover-bg-lighten")]
(if (or (empty? value) (expanded? this depth))
[:table.relative.inline-flex.v-mid
{:class hover-class}
[:tbody
(or (some->> (seq (take limit-n value))
(map-indexed (fn [n [a b]]
[:tr
{:key n}
[:td.v-top.nowrap
(when (= n 0) (toggle-depth this depth (str space lb space)))]
[:td.v-top
(format-value (inc depth) a) space]
[:td.v-top
(format-value (inc depth) b)]
[:td.v-top.nowrap (when (= (inc n) last-n) (str space rb space))]])))
[:tr [:td.hover-bg-darken.nowrap (str space lb rb space)]])
(when more? [:tr [:td {:col-span 2}
[expander-outter {:on-click #(swap! state update :limit-n + 20)} [inline-centered "…"]]]])]]
[:.inline-flex.items-center.gray
{:class hover-class} (toggle-depth this depth (str space lb "…" rb space))])))
(v/defclass format-function
{:view/initial-state (fn [_ value] {:expanded? false})}
[{:keys [view/state]} value]
(let [{:keys [expanded?]} @state]
[:span
"Fun"
[expander-outter {:on-click #(swap! state update :expanded? not)}
[inline-centered [:span.o-50.mr1 (str "ƒ " (j/get value :name))]
(-> (if expanded? ArrowPointingUp
ArrowPointingDown)
(update 1 assoc :width 20 :height 20 :class "mln1 mrn1 o-50"))]
(when expanded?
(.toString value))]]))
(defprotocol IView
(view [this] "Returns a view for `this`"))
(v/defview format-value
([value] (format-value 1 value))
([depth value]
(when (> depth 200)
(prn value)
(throw (js/Error. "Format depth too deep!")))
(cond (v/element? value) value
(or (satisfies? hiccup/IElement value)
(and (vector? value)
(:hiccup (meta value)))) (hiccup/to-element value)
(satisfies? IView value) (format-value depth (view value))
:else
(case (kind value)
(:vector
:sequence
:set) [format-collection depth value]
:map [format-map depth value]
:var [:div
[:.o-50.mb2 (str value)]
[format-value depth @value]]
:nil "nil"
:function [format-function value]
:atom (wrap-value [[:span.gray.mr1 "#Atom"] nil]
(format-value depth (j/get value :state)))
(cond
(v/element? value) value
(instance? cljs.core/Namespace value) (str value)
(instance? Deferred value) (display-deferred {:deferred value})
:else (try (pr-str value)
(catch js/Error e
(do "error printing result"
(.log js/console e)
(prn (type value))
(prn :kind (kind value))
(.log js/console value)
(prn value)))))))))
|
|
f8d73f7573f546cf189bf45a69e4b2d69ea6a507389733f45f3d1a023ae33fac | mtolly/onyxite-customs | Sng2014.hs | {-# LANGUAGE ImplicitParams #-}
# LANGUAGE RecordWildCards #
module Onyx.Rocksmith.Sng2014 where
import Control.Monad
import qualified Data.ByteString as B
import Debug.Trace
import Onyx.Codec.Binary
import Onyx.Rocksmith.Crypt
import Onyx.Xbox.STFS (runGetM)
lenArray :: (?endian :: ByteOrder) => BinaryCodec a -> BinaryCodec [a]
lenArray c = Codec
{ codecIn = do
len <- codecIn codecLen
replicateM (fromIntegral len) $ codecIn c
, codecOut = fmapArg $ \xs -> do
void $ codecOut codecLen $ fromIntegral $ length xs
forM_ xs $ codecOut c
} where codecLen = binEndian :: BinaryCodec Word32
nullTerm :: Int -> BinaryCodec B.ByteString
nullTerm n = Codec
{ codecIn = B.takeWhile (/= 0) <$> getByteString n
, codecOut = fmapArg $ \b -> putByteString $ case compare n $ B.length b of
EQ -> b
LT -> B.take n b
GT -> b <> B.replicate (B.length b - n) 0
}
data BPM = BPM -- actually <ebeat>
{ bpm_Time :: Float
, bpm_Measure :: Int16
, bpm_Beat :: Int16
, bpm_PhraseIteration :: Int32
, bpm_Mask :: Int32
} deriving (Eq, Show)
instance BinEndian BPM where
binEndian = do
bpm_Time <- bpm_Time =. binEndian
bpm_Measure <- bpm_Measure =. binEndian
bpm_Beat <- bpm_Beat =. binEndian
bpm_PhraseIteration <- bpm_PhraseIteration =. binEndian
bpm_Mask <- bpm_Mask =. binEndian
return BPM{..}
data Phrase = Phrase
{ phrase_Solo :: Word8
, phrase_Disparity :: Word8
, phrase_Ignore :: Word8
, phrase_Padding :: Word8
, phrase_MaxDifficulty :: Int32
, phrase_PhraseIterationLinks :: Int32
, phrase_Name :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Phrase where
binEndian = do
phrase_Solo <- phrase_Solo =. bin
phrase_Disparity <- phrase_Disparity =. bin
phrase_Ignore <- phrase_Ignore =. bin
phrase_Padding <- phrase_Padding =. bin
phrase_MaxDifficulty <- phrase_MaxDifficulty =. binEndian
phrase_PhraseIterationLinks <- phrase_PhraseIterationLinks =. binEndian
phrase_Name <- phrase_Name =. nullTerm 32
return Phrase{..}
actually < chordTemplate >
{ chord_Mask :: Word32
, chord_Frets :: [Int8]
, chord_Fingers :: [Int8]
, chord_Notes :: [Int32]
, chord_Name :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Chord where
binEndian = do
chord_Mask <- chord_Mask =. binEndian
chord_Frets <- chord_Frets =. fixedArray 6 bin
chord_Fingers <- chord_Fingers =. fixedArray 6 bin
chord_Notes <- chord_Notes =. fixedArray 6 binEndian
chord_Name <- chord_Name =. nullTerm 32
return Chord{..}
data BendData32 = BendData32
{ bd32_Time :: Float
, bd32_Step :: Float
, bd32_Unk3_0 :: Int16
, bd32_Unk4_0 :: Word8
, bd32_Unk5 :: Word8
} deriving (Eq, Show)
instance BinEndian BendData32 where
binEndian = do
bd32_Time <- bd32_Time =. binEndian
bd32_Step <- bd32_Step =. binEndian
bd32_Unk3_0 <- bd32_Unk3_0 =. binEndian
bd32_Unk4_0 <- bd32_Unk4_0 =. bin
bd32_Unk5 <- bd32_Unk5 =. bin
return BendData32{..}
data BendData = BendData
{ bd_BendData32 :: [BendData32]
, bd_UsedCount :: Int32
} deriving (Eq, Show)
instance BinEndian BendData where
binEndian = do
bd_BendData32 <- bd_BendData32 =. fixedArray 32 binEndian
bd_UsedCount <- bd_UsedCount =. binEndian
return BendData{..}
data ChordNotes = ChordNotes
{ cn_NoteMask :: [Word32]
, cn_BendData :: [BendData]
, cn_SlideTo :: [Int8]
, cn_SlideUnpitchTo :: [Int8]
, cn_Vibrato :: [Int16]
} deriving (Eq, Show)
instance BinEndian ChordNotes where
binEndian = do
cn_NoteMask <- cn_NoteMask =. fixedArray 6 binEndian
cn_BendData <- cn_BendData =. fixedArray 6 binEndian
cn_SlideTo <- cn_SlideTo =. fixedArray 6 bin
cn_SlideUnpitchTo <- cn_SlideUnpitchTo =. fixedArray 6 bin
cn_Vibrato <- cn_Vibrato =. fixedArray 6 binEndian
return ChordNotes{..}
data Vocal = Vocal
{ vocal_Time :: Float
, vocal_Note :: Int32
, vocal_Length :: Float
, vocal_Lyric :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Vocal where
binEndian = do
vocal_Time <- vocal_Time =. binEndian
vocal_Note <- vocal_Note =. binEndian
vocal_Length <- vocal_Length =. binEndian
vocal_Lyric <- vocal_Lyric =. nullTerm 48
return Vocal{..}
writePosn :: String -> CodecFor Get PutM a ()
writePosn s = Codec
{ codecIn = do
n <- bytesRead
trace ("[" ++ s ++ "] " ++ show n) $ return ()
, codecOut = \_ -> return ()
}
data SymbolHeader = SymbolHeader
{ sh_Unk1 :: Int32
, sh_Unk2 :: Int32
, sh_Unk3 :: Int32
, sh_Unk4 :: Int32
, sh_Unk5 :: Int32
, sh_Unk6 :: Int32
, sh_Unk7 :: Int32
, sh_Unk8 :: Int32
} deriving (Eq, Show)
instance BinEndian SymbolHeader where
binEndian = do
sh_Unk1 <- sh_Unk1 =. binEndian
sh_Unk2 <- sh_Unk2 =. binEndian
sh_Unk3 <- sh_Unk3 =. binEndian
sh_Unk4 <- sh_Unk4 =. binEndian
sh_Unk5 <- sh_Unk5 =. binEndian
sh_Unk6 <- sh_Unk6 =. binEndian
sh_Unk7 <- sh_Unk7 =. binEndian
sh_Unk8 <- sh_Unk8 =. binEndian
return SymbolHeader{..}
data SymbolTexture = SymbolTexture
{ st_Font :: B.ByteString
, st_FontpathLength :: Int32
, st_Unk1_0 :: Int32
, st_Width :: Int32
, st_Height :: Int32
} deriving (Eq, Show)
instance BinEndian SymbolTexture where
binEndian = do
st_Font <- st_Font =. nullTerm 128
st_FontpathLength <- st_FontpathLength =. binEndian
st_Unk1_0 <- st_Unk1_0 =. binEndian
st_Width <- st_Width =. binEndian
st_Height <- st_Height =. binEndian
return SymbolTexture{..}
data Rect = Rect
{ rect_yMin :: Float
, rect_xMin :: Float
, rect_yMax :: Float
, rect_xMax :: Float
} deriving (Eq, Show)
instance BinEndian Rect where
binEndian = do
rect_yMin <- rect_yMin =. binEndian
rect_xMin <- rect_xMin =. binEndian
rect_yMax <- rect_yMax =. binEndian
rect_xMax <- rect_xMax =. binEndian
return Rect{..}
data SymbolDefinition = SymbolDefinition
{ sd_Text :: B.ByteString
, sd_Rect_Outer :: Rect
, sd_Rect_Inner :: Rect
} deriving (Eq, Show)
instance BinEndian SymbolDefinition where
binEndian = do
sd_Text <- sd_Text =. nullTerm 12
sd_Rect_Outer <- sd_Rect_Outer =. binEndian
sd_Rect_Inner <- sd_Rect_Inner =. binEndian
return SymbolDefinition{..}
data PhraseIteration = PhraseIteration
{ pi_PhraseId :: Int32
, pi_StartTime :: Float
, pi_NextPhraseTime :: Float
, pi_Difficulty :: [Int32]
} deriving (Eq, Show)
instance BinEndian PhraseIteration where
binEndian = do
pi_PhraseId <- pi_PhraseId =. binEndian
pi_StartTime <- pi_StartTime =. binEndian
pi_NextPhraseTime <- pi_NextPhraseTime =. binEndian
pi_Difficulty <- pi_Difficulty =. fixedArray 3 binEndian
return PhraseIteration{..}
data PhraseExtraInfo = PhraseExtraInfo
{ pei_PhraseId :: Int32
, pei_Difficulty :: Int32
, pei_Empty :: Int32
, pei_LevelJump :: Word8
, pei_Redundant :: Int16
, pei_Padding :: Word8
} deriving (Eq, Show)
instance BinEndian PhraseExtraInfo where
binEndian = do
pei_PhraseId <- pei_PhraseId =. binEndian
pei_Difficulty <- pei_Difficulty =. binEndian
pei_Empty <- pei_Empty =. binEndian
pei_LevelJump <- pei_LevelJump =. bin
pei_Redundant <- pei_Redundant =. binEndian
pei_Padding <- pei_Padding =. bin
return PhraseExtraInfo{..}
data NLinkedDifficulty = NLinkedDifficulty
{ nld_LevelBreak :: Int32
, nld_Phrase :: [Int32]
} deriving (Eq, Show)
instance BinEndian NLinkedDifficulty where
binEndian = do
nld_LevelBreak <- nld_LevelBreak =. binEndian
nld_Phrase <- nld_Phrase =. lenArray binEndian
return NLinkedDifficulty{..}
data TimeName = TimeName
{ tn_Time :: Float
, tn_Name :: B.ByteString
} deriving (Eq, Show)
instance BinEndian TimeName where
binEndian = do
tn_Time <- tn_Time =. binEndian
tn_Name <- tn_Name =. nullTerm 256
return TimeName{..}
data TimeID = TimeID
{ tid_Time :: Float
, tid_ID :: Int32
} deriving (Eq, Show)
instance BinEndian TimeID where
binEndian = do
tid_Time <- tid_Time =. binEndian
tid_ID <- tid_ID =. binEndian
return TimeID{..}
data Section = Section
{ sect_Name :: B.ByteString
, sect_Number :: Int32
, sect_StartTime :: Float
, sect_EndTime :: Float
, sect_StartPhraseIterationId :: Int32
, sect_EndPhraseIterationId :: Int32
, sect_StringMask :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Section where
binEndian = do
sect_Name <- sect_Name =. nullTerm 32
sect_Number <- sect_Number =. binEndian
sect_StartTime <- sect_StartTime =. binEndian
sect_EndTime <- sect_EndTime =. binEndian
sect_StartPhraseIterationId <- sect_StartPhraseIterationId =. binEndian
sect_EndPhraseIterationId <- sect_EndPhraseIterationId =. binEndian
sect_StringMask <- sect_StringMask =. byteString 36
return Section{..}
data Anchor = Anchor
{ anchor_StartBeatTime :: Float
, anchor_EndBeatTime :: Float
, anchor_Unk3_FirstNoteTime :: Float
, anchor_Unk4_LastNoteTime :: Float
, anchor_FretId :: Word8
, anchor_Padding :: B.ByteString
, anchor_Width :: Int32
, anchor_PhraseIterationId :: Int32
} deriving (Eq, Show)
instance BinEndian Anchor where
binEndian = do
anchor_StartBeatTime <- anchor_StartBeatTime =. binEndian
anchor_EndBeatTime <- anchor_EndBeatTime =. binEndian
anchor_Unk3_FirstNoteTime <- anchor_Unk3_FirstNoteTime =. binEndian
anchor_Unk4_LastNoteTime <- anchor_Unk4_LastNoteTime =. binEndian
anchor_FretId <- anchor_FretId =. bin
anchor_Padding <- anchor_Padding =. byteString 3
anchor_Width <- anchor_Width =. binEndian
anchor_PhraseIterationId <- anchor_PhraseIterationId =. binEndian
return Anchor{..}
data AnchorExtension = AnchorExtension
{ ae_BeatTime :: Float
, ae_FretId :: Word8
, ae_Unk2_0 :: Int32
, ae_Unk3_0 :: Int16
, ae_Unk4_0 :: Word8
} deriving (Eq, Show)
instance BinEndian AnchorExtension where
binEndian = do
ae_BeatTime <- ae_BeatTime =. binEndian
ae_FretId <- ae_FretId =. bin
ae_Unk2_0 <- ae_Unk2_0 =. binEndian
ae_Unk3_0 <- ae_Unk3_0 =. binEndian
ae_Unk4_0 <- ae_Unk4_0 =. bin
return AnchorExtension{..}
data Fingerprint = Fingerprint
{ fp_ChordId :: Int32
, fp_StartTime :: Float
, fp_EndTime :: Float
, fp_Unk3_FirstNoteTime :: Float
, fp_Unk4_LastNoteTime :: Float
} deriving (Eq, Show)
instance BinEndian Fingerprint where
binEndian = do
fp_ChordId <- fp_ChordId =. binEndian
fp_StartTime <- fp_StartTime =. binEndian
fp_EndTime <- fp_EndTime =. binEndian
fp_Unk3_FirstNoteTime <- fp_Unk3_FirstNoteTime =. binEndian
fp_Unk4_LastNoteTime <- fp_Unk4_LastNoteTime =. binEndian
return Fingerprint{..}
data Notes = Notes
{ notes_NoteMask :: Word32
, notes_NoteFlags :: Word32
, notes_Hash :: Word32
, notes_Time :: Float
, notes_StringIndex :: Int8
, notes_FretId :: Int8
, notes_AnchorFretId :: Word8
, notes_AnchorWidth :: Word8
, notes_ChordId :: Int32
, notes_ChordNotesId :: Int32
, notes_PhraseId :: Int32
, notes_PhraseIterationId :: Int32
, notes_FingerPrintId :: [Int16]
, notes_NextIterNote :: Int16
, notes_PrevIterNote :: Int16
, notes_ParentPrevNote :: Int16
, notes_SlideTo :: Int8
, notes_SlideUnpitchTo :: Int8
, notes_LeftHand :: Int8
, notes_Tap :: Int8
, notes_PickDirection :: Word8
, notes_Slap :: Int8
, notes_Pluck :: Int8
, notes_Vibrato :: Int16
, notes_Sustain :: Float
, notes_MaxBend :: Float
, notes_BendData :: [BendData32]
} deriving (Eq, Show)
instance BinEndian Notes where
binEndian = do
notes_NoteMask <- notes_NoteMask =. binEndian
notes_NoteFlags <- notes_NoteFlags =. binEndian
notes_Hash <- notes_Hash =. binEndian
notes_Time <- notes_Time =. binEndian
notes_StringIndex <- notes_StringIndex =. bin
notes_FretId <- notes_FretId =. bin
notes_AnchorFretId <- notes_AnchorFretId =. bin
notes_AnchorWidth <- notes_AnchorWidth =. bin
notes_ChordId <- notes_ChordId =. binEndian
notes_ChordNotesId <- notes_ChordNotesId =. binEndian
notes_PhraseId <- notes_PhraseId =. binEndian
notes_PhraseIterationId <- notes_PhraseIterationId =. binEndian
notes_FingerPrintId <- notes_FingerPrintId =. fixedArray 2 binEndian
notes_NextIterNote <- notes_NextIterNote =. binEndian
notes_PrevIterNote <- notes_PrevIterNote =. binEndian
notes_ParentPrevNote <- notes_ParentPrevNote =. binEndian
notes_SlideTo <- notes_SlideTo =. bin
notes_SlideUnpitchTo <- notes_SlideUnpitchTo =. bin
notes_LeftHand <- notes_LeftHand =. bin
notes_Tap <- notes_Tap =. bin
notes_PickDirection <- notes_PickDirection =. bin
notes_Slap <- notes_Slap =. bin
notes_Pluck <- notes_Pluck =. bin
notes_Vibrato <- notes_Vibrato =. binEndian
notes_Sustain <- notes_Sustain =. binEndian
notes_MaxBend <- notes_MaxBend =. binEndian
notes_BendData <- notes_BendData =. lenArray binEndian
return Notes{..}
data Arrangement = Arrangement -- actually <level>
{ arr_Difficulty :: Int32
, arr_Anchors :: [Anchor]
, arr_AnchorExtensions :: [AnchorExtension]
, arr_Fingerprints1 :: [Fingerprint]
, arr_Fingerprints2 :: [Fingerprint]
, arr_Notes :: [Notes]
, arr_AverageNotesPerIteration :: [Float]
, arr_NotesInIteration1 :: [Int32]
, arr_NotesInIteration2 :: [Int32]
} deriving (Eq, Show)
instance BinEndian Arrangement where
binEndian = do
arr_Difficulty <- arr_Difficulty =. binEndian
arr_Anchors <- arr_Anchors =. lenArray binEndian
arr_AnchorExtensions <- arr_AnchorExtensions =. lenArray binEndian
arr_Fingerprints1 <- arr_Fingerprints1 =. lenArray binEndian
arr_Fingerprints2 <- arr_Fingerprints2 =. lenArray binEndian
arr_Notes <- arr_Notes =. lenArray binEndian
arr_AverageNotesPerIteration <- arr_AverageNotesPerIteration =. lenArray binEndian
arr_NotesInIteration1 <- arr_NotesInIteration1 =. lenArray binEndian
arr_NotesInIteration2 <- arr_NotesInIteration2 =. lenArray binEndian
return Arrangement{..}
data Metadata = Metadata
{ meta_MaxScore :: Double
, meta_MaxNotesAndChords :: Double
, meta_MaxNotesAndChords_Real :: Double
, meta_PointsPerNote :: Double
, meta_FirstBeatLength :: Float
, meta_StartTime :: Float
, meta_CapoFretId :: Int8
= new ] ;
, meta_Part :: Int16
, meta_SongLength :: Float
, meta_Tuning :: [Int16]
, meta_Unk11_FirstNoteTime :: Float
, meta_Unk12_FirstNoteTime :: Float
, meta_MaxDifficulty :: Int32
} deriving (Eq, Show)
instance BinEndian Metadata where
binEndian = do
meta_MaxScore <- meta_MaxScore =. binEndian
meta_MaxNotesAndChords <- meta_MaxNotesAndChords =. binEndian
meta_MaxNotesAndChords_Real <- meta_MaxNotesAndChords_Real =. binEndian
meta_PointsPerNote <- meta_PointsPerNote =. binEndian
meta_FirstBeatLength <- meta_FirstBeatLength =. binEndian
meta_StartTime <- meta_StartTime =. binEndian
meta_CapoFretId <- meta_CapoFretId =. bin
meta_LastConversionDateTime <- meta_LastConversionDateTime =. nullTerm 32
meta_Part <- meta_Part =. binEndian
meta_SongLength <- meta_SongLength =. binEndian
meta_Tuning <- meta_Tuning =. lenArray binEndian
meta_Unk11_FirstNoteTime <- meta_Unk11_FirstNoteTime =. binEndian
meta_Unk12_FirstNoteTime <- meta_Unk12_FirstNoteTime =. binEndian
meta_MaxDifficulty <- meta_MaxDifficulty =. binEndian
return Metadata{..}
data SNG2014 = SNG2014
{ sng_BPMs :: [BPM]
, sng_Phrases :: [Phrase]
, sng_Chords :: [Chord]
, sng_ChordNotes :: [ChordNotes]
, sng_Vocals :: [Vocal]
, sng_SymbolHeaders :: [SymbolHeader] -- only in vocals files
, sng_SymbolTextures :: [SymbolTexture] -- only in vocals files
, sng_SymbolDefinitions :: [SymbolDefinition] -- only in vocals files
, sng_PhraseIterations :: [PhraseIteration]
, sng_PhraseExtraInfo :: [PhraseExtraInfo]
, sng_NLinkedDifficulty :: [NLinkedDifficulty]
, sng_Actions :: [TimeName]
, sng_Events :: [TimeName]
, sng_Tones :: [TimeID]
, sng_DNAs :: [TimeID]
, sng_Sections :: [Section]
, sng_Arrangements :: [Arrangement]
, sng_Metadata :: Metadata
} deriving (Eq, Show)
instance BinEndian SNG2014 where
binEndian = do
sng_BPMs <- sng_BPMs =. lenArray binEndian
sng_Phrases <- sng_Phrases =. lenArray binEndian
sng_Chords <- sng_Chords =. lenArray binEndian
sng_ChordNotes <- sng_ChordNotes =. lenArray binEndian
sng_Vocals <- sng_Vocals =. lenArray binEndian
let onlyVox p = if null sng_Vocals then return [] else p
sng_SymbolHeaders <- onlyVox $ sng_SymbolHeaders =. lenArray binEndian
sng_SymbolTextures <- onlyVox $ sng_SymbolTextures =. lenArray binEndian
sng_SymbolDefinitions <- onlyVox $ sng_SymbolDefinitions =. lenArray binEndian
sng_PhraseIterations <- sng_PhraseIterations =. lenArray binEndian
sng_PhraseExtraInfo <- sng_PhraseExtraInfo =. lenArray binEndian
sng_NLinkedDifficulty <- sng_NLinkedDifficulty =. lenArray binEndian
sng_Actions <- sng_Actions =. lenArray binEndian
sng_Events <- sng_Events =. lenArray binEndian
sng_Tones <- sng_Tones =. lenArray binEndian
sng_DNAs <- sng_DNAs =. lenArray binEndian
sng_Sections <- sng_Sections =. lenArray binEndian
sng_Arrangements <- sng_Arrangements =. lenArray binEndian
sng_Metadata <- sng_Metadata =. binEndian
return SNG2014{..}
loadSNG :: (MonadFail m) => GamePlatform -> B.ByteString -> m SNG2014
loadSNG plat bs = do
bs' <- unpackSNG plat bs
let ?endian = case plat of
PC -> LittleEndian
Mac -> LittleEndian
Xbox360 -> BigEndian
PS3 -> BigEndian
runGetM (codecIn binEndian) bs'
| null | https://raw.githubusercontent.com/mtolly/onyxite-customs/0c8acd6248fe92ea0d994b18b551973816adf85b/haskell/packages/onyx-lib/src/Onyx/Rocksmith/Sng2014.hs | haskell | # LANGUAGE ImplicitParams #
actually <ebeat>
actually <level>
only in vocals files
only in vocals files
only in vocals files | # LANGUAGE RecordWildCards #
module Onyx.Rocksmith.Sng2014 where
import Control.Monad
import qualified Data.ByteString as B
import Debug.Trace
import Onyx.Codec.Binary
import Onyx.Rocksmith.Crypt
import Onyx.Xbox.STFS (runGetM)
lenArray :: (?endian :: ByteOrder) => BinaryCodec a -> BinaryCodec [a]
lenArray c = Codec
{ codecIn = do
len <- codecIn codecLen
replicateM (fromIntegral len) $ codecIn c
, codecOut = fmapArg $ \xs -> do
void $ codecOut codecLen $ fromIntegral $ length xs
forM_ xs $ codecOut c
} where codecLen = binEndian :: BinaryCodec Word32
nullTerm :: Int -> BinaryCodec B.ByteString
nullTerm n = Codec
{ codecIn = B.takeWhile (/= 0) <$> getByteString n
, codecOut = fmapArg $ \b -> putByteString $ case compare n $ B.length b of
EQ -> b
LT -> B.take n b
GT -> b <> B.replicate (B.length b - n) 0
}
{ bpm_Time :: Float
, bpm_Measure :: Int16
, bpm_Beat :: Int16
, bpm_PhraseIteration :: Int32
, bpm_Mask :: Int32
} deriving (Eq, Show)
instance BinEndian BPM where
binEndian = do
bpm_Time <- bpm_Time =. binEndian
bpm_Measure <- bpm_Measure =. binEndian
bpm_Beat <- bpm_Beat =. binEndian
bpm_PhraseIteration <- bpm_PhraseIteration =. binEndian
bpm_Mask <- bpm_Mask =. binEndian
return BPM{..}
data Phrase = Phrase
{ phrase_Solo :: Word8
, phrase_Disparity :: Word8
, phrase_Ignore :: Word8
, phrase_Padding :: Word8
, phrase_MaxDifficulty :: Int32
, phrase_PhraseIterationLinks :: Int32
, phrase_Name :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Phrase where
binEndian = do
phrase_Solo <- phrase_Solo =. bin
phrase_Disparity <- phrase_Disparity =. bin
phrase_Ignore <- phrase_Ignore =. bin
phrase_Padding <- phrase_Padding =. bin
phrase_MaxDifficulty <- phrase_MaxDifficulty =. binEndian
phrase_PhraseIterationLinks <- phrase_PhraseIterationLinks =. binEndian
phrase_Name <- phrase_Name =. nullTerm 32
return Phrase{..}
actually < chordTemplate >
{ chord_Mask :: Word32
, chord_Frets :: [Int8]
, chord_Fingers :: [Int8]
, chord_Notes :: [Int32]
, chord_Name :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Chord where
binEndian = do
chord_Mask <- chord_Mask =. binEndian
chord_Frets <- chord_Frets =. fixedArray 6 bin
chord_Fingers <- chord_Fingers =. fixedArray 6 bin
chord_Notes <- chord_Notes =. fixedArray 6 binEndian
chord_Name <- chord_Name =. nullTerm 32
return Chord{..}
data BendData32 = BendData32
{ bd32_Time :: Float
, bd32_Step :: Float
, bd32_Unk3_0 :: Int16
, bd32_Unk4_0 :: Word8
, bd32_Unk5 :: Word8
} deriving (Eq, Show)
instance BinEndian BendData32 where
binEndian = do
bd32_Time <- bd32_Time =. binEndian
bd32_Step <- bd32_Step =. binEndian
bd32_Unk3_0 <- bd32_Unk3_0 =. binEndian
bd32_Unk4_0 <- bd32_Unk4_0 =. bin
bd32_Unk5 <- bd32_Unk5 =. bin
return BendData32{..}
data BendData = BendData
{ bd_BendData32 :: [BendData32]
, bd_UsedCount :: Int32
} deriving (Eq, Show)
instance BinEndian BendData where
binEndian = do
bd_BendData32 <- bd_BendData32 =. fixedArray 32 binEndian
bd_UsedCount <- bd_UsedCount =. binEndian
return BendData{..}
data ChordNotes = ChordNotes
{ cn_NoteMask :: [Word32]
, cn_BendData :: [BendData]
, cn_SlideTo :: [Int8]
, cn_SlideUnpitchTo :: [Int8]
, cn_Vibrato :: [Int16]
} deriving (Eq, Show)
instance BinEndian ChordNotes where
binEndian = do
cn_NoteMask <- cn_NoteMask =. fixedArray 6 binEndian
cn_BendData <- cn_BendData =. fixedArray 6 binEndian
cn_SlideTo <- cn_SlideTo =. fixedArray 6 bin
cn_SlideUnpitchTo <- cn_SlideUnpitchTo =. fixedArray 6 bin
cn_Vibrato <- cn_Vibrato =. fixedArray 6 binEndian
return ChordNotes{..}
data Vocal = Vocal
{ vocal_Time :: Float
, vocal_Note :: Int32
, vocal_Length :: Float
, vocal_Lyric :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Vocal where
binEndian = do
vocal_Time <- vocal_Time =. binEndian
vocal_Note <- vocal_Note =. binEndian
vocal_Length <- vocal_Length =. binEndian
vocal_Lyric <- vocal_Lyric =. nullTerm 48
return Vocal{..}
writePosn :: String -> CodecFor Get PutM a ()
writePosn s = Codec
{ codecIn = do
n <- bytesRead
trace ("[" ++ s ++ "] " ++ show n) $ return ()
, codecOut = \_ -> return ()
}
data SymbolHeader = SymbolHeader
{ sh_Unk1 :: Int32
, sh_Unk2 :: Int32
, sh_Unk3 :: Int32
, sh_Unk4 :: Int32
, sh_Unk5 :: Int32
, sh_Unk6 :: Int32
, sh_Unk7 :: Int32
, sh_Unk8 :: Int32
} deriving (Eq, Show)
instance BinEndian SymbolHeader where
binEndian = do
sh_Unk1 <- sh_Unk1 =. binEndian
sh_Unk2 <- sh_Unk2 =. binEndian
sh_Unk3 <- sh_Unk3 =. binEndian
sh_Unk4 <- sh_Unk4 =. binEndian
sh_Unk5 <- sh_Unk5 =. binEndian
sh_Unk6 <- sh_Unk6 =. binEndian
sh_Unk7 <- sh_Unk7 =. binEndian
sh_Unk8 <- sh_Unk8 =. binEndian
return SymbolHeader{..}
data SymbolTexture = SymbolTexture
{ st_Font :: B.ByteString
, st_FontpathLength :: Int32
, st_Unk1_0 :: Int32
, st_Width :: Int32
, st_Height :: Int32
} deriving (Eq, Show)
instance BinEndian SymbolTexture where
binEndian = do
st_Font <- st_Font =. nullTerm 128
st_FontpathLength <- st_FontpathLength =. binEndian
st_Unk1_0 <- st_Unk1_0 =. binEndian
st_Width <- st_Width =. binEndian
st_Height <- st_Height =. binEndian
return SymbolTexture{..}
data Rect = Rect
{ rect_yMin :: Float
, rect_xMin :: Float
, rect_yMax :: Float
, rect_xMax :: Float
} deriving (Eq, Show)
instance BinEndian Rect where
binEndian = do
rect_yMin <- rect_yMin =. binEndian
rect_xMin <- rect_xMin =. binEndian
rect_yMax <- rect_yMax =. binEndian
rect_xMax <- rect_xMax =. binEndian
return Rect{..}
data SymbolDefinition = SymbolDefinition
{ sd_Text :: B.ByteString
, sd_Rect_Outer :: Rect
, sd_Rect_Inner :: Rect
} deriving (Eq, Show)
instance BinEndian SymbolDefinition where
binEndian = do
sd_Text <- sd_Text =. nullTerm 12
sd_Rect_Outer <- sd_Rect_Outer =. binEndian
sd_Rect_Inner <- sd_Rect_Inner =. binEndian
return SymbolDefinition{..}
data PhraseIteration = PhraseIteration
{ pi_PhraseId :: Int32
, pi_StartTime :: Float
, pi_NextPhraseTime :: Float
, pi_Difficulty :: [Int32]
} deriving (Eq, Show)
instance BinEndian PhraseIteration where
binEndian = do
pi_PhraseId <- pi_PhraseId =. binEndian
pi_StartTime <- pi_StartTime =. binEndian
pi_NextPhraseTime <- pi_NextPhraseTime =. binEndian
pi_Difficulty <- pi_Difficulty =. fixedArray 3 binEndian
return PhraseIteration{..}
data PhraseExtraInfo = PhraseExtraInfo
{ pei_PhraseId :: Int32
, pei_Difficulty :: Int32
, pei_Empty :: Int32
, pei_LevelJump :: Word8
, pei_Redundant :: Int16
, pei_Padding :: Word8
} deriving (Eq, Show)
instance BinEndian PhraseExtraInfo where
binEndian = do
pei_PhraseId <- pei_PhraseId =. binEndian
pei_Difficulty <- pei_Difficulty =. binEndian
pei_Empty <- pei_Empty =. binEndian
pei_LevelJump <- pei_LevelJump =. bin
pei_Redundant <- pei_Redundant =. binEndian
pei_Padding <- pei_Padding =. bin
return PhraseExtraInfo{..}
data NLinkedDifficulty = NLinkedDifficulty
{ nld_LevelBreak :: Int32
, nld_Phrase :: [Int32]
} deriving (Eq, Show)
instance BinEndian NLinkedDifficulty where
binEndian = do
nld_LevelBreak <- nld_LevelBreak =. binEndian
nld_Phrase <- nld_Phrase =. lenArray binEndian
return NLinkedDifficulty{..}
data TimeName = TimeName
{ tn_Time :: Float
, tn_Name :: B.ByteString
} deriving (Eq, Show)
instance BinEndian TimeName where
binEndian = do
tn_Time <- tn_Time =. binEndian
tn_Name <- tn_Name =. nullTerm 256
return TimeName{..}
data TimeID = TimeID
{ tid_Time :: Float
, tid_ID :: Int32
} deriving (Eq, Show)
instance BinEndian TimeID where
binEndian = do
tid_Time <- tid_Time =. binEndian
tid_ID <- tid_ID =. binEndian
return TimeID{..}
data Section = Section
{ sect_Name :: B.ByteString
, sect_Number :: Int32
, sect_StartTime :: Float
, sect_EndTime :: Float
, sect_StartPhraseIterationId :: Int32
, sect_EndPhraseIterationId :: Int32
, sect_StringMask :: B.ByteString
} deriving (Eq, Show)
instance BinEndian Section where
binEndian = do
sect_Name <- sect_Name =. nullTerm 32
sect_Number <- sect_Number =. binEndian
sect_StartTime <- sect_StartTime =. binEndian
sect_EndTime <- sect_EndTime =. binEndian
sect_StartPhraseIterationId <- sect_StartPhraseIterationId =. binEndian
sect_EndPhraseIterationId <- sect_EndPhraseIterationId =. binEndian
sect_StringMask <- sect_StringMask =. byteString 36
return Section{..}
data Anchor = Anchor
{ anchor_StartBeatTime :: Float
, anchor_EndBeatTime :: Float
, anchor_Unk3_FirstNoteTime :: Float
, anchor_Unk4_LastNoteTime :: Float
, anchor_FretId :: Word8
, anchor_Padding :: B.ByteString
, anchor_Width :: Int32
, anchor_PhraseIterationId :: Int32
} deriving (Eq, Show)
instance BinEndian Anchor where
binEndian = do
anchor_StartBeatTime <- anchor_StartBeatTime =. binEndian
anchor_EndBeatTime <- anchor_EndBeatTime =. binEndian
anchor_Unk3_FirstNoteTime <- anchor_Unk3_FirstNoteTime =. binEndian
anchor_Unk4_LastNoteTime <- anchor_Unk4_LastNoteTime =. binEndian
anchor_FretId <- anchor_FretId =. bin
anchor_Padding <- anchor_Padding =. byteString 3
anchor_Width <- anchor_Width =. binEndian
anchor_PhraseIterationId <- anchor_PhraseIterationId =. binEndian
return Anchor{..}
data AnchorExtension = AnchorExtension
{ ae_BeatTime :: Float
, ae_FretId :: Word8
, ae_Unk2_0 :: Int32
, ae_Unk3_0 :: Int16
, ae_Unk4_0 :: Word8
} deriving (Eq, Show)
instance BinEndian AnchorExtension where
binEndian = do
ae_BeatTime <- ae_BeatTime =. binEndian
ae_FretId <- ae_FretId =. bin
ae_Unk2_0 <- ae_Unk2_0 =. binEndian
ae_Unk3_0 <- ae_Unk3_0 =. binEndian
ae_Unk4_0 <- ae_Unk4_0 =. bin
return AnchorExtension{..}
data Fingerprint = Fingerprint
{ fp_ChordId :: Int32
, fp_StartTime :: Float
, fp_EndTime :: Float
, fp_Unk3_FirstNoteTime :: Float
, fp_Unk4_LastNoteTime :: Float
} deriving (Eq, Show)
instance BinEndian Fingerprint where
binEndian = do
fp_ChordId <- fp_ChordId =. binEndian
fp_StartTime <- fp_StartTime =. binEndian
fp_EndTime <- fp_EndTime =. binEndian
fp_Unk3_FirstNoteTime <- fp_Unk3_FirstNoteTime =. binEndian
fp_Unk4_LastNoteTime <- fp_Unk4_LastNoteTime =. binEndian
return Fingerprint{..}
data Notes = Notes
{ notes_NoteMask :: Word32
, notes_NoteFlags :: Word32
, notes_Hash :: Word32
, notes_Time :: Float
, notes_StringIndex :: Int8
, notes_FretId :: Int8
, notes_AnchorFretId :: Word8
, notes_AnchorWidth :: Word8
, notes_ChordId :: Int32
, notes_ChordNotesId :: Int32
, notes_PhraseId :: Int32
, notes_PhraseIterationId :: Int32
, notes_FingerPrintId :: [Int16]
, notes_NextIterNote :: Int16
, notes_PrevIterNote :: Int16
, notes_ParentPrevNote :: Int16
, notes_SlideTo :: Int8
, notes_SlideUnpitchTo :: Int8
, notes_LeftHand :: Int8
, notes_Tap :: Int8
, notes_PickDirection :: Word8
, notes_Slap :: Int8
, notes_Pluck :: Int8
, notes_Vibrato :: Int16
, notes_Sustain :: Float
, notes_MaxBend :: Float
, notes_BendData :: [BendData32]
} deriving (Eq, Show)
instance BinEndian Notes where
binEndian = do
notes_NoteMask <- notes_NoteMask =. binEndian
notes_NoteFlags <- notes_NoteFlags =. binEndian
notes_Hash <- notes_Hash =. binEndian
notes_Time <- notes_Time =. binEndian
notes_StringIndex <- notes_StringIndex =. bin
notes_FretId <- notes_FretId =. bin
notes_AnchorFretId <- notes_AnchorFretId =. bin
notes_AnchorWidth <- notes_AnchorWidth =. bin
notes_ChordId <- notes_ChordId =. binEndian
notes_ChordNotesId <- notes_ChordNotesId =. binEndian
notes_PhraseId <- notes_PhraseId =. binEndian
notes_PhraseIterationId <- notes_PhraseIterationId =. binEndian
notes_FingerPrintId <- notes_FingerPrintId =. fixedArray 2 binEndian
notes_NextIterNote <- notes_NextIterNote =. binEndian
notes_PrevIterNote <- notes_PrevIterNote =. binEndian
notes_ParentPrevNote <- notes_ParentPrevNote =. binEndian
notes_SlideTo <- notes_SlideTo =. bin
notes_SlideUnpitchTo <- notes_SlideUnpitchTo =. bin
notes_LeftHand <- notes_LeftHand =. bin
notes_Tap <- notes_Tap =. bin
notes_PickDirection <- notes_PickDirection =. bin
notes_Slap <- notes_Slap =. bin
notes_Pluck <- notes_Pluck =. bin
notes_Vibrato <- notes_Vibrato =. binEndian
notes_Sustain <- notes_Sustain =. binEndian
notes_MaxBend <- notes_MaxBend =. binEndian
notes_BendData <- notes_BendData =. lenArray binEndian
return Notes{..}
{ arr_Difficulty :: Int32
, arr_Anchors :: [Anchor]
, arr_AnchorExtensions :: [AnchorExtension]
, arr_Fingerprints1 :: [Fingerprint]
, arr_Fingerprints2 :: [Fingerprint]
, arr_Notes :: [Notes]
, arr_AverageNotesPerIteration :: [Float]
, arr_NotesInIteration1 :: [Int32]
, arr_NotesInIteration2 :: [Int32]
} deriving (Eq, Show)
instance BinEndian Arrangement where
binEndian = do
arr_Difficulty <- arr_Difficulty =. binEndian
arr_Anchors <- arr_Anchors =. lenArray binEndian
arr_AnchorExtensions <- arr_AnchorExtensions =. lenArray binEndian
arr_Fingerprints1 <- arr_Fingerprints1 =. lenArray binEndian
arr_Fingerprints2 <- arr_Fingerprints2 =. lenArray binEndian
arr_Notes <- arr_Notes =. lenArray binEndian
arr_AverageNotesPerIteration <- arr_AverageNotesPerIteration =. lenArray binEndian
arr_NotesInIteration1 <- arr_NotesInIteration1 =. lenArray binEndian
arr_NotesInIteration2 <- arr_NotesInIteration2 =. lenArray binEndian
return Arrangement{..}
data Metadata = Metadata
{ meta_MaxScore :: Double
, meta_MaxNotesAndChords :: Double
, meta_MaxNotesAndChords_Real :: Double
, meta_PointsPerNote :: Double
, meta_FirstBeatLength :: Float
, meta_StartTime :: Float
, meta_CapoFretId :: Int8
= new ] ;
, meta_Part :: Int16
, meta_SongLength :: Float
, meta_Tuning :: [Int16]
, meta_Unk11_FirstNoteTime :: Float
, meta_Unk12_FirstNoteTime :: Float
, meta_MaxDifficulty :: Int32
} deriving (Eq, Show)
instance BinEndian Metadata where
binEndian = do
meta_MaxScore <- meta_MaxScore =. binEndian
meta_MaxNotesAndChords <- meta_MaxNotesAndChords =. binEndian
meta_MaxNotesAndChords_Real <- meta_MaxNotesAndChords_Real =. binEndian
meta_PointsPerNote <- meta_PointsPerNote =. binEndian
meta_FirstBeatLength <- meta_FirstBeatLength =. binEndian
meta_StartTime <- meta_StartTime =. binEndian
meta_CapoFretId <- meta_CapoFretId =. bin
meta_LastConversionDateTime <- meta_LastConversionDateTime =. nullTerm 32
meta_Part <- meta_Part =. binEndian
meta_SongLength <- meta_SongLength =. binEndian
meta_Tuning <- meta_Tuning =. lenArray binEndian
meta_Unk11_FirstNoteTime <- meta_Unk11_FirstNoteTime =. binEndian
meta_Unk12_FirstNoteTime <- meta_Unk12_FirstNoteTime =. binEndian
meta_MaxDifficulty <- meta_MaxDifficulty =. binEndian
return Metadata{..}
data SNG2014 = SNG2014
{ sng_BPMs :: [BPM]
, sng_Phrases :: [Phrase]
, sng_Chords :: [Chord]
, sng_ChordNotes :: [ChordNotes]
, sng_Vocals :: [Vocal]
, sng_PhraseIterations :: [PhraseIteration]
, sng_PhraseExtraInfo :: [PhraseExtraInfo]
, sng_NLinkedDifficulty :: [NLinkedDifficulty]
, sng_Actions :: [TimeName]
, sng_Events :: [TimeName]
, sng_Tones :: [TimeID]
, sng_DNAs :: [TimeID]
, sng_Sections :: [Section]
, sng_Arrangements :: [Arrangement]
, sng_Metadata :: Metadata
} deriving (Eq, Show)
instance BinEndian SNG2014 where
binEndian = do
sng_BPMs <- sng_BPMs =. lenArray binEndian
sng_Phrases <- sng_Phrases =. lenArray binEndian
sng_Chords <- sng_Chords =. lenArray binEndian
sng_ChordNotes <- sng_ChordNotes =. lenArray binEndian
sng_Vocals <- sng_Vocals =. lenArray binEndian
let onlyVox p = if null sng_Vocals then return [] else p
sng_SymbolHeaders <- onlyVox $ sng_SymbolHeaders =. lenArray binEndian
sng_SymbolTextures <- onlyVox $ sng_SymbolTextures =. lenArray binEndian
sng_SymbolDefinitions <- onlyVox $ sng_SymbolDefinitions =. lenArray binEndian
sng_PhraseIterations <- sng_PhraseIterations =. lenArray binEndian
sng_PhraseExtraInfo <- sng_PhraseExtraInfo =. lenArray binEndian
sng_NLinkedDifficulty <- sng_NLinkedDifficulty =. lenArray binEndian
sng_Actions <- sng_Actions =. lenArray binEndian
sng_Events <- sng_Events =. lenArray binEndian
sng_Tones <- sng_Tones =. lenArray binEndian
sng_DNAs <- sng_DNAs =. lenArray binEndian
sng_Sections <- sng_Sections =. lenArray binEndian
sng_Arrangements <- sng_Arrangements =. lenArray binEndian
sng_Metadata <- sng_Metadata =. binEndian
return SNG2014{..}
loadSNG :: (MonadFail m) => GamePlatform -> B.ByteString -> m SNG2014
loadSNG plat bs = do
bs' <- unpackSNG plat bs
let ?endian = case plat of
PC -> LittleEndian
Mac -> LittleEndian
Xbox360 -> BigEndian
PS3 -> BigEndian
runGetM (codecIn binEndian) bs'
|
060b13c6d645a5b7b886d6d9cbddd26ffcf5e5d02184cb170bd2ecfb2c2ef1f4 | HealthSamurai/stresty | core.clj | (ns stresty.core
(:require [stresty.server.core :as server])
(:gen-class))
(set! *warn-on-reflection* true)
(defn -main [& args]
(let [{err :error} (stresty.server.core/main args)]
(if err
(System/exit 1)
(System/exit 0))))
| null | https://raw.githubusercontent.com/HealthSamurai/stresty/1fd356bc7328735d56741bd6586b1ad0671fbb9a/src/stresty/core.clj | clojure | (ns stresty.core
(:require [stresty.server.core :as server])
(:gen-class))
(set! *warn-on-reflection* true)
(defn -main [& args]
(let [{err :error} (stresty.server.core/main args)]
(if err
(System/exit 1)
(System/exit 0))))
|
|
a69b3fbe87b42d8825e9df8b79988213d6b90cc8e667849d8b779827df94feb7 | airbus-seclab/bincat | lowspeak.ml |
C2Newspea : compiles C code into Newspeak . Newspeak is a minimal language
well - suited for static analysis .
Copyright ( C ) 2007 - 2022 , , ,
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
EADS Innovation Works - SE / CS
12 , rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email :
email :
EADS Innovation Works - SE / IS
12 , rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email :
EADS Innovation Works - SE / IS
12 , rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email :
C2Newspea: compiles C code into Newspeak. Newspeak is a minimal language
well-suited for static analysis.
Copyright (C) 2007-2022 Charles Hymans, Olivier Levillain, Sarah Zennou,
Etienne Millon
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Charles Hymans
EADS Innovation Works - SE/CS
12, rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email:
Olivier Levillain
email:
Sarah Zennou
EADS Innovation Works - SE/IS
12, rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email:
Etienne Millon
EADS Innovation Works - SE/IS
12, rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email:
*)
module N = Newspeak
(*-------*)
(* Types *)
(*-------*)
type t = {
globals: N.globals;
init: blk;
fundecs: (N.fid, fundec) Hashtbl.t;
ptr_sz: N.size_t;
src_lang: N.src_lang;
abi: N.abi_t;
}
and fundec = {
position: Newspeak.location;
ftyp: N.ftyp;
body: blk;
}
and assertion = spec_token list
and spec_token =
| SymbolToken of char
| IdentToken of string
| LvalToken of (lval * N.typ)
| CstToken of N.cst
and stmtkind =
Set of (lval * exp * N.scalar_t)
| Copy of (lval * lval * N.size_t)
| Guard of exp
| Decl of (string * N.typ * blk)
| Select of (blk * blk)
| InfLoop of blk
| DoWith of (blk * N.lbl)
| Goto of N.lbl
| Call of funexp
| UserSpec of assertion
and stmt = stmtkind * N.location
and blk = stmt list
and funexp =
FunId of N.fid
| FunDeref of (exp * N.ftyp)
and lval =
Local of N.vid
| Global of string
| Deref of (exp * N.size_t)
| Shift of (lval * exp)
and exp =
Const of N.cst
| Lval of (lval * N.scalar_t)
| AddrOf of lval
| AddrOfFun of (N.fid * N.ftyp)
| UnOp of (N.unop * exp)
| BinOp of (N.binop * exp * exp)
let exp_of_int x = Const (N.CInt (N.Nat.of_int x))
(***************************************************)
module StringMap =
Map.Make (struct type t = string let compare = Stdlib.compare end)
let rec seq sep f l =
match l with
| [] -> ""
| [e] -> f e
| e::r -> (f e)^sep^(seq sep f r)
(* Types *)
let string_of_size_t = string_of_int
let string_of_sign_t sg =
match sg with
N.Unsigned -> "u"
| N.Signed -> ""
let string_of_scalar s =
match s with
N.Int (sg, sz) -> (string_of_sign_t sg)^"int"^(string_of_size_t sz)
| N.Float sz -> "float" ^ (string_of_size_t sz)
| N.Ptr -> "ptr"
| N.FunPtr -> "fptr"
let rec string_of_typ t =
match t with
N.Scalar s -> string_of_scalar s
| N.Array (t, sz) -> (string_of_typ t)^"["^(string_of_size_t sz)^"]"
| N.Region (lst, sz) ->
let res = ref "{ " in
let string_of_elt (off, t) =
res := !res^(string_of_typ t)^" "^(string_of_size_t off)^"; "
in
List.iter string_of_elt lst;
!res^"}"^(string_of_size_t sz)
let string_of_args_t args =
match args with
hd::[] -> string_of_typ hd
| hd::tl ->
let res = ref (string_of_typ hd) in
List.iter (fun x -> res := !res^", "^(string_of_typ x)) tl;
!res
| [] -> "void"
let string_of_ret_t ret = string_of_args_t ret
let string_of_loc (fname, line, carac) =
if (fname = "")
then Npkcontext.report_error "Newspeak.string_of_loc" "unknown location";
if (line < 0) || (carac < 0) then fname
else (fname^":"^(string_of_int line)^"#"^(string_of_int carac))
(* Expressions *)
let string_of_cst c =
match c with
N.CInt c -> N.Nat.to_string c
| N.CFloat (_, s) -> s
| N.Nil -> "nil"
let string_of_bounds (l, u) = "["^(N.Nat.to_string l)^","^(N.Nat.to_string u)^"]"
let string_of_unop op =
match op with
N.Belongs r -> "belongs"^(string_of_bounds r)
| N.Coerce r -> "coerce"^(string_of_bounds r)
| N.Focus sz -> "focus"^(string_of_size_t sz)
| N.Cast (typ, typ') ->
"("^(string_of_scalar typ')^" <= "^(string_of_scalar typ)^")"
| N.Not -> "!"
| N.BNot _ -> "~"
| N.PtrToInt i -> "("^(string_of_scalar (N.Int i))^")"
| N.IntToPtr _ -> "(ptr)"
let string_of_binop op =
match op with
| N.Gt _ -> ">"
| N.Eq t -> "==_"^(string_of_scalar t)
| N.PlusI -> "+"
| N.MinusI -> "-"
| N.MultI -> "*"
| N.Mod -> "%"
| N.DivI -> "/"
| N.PlusF _ -> "+."
| N.MinusF _ -> "-."
| N.MultF _ -> "*."
| N.DivF _ -> "/."
| N.BAnd _ -> "&"
| N.BOr _ -> "|"
| N.BXor _ -> "^"
| N.Shiftlt -> "<<"
| N.Shiftrt -> ">>"
| N.PlusPI -> "+"
| N.MinusPP -> "-"
let rec string_of_lval lv =
match lv with
Local vid -> (string_of_int vid) ^ "-"
| Global name -> name
| Deref (e, sz) -> "["^(string_of_exp e)^"]"^(string_of_size_t sz)
| Shift (lv, sh) -> (string_of_lval lv)^" + "^(string_of_exp sh)
and string_of_exp e =
match e with
Const c -> string_of_cst c
| Lval (lv, t) -> (string_of_lval lv)^"_"^(string_of_scalar t)
| AddrOf lv -> "&("^(string_of_lval lv)^")"
| AddrOfFun (fid, ft) -> "&_{"^(N.string_of_ftyp ft)^"}("^fid^")"
| BinOp (op, e1, e2) ->
"("^(string_of_exp e1)^" "^(string_of_binop op)^
" "^(string_of_exp e2)^")"
| UnOp (op, exp) -> (string_of_unop op)^" "^(string_of_exp exp)
let string_of_funexp f =
match f with
FunId fid -> fid^"()"
| FunDeref (exp, (args_t, [ret_t])) ->
"["^(string_of_exp exp)^"]("^
(seq ", " string_of_typ args_t)^") -> "^(string_of_typ ret_t)
| FunDeref (exp, (args_t, _)) ->
"["^(string_of_exp exp)^"]("^(seq ", " string_of_typ args_t)^")"
(* Actual dump *)
let string_of_lbl l = "lbl"^(string_of_int l)
let dump_gdecl name t = print_endline (string_of_typ t^" "^name^";")
let string_of_token x =
match x with
SymbolToken x -> String.make 1 x
| IdentToken x -> x
| LvalToken (x, _) -> "'"^(string_of_lval x)^"'"
| CstToken c -> string_of_cst c
let string_of_assertion x =
let res = ref "" in
let append_token x = res := !res^(string_of_token x)^" " in
List.iter append_token x;
!res
let string_of_blk offset x =
let buf = Buffer.create 80 in
let offset = ref offset in
let incr_margin () = offset := !offset + 2 in
let decr_margin () = offset := !offset - 2 in
let dump_line str =
let margin = String.make !offset ' ' in
Buffer.add_string buf (margin^str^"\n")
in
let dump_line_at loc str =
let loc = if loc = N.unknown_loc then "" else "("^(string_of_loc loc)^")^" in
let margin = String.make !offset ' ' in
Buffer.add_string buf (margin^loc^str^"\n")
in
let rec dump_stmt only (sk, loc) =
match sk with
Set (lv, e, sc) ->
dump_line_at loc ((string_of_lval lv)^" =("^(string_of_scalar sc)^
") "^(string_of_exp e)^";")
| Guard b -> dump_line_at loc ("guard("^(string_of_exp b)^");")
| Copy (lv1, lv2, sz) ->
dump_line_at loc ((string_of_lval lv1)^" ="^(string_of_size_t sz)^
" "^(string_of_lval lv2)^";")
| Decl (x, t, body) ->
if only then begin
dump_line_at loc ((string_of_typ t)^" "^x^";");
dump_blk body
end else begin
dump_line_at loc "{";
incr_margin ();
dump_line ((string_of_typ t)^" "^x^";");
dump_blk body;
decr_margin ();
dump_line "}"
end
| DoWith (body, lbl) ->
dump_line_at loc "do {";
incr_margin ();
dump_blk body;
decr_margin ();
dump_line ("} with lbl"^(string_of_int lbl)^":")
| Goto l -> dump_line_at loc ("goto "^(string_of_lbl l)^";")
| Call f -> dump_line_at loc ((string_of_funexp f)^";")
| Select (body1, body2) ->
dump_line_at loc "choose {";
dump_line " -->";
incr_margin ();
dump_blk body1;
decr_margin ();
dump_line " -->";
incr_margin ();
dump_blk body2;
decr_margin ();
dump_line "}"
| InfLoop body ->
dump_line_at loc "while (1) {";
incr_margin ();
dump_blk body;
decr_margin ();
dump_line "}"
| UserSpec x -> dump_line_at loc (string_of_assertion x)
and dump_blk b =
match b with
| hd::[] -> dump_stmt true hd
| hd::r ->
dump_stmt false hd;
List.iter (dump_stmt false) r
| [] -> ()
in
dump_blk x;
Buffer.contents buf
let dump_fundec name declaration =
let (args_t, ret_t) = declaration.ftyp in
let args_t = string_of_args_t args_t in
let ret_t = string_of_ret_t ret_t in
print_endline (ret_t^" "^name^"("^args_t^") {");
print_string (string_of_blk 2 declaration.body);
print_endline "}";
print_newline ()
let dump_globals gdecls =
(* TODO: Clean this mess... StringMap *)
let glbs = ref (StringMap.empty) in
Hashtbl.iter
(fun name info -> glbs := (StringMap.add name info !glbs))
gdecls;
StringMap.iter dump_gdecl !glbs
(* Exported print functions *)
let dump prog =
(* TODO: Clean this mess... StringMap *)
let funs = ref (StringMap.empty) in
let collect_funbody name body =
funs := StringMap.add name body !funs
in
let init = string_of_blk 0 prog.init in
Hashtbl.iter collect_funbody prog.fundecs;
StringMap.iter dump_fundec !funs;
dump_globals prog.globals;
print_string init
let string_of_blk x = string_of_blk 0 x
let string_of_stmt x = string_of_blk (x::[])
type visitor_t =
{ mutable loc : Newspeak.location
; gdecl : string -> Newspeak.typ -> bool
; func : Newspeak.fid -> fundec -> bool
; func_after : unit -> unit
; stmt : stmt -> bool
; funexp : funexp -> bool
; exp : Newspeak.location -> exp -> bool
; bexp : exp -> unit
; lval : lval -> bool
; unop : Newspeak.unop -> unit
; binop : Newspeak.binop -> unit
; size_t : Newspeak.size_t -> unit
; length : Newspeak.length -> unit
; typ : Newspeak.typ -> unit
}
let visit_nop =
let f2true _ _ = true in
let f1unit _ = () in
let f1true _ = true in
{ loc = Newspeak.unknown_loc
; gdecl = f2true
; func = f2true
; func_after = f1unit
; stmt = f1true
; funexp = f1true
; exp = f2true
; bexp = f1unit
; lval = f1true
; unop = f1unit
; binop = f1unit
; size_t = f1unit
; length = f1unit
; typ = f1unit
}
class visitor =
object
val mutable cur_loc = N.unknown_loc
method set_loc loc = cur_loc <- loc
method get_loc = cur_loc
method process_gdecl (_: string) (_: N.typ) = true
method process_fun (_: N.fid) (_: fundec) = true
method process_fun_after () = ()
method process_stmt (_: stmt) = true
method process_funexp (_: funexp) = true
method process_exp (_: exp) = true
method process_bexp (_: exp) = ()
method process_lval (_: lval) = true
method process_unop (_: N.unop) = ()
method process_binop (_: N.binop) = ()
method process_size_t (_: N.size_t) = ()
method process_length (_: N.length) = ()
method process_typ (_: N.typ) = ()
method raise_error msg =
let (file, line, _) = cur_loc in
let pos =
if cur_loc = N.unknown_loc then ""
else " in "^file^" line "^(string_of_int line)
in
(StandardApplication.report_error (msg^pos) : unit)
method print_warning msg =
let (file, line, _) = cur_loc in
let pos =
if cur_loc = N.unknown_loc then ""
else " in "^file^" line "^(string_of_int line)
in
print_endline ("Warning: "^msg^pos)
end
let visit_scalar_t visitor t =
match t with
N.Int k -> visitor.size_t (snd k)
| N.Float sz -> visitor.size_t sz
| N.Ptr -> ()
| N.FunPtr -> ()
let visit_typ visitor t =
visitor.typ t;
let rec visit_typ t =
match t with
N.Scalar t -> visit_scalar_t visitor t
| N.Array (t, n) ->
visit_typ t;
visitor.length n
| N.Region (fields, sz) ->
List.iter (fun (_, t) -> visit_typ t) fields;
visitor.size_t sz
in
visit_typ t
let visit_ftyp visitor (args, ret) =
List.iter (visit_typ visitor) args;
List.iter (visit_typ visitor) ret
let rec visit_lval visitor x =
let continue = visitor.lval x in
match x with
Deref (e, sz) when continue ->
visit_exp visitor e;
visitor.size_t sz
| Shift (lv, e) when continue ->
visit_lval visitor lv;
visit_exp visitor e
| _ -> ()
and visit_exp visitor x =
let continue = visitor.exp visitor.loc x in
if continue then begin
match x with
Lval (lv, _) -> visit_lval visitor lv
| AddrOf lv -> visit_lval visitor lv
| UnOp (op, e) ->
visitor.unop op;
visit_exp visitor e
| BinOp (bop, e1, e2) ->
visitor.binop bop;
visit_binop visitor bop;
visit_exp visitor e1;
visit_exp visitor e2
| _ -> ()
end
and visit_binop visitor op =
match op with
| N.PlusF sz
| N.MinusF sz
| N.MultF sz
| N.DivF sz -> visitor.size_t sz
| _ -> ()
let visit_funexp visitor x =
let continue = visitor.funexp x in
match x with
FunDeref (e, t) when continue ->
visit_exp visitor e;
visit_ftyp visitor t
| _ -> ()
let rec visit_blk visitor x = List.iter (visit_stmt visitor) x
and visit_stmt visitor (x, loc) =
visitor.loc <- loc;
let continue = visitor.stmt (x, loc) in
if continue then begin
match x with
Set (lv, e, _) ->
visit_lval visitor lv;
visit_exp visitor e
| Copy (lv1, lv2, sz) ->
visit_lval visitor lv1;
visit_lval visitor lv2;
visitor.size_t sz
| Guard b ->
visitor.bexp b;
visit_exp visitor b
| Decl (_, t, body) ->
visit_typ visitor t;
visit_blk visitor body
| Call fn -> visit_funexp visitor fn
| Select (body1, body2) ->
visitor.loc <- loc;
visit_blk visitor body1;
visitor.loc <- loc;
visit_blk visitor body2
| InfLoop x -> visit_blk visitor x
| DoWith (body, _) -> visit_blk visitor body
| Goto _ -> ()
| UserSpec assertion -> List.iter (visit_token visitor) assertion
end else ()
and visit_token builder x =
match x with
LvalToken (lv, t) ->
visit_lval builder lv;
visit_typ builder t
| _ -> ()
let visit_fun visitor fid declaration =
let continue = visitor.func fid declaration in
if continue then begin
visit_ftyp visitor declaration.ftyp;
visit_blk visitor declaration.body;
visitor.func_after ()
end
let visit_glb visitor id t =
let continue = visitor.gdecl id t in
if continue then visit_typ visitor t
let visit visitor prog =
Hashtbl.iter (visit_glb visitor) prog.globals;
visit_blk visitor prog.init;
Hashtbl.iter (visit_fun visitor) prog.fundecs
let collect_fid_addrof prog =
let fid_list = ref [] in
let fid_addrof_visitor =
{ visit_nop with exp = fun _ -> function
| AddrOfFun (id, _) when not (List.mem id !fid_list) ->
fid_list := id::!fid_list; true
| _ -> true
} in
visit fid_addrof_visitor prog;
!fid_list
let rec negate exp =
match exp with
| UnOp (N.Not, BinOp (N.Eq t, e2, e1)) -> BinOp (N.Eq t, e1, e2)
| UnOp (N.Not, e) -> e
| BinOp (N.Gt t, e1, e2) -> UnOp (N.Not, BinOp (N.Gt t, e1, e2))
| BinOp (N.Eq t, e1, e2) -> UnOp (N.Not, BinOp (N.Eq t, e1, e2))
| UnOp (N.Coerce i, e) -> UnOp (N.Coerce i, negate e)
| _ -> StandardApplication.report_error "Newspeak.negate"
let zero = Const (N.CInt N.Nat.zero)
let one = Const (N.CInt N.Nat.one)
class builder =
object
val mutable curloc = N.unknown_loc
method set_curloc loc = curloc <- loc
method curloc = curloc
method process_global (_: string) (x: N.typ) = x
method process_lval (x: lval) = x
method process_exp (x: exp) = x
method process_blk (x: blk) = x
method enter_stmtkind (_: stmtkind) = ()
method process_stmtkind (x: stmtkind) = x
method process_size_t (x: N.size_t) = x
method process_offset (x: N.offset) = x
end
class simplify_coerce =
object
inherit builder
TODO : put these theorems in Newspeak semantics paper
method process_exp e =
match e with
Coerce [ a;b ] Coerce [ c;d ] e
- > Coerce [ c;d ] if [ a;b ] contains [ c;d ]
-> Coerce [c;d] if [a;b] contains [c;d] *)
| UnOp (N.Coerce r1, UnOp (N.Coerce r2, e)) when N.contains r1 r2 ->
UnOp (N.Coerce r2, e)
Coerce [ a;b ] Coerce [ c;d ] e - > Coerce [ a;b ] if [ c;d ] contains [ a;b ]
| UnOp (N.Coerce r1, UnOp (N.Coerce r2, e)) when N.contains r2 r1 ->
UnOp (N.Coerce r1, e)
Coerce / Belongs [ a;b ] Const c - > Const c if c in [ a;b ]
| UnOp ((N.Coerce r | N.Belongs r), Const (N.CInt c))
when N.belongs c r -> Const (N.CInt c)
Coerce / Belongs [ a;b ] Lval ( lv , t ) - > Lval ( lv , t )
if [ a ; b ] contains dom(t )
if [a; b] contains dom(t) *)
| UnOp ((N.Coerce r | N.Belongs r), (Lval (_, N.Int k) as lv))
when N.contains r (N.domain_of_typ k) -> lv
(* TODO: could do this after a sanity checks that checks the largest and
smallest integer ever computed in expressions!! *)
| UnOp (N.Coerce r,
(BinOp (N.MultI, UnOp (N.Belongs (l, u), _), Const N.CInt x) as e')) ->
let l = N.Nat.mul l x in
let u = N.Nat.mul u x in
if N.contains r (l, u) then e' else e
| _ -> e
end
class simplify_choose =
object
inherit builder
method process_blk x =
match x with
This rule is incorrect when body is blocking ! ! !
( Select ( body , [ ] ) , _ ): : tl | ( Select ( [ ] , body ) , _ ): : tl - >
( body)@tl
(Select (body, []), _)::tl | (Select ([], body), _)::tl ->
(self#process_blk body)@tl*)
| (Select (body, (Guard Const N.CInt i, _)::_), _)::tl
when N.Nat.compare i N.Nat.zero = 0 -> body@tl
| (Select ((Guard Const N.CInt i, _)::_, body), _)::tl
when N.Nat.compare i N.Nat.zero = 0 -> body@tl
| (Guard Const N.CInt i, _)::tl when N.Nat.compare i N.Nat.one = 0 -> tl
| _ -> x
end
let rec addr_of_deref lv =
match lv with
Deref (e, _) -> e
| Shift (lv, i) -> BinOp (N.PlusPI, addr_of_deref lv, i)
| _ -> raise Not_found
class simplify_ptr =
object
inherit builder
method process_lval lv =
match lv with
Deref (UnOp (N.Focus n, AddrOf lv), n') when n' <= n -> lv
| _ -> lv
method process_exp e =
match e with
AddrOf lv -> begin
try addr_of_deref lv
with Not_found -> e
end
| _ -> e
end
class simplify_arith =
object (self)
inherit builder
method process_lval x =
match x with
Shift (lv, Const N.CInt c) when N.Nat.compare c N.Nat.zero = 0 -> lv
| Shift (Shift (lv, Const N.CInt c1), Const N.CInt c2) ->
let c = N.Nat.add c1 c2 in
let lv = Shift (lv, Const (N.CInt c)) in
self#process_lval lv
| _ -> x
TODO : generatlization of all this : do the operations with bignums
and then come back to Int64
and then come back to Int64 *)
TODO : should use string to representer constants , not Int64 , since
not all unsigned long long can be represented
not all unsigned long long can be represented *)
method process_exp e =
match e with
BinOp (N.MultI|N.PlusI|N.MinusI as op, Const N.CInt x, Const N.CInt y) ->
let nat_op = function
| N.PlusI -> N.Nat.add
| N.MinusI -> N.Nat.sub
| N.MultI -> N.Nat.mul
| _ ->
Npkcontext.report_error "Newspeak.big_int_op"
"unexpected operator"
in
let z = nat_op op x y in
Const (N.CInt z)
| BinOp (N.PlusPI, e, Const N.CInt x) when (N.Nat.compare x N.Nat.zero = 0) -> e
| BinOp (N.PlusPI, BinOp (N.PlusPI, e, Const N.CInt y), Const N.CInt x)
when (N.Nat.compare x N.Nat.zero >= 0)
&& (N.Nat.compare y N.Nat.zero >= 0) ->
BinOp (N.PlusPI, e, Const (N.CInt (N.Nat.add x y)))
| BinOp (N.DivI, Const N.CInt i1, Const N.CInt i2)
when N.Nat.compare i2 N.Nat.zero <> 0 ->
Const (N.CInt (N.Nat.div i1 i2))
| UnOp (N.Not, Const N.CInt i) when N.Nat.compare i N.Nat.zero = 0 ->
exp_of_int 1
| UnOp (N.Not, Const N.CInt i) when N.Nat.compare i N.Nat.zero <> 0 ->
exp_of_int 0
| _ -> e
end
module Lbl =
struct
type t = N.lbl
let compare = compare
end
module LblSet = Set.Make(Lbl)
let simplify_gotos blk =
let current_lbl = ref (-1) in
let stack = ref [] in
let used_lbls = ref LblSet.empty in
let new_lbl () = incr current_lbl; !current_lbl in
let find lbl =
let lbl' = List.assoc lbl !stack in
used_lbls := LblSet.add lbl' !used_lbls;
lbl'
in
let push lbl1 lbl2 = stack := (lbl1, lbl2)::(!stack) in
let pop () =
match !stack with
(_, lbl)::tl ->
used_lbls := LblSet.remove lbl !used_lbls;
stack := tl
| [] ->
Npkcontext.report_error "Newspeak.simplify_gotos"
"unexpected empty stack"
in
let rec simplify_blk x =
match x with
hd::tl ->
let hd = simplify_stmt hd in
let tl = simplify_blk tl in
hd@tl
| [] -> []
and simplify_stmt (x, loc) =
match x with
DoWith (body, lbl) ->
let lbl' = new_lbl () in
push lbl lbl';
simplify_dowith_goto loc (body, lbl')
| _ -> (simplify_stmtkind x, loc)::[]
and simplify_stmtkind x =
match x with
| Goto lbl -> Goto (find lbl)
| Decl (name, t, body) ->
let body = simplify_blk body in
Decl (name, t, body)
| Select (body1, body2) -> Select (simplify_blk body1, simplify_blk body2)
| InfLoop body ->
let body = simplify_blk body in
InfLoop body
| _ -> x
and remove_final_goto lbl blk =
let rec remove blk =
match blk with
(Goto lbl', _)::[] when List.assoc lbl' !stack = lbl -> []
| hd::tl -> hd::(remove tl)
| [] -> []
in
try remove blk
with Not_found -> blk
and simplify_dowith loc (body, lbl) =
match body with
(DoWith (body, lbl'), _)::[] ->
push lbl' lbl;
let x = simplify_dowith_goto loc (body, lbl) in
pop ();
x
| hd::tl ->
let hd = simplify_stmt hd in
if LblSet.mem lbl !used_lbls then begin
let tl = simplify_blk tl in
let body = hd@tl in
pop ();
(DoWith (body, lbl), loc)::[]
end else hd@(simplify_dowith loc (tl, lbl))
| [] ->
pop ();
[]
and simplify_dowith_goto loc (body, lbl) =
simplify_dowith loc (remove_final_goto lbl body, lbl)
in
let blk = simplify_blk blk in
if not (LblSet.is_empty !used_lbls)
then begin
Npkcontext.report_error "Newspeak.simplify_gotos"
"unexpected goto without label"
end;
blk
let rec simplify_stmt actions (x, loc) =
List.iter (fun a -> a#enter_stmtkind x) actions;
let x =
match x with
| Set (lv, e, sca) ->
Set (simplify_lval actions lv, simplify_exp actions e, sca)
| Copy (lv1, lv2, sz) ->
let lv1 = simplify_lval actions lv1 in
let lv2 = simplify_lval actions lv2 in
Copy (lv1, lv2, sz)
| Guard b -> Guard (simplify_exp actions b)
| Call (FunDeref (e, t)) -> Call (FunDeref (simplify_exp actions e, t))
| Decl (name, t, body) -> Decl (name, t, simplify_blk actions body)
| Select (body1, body2) ->
Select (simplify_blk actions body1, simplify_blk actions body2)
| InfLoop body ->
let body = simplify_blk actions body in
InfLoop body
| DoWith (body, l) -> DoWith (simplify_blk actions body, l)
| _ -> x
in
let stmt = ref x in
List.iter (fun x -> stmt := x#process_stmtkind !stmt) actions;
(!stmt, loc)
and simplify_exp actions e =
let e =
match e with
Lval (lv, sca) -> Lval (simplify_lval actions lv, sca)
| AddrOf lv -> AddrOf (simplify_lval actions lv)
| UnOp (o, e) -> UnOp (o, simplify_exp actions e)
| BinOp (o, e1, e2) ->
BinOp (o, simplify_exp actions e1, simplify_exp actions e2)
| _ -> e
in
let e = ref e in
List.iter (fun x -> e := x#process_exp !e) actions;
!e
and simplify_lval actions lv =
let lv =
match lv with
| Deref (e, sz) -> Deref (simplify_exp actions e, sz)
| Shift (l, e) -> Shift (simplify_lval actions l, simplify_exp actions e)
| _ -> lv
in
let lv = ref lv in
List.iter (fun x -> lv := x#process_lval !lv) actions;
!lv
and simplify_blk actions blk =
match blk with
hd::tl ->
let hd = simplify_stmt actions hd in
let tl = simplify_blk actions tl in
let blk = ref (hd::tl) in
List.iter (fun x -> blk := x#process_blk !blk) actions;
!blk
| [] -> []
let simplify_blk opt_checks b =
let simplifications = if opt_checks then (new simplify_coerce)::[] else [] in
let simplifications =
(new simplify_choose)::(new simplify_ptr)
::(new simplify_arith)::simplifications
in
simplify_gotos (simplify_blk simplifications b)
let simplify opt_checks prog =
let fundecs = Hashtbl.create 100 in
let globals = Hashtbl.create 100 in
let simplify_global x info = Hashtbl.add globals x info in
let simplify_fundec f declaration =
let body = simplify_blk opt_checks declaration.body in
let declaration = { declaration with body = body } in
Hashtbl.add fundecs f declaration
in
let init = simplify_blk opt_checks prog.init in
Hashtbl.iter simplify_global prog.globals;
Hashtbl.iter simplify_fundec prog.fundecs;
{ prog with globals = globals; init = init; fundecs = fundecs }
let rec belongs_of_exp x =
match x with
Lval (lv, _) | AddrOf lv -> belongs_of_lval lv
| UnOp (N.Belongs b, e) -> (b, e)::(belongs_of_exp e)
| UnOp (_, e) -> belongs_of_exp e
| BinOp (_, e1, e2) -> (belongs_of_exp e1)@(belongs_of_exp e2)
| _ -> []
and belongs_of_lval x =
match x with
Deref (e, _) -> belongs_of_exp e
| Shift (lv, e) -> (belongs_of_lval lv)@(belongs_of_exp e)
| _ -> []
let belongs_of_funexp x =
match x with
FunDeref (e, _) -> belongs_of_exp e
| _ -> []
let rec build builder prog =
let globals' = Hashtbl.create 100 in
let fundecs' = Hashtbl.create 100 in
let build_global x gdecl =
let gdecl = build_gdecl builder gdecl in
let gdecl = builder#process_global x gdecl in
Hashtbl.add globals' x gdecl
in
let build_fundec f fundec =
builder#set_curloc N.unknown_loc;
let fundec = build_fundec builder fundec in
Hashtbl.add fundecs' f fundec
in
Hashtbl.iter build_global prog.globals;
Hashtbl.iter build_fundec prog.fundecs;
{ prog with globals = globals'; fundecs = fundecs' }
and build_gdecl builder t =
build_typ builder t
and build_fundec builder declaration =
let ftyp = build_ftyp builder declaration.ftyp in
let body = build_blk builder declaration.body in
{ declaration with ftyp = ftyp; body = body }
and build_typ builder t =
match t with
N.Scalar t -> N.Scalar (build_scalar_t builder t)
| N.Array (t, n) ->
let t = build_typ builder t in
N.Array (t, n)
| N.Region (fields, sz) ->
let fields = List.map (build_field builder) fields in
let sz = build_size_t builder sz in
N.Region (fields, sz)
and build_scalar_t builder t =
match t with
N.Int k ->
let k = build_ikind builder k in
N.Int k
| N.Float sz ->
let sz = build_size_t builder sz in
N.Float sz
| N.Ptr -> t
| N.FunPtr -> t
and build_field builder (o, t) =
let o = build_offset builder o in
let t = build_typ builder t in
(o, t)
and build_ikind builder (sign, sz) =
let sz = build_size_t builder sz in
(sign, sz)
and build_ftyp builder (args, ret) =
let args = List.map (build_typ builder) args in
let ret = List.map (build_typ builder) ret in
(args, ret)
and build_offset builder o = builder#process_offset o
and build_size_t builder sz = builder#process_size_t sz
and build_blk builder blk =
let blk =
match blk with
hd::tl ->
let hd = build_stmt builder hd in
let tl = build_blk builder tl in
hd::tl
| [] -> []
in
builder#process_blk blk
and build_stmt builder (x, loc) =
builder#set_curloc loc;
let x = build_stmtkind builder x in
(x, loc)
and build_stmtkind builder x =
builder#enter_stmtkind x;
let x =
match x with
Set (lv, e, t) ->
let lv = build_lval builder lv in
let e = build_exp builder e in
let t = build_scalar_t builder t in
Set (lv, e, t)
| Copy (lv1, lv2, n) ->
let lv1 = build_lval builder lv1 in
let lv2 = build_lval builder lv2 in
let n = build_size_t builder n in
Copy (lv1, lv2, n)
| Guard b ->
Guard (build_exp builder b)
| Decl (x, t, body) ->
let t = build_typ builder t in
let body = build_blk builder body in
Decl (x, t, body)
| Select (body1, body2) ->
Select (build_blk builder body1, build_blk builder body2)
| InfLoop body ->
let body = build_blk builder body in
InfLoop body
| DoWith (body, lbl) -> DoWith (build_blk builder body, lbl)
| Goto lbl -> Goto lbl
| Call fn ->
let fn = build_funexp builder fn in
Call fn
| UserSpec assertion ->
let assertion = List.map (build_token builder) assertion in
UserSpec assertion
in
builder#process_stmtkind x
and build_token builder x =
match x with
LvalToken (lv, t) -> LvalToken ((build_lval builder lv), t)
| _ -> x
and build_funexp builder fn =
match fn with
FunId f -> FunId f
| FunDeref (e, ft) ->
let e = build_exp builder e in
let ft = build_ftyp builder ft in
FunDeref (e, ft)
and build_lval builder lv =
let lv =
match lv with
Local x -> Local x
| Global str -> Global str
| Deref (e, sz) ->
let e = build_exp builder e in
let sz = build_size_t builder sz in
Deref (e, sz)
| Shift (lv, e) ->
let lv = build_lval builder lv in
let e = build_exp builder e in
Shift (lv, e)
in
builder#process_lval lv
and build_exp builder e =
let e =
match e with
Const c -> Const c
| Lval (lv, t) ->
let lv = build_lval builder lv in
let t = build_scalar_t builder t in
Lval (lv, t)
| AddrOf lv ->
let lv = build_lval builder lv in
AddrOf lv
| AddrOfFun f -> AddrOfFun f
| UnOp (op, e) ->
let op = build_unop builder op in
let e = build_exp builder e in
UnOp (op, e)
| BinOp (op, e1, e2) ->
let op = build_binop builder op in
let e1 = build_exp builder e1 in
let e2 = build_exp builder e2 in
BinOp (op, e1, e2)
in
builder#process_exp e
and build_unop builder op =
match op with
N.PtrToInt k ->
let k = build_ikind builder k in
N.PtrToInt k
| N.IntToPtr k ->
let k = build_ikind builder k in
N.IntToPtr k
| N.Cast (t1, t2) ->
let t1 = build_scalar_t builder t1 in
let t2 = build_scalar_t builder t2 in
N.Cast (t1, t2)
| N.Focus sz -> N.Focus (build_size_t builder sz)
| N.Belongs _ | N.Coerce _ | N.Not | N.BNot _-> op
and build_binop builder op =
match op with
N.PlusF sz -> N.PlusF (build_size_t builder sz)
| N.MinusF sz -> N.MinusF (build_size_t builder sz)
| N.MultF sz -> N.MultF (build_size_t builder sz)
| N.DivF sz -> N.DivF (build_size_t builder sz)
| N.MinusPP -> N.MinusPP
| N.Gt t -> N.Gt (build_scalar_t builder t)
| N.Eq t -> N.Eq (build_scalar_t builder t)
| N.PlusI | N.MinusI | N.MultI | N.DivI | N.Mod
| N.BOr _ | N.BAnd _ | N.BXor _ | N.Shiftlt | N.Shiftrt | N.PlusPI -> op
| null | https://raw.githubusercontent.com/airbus-seclab/bincat/7d4a0b90cf950c0f43e252602a348cf9e2f858ba/ocaml/src/npk/newspeak/lowspeak.ml | ocaml | -------
Types
-------
*************************************************
Types
Expressions
Actual dump
TODO: Clean this mess... StringMap
Exported print functions
TODO: Clean this mess... StringMap
TODO: could do this after a sanity checks that checks the largest and
smallest integer ever computed in expressions!! |
C2Newspea : compiles C code into Newspeak . Newspeak is a minimal language
well - suited for static analysis .
Copyright ( C ) 2007 - 2022 , , ,
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
EADS Innovation Works - SE / CS
12 , rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email :
email :
EADS Innovation Works - SE / IS
12 , rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email :
EADS Innovation Works - SE / IS
12 , rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email :
C2Newspea: compiles C code into Newspeak. Newspeak is a minimal language
well-suited for static analysis.
Copyright (C) 2007-2022 Charles Hymans, Olivier Levillain, Sarah Zennou,
Etienne Millon
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Charles Hymans
EADS Innovation Works - SE/CS
12, rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email:
Olivier Levillain
email:
Sarah Zennou
EADS Innovation Works - SE/IS
12, rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email:
Etienne Millon
EADS Innovation Works - SE/IS
12, rue Pasteur - BP 76 - 92152 Suresnes Cedex - France
email:
*)
module N = Newspeak
type t = {
globals: N.globals;
init: blk;
fundecs: (N.fid, fundec) Hashtbl.t;
ptr_sz: N.size_t;
src_lang: N.src_lang;
abi: N.abi_t;
}
and fundec = {
position: Newspeak.location;
ftyp: N.ftyp;
body: blk;
}
and assertion = spec_token list
and spec_token =
| SymbolToken of char
| IdentToken of string
| LvalToken of (lval * N.typ)
| CstToken of N.cst
and stmtkind =
Set of (lval * exp * N.scalar_t)
| Copy of (lval * lval * N.size_t)
| Guard of exp
| Decl of (string * N.typ * blk)
| Select of (blk * blk)
| InfLoop of blk
| DoWith of (blk * N.lbl)
| Goto of N.lbl
| Call of funexp
| UserSpec of assertion
and stmt = stmtkind * N.location
and blk = stmt list
and funexp =
FunId of N.fid
| FunDeref of (exp * N.ftyp)
and lval =
Local of N.vid
| Global of string
| Deref of (exp * N.size_t)
| Shift of (lval * exp)
and exp =
Const of N.cst
| Lval of (lval * N.scalar_t)
| AddrOf of lval
| AddrOfFun of (N.fid * N.ftyp)
| UnOp of (N.unop * exp)
| BinOp of (N.binop * exp * exp)
let exp_of_int x = Const (N.CInt (N.Nat.of_int x))
module StringMap =
Map.Make (struct type t = string let compare = Stdlib.compare end)
let rec seq sep f l =
match l with
| [] -> ""
| [e] -> f e
| e::r -> (f e)^sep^(seq sep f r)
let string_of_size_t = string_of_int
let string_of_sign_t sg =
match sg with
N.Unsigned -> "u"
| N.Signed -> ""
let string_of_scalar s =
match s with
N.Int (sg, sz) -> (string_of_sign_t sg)^"int"^(string_of_size_t sz)
| N.Float sz -> "float" ^ (string_of_size_t sz)
| N.Ptr -> "ptr"
| N.FunPtr -> "fptr"
let rec string_of_typ t =
match t with
N.Scalar s -> string_of_scalar s
| N.Array (t, sz) -> (string_of_typ t)^"["^(string_of_size_t sz)^"]"
| N.Region (lst, sz) ->
let res = ref "{ " in
let string_of_elt (off, t) =
res := !res^(string_of_typ t)^" "^(string_of_size_t off)^"; "
in
List.iter string_of_elt lst;
!res^"}"^(string_of_size_t sz)
let string_of_args_t args =
match args with
hd::[] -> string_of_typ hd
| hd::tl ->
let res = ref (string_of_typ hd) in
List.iter (fun x -> res := !res^", "^(string_of_typ x)) tl;
!res
| [] -> "void"
let string_of_ret_t ret = string_of_args_t ret
let string_of_loc (fname, line, carac) =
if (fname = "")
then Npkcontext.report_error "Newspeak.string_of_loc" "unknown location";
if (line < 0) || (carac < 0) then fname
else (fname^":"^(string_of_int line)^"#"^(string_of_int carac))
let string_of_cst c =
match c with
N.CInt c -> N.Nat.to_string c
| N.CFloat (_, s) -> s
| N.Nil -> "nil"
let string_of_bounds (l, u) = "["^(N.Nat.to_string l)^","^(N.Nat.to_string u)^"]"
let string_of_unop op =
match op with
N.Belongs r -> "belongs"^(string_of_bounds r)
| N.Coerce r -> "coerce"^(string_of_bounds r)
| N.Focus sz -> "focus"^(string_of_size_t sz)
| N.Cast (typ, typ') ->
"("^(string_of_scalar typ')^" <= "^(string_of_scalar typ)^")"
| N.Not -> "!"
| N.BNot _ -> "~"
| N.PtrToInt i -> "("^(string_of_scalar (N.Int i))^")"
| N.IntToPtr _ -> "(ptr)"
let string_of_binop op =
match op with
| N.Gt _ -> ">"
| N.Eq t -> "==_"^(string_of_scalar t)
| N.PlusI -> "+"
| N.MinusI -> "-"
| N.MultI -> "*"
| N.Mod -> "%"
| N.DivI -> "/"
| N.PlusF _ -> "+."
| N.MinusF _ -> "-."
| N.MultF _ -> "*."
| N.DivF _ -> "/."
| N.BAnd _ -> "&"
| N.BOr _ -> "|"
| N.BXor _ -> "^"
| N.Shiftlt -> "<<"
| N.Shiftrt -> ">>"
| N.PlusPI -> "+"
| N.MinusPP -> "-"
let rec string_of_lval lv =
match lv with
Local vid -> (string_of_int vid) ^ "-"
| Global name -> name
| Deref (e, sz) -> "["^(string_of_exp e)^"]"^(string_of_size_t sz)
| Shift (lv, sh) -> (string_of_lval lv)^" + "^(string_of_exp sh)
and string_of_exp e =
match e with
Const c -> string_of_cst c
| Lval (lv, t) -> (string_of_lval lv)^"_"^(string_of_scalar t)
| AddrOf lv -> "&("^(string_of_lval lv)^")"
| AddrOfFun (fid, ft) -> "&_{"^(N.string_of_ftyp ft)^"}("^fid^")"
| BinOp (op, e1, e2) ->
"("^(string_of_exp e1)^" "^(string_of_binop op)^
" "^(string_of_exp e2)^")"
| UnOp (op, exp) -> (string_of_unop op)^" "^(string_of_exp exp)
let string_of_funexp f =
match f with
FunId fid -> fid^"()"
| FunDeref (exp, (args_t, [ret_t])) ->
"["^(string_of_exp exp)^"]("^
(seq ", " string_of_typ args_t)^") -> "^(string_of_typ ret_t)
| FunDeref (exp, (args_t, _)) ->
"["^(string_of_exp exp)^"]("^(seq ", " string_of_typ args_t)^")"
let string_of_lbl l = "lbl"^(string_of_int l)
let dump_gdecl name t = print_endline (string_of_typ t^" "^name^";")
let string_of_token x =
match x with
SymbolToken x -> String.make 1 x
| IdentToken x -> x
| LvalToken (x, _) -> "'"^(string_of_lval x)^"'"
| CstToken c -> string_of_cst c
let string_of_assertion x =
let res = ref "" in
let append_token x = res := !res^(string_of_token x)^" " in
List.iter append_token x;
!res
let string_of_blk offset x =
let buf = Buffer.create 80 in
let offset = ref offset in
let incr_margin () = offset := !offset + 2 in
let decr_margin () = offset := !offset - 2 in
let dump_line str =
let margin = String.make !offset ' ' in
Buffer.add_string buf (margin^str^"\n")
in
let dump_line_at loc str =
let loc = if loc = N.unknown_loc then "" else "("^(string_of_loc loc)^")^" in
let margin = String.make !offset ' ' in
Buffer.add_string buf (margin^loc^str^"\n")
in
let rec dump_stmt only (sk, loc) =
match sk with
Set (lv, e, sc) ->
dump_line_at loc ((string_of_lval lv)^" =("^(string_of_scalar sc)^
") "^(string_of_exp e)^";")
| Guard b -> dump_line_at loc ("guard("^(string_of_exp b)^");")
| Copy (lv1, lv2, sz) ->
dump_line_at loc ((string_of_lval lv1)^" ="^(string_of_size_t sz)^
" "^(string_of_lval lv2)^";")
| Decl (x, t, body) ->
if only then begin
dump_line_at loc ((string_of_typ t)^" "^x^";");
dump_blk body
end else begin
dump_line_at loc "{";
incr_margin ();
dump_line ((string_of_typ t)^" "^x^";");
dump_blk body;
decr_margin ();
dump_line "}"
end
| DoWith (body, lbl) ->
dump_line_at loc "do {";
incr_margin ();
dump_blk body;
decr_margin ();
dump_line ("} with lbl"^(string_of_int lbl)^":")
| Goto l -> dump_line_at loc ("goto "^(string_of_lbl l)^";")
| Call f -> dump_line_at loc ((string_of_funexp f)^";")
| Select (body1, body2) ->
dump_line_at loc "choose {";
dump_line " -->";
incr_margin ();
dump_blk body1;
decr_margin ();
dump_line " -->";
incr_margin ();
dump_blk body2;
decr_margin ();
dump_line "}"
| InfLoop body ->
dump_line_at loc "while (1) {";
incr_margin ();
dump_blk body;
decr_margin ();
dump_line "}"
| UserSpec x -> dump_line_at loc (string_of_assertion x)
and dump_blk b =
match b with
| hd::[] -> dump_stmt true hd
| hd::r ->
dump_stmt false hd;
List.iter (dump_stmt false) r
| [] -> ()
in
dump_blk x;
Buffer.contents buf
let dump_fundec name declaration =
let (args_t, ret_t) = declaration.ftyp in
let args_t = string_of_args_t args_t in
let ret_t = string_of_ret_t ret_t in
print_endline (ret_t^" "^name^"("^args_t^") {");
print_string (string_of_blk 2 declaration.body);
print_endline "}";
print_newline ()
let dump_globals gdecls =
let glbs = ref (StringMap.empty) in
Hashtbl.iter
(fun name info -> glbs := (StringMap.add name info !glbs))
gdecls;
StringMap.iter dump_gdecl !glbs
let dump prog =
let funs = ref (StringMap.empty) in
let collect_funbody name body =
funs := StringMap.add name body !funs
in
let init = string_of_blk 0 prog.init in
Hashtbl.iter collect_funbody prog.fundecs;
StringMap.iter dump_fundec !funs;
dump_globals prog.globals;
print_string init
let string_of_blk x = string_of_blk 0 x
let string_of_stmt x = string_of_blk (x::[])
type visitor_t =
{ mutable loc : Newspeak.location
; gdecl : string -> Newspeak.typ -> bool
; func : Newspeak.fid -> fundec -> bool
; func_after : unit -> unit
; stmt : stmt -> bool
; funexp : funexp -> bool
; exp : Newspeak.location -> exp -> bool
; bexp : exp -> unit
; lval : lval -> bool
; unop : Newspeak.unop -> unit
; binop : Newspeak.binop -> unit
; size_t : Newspeak.size_t -> unit
; length : Newspeak.length -> unit
; typ : Newspeak.typ -> unit
}
let visit_nop =
let f2true _ _ = true in
let f1unit _ = () in
let f1true _ = true in
{ loc = Newspeak.unknown_loc
; gdecl = f2true
; func = f2true
; func_after = f1unit
; stmt = f1true
; funexp = f1true
; exp = f2true
; bexp = f1unit
; lval = f1true
; unop = f1unit
; binop = f1unit
; size_t = f1unit
; length = f1unit
; typ = f1unit
}
class visitor =
object
val mutable cur_loc = N.unknown_loc
method set_loc loc = cur_loc <- loc
method get_loc = cur_loc
method process_gdecl (_: string) (_: N.typ) = true
method process_fun (_: N.fid) (_: fundec) = true
method process_fun_after () = ()
method process_stmt (_: stmt) = true
method process_funexp (_: funexp) = true
method process_exp (_: exp) = true
method process_bexp (_: exp) = ()
method process_lval (_: lval) = true
method process_unop (_: N.unop) = ()
method process_binop (_: N.binop) = ()
method process_size_t (_: N.size_t) = ()
method process_length (_: N.length) = ()
method process_typ (_: N.typ) = ()
method raise_error msg =
let (file, line, _) = cur_loc in
let pos =
if cur_loc = N.unknown_loc then ""
else " in "^file^" line "^(string_of_int line)
in
(StandardApplication.report_error (msg^pos) : unit)
method print_warning msg =
let (file, line, _) = cur_loc in
let pos =
if cur_loc = N.unknown_loc then ""
else " in "^file^" line "^(string_of_int line)
in
print_endline ("Warning: "^msg^pos)
end
let visit_scalar_t visitor t =
match t with
N.Int k -> visitor.size_t (snd k)
| N.Float sz -> visitor.size_t sz
| N.Ptr -> ()
| N.FunPtr -> ()
let visit_typ visitor t =
visitor.typ t;
let rec visit_typ t =
match t with
N.Scalar t -> visit_scalar_t visitor t
| N.Array (t, n) ->
visit_typ t;
visitor.length n
| N.Region (fields, sz) ->
List.iter (fun (_, t) -> visit_typ t) fields;
visitor.size_t sz
in
visit_typ t
let visit_ftyp visitor (args, ret) =
List.iter (visit_typ visitor) args;
List.iter (visit_typ visitor) ret
let rec visit_lval visitor x =
let continue = visitor.lval x in
match x with
Deref (e, sz) when continue ->
visit_exp visitor e;
visitor.size_t sz
| Shift (lv, e) when continue ->
visit_lval visitor lv;
visit_exp visitor e
| _ -> ()
and visit_exp visitor x =
let continue = visitor.exp visitor.loc x in
if continue then begin
match x with
Lval (lv, _) -> visit_lval visitor lv
| AddrOf lv -> visit_lval visitor lv
| UnOp (op, e) ->
visitor.unop op;
visit_exp visitor e
| BinOp (bop, e1, e2) ->
visitor.binop bop;
visit_binop visitor bop;
visit_exp visitor e1;
visit_exp visitor e2
| _ -> ()
end
and visit_binop visitor op =
match op with
| N.PlusF sz
| N.MinusF sz
| N.MultF sz
| N.DivF sz -> visitor.size_t sz
| _ -> ()
let visit_funexp visitor x =
let continue = visitor.funexp x in
match x with
FunDeref (e, t) when continue ->
visit_exp visitor e;
visit_ftyp visitor t
| _ -> ()
let rec visit_blk visitor x = List.iter (visit_stmt visitor) x
and visit_stmt visitor (x, loc) =
visitor.loc <- loc;
let continue = visitor.stmt (x, loc) in
if continue then begin
match x with
Set (lv, e, _) ->
visit_lval visitor lv;
visit_exp visitor e
| Copy (lv1, lv2, sz) ->
visit_lval visitor lv1;
visit_lval visitor lv2;
visitor.size_t sz
| Guard b ->
visitor.bexp b;
visit_exp visitor b
| Decl (_, t, body) ->
visit_typ visitor t;
visit_blk visitor body
| Call fn -> visit_funexp visitor fn
| Select (body1, body2) ->
visitor.loc <- loc;
visit_blk visitor body1;
visitor.loc <- loc;
visit_blk visitor body2
| InfLoop x -> visit_blk visitor x
| DoWith (body, _) -> visit_blk visitor body
| Goto _ -> ()
| UserSpec assertion -> List.iter (visit_token visitor) assertion
end else ()
and visit_token builder x =
match x with
LvalToken (lv, t) ->
visit_lval builder lv;
visit_typ builder t
| _ -> ()
let visit_fun visitor fid declaration =
let continue = visitor.func fid declaration in
if continue then begin
visit_ftyp visitor declaration.ftyp;
visit_blk visitor declaration.body;
visitor.func_after ()
end
let visit_glb visitor id t =
let continue = visitor.gdecl id t in
if continue then visit_typ visitor t
let visit visitor prog =
Hashtbl.iter (visit_glb visitor) prog.globals;
visit_blk visitor prog.init;
Hashtbl.iter (visit_fun visitor) prog.fundecs
let collect_fid_addrof prog =
let fid_list = ref [] in
let fid_addrof_visitor =
{ visit_nop with exp = fun _ -> function
| AddrOfFun (id, _) when not (List.mem id !fid_list) ->
fid_list := id::!fid_list; true
| _ -> true
} in
visit fid_addrof_visitor prog;
!fid_list
let rec negate exp =
match exp with
| UnOp (N.Not, BinOp (N.Eq t, e2, e1)) -> BinOp (N.Eq t, e1, e2)
| UnOp (N.Not, e) -> e
| BinOp (N.Gt t, e1, e2) -> UnOp (N.Not, BinOp (N.Gt t, e1, e2))
| BinOp (N.Eq t, e1, e2) -> UnOp (N.Not, BinOp (N.Eq t, e1, e2))
| UnOp (N.Coerce i, e) -> UnOp (N.Coerce i, negate e)
| _ -> StandardApplication.report_error "Newspeak.negate"
let zero = Const (N.CInt N.Nat.zero)
let one = Const (N.CInt N.Nat.one)
class builder =
object
val mutable curloc = N.unknown_loc
method set_curloc loc = curloc <- loc
method curloc = curloc
method process_global (_: string) (x: N.typ) = x
method process_lval (x: lval) = x
method process_exp (x: exp) = x
method process_blk (x: blk) = x
method enter_stmtkind (_: stmtkind) = ()
method process_stmtkind (x: stmtkind) = x
method process_size_t (x: N.size_t) = x
method process_offset (x: N.offset) = x
end
class simplify_coerce =
object
inherit builder
TODO : put these theorems in Newspeak semantics paper
method process_exp e =
match e with
Coerce [ a;b ] Coerce [ c;d ] e
- > Coerce [ c;d ] if [ a;b ] contains [ c;d ]
-> Coerce [c;d] if [a;b] contains [c;d] *)
| UnOp (N.Coerce r1, UnOp (N.Coerce r2, e)) when N.contains r1 r2 ->
UnOp (N.Coerce r2, e)
Coerce [ a;b ] Coerce [ c;d ] e - > Coerce [ a;b ] if [ c;d ] contains [ a;b ]
| UnOp (N.Coerce r1, UnOp (N.Coerce r2, e)) when N.contains r2 r1 ->
UnOp (N.Coerce r1, e)
Coerce / Belongs [ a;b ] Const c - > Const c if c in [ a;b ]
| UnOp ((N.Coerce r | N.Belongs r), Const (N.CInt c))
when N.belongs c r -> Const (N.CInt c)
Coerce / Belongs [ a;b ] Lval ( lv , t ) - > Lval ( lv , t )
if [ a ; b ] contains dom(t )
if [a; b] contains dom(t) *)
| UnOp ((N.Coerce r | N.Belongs r), (Lval (_, N.Int k) as lv))
when N.contains r (N.domain_of_typ k) -> lv
| UnOp (N.Coerce r,
(BinOp (N.MultI, UnOp (N.Belongs (l, u), _), Const N.CInt x) as e')) ->
let l = N.Nat.mul l x in
let u = N.Nat.mul u x in
if N.contains r (l, u) then e' else e
| _ -> e
end
class simplify_choose =
object
inherit builder
method process_blk x =
match x with
This rule is incorrect when body is blocking ! ! !
( Select ( body , [ ] ) , _ ): : tl | ( Select ( [ ] , body ) , _ ): : tl - >
( body)@tl
(Select (body, []), _)::tl | (Select ([], body), _)::tl ->
(self#process_blk body)@tl*)
| (Select (body, (Guard Const N.CInt i, _)::_), _)::tl
when N.Nat.compare i N.Nat.zero = 0 -> body@tl
| (Select ((Guard Const N.CInt i, _)::_, body), _)::tl
when N.Nat.compare i N.Nat.zero = 0 -> body@tl
| (Guard Const N.CInt i, _)::tl when N.Nat.compare i N.Nat.one = 0 -> tl
| _ -> x
end
let rec addr_of_deref lv =
match lv with
Deref (e, _) -> e
| Shift (lv, i) -> BinOp (N.PlusPI, addr_of_deref lv, i)
| _ -> raise Not_found
class simplify_ptr =
object
inherit builder
method process_lval lv =
match lv with
Deref (UnOp (N.Focus n, AddrOf lv), n') when n' <= n -> lv
| _ -> lv
method process_exp e =
match e with
AddrOf lv -> begin
try addr_of_deref lv
with Not_found -> e
end
| _ -> e
end
class simplify_arith =
object (self)
inherit builder
method process_lval x =
match x with
Shift (lv, Const N.CInt c) when N.Nat.compare c N.Nat.zero = 0 -> lv
| Shift (Shift (lv, Const N.CInt c1), Const N.CInt c2) ->
let c = N.Nat.add c1 c2 in
let lv = Shift (lv, Const (N.CInt c)) in
self#process_lval lv
| _ -> x
TODO : generatlization of all this : do the operations with bignums
and then come back to Int64
and then come back to Int64 *)
TODO : should use string to representer constants , not Int64 , since
not all unsigned long long can be represented
not all unsigned long long can be represented *)
method process_exp e =
match e with
BinOp (N.MultI|N.PlusI|N.MinusI as op, Const N.CInt x, Const N.CInt y) ->
let nat_op = function
| N.PlusI -> N.Nat.add
| N.MinusI -> N.Nat.sub
| N.MultI -> N.Nat.mul
| _ ->
Npkcontext.report_error "Newspeak.big_int_op"
"unexpected operator"
in
let z = nat_op op x y in
Const (N.CInt z)
| BinOp (N.PlusPI, e, Const N.CInt x) when (N.Nat.compare x N.Nat.zero = 0) -> e
| BinOp (N.PlusPI, BinOp (N.PlusPI, e, Const N.CInt y), Const N.CInt x)
when (N.Nat.compare x N.Nat.zero >= 0)
&& (N.Nat.compare y N.Nat.zero >= 0) ->
BinOp (N.PlusPI, e, Const (N.CInt (N.Nat.add x y)))
| BinOp (N.DivI, Const N.CInt i1, Const N.CInt i2)
when N.Nat.compare i2 N.Nat.zero <> 0 ->
Const (N.CInt (N.Nat.div i1 i2))
| UnOp (N.Not, Const N.CInt i) when N.Nat.compare i N.Nat.zero = 0 ->
exp_of_int 1
| UnOp (N.Not, Const N.CInt i) when N.Nat.compare i N.Nat.zero <> 0 ->
exp_of_int 0
| _ -> e
end
module Lbl =
struct
type t = N.lbl
let compare = compare
end
module LblSet = Set.Make(Lbl)
let simplify_gotos blk =
let current_lbl = ref (-1) in
let stack = ref [] in
let used_lbls = ref LblSet.empty in
let new_lbl () = incr current_lbl; !current_lbl in
let find lbl =
let lbl' = List.assoc lbl !stack in
used_lbls := LblSet.add lbl' !used_lbls;
lbl'
in
let push lbl1 lbl2 = stack := (lbl1, lbl2)::(!stack) in
let pop () =
match !stack with
(_, lbl)::tl ->
used_lbls := LblSet.remove lbl !used_lbls;
stack := tl
| [] ->
Npkcontext.report_error "Newspeak.simplify_gotos"
"unexpected empty stack"
in
let rec simplify_blk x =
match x with
hd::tl ->
let hd = simplify_stmt hd in
let tl = simplify_blk tl in
hd@tl
| [] -> []
and simplify_stmt (x, loc) =
match x with
DoWith (body, lbl) ->
let lbl' = new_lbl () in
push lbl lbl';
simplify_dowith_goto loc (body, lbl')
| _ -> (simplify_stmtkind x, loc)::[]
and simplify_stmtkind x =
match x with
| Goto lbl -> Goto (find lbl)
| Decl (name, t, body) ->
let body = simplify_blk body in
Decl (name, t, body)
| Select (body1, body2) -> Select (simplify_blk body1, simplify_blk body2)
| InfLoop body ->
let body = simplify_blk body in
InfLoop body
| _ -> x
and remove_final_goto lbl blk =
let rec remove blk =
match blk with
(Goto lbl', _)::[] when List.assoc lbl' !stack = lbl -> []
| hd::tl -> hd::(remove tl)
| [] -> []
in
try remove blk
with Not_found -> blk
and simplify_dowith loc (body, lbl) =
match body with
(DoWith (body, lbl'), _)::[] ->
push lbl' lbl;
let x = simplify_dowith_goto loc (body, lbl) in
pop ();
x
| hd::tl ->
let hd = simplify_stmt hd in
if LblSet.mem lbl !used_lbls then begin
let tl = simplify_blk tl in
let body = hd@tl in
pop ();
(DoWith (body, lbl), loc)::[]
end else hd@(simplify_dowith loc (tl, lbl))
| [] ->
pop ();
[]
and simplify_dowith_goto loc (body, lbl) =
simplify_dowith loc (remove_final_goto lbl body, lbl)
in
let blk = simplify_blk blk in
if not (LblSet.is_empty !used_lbls)
then begin
Npkcontext.report_error "Newspeak.simplify_gotos"
"unexpected goto without label"
end;
blk
let rec simplify_stmt actions (x, loc) =
List.iter (fun a -> a#enter_stmtkind x) actions;
let x =
match x with
| Set (lv, e, sca) ->
Set (simplify_lval actions lv, simplify_exp actions e, sca)
| Copy (lv1, lv2, sz) ->
let lv1 = simplify_lval actions lv1 in
let lv2 = simplify_lval actions lv2 in
Copy (lv1, lv2, sz)
| Guard b -> Guard (simplify_exp actions b)
| Call (FunDeref (e, t)) -> Call (FunDeref (simplify_exp actions e, t))
| Decl (name, t, body) -> Decl (name, t, simplify_blk actions body)
| Select (body1, body2) ->
Select (simplify_blk actions body1, simplify_blk actions body2)
| InfLoop body ->
let body = simplify_blk actions body in
InfLoop body
| DoWith (body, l) -> DoWith (simplify_blk actions body, l)
| _ -> x
in
let stmt = ref x in
List.iter (fun x -> stmt := x#process_stmtkind !stmt) actions;
(!stmt, loc)
and simplify_exp actions e =
let e =
match e with
Lval (lv, sca) -> Lval (simplify_lval actions lv, sca)
| AddrOf lv -> AddrOf (simplify_lval actions lv)
| UnOp (o, e) -> UnOp (o, simplify_exp actions e)
| BinOp (o, e1, e2) ->
BinOp (o, simplify_exp actions e1, simplify_exp actions e2)
| _ -> e
in
let e = ref e in
List.iter (fun x -> e := x#process_exp !e) actions;
!e
and simplify_lval actions lv =
let lv =
match lv with
| Deref (e, sz) -> Deref (simplify_exp actions e, sz)
| Shift (l, e) -> Shift (simplify_lval actions l, simplify_exp actions e)
| _ -> lv
in
let lv = ref lv in
List.iter (fun x -> lv := x#process_lval !lv) actions;
!lv
and simplify_blk actions blk =
match blk with
hd::tl ->
let hd = simplify_stmt actions hd in
let tl = simplify_blk actions tl in
let blk = ref (hd::tl) in
List.iter (fun x -> blk := x#process_blk !blk) actions;
!blk
| [] -> []
let simplify_blk opt_checks b =
let simplifications = if opt_checks then (new simplify_coerce)::[] else [] in
let simplifications =
(new simplify_choose)::(new simplify_ptr)
::(new simplify_arith)::simplifications
in
simplify_gotos (simplify_blk simplifications b)
let simplify opt_checks prog =
let fundecs = Hashtbl.create 100 in
let globals = Hashtbl.create 100 in
let simplify_global x info = Hashtbl.add globals x info in
let simplify_fundec f declaration =
let body = simplify_blk opt_checks declaration.body in
let declaration = { declaration with body = body } in
Hashtbl.add fundecs f declaration
in
let init = simplify_blk opt_checks prog.init in
Hashtbl.iter simplify_global prog.globals;
Hashtbl.iter simplify_fundec prog.fundecs;
{ prog with globals = globals; init = init; fundecs = fundecs }
let rec belongs_of_exp x =
match x with
Lval (lv, _) | AddrOf lv -> belongs_of_lval lv
| UnOp (N.Belongs b, e) -> (b, e)::(belongs_of_exp e)
| UnOp (_, e) -> belongs_of_exp e
| BinOp (_, e1, e2) -> (belongs_of_exp e1)@(belongs_of_exp e2)
| _ -> []
and belongs_of_lval x =
match x with
Deref (e, _) -> belongs_of_exp e
| Shift (lv, e) -> (belongs_of_lval lv)@(belongs_of_exp e)
| _ -> []
let belongs_of_funexp x =
match x with
FunDeref (e, _) -> belongs_of_exp e
| _ -> []
let rec build builder prog =
let globals' = Hashtbl.create 100 in
let fundecs' = Hashtbl.create 100 in
let build_global x gdecl =
let gdecl = build_gdecl builder gdecl in
let gdecl = builder#process_global x gdecl in
Hashtbl.add globals' x gdecl
in
let build_fundec f fundec =
builder#set_curloc N.unknown_loc;
let fundec = build_fundec builder fundec in
Hashtbl.add fundecs' f fundec
in
Hashtbl.iter build_global prog.globals;
Hashtbl.iter build_fundec prog.fundecs;
{ prog with globals = globals'; fundecs = fundecs' }
and build_gdecl builder t =
build_typ builder t
and build_fundec builder declaration =
let ftyp = build_ftyp builder declaration.ftyp in
let body = build_blk builder declaration.body in
{ declaration with ftyp = ftyp; body = body }
and build_typ builder t =
match t with
N.Scalar t -> N.Scalar (build_scalar_t builder t)
| N.Array (t, n) ->
let t = build_typ builder t in
N.Array (t, n)
| N.Region (fields, sz) ->
let fields = List.map (build_field builder) fields in
let sz = build_size_t builder sz in
N.Region (fields, sz)
and build_scalar_t builder t =
match t with
N.Int k ->
let k = build_ikind builder k in
N.Int k
| N.Float sz ->
let sz = build_size_t builder sz in
N.Float sz
| N.Ptr -> t
| N.FunPtr -> t
and build_field builder (o, t) =
let o = build_offset builder o in
let t = build_typ builder t in
(o, t)
and build_ikind builder (sign, sz) =
let sz = build_size_t builder sz in
(sign, sz)
and build_ftyp builder (args, ret) =
let args = List.map (build_typ builder) args in
let ret = List.map (build_typ builder) ret in
(args, ret)
and build_offset builder o = builder#process_offset o
and build_size_t builder sz = builder#process_size_t sz
and build_blk builder blk =
let blk =
match blk with
hd::tl ->
let hd = build_stmt builder hd in
let tl = build_blk builder tl in
hd::tl
| [] -> []
in
builder#process_blk blk
and build_stmt builder (x, loc) =
builder#set_curloc loc;
let x = build_stmtkind builder x in
(x, loc)
and build_stmtkind builder x =
builder#enter_stmtkind x;
let x =
match x with
Set (lv, e, t) ->
let lv = build_lval builder lv in
let e = build_exp builder e in
let t = build_scalar_t builder t in
Set (lv, e, t)
| Copy (lv1, lv2, n) ->
let lv1 = build_lval builder lv1 in
let lv2 = build_lval builder lv2 in
let n = build_size_t builder n in
Copy (lv1, lv2, n)
| Guard b ->
Guard (build_exp builder b)
| Decl (x, t, body) ->
let t = build_typ builder t in
let body = build_blk builder body in
Decl (x, t, body)
| Select (body1, body2) ->
Select (build_blk builder body1, build_blk builder body2)
| InfLoop body ->
let body = build_blk builder body in
InfLoop body
| DoWith (body, lbl) -> DoWith (build_blk builder body, lbl)
| Goto lbl -> Goto lbl
| Call fn ->
let fn = build_funexp builder fn in
Call fn
| UserSpec assertion ->
let assertion = List.map (build_token builder) assertion in
UserSpec assertion
in
builder#process_stmtkind x
and build_token builder x =
match x with
LvalToken (lv, t) -> LvalToken ((build_lval builder lv), t)
| _ -> x
and build_funexp builder fn =
match fn with
FunId f -> FunId f
| FunDeref (e, ft) ->
let e = build_exp builder e in
let ft = build_ftyp builder ft in
FunDeref (e, ft)
and build_lval builder lv =
let lv =
match lv with
Local x -> Local x
| Global str -> Global str
| Deref (e, sz) ->
let e = build_exp builder e in
let sz = build_size_t builder sz in
Deref (e, sz)
| Shift (lv, e) ->
let lv = build_lval builder lv in
let e = build_exp builder e in
Shift (lv, e)
in
builder#process_lval lv
and build_exp builder e =
let e =
match e with
Const c -> Const c
| Lval (lv, t) ->
let lv = build_lval builder lv in
let t = build_scalar_t builder t in
Lval (lv, t)
| AddrOf lv ->
let lv = build_lval builder lv in
AddrOf lv
| AddrOfFun f -> AddrOfFun f
| UnOp (op, e) ->
let op = build_unop builder op in
let e = build_exp builder e in
UnOp (op, e)
| BinOp (op, e1, e2) ->
let op = build_binop builder op in
let e1 = build_exp builder e1 in
let e2 = build_exp builder e2 in
BinOp (op, e1, e2)
in
builder#process_exp e
and build_unop builder op =
match op with
N.PtrToInt k ->
let k = build_ikind builder k in
N.PtrToInt k
| N.IntToPtr k ->
let k = build_ikind builder k in
N.IntToPtr k
| N.Cast (t1, t2) ->
let t1 = build_scalar_t builder t1 in
let t2 = build_scalar_t builder t2 in
N.Cast (t1, t2)
| N.Focus sz -> N.Focus (build_size_t builder sz)
| N.Belongs _ | N.Coerce _ | N.Not | N.BNot _-> op
and build_binop builder op =
match op with
N.PlusF sz -> N.PlusF (build_size_t builder sz)
| N.MinusF sz -> N.MinusF (build_size_t builder sz)
| N.MultF sz -> N.MultF (build_size_t builder sz)
| N.DivF sz -> N.DivF (build_size_t builder sz)
| N.MinusPP -> N.MinusPP
| N.Gt t -> N.Gt (build_scalar_t builder t)
| N.Eq t -> N.Eq (build_scalar_t builder t)
| N.PlusI | N.MinusI | N.MultI | N.DivI | N.Mod
| N.BOr _ | N.BAnd _ | N.BXor _ | N.Shiftlt | N.Shiftrt | N.PlusPI -> op
|
5e53bb1bd747cbb4292a046a91f4c388e7b38a9fc9b533250c2cbd21413885d9 | minio/minio-hs | Spec.hs | --
MinIO Haskell SDK , ( C ) 2017 , 2018 MinIO , Inc.
--
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- -2.0
--
-- Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
import qualified Data.ByteString as B
import qualified Data.List as L
import Lib.Prelude
import Network.Minio.API.Test
import Network.Minio.CopyObject
import Network.Minio.Data
import Network.Minio.PutObject
import Network.Minio.Utils.Test
import Network.Minio.XmlGenerator.Test
import Network.Minio.XmlParser.Test
import Test.Tasty
import Test.Tasty.QuickCheck as QC
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [properties, unitTests]
properties :: TestTree
properties = testGroup "Properties" [qcProps] -- [scProps]
scProps = testGroup " ( checked by SmallCheck ) "
-- [ SC.testProperty "sort == sort . reverse" $
-- \list -> sort (list :: [Int]) == sort (reverse list)
, SC.testProperty " Fermat 's little theorem " $
\x - > ( ( x : : Integer)^7 - x ) ` mod ` 7 = = 0
-- -- the following property does not hold
, SC.testProperty " Fermat 's last theorem " $
-- \x y z n ->
( n : : Integer ) > = 3 SC.== > x^n + y^n /= ( z^n : : Integer )
-- ]
qcProps :: TestTree
qcProps =
testGroup
"(checked by QuickCheck)"
[ QC.testProperty "selectPartSizes:" $
\n ->
let (pns, offs, sizes) = L.unzip3 (selectPartSizes n)
check that pns increments from 1 .
isPNumsAscendingFrom1 = all (uncurry (==)) $ zip pns [1 ..]
consPairs [] = []
consPairs [_] = []
consPairs (a : (b : c)) = (a, b) : consPairs (b : c)
-- check `offs` is monotonically increasing.
isOffsetsAsc = all (uncurry (<)) $ consPairs offs
-- check sizes sums to n.
isSumSizeOk = sum sizes == n
-- check sizes are constant except last
isSizesConstantExceptLast =
all (uncurry (==)) (consPairs $ L.init sizes)
-- check each part except last is at least minPartSize;
-- last part may be 0 only if it is the only part.
nparts = length sizes
isMinPartSizeOk =
if
| nparts > 1 -> -- last part can be smaller but > 0
all (>= minPartSize) (take (nparts - 1) sizes)
&& all (> 0) (drop (nparts - 1) sizes)
| nparts == 1 -> -- size may be 0 here.
maybe True (\x -> x >= 0 && x <= minPartSize) $
listToMaybe sizes
| otherwise -> False
in n < 0
|| ( isPNumsAscendingFrom1
&& isOffsetsAsc
&& isSumSizeOk
&& isSizesConstantExceptLast
&& isMinPartSizeOk
),
QC.testProperty "selectCopyRanges:" $
\(start, end) ->
let (_, pairs) = L.unzip (selectCopyRanges (start, end))
is last part 's snd offset end ?
isLastPartOk = maybe False ((end ==) . snd) $ lastMay pairs
is first part 's fst offset start
isFirstPartOk = maybe False ((start ==) . fst) $ listToMaybe pairs
-- each pair is >=64MiB except last, and all those parts
-- have same size.
initSizes = maybe [] (map (\(a, b) -> b - a + 1) . init) (nonEmpty pairs)
isPartSizesOk =
all (>= minPartSize) initSizes
&& maybe
True
(\k -> all (== k) initSizes)
(listToMaybe initSizes)
-- returned offsets are contiguous.
fsts = drop 1 $ map fst pairs
snds = take (length pairs - 1) $ map snd pairs
isContParts =
length fsts == length snds
&& all (\(a, b) -> a == b + 1) (zip fsts snds)
in start < 0
|| start > end
|| (isLastPartOk && isFirstPartOk && isPartSizesOk && isContParts),
QC.testProperty "mkSSECKey:" $
\w8s ->
let bs = B.pack w8s
r = mkSSECKey bs
in case r of
Just _ -> B.length bs == 32
Nothing -> B.length bs /= 32
]
unitTests :: TestTree
unitTests =
testGroup
"Unit tests"
[ xmlGeneratorTests,
xmlParserTests,
bucketNameValidityTests,
objectNameValidityTests,
parseServerInfoJSONTest,
parseHealStatusTest,
parseHealStartRespTest,
limitedMapConcurrentlyTests
]
| null | https://raw.githubusercontent.com/minio/minio-hs/d59f45fec4481313cfb5fafd635558ce385e7422/test/Spec.hs | haskell |
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.
[scProps]
[ SC.testProperty "sort == sort . reverse" $
\list -> sort (list :: [Int]) == sort (reverse list)
-- the following property does not hold
\x y z n ->
]
check `offs` is monotonically increasing.
check sizes sums to n.
check sizes are constant except last
check each part except last is at least minPartSize;
last part may be 0 only if it is the only part.
last part can be smaller but > 0
size may be 0 here.
each pair is >=64MiB except last, and all those parts
have same size.
returned offsets are contiguous. | MinIO Haskell SDK , ( C ) 2017 , 2018 MinIO , Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
import qualified Data.ByteString as B
import qualified Data.List as L
import Lib.Prelude
import Network.Minio.API.Test
import Network.Minio.CopyObject
import Network.Minio.Data
import Network.Minio.PutObject
import Network.Minio.Utils.Test
import Network.Minio.XmlGenerator.Test
import Network.Minio.XmlParser.Test
import Test.Tasty
import Test.Tasty.QuickCheck as QC
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [properties, unitTests]
properties :: TestTree
scProps = testGroup " ( checked by SmallCheck ) "
, SC.testProperty " Fermat 's little theorem " $
\x - > ( ( x : : Integer)^7 - x ) ` mod ` 7 = = 0
, SC.testProperty " Fermat 's last theorem " $
( n : : Integer ) > = 3 SC.== > x^n + y^n /= ( z^n : : Integer )
qcProps :: TestTree
qcProps =
testGroup
"(checked by QuickCheck)"
[ QC.testProperty "selectPartSizes:" $
\n ->
let (pns, offs, sizes) = L.unzip3 (selectPartSizes n)
check that pns increments from 1 .
isPNumsAscendingFrom1 = all (uncurry (==)) $ zip pns [1 ..]
consPairs [] = []
consPairs [_] = []
consPairs (a : (b : c)) = (a, b) : consPairs (b : c)
isOffsetsAsc = all (uncurry (<)) $ consPairs offs
isSumSizeOk = sum sizes == n
isSizesConstantExceptLast =
all (uncurry (==)) (consPairs $ L.init sizes)
nparts = length sizes
isMinPartSizeOk =
if
all (>= minPartSize) (take (nparts - 1) sizes)
&& all (> 0) (drop (nparts - 1) sizes)
maybe True (\x -> x >= 0 && x <= minPartSize) $
listToMaybe sizes
| otherwise -> False
in n < 0
|| ( isPNumsAscendingFrom1
&& isOffsetsAsc
&& isSumSizeOk
&& isSizesConstantExceptLast
&& isMinPartSizeOk
),
QC.testProperty "selectCopyRanges:" $
\(start, end) ->
let (_, pairs) = L.unzip (selectCopyRanges (start, end))
is last part 's snd offset end ?
isLastPartOk = maybe False ((end ==) . snd) $ lastMay pairs
is first part 's fst offset start
isFirstPartOk = maybe False ((start ==) . fst) $ listToMaybe pairs
initSizes = maybe [] (map (\(a, b) -> b - a + 1) . init) (nonEmpty pairs)
isPartSizesOk =
all (>= minPartSize) initSizes
&& maybe
True
(\k -> all (== k) initSizes)
(listToMaybe initSizes)
fsts = drop 1 $ map fst pairs
snds = take (length pairs - 1) $ map snd pairs
isContParts =
length fsts == length snds
&& all (\(a, b) -> a == b + 1) (zip fsts snds)
in start < 0
|| start > end
|| (isLastPartOk && isFirstPartOk && isPartSizesOk && isContParts),
QC.testProperty "mkSSECKey:" $
\w8s ->
let bs = B.pack w8s
r = mkSSECKey bs
in case r of
Just _ -> B.length bs == 32
Nothing -> B.length bs /= 32
]
unitTests :: TestTree
unitTests =
testGroup
"Unit tests"
[ xmlGeneratorTests,
xmlParserTests,
bucketNameValidityTests,
objectNameValidityTests,
parseServerInfoJSONTest,
parseHealStatusTest,
parseHealStartRespTest,
limitedMapConcurrentlyTests
]
|
f5d03261ceff7744537731656713503b48639aaf4d0639bdfa151ff9166935f8 | racket/redex | all-info.rkt | #lang racket/base
(require racket/runtime-path
racket/list
racket/path)
(provide all-mods)
(define-runtime-path here ".")
(define (all-info-files)
(for/list ([f (in-directory here)]
#:when (and (file-exists? f)
(regexp-match #rx"^.*info\\.rkt$"
(path->string f)))
#:unless (regexp-match #rx".*all-info.*"
(path->string f)))
(path->string
(find-relative-path (simplify-path (current-directory))
(simplify-path f)))))
(define (all-mods)
(append-map (λ (f)
((dynamic-require f 'all-mods)))
(all-info-files)))
| null | https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-benchmark/redex/benchmark/models/all-info.rkt | racket | #lang racket/base
(require racket/runtime-path
racket/list
racket/path)
(provide all-mods)
(define-runtime-path here ".")
(define (all-info-files)
(for/list ([f (in-directory here)]
#:when (and (file-exists? f)
(regexp-match #rx"^.*info\\.rkt$"
(path->string f)))
#:unless (regexp-match #rx".*all-info.*"
(path->string f)))
(path->string
(find-relative-path (simplify-path (current-directory))
(simplify-path f)))))
(define (all-mods)
(append-map (λ (f)
((dynamic-require f 'all-mods)))
(all-info-files)))
|
|
6be9412c9dcc1ba2727f18203a55394c938dd40ffc2c80a0ab176b9b04945ea1 | alanz/ghc-exactprint | Q.hs | module Q where
import qualified Map
import Map(Map)
mymember :: Int -> Map Int a -> Bool
mymember k m = Map.member k m || Map.member (k + 1) m
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/Q.hs | haskell | module Q where
import qualified Map
import Map(Map)
mymember :: Int -> Map Int a -> Bool
mymember k m = Map.member k m || Map.member (k + 1) m
|
|
2fb790f34622b4bf40609a8341057f20b0decce39680b9c32f553f566e266772 | ChrisTitusTech/gimphelp | 210_edges_trans-border.scm | 210_edges_trans-border.scm
last modified / tested by [ gimphelp.org ]
05/11/2019 on GIMP 2.10.10
;==================================================
;
; Installation:
; This script should be placed in the user or system-wide script folder.
;
; Windows 7/10
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
C:\Users\YOUR - NAME\AppData\Roaming\GIMP\2.10\scripts
;
;
; Linux
; /home/yourname/.config/GIMP/2.10/scripts
; or
; Linux system-wide
; /usr/share/gimp/2.0/scripts
;
;==================================================
;
; LICENSE
;
; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program. If not, see </>.
;
;==============================================================
; Original information
;
; Translucent Border is a script for The GIMP
Creates a border with reduced brightness and 2 inner colours .
; The script is located in menu "<Image>/Script-Fu/Edges/Translucent Border"
Last changed : 7 August 2007
;
Copyright ( C ) 2007 < >
;==============================================================
(define (210-trans-border
theImage
theLayer
innerColour
innerSize
outerColour
outerSize
borderType
borderSize
borderPercent
borderBrightness
)
(let*
(
;Read the current colours
(myForeground (car (gimp-context-get-foreground)))
(myBackground (car (gimp-context-get-background)))
;Read the image width and height
(imageWidth (car (gimp-image-width theImage)))
(imageHeight (car (gimp-image-height theImage)))
(selectWidth)
(selectHeight)
(outerLayer)
(innerLayer)
(mask)
(co-ord)
(sizeBAD FALSE)
(copyBack)
)
;Calculate the selection sizes
(if (= borderType 0)
;Set the co-ord to the pixel size
(set! co-ord borderSize)
(begin
;Set the co-ord to a percentage of the shortest side
(if (> imageWidth imageHeight)
(set! co-ord (/ (* imageHeight borderPercent) 100))
(set! co-ord (/ (* imageWidth borderPercent) 100)))
)
)
;Check the width
(if (< imageWidth (+ innerSize (+ outerSize (* 2 borderSize))))
(set! sizeBAD TRUE)
())
;Check the height
(if (< imageHeight (+ innerSize (+ outerSize (* 2 borderSize))))
(set! sizeBAD TRUE)
())
;Give an error message if the size is not ok
(if (= sizeBAD TRUE)
(gimp-message "The image is not large enough for that border size")
(begin
Start an undo group so the process can be undone with one undo
(gimp-image-undo-group-start theImage)
;Copy the layer
(set! copyBack (car (gimp-layer-copy theLayer 1)))
;Select none
(gimp-selection-none theImage)
;Set the foreground and background colours
(gimp-context-set-foreground outerColour)
(gimp-context-set-background innerColour)
Add the first layer to the image
(gimp-image-insert-layer theImage copyBack 0 0)
;Rename the layer
(gimp-item-set-name copyBack "Original")
;Set the brightness of the background layer
(gimp-brightness-contrast theLayer borderBrightness 0)
;Calculate the selection size
(set! selectWidth (- imageWidth (* co-ord 2)))
(set! selectHeight (- imageHeight (* co-ord 2)))
Select the first part
(gimp-image-select-rectangle theImage CHANNEL-OP-REPLACE co-ord co-ord selectWidth selectHeight)
;Add the outer layer
(set! outerLayer (car (gimp-layer-new theImage imageWidth imageHeight 1 "Outer" 100 0)))
(gimp-image-insert-layer theImage outerLayer 0 1)
Fill the layer with FG colour
(gimp-edit-fill outerLayer 0)
;Add a layer mask
(set! mask (car (gimp-layer-create-mask outerLayer 4)))
(gimp-layer-add-mask outerLayer mask)
;Add the inner layer(car (gimp-context-get-foreground))
(set! innerLayer (car (gimp-layer-new theImage imageWidth imageHeight 1 "Inner" 100 0)))
(gimp-image-insert-layer theImage innerLayer 0 1)
Fill the layer with BG colour
(gimp-edit-fill innerLayer 1)
;Reduce the selection by the outer amount
(gimp-selection-shrink theImage outerSize)
;Add a layer mask
(set! mask (car (gimp-layer-create-mask innerLayer 4)))
(gimp-layer-add-mask innerLayer mask)
;Reduce the selection by the inner amount
(gimp-selection-shrink theImage innerSize)
;Add a layer mask to the original
(set! mask (car (gimp-layer-create-mask copyBack 4)))
(gimp-layer-add-mask copyBack mask)
;Select none
(gimp-selection-none theImage)
Set the FG and BG colours back to what they were
(gimp-context-set-foreground myForeground)
(gimp-context-set-background myBackground)
;Finish the undo group for the process
(gimp-image-undo-group-end theImage)
;Ensure the updated image is displayed now
(gimp-displays-flush)
))))
(script-fu-register "210-trans-border"
"Translucent Border"
"Gives a transparent border with two inner lines"
"Harry Phillips"
"Harry Phillips"
"Mar. 16 2007"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-COLOR "Inner colour" '(255 255 255)
SF-ADJUSTMENT "Inner size" '(5 0 50 1 1 0 0)
SF-COLOR "Outer colour" '(0 0 0)
SF-ADJUSTMENT "Outer size" '(5 0 50 1 1 0 0)
SF-OPTION "Border type" '("Pixels" "Percentage")
SF-ADJUSTMENT "Border pixels" '(200 0 1000 1 1 0 0)
SF-ADJUSTMENT "Border percentage" '(10 0 100 1 1 0 0)
SF-ADJUSTMENT "Border brightness" '(-80 -127 0 1 1 0 1)
)
(script-fu-menu-register "210-trans-border" "<Image>/Script-Fu/Edges")
| null | https://raw.githubusercontent.com/ChrisTitusTech/gimphelp/fdbc7e3671ce6bd74cefd83ecf7216e5ee0f1542/gimp_scripts-2.10/210_edges_trans-border.scm | scheme | ==================================================
Installation:
This script should be placed in the user or system-wide script folder.
Windows 7/10
or
Linux
/home/yourname/.config/GIMP/2.10/scripts
or
Linux system-wide
/usr/share/gimp/2.0/scripts
==================================================
LICENSE
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
==============================================================
Original information
Translucent Border is a script for The GIMP
The script is located in menu "<Image>/Script-Fu/Edges/Translucent Border"
==============================================================
Read the current colours
Read the image width and height
Calculate the selection sizes
Set the co-ord to the pixel size
Set the co-ord to a percentage of the shortest side
Check the width
Check the height
Give an error message if the size is not ok
Copy the layer
Select none
Set the foreground and background colours
Rename the layer
Set the brightness of the background layer
Calculate the selection size
Add the outer layer
Add a layer mask
Add the inner layer(car (gimp-context-get-foreground))
Reduce the selection by the outer amount
Add a layer mask
Reduce the selection by the inner amount
Add a layer mask to the original
Select none
Finish the undo group for the process
Ensure the updated image is displayed now | 210_edges_trans-border.scm
last modified / tested by [ gimphelp.org ]
05/11/2019 on GIMP 2.10.10
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
C:\Users\YOUR - NAME\AppData\Roaming\GIMP\2.10\scripts
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
Creates a border with reduced brightness and 2 inner colours .
Last changed : 7 August 2007
Copyright ( C ) 2007 < >
(define (210-trans-border
theImage
theLayer
innerColour
innerSize
outerColour
outerSize
borderType
borderSize
borderPercent
borderBrightness
)
(let*
(
(myForeground (car (gimp-context-get-foreground)))
(myBackground (car (gimp-context-get-background)))
(imageWidth (car (gimp-image-width theImage)))
(imageHeight (car (gimp-image-height theImage)))
(selectWidth)
(selectHeight)
(outerLayer)
(innerLayer)
(mask)
(co-ord)
(sizeBAD FALSE)
(copyBack)
)
(if (= borderType 0)
(set! co-ord borderSize)
(begin
(if (> imageWidth imageHeight)
(set! co-ord (/ (* imageHeight borderPercent) 100))
(set! co-ord (/ (* imageWidth borderPercent) 100)))
)
)
(if (< imageWidth (+ innerSize (+ outerSize (* 2 borderSize))))
(set! sizeBAD TRUE)
())
(if (< imageHeight (+ innerSize (+ outerSize (* 2 borderSize))))
(set! sizeBAD TRUE)
())
(if (= sizeBAD TRUE)
(gimp-message "The image is not large enough for that border size")
(begin
Start an undo group so the process can be undone with one undo
(gimp-image-undo-group-start theImage)
(set! copyBack (car (gimp-layer-copy theLayer 1)))
(gimp-selection-none theImage)
(gimp-context-set-foreground outerColour)
(gimp-context-set-background innerColour)
Add the first layer to the image
(gimp-image-insert-layer theImage copyBack 0 0)
(gimp-item-set-name copyBack "Original")
(gimp-brightness-contrast theLayer borderBrightness 0)
(set! selectWidth (- imageWidth (* co-ord 2)))
(set! selectHeight (- imageHeight (* co-ord 2)))
Select the first part
(gimp-image-select-rectangle theImage CHANNEL-OP-REPLACE co-ord co-ord selectWidth selectHeight)
(set! outerLayer (car (gimp-layer-new theImage imageWidth imageHeight 1 "Outer" 100 0)))
(gimp-image-insert-layer theImage outerLayer 0 1)
Fill the layer with FG colour
(gimp-edit-fill outerLayer 0)
(set! mask (car (gimp-layer-create-mask outerLayer 4)))
(gimp-layer-add-mask outerLayer mask)
(set! innerLayer (car (gimp-layer-new theImage imageWidth imageHeight 1 "Inner" 100 0)))
(gimp-image-insert-layer theImage innerLayer 0 1)
Fill the layer with BG colour
(gimp-edit-fill innerLayer 1)
(gimp-selection-shrink theImage outerSize)
(set! mask (car (gimp-layer-create-mask innerLayer 4)))
(gimp-layer-add-mask innerLayer mask)
(gimp-selection-shrink theImage innerSize)
(set! mask (car (gimp-layer-create-mask copyBack 4)))
(gimp-layer-add-mask copyBack mask)
(gimp-selection-none theImage)
Set the FG and BG colours back to what they were
(gimp-context-set-foreground myForeground)
(gimp-context-set-background myBackground)
(gimp-image-undo-group-end theImage)
(gimp-displays-flush)
))))
(script-fu-register "210-trans-border"
"Translucent Border"
"Gives a transparent border with two inner lines"
"Harry Phillips"
"Harry Phillips"
"Mar. 16 2007"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-COLOR "Inner colour" '(255 255 255)
SF-ADJUSTMENT "Inner size" '(5 0 50 1 1 0 0)
SF-COLOR "Outer colour" '(0 0 0)
SF-ADJUSTMENT "Outer size" '(5 0 50 1 1 0 0)
SF-OPTION "Border type" '("Pixels" "Percentage")
SF-ADJUSTMENT "Border pixels" '(200 0 1000 1 1 0 0)
SF-ADJUSTMENT "Border percentage" '(10 0 100 1 1 0 0)
SF-ADJUSTMENT "Border brightness" '(-80 -127 0 1 1 0 1)
)
(script-fu-menu-register "210-trans-border" "<Image>/Script-Fu/Edges")
|
1d2ba8aaaad8d780a6d6f40832ada82b35ebbdcdc0e430e041dc5ccef4582e26 | roehst/tapl-implementations | core.ml | open Format
open Syntax
open Support.Error
open Support.Pervasive
(* ------------------------ EVALUATION ------------------------ *)
let rec isnumericval ctx t = match t with
TmZero(_) -> true
| TmSucc(_,t1) -> isnumericval ctx t1
| _ -> false
let rec isval ctx t = match t with
TmString _ -> true
| TmUnit(_) -> true
| TmLoc(_,_) -> true
| TmFloat _ -> true
| TmTrue(_) -> true
| TmFalse(_) -> true
| t when isnumericval ctx t -> true
| TmAbs(_,_,_,_) -> true
| TmRecord(_,fields) -> List.for_all (fun (l,ti) -> isval ctx ti) fields
| TmPack(_,_,v1,_) when isval ctx v1 -> true
| TmTAbs(_,_,_,_) -> true
| _ -> false
type store = term list
let emptystore = []
let extendstore store v = (List.length store, List.append store [v])
let lookuploc store l = List.nth store l
let updatestore store n v =
let rec f s = match s with
(0, v'::rest) -> v::rest
| (n, v'::rest) -> v' :: (f (n-1,rest))
| _ -> error dummyinfo "updatestore: bad index"
in
f (n,store)
let shiftstore i store = List.map (fun t -> termShift i t) store
exception NoRuleApplies
let rec eval1 ctx store t = match t with
TmAscribe(fi,v1,tyT) when isval ctx v1 ->
v1, store
| TmAscribe(fi,t1,tyT) ->
let t1',store' = eval1 ctx store t1 in
TmAscribe(fi,t1',tyT), store'
| TmApp(fi,TmAbs(_,x,tyT11,t12),v2) when isval ctx v2 ->
termSubstTop v2 t12, store
| TmApp(fi,v1,t2) when isval ctx v1 ->
let t2',store' = eval1 ctx store t2 in
TmApp(fi, v1, t2'), store'
| TmApp(fi,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmApp(fi, t1', t2), store'
| TmRecord(fi,fields) ->
let rec evalafield l = match l with
[] -> raise NoRuleApplies
| (l,vi)::rest when isval ctx vi ->
let rest',store' = evalafield rest in
(l,vi)::rest', store'
| (l,ti)::rest ->
let ti',store' = eval1 ctx store ti in
(l, ti')::rest, store'
in let fields',store' = evalafield fields in
TmRecord(fi, fields'), store'
| TmProj(fi, (TmRecord(_, fields) as v1), l) when isval ctx v1 ->
(try List.assoc l fields, store
with Not_found -> raise NoRuleApplies)
| TmProj(fi, t1, l) ->
let t1',store' = eval1 ctx store t1 in
TmProj(fi, t1', l), store'
| TmRef(fi,t1) ->
if not (isval ctx t1) then
let (t1',store') = eval1 ctx store t1
in (TmRef(fi,t1'), store')
else
let (l,store') = extendstore store t1 in
(TmLoc(dummyinfo,l), store')
| TmDeref(fi,t1) ->
if not (isval ctx t1) then
let (t1',store') = eval1 ctx store t1
in (TmDeref(fi,t1'), store')
else (match t1 with
TmLoc(_,l) -> (lookuploc store l, store)
| _ -> raise NoRuleApplies)
| TmAssign(fi,t1,t2) ->
if not (isval ctx t1) then
let (t1',store') = eval1 ctx store t1
in (TmAssign(fi,t1',t2), store')
else if not (isval ctx t2) then
let (t2',store') = eval1 ctx store t2
in (TmAssign(fi,t1,t2'), store')
else (match t1 with
TmLoc(_,l) -> (TmUnit(dummyinfo), updatestore store l t2)
| _ -> raise NoRuleApplies)
| TmTimesfloat(fi,TmFloat(_,f1),TmFloat(_,f2)) ->
TmFloat(fi, f1 *. f2), store
| TmTimesfloat(fi,(TmFloat(_,f1) as t1),t2) ->
let t2',store' = eval1 ctx store t2 in
TmTimesfloat(fi,t1,t2') , store'
| TmTimesfloat(fi,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmTimesfloat(fi,t1',t2) , store'
| TmLet(fi,x,v1,t2) when isval ctx v1 ->
termSubstTop v1 t2, store
| TmLet(fi,x,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmLet(fi, x, t1', t2), store'
| TmIf(_,TmTrue(_),t2,t3) ->
t2, store
| TmIf(_,TmFalse(_),t2,t3) ->
t3, store
| TmIf(fi,t1,t2,t3) ->
let t1',store' = eval1 ctx store t1 in
TmIf(fi, t1', t2, t3), store'
| TmSucc(fi,t1) ->
let t1',store' = eval1 ctx store t1 in
TmSucc(fi, t1'), store'
| TmPred(_,TmZero(_)) ->
TmZero(dummyinfo), store
| TmPred(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
nv1, store
| TmPred(fi,t1) ->
let t1',store' = eval1 ctx store t1 in
TmPred(fi, t1'), store'
| TmIsZero(_,TmZero(_)) ->
TmTrue(dummyinfo), store
| TmIsZero(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
TmFalse(dummyinfo), store
| TmIsZero(fi,t1) ->
let t1',store' = eval1 ctx store t1 in
TmIsZero(fi, t1'), store'
| TmFix(fi,v1) as t when isval ctx v1 ->
(match v1 with
TmAbs(_,_,_,t12) -> termSubstTop t t12, store
| _ -> raise NoRuleApplies)
| TmFix(fi,t1) ->
let t1',store' = eval1 ctx store t1
in TmFix(fi,t1'), store'
| TmTApp(fi,TmTAbs(_,x,_,t11),tyT2) ->
tytermSubstTop tyT2 t11, store
| TmTApp(fi,t1,tyT2) ->
let t1',store' = eval1 ctx store t1 in
TmTApp(fi, t1', tyT2), store'
| TmUnpack(fi,_,_,TmPack(_,tyT11,v12,_),t2) when isval ctx v12 ->
tytermSubstTop tyT11 (termSubstTop (termShift 1 v12) t2), store
| TmUnpack(fi,tyX,x,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmUnpack(fi,tyX,x,t1',t2), store'
| TmPack(fi,tyT1,t2,tyT3) ->
let t2',store' = eval1 ctx store t2 in
TmPack(fi,tyT1,t2',tyT3), store'
| TmVar(fi,n,_) ->
(match getbinding fi ctx n with
TmAbbBind(t,_) -> t,store
| _ -> raise NoRuleApplies)
| _ ->
raise NoRuleApplies
let rec eval ctx store t =
try let t',store' = eval1 ctx store t
in eval ctx store' t'
with NoRuleApplies -> t,store
------------------------ KINDING ------------------------
let istyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT,_) -> true
| _ -> false
let gettyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT,_) -> tyT
| _ -> raise NoRuleApplies
let rec computety ctx tyT = match tyT with
TyVar(i,_) when istyabb ctx i -> gettyabb ctx i
| TyApp(TyAbs(_,_,tyT12),tyT2) -> typeSubstTop tyT2 tyT12
| _ -> raise NoRuleApplies
let rec simplifyty ctx tyT =
let tyT =
match tyT with
TyApp(tyT1,tyT2) -> TyApp(simplifyty ctx tyT1,tyT2)
| tyT -> tyT
in
try
let tyT' = computety ctx tyT in
simplifyty ctx tyT'
with NoRuleApplies -> tyT
let rec tyeqv ctx tyS tyT =
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyString,TyString) -> true
| (TyId(b1),TyId(b2)) -> b1=b2
| (TyUnit,TyUnit) -> true
| (TyRef(tyT1),TyRef(tyT2)) -> tyeqv ctx tyT1 tyT2
| (TyFloat,TyFloat) -> true
| (TyVar(i,_), _) when istyabb ctx i ->
tyeqv ctx (gettyabb ctx i) tyT
| (_, TyVar(i,_)) when istyabb ctx i ->
tyeqv ctx tyS (gettyabb ctx i)
| (TyVar(i,_),TyVar(j,_)) -> i=j
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(tyeqv ctx tyS1 tyT1) && (tyeqv ctx tyS2 tyT2)
| (TyBool,TyBool) -> true
| (TyNat,TyNat) -> true
| (TyRecord(fields1),TyRecord(fields2)) ->
List.length fields1 = List.length fields2
&&
List.for_all
(fun (li2,tyTi2) ->
try let (tyTi1) = List.assoc li2 fields1 in
tyeqv ctx tyTi1 tyTi2
with Not_found -> false)
fields2
| (TySome(tyX1,knK1,tyS2),TySome(_,knK1',tyT2)) ->
(=) knK1 knK1' &&
let ctx1 = addname ctx tyX1 in
tyeqv ctx1 tyS2 tyT2
| (TyAll(tyX1,knK1,tyS2),TyAll(_,knK2,tyT2)) ->
let ctx1 = addname ctx tyX1 in
(=) knK1 knK2 && tyeqv ctx1 tyS2 tyT2
| (TyAbs(tyX1,knKS1,tyS2),TyAbs(_,knKT1,tyT2)) ->
((=) knKS1 knKT1)
&&
(let ctx = addname ctx tyX1 in
tyeqv ctx tyS2 tyT2)
| (TyApp(tyS1,tyS2),TyApp(tyT1,tyT2)) ->
(tyeqv ctx tyS1 tyT1) && (tyeqv ctx tyS2 tyT2)
| _ -> false
let getkind fi ctx i =
match getbinding fi ctx i with
TyVarBind(knK) -> knK
| TyAbbBind(_,Some(knK)) -> knK
| TyAbbBind(_,None) -> error fi ("No kind recorded for variable "
^ (index2name fi ctx i))
| _ -> error fi ("getkind: Wrong kind of binding for variable "
^ (index2name fi ctx i))
let rec kindof ctx tyT = match tyT with
TyArr(tyT1,tyT2) ->
if kindof ctx tyT1 <> KnStar then error dummyinfo "star kind expected";
if kindof ctx tyT2 <> KnStar then error dummyinfo "star kind expected";
KnStar
| TyVar(i,_) ->
let knK = getkind dummyinfo ctx i
in knK
| TyRecord(fldtys) ->
List.iter (fun (l,tyS) ->
if kindof ctx tyS<>KnStar then error dummyinfo "Kind * expected")
fldtys;
KnStar
| TyAll(tyX,knK1,tyT2) ->
let ctx' = addbinding ctx tyX (TyVarBind knK1) in
if kindof ctx' tyT2 <> KnStar then error dummyinfo "Kind * expected";
KnStar
| TyAbs(tyX,knK1,tyT2) ->
let ctx' = addbinding ctx tyX (TyVarBind(knK1)) in
let knK2 = kindof ctx' tyT2 in
KnArr(knK1,knK2)
| TyApp(tyT1,tyT2) ->
let knK1 = kindof ctx tyT1 in
let knK2 = kindof ctx tyT2 in
(match knK1 with
KnArr(knK11,knK12) ->
if (=) knK2 knK11 then knK12
else error dummyinfo "parameter kind mismatch"
| _ -> error dummyinfo "arrow kind expected")
| TySome(tyX,knK,tyT2) ->
let ctx' = addbinding ctx tyX (TyVarBind(knK)) in
if kindof ctx' tyT2 <> KnStar then error dummyinfo "Kind * expected";
KnStar
| _ -> KnStar
let checkkindstar fi ctx tyT =
let k = kindof ctx tyT in
if k = KnStar then ()
else error fi "Kind * expected"
(* ------------------------ TYPING ------------------------ *)
let rec typeof ctx t =
match t with
TmInert(fi,tyT) ->
tyT
| TmAscribe(fi,t1,tyT) ->
checkkindstar fi ctx tyT;
if tyeqv ctx (typeof ctx t1) tyT then
tyT
else
error fi "body of as-term does not have the expected type"
| TmVar(fi,i,_) -> getTypeFromContext fi ctx i
| TmAbs(fi,x,tyT1,t2) ->
checkkindstar fi ctx tyT1;
let ctx' = addbinding ctx x (VarBind(tyT1)) in
let tyT2 = typeof ctx' t2 in
TyArr(tyT1, typeShift (-1) tyT2)
| TmApp(fi,t1,t2) ->
let tyT1 = typeof ctx t1 in
let tyT2 = typeof ctx t2 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if tyeqv ctx tyT2 tyT11 then tyT12
else error fi "parameter type mismatch"
| _ -> error fi "arrow type expected")
| TmString _ -> TyString
| TmUnit(fi) -> TyUnit
| TmRef(fi,t1) ->
TyRef(typeof ctx t1)
| TmLoc(fi,l) ->
error fi "locations are not supposed to occur in source programs!"
| TmDeref(fi,t1) ->
(match simplifyty ctx (typeof ctx t1) with
TyRef(tyT1) -> tyT1
| _ -> error fi "argument of ! is not a Ref")
| TmAssign(fi,t1,t2) ->
(match simplifyty ctx (typeof ctx t1) with
TyRef(tyT1) ->
if tyeqv ctx (typeof ctx t2) tyT1 then
TyUnit
else
error fi "arguments of := are incompatible"
| _ -> error fi "argument of ! is not a Ref")
| TmRecord(fi, fields) ->
let fieldtys =
List.map (fun (li,ti) -> (li, typeof ctx ti)) fields in
TyRecord(fieldtys)
| TmProj(fi, t1, l) ->
(match simplifyty ctx (typeof ctx t1) with
TyRecord(fieldtys) ->
(try List.assoc l fieldtys
with Not_found -> error fi ("label "^l^" not found"))
| _ -> error fi "Expected record type")
| TmTrue(fi) ->
TyBool
| TmFalse(fi) ->
TyBool
| TmIf(fi,t1,t2,t3) ->
if tyeqv ctx (typeof ctx t1) TyBool then
let tyT2 = typeof ctx t2 in
if tyeqv ctx tyT2 (typeof ctx t3) then tyT2
else error fi "arms of conditional have different types"
else error fi "guard of conditional not a boolean"
| TmLet(fi,x,t1,t2) ->
let tyT1 = typeof ctx t1 in
let ctx' = addbinding ctx x (VarBind(tyT1)) in
typeShift (-1) (typeof ctx' t2)
| TmFloat _ -> TyFloat
| TmTimesfloat(fi,t1,t2) ->
if tyeqv ctx (typeof ctx t1) TyFloat
&& tyeqv ctx (typeof ctx t2) TyFloat then TyFloat
else error fi "argument of timesfloat is not a number"
| TmFix(fi, t1) ->
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if tyeqv ctx tyT12 tyT11 then tyT12
else error fi "result of body not compatible with domain"
| _ -> error fi "arrow type expected")
| TmTAbs(fi,tyX,knK1,t2) ->
let ctx = addbinding ctx tyX (TyVarBind(knK1)) in
let tyT2 = typeof ctx t2 in
TyAll(tyX,knK1,tyT2)
| TmTApp(fi,t1,tyT2) ->
let knKT2 = kindof ctx tyT2 in
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TyAll(_,knK11,tyT12) ->
if knK11 <> knKT2 then
error fi "Type argument has wrong kind";
typeSubstTop tyT2 tyT12
| _ -> error fi "universal type expected")
| TmZero(fi) ->
TyNat
| TmSucc(fi,t1) ->
if tyeqv ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of succ is not a number"
| TmPred(fi,t1) ->
if tyeqv ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of pred is not a number"
| TmIsZero(fi,t1) ->
if tyeqv ctx (typeof ctx t1) TyNat then TyBool
else error fi "argument of iszero is not a number"
| TmPack(fi,tyT1,t2,tyT) ->
checkkindstar fi ctx tyT;
(match simplifyty ctx tyT with
TySome(tyY,k,tyT2) ->
if kindof ctx tyT1 <> k then
error fi "type component does not have expected kind";
let tyU = typeof ctx t2 in
let tyU' = typeSubstTop tyT1 tyT2 in
if tyeqv ctx tyU tyU' then tyT
else error fi "doesn't match declared type"
| _ -> error fi "existential type expected")
| TmUnpack(fi,tyX,x,t1,t2) ->
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TySome(tyY,k,tyT11) ->
let ctx' = addbinding ctx tyX (TyVarBind k) in
let ctx'' = addbinding ctx' x (VarBind tyT11) in
let tyT2 = typeof ctx'' t2 in
typeShift (-2) tyT2
| _ -> error fi "existential type expected")
let evalbinding ctx store b = match b with
TmAbbBind(t,tyT) ->
let t',store' = eval ctx store t in
TmAbbBind(t',tyT), store'
| bind -> bind,store
| null | https://raw.githubusercontent.com/roehst/tapl-implementations/23c0dc505a8c0b0a797201a7e4e3e5b939dd8fdb/fullomega/core.ml | ocaml | ------------------------ EVALUATION ------------------------
------------------------ TYPING ------------------------ | open Format
open Syntax
open Support.Error
open Support.Pervasive
let rec isnumericval ctx t = match t with
TmZero(_) -> true
| TmSucc(_,t1) -> isnumericval ctx t1
| _ -> false
let rec isval ctx t = match t with
TmString _ -> true
| TmUnit(_) -> true
| TmLoc(_,_) -> true
| TmFloat _ -> true
| TmTrue(_) -> true
| TmFalse(_) -> true
| t when isnumericval ctx t -> true
| TmAbs(_,_,_,_) -> true
| TmRecord(_,fields) -> List.for_all (fun (l,ti) -> isval ctx ti) fields
| TmPack(_,_,v1,_) when isval ctx v1 -> true
| TmTAbs(_,_,_,_) -> true
| _ -> false
type store = term list
let emptystore = []
let extendstore store v = (List.length store, List.append store [v])
let lookuploc store l = List.nth store l
let updatestore store n v =
let rec f s = match s with
(0, v'::rest) -> v::rest
| (n, v'::rest) -> v' :: (f (n-1,rest))
| _ -> error dummyinfo "updatestore: bad index"
in
f (n,store)
let shiftstore i store = List.map (fun t -> termShift i t) store
exception NoRuleApplies
let rec eval1 ctx store t = match t with
TmAscribe(fi,v1,tyT) when isval ctx v1 ->
v1, store
| TmAscribe(fi,t1,tyT) ->
let t1',store' = eval1 ctx store t1 in
TmAscribe(fi,t1',tyT), store'
| TmApp(fi,TmAbs(_,x,tyT11,t12),v2) when isval ctx v2 ->
termSubstTop v2 t12, store
| TmApp(fi,v1,t2) when isval ctx v1 ->
let t2',store' = eval1 ctx store t2 in
TmApp(fi, v1, t2'), store'
| TmApp(fi,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmApp(fi, t1', t2), store'
| TmRecord(fi,fields) ->
let rec evalafield l = match l with
[] -> raise NoRuleApplies
| (l,vi)::rest when isval ctx vi ->
let rest',store' = evalafield rest in
(l,vi)::rest', store'
| (l,ti)::rest ->
let ti',store' = eval1 ctx store ti in
(l, ti')::rest, store'
in let fields',store' = evalafield fields in
TmRecord(fi, fields'), store'
| TmProj(fi, (TmRecord(_, fields) as v1), l) when isval ctx v1 ->
(try List.assoc l fields, store
with Not_found -> raise NoRuleApplies)
| TmProj(fi, t1, l) ->
let t1',store' = eval1 ctx store t1 in
TmProj(fi, t1', l), store'
| TmRef(fi,t1) ->
if not (isval ctx t1) then
let (t1',store') = eval1 ctx store t1
in (TmRef(fi,t1'), store')
else
let (l,store') = extendstore store t1 in
(TmLoc(dummyinfo,l), store')
| TmDeref(fi,t1) ->
if not (isval ctx t1) then
let (t1',store') = eval1 ctx store t1
in (TmDeref(fi,t1'), store')
else (match t1 with
TmLoc(_,l) -> (lookuploc store l, store)
| _ -> raise NoRuleApplies)
| TmAssign(fi,t1,t2) ->
if not (isval ctx t1) then
let (t1',store') = eval1 ctx store t1
in (TmAssign(fi,t1',t2), store')
else if not (isval ctx t2) then
let (t2',store') = eval1 ctx store t2
in (TmAssign(fi,t1,t2'), store')
else (match t1 with
TmLoc(_,l) -> (TmUnit(dummyinfo), updatestore store l t2)
| _ -> raise NoRuleApplies)
| TmTimesfloat(fi,TmFloat(_,f1),TmFloat(_,f2)) ->
TmFloat(fi, f1 *. f2), store
| TmTimesfloat(fi,(TmFloat(_,f1) as t1),t2) ->
let t2',store' = eval1 ctx store t2 in
TmTimesfloat(fi,t1,t2') , store'
| TmTimesfloat(fi,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmTimesfloat(fi,t1',t2) , store'
| TmLet(fi,x,v1,t2) when isval ctx v1 ->
termSubstTop v1 t2, store
| TmLet(fi,x,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmLet(fi, x, t1', t2), store'
| TmIf(_,TmTrue(_),t2,t3) ->
t2, store
| TmIf(_,TmFalse(_),t2,t3) ->
t3, store
| TmIf(fi,t1,t2,t3) ->
let t1',store' = eval1 ctx store t1 in
TmIf(fi, t1', t2, t3), store'
| TmSucc(fi,t1) ->
let t1',store' = eval1 ctx store t1 in
TmSucc(fi, t1'), store'
| TmPred(_,TmZero(_)) ->
TmZero(dummyinfo), store
| TmPred(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
nv1, store
| TmPred(fi,t1) ->
let t1',store' = eval1 ctx store t1 in
TmPred(fi, t1'), store'
| TmIsZero(_,TmZero(_)) ->
TmTrue(dummyinfo), store
| TmIsZero(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
TmFalse(dummyinfo), store
| TmIsZero(fi,t1) ->
let t1',store' = eval1 ctx store t1 in
TmIsZero(fi, t1'), store'
| TmFix(fi,v1) as t when isval ctx v1 ->
(match v1 with
TmAbs(_,_,_,t12) -> termSubstTop t t12, store
| _ -> raise NoRuleApplies)
| TmFix(fi,t1) ->
let t1',store' = eval1 ctx store t1
in TmFix(fi,t1'), store'
| TmTApp(fi,TmTAbs(_,x,_,t11),tyT2) ->
tytermSubstTop tyT2 t11, store
| TmTApp(fi,t1,tyT2) ->
let t1',store' = eval1 ctx store t1 in
TmTApp(fi, t1', tyT2), store'
| TmUnpack(fi,_,_,TmPack(_,tyT11,v12,_),t2) when isval ctx v12 ->
tytermSubstTop tyT11 (termSubstTop (termShift 1 v12) t2), store
| TmUnpack(fi,tyX,x,t1,t2) ->
let t1',store' = eval1 ctx store t1 in
TmUnpack(fi,tyX,x,t1',t2), store'
| TmPack(fi,tyT1,t2,tyT3) ->
let t2',store' = eval1 ctx store t2 in
TmPack(fi,tyT1,t2',tyT3), store'
| TmVar(fi,n,_) ->
(match getbinding fi ctx n with
TmAbbBind(t,_) -> t,store
| _ -> raise NoRuleApplies)
| _ ->
raise NoRuleApplies
let rec eval ctx store t =
try let t',store' = eval1 ctx store t
in eval ctx store' t'
with NoRuleApplies -> t,store
------------------------ KINDING ------------------------
let istyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT,_) -> true
| _ -> false
let gettyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT,_) -> tyT
| _ -> raise NoRuleApplies
let rec computety ctx tyT = match tyT with
TyVar(i,_) when istyabb ctx i -> gettyabb ctx i
| TyApp(TyAbs(_,_,tyT12),tyT2) -> typeSubstTop tyT2 tyT12
| _ -> raise NoRuleApplies
let rec simplifyty ctx tyT =
let tyT =
match tyT with
TyApp(tyT1,tyT2) -> TyApp(simplifyty ctx tyT1,tyT2)
| tyT -> tyT
in
try
let tyT' = computety ctx tyT in
simplifyty ctx tyT'
with NoRuleApplies -> tyT
let rec tyeqv ctx tyS tyT =
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyString,TyString) -> true
| (TyId(b1),TyId(b2)) -> b1=b2
| (TyUnit,TyUnit) -> true
| (TyRef(tyT1),TyRef(tyT2)) -> tyeqv ctx tyT1 tyT2
| (TyFloat,TyFloat) -> true
| (TyVar(i,_), _) when istyabb ctx i ->
tyeqv ctx (gettyabb ctx i) tyT
| (_, TyVar(i,_)) when istyabb ctx i ->
tyeqv ctx tyS (gettyabb ctx i)
| (TyVar(i,_),TyVar(j,_)) -> i=j
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(tyeqv ctx tyS1 tyT1) && (tyeqv ctx tyS2 tyT2)
| (TyBool,TyBool) -> true
| (TyNat,TyNat) -> true
| (TyRecord(fields1),TyRecord(fields2)) ->
List.length fields1 = List.length fields2
&&
List.for_all
(fun (li2,tyTi2) ->
try let (tyTi1) = List.assoc li2 fields1 in
tyeqv ctx tyTi1 tyTi2
with Not_found -> false)
fields2
| (TySome(tyX1,knK1,tyS2),TySome(_,knK1',tyT2)) ->
(=) knK1 knK1' &&
let ctx1 = addname ctx tyX1 in
tyeqv ctx1 tyS2 tyT2
| (TyAll(tyX1,knK1,tyS2),TyAll(_,knK2,tyT2)) ->
let ctx1 = addname ctx tyX1 in
(=) knK1 knK2 && tyeqv ctx1 tyS2 tyT2
| (TyAbs(tyX1,knKS1,tyS2),TyAbs(_,knKT1,tyT2)) ->
((=) knKS1 knKT1)
&&
(let ctx = addname ctx tyX1 in
tyeqv ctx tyS2 tyT2)
| (TyApp(tyS1,tyS2),TyApp(tyT1,tyT2)) ->
(tyeqv ctx tyS1 tyT1) && (tyeqv ctx tyS2 tyT2)
| _ -> false
let getkind fi ctx i =
match getbinding fi ctx i with
TyVarBind(knK) -> knK
| TyAbbBind(_,Some(knK)) -> knK
| TyAbbBind(_,None) -> error fi ("No kind recorded for variable "
^ (index2name fi ctx i))
| _ -> error fi ("getkind: Wrong kind of binding for variable "
^ (index2name fi ctx i))
let rec kindof ctx tyT = match tyT with
TyArr(tyT1,tyT2) ->
if kindof ctx tyT1 <> KnStar then error dummyinfo "star kind expected";
if kindof ctx tyT2 <> KnStar then error dummyinfo "star kind expected";
KnStar
| TyVar(i,_) ->
let knK = getkind dummyinfo ctx i
in knK
| TyRecord(fldtys) ->
List.iter (fun (l,tyS) ->
if kindof ctx tyS<>KnStar then error dummyinfo "Kind * expected")
fldtys;
KnStar
| TyAll(tyX,knK1,tyT2) ->
let ctx' = addbinding ctx tyX (TyVarBind knK1) in
if kindof ctx' tyT2 <> KnStar then error dummyinfo "Kind * expected";
KnStar
| TyAbs(tyX,knK1,tyT2) ->
let ctx' = addbinding ctx tyX (TyVarBind(knK1)) in
let knK2 = kindof ctx' tyT2 in
KnArr(knK1,knK2)
| TyApp(tyT1,tyT2) ->
let knK1 = kindof ctx tyT1 in
let knK2 = kindof ctx tyT2 in
(match knK1 with
KnArr(knK11,knK12) ->
if (=) knK2 knK11 then knK12
else error dummyinfo "parameter kind mismatch"
| _ -> error dummyinfo "arrow kind expected")
| TySome(tyX,knK,tyT2) ->
let ctx' = addbinding ctx tyX (TyVarBind(knK)) in
if kindof ctx' tyT2 <> KnStar then error dummyinfo "Kind * expected";
KnStar
| _ -> KnStar
let checkkindstar fi ctx tyT =
let k = kindof ctx tyT in
if k = KnStar then ()
else error fi "Kind * expected"
let rec typeof ctx t =
match t with
TmInert(fi,tyT) ->
tyT
| TmAscribe(fi,t1,tyT) ->
checkkindstar fi ctx tyT;
if tyeqv ctx (typeof ctx t1) tyT then
tyT
else
error fi "body of as-term does not have the expected type"
| TmVar(fi,i,_) -> getTypeFromContext fi ctx i
| TmAbs(fi,x,tyT1,t2) ->
checkkindstar fi ctx tyT1;
let ctx' = addbinding ctx x (VarBind(tyT1)) in
let tyT2 = typeof ctx' t2 in
TyArr(tyT1, typeShift (-1) tyT2)
| TmApp(fi,t1,t2) ->
let tyT1 = typeof ctx t1 in
let tyT2 = typeof ctx t2 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if tyeqv ctx tyT2 tyT11 then tyT12
else error fi "parameter type mismatch"
| _ -> error fi "arrow type expected")
| TmString _ -> TyString
| TmUnit(fi) -> TyUnit
| TmRef(fi,t1) ->
TyRef(typeof ctx t1)
| TmLoc(fi,l) ->
error fi "locations are not supposed to occur in source programs!"
| TmDeref(fi,t1) ->
(match simplifyty ctx (typeof ctx t1) with
TyRef(tyT1) -> tyT1
| _ -> error fi "argument of ! is not a Ref")
| TmAssign(fi,t1,t2) ->
(match simplifyty ctx (typeof ctx t1) with
TyRef(tyT1) ->
if tyeqv ctx (typeof ctx t2) tyT1 then
TyUnit
else
error fi "arguments of := are incompatible"
| _ -> error fi "argument of ! is not a Ref")
| TmRecord(fi, fields) ->
let fieldtys =
List.map (fun (li,ti) -> (li, typeof ctx ti)) fields in
TyRecord(fieldtys)
| TmProj(fi, t1, l) ->
(match simplifyty ctx (typeof ctx t1) with
TyRecord(fieldtys) ->
(try List.assoc l fieldtys
with Not_found -> error fi ("label "^l^" not found"))
| _ -> error fi "Expected record type")
| TmTrue(fi) ->
TyBool
| TmFalse(fi) ->
TyBool
| TmIf(fi,t1,t2,t3) ->
if tyeqv ctx (typeof ctx t1) TyBool then
let tyT2 = typeof ctx t2 in
if tyeqv ctx tyT2 (typeof ctx t3) then tyT2
else error fi "arms of conditional have different types"
else error fi "guard of conditional not a boolean"
| TmLet(fi,x,t1,t2) ->
let tyT1 = typeof ctx t1 in
let ctx' = addbinding ctx x (VarBind(tyT1)) in
typeShift (-1) (typeof ctx' t2)
| TmFloat _ -> TyFloat
| TmTimesfloat(fi,t1,t2) ->
if tyeqv ctx (typeof ctx t1) TyFloat
&& tyeqv ctx (typeof ctx t2) TyFloat then TyFloat
else error fi "argument of timesfloat is not a number"
| TmFix(fi, t1) ->
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if tyeqv ctx tyT12 tyT11 then tyT12
else error fi "result of body not compatible with domain"
| _ -> error fi "arrow type expected")
| TmTAbs(fi,tyX,knK1,t2) ->
let ctx = addbinding ctx tyX (TyVarBind(knK1)) in
let tyT2 = typeof ctx t2 in
TyAll(tyX,knK1,tyT2)
| TmTApp(fi,t1,tyT2) ->
let knKT2 = kindof ctx tyT2 in
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TyAll(_,knK11,tyT12) ->
if knK11 <> knKT2 then
error fi "Type argument has wrong kind";
typeSubstTop tyT2 tyT12
| _ -> error fi "universal type expected")
| TmZero(fi) ->
TyNat
| TmSucc(fi,t1) ->
if tyeqv ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of succ is not a number"
| TmPred(fi,t1) ->
if tyeqv ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of pred is not a number"
| TmIsZero(fi,t1) ->
if tyeqv ctx (typeof ctx t1) TyNat then TyBool
else error fi "argument of iszero is not a number"
| TmPack(fi,tyT1,t2,tyT) ->
checkkindstar fi ctx tyT;
(match simplifyty ctx tyT with
TySome(tyY,k,tyT2) ->
if kindof ctx tyT1 <> k then
error fi "type component does not have expected kind";
let tyU = typeof ctx t2 in
let tyU' = typeSubstTop tyT1 tyT2 in
if tyeqv ctx tyU tyU' then tyT
else error fi "doesn't match declared type"
| _ -> error fi "existential type expected")
| TmUnpack(fi,tyX,x,t1,t2) ->
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TySome(tyY,k,tyT11) ->
let ctx' = addbinding ctx tyX (TyVarBind k) in
let ctx'' = addbinding ctx' x (VarBind tyT11) in
let tyT2 = typeof ctx'' t2 in
typeShift (-2) tyT2
| _ -> error fi "existential type expected")
let evalbinding ctx store b = match b with
TmAbbBind(t,tyT) ->
let t',store' = eval ctx store t in
TmAbbBind(t',tyT), store'
| bind -> bind,store
|
db78a54deaa22945f53d029477d353aab6afcfcb5911f7260cec15048edb0753 | wireless-net/erlang-nommu | wxe_server.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2014 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%%-------------------------------------------------------------------
%%% File : wxe_server.erl
Author :
%%% Description : Application server monitors the application and handles
%%% callbacks, some cleaning if processes dies.
%%% The interface functions is found in wxe_util.erl
Created : 17 Jan 2007 by
%%%-------------------------------------------------------------------
%% @hidden
-module(wxe_server).
-behaviour(gen_server).
%% API
-export([start/1, stop/0, register_me/1, set_debug/2, invoke_callback/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {port,cb_port,users,cleaners=[],cb,cb_cnt}).
-record(user, {events=[]}).
%%-record(event, {object, callback, cb_handler}).
-define(APPLICATION, wxe).
-define(log(S,A), log(?MODULE,?LINE,S,A)).
-include("wxe.hrl").
-include("../include/wx.hrl").
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start(SilentStart ) - > # wx_env { }
%% Description: Starts the server
%%--------------------------------------------------------------------
start(SilentStart) ->
case get(?WXE_IDENTIFIER) of
undefined ->
case gen_server:start(?MODULE, [SilentStart], []) of
{ok, Pid} ->
{ok, Port} = gen_server:call(Pid, get_port, infinity),
wx:set_env(Env = #wx_env{port=Port,sv=Pid}),
Env;
{error, {Reason, _Stack}} ->
erlang:error(Reason)
end;
Env = #wx_env{sv=Pid} ->
case erlang:is_process_alive(Pid) of
true ->
Env;
false -> %% Ok we got an old wx env, someone forgot
erase(?WXE_IDENTIFIER), %% to call wx:destroy()
start(SilentStart)
end
end.
stop() ->
#wx_env{sv=Pid} = get(?WXE_IDENTIFIER),
catch gen_server:call(Pid, stop, infinity),
ok.
register_me(Pid) ->
ok = gen_server:call(Pid, register_me, infinity).
set_debug(Pid, Level) ->
gen_server:cast(Pid, {debug, Level}).
%%====================================================================
%% gen_server callbacks
%%====================================================================
init([SilentStart]) ->
{Port,CBPort} = wxe_master:init_port(SilentStart),
put(?WXE_IDENTIFIER, #wx_env{port=Port,sv=self()}),
{ok,#state{port=Port, cb_port=CBPort,
users=gb_trees:empty(), cb=gb_trees:empty(), cb_cnt=1}}.
Register process
handle_call(register_me, {From,_}, State=#state{users=Users}) ->
erlang:monitor(process, From),
case gb_trees:is_defined(From, Users) of
true ->
{reply, ok, State};
false ->
New = gb_trees:insert(From, #user{}, Users),
{reply, ok, State#state{users=New}}
end;
%% Port request
handle_call(get_port, _, State=#state{port=Port}) ->
{reply, {ok,Port}, State};
Connect callback
handle_call({connect_cb,Obj,Msg},{From,_},State) ->
handle_connect(Obj,Msg, From, State);
handle_call({disconnect_cb,Obj,Msg},{From,_},State) ->
handle_disconnect(Obj,Msg, From, State);
handle_call(stop,{_From,_},State = #state{users=Users0, cleaners=Cs0}) ->
Env = get(?WXE_IDENTIFIER),
Users = gb_trees:to_list(Users0),
Cs = lists:map(fun({_Pid,User}) ->
spawn_link(fun() -> cleanup(Env,[User]) end)
end, Users),
{noreply, State#state{users=gb_trees:empty(), cleaners=Cs ++ Cs0}};
handle_call({register_cb, Fun}, _, State0) ->
{FunId, State} = attach_fun(Fun,State0),
{reply, FunId, State};
%% Error
handle_call(_Request, _From, State) ->
?log("Unknown request ~p sent to ~p from ~p ~n",[_Request, ?MODULE, _From]),
Reply = ok,
{reply, Reply, State}.
%%%%%%%%%%%% Cast's
handle_cast({cleaned, From}, State=#state{users=Users,cleaners=Cs0}) ->
Cs = lists:delete(From,Cs0),
case Cs =:= [] andalso gb_trees:is_empty(Users) of
true -> {stop, normal, State#state{cleaners=Cs}};
false -> {noreply,State#state{cleaners=Cs}}
end;
handle_cast({debug, Level}, State) ->
Env = get(?WXE_IDENTIFIER),
put(?WXE_IDENTIFIER, Env#wx_env{debug=Level}),
{noreply, State};
handle_cast(_Msg, State) ->
?log("Unknown message ~p sent to ~p~n",[_Msg, ?MODULE]),
{noreply, State}.
%%%% Info
%% Callback request from driver
handle_info(Cb = {_, _, '_wx_invoke_cb_'}, State) ->
invoke_cb(Cb, State),
{noreply, State};
handle_info({wx_delete_cb, FunId}, State)
when is_integer(FunId) ->
{noreply, delete_fun(FunId, State)};
handle_info({wx_delete_cb, Id, EvtListener, Obj}, State = #state{users=Users}) ->
From = erase(EvtListener),
case gb_trees:lookup(From, Users) of
none ->
{noreply, delete_fun(Id, State)};
{value, User0} ->
User = cleanup_evt_listener(User0, EvtListener, Obj),
{noreply, delete_fun(Id, State#state{users=gb_trees:update(From, User, Users)})}
end;
handle_info({'DOWN',_,process,Pid,_}, State=#state{users=Users0,cleaners=Cs}) ->
try
User = gb_trees:get(Pid,Users0),
Users = gb_trees:delete(Pid,Users0),
Env = wx:get_env(),
case User of
#user{events=[]} -> %% No need to spawn
case Cs =:= [] andalso gb_trees:is_empty(Users) of
true -> {stop, normal, State#state{users=Users}};
false -> {noreply, State#state{users=Users}}
end;
_ ->
Cleaner = spawn_link(fun() -> cleanup(Env,[User]) end),
{noreply, State#state{users=Users,cleaners=[Cleaner|Cs]}}
end
catch _E:_R ->
%% ?log("Error: ~p ~p", [_E,_R]),
{noreply, State}
end;
handle_info(_Info, State) ->
?log("Unknown message ~p sent to ~p~n",[_Info, ?MODULE]),
{noreply, State}.
terminate(_Reason, _State) ->
erlang : display({?MODULE , killed , process_info(self(),trap_exit),_Reason } ) ,
timer : sleep(250 ) , % % Give driver a chance to clean up
shutdown.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
log(Mod,Line,Str,Args) ->
error_logger:format("~p:~p: " ++ Str, [Mod,Line|Args]).
handle_connect(Object, #evh{handler=undefined, cb=Callback} = EvData0,
From, State0) ->
%% Callback let this process listen to the events
{FunId, State} = attach_fun(Callback,State0),
EvData1 = EvData0#evh{cb=FunId},
case wxEvtHandler:connect_impl(Object,EvData1) of
{ok, Handler} ->
EvData = EvData1#evh{handler=Handler,userdata=undefined},
handle_connect(Object, EvData, From, State);
Error ->
{reply, Error, State0}
end;
handle_connect(Object, EvData=#evh{handler=Handler},
From, State0 = #state{users=Users}) ->
%% Correct process is already listening just register it
put(Handler, From),
User0 = #user{events=Listeners0} = gb_trees:get(From, Users),
User = User0#user{events=[{Object,EvData}|Listeners0]},
State = State0#state{users=gb_trees:update(From, User, Users)},
{reply, ok, State}.
invoke_cb({{Ev=#wx{}, Ref=#wx_ref{}}, FunId,_}, _S) ->
%% Event callbacks
case get(FunId) of
{Fun,_} when is_function(Fun) ->
invoke_callback(fun() -> Fun(Ev, Ref), <<>> end);
{Pid,_} when is_pid(Pid) -> %% wx_object sync event
invoke_callback(Pid, Ev, Ref);
Err ->
?log("Internal Error ~p~n",[Err])
end;
invoke_cb({FunId, Args, _}, _S) when is_list(Args), is_integer(FunId) ->
%% Overloaded functions
case get(FunId) of
{Fun,_} when is_function(Fun) ->
invoke_callback(fun() -> Fun(Args) end);
Err ->
?log("Internal Error ~p ~p ~p~n",[Err, FunId, Args])
end.
invoke_callback(Fun) ->
Env = get(?WXE_IDENTIFIER),
CB = fun() ->
wx:set_env(Env),
wxe_util:cast(?WXE_CB_START, <<>>),
Res = try
Return = Fun(),
true = is_binary(Return),
Return
catch _:Reason ->
?log("Callback fun crashed with {'EXIT, ~p, ~p}~n",
[Reason, erlang:get_stacktrace()]),
<<>>
end,
wxe_util:cast(?WXE_CB_RETURN, Res)
end,
spawn(CB),
ok.
invoke_callback(Pid, Ev, Ref) ->
Env = get(?WXE_IDENTIFIER),
CB = fun() ->
wx:set_env(Env),
wxe_util:cast(?WXE_CB_START, <<>>),
try
case get_wx_object_state(Pid) of
ignore ->
%% Ignore early events
wxEvent:skip(Ref);
{Mod, State} ->
case Mod:handle_sync_event(Ev, Ref, State) of
ok -> ok;
noreply -> ok;
Return -> exit({bad_return, Return})
end
end
catch _:Reason ->
wxEvent:skip(Ref),
?log("Callback fun crashed with {'EXIT, ~p, ~p}~n",
[Reason, erlang:get_stacktrace()])
end,
wxe_util:cast(?WXE_CB_RETURN, <<>>)
end,
spawn(CB),
ok.
get_wx_object_state(Pid) ->
case process_info(Pid, dictionary) of
{dictionary, Dict} ->
case lists:keysearch('_wx_object_',1,Dict) of
{value, {'_wx_object_', {_Mod, '_wx_init_'}}} -> ignore;
{value, {'_wx_object_', Value}} -> Value;
_ -> ignore
end;
_ -> ignore
end.
attach_fun(Fun, S = #state{cb=CB,cb_cnt=Next}) ->
case gb_trees:lookup(Fun,CB) of
{value, ID} ->
{Fun, N} = get(ID),
put(ID, {Fun,N+1}),
{ID,S};
none ->
put(Next,{Fun, 1}),
{Next,S#state{cb=gb_trees:insert(Fun,Next,CB),cb_cnt=Next+1}}
end.
delete_fun(0, State) -> State;
delete_fun(FunId, State = #state{cb=CB}) ->
case get(FunId) of
undefined ->
State;
{Fun,N} when N < 2 ->
erase(FunId),
State#state{cb=gb_trees:delete(Fun, CB)};
{Fun,N} ->
put(FunId, {Fun, N-1}),
State
end.
cleanup_evt_listener(U=#user{events=Evs0}, EvtListener, Object) ->
Filter = fun({Obj,#evh{handler=Evl}}) ->
not (Object =:= Obj andalso Evl =:= EvtListener)
end,
U#user{events=lists:filter(Filter, Evs0)}.
handle_disconnect(Object, Evh = #evh{cb=Fun}, From,
State0 = #state{users=Users0, cb=Callbacks}) ->
#user{events=Evs0} = gb_trees:get(From, Users0),
FunId = gb_trees:lookup(Fun, Callbacks),
case find_handler(Evs0, Object, Evh#evh{cb=FunId}) of
[] ->
{reply, false, State0};
Handlers ->
case disconnect(Object,Handlers) of
#evh{} -> {reply, true, State0};
Result -> {reply, Result, State0}
end
end.
disconnect(Object,[Ev|Evs]) ->
try wxEvtHandler:disconnect_impl(Object,Ev) of
true -> Ev;
false -> disconnect(Object, Evs);
Error -> Error
catch _:_ ->
false
end;
disconnect(_, []) -> false.
find_handler([{Object,Evh}|Evs], Object, Match) ->
case match_handler(Match, Evh) of
false -> find_handler(Evs, Object, Match);
Res -> [Res|find_handler(Evs,Object,Match)]
end;
find_handler([_|Evs], Object, Match) ->
find_handler(Evs, Object, Match);
find_handler([], _, _) -> [].
match_handler(M=#evh{et=MET, cb=MCB},
#evh{et=ET, cb=CB, handler=Handler}) ->
%% Let wxWidgets handle the id matching
Match = match_et(MET, ET)
andalso match_cb(MCB, CB),
Match andalso M#evh{handler=Handler}.
match_et(null, _) -> true;
match_et(Met, Et) -> Met =:= Et.
match_cb(none, _) -> true;
match_cb({value,MId}, Id) -> MId =:= Id.
%% Cleanup
%% The server handles callbacks from driver so every other wx call must
%% be called from another process, therefore the cleaning must be spawned.
%%
cleanup(Env, Data) ->
put(?WXE_IDENTIFIER, Env),
Disconnect = fun({Object, Ev}) ->
try wxEvtHandler:disconnect_impl(Object,Ev)
catch _:_ -> ok
end
end,
lists:foreach(fun(#user{events=Evs}) ->
[Disconnect(Ev) || Ev <- Evs]
end, Data),
gen_server:cast(Env#wx_env.sv, {cleaned, self()}),
normal.
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/wx/src/wxe_server.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
-------------------------------------------------------------------
File : wxe_server.erl
Description : Application server monitors the application and handles
callbacks, some cleaning if processes dies.
The interface functions is found in wxe_util.erl
-------------------------------------------------------------------
@hidden
API
gen_server callbacks
-record(event, {object, callback, cb_handler}).
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
Ok we got an old wx env, someone forgot
to call wx:destroy()
====================================================================
gen_server callbacks
====================================================================
Port request
Error
Cast's
Info
Callback request from driver
No need to spawn
?log("Error: ~p ~p", [_E,_R]),
% Give driver a chance to clean up
--------------------------------------------------------------------
--------------------------------------------------------------------
Callback let this process listen to the events
Correct process is already listening just register it
Event callbacks
wx_object sync event
Overloaded functions
Ignore early events
Let wxWidgets handle the id matching
Cleanup
The server handles callbacks from driver so every other wx call must
be called from another process, therefore the cleaning must be spawned.
| Copyright Ericsson AB 2008 - 2014 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
Author :
Created : 17 Jan 2007 by
-module(wxe_server).
-behaviour(gen_server).
-export([start/1, stop/0, register_me/1, set_debug/2, invoke_callback/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {port,cb_port,users,cleaners=[],cb,cb_cnt}).
-record(user, {events=[]}).
-define(APPLICATION, wxe).
-define(log(S,A), log(?MODULE,?LINE,S,A)).
-include("wxe.hrl").
-include("../include/wx.hrl").
Function : start(SilentStart ) - > # wx_env { }
start(SilentStart) ->
case get(?WXE_IDENTIFIER) of
undefined ->
case gen_server:start(?MODULE, [SilentStart], []) of
{ok, Pid} ->
{ok, Port} = gen_server:call(Pid, get_port, infinity),
wx:set_env(Env = #wx_env{port=Port,sv=Pid}),
Env;
{error, {Reason, _Stack}} ->
erlang:error(Reason)
end;
Env = #wx_env{sv=Pid} ->
case erlang:is_process_alive(Pid) of
true ->
Env;
start(SilentStart)
end
end.
stop() ->
#wx_env{sv=Pid} = get(?WXE_IDENTIFIER),
catch gen_server:call(Pid, stop, infinity),
ok.
register_me(Pid) ->
ok = gen_server:call(Pid, register_me, infinity).
set_debug(Pid, Level) ->
gen_server:cast(Pid, {debug, Level}).
init([SilentStart]) ->
{Port,CBPort} = wxe_master:init_port(SilentStart),
put(?WXE_IDENTIFIER, #wx_env{port=Port,sv=self()}),
{ok,#state{port=Port, cb_port=CBPort,
users=gb_trees:empty(), cb=gb_trees:empty(), cb_cnt=1}}.
Register process
handle_call(register_me, {From,_}, State=#state{users=Users}) ->
erlang:monitor(process, From),
case gb_trees:is_defined(From, Users) of
true ->
{reply, ok, State};
false ->
New = gb_trees:insert(From, #user{}, Users),
{reply, ok, State#state{users=New}}
end;
handle_call(get_port, _, State=#state{port=Port}) ->
{reply, {ok,Port}, State};
Connect callback
handle_call({connect_cb,Obj,Msg},{From,_},State) ->
handle_connect(Obj,Msg, From, State);
handle_call({disconnect_cb,Obj,Msg},{From,_},State) ->
handle_disconnect(Obj,Msg, From, State);
handle_call(stop,{_From,_},State = #state{users=Users0, cleaners=Cs0}) ->
Env = get(?WXE_IDENTIFIER),
Users = gb_trees:to_list(Users0),
Cs = lists:map(fun({_Pid,User}) ->
spawn_link(fun() -> cleanup(Env,[User]) end)
end, Users),
{noreply, State#state{users=gb_trees:empty(), cleaners=Cs ++ Cs0}};
handle_call({register_cb, Fun}, _, State0) ->
{FunId, State} = attach_fun(Fun,State0),
{reply, FunId, State};
handle_call(_Request, _From, State) ->
?log("Unknown request ~p sent to ~p from ~p ~n",[_Request, ?MODULE, _From]),
Reply = ok,
{reply, Reply, State}.
handle_cast({cleaned, From}, State=#state{users=Users,cleaners=Cs0}) ->
Cs = lists:delete(From,Cs0),
case Cs =:= [] andalso gb_trees:is_empty(Users) of
true -> {stop, normal, State#state{cleaners=Cs}};
false -> {noreply,State#state{cleaners=Cs}}
end;
handle_cast({debug, Level}, State) ->
Env = get(?WXE_IDENTIFIER),
put(?WXE_IDENTIFIER, Env#wx_env{debug=Level}),
{noreply, State};
handle_cast(_Msg, State) ->
?log("Unknown message ~p sent to ~p~n",[_Msg, ?MODULE]),
{noreply, State}.
handle_info(Cb = {_, _, '_wx_invoke_cb_'}, State) ->
invoke_cb(Cb, State),
{noreply, State};
handle_info({wx_delete_cb, FunId}, State)
when is_integer(FunId) ->
{noreply, delete_fun(FunId, State)};
handle_info({wx_delete_cb, Id, EvtListener, Obj}, State = #state{users=Users}) ->
From = erase(EvtListener),
case gb_trees:lookup(From, Users) of
none ->
{noreply, delete_fun(Id, State)};
{value, User0} ->
User = cleanup_evt_listener(User0, EvtListener, Obj),
{noreply, delete_fun(Id, State#state{users=gb_trees:update(From, User, Users)})}
end;
handle_info({'DOWN',_,process,Pid,_}, State=#state{users=Users0,cleaners=Cs}) ->
try
User = gb_trees:get(Pid,Users0),
Users = gb_trees:delete(Pid,Users0),
Env = wx:get_env(),
case User of
case Cs =:= [] andalso gb_trees:is_empty(Users) of
true -> {stop, normal, State#state{users=Users}};
false -> {noreply, State#state{users=Users}}
end;
_ ->
Cleaner = spawn_link(fun() -> cleanup(Env,[User]) end),
{noreply, State#state{users=Users,cleaners=[Cleaner|Cs]}}
end
catch _E:_R ->
{noreply, State}
end;
handle_info(_Info, State) ->
?log("Unknown message ~p sent to ~p~n",[_Info, ?MODULE]),
{noreply, State}.
terminate(_Reason, _State) ->
erlang : display({?MODULE , killed , process_info(self(),trap_exit),_Reason } ) ,
shutdown.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
log(Mod,Line,Str,Args) ->
error_logger:format("~p:~p: " ++ Str, [Mod,Line|Args]).
handle_connect(Object, #evh{handler=undefined, cb=Callback} = EvData0,
From, State0) ->
{FunId, State} = attach_fun(Callback,State0),
EvData1 = EvData0#evh{cb=FunId},
case wxEvtHandler:connect_impl(Object,EvData1) of
{ok, Handler} ->
EvData = EvData1#evh{handler=Handler,userdata=undefined},
handle_connect(Object, EvData, From, State);
Error ->
{reply, Error, State0}
end;
handle_connect(Object, EvData=#evh{handler=Handler},
From, State0 = #state{users=Users}) ->
put(Handler, From),
User0 = #user{events=Listeners0} = gb_trees:get(From, Users),
User = User0#user{events=[{Object,EvData}|Listeners0]},
State = State0#state{users=gb_trees:update(From, User, Users)},
{reply, ok, State}.
invoke_cb({{Ev=#wx{}, Ref=#wx_ref{}}, FunId,_}, _S) ->
case get(FunId) of
{Fun,_} when is_function(Fun) ->
invoke_callback(fun() -> Fun(Ev, Ref), <<>> end);
invoke_callback(Pid, Ev, Ref);
Err ->
?log("Internal Error ~p~n",[Err])
end;
invoke_cb({FunId, Args, _}, _S) when is_list(Args), is_integer(FunId) ->
case get(FunId) of
{Fun,_} when is_function(Fun) ->
invoke_callback(fun() -> Fun(Args) end);
Err ->
?log("Internal Error ~p ~p ~p~n",[Err, FunId, Args])
end.
invoke_callback(Fun) ->
Env = get(?WXE_IDENTIFIER),
CB = fun() ->
wx:set_env(Env),
wxe_util:cast(?WXE_CB_START, <<>>),
Res = try
Return = Fun(),
true = is_binary(Return),
Return
catch _:Reason ->
?log("Callback fun crashed with {'EXIT, ~p, ~p}~n",
[Reason, erlang:get_stacktrace()]),
<<>>
end,
wxe_util:cast(?WXE_CB_RETURN, Res)
end,
spawn(CB),
ok.
invoke_callback(Pid, Ev, Ref) ->
Env = get(?WXE_IDENTIFIER),
CB = fun() ->
wx:set_env(Env),
wxe_util:cast(?WXE_CB_START, <<>>),
try
case get_wx_object_state(Pid) of
ignore ->
wxEvent:skip(Ref);
{Mod, State} ->
case Mod:handle_sync_event(Ev, Ref, State) of
ok -> ok;
noreply -> ok;
Return -> exit({bad_return, Return})
end
end
catch _:Reason ->
wxEvent:skip(Ref),
?log("Callback fun crashed with {'EXIT, ~p, ~p}~n",
[Reason, erlang:get_stacktrace()])
end,
wxe_util:cast(?WXE_CB_RETURN, <<>>)
end,
spawn(CB),
ok.
get_wx_object_state(Pid) ->
case process_info(Pid, dictionary) of
{dictionary, Dict} ->
case lists:keysearch('_wx_object_',1,Dict) of
{value, {'_wx_object_', {_Mod, '_wx_init_'}}} -> ignore;
{value, {'_wx_object_', Value}} -> Value;
_ -> ignore
end;
_ -> ignore
end.
attach_fun(Fun, S = #state{cb=CB,cb_cnt=Next}) ->
case gb_trees:lookup(Fun,CB) of
{value, ID} ->
{Fun, N} = get(ID),
put(ID, {Fun,N+1}),
{ID,S};
none ->
put(Next,{Fun, 1}),
{Next,S#state{cb=gb_trees:insert(Fun,Next,CB),cb_cnt=Next+1}}
end.
delete_fun(0, State) -> State;
delete_fun(FunId, State = #state{cb=CB}) ->
case get(FunId) of
undefined ->
State;
{Fun,N} when N < 2 ->
erase(FunId),
State#state{cb=gb_trees:delete(Fun, CB)};
{Fun,N} ->
put(FunId, {Fun, N-1}),
State
end.
cleanup_evt_listener(U=#user{events=Evs0}, EvtListener, Object) ->
Filter = fun({Obj,#evh{handler=Evl}}) ->
not (Object =:= Obj andalso Evl =:= EvtListener)
end,
U#user{events=lists:filter(Filter, Evs0)}.
handle_disconnect(Object, Evh = #evh{cb=Fun}, From,
State0 = #state{users=Users0, cb=Callbacks}) ->
#user{events=Evs0} = gb_trees:get(From, Users0),
FunId = gb_trees:lookup(Fun, Callbacks),
case find_handler(Evs0, Object, Evh#evh{cb=FunId}) of
[] ->
{reply, false, State0};
Handlers ->
case disconnect(Object,Handlers) of
#evh{} -> {reply, true, State0};
Result -> {reply, Result, State0}
end
end.
disconnect(Object,[Ev|Evs]) ->
try wxEvtHandler:disconnect_impl(Object,Ev) of
true -> Ev;
false -> disconnect(Object, Evs);
Error -> Error
catch _:_ ->
false
end;
disconnect(_, []) -> false.
find_handler([{Object,Evh}|Evs], Object, Match) ->
case match_handler(Match, Evh) of
false -> find_handler(Evs, Object, Match);
Res -> [Res|find_handler(Evs,Object,Match)]
end;
find_handler([_|Evs], Object, Match) ->
find_handler(Evs, Object, Match);
find_handler([], _, _) -> [].
match_handler(M=#evh{et=MET, cb=MCB},
#evh{et=ET, cb=CB, handler=Handler}) ->
Match = match_et(MET, ET)
andalso match_cb(MCB, CB),
Match andalso M#evh{handler=Handler}.
match_et(null, _) -> true;
match_et(Met, Et) -> Met =:= Et.
match_cb(none, _) -> true;
match_cb({value,MId}, Id) -> MId =:= Id.
cleanup(Env, Data) ->
put(?WXE_IDENTIFIER, Env),
Disconnect = fun({Object, Ev}) ->
try wxEvtHandler:disconnect_impl(Object,Ev)
catch _:_ -> ok
end
end,
lists:foreach(fun(#user{events=Evs}) ->
[Disconnect(Ev) || Ev <- Evs]
end, Data),
gen_server:cast(Env#wx_env.sv, {cleaned, self()}),
normal.
|
3a86f66d9d1cc5986cc6f3435eee7331c1562192da47693cb308c5508c2c8c68 | hipsleek/hipsleek | dp.ml | #include "xdebug.cppo"
open Globals
open VarGen
open Error
open Cpure
type var_rep = string
type sformula =
| STrue
| SFalse
| SComp of scform
and scform =
| Seq of (var_rep*var_rep)
| Sneq of (var_rep*var_rep)
| SAnd of (scform * scform)
| SOr of (scform * scform)
let rec string_of_scformula f = match f with
| Seq (v1,v2) -> v1^" = "^v2
| Sneq (v1,v2) -> v1^" != "^v2
| SAnd (f1,f2) -> (string_of_scformula f1)^" & " ^ (string_of_scformula f2)
| SOr (f1,f2) -> " ("^(string_of_scformula f1)^") | (" ^ (string_of_scformula f2)^") "
let string_of_sformula f = match f with
| STrue -> "true"
| SFalse -> "false"
| SComp f -> string_of_scformula f
eq_spec_var
let mkSAnd f1 f2 = match f1 with
| STrue -> f2
| SFalse -> SFalse
| SComp fc1 -> match f2 with
| STrue -> f1
| SFalse -> SFalse
| SComp fc2 -> SComp (SAnd (fc1,fc2))
let mkSOr f1 f2 = match f1 with
| STrue -> STrue
| SFalse -> f2
| SComp fc1 -> match f2 with
| STrue -> STrue
| SFalse -> f1
| SComp fc2 -> SComp (SOr (fc1,fc2))
let rec scfv f = match f with
| Seq (v1,v2)
| Sneq(v1,v2) -> [v1;v2]
| SAnd (f1,f2)
| SOr (f1,f2) -> (Gen.BList.remove_dups_eq s_eq ((scfv f1)@ (scfv f2)))
let subst_s (fr, t) o = if s_eq fr o then t else o
let rec subst_cformula s f = match f with
| Seq (v1,v2) ->
let r1 = subst_s s v1 in
let r2 = subst_s s v2 in
if s_eq r1 r2 then STrue else SComp(Seq(r1,r2))
| Sneq (v1,v2) ->
let r1 = subst_s s v1 in
let r2 = subst_s s v2 in
if s_eq r1 r2 then SFalse else SComp(Sneq(r1,r2))
| SAnd (f1,f2) -> mkSAnd (subst_cformula s f1) (subst_cformula s f2)
| SOr (f1,f2) -> mkSOr (subst_cformula s f1) (subst_cformula s f2)
let subst_formula s f = match f with
| SComp fc -> subst_cformula s fc | _ -> f
let set_add_eq l (v1,v2) =
let rec f_rem v l= match l with
| [] -> ([v],[])
| h::t->
if (Gen.BList.mem_eq s_eq v h) then (h,t)
else
let r1,r2 = f_rem v t in
(r1,h::r2) in
let r11,r2 = f_rem v1 l in
let r12,r2 = f_rem v2 r2 in
(Gen.BList.remove_dups_eq s_eq (r11@r12))::r2
let get_aset l v = try List.find (Gen.BList.mem_eq s_eq v) l with | Not_found -> [v]
let trans_exp e : var_rep = match e with
| Var (v1,_) -> Cprinter.string_of_spec_var v1
| Null _ -> "null"
| IConst (i,_) -> string_of_int i
| FConst (f,_) -> string_of_float f
| _ -> failwith "found unexpected expression1"
let trans_bf bf = match bf with
| BConst (b,_) -> if b then STrue else SFalse
| Eq (IConst (c1,_),IConst(c2,_),_) -> if (c1=c2) then STrue else SFalse
| Eq (FConst (c1,_),FConst(c2,_),_) -> if (c1=c2) then STrue else SFalse
| Neq (IConst (c1,_),IConst(c2,_),_) -> if (c1=c2) then SFalse else STrue
| Neq (FConst (c1,_),FConst(c2,_),_) -> if (c1=c2) then SFalse else STrue
| Eq (e1,e2,_) ->
let v1 = trans_exp e1 in
let v2 = trans_exp e2 in
if (s_eq v1 v2) then STrue else SComp (Seq (v1,v2))
| Neq (e1,e2,_) ->
let v1 = trans_exp e1 in
let v2 = trans_exp e2 in
if (s_eq v1 v2) then SFalse else SComp (Sneq (v1,v2))
SComp ( Seq ( Cprinter.string_of_spec_var v , " true " ) )
| _ -> failwith ("found unexpected expression2 :"^(Cprinter.string_of_b_formula (bf,None)))
let neg f = match f with
| STrue -> SFalse
| SFalse -> STrue
| SComp fc ->
let rec helper fc = match fc with
| Seq f -> Sneq f
| Sneq f -> Seq f
| SAnd (f1,f2) -> SOr (helper f1, helper f2)
| SOr (f1,f2) -> SAnd (helper f1, helper f2) in
SComp (helper fc)
let elim_ex v f = match f with
| STrue -> STrue
| SFalse -> SFalse
| SComp fc1 ->
let rec purge_v f1 = match f1 with
| STrue -> STrue
| SFalse -> SFalse
| SComp f1->
let rec h f1 = match f1 with
| Seq (v1,v2) -> if (s_eq v1 v)|| (s_eq v2 v) then failwith ("could not elim ex "^v^" in "^(string_of_sformula f)) else SComp f1
| Sneq (v1,v2)-> if (s_eq v1 v)|| (s_eq v2 v) then STrue else SComp f1
| SAnd (f1,f2) -> mkSAnd (h f1) (h f2)
| SOr (f1,f2) -> mkSOr (h f1) (h f2) in
h f1 in
let rec or_lin f = match f with | SOr (f1,f2) -> (or_lin f1)@(or_lin f2) | _ -> [f] in
let rec and1_lin f = match f with | SAnd (f1,f2) -> (and1_lin f1)@(and1_lin f2) | _ -> [f] in
let rec find_eq f = match f with
| Seq (v1,v2) -> if s_eq v v1 then [(v1,v2)] else if (s_eq v v2) then [(v2,v1)] else []
| SAnd (f1,f2) ->
let r = find_eq f1 in
if r=[] then find_eq f2 else r
| _ -> [] in
let llo = List.map or_lin (and1_lin fc1) in
let rec search opt lacc l = match l with
| [] -> (opt,lacc)
| h::t ->
let lfh = List.concat (List.map find_eq h) in
let lfh = List.length lfh in
let lh = List.length h in
if (lh<>lfh) then search opt (h::lacc) t
else if (lh=1) then
match opt with
| None -> (Some h,lacc@t)
| Some s -> (Some h,lacc@(s::t))
else match opt with
| None -> search (Some h) lacc t
| Some _ -> search opt (h::lacc) t in
let s,l = search None [] llo in
match s with
| None -> purge_v f
| Some s ->
let f_or f = List.fold_left (fun a c-> SOr(a,c)) (List.hd f) (List.tl f) in
let ff_or f = List.fold_left (fun a c-> mkSOr a c) (List.hd f) (List.tl f) in
let f_and f = SComp (List.fold_left (fun a c-> SAnd (a,(f_or c))) (f_or(List.hd l)) (List.tl l)) in
let fr = if l=[] then STrue else f_and l in
if (List.length s)=1 then subst_formula (List.hd (find_eq (List.hd s))) fr
else ff_or (List.map (fun c-> subst_formula (List.hd (find_eq c)) (mkSAnd (SComp c) fr) ) s)
let rec trans_f b f = match f with
| BForm ((bf,_),_) -> trans_bf bf
| AndList _ -> Gen.report_error no_pos "dp.ml: encountered AndList, should have been already handled"
| And (f1,f2,_) -> mkSAnd (trans_f b f1) (trans_f b f2)
| Or (f1,f2,_,_) -> mkSOr (trans_f b f1) (trans_f b f2)
| Not (f,_,_) -> neg (trans_f b f)
| Forall _ -> failwith "unexpected forall!"
| Exists (v,f,_,_) -> if b then elim_ex (Cprinter.string_of_spec_var v) (trans_f b f) else trans_f b f
let trans_f b f = Gen.Profiling.do_2 "dptransf" trans_f b f
let sat_check f =
let rec and_lin f = match f with | SAnd (f1,f2) -> (and_lin f1)@(and_lin f2) | _ -> [f] in
let contra_test1 eq_s (v1,v2) = Gen.BList.mem_eq s_eq v2 (get_aset eq_s v1) in
let contra_test eq_s neq_s = List.exists (contra_test1 eq_s) neq_s in
let rec helper eqs neqs w_l f = match f with
| Seq a ->
let eqs = set_add_eq eqs a in
( match w_l with
| [] -> not (contra_test eqs neqs)
| h::t ->
if (List.exists (fun (v1,v2)->(v1,v2)=a || (v2,v1)=a) neqs) then false
else helper eqs neqs t h)
| Sneq a ->
(match w_l with
| [] -> not (contra_test eqs (a::neqs))
| h::t ->
if contra_test1 eqs a then false
else helper eqs (a::neqs) t h)
| SAnd _ ->
let l1,l2 = List.partition (fun c-> match c with | SOr _ -> true | _ -> false ) (and_lin f) in
let l = l2@l1 in
helper eqs neqs ((List.tl l) @ w_l) (List.hd l)
| SOr (f1,f2) -> (helper eqs neqs w_l f1) || (helper eqs neqs w_l f2) in
helper [] [] [] f
let is_sat f sat_no =
let h f = match trans_f false f with
| STrue -> true
| SFalse -> false
| SComp fc -> sat_check fc in
print_string ( " is sat : " " ) ; flush(stdout ) ;
Gen.Profiling.do_1 "dpsat" h f
let imply_test afc cfc =
let rec t_imply e_s n_s cfc = match cfc with
| Seq (v1,v2) -> Gen.BList.mem_eq s_eq v2 (get_aset e_s v1)
| Sneq (v1,v2) ->
let sv1 = get_aset e_s v1 in
let sv2 = get_aset e_s v2 in
List.exists (fun (v1,v2)->
(Gen.BList.mem_eq s_eq v1 sv1 && Gen.BList.mem_eq s_eq v2 sv2) ||
(Gen.BList.mem_eq s_eq v1 sv2 && Gen.BList.mem_eq s_eq v2 sv1)) n_s
| SAnd (f1,f2) -> (t_imply e_s n_s f1) && (t_imply e_s n_s f2)
| SOr (f1,f2) -> (t_imply e_s n_s f1) || (t_imply e_s n_s f2) in
let rec icollect afc e_s n_l w_l = match afc with
| Seq a -> (match w_l with
| [] -> t_imply (set_add_eq e_s a) n_l cfc
| h::t -> icollect h (set_add_eq e_s a) n_l t)
| Sneq a -> (match w_l with
| [] -> t_imply e_s (a::n_l) cfc
| h::t -> icollect h e_s (a::n_l) t)
| SAnd (f1,f2)-> icollect f1 e_s n_l (f2::w_l)
| SOr (f1,f2) -> (icollect f1 e_s n_l w_l) && (icollect f2 e_s n_l w_l) in
icollect afc [] [] []
let imply ante conseq impl_no _ =
let h ante conseq = match trans_f true conseq with
| SFalse -> false
| STrue -> true
| SComp cfc -> match trans_f false ante with
| STrue -> false
| SFalse -> true
| SComp afc -> imply_test afc cfc in
Gen.Profiling.do_2 "dpimply" h ante conseq
let imply ante conseq i f = Gen. " dpimply " Smtsolver.imply ( * i f
let imply ante conseq i f = Gen.Profiling.do_2 "dpimply" Smtsolver.imply ante conseq(* i f*)
let is_sat f sn = Gen.Profiling.do_2 "dpsat" Smtsolver.is_sat f sn
*)
let simplify f = (* (x_add Omega.simplify) *) !Cpure.simplify f
let hull f = x_add_1 Omega.hull f
let pairwisecheck f = x_add_1 Omega.pairwisecheck f
let imply ante impl_no _ = match trans_f false ante with
| SFalse - > true
| STrue - > ( match trans_f true conseq with
| STrue - > true
| _ - > false )
| SComp - > match ( trans_f ) with
| STrue - > true
| SFalse - > false ( * if not ( ) then true else false
| SFalse -> true
| STrue -> (match trans_f true conseq with
| STrue -> true
| _ -> false)
| SComp afc -> match (trans_f true conseq) with
| STrue -> true
| SFalse -> false (*if not (sat_check afc) then true else false*)
| SComp cfc ->
if not ( ) then true
else if ( sat_check cfc ) then
else
else if (sat_check cfc) then
else *)
imply_test afc cfc *)
and sets = ( var_rep list list * )
let sets_add_eq ( ( s1,s2):sets ) ( v1,v2 ) =
let le , ln = List.partition ( fun c- > ( Gen. BList.mem_eq s_eq v1 c)||(Gen . BList.mem_eq s_eq v2 c ) ) s1 in
let le = Gen. ( ) ) ) in
let s2 = in
( le::ln , s2 )
let sets_add_neq ( ( s1,s2):sets ) ( v1,v2 ) =
and sets = (var_rep list list * Hashtbl.t)
let sets_add_eq ((s1,s2):sets) (v1,v2) =
let le,ln = List.partition (fun c-> (Gen.BList.mem_eq s_eq v1 c)||(Gen.BList.mem_eq s_eq v2 c)) s1 in
let le = Gen.BList.remove_dups_eq s_eq (v1::(v2::(List.concat le))) in
let s2 = in
(le::ln,s2)
let sets_add_neq ((s1,s2):sets) (v1,v2) =
*)
let get_nset l v = try snd ( List.find ( fun ( c,_)- > s_eq c v ) l ) with | Not_found - > [ ]
let sets_add_eq ( e_s , n_s ) ( v1,v2 ) =
let rec f_rem v l= match l with
| [ ] - > ( [ v ] , [ ] )
| h::t- >
if ( Gen. BList.mem_eq s_eq v h ) then ( h , t )
else
let r1,r2 = f_rem v t in
( r1,h::r2 ) in
let rec get s l = match l with
| [ ] - > ( [ ] , [ ] )
| ( hv , hl)::t - >
if s_eq hv s then ( hl , t )
else
let r1,r2 = get s t in
( r1,(hv , hl)::r2 ) in
let r11,r2 = f_rem v1 l in
let r12,r2 = f_rem v2 r2 in
let new_es = Gen. ( r11@r12 ) in
let e_s = new_es::r2 in
let folder r n_s c =
List.fold_left r
let n_s = List.fold_left ( folder r12 ) n_s r11 in
let n_s = List.fold_left ( folder r11 ) n_s r12 in
( e_s , n_s )
let sets_add_neq ( e_s , n_s ) ( v1,v2 ) =
let get s l = match l with
| [ ] - > ( [ ] , [ ] )
| ( hv , hl)::t - >
if s_eq hv s then ( hl , t )
else
let r1,r2 = get s t in
( r1,(hv , hl)::r2 ) in
let v1_ns , r2 = get v1 n_s in
let v2_ns , r2 = get v2 r2 in
let nv1 = Gen. ( List.concat ( List.map ( get_nset r2 ) ( get_aset e_s v2))@v1_ns ) in
let nv2 = Gen. ( List.concat ( List.map ( get_nset r2 ) ( get_aset e_s v1))@v2_ns ) in
( e_s , ( v2,nv2)::((v1,nv1)::r2 ) )
let get_nset l v = try snd (List.find (fun (c,_)-> s_eq c v) l) with | Not_found -> []
let sets_add_eq (e_s,n_s) (v1,v2) =
let rec f_rem v l= match l with
| [] -> ([v],[])
| h::t->
if (Gen.BList.mem_eq s_eq v h) then (h,t)
else
let r1,r2 = f_rem v t in
(r1,h::r2) in
let rec get s l =match l with
| [] -> ([],[])
| (hv,hl)::t ->
if s_eq hv s then (hl,t)
else
let r1,r2 = get s t in
(r1,(hv,hl)::r2) in
let r11,r2 = f_rem v1 l in
let r12,r2 = f_rem v2 r2 in
let new_es = Gen.BList.remove_dups_eq s_eq (r11@r12) in
let e_s = new_es::r2 in
let folder r n_s c =
List.fold_left r
let n_s = List.fold_left (folder r12) n_s r11 in
let n_s = List.fold_left (folder r11) n_s r12 in
(e_s,n_s)
let sets_add_neq (e_s,n_s) (v1,v2) =
let get s l =match l with
| [] -> ([],[])
| (hv,hl)::t ->
if s_eq hv s then (hl,t)
else
let r1,r2 = get s t in
(r1,(hv,hl)::r2) in
let v1_ns,r2 = get v1 n_s in
let v2_ns,r2 = get v2 r2 in
let nv1 = Gen.BList.remove_dups_eq s_eq (List.concat (List.map (get_nset r2) (get_aset e_s v2))@v1_ns) in
let nv2 = Gen.BList.remove_dups_eq s_eq (List.concat (List.map (get_nset r2) (get_aset e_s v1))@v2_ns) in
(e_s, (v2,nv2)::((v1,nv1)::r2))
*)
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/src/dp.ml | ocaml | i f
(x_add Omega.simplify)
if not (sat_check afc) then true else false | #include "xdebug.cppo"
open Globals
open VarGen
open Error
open Cpure
type var_rep = string
type sformula =
| STrue
| SFalse
| SComp of scform
and scform =
| Seq of (var_rep*var_rep)
| Sneq of (var_rep*var_rep)
| SAnd of (scform * scform)
| SOr of (scform * scform)
let rec string_of_scformula f = match f with
| Seq (v1,v2) -> v1^" = "^v2
| Sneq (v1,v2) -> v1^" != "^v2
| SAnd (f1,f2) -> (string_of_scformula f1)^" & " ^ (string_of_scformula f2)
| SOr (f1,f2) -> " ("^(string_of_scformula f1)^") | (" ^ (string_of_scformula f2)^") "
let string_of_sformula f = match f with
| STrue -> "true"
| SFalse -> "false"
| SComp f -> string_of_scformula f
eq_spec_var
let mkSAnd f1 f2 = match f1 with
| STrue -> f2
| SFalse -> SFalse
| SComp fc1 -> match f2 with
| STrue -> f1
| SFalse -> SFalse
| SComp fc2 -> SComp (SAnd (fc1,fc2))
let mkSOr f1 f2 = match f1 with
| STrue -> STrue
| SFalse -> f2
| SComp fc1 -> match f2 with
| STrue -> STrue
| SFalse -> f1
| SComp fc2 -> SComp (SOr (fc1,fc2))
let rec scfv f = match f with
| Seq (v1,v2)
| Sneq(v1,v2) -> [v1;v2]
| SAnd (f1,f2)
| SOr (f1,f2) -> (Gen.BList.remove_dups_eq s_eq ((scfv f1)@ (scfv f2)))
let subst_s (fr, t) o = if s_eq fr o then t else o
let rec subst_cformula s f = match f with
| Seq (v1,v2) ->
let r1 = subst_s s v1 in
let r2 = subst_s s v2 in
if s_eq r1 r2 then STrue else SComp(Seq(r1,r2))
| Sneq (v1,v2) ->
let r1 = subst_s s v1 in
let r2 = subst_s s v2 in
if s_eq r1 r2 then SFalse else SComp(Sneq(r1,r2))
| SAnd (f1,f2) -> mkSAnd (subst_cformula s f1) (subst_cformula s f2)
| SOr (f1,f2) -> mkSOr (subst_cformula s f1) (subst_cformula s f2)
let subst_formula s f = match f with
| SComp fc -> subst_cformula s fc | _ -> f
let set_add_eq l (v1,v2) =
let rec f_rem v l= match l with
| [] -> ([v],[])
| h::t->
if (Gen.BList.mem_eq s_eq v h) then (h,t)
else
let r1,r2 = f_rem v t in
(r1,h::r2) in
let r11,r2 = f_rem v1 l in
let r12,r2 = f_rem v2 r2 in
(Gen.BList.remove_dups_eq s_eq (r11@r12))::r2
let get_aset l v = try List.find (Gen.BList.mem_eq s_eq v) l with | Not_found -> [v]
let trans_exp e : var_rep = match e with
| Var (v1,_) -> Cprinter.string_of_spec_var v1
| Null _ -> "null"
| IConst (i,_) -> string_of_int i
| FConst (f,_) -> string_of_float f
| _ -> failwith "found unexpected expression1"
let trans_bf bf = match bf with
| BConst (b,_) -> if b then STrue else SFalse
| Eq (IConst (c1,_),IConst(c2,_),_) -> if (c1=c2) then STrue else SFalse
| Eq (FConst (c1,_),FConst(c2,_),_) -> if (c1=c2) then STrue else SFalse
| Neq (IConst (c1,_),IConst(c2,_),_) -> if (c1=c2) then SFalse else STrue
| Neq (FConst (c1,_),FConst(c2,_),_) -> if (c1=c2) then SFalse else STrue
| Eq (e1,e2,_) ->
let v1 = trans_exp e1 in
let v2 = trans_exp e2 in
if (s_eq v1 v2) then STrue else SComp (Seq (v1,v2))
| Neq (e1,e2,_) ->
let v1 = trans_exp e1 in
let v2 = trans_exp e2 in
if (s_eq v1 v2) then SFalse else SComp (Sneq (v1,v2))
SComp ( Seq ( Cprinter.string_of_spec_var v , " true " ) )
| _ -> failwith ("found unexpected expression2 :"^(Cprinter.string_of_b_formula (bf,None)))
let neg f = match f with
| STrue -> SFalse
| SFalse -> STrue
| SComp fc ->
let rec helper fc = match fc with
| Seq f -> Sneq f
| Sneq f -> Seq f
| SAnd (f1,f2) -> SOr (helper f1, helper f2)
| SOr (f1,f2) -> SAnd (helper f1, helper f2) in
SComp (helper fc)
let elim_ex v f = match f with
| STrue -> STrue
| SFalse -> SFalse
| SComp fc1 ->
let rec purge_v f1 = match f1 with
| STrue -> STrue
| SFalse -> SFalse
| SComp f1->
let rec h f1 = match f1 with
| Seq (v1,v2) -> if (s_eq v1 v)|| (s_eq v2 v) then failwith ("could not elim ex "^v^" in "^(string_of_sformula f)) else SComp f1
| Sneq (v1,v2)-> if (s_eq v1 v)|| (s_eq v2 v) then STrue else SComp f1
| SAnd (f1,f2) -> mkSAnd (h f1) (h f2)
| SOr (f1,f2) -> mkSOr (h f1) (h f2) in
h f1 in
let rec or_lin f = match f with | SOr (f1,f2) -> (or_lin f1)@(or_lin f2) | _ -> [f] in
let rec and1_lin f = match f with | SAnd (f1,f2) -> (and1_lin f1)@(and1_lin f2) | _ -> [f] in
let rec find_eq f = match f with
| Seq (v1,v2) -> if s_eq v v1 then [(v1,v2)] else if (s_eq v v2) then [(v2,v1)] else []
| SAnd (f1,f2) ->
let r = find_eq f1 in
if r=[] then find_eq f2 else r
| _ -> [] in
let llo = List.map or_lin (and1_lin fc1) in
let rec search opt lacc l = match l with
| [] -> (opt,lacc)
| h::t ->
let lfh = List.concat (List.map find_eq h) in
let lfh = List.length lfh in
let lh = List.length h in
if (lh<>lfh) then search opt (h::lacc) t
else if (lh=1) then
match opt with
| None -> (Some h,lacc@t)
| Some s -> (Some h,lacc@(s::t))
else match opt with
| None -> search (Some h) lacc t
| Some _ -> search opt (h::lacc) t in
let s,l = search None [] llo in
match s with
| None -> purge_v f
| Some s ->
let f_or f = List.fold_left (fun a c-> SOr(a,c)) (List.hd f) (List.tl f) in
let ff_or f = List.fold_left (fun a c-> mkSOr a c) (List.hd f) (List.tl f) in
let f_and f = SComp (List.fold_left (fun a c-> SAnd (a,(f_or c))) (f_or(List.hd l)) (List.tl l)) in
let fr = if l=[] then STrue else f_and l in
if (List.length s)=1 then subst_formula (List.hd (find_eq (List.hd s))) fr
else ff_or (List.map (fun c-> subst_formula (List.hd (find_eq c)) (mkSAnd (SComp c) fr) ) s)
let rec trans_f b f = match f with
| BForm ((bf,_),_) -> trans_bf bf
| AndList _ -> Gen.report_error no_pos "dp.ml: encountered AndList, should have been already handled"
| And (f1,f2,_) -> mkSAnd (trans_f b f1) (trans_f b f2)
| Or (f1,f2,_,_) -> mkSOr (trans_f b f1) (trans_f b f2)
| Not (f,_,_) -> neg (trans_f b f)
| Forall _ -> failwith "unexpected forall!"
| Exists (v,f,_,_) -> if b then elim_ex (Cprinter.string_of_spec_var v) (trans_f b f) else trans_f b f
let trans_f b f = Gen.Profiling.do_2 "dptransf" trans_f b f
let sat_check f =
let rec and_lin f = match f with | SAnd (f1,f2) -> (and_lin f1)@(and_lin f2) | _ -> [f] in
let contra_test1 eq_s (v1,v2) = Gen.BList.mem_eq s_eq v2 (get_aset eq_s v1) in
let contra_test eq_s neq_s = List.exists (contra_test1 eq_s) neq_s in
let rec helper eqs neqs w_l f = match f with
| Seq a ->
let eqs = set_add_eq eqs a in
( match w_l with
| [] -> not (contra_test eqs neqs)
| h::t ->
if (List.exists (fun (v1,v2)->(v1,v2)=a || (v2,v1)=a) neqs) then false
else helper eqs neqs t h)
| Sneq a ->
(match w_l with
| [] -> not (contra_test eqs (a::neqs))
| h::t ->
if contra_test1 eqs a then false
else helper eqs (a::neqs) t h)
| SAnd _ ->
let l1,l2 = List.partition (fun c-> match c with | SOr _ -> true | _ -> false ) (and_lin f) in
let l = l2@l1 in
helper eqs neqs ((List.tl l) @ w_l) (List.hd l)
| SOr (f1,f2) -> (helper eqs neqs w_l f1) || (helper eqs neqs w_l f2) in
helper [] [] [] f
let is_sat f sat_no =
let h f = match trans_f false f with
| STrue -> true
| SFalse -> false
| SComp fc -> sat_check fc in
print_string ( " is sat : " " ) ; flush(stdout ) ;
Gen.Profiling.do_1 "dpsat" h f
let imply_test afc cfc =
let rec t_imply e_s n_s cfc = match cfc with
| Seq (v1,v2) -> Gen.BList.mem_eq s_eq v2 (get_aset e_s v1)
| Sneq (v1,v2) ->
let sv1 = get_aset e_s v1 in
let sv2 = get_aset e_s v2 in
List.exists (fun (v1,v2)->
(Gen.BList.mem_eq s_eq v1 sv1 && Gen.BList.mem_eq s_eq v2 sv2) ||
(Gen.BList.mem_eq s_eq v1 sv2 && Gen.BList.mem_eq s_eq v2 sv1)) n_s
| SAnd (f1,f2) -> (t_imply e_s n_s f1) && (t_imply e_s n_s f2)
| SOr (f1,f2) -> (t_imply e_s n_s f1) || (t_imply e_s n_s f2) in
let rec icollect afc e_s n_l w_l = match afc with
| Seq a -> (match w_l with
| [] -> t_imply (set_add_eq e_s a) n_l cfc
| h::t -> icollect h (set_add_eq e_s a) n_l t)
| Sneq a -> (match w_l with
| [] -> t_imply e_s (a::n_l) cfc
| h::t -> icollect h e_s (a::n_l) t)
| SAnd (f1,f2)-> icollect f1 e_s n_l (f2::w_l)
| SOr (f1,f2) -> (icollect f1 e_s n_l w_l) && (icollect f2 e_s n_l w_l) in
icollect afc [] [] []
let imply ante conseq impl_no _ =
let h ante conseq = match trans_f true conseq with
| SFalse -> false
| STrue -> true
| SComp cfc -> match trans_f false ante with
| STrue -> false
| SFalse -> true
| SComp afc -> imply_test afc cfc in
Gen.Profiling.do_2 "dpimply" h ante conseq
let imply ante conseq i f = Gen. " dpimply " Smtsolver.imply ( * i f
let is_sat f sn = Gen.Profiling.do_2 "dpsat" Smtsolver.is_sat f sn
*)
let hull f = x_add_1 Omega.hull f
let pairwisecheck f = x_add_1 Omega.pairwisecheck f
let imply ante impl_no _ = match trans_f false ante with
| SFalse - > true
| STrue - > ( match trans_f true conseq with
| STrue - > true
| _ - > false )
| SComp - > match ( trans_f ) with
| STrue - > true
| SFalse - > false ( * if not ( ) then true else false
| SFalse -> true
| STrue -> (match trans_f true conseq with
| STrue -> true
| _ -> false)
| SComp afc -> match (trans_f true conseq) with
| STrue -> true
| SComp cfc ->
if not ( ) then true
else if ( sat_check cfc ) then
else
else if (sat_check cfc) then
else *)
imply_test afc cfc *)
and sets = ( var_rep list list * )
let sets_add_eq ( ( s1,s2):sets ) ( v1,v2 ) =
let le , ln = List.partition ( fun c- > ( Gen. BList.mem_eq s_eq v1 c)||(Gen . BList.mem_eq s_eq v2 c ) ) s1 in
let le = Gen. ( ) ) ) in
let s2 = in
( le::ln , s2 )
let sets_add_neq ( ( s1,s2):sets ) ( v1,v2 ) =
and sets = (var_rep list list * Hashtbl.t)
let sets_add_eq ((s1,s2):sets) (v1,v2) =
let le,ln = List.partition (fun c-> (Gen.BList.mem_eq s_eq v1 c)||(Gen.BList.mem_eq s_eq v2 c)) s1 in
let le = Gen.BList.remove_dups_eq s_eq (v1::(v2::(List.concat le))) in
let s2 = in
(le::ln,s2)
let sets_add_neq ((s1,s2):sets) (v1,v2) =
*)
let get_nset l v = try snd ( List.find ( fun ( c,_)- > s_eq c v ) l ) with | Not_found - > [ ]
let sets_add_eq ( e_s , n_s ) ( v1,v2 ) =
let rec f_rem v l= match l with
| [ ] - > ( [ v ] , [ ] )
| h::t- >
if ( Gen. BList.mem_eq s_eq v h ) then ( h , t )
else
let r1,r2 = f_rem v t in
( r1,h::r2 ) in
let rec get s l = match l with
| [ ] - > ( [ ] , [ ] )
| ( hv , hl)::t - >
if s_eq hv s then ( hl , t )
else
let r1,r2 = get s t in
( r1,(hv , hl)::r2 ) in
let r11,r2 = f_rem v1 l in
let r12,r2 = f_rem v2 r2 in
let new_es = Gen. ( r11@r12 ) in
let e_s = new_es::r2 in
let folder r n_s c =
List.fold_left r
let n_s = List.fold_left ( folder r12 ) n_s r11 in
let n_s = List.fold_left ( folder r11 ) n_s r12 in
( e_s , n_s )
let sets_add_neq ( e_s , n_s ) ( v1,v2 ) =
let get s l = match l with
| [ ] - > ( [ ] , [ ] )
| ( hv , hl)::t - >
if s_eq hv s then ( hl , t )
else
let r1,r2 = get s t in
( r1,(hv , hl)::r2 ) in
let v1_ns , r2 = get v1 n_s in
let v2_ns , r2 = get v2 r2 in
let nv1 = Gen. ( List.concat ( List.map ( get_nset r2 ) ( get_aset e_s v2))@v1_ns ) in
let nv2 = Gen. ( List.concat ( List.map ( get_nset r2 ) ( get_aset e_s v1))@v2_ns ) in
( e_s , ( v2,nv2)::((v1,nv1)::r2 ) )
let get_nset l v = try snd (List.find (fun (c,_)-> s_eq c v) l) with | Not_found -> []
let sets_add_eq (e_s,n_s) (v1,v2) =
let rec f_rem v l= match l with
| [] -> ([v],[])
| h::t->
if (Gen.BList.mem_eq s_eq v h) then (h,t)
else
let r1,r2 = f_rem v t in
(r1,h::r2) in
let rec get s l =match l with
| [] -> ([],[])
| (hv,hl)::t ->
if s_eq hv s then (hl,t)
else
let r1,r2 = get s t in
(r1,(hv,hl)::r2) in
let r11,r2 = f_rem v1 l in
let r12,r2 = f_rem v2 r2 in
let new_es = Gen.BList.remove_dups_eq s_eq (r11@r12) in
let e_s = new_es::r2 in
let folder r n_s c =
List.fold_left r
let n_s = List.fold_left (folder r12) n_s r11 in
let n_s = List.fold_left (folder r11) n_s r12 in
(e_s,n_s)
let sets_add_neq (e_s,n_s) (v1,v2) =
let get s l =match l with
| [] -> ([],[])
| (hv,hl)::t ->
if s_eq hv s then (hl,t)
else
let r1,r2 = get s t in
(r1,(hv,hl)::r2) in
let v1_ns,r2 = get v1 n_s in
let v2_ns,r2 = get v2 r2 in
let nv1 = Gen.BList.remove_dups_eq s_eq (List.concat (List.map (get_nset r2) (get_aset e_s v2))@v1_ns) in
let nv2 = Gen.BList.remove_dups_eq s_eq (List.concat (List.map (get_nset r2) (get_aset e_s v1))@v2_ns) in
(e_s, (v2,nv2)::((v1,nv1)::r2))
*)
|
b99c54e231ab27793e9c41067f9be25f09f0079a0858950f9a932c283d1bb168 | naoiwata/sicp | ex3.81.scm | ;;
;; @author naoiwata
SICP Chapter3
Exercise 3.81 .
;;
; ------------------------------------------------------------------------
; question
; ------------------------------------------------------------------------
(add-load-path "./pages/" :relative)
(load "stream.scm")
(define (random-stream requests)
(define (rand req prev)
(random-update
(cond
((and (symbol? req) (eq? req 'generate)) prev)
((and (pair? req) (eq? (car req) 'reset)) (cdr req))
(else
(error "Unknown request -- RAND" req)))))
(define random-numbers
(cons-stream (rand (stream-car requests) random-init)
(stream-map rand (stream-cdr requests) random-numbers)))
random-numbers)
| null | https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter3/ex3.81.scm | scheme |
@author naoiwata
------------------------------------------------------------------------
question
------------------------------------------------------------------------ | SICP Chapter3
Exercise 3.81 .
(add-load-path "./pages/" :relative)
(load "stream.scm")
(define (random-stream requests)
(define (rand req prev)
(random-update
(cond
((and (symbol? req) (eq? req 'generate)) prev)
((and (pair? req) (eq? (car req) 'reset)) (cdr req))
(else
(error "Unknown request -- RAND" req)))))
(define random-numbers
(cons-stream (rand (stream-car requests) random-init)
(stream-map rand (stream-cdr requests) random-numbers)))
random-numbers)
|
ae6bb8d7b50bc95a214825aa7ab7a7fa89cfc47bb89dc7c7cb62295343e3e3b9 | input-output-hk/ouroboros-network | State.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
# LANGUAGE UndecidableInstances #
module Ouroboros.Consensus.Mock.Ledger.State (
-- * State of the mock ledger
MockError (..)
, MockState (..)
, updateMockState
, updateMockTip
, updateMockUTxO
* Genesis state
, genesisMockState
) where
import Cardano.Binary (toCBOR)
import Codec.Serialise (Serialise)
import Control.Monad.Except
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Cardano.Crypto.Hash
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Mock.Ledger.Address
import Ouroboros.Consensus.Mock.Ledger.UTxO
import Ouroboros.Consensus.Util (ShowProxy (..), repeatedlyM)
{-------------------------------------------------------------------------------
State of the mock ledger
-------------------------------------------------------------------------------}
data MockState blk = MockState {
mockUtxo :: !Utxo
, mockConfirmed :: !(Set TxId)
, mockTip :: !(Point blk)
}
deriving (Show, Eq, Generic, NoThunks)
deriving instance Serialise (HeaderHash blk) => Serialise (MockState blk)
data MockError blk =
MockExpired !SlotNo !SlotNo
^ The transaction expired in the first ' SlotNo ' , and it failed to
validate in the second ' SlotNo ' .
| MockUtxoError UtxoError
| MockInvalidHash (ChainHash blk) (ChainHash blk)
deriving (Generic, NoThunks)
deriving instance StandardHash blk => Show (MockError blk)
deriving instance StandardHash blk => Eq (MockError blk)
deriving instance Serialise (HeaderHash blk) => Serialise (MockError blk)
instance Typeable blk => ShowProxy (MockError blk) where
updateMockState :: (GetPrevHash blk, HasMockTxs blk)
=> blk
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockState blk st = do
let hdr = getHeader blk
st' <- updateMockTip hdr st
updateMockUTxO (blockSlot hdr) blk st'
updateMockTip :: GetPrevHash blk
=> Header blk
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockTip hdr (MockState u c t)
| headerPrevHash hdr == pointHash t
= return $ MockState u c (headerPoint hdr)
| otherwise
= throwError $ MockInvalidHash (headerPrevHash hdr) (pointHash t)
updateMockUTxO :: HasMockTxs a
=> SlotNo
-> a
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockUTxO now = repeatedlyM (updateMockUTxO1 now) . getMockTxs
updateMockUTxO1 :: forall blk.
SlotNo
-> Tx
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockUTxO1 now tx (MockState u c t) = case hasExpired of
Just e -> throwError e
Nothing -> do
u' <- withExcept MockUtxoError $ updateUtxo tx u
return $ MockState u' (c `Set.union` confirmed tx) t
where
Tx expiry _ins _outs = tx
hasExpired :: Maybe (MockError blk)
hasExpired = case expiry of
DoNotExpire -> Nothing
ExpireAtOnsetOf s -> do
guard $ s <= now
Just $ MockExpired s now
------------------------------------------------------------------------------
Genesis
------------------------------------------------------------------------------
Genesis
-------------------------------------------------------------------------------}
genesisMockState :: AddrDist -> MockState blk
genesisMockState addrDist = MockState {
mockUtxo = genesisUtxo addrDist
, mockConfirmed = Set.singleton (hashWithSerialiser toCBOR (genesisTx addrDist))
, mockTip = GenesisPoint
}
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus-mock/src/Ouroboros/Consensus/Mock/Ledger/State.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
* State of the mock ledger
------------------------------------------------------------------------------
State of the mock ledger
------------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------} | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
module Ouroboros.Consensus.Mock.Ledger.State (
MockError (..)
, MockState (..)
, updateMockState
, updateMockTip
, updateMockUTxO
* Genesis state
, genesisMockState
) where
import Cardano.Binary (toCBOR)
import Codec.Serialise (Serialise)
import Control.Monad.Except
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Cardano.Crypto.Hash
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Mock.Ledger.Address
import Ouroboros.Consensus.Mock.Ledger.UTxO
import Ouroboros.Consensus.Util (ShowProxy (..), repeatedlyM)
data MockState blk = MockState {
mockUtxo :: !Utxo
, mockConfirmed :: !(Set TxId)
, mockTip :: !(Point blk)
}
deriving (Show, Eq, Generic, NoThunks)
deriving instance Serialise (HeaderHash blk) => Serialise (MockState blk)
data MockError blk =
MockExpired !SlotNo !SlotNo
^ The transaction expired in the first ' SlotNo ' , and it failed to
validate in the second ' SlotNo ' .
| MockUtxoError UtxoError
| MockInvalidHash (ChainHash blk) (ChainHash blk)
deriving (Generic, NoThunks)
deriving instance StandardHash blk => Show (MockError blk)
deriving instance StandardHash blk => Eq (MockError blk)
deriving instance Serialise (HeaderHash blk) => Serialise (MockError blk)
instance Typeable blk => ShowProxy (MockError blk) where
updateMockState :: (GetPrevHash blk, HasMockTxs blk)
=> blk
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockState blk st = do
let hdr = getHeader blk
st' <- updateMockTip hdr st
updateMockUTxO (blockSlot hdr) blk st'
updateMockTip :: GetPrevHash blk
=> Header blk
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockTip hdr (MockState u c t)
| headerPrevHash hdr == pointHash t
= return $ MockState u c (headerPoint hdr)
| otherwise
= throwError $ MockInvalidHash (headerPrevHash hdr) (pointHash t)
updateMockUTxO :: HasMockTxs a
=> SlotNo
-> a
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockUTxO now = repeatedlyM (updateMockUTxO1 now) . getMockTxs
updateMockUTxO1 :: forall blk.
SlotNo
-> Tx
-> MockState blk
-> Except (MockError blk) (MockState blk)
updateMockUTxO1 now tx (MockState u c t) = case hasExpired of
Just e -> throwError e
Nothing -> do
u' <- withExcept MockUtxoError $ updateUtxo tx u
return $ MockState u' (c `Set.union` confirmed tx) t
where
Tx expiry _ins _outs = tx
hasExpired :: Maybe (MockError blk)
hasExpired = case expiry of
DoNotExpire -> Nothing
ExpireAtOnsetOf s -> do
guard $ s <= now
Just $ MockExpired s now
Genesis
Genesis
genesisMockState :: AddrDist -> MockState blk
genesisMockState addrDist = MockState {
mockUtxo = genesisUtxo addrDist
, mockConfirmed = Set.singleton (hashWithSerialiser toCBOR (genesisTx addrDist))
, mockTip = GenesisPoint
}
|
0ef61b08a8407498f6495f1eec1c9f3a91609815f4afb99b2e322ee27dd66542 | imdea-software/leap | YicesPairsQuery.mli |
(***********************************************************************)
(* *)
LEAP
(* *)
, IMDEA Software Institute
(* *)
(* *)
Copyright 2011 IMDEA Software Institute
(* *)
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 PairsQuery
module YicesPairsQuery : PAIRS_QUERY
| null | https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/solvers/backend/query/yices/YicesPairsQuery.mli | ocaml | *********************************************************************
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
********************************************************************* |
LEAP
, IMDEA Software Institute
Copyright 2011 IMDEA Software Institute
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND ,
open PairsQuery
module YicesPairsQuery : PAIRS_QUERY
|
d94d2f4ab9111d11b1f3c9c70ec784f53554484a213187dd1ce89d80068f1ff6 | tsahyt/clingo-haskell | TheoryAtoms.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Clingo.Control
import Clingo.Model
import Clingo.ProgramBuilding
import Clingo.Solving
import Clingo.Symbol
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Maybe
import Clingo.Inspection.Theory
printModel :: (MonadIO (m s), MonadModel m) => Model s -> m s ()
printModel m = do
syms <-
map prettySymbol <$> modelSymbols m (selectNone {selectShown = True})
liftIO (putStr "Model: " >> print syms)
theory ::
(MonadThrow m, MonadIO m)
=> TheoryAtoms s
-> ClingoT m s (AspifLiteral s)
theory t
-- obtain number of theory atoms via length
= do
size <- fromTheoryAtoms t length
liftIO (putStrLn $ "number of grounded theory atoms: " ++ show size)
-- find the atom b/1 and determine whether it has a guard
atomB <- fromTheoryAtoms t (head . filter (nameIs "b"))
liftIO
(putStrLn $
"theory atom b/1 has guard: " ++ show (isJust . atomGuard $ atomB))
return (atomLiteral atomB)
where
nameIs a x =
case termName (atomTerm x) of
Nothing -> False
Just b -> a == b
main :: IO ()
main =
withDefaultClingo $ do
addProgram "base" [] $
mconcat
[ "#theory t {"
, " term { + : 1, binary, left };"
, " &a/0 : term, any;"
, " &b/1 : term, {=}, term, any"
, "}."
, "x :- &a { 1+2 }."
, "y :- &b(3) { } = 17."
]
ground [Part "base" []] Nothing
lit <- theory =<< theoryAtoms
flip addGroundStatements [assume [lit]] =<< backend
withSolver [] (withModel printModel)
| null | https://raw.githubusercontent.com/tsahyt/clingo-haskell/083c84aae63565067644ccaa72223a4c12b33b88/examples/TheoryAtoms.hs | haskell | # LANGUAGE OverloadedStrings #
obtain number of theory atoms via length
find the atom b/1 and determine whether it has a guard |
module Main where
import Clingo.Control
import Clingo.Model
import Clingo.ProgramBuilding
import Clingo.Solving
import Clingo.Symbol
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Maybe
import Clingo.Inspection.Theory
printModel :: (MonadIO (m s), MonadModel m) => Model s -> m s ()
printModel m = do
syms <-
map prettySymbol <$> modelSymbols m (selectNone {selectShown = True})
liftIO (putStr "Model: " >> print syms)
theory ::
(MonadThrow m, MonadIO m)
=> TheoryAtoms s
-> ClingoT m s (AspifLiteral s)
theory t
= do
size <- fromTheoryAtoms t length
liftIO (putStrLn $ "number of grounded theory atoms: " ++ show size)
atomB <- fromTheoryAtoms t (head . filter (nameIs "b"))
liftIO
(putStrLn $
"theory atom b/1 has guard: " ++ show (isJust . atomGuard $ atomB))
return (atomLiteral atomB)
where
nameIs a x =
case termName (atomTerm x) of
Nothing -> False
Just b -> a == b
main :: IO ()
main =
withDefaultClingo $ do
addProgram "base" [] $
mconcat
[ "#theory t {"
, " term { + : 1, binary, left };"
, " &a/0 : term, any;"
, " &b/1 : term, {=}, term, any"
, "}."
, "x :- &a { 1+2 }."
, "y :- &b(3) { } = 17."
]
ground [Part "base" []] Nothing
lit <- theory =<< theoryAtoms
flip addGroundStatements [assume [lit]] =<< backend
withSolver [] (withModel printModel)
|
110069aed80eb06691b117b89ca78de94689f13df7395db68438a859b7a55e49 | cram2/cram | hypergeometric-randist.lisp | Regression test - RANDIST for GSLL , automatically generated
;;
Copyright 2009
Distributed under the terms of the GNU General Public License
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST HYPERGEOMETRIC-RANDIST
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST (LIST 2 1 0 0 1 1 3 1 0 1 3))
(MULTIPLE-VALUE-LIST
(LET ((RNG (MAKE-RANDOM-NUMBER-GENERATOR +MT19937+ 0)))
(LOOP FOR I FROM 0 TO 10 COLLECT
(sample rng :hypergeometric :n1 3 :n2 6 :tt 3)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.35714285714285693d0)
(MULTIPLE-VALUE-LIST (HYPERGEOMETRIC-PDF 0 2 6 3)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.892857142857143d0)
(MULTIPLE-VALUE-LIST (HYPERGEOMETRIC-P 1 2 6 3)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.10714285714285704d0)
(MULTIPLE-VALUE-LIST (HYPERGEOMETRIC-Q 1 2 6 3))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/tests/hypergeometric-randist.lisp | lisp |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | Regression test - RANDIST for GSLL , automatically generated
Copyright 2009
Distributed under the terms of the GNU General Public License
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST HYPERGEOMETRIC-RANDIST
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST (LIST 2 1 0 0 1 1 3 1 0 1 3))
(MULTIPLE-VALUE-LIST
(LET ((RNG (MAKE-RANDOM-NUMBER-GENERATOR +MT19937+ 0)))
(LOOP FOR I FROM 0 TO 10 COLLECT
(sample rng :hypergeometric :n1 3 :n2 6 :tt 3)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.35714285714285693d0)
(MULTIPLE-VALUE-LIST (HYPERGEOMETRIC-PDF 0 2 6 3)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.892857142857143d0)
(MULTIPLE-VALUE-LIST (HYPERGEOMETRIC-P 1 2 6 3)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.10714285714285704d0)
(MULTIPLE-VALUE-LIST (HYPERGEOMETRIC-Q 1 2 6 3))))
|
9ab82e32aec55b8a98938b06a183a47d7a42299111186792b0962e50f263e9f6 | re-ops/re-gent | log.clj | (ns re-gent.log
"log setup"
(:require
[re-share.log :as log]
[taoensso.timbre :refer (refer-timbre set-level!)]))
(refer-timbre)
(defn setup-logging
"Sets up logging configuration:
- steam collect logs
- log level
"
[& {:keys [level] :or {level :info}}]
(log/setup "re-gent" [])
(set-level! level))
(defn debug-on []
(set-level! :debug))
(defn debug-off []
(set-level! :debug))
| null | https://raw.githubusercontent.com/re-ops/re-gent/78bcd22011a31ca3f19a7221e87a6a7afd7682a5/src/re_gent/log.clj | clojure | (ns re-gent.log
"log setup"
(:require
[re-share.log :as log]
[taoensso.timbre :refer (refer-timbre set-level!)]))
(refer-timbre)
(defn setup-logging
"Sets up logging configuration:
- steam collect logs
- log level
"
[& {:keys [level] :or {level :info}}]
(log/setup "re-gent" [])
(set-level! level))
(defn debug-on []
(set-level! :debug))
(defn debug-off []
(set-level! :debug))
|
|
10c94130b9be22a16cd7d8ba8fa2247f580a4876c4193e3d9df3bfa825ea9b9d | oriansj/mes-m2 | load.scm | ;;; -*-scheme-*-
GNU --- Maxwell Equations of Software
Copyright © 2016 Jan ( janneke ) Nieuwenhuizen < >
;;;
This file is part of GNU .
;;;
GNU 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.
;;;
GNU 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 GNU . If not , see < / > .
(define the-answer 42)
| null | https://raw.githubusercontent.com/oriansj/mes-m2/b44fbc976ae334252de4eb82a57c361a195f2194/test/data/load.scm | scheme | -*-scheme-*-
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
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.
|
GNU --- Maxwell Equations of Software
Copyright © 2016 Jan ( janneke ) Nieuwenhuizen < >
This file is part of GNU .
under the terms of the GNU General Public License as published by
GNU is distributed in the hope that it will be useful , but
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define the-answer 42)
|
a9ef4dfa50ab7d57944c686b14250fc55f4e1e043fcda78cd2621cd36d11c8b0 | syntax-objects/syntax-parse-example | 2-test.rkt | #lang racket/base
(module+ test
(require rackunit
(only-in racket/port with-output-to-string)
syntax-parse-example/try-catch-finally/2)
(test-case "catch"
(check-equal?
(try
(raise-syntax-error #f "a syntax error")
(catch (exn:fail:syntax? e)
"got a syntax error"))
"got a syntax error"))
(test-case "cc"
(check-equal?
(with-output-to-string
(lambda ()
(let/cc up
(try
(displayln "at before")
(up (void))
(displayln "at after")
(finally (displayln "out"))))))
"at before\nout\n"))
)
| null | https://raw.githubusercontent.com/syntax-objects/syntax-parse-example/0675ce0717369afcde284202ec7df661d7af35aa/try-catch-finally/2-test.rkt | racket | #lang racket/base
(module+ test
(require rackunit
(only-in racket/port with-output-to-string)
syntax-parse-example/try-catch-finally/2)
(test-case "catch"
(check-equal?
(try
(raise-syntax-error #f "a syntax error")
(catch (exn:fail:syntax? e)
"got a syntax error"))
"got a syntax error"))
(test-case "cc"
(check-equal?
(with-output-to-string
(lambda ()
(let/cc up
(try
(displayln "at before")
(up (void))
(displayln "at after")
(finally (displayln "out"))))))
"at before\nout\n"))
)
|
|
9b56cfe7729d9c990d8021db18e2bbc1213fbca7784ffc277e89019dd65d26a8 | khasm-lang/khasmc | lamlift.ml | open Exp
open Kir
type lamctx = { frees : (kirval * kirtype) list }
[@@deriving show { with_path = false }]
let emptyctx () = { frees = [] }
let add_bound ctx v ts = { ctx with frees = (v, ts) :: ctx.frees }
let ctxwith frees = { frees }
let rec deconstruct_assoc_list al =
match al with
| [] -> ([], [])
| [ x ] -> ([ fst x ], [ snd x ])
| x :: xs ->
let a, b = deconstruct_assoc_list [ x ] in
let c, d = deconstruct_assoc_list xs in
(a @ c, b @ d)
let rec gen_lams ctx'frees inner =
match ctx'frees with
| [] -> ([], inner)
| x :: xs ->
let v, ts = x in
let a, b = gen_lams xs inner in
print_endline "loop?";
print_endline (show_kirexpr b);
let c, d = llift_expr (ctxwith ctx'frees) b in
(a @ c, d)
and gen_fcall ctx'frees inner =
match ctx'frees with
| [] -> inner
| x :: xs ->
let v, ts = x in
let t = gen_fcall xs inner in
Call (kirexpr_typ t, t, Val (ts, v))
and llift_expr ctx expr =
print_endline "\n\nDEBUG:";
print_endline (show_lamctx ctx);
print_endline (show_kirexpr expr);
print_endline "DONE;\n";
match expr with
| Val (_, _) | Int _ | Float _ | Str _ | Bool _ -> ([], expr)
| Tuple (ts, expr) ->
let tmp = List.map (llift_expr ctx) expr in
let a, b = deconstruct_assoc_list tmp in
(List.flatten a, Tuple (ts, b))
| Call (ts, e1, e2) ->
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx e2 in
(a @ c, Call (ts, b, d))
| Seq (ts, e1, e2) ->
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx e2 in
(a @ c, Seq (ts, b, d))
| TupAcc (ts, ex, i) ->
let a, b = llift_expr ctx ex in
(a, TupAcc (ts, b, i))
| Let (ts, v, e1, e2) ->
let ctx' = add_bound ctx v (kirexpr_typ e1) in
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx' e2 in
(a @ c, Let (ts, v, b, d))
| Lam (ts, v, e) ->
let ctx' = add_bound ctx v ts in
let added1, e' = llift_expr ctx' e in
print_endline "huh?";
print_endline (show_kirexpr e');
let added2, get = gen_lams ctx.frees e' in
let final = Let (ts, v, get) in
let asval = Val (ts, v) in
let call = gen_fcall ctx.frees asval in
print_endline "weird?";
print_endline (show_kirexpr call);
((final :: added1) @ added2, call)
| IfElse (ts, e1, e2, e3) ->
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx e2 in
let e, f = llift_expr ctx e3 in
(a @ c @ e, IfElse (ts, b, d, f))
let rec llift_top top =
match top with
| Extern (_, _, _) -> ([], top)
| Bind (_, _) -> ([], top)
| Let (ts, v, exp) ->
let added, n = llift_expr (emptyctx ()) exp in
(added, Let (ts, v, n))
| LetRec (ts, v, exp) ->
let added, n = llift_expr (emptyctx ()) exp in
(added, LetRec (ts, v, n))
let rec lambda_lift_h tops =
match tops with
| [] -> []
| x :: xs ->
let added, n = llift_top x in
(added @ (n :: [])) @ lambda_lift_h xs
let lambda_lift kir = (fst kir, lambda_lift_h @@ snd kir)
| null | https://raw.githubusercontent.com/khasm-lang/khasmc/e190cad60ba66e701ad0ae9d288ddb9a55e63a12/lib/middleend/lamlift.ml | ocaml | open Exp
open Kir
type lamctx = { frees : (kirval * kirtype) list }
[@@deriving show { with_path = false }]
let emptyctx () = { frees = [] }
let add_bound ctx v ts = { ctx with frees = (v, ts) :: ctx.frees }
let ctxwith frees = { frees }
let rec deconstruct_assoc_list al =
match al with
| [] -> ([], [])
| [ x ] -> ([ fst x ], [ snd x ])
| x :: xs ->
let a, b = deconstruct_assoc_list [ x ] in
let c, d = deconstruct_assoc_list xs in
(a @ c, b @ d)
let rec gen_lams ctx'frees inner =
match ctx'frees with
| [] -> ([], inner)
| x :: xs ->
let v, ts = x in
let a, b = gen_lams xs inner in
print_endline "loop?";
print_endline (show_kirexpr b);
let c, d = llift_expr (ctxwith ctx'frees) b in
(a @ c, d)
and gen_fcall ctx'frees inner =
match ctx'frees with
| [] -> inner
| x :: xs ->
let v, ts = x in
let t = gen_fcall xs inner in
Call (kirexpr_typ t, t, Val (ts, v))
and llift_expr ctx expr =
print_endline "\n\nDEBUG:";
print_endline (show_lamctx ctx);
print_endline (show_kirexpr expr);
print_endline "DONE;\n";
match expr with
| Val (_, _) | Int _ | Float _ | Str _ | Bool _ -> ([], expr)
| Tuple (ts, expr) ->
let tmp = List.map (llift_expr ctx) expr in
let a, b = deconstruct_assoc_list tmp in
(List.flatten a, Tuple (ts, b))
| Call (ts, e1, e2) ->
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx e2 in
(a @ c, Call (ts, b, d))
| Seq (ts, e1, e2) ->
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx e2 in
(a @ c, Seq (ts, b, d))
| TupAcc (ts, ex, i) ->
let a, b = llift_expr ctx ex in
(a, TupAcc (ts, b, i))
| Let (ts, v, e1, e2) ->
let ctx' = add_bound ctx v (kirexpr_typ e1) in
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx' e2 in
(a @ c, Let (ts, v, b, d))
| Lam (ts, v, e) ->
let ctx' = add_bound ctx v ts in
let added1, e' = llift_expr ctx' e in
print_endline "huh?";
print_endline (show_kirexpr e');
let added2, get = gen_lams ctx.frees e' in
let final = Let (ts, v, get) in
let asval = Val (ts, v) in
let call = gen_fcall ctx.frees asval in
print_endline "weird?";
print_endline (show_kirexpr call);
((final :: added1) @ added2, call)
| IfElse (ts, e1, e2, e3) ->
let a, b = llift_expr ctx e1 in
let c, d = llift_expr ctx e2 in
let e, f = llift_expr ctx e3 in
(a @ c @ e, IfElse (ts, b, d, f))
let rec llift_top top =
match top with
| Extern (_, _, _) -> ([], top)
| Bind (_, _) -> ([], top)
| Let (ts, v, exp) ->
let added, n = llift_expr (emptyctx ()) exp in
(added, Let (ts, v, n))
| LetRec (ts, v, exp) ->
let added, n = llift_expr (emptyctx ()) exp in
(added, LetRec (ts, v, n))
let rec lambda_lift_h tops =
match tops with
| [] -> []
| x :: xs ->
let added, n = llift_top x in
(added @ (n :: [])) @ lambda_lift_h xs
let lambda_lift kir = (fst kir, lambda_lift_h @@ snd kir)
|
|
80808b60c1ed857356a7a4eb33117e5b8314932afaa970621732fa023c5bdf28 | exercism/ocaml | bowling.mli | open Base
(** Abstract type for the bowling game. *)
type t
(** A new bowling game *)
val new_game: t
(** This is called each time the player rolls a ball, with input the number
of pins knocked down. The return value is the updated state of the game. *)
val roll : int -> t -> (t, string) Result.t
(** This is called at the end of a game to retrieve the final score. *)
val score : t -> (int, string) Result.t
| null | https://raw.githubusercontent.com/exercism/ocaml/bfd6121f757817865a34db06c3188b5e0ccab518/exercises/practice/bowling/bowling.mli | ocaml | * Abstract type for the bowling game.
* A new bowling game
* This is called each time the player rolls a ball, with input the number
of pins knocked down. The return value is the updated state of the game.
* This is called at the end of a game to retrieve the final score. | open Base
type t
val new_game: t
val roll : int -> t -> (t, string) Result.t
val score : t -> (int, string) Result.t
|
433458fbd1939ed546a73f823f8b129dfb17e6e9a99b1ed0cfc0ac80d7681fcf | alaricsp/chicken-scheme | srfi-18-tests.scm | (require-extension srfi-18)
(cond-expand (dribble
(define-for-syntax count 0)
(define-syntax trail
(lambda (form r c) ; doesn't bother much with renaming
(let ((loc (cadr form))
(expr (caddr form)))
(set! count (add1 count))
`(,(r 'begin)
(print "(" ,count ") " ,loc ": " ',expr ": get: " (##sys#slot get-mutex 5) ", put: " (##sys#slot put-mutex 5))
(let ((xxx ,expr))
(print " (" ,count ") " ,loc ": " ',expr ": get: " (##sys#slot get-mutex 5) ", put: " (##sys#slot put-mutex 5))
xxx) ) ))))
(else (define-syntax trail (syntax-rules () ((_ loc expr) expr)))))
(define (tprint . x)
(printf "~a " (current-milliseconds))
(apply print x))
(define (make-empty-mailbox)
(let ((put-mutex (make-mutex)) ; allow put! operation
(get-mutex (make-mutex))
(cell #f))
(define (put! obj)
(trail 'put! (mutex-lock! put-mutex #f #f)) ; prevent put! operation
(set! cell obj)
(trail 'put! (mutex-unlock! get-mutex)) )
(define (get!)
(trail 'get! (mutex-lock! get-mutex #f #f)) ; wait until object in mailbox
(let ((result cell))
(set! cell #f) ; prevent space leaks
(trail 'get! (mutex-unlock! put-mutex)) ; allow put! operation
result))
(trail 'main (mutex-lock! get-mutex #f #f)) ; prevent get! operation
(lambda (print)
(case print
((put!) put!)
((get!) get!)
(else (error "unknown message"))))))
(define (mailbox-put! m obj) ((m 'put!) obj))
(define (mailbox-get! m) ((m 'get!)))
;(tprint 'start)
(define mb (make-empty-mailbox))
(thread-start!
(make-thread
(lambda ()
(let lp ()
( print " 1 : get " )
(let ((x (mailbox-get! mb)))
;(tprint "read: " x)
(assert x)
(lp))))))
(thread-start!
(make-thread
(lambda ()
(thread-sleep! 1)
;(tprint 'put)
( print " 2 : put " )
(mailbox-put! mb 'test)
( print " 2 : endput " ) ) ) )
(thread-sleep! 3)
;(tprint 'exit)
| null | https://raw.githubusercontent.com/alaricsp/chicken-scheme/1eb14684c26b7c2250ca9b944c6b671cb62cafbc/tests/srfi-18-tests.scm | scheme | doesn't bother much with renaming
allow put! operation
prevent put! operation
wait until object in mailbox
prevent space leaks
allow put! operation
prevent get! operation
(tprint 'start)
(tprint "read: " x)
(tprint 'put)
(tprint 'exit) | (require-extension srfi-18)
(cond-expand (dribble
(define-for-syntax count 0)
(define-syntax trail
(let ((loc (cadr form))
(expr (caddr form)))
(set! count (add1 count))
`(,(r 'begin)
(print "(" ,count ") " ,loc ": " ',expr ": get: " (##sys#slot get-mutex 5) ", put: " (##sys#slot put-mutex 5))
(let ((xxx ,expr))
(print " (" ,count ") " ,loc ": " ',expr ": get: " (##sys#slot get-mutex 5) ", put: " (##sys#slot put-mutex 5))
xxx) ) ))))
(else (define-syntax trail (syntax-rules () ((_ loc expr) expr)))))
(define (tprint . x)
(printf "~a " (current-milliseconds))
(apply print x))
(define (make-empty-mailbox)
(get-mutex (make-mutex))
(cell #f))
(define (put! obj)
(set! cell obj)
(trail 'put! (mutex-unlock! get-mutex)) )
(define (get!)
(let ((result cell))
result))
(lambda (print)
(case print
((put!) put!)
((get!) get!)
(else (error "unknown message"))))))
(define (mailbox-put! m obj) ((m 'put!) obj))
(define (mailbox-get! m) ((m 'get!)))
(define mb (make-empty-mailbox))
(thread-start!
(make-thread
(lambda ()
(let lp ()
( print " 1 : get " )
(let ((x (mailbox-get! mb)))
(assert x)
(lp))))))
(thread-start!
(make-thread
(lambda ()
(thread-sleep! 1)
( print " 2 : put " )
(mailbox-put! mb 'test)
( print " 2 : endput " ) ) ) )
(thread-sleep! 3)
|
b3b18e5ee3b2c5c5d9c2fdb313c66b80a4cf1d915f4851959dae2f67a14fbc5e | racket/racket7 | pkgs-config.rkt | #lang racket/base
(require racket/cmdline
racket/format
racket/path)
;; Adjust the configuration to consult a catalog that is
;; expected to map some packages to directory links.
;; Used by the top-level Makefile in the main Racket repository.
(define config-dir-path (build-path "racket" "etc"))
(define config-file-path (build-path config-dir-path "config.rktd"))
(define catalog-relative-path (build-path 'up "share" "pkgs-catalog"))
(define catalog-relative-path-str (path->string catalog-relative-path))
(define-values (default-src-catalog src-catalog)
(command-line
#:args
(default-src-catalog src-catalog)
(values default-src-catalog src-catalog)))
(define src-catalog-is-default?
(equal? src-catalog default-src-catalog))
(when (file-exists? config-file-path)
(call-with-input-file*
config-file-path
(lambda (i)
(define r (read i))
(define l (hash-ref r 'catalogs #f))
(define starts-as-expected?
(and (list? l)
((length l) . >= . 1)
(equal? (car l) catalog-relative-path-str)))
(define has-src-catalog?
(or (and src-catalog-is-default?
(member #f l))
(member src-catalog l)))
(unless (and starts-as-expected?
has-src-catalog?)
(error 'pkgs-catalog
(~a "config file exists, but with a mismatched `catalogs';\n"
" the existing configuration does not ~a\n"
" config file: ~a\n"
" expected ~acatalog: ~s\n"
" possible solution: delete the config file")
(if (not starts-as-expected?)
"start as expected"
"include the specified catalog")
config-file-path
(if (not starts-as-expected?)
"initial "
"")
(if (not starts-as-expected?)
catalog-relative-path-str
src-catalog))))))
(unless (file-exists? config-file-path)
(printf "Writing ~a\n" config-file-path)
(call-with-output-file*
config-file-path
(lambda (o)
(write (hash 'catalogs
(cons catalog-relative-path-str
(append
(if src-catalog-is-default?
'()
(list src-catalog))
(list #f)))
'installation-name
"development"
'default-scope
"installation"
'interactive-file
'racket/interactive
'gui-interactive-file
'racket/gui/interactive)
o)
(newline o))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/pkgs-config.rkt | racket | Adjust the configuration to consult a catalog that is
expected to map some packages to directory links.
Used by the top-level Makefile in the main Racket repository. | #lang racket/base
(require racket/cmdline
racket/format
racket/path)
(define config-dir-path (build-path "racket" "etc"))
(define config-file-path (build-path config-dir-path "config.rktd"))
(define catalog-relative-path (build-path 'up "share" "pkgs-catalog"))
(define catalog-relative-path-str (path->string catalog-relative-path))
(define-values (default-src-catalog src-catalog)
(command-line
#:args
(default-src-catalog src-catalog)
(values default-src-catalog src-catalog)))
(define src-catalog-is-default?
(equal? src-catalog default-src-catalog))
(when (file-exists? config-file-path)
(call-with-input-file*
config-file-path
(lambda (i)
(define r (read i))
(define l (hash-ref r 'catalogs #f))
(define starts-as-expected?
(and (list? l)
((length l) . >= . 1)
(equal? (car l) catalog-relative-path-str)))
(define has-src-catalog?
(or (and src-catalog-is-default?
(member #f l))
(member src-catalog l)))
(unless (and starts-as-expected?
has-src-catalog?)
(error 'pkgs-catalog
(~a "config file exists, but with a mismatched `catalogs';\n"
" the existing configuration does not ~a\n"
" config file: ~a\n"
" expected ~acatalog: ~s\n"
" possible solution: delete the config file")
(if (not starts-as-expected?)
"start as expected"
"include the specified catalog")
config-file-path
(if (not starts-as-expected?)
"initial "
"")
(if (not starts-as-expected?)
catalog-relative-path-str
src-catalog))))))
(unless (file-exists? config-file-path)
(printf "Writing ~a\n" config-file-path)
(call-with-output-file*
config-file-path
(lambda (o)
(write (hash 'catalogs
(cons catalog-relative-path-str
(append
(if src-catalog-is-default?
'()
(list src-catalog))
(list #f)))
'installation-name
"development"
'default-scope
"installation"
'interactive-file
'racket/interactive
'gui-interactive-file
'racket/gui/interactive)
o)
(newline o))))
|
5b6cf03bbd286675c908046fa3f5d7c8bd925d2e357d75ffbd944dea610e57f4 | rudymatela/express | Derive.hs | # LANGUAGE TemplateHaskell , CPP #
-- |
-- Module : Data.Express.Express.Derive
Copyright : ( c ) 2019 - 2021
License : 3 - Clause BSD ( see the file LICENSE )
Maintainer : < >
--
Allows automatic derivation of ' Express ' typeclass instances .
module Data.Express.Express.Derive
( deriveExpress
, deriveExpressCascading
, deriveExpressIfNeeded
)
where
import Data.Express.Core
import Data.Express.Express
import Control.Monad
import Data.Char
import Data.List
import Data.Express.Utils.TH
import Data.Express.Utils.List
import Data.Express.Utils.String
import Language.Haskell.TH.Lib
| Derives an ' Express ' instance for the given type ' Name ' .
--
This function needs the extension .
--
-- If '-:', '->:', '->>:', '->>>:', ... are not in scope,
-- this will derive them as well.
deriveExpress :: Name -> DecsQ
deriveExpress = deriveWhenNeededOrWarn ''Express reallyDeriveExpress
-- | Same as 'deriveExpress' but does not warn when instance already exists
-- ('deriveExpress' is preferable).
deriveExpressIfNeeded :: Name -> DecsQ
deriveExpressIfNeeded = deriveWhenNeeded ''Express reallyDeriveExpress
| Derives a ' Express ' instance for a given type ' Name '
-- cascading derivation of type arguments as well.
deriveExpressCascading :: Name -> DecsQ
deriveExpressCascading = deriveWhenNeeded ''Express reallyDeriveExpressCascading
reallyDeriveExpress :: Name -> DecsQ
reallyDeriveExpress t = do
isEq <- t `isInstanceOf` ''Eq
isOrd <- t `isInstanceOf` ''Ord
(nt,vs) <- normalizeType t
#if __GLASGOW_HASKELL__ >= 710
cxt <- sequence [ [t| $(conT c) $(return v) |]
#else
template - haskell < = 2.9.0.0 :
cxt <- sequence [ classP c [return v]
#endif
| c <- ''Express:([''Eq | isEq] ++ [''Ord | isOrd])
, v <- vs]
cs <- typeConstructorsArgNames t
asName <- newName "x"
let withTheReturnTypeOfs = deriveWithTheReturnTypeOfs $ [length ns | (_,ns) <- cs]
let generalizableExpr = mergeIFns $ foldr1 mergeI
[ do let retTypeOf = mkName $ "-" ++ replicate (length ns) '>' ++ ":"
let exprs = [[| expr $(varE n) |] | n <- ns]
let conex = [| $(varE retTypeOf) $(conE c) $(varE asName) |]
let root = [| value $(stringE $ showJustName c) $(conex) |]
let rhs = foldl (\e1 e2 -> [| $e1 :$ $e2 |]) root exprs
[d| instance Express $(return nt) where
expr $(asP asName $ conP c (map varP ns)) = $rhs |]
| (c,ns) <- cs
]
withTheReturnTypeOfs |++| (cxt |=>| generalizableExpr)
Not only really derive Express instances ,
-- but cascade through argument types.
reallyDeriveExpressCascading :: Name -> DecsQ
reallyDeriveExpressCascading = reallyDeriveCascading ''Express reallyDeriveExpress
deriveWithTheReturnTypeOfs :: [Int] -> DecsQ
deriveWithTheReturnTypeOfs =
fmap concat . mapM deriveWithTheReturnTypeOf . nubSort
deriveWithTheReturnTypeOf :: Int -> DecsQ
deriveWithTheReturnTypeOf n = do
mf <- lookupValueName name
case mf of
Nothing -> reallyDeriveWithTheReturnTypeOf n
Just _ -> return []
where
name = "-" ++ replicate n '>' ++ ":"
reallyDeriveWithTheReturnTypeOf :: Int -> DecsQ
reallyDeriveWithTheReturnTypeOf n = do
td <- sigD name theT
vd <- [d| $(varP name) = const |]
return $ td:vd
where
theT = bind [t| $(theFunT) -> $(last vars) -> $(theFunT) |]
theFunT = foldr1 funT vars
funT t1 t2 = [t| $(t1) -> $(t2) |]
vars = map (varT . mkName) . take (n+1) . primeCycle $ map (:"") ['a'..'z']
name = mkName $ "-" ++ replicate n '>' ++ ":"
#if __GLASGOW_HASKELL__ >= 800
bind = id -- unbound variables are automatically bound
#else
bind = toBoundedQ
#endif
| null | https://raw.githubusercontent.com/rudymatela/express/7a59ecc1cd8e7ff7f2fbe76d33380006d329be8c/src/Data/Express/Express/Derive.hs | haskell | |
Module : Data.Express.Express.Derive
If '-:', '->:', '->>:', '->>>:', ... are not in scope,
this will derive them as well.
| Same as 'deriveExpress' but does not warn when instance already exists
('deriveExpress' is preferable).
cascading derivation of type arguments as well.
but cascade through argument types.
unbound variables are automatically bound | # LANGUAGE TemplateHaskell , CPP #
Copyright : ( c ) 2019 - 2021
License : 3 - Clause BSD ( see the file LICENSE )
Maintainer : < >
Allows automatic derivation of ' Express ' typeclass instances .
module Data.Express.Express.Derive
( deriveExpress
, deriveExpressCascading
, deriveExpressIfNeeded
)
where
import Data.Express.Core
import Data.Express.Express
import Control.Monad
import Data.Char
import Data.List
import Data.Express.Utils.TH
import Data.Express.Utils.List
import Data.Express.Utils.String
import Language.Haskell.TH.Lib
| Derives an ' Express ' instance for the given type ' Name ' .
This function needs the extension .
deriveExpress :: Name -> DecsQ
deriveExpress = deriveWhenNeededOrWarn ''Express reallyDeriveExpress
deriveExpressIfNeeded :: Name -> DecsQ
deriveExpressIfNeeded = deriveWhenNeeded ''Express reallyDeriveExpress
| Derives a ' Express ' instance for a given type ' Name '
deriveExpressCascading :: Name -> DecsQ
deriveExpressCascading = deriveWhenNeeded ''Express reallyDeriveExpressCascading
reallyDeriveExpress :: Name -> DecsQ
reallyDeriveExpress t = do
isEq <- t `isInstanceOf` ''Eq
isOrd <- t `isInstanceOf` ''Ord
(nt,vs) <- normalizeType t
#if __GLASGOW_HASKELL__ >= 710
cxt <- sequence [ [t| $(conT c) $(return v) |]
#else
template - haskell < = 2.9.0.0 :
cxt <- sequence [ classP c [return v]
#endif
| c <- ''Express:([''Eq | isEq] ++ [''Ord | isOrd])
, v <- vs]
cs <- typeConstructorsArgNames t
asName <- newName "x"
let withTheReturnTypeOfs = deriveWithTheReturnTypeOfs $ [length ns | (_,ns) <- cs]
let generalizableExpr = mergeIFns $ foldr1 mergeI
[ do let retTypeOf = mkName $ "-" ++ replicate (length ns) '>' ++ ":"
let exprs = [[| expr $(varE n) |] | n <- ns]
let conex = [| $(varE retTypeOf) $(conE c) $(varE asName) |]
let root = [| value $(stringE $ showJustName c) $(conex) |]
let rhs = foldl (\e1 e2 -> [| $e1 :$ $e2 |]) root exprs
[d| instance Express $(return nt) where
expr $(asP asName $ conP c (map varP ns)) = $rhs |]
| (c,ns) <- cs
]
withTheReturnTypeOfs |++| (cxt |=>| generalizableExpr)
Not only really derive Express instances ,
reallyDeriveExpressCascading :: Name -> DecsQ
reallyDeriveExpressCascading = reallyDeriveCascading ''Express reallyDeriveExpress
deriveWithTheReturnTypeOfs :: [Int] -> DecsQ
deriveWithTheReturnTypeOfs =
fmap concat . mapM deriveWithTheReturnTypeOf . nubSort
deriveWithTheReturnTypeOf :: Int -> DecsQ
deriveWithTheReturnTypeOf n = do
mf <- lookupValueName name
case mf of
Nothing -> reallyDeriveWithTheReturnTypeOf n
Just _ -> return []
where
name = "-" ++ replicate n '>' ++ ":"
reallyDeriveWithTheReturnTypeOf :: Int -> DecsQ
reallyDeriveWithTheReturnTypeOf n = do
td <- sigD name theT
vd <- [d| $(varP name) = const |]
return $ td:vd
where
theT = bind [t| $(theFunT) -> $(last vars) -> $(theFunT) |]
theFunT = foldr1 funT vars
funT t1 t2 = [t| $(t1) -> $(t2) |]
vars = map (varT . mkName) . take (n+1) . primeCycle $ map (:"") ['a'..'z']
name = mkName $ "-" ++ replicate n '>' ++ ":"
#if __GLASGOW_HASKELL__ >= 800
#else
bind = toBoundedQ
#endif
|
8692ee1e76cb74e989eb495766731d43771e9b88f5b6754cd8ff86ad02f3c3cb | erlang/erlide_kernel | erlide_builder_server.erl | %%% ******************************************************************************
Copyright ( c ) 2009 and others .
%%% All rights reserved. This program and the accompanying materials
%%% are made available under the terms of the Eclipse Public License v1.0
%%% which accompanies this distribution, and is available at
-v10.html
%%%
%%% Contributors:
%%% ******************************************************************************/
%%% File : erlide_builder.erl
Author :
%%% Description :
-module(erlide_builder_server).
-behaviour(gen_server).
%% --------------------------------------------------------------------
%% Include files
%% --------------------------------------------------------------------
-define(DEBUG , 1 ) .
-include_lib("erlide_common/include/erlide_dbglog.hrl").
%% --------------------------------------------------------------------
%% External exports
-export([
start/0,
stop/0,
add_project/2,
remove_project/1
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {slaves=[]}).
%% ====================================================================
%% External functions
%% ====================================================================
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], []).
stop() ->
gen_server:cast(?MODULE, stop).
add_project(Id, Data) ->
gen_server:call(?MODULE, {add_project, Id, Data}).
remove_project(Id) ->
gen_server:call(?MODULE, {remove_project, Id}).
%% ====================================================================
%% Server functions
%% ====================================================================
%% --------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%% Returns: {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% --------------------------------------------------------------------
init(_) ->
{ok, #state{}}.
%% --------------------------------------------------------------------
Function : handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%% --------------------------------------------------------------------
handle_call({add_project, Id, Data}, _From, #state{slaves=Slaves}=State) ->
{ok, Pid} = erlide_builder_slave:start(Id, Data),
erlang:monitor(process, Pid),
case lists:keytake(Id, 1, Slaves) of
{value, _, _} ->
{reply, {error, project_exists}, State};
false ->
erlide_log:log({builder_server, add_project, Id}),
{reply, {ok, Pid}, State#state{slaves=[{Id, Pid} | Slaves]}}
end;
handle_call({remove_project, Id}, _From, #state{slaves=Slaves}=State) ->
case lists:keytake(Id, 1, Slaves) of
{value, {Id, Pid}, NewSlaves} ->
erlide_log:log({builder_server, remove_project, Id}),
erlide_builder_slave:stop(Pid),
{reply, ok, State#state{slaves=NewSlaves}};
false ->
{reply, {error, no_project}, State}
end;
handle_call(Request, _From, State) ->
Reply = {error, unexpected, Request},
{reply, Reply, State}.
%% --------------------------------------------------------------------
%% Function: handle_cast/2
%% Description: Handling cast messages
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%% --------------------------------------------------------------------
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(_Msg, State) ->
{noreply, State}.
%% --------------------------------------------------------------------
%% Function: handle_info/2
%% Description: Handling all non call/cast messages
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%% --------------------------------------------------------------------
handle_info({'DOWN', _Mref, _, Pid, _Info}, #state{slaves=Slaves}=State) ->
NewSlaves = case lists:keytake(Pid, 2, Slaves) of
false ->
Slaves;
{value, {Id, Pid}, New} ->
erlide_log:log({builder_slave_died, Id}),
New
end,
{noreply, State#state{slaves=NewSlaves}};
handle_info(_Info, State) ->
{noreply, State}.
%% --------------------------------------------------------------------
%% Function: terminate/2
%% Description: Shutdown the server
%% Returns: any (ignored by gen_server)
%% --------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%% --------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%% Returns: {ok, NewState}
%% --------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% --------------------------------------------------------------------
Internal functions
%% --------------------------------------------------------------------
| null | https://raw.githubusercontent.com/erlang/erlide_kernel/763a7fe47213f374b59862fd5a17d5dcc2811c7b/common/apps/erlide_builder/src/erlide_builder_server.erl | erlang | ******************************************************************************
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
******************************************************************************/
File : erlide_builder.erl
Description :
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
External exports
gen_server callbacks
====================================================================
External functions
====================================================================
====================================================================
Server functions
====================================================================
--------------------------------------------------------------------
Function: init/1
Description: Initiates the server
Returns: {ok, State} |
ignore |
{stop, Reason}
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handling call messages
Returns: {reply, Reply, State} |
{stop, Reason, Reply, State} | (terminate/2 is called)
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_cast/2
Description: Handling cast messages
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_info/2
Description: Handling all non call/cast messages
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate/2
Description: Shutdown the server
Returns: any (ignored by gen_server)
--------------------------------------------------------------------
--------------------------------------------------------------------
Func: code_change/3
Purpose: Convert process state when code is changed
Returns: {ok, NewState}
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright ( c ) 2009 and others .
-v10.html
Author :
-module(erlide_builder_server).
-behaviour(gen_server).
-define(DEBUG , 1 ) .
-include_lib("erlide_common/include/erlide_dbglog.hrl").
-export([
start/0,
stop/0,
add_project/2,
remove_project/1
]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {slaves=[]}).
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], []).
stop() ->
gen_server:cast(?MODULE, stop).
add_project(Id, Data) ->
gen_server:call(?MODULE, {add_project, Id, Data}).
remove_project(Id) ->
gen_server:call(?MODULE, {remove_project, Id}).
{ ok , State , Timeout } |
init(_) ->
{ok, #state{}}.
Function : handle_call/3
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call({add_project, Id, Data}, _From, #state{slaves=Slaves}=State) ->
{ok, Pid} = erlide_builder_slave:start(Id, Data),
erlang:monitor(process, Pid),
case lists:keytake(Id, 1, Slaves) of
{value, _, _} ->
{reply, {error, project_exists}, State};
false ->
erlide_log:log({builder_server, add_project, Id}),
{reply, {ok, Pid}, State#state{slaves=[{Id, Pid} | Slaves]}}
end;
handle_call({remove_project, Id}, _From, #state{slaves=Slaves}=State) ->
case lists:keytake(Id, 1, Slaves) of
{value, {Id, Pid}, NewSlaves} ->
erlide_log:log({builder_server, remove_project, Id}),
erlide_builder_slave:stop(Pid),
{reply, ok, State#state{slaves=NewSlaves}};
false ->
{reply, {error, no_project}, State}
end;
handle_call(Request, _From, State) ->
Reply = {error, unexpected, Request},
{reply, Reply, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(_Msg, State) ->
{noreply, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_info({'DOWN', _Mref, _, Pid, _Info}, #state{slaves=Slaves}=State) ->
NewSlaves = case lists:keytake(Pid, 2, Slaves) of
false ->
Slaves;
{value, {Id, Pid}, New} ->
erlide_log:log({builder_slave_died, Id}),
New
end,
{noreply, State#state{slaves=NewSlaves}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
|
349248129384e593fa42ec88f32870a57cce51ce29f67ab8047c07ba3bda37c0 | mtgred/netrunner | users.cljs | (ns nr.users
(:require
[clojure.string :as str]
[nr.appstate :refer [app-state]]
[nr.utils :refer [non-game-toast]]
[nr.ws :as ws]
[reagent.core :as r]))
(def users-state (r/atom {}))
(defmethod ws/event-msg-handler :admin/fetch-users
[{{success :success} :?data}]
(when success
(reset!
users-state
(reduce
(fn [acc {:keys [ismoderator special tournament-organizer banned] :as user}]
(cond-> acc
ismoderator (update :mods conj user)
special (update :specials conj user)
tournament-organizer (update :tos conj user)
banned (update :banned conj user)))
{}
success))))
(defmethod ws/event-msg-handler :admin/user-edit
[{{:keys [error success]} :?data}]
(cond
error (non-game-toast error "error" nil)
success
(let [{:keys [action user-type user]} success]
(case action
:admin/add-user
(do (swap! users-state update user-type (fnil conj #{}) user)
(non-game-toast (str "Updated " (:username user)) "success" nil))
:admin/remove-user
(do (swap! users-state update user-type
(fn [lst elt] (remove #(= (:_id elt) (:_id %)) lst))
user)
(non-game-toast (str "Removed " (:username user)) "success" nil))
; else
(non-game-toast "Wrong action type" "error" nil)))))
(defn- remove-user
"Creates a handler which will remove the `user-type` from the user"
[user-type]
(fn [username]
(ws/ws-send! [:admin/edit-user {:action :admin/remove-user
:user-type user-type
:username username}])))
(defn- add-user
"Creates a handler which will add the `user-type` to the user"
[user-type]
(fn [username]
(ws/ws-send! [:admin/edit-user {:action :admin/add-user
:user-type user-type
:username username}])))
(defn- users-list [users remove-fn]
[:div.users-box.panel.blue-shade
[:ul.list
(doall
(for [d (sort-by #(str/lower-case (:username %)) @users)]
[:li.users-item
{:key (:_id d)}
[:span
[:button.delete
{:on-click #(remove-fn (:username d))}
"Remove"]]
[:span.title (:username d "")]]))]])
(defn- user-add [state state-key add-fn]
[:form.msg-box {:on-submit #(let [username (state-key @state "")]
(.preventDefault %)
(when-not (str/blank? username)
(add-fn username)
(swap! state assoc state-key "")))}
[:input {:type "text"
:placeholder "Type username"
:value (state-key @state "")
:on-change #(swap! state assoc state-key (-> % .-target .-value))}]
(let [username (state-key @state "")
disabled (str/blank? username)]
[:button {:disabled disabled
:class (if disabled "disabled" "")}
"Add"])])
(defn users-container []
(r/with-let [mods (r/cursor users-state [:mods])
specials (r/cursor users-state [:specials])
tos (r/cursor users-state [:tos])
banned (r/cursor users-state [:banned])]
(let [s (r/atom {})
rows [{:h3 "Moderators"
:cursor mods
:key :mods
:h4 "Add moderator"}
{:h3 "Alt Art Access"
:cursor specials
:key :specials
:h4 "Give user alt art access"}
{:h3 "Tournament Organizers"
:cursor tos
:key :tos
:h4 "Add Tournament Organizer"}
{:h3 "Banned Users"
:cursor banned
:key :banned
:h4 "Ban user"}]]
(fn []
(into [:div.container.panel.blue-shade.content-page]
(->> (for [row rows]
[[:h3 (:h3 row)]
(users-list (:cursor row) (remove-user (:key row)))
[:h4 (:h4 row)]
(user-add s (:key row) (add-user (:key row)))])
(interpose [[:br]])
(mapcat identity)
(map-indexed (fn [idx itm] ^{:key idx} itm))))))))
(defn users []
(r/with-let [user (r/cursor app-state [:user])]
(ws/ws-send! [:admin/fetch-users])
[:div.page-container
[:div.account-bg]
(when (or (:isadmin @user) (:ismoderator @user))
[users-container])]))
| null | https://raw.githubusercontent.com/mtgred/netrunner/7ef14ac2b02cd863879a339ffd7fbe2fa8d6e009/src/cljs/nr/users.cljs | clojure | else | (ns nr.users
(:require
[clojure.string :as str]
[nr.appstate :refer [app-state]]
[nr.utils :refer [non-game-toast]]
[nr.ws :as ws]
[reagent.core :as r]))
(def users-state (r/atom {}))
(defmethod ws/event-msg-handler :admin/fetch-users
[{{success :success} :?data}]
(when success
(reset!
users-state
(reduce
(fn [acc {:keys [ismoderator special tournament-organizer banned] :as user}]
(cond-> acc
ismoderator (update :mods conj user)
special (update :specials conj user)
tournament-organizer (update :tos conj user)
banned (update :banned conj user)))
{}
success))))
(defmethod ws/event-msg-handler :admin/user-edit
[{{:keys [error success]} :?data}]
(cond
error (non-game-toast error "error" nil)
success
(let [{:keys [action user-type user]} success]
(case action
:admin/add-user
(do (swap! users-state update user-type (fnil conj #{}) user)
(non-game-toast (str "Updated " (:username user)) "success" nil))
:admin/remove-user
(do (swap! users-state update user-type
(fn [lst elt] (remove #(= (:_id elt) (:_id %)) lst))
user)
(non-game-toast (str "Removed " (:username user)) "success" nil))
(non-game-toast "Wrong action type" "error" nil)))))
(defn- remove-user
"Creates a handler which will remove the `user-type` from the user"
[user-type]
(fn [username]
(ws/ws-send! [:admin/edit-user {:action :admin/remove-user
:user-type user-type
:username username}])))
(defn- add-user
"Creates a handler which will add the `user-type` to the user"
[user-type]
(fn [username]
(ws/ws-send! [:admin/edit-user {:action :admin/add-user
:user-type user-type
:username username}])))
(defn- users-list [users remove-fn]
[:div.users-box.panel.blue-shade
[:ul.list
(doall
(for [d (sort-by #(str/lower-case (:username %)) @users)]
[:li.users-item
{:key (:_id d)}
[:span
[:button.delete
{:on-click #(remove-fn (:username d))}
"Remove"]]
[:span.title (:username d "")]]))]])
(defn- user-add [state state-key add-fn]
[:form.msg-box {:on-submit #(let [username (state-key @state "")]
(.preventDefault %)
(when-not (str/blank? username)
(add-fn username)
(swap! state assoc state-key "")))}
[:input {:type "text"
:placeholder "Type username"
:value (state-key @state "")
:on-change #(swap! state assoc state-key (-> % .-target .-value))}]
(let [username (state-key @state "")
disabled (str/blank? username)]
[:button {:disabled disabled
:class (if disabled "disabled" "")}
"Add"])])
(defn users-container []
(r/with-let [mods (r/cursor users-state [:mods])
specials (r/cursor users-state [:specials])
tos (r/cursor users-state [:tos])
banned (r/cursor users-state [:banned])]
(let [s (r/atom {})
rows [{:h3 "Moderators"
:cursor mods
:key :mods
:h4 "Add moderator"}
{:h3 "Alt Art Access"
:cursor specials
:key :specials
:h4 "Give user alt art access"}
{:h3 "Tournament Organizers"
:cursor tos
:key :tos
:h4 "Add Tournament Organizer"}
{:h3 "Banned Users"
:cursor banned
:key :banned
:h4 "Ban user"}]]
(fn []
(into [:div.container.panel.blue-shade.content-page]
(->> (for [row rows]
[[:h3 (:h3 row)]
(users-list (:cursor row) (remove-user (:key row)))
[:h4 (:h4 row)]
(user-add s (:key row) (add-user (:key row)))])
(interpose [[:br]])
(mapcat identity)
(map-indexed (fn [idx itm] ^{:key idx} itm))))))))
(defn users []
(r/with-let [user (r/cursor app-state [:user])]
(ws/ws-send! [:admin/fetch-users])
[:div.page-container
[:div.account-bg]
(when (or (:isadmin @user) (:ismoderator @user))
[users-container])]))
|
33df4a91d2ceed69e24fec103c913e2d2397ba9653c46d0e88e1b74cb0a7e379 | privet-kitty/cl-competitive | integer-root.lisp | (defpackage :cp/integer-root
(:use :cl)
(:export #:iroot)
(:documentation
"Provides computation of the floor of the nth root of an integer."))
(in-package :cp/integer-root)
This value is set for SBCL x86 - 64
(defconstant +bit-width+ 62)
(deftype uint () '(unsigned-byte #.+bit-width+))
(declaim ((simple-array uint (*)) *supremums*))
(defparameter *supremums*
(make-array (+ 1 +bit-width+) :element-type 'uint))
(defun initialize ()
(let ((most-uint (ldb (byte +bit-width+ 0) -1)))
(loop for exp from 2 to +bit-width+
do (let ((ok 0)
(ng 1))
(loop while (<= (expt ng exp) most-uint)
do (setq ng (ash ng 1)))
(loop until (= (- ng ok) 1)
for mid = (ash (+ ng ok) -1)
when (<= (expt mid exp) most-uint)
do (setq ok mid)
else
do (setq ng mid))
(setf (aref *supremums* exp) ng)))))
(initialize)
(declaim (inline %power)
(ftype (function * (values uint &optional)) %power))
(defun %power (base exp)
"Is equivalent to CL:EXPT for this purpose."
(declare (uint base exp))
(let ((res 1))
(declare (uint res))
(loop when (oddp exp)
do (setq res (* res base))
do (setq exp (ash exp -1))
until (zerop exp)
do (setq base (* base base)))
res))
(declaim (ftype (function * (values uint &optional)) iroot))
(defun iroot (x index)
"Returns the greatest integer less than or equal to the non-negative INDEX-th
root of X."
(declare (optimize (speed 3))
(uint x)
((integer 1) index))
(locally (declare (optimize (safety 0)))
(cond ((zerop x) 0)
((> index +bit-width+) 1)
((>= index 3)
(let ((ok 0)
(ng (aref *supremums* index)))
(declare (uint ok ng))
(loop until (= (the uint (- ng ok)) 1)
for mid = (ldb (byte +bit-width+ 0)
(+ (ash ng -1) (ash ok -1)
(ash (+ (logand ng 1) (logand ok 1)) -1)))
when (<= (%power mid index) x)
do (setq ok mid)
else
do (setq ng mid))
ok))
((= index 2) (isqrt x))
(t x))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/c1c59532ccd1d7940b27c64362b957cebcf267a5/module/integer-root.lisp | lisp | (defpackage :cp/integer-root
(:use :cl)
(:export #:iroot)
(:documentation
"Provides computation of the floor of the nth root of an integer."))
(in-package :cp/integer-root)
This value is set for SBCL x86 - 64
(defconstant +bit-width+ 62)
(deftype uint () '(unsigned-byte #.+bit-width+))
(declaim ((simple-array uint (*)) *supremums*))
(defparameter *supremums*
(make-array (+ 1 +bit-width+) :element-type 'uint))
(defun initialize ()
(let ((most-uint (ldb (byte +bit-width+ 0) -1)))
(loop for exp from 2 to +bit-width+
do (let ((ok 0)
(ng 1))
(loop while (<= (expt ng exp) most-uint)
do (setq ng (ash ng 1)))
(loop until (= (- ng ok) 1)
for mid = (ash (+ ng ok) -1)
when (<= (expt mid exp) most-uint)
do (setq ok mid)
else
do (setq ng mid))
(setf (aref *supremums* exp) ng)))))
(initialize)
(declaim (inline %power)
(ftype (function * (values uint &optional)) %power))
(defun %power (base exp)
"Is equivalent to CL:EXPT for this purpose."
(declare (uint base exp))
(let ((res 1))
(declare (uint res))
(loop when (oddp exp)
do (setq res (* res base))
do (setq exp (ash exp -1))
until (zerop exp)
do (setq base (* base base)))
res))
(declaim (ftype (function * (values uint &optional)) iroot))
(defun iroot (x index)
"Returns the greatest integer less than or equal to the non-negative INDEX-th
root of X."
(declare (optimize (speed 3))
(uint x)
((integer 1) index))
(locally (declare (optimize (safety 0)))
(cond ((zerop x) 0)
((> index +bit-width+) 1)
((>= index 3)
(let ((ok 0)
(ng (aref *supremums* index)))
(declare (uint ok ng))
(loop until (= (the uint (- ng ok)) 1)
for mid = (ldb (byte +bit-width+ 0)
(+ (ash ng -1) (ash ok -1)
(ash (+ (logand ng 1) (logand ok 1)) -1)))
when (<= (%power mid index) x)
do (setq ok mid)
else
do (setq ng mid))
ok))
((= index 2) (isqrt x))
(t x))))
|
|
6a9d94d85507e4b78c011dbe10dea78c3364d0f894b11a8bffa760e15de24c32 | amoe/boson | run-server.sps | #! /usr/bin/env scheme-r6rs
#!r6rs
(import (rnrs)
(boson http))
(define httpd (web-server (list 'port 8080)))
(web-server-start httpd (lambda () #t))
| null | https://raw.githubusercontent.com/amoe/boson/51c77d8f9a08da39315d76cbba9e4d9ad318efe7/run-server.sps | scheme | #! /usr/bin/env scheme-r6rs
#!r6rs
(import (rnrs)
(boson http))
(define httpd (web-server (list 'port 8080)))
(web-server-start httpd (lambda () #t))
|
|
0e2ead6ceecb14a75fdd9d44acc44a23ea4d4e4c7a237c7e2f0d13913ec399c5 | MedeaMelana/JsonGrammar2 | Types.hs | module Types where
import Data.Text (Text)
data Person = Person
{ name :: Text
, gender :: Gender
, age :: Int
, location :: Coords
} deriving (Show, Eq)
data Coords = Coords { lat :: Float, lng :: Float }
deriving (Show, Eq)
data Gender = Male | Female deriving (Show, Eq)
| null | https://raw.githubusercontent.com/MedeaMelana/JsonGrammar2/1d3976f9ec5a00940cc9fc6f29a173df9b621bd4/tests/Types.hs | haskell | module Types where
import Data.Text (Text)
data Person = Person
{ name :: Text
, gender :: Gender
, age :: Int
, location :: Coords
} deriving (Show, Eq)
data Coords = Coords { lat :: Float, lng :: Float }
deriving (Show, Eq)
data Gender = Male | Female deriving (Show, Eq)
|
|
4b69d7894764e1c12a82a3c317ac14712e9c19cfda91d7bf0a9efe880c3012a8 | maximedenes/native-coq | unification.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Term
open Environ
open Evd
type unify_flags = {
modulo_conv_on_closed_terms : Names.transparent_state option;
use_metas_eagerly_in_conv_on_closed_terms : bool;
modulo_delta : Names.transparent_state;
modulo_delta_types : Names.transparent_state;
check_applied_meta_types : bool;
resolve_evars : bool;
use_pattern_unification : bool;
use_meta_bound_pattern_unification : bool;
frozen_evars : ExistentialSet.t;
restrict_conv_on_strict_subterms : bool;
modulo_betaiota : bool;
modulo_eta : bool;
allow_K_in_toplevel_higher_order_unification : bool
}
val default_unify_flags : unify_flags
val default_no_delta_unify_flags : unify_flags
val elim_flags : unify_flags
val elim_no_delta_flags : unify_flags
(** The "unique" unification fonction *)
val w_unify :
env -> evar_map -> conv_pb -> ?flags:unify_flags -> constr -> constr -> evar_map
(** [w_unify_to_subterm env (c,t) m] performs unification of [c] with a
subterm of [t]. Constraints are added to [m] and the matched
subterm of [t] is also returned. *)
val w_unify_to_subterm :
env -> evar_map -> ?flags:unify_flags -> constr * constr -> evar_map * constr
val w_unify_to_subterm_all :
env -> evar_map -> ?flags:unify_flags -> constr * constr -> (evar_map * constr) list
val w_unify_meta_types : env -> ?flags:unify_flags -> evar_map -> evar_map
* [ w_coerce_to_type env evd c ] tries to coerce [ c ] of type
[ ctyp ] so that its gets type [ typ ] ; [ typ ] may contain metavariables
[ctyp] so that its gets type [typ]; [typ] may contain metavariables *)
val w_coerce_to_type : env -> evar_map -> constr -> types -> types ->
evar_map * constr
(*i This should be in another module i*)
(** [abstract_list_all env evd t c l]
abstracts the terms in l over c to get a term of type t
(exported for inv.ml) *)
val abstract_list_all :
env -> evar_map -> constr -> constr -> constr list -> constr
(* For tracing *)
val w_merge : env -> bool -> unify_flags -> evar_map *
(metavariable * constr * (instance_constraint * instance_typing_status)) list *
(env * types pexistential * types) list -> evar_map
val unify_0 : Environ.env ->
Evd.evar_map ->
Evd.conv_pb ->
unify_flags ->
Term.types ->
Term.types ->
Evd.evar_map * Evd.metabinding list *
(Environ.env * Term.types Term.pexistential * Term.constr) list
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/pretyping/unification.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* The "unique" unification fonction
* [w_unify_to_subterm env (c,t) m] performs unification of [c] with a
subterm of [t]. Constraints are added to [m] and the matched
subterm of [t] is also returned.
i This should be in another module i
* [abstract_list_all env evd t c l]
abstracts the terms in l over c to get a term of type t
(exported for inv.ml)
For tracing | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Term
open Environ
open Evd
type unify_flags = {
modulo_conv_on_closed_terms : Names.transparent_state option;
use_metas_eagerly_in_conv_on_closed_terms : bool;
modulo_delta : Names.transparent_state;
modulo_delta_types : Names.transparent_state;
check_applied_meta_types : bool;
resolve_evars : bool;
use_pattern_unification : bool;
use_meta_bound_pattern_unification : bool;
frozen_evars : ExistentialSet.t;
restrict_conv_on_strict_subterms : bool;
modulo_betaiota : bool;
modulo_eta : bool;
allow_K_in_toplevel_higher_order_unification : bool
}
val default_unify_flags : unify_flags
val default_no_delta_unify_flags : unify_flags
val elim_flags : unify_flags
val elim_no_delta_flags : unify_flags
val w_unify :
env -> evar_map -> conv_pb -> ?flags:unify_flags -> constr -> constr -> evar_map
val w_unify_to_subterm :
env -> evar_map -> ?flags:unify_flags -> constr * constr -> evar_map * constr
val w_unify_to_subterm_all :
env -> evar_map -> ?flags:unify_flags -> constr * constr -> (evar_map * constr) list
val w_unify_meta_types : env -> ?flags:unify_flags -> evar_map -> evar_map
* [ w_coerce_to_type env evd c ] tries to coerce [ c ] of type
[ ctyp ] so that its gets type [ typ ] ; [ typ ] may contain metavariables
[ctyp] so that its gets type [typ]; [typ] may contain metavariables *)
val w_coerce_to_type : env -> evar_map -> constr -> types -> types ->
evar_map * constr
val abstract_list_all :
env -> evar_map -> constr -> constr -> constr list -> constr
val w_merge : env -> bool -> unify_flags -> evar_map *
(metavariable * constr * (instance_constraint * instance_typing_status)) list *
(env * types pexistential * types) list -> evar_map
val unify_0 : Environ.env ->
Evd.evar_map ->
Evd.conv_pb ->
unify_flags ->
Term.types ->
Term.types ->
Evd.evar_map * Evd.metabinding list *
(Environ.env * Term.types Term.pexistential * Term.constr) list
|
8f522bfe0b21a3008d84f67993fd40ee8db258dd68a32b01176f205e5da6c703 | borkdude/advent-of-cljc | dfuenzalida.cljc | (ns aoc.y2017.d07.dfuenzalida
(:refer-clojure :exclude [read-string format])
(:require
[aoc.utils :as u :refer [deftest read-string format]]
[aoc.y2017.d07.data :refer [input answer-1 answer-2]]
[clojure.string :as s]
[clojure.test :as t :refer [is testing]]))
(defn parents-in [[k vs]]
(reduce merge {}
(map #(hash-map % k) vs)))
(defn parents-map [m]
(reduce merge (map parents-in m)))
(defn parse-line [s]
(let [[_ parent weight] (first (re-seq #"(\w+) \((\d+)\)" s))
[_ s2] (first (re-seq #".* -> (.*)" s))
children (when s2 (s/split s2 #", "))]
[parent (read-string weight) children]))
(defn lines-to-children-map [lines]
(->> lines
(map parse-line)
(map (juxt first last)) ;; name and children
(filter last) ;; leave only nodes with children
(into {})
parents-map))
(defn find-root [lines]
(let [data-map (lines-to-children-map lines)]
(first
(filter #(nil? (data-map %))
(vals data-map)))))
(defn read-input []
(s/split-lines input))
(defn solve-1 []
(find-root (read-input)))
(defn root-name []
(find-root (read-input)))
(defn load-map [lines f]
(->> lines
(map parse-line)
(map f)
we do n't want nil values in the hashmap
(into {})))
(defn weight [weight-map children-map node]
(+ (weight-map node)
(reduce +
(map (partial weight weight-map children-map)
(children-map node)))))
(defn unbalanced [weight-map children-map node]
(if (<= (count (into #{} (map (partial weight weight-map children-map)
(children-map node)))) 1)
node ;; the current node is not balanced, all children have same weight
(let [unb-child (->> (map (juxt identity
(partial weight weight-map children-map))
(children-map node))
(group-by second)
(filter #(= 1 (count (second %))))
first second first first)]
(unbalanced weight-map children-map unb-child))))
(defn solve-2 []
(let [input (read-input)
large-weight-map (load-map input (juxt first second))
large-children-map (load-map input (juxt first last))
large-unbalanced (unbalanced large-weight-map large-children-map (root-name))
large-parent-map (lines-to-children-map input)
large-desired-tree (->> large-unbalanced
large-parent-map
large-children-map
(filter #(not= large-unbalanced %))
first
(weight large-weight-map large-children-map))]
(+ (large-weight-map large-unbalanced)
(- large-desired-tree
(weight large-weight-map large-children-map large-unbalanced)))))
(deftest part-1
(is (= (str answer-1)
(str (solve-1)))))
(deftest part-2
(is (= (str answer-2)
(str (solve-2)))))
;;;; Scratch
(comment
(t/run-tests)
)
| null | https://raw.githubusercontent.com/borkdude/advent-of-cljc/17c8abb876b95ab01eee418f1da2e402e845c596/src/aoc/y2017/d07/dfuenzalida.cljc | clojure | name and children
leave only nodes with children
the current node is not balanced, all children have same weight
Scratch | (ns aoc.y2017.d07.dfuenzalida
(:refer-clojure :exclude [read-string format])
(:require
[aoc.utils :as u :refer [deftest read-string format]]
[aoc.y2017.d07.data :refer [input answer-1 answer-2]]
[clojure.string :as s]
[clojure.test :as t :refer [is testing]]))
(defn parents-in [[k vs]]
(reduce merge {}
(map #(hash-map % k) vs)))
(defn parents-map [m]
(reduce merge (map parents-in m)))
(defn parse-line [s]
(let [[_ parent weight] (first (re-seq #"(\w+) \((\d+)\)" s))
[_ s2] (first (re-seq #".* -> (.*)" s))
children (when s2 (s/split s2 #", "))]
[parent (read-string weight) children]))
(defn lines-to-children-map [lines]
(->> lines
(map parse-line)
(into {})
parents-map))
(defn find-root [lines]
(let [data-map (lines-to-children-map lines)]
(first
(filter #(nil? (data-map %))
(vals data-map)))))
(defn read-input []
(s/split-lines input))
(defn solve-1 []
(find-root (read-input)))
(defn root-name []
(find-root (read-input)))
(defn load-map [lines f]
(->> lines
(map parse-line)
(map f)
we do n't want nil values in the hashmap
(into {})))
(defn weight [weight-map children-map node]
(+ (weight-map node)
(reduce +
(map (partial weight weight-map children-map)
(children-map node)))))
(defn unbalanced [weight-map children-map node]
(if (<= (count (into #{} (map (partial weight weight-map children-map)
(children-map node)))) 1)
(let [unb-child (->> (map (juxt identity
(partial weight weight-map children-map))
(children-map node))
(group-by second)
(filter #(= 1 (count (second %))))
first second first first)]
(unbalanced weight-map children-map unb-child))))
(defn solve-2 []
(let [input (read-input)
large-weight-map (load-map input (juxt first second))
large-children-map (load-map input (juxt first last))
large-unbalanced (unbalanced large-weight-map large-children-map (root-name))
large-parent-map (lines-to-children-map input)
large-desired-tree (->> large-unbalanced
large-parent-map
large-children-map
(filter #(not= large-unbalanced %))
first
(weight large-weight-map large-children-map))]
(+ (large-weight-map large-unbalanced)
(- large-desired-tree
(weight large-weight-map large-children-map large-unbalanced)))))
(deftest part-1
(is (= (str answer-1)
(str (solve-1)))))
(deftest part-2
(is (= (str answer-2)
(str (solve-2)))))
(comment
(t/run-tests)
)
|
55c0b10da135e588f1409033d8c64efa6b6ce7aab5f19fc1bdc973815a91e523 | rbardou/red | spawn.mli | (** Spawn cooperative threads and run them. *)
* { 2 Groups }
(** Collections of tasks. *)
type group
(** The default group for new tasks. *)
val default_group: group
* Create a new empty collection of tasks .
Subtasks ( tasks spawned by other tasks ) belong to the group of their parent by default .
Root tasks ( tasks which are spawned outside of any task ) belong to [ default ] .
Subtasks (tasks spawned by other tasks) belong to the group of their parent by default.
Root tasks (tasks which are spawned outside of any task) belong to [default]. *)
val group: unit -> group
(** Cancel all tasks of a given collection.
If you try to add a task to a dead group, the task will just be ignored.
Warning: if a task is responsible of cleaning up something
(like closing open file descriptors or terminating open processes),
killing it will prevent the cleanup. So don't have tasks be responsible of
cleaning up if you intend to potentially kill them.
Note that this does not actually remove the tasks immediately from the list
of pending task. They are removed when the scheduler runs. *)
val kill: group -> unit
(** Return whether a group is still active, or if it has been killed. *)
val is_active: group -> bool
* { 2 Low - Level Tasks }
(** Spawn a task to be executed as soon as possible but not immediately. *)
val task: ?group: group -> (unit -> unit) -> unit
* Spawn a task to be executed at a given time ( as returned by [ Unix.gettimeofday ] ) .
val alarm: ?group: group -> float -> (unit -> unit) -> unit
* Spawn a task to be executed after a given time interval ( in seconds ) .
val sleep: ?group: group -> float -> (unit -> unit) -> unit
(** Spawn a task to be executed as soon as a file descriptor can be read without blocking.
This includes reading "end of file". *)
val on_read: ?group: group -> Unix.file_descr -> (unit -> unit) -> unit
(** Spawn a task to be executed as soon as a file descriptor can be written without blocking.
Writing too much data may still block. *)
val on_write: ?group: group -> Unix.file_descr -> (unit -> unit) -> unit
* { 2 Execution }
* Run one iteration of the scheduler .
The scheduler does not catch exceptions . If an exception is raised by a task , this may cause
other tasks to be arbitrarily killed , so you should stop the program immediately .
[ on_wait ] is called after tasks which could be run immediately have been run ,
i.e. just before waiting on file descriptors . It is called even if there is nothing to wait for .
The scheduler does not catch exceptions. If an exception is raised by a task, this may cause
other tasks to be arbitrarily killed, so you should stop the program immediately.
[on_wait] is called after tasks which could be run immediately have been run,
i.e. just before waiting on file descriptors. It is called even if there is nothing to wait for. *)
val run_once: ?on_wait: (unit -> unit) -> unit -> unit
(** Run the scheduler until there is no pending task. *)
val run: ?on_wait: (unit -> unit) -> unit -> unit
| null | https://raw.githubusercontent.com/rbardou/red/e23c2830909b9e5cd6afe563313435ddaeda90bf/termlib/spawn.mli | ocaml | * Spawn cooperative threads and run them.
* Collections of tasks.
* The default group for new tasks.
* Cancel all tasks of a given collection.
If you try to add a task to a dead group, the task will just be ignored.
Warning: if a task is responsible of cleaning up something
(like closing open file descriptors or terminating open processes),
killing it will prevent the cleanup. So don't have tasks be responsible of
cleaning up if you intend to potentially kill them.
Note that this does not actually remove the tasks immediately from the list
of pending task. They are removed when the scheduler runs.
* Return whether a group is still active, or if it has been killed.
* Spawn a task to be executed as soon as possible but not immediately.
* Spawn a task to be executed as soon as a file descriptor can be read without blocking.
This includes reading "end of file".
* Spawn a task to be executed as soon as a file descriptor can be written without blocking.
Writing too much data may still block.
* Run the scheduler until there is no pending task. |
* { 2 Groups }
type group
val default_group: group
* Create a new empty collection of tasks .
Subtasks ( tasks spawned by other tasks ) belong to the group of their parent by default .
Root tasks ( tasks which are spawned outside of any task ) belong to [ default ] .
Subtasks (tasks spawned by other tasks) belong to the group of their parent by default.
Root tasks (tasks which are spawned outside of any task) belong to [default]. *)
val group: unit -> group
val kill: group -> unit
val is_active: group -> bool
* { 2 Low - Level Tasks }
val task: ?group: group -> (unit -> unit) -> unit
* Spawn a task to be executed at a given time ( as returned by [ Unix.gettimeofday ] ) .
val alarm: ?group: group -> float -> (unit -> unit) -> unit
* Spawn a task to be executed after a given time interval ( in seconds ) .
val sleep: ?group: group -> float -> (unit -> unit) -> unit
val on_read: ?group: group -> Unix.file_descr -> (unit -> unit) -> unit
val on_write: ?group: group -> Unix.file_descr -> (unit -> unit) -> unit
* { 2 Execution }
* Run one iteration of the scheduler .
The scheduler does not catch exceptions . If an exception is raised by a task , this may cause
other tasks to be arbitrarily killed , so you should stop the program immediately .
[ on_wait ] is called after tasks which could be run immediately have been run ,
i.e. just before waiting on file descriptors . It is called even if there is nothing to wait for .
The scheduler does not catch exceptions. If an exception is raised by a task, this may cause
other tasks to be arbitrarily killed, so you should stop the program immediately.
[on_wait] is called after tasks which could be run immediately have been run,
i.e. just before waiting on file descriptors. It is called even if there is nothing to wait for. *)
val run_once: ?on_wait: (unit -> unit) -> unit -> unit
val run: ?on_wait: (unit -> unit) -> unit -> unit
|
470c580bdf21ae087db9de253c6e5f4cd695b7ad7a613a7c33d64f70b71b561d | byteally/dbrecord | PPCheck.hs | {-# LANGUAGE OverloadedStrings #-}
module Test.DBRecord.PPCheck where
import qualified DBRecord.Postgres.Internal.Sql.Pretty as PG
import qualified DBRecord.MSSQL.Internal.Sql.Pretty as MSSQL
import qualified DBRecord.MySQL.Internal.Sql.Pretty as MySQL
import qualified DBRecord.Sqlite.Internal.Sql.Pretty as SQLite
import DBRecord.Internal.PrimQuery
import DBRecord.Internal.Expr as E
import Data.Aeson
import DBRecord.Query
import DBRecord.Internal.Schema hiding (insert, name, version)
import DBRecord.Internal.Common
import DBRecord.Internal.Types
import DBRecord.Schema
import DBRecord.Internal.DBTypes
import DBRecord.Internal.Sql.SqlGen
import qualified Data.List.NonEmpty as NEL
ppUpsert :: Int -> Int -> Int -> {-Value ->-} IO ()
ppUpsert qid groupId viewId {-offset-} = do
let updRunQ = toUpdQuery "queue_offset" runFlts runKeyVals
( " current_offset " , . E.toNullable . $ offset )
("view_id", toConst viewId)
]
runFlts = [ BinExpr OpEq (AttrExpr (Sym ["queue_offset"] "queue_id")) (toConst qid)
, BinExpr OpEq (AttrExpr (Sym ["queue_offset"] "consumer_group_id")) (toConst groupId)
, BinExpr OpEq ( AttrExpr ( Sym [ ] " view_id " ) ) ( toConst viewId )
]
insQ = toInsQuery "queue_offset" keyVals (Just (Conflict (ConflictColumn ["view_id", "queue_id"]) (ConflictUpdate updRunQ))) []
( " current_offset " , . E.toNullable . $ offset )
("queue_id", toConst qid)
, ("consumer_group_id", toConst groupId)
-- , ("view_id", toConst viewId)
]
insQSql = insertSql insQ
updQSql = updateSql updRunQ
putStrLn "-----Postgresql-------"
putStrLn (PG.renderInsert insQSql)
putStrLn (PG.renderUpdate updQSql)
putStrLn "----------------------"
putStrLn "--------MSSQL---------"
putStrLn (MSSQL.renderInsert insQSql)
putStrLn "----------------------"
putStrLn "-------SQLITE---------"
putStrLn (SQLite.renderInsert insQSql)
putStrLn "----------------------"
putStrLn "--------MySQL----------"
putStrLn (MySQL.renderInsert insQSql)
putStrLn "----------------------"
toInsQuery tab keyVals ret =
let tabId = TableId "workflow" "public" tab
(keys, vals) = unzip keyVals
in InsertQuery tabId keys (vals NEL.:| []) ret
toUpdQuery tab flts keyVals =
let tabId = TableId "workflow" "public" tab
in UpdateQuery tabId flts keyVals []
toDelQuery tab flts =
let tabId = TableId "workflow" "public" tab
in DeleteQuery tabId flts
toConst :: ConstExpr t => t -> PrimExpr
toConst = getExpr . constExpr
| null | https://raw.githubusercontent.com/byteally/dbrecord/991efe9a293532ee9242b3e9a26434cf16f5b2a0/dbrecord-test/src/Test/DBRecord/PPCheck.hs | haskell | # LANGUAGE OverloadedStrings #
Value ->
offset
, ("view_id", toConst viewId) | module Test.DBRecord.PPCheck where
import qualified DBRecord.Postgres.Internal.Sql.Pretty as PG
import qualified DBRecord.MSSQL.Internal.Sql.Pretty as MSSQL
import qualified DBRecord.MySQL.Internal.Sql.Pretty as MySQL
import qualified DBRecord.Sqlite.Internal.Sql.Pretty as SQLite
import DBRecord.Internal.PrimQuery
import DBRecord.Internal.Expr as E
import Data.Aeson
import DBRecord.Query
import DBRecord.Internal.Schema hiding (insert, name, version)
import DBRecord.Internal.Common
import DBRecord.Internal.Types
import DBRecord.Schema
import DBRecord.Internal.DBTypes
import DBRecord.Internal.Sql.SqlGen
import qualified Data.List.NonEmpty as NEL
let updRunQ = toUpdQuery "queue_offset" runFlts runKeyVals
( " current_offset " , . E.toNullable . $ offset )
("view_id", toConst viewId)
]
runFlts = [ BinExpr OpEq (AttrExpr (Sym ["queue_offset"] "queue_id")) (toConst qid)
, BinExpr OpEq (AttrExpr (Sym ["queue_offset"] "consumer_group_id")) (toConst groupId)
, BinExpr OpEq ( AttrExpr ( Sym [ ] " view_id " ) ) ( toConst viewId )
]
insQ = toInsQuery "queue_offset" keyVals (Just (Conflict (ConflictColumn ["view_id", "queue_id"]) (ConflictUpdate updRunQ))) []
( " current_offset " , . E.toNullable . $ offset )
("queue_id", toConst qid)
, ("consumer_group_id", toConst groupId)
]
insQSql = insertSql insQ
updQSql = updateSql updRunQ
putStrLn "-----Postgresql-------"
putStrLn (PG.renderInsert insQSql)
putStrLn (PG.renderUpdate updQSql)
putStrLn "----------------------"
putStrLn "--------MSSQL---------"
putStrLn (MSSQL.renderInsert insQSql)
putStrLn "----------------------"
putStrLn "-------SQLITE---------"
putStrLn (SQLite.renderInsert insQSql)
putStrLn "----------------------"
putStrLn "--------MySQL----------"
putStrLn (MySQL.renderInsert insQSql)
putStrLn "----------------------"
toInsQuery tab keyVals ret =
let tabId = TableId "workflow" "public" tab
(keys, vals) = unzip keyVals
in InsertQuery tabId keys (vals NEL.:| []) ret
toUpdQuery tab flts keyVals =
let tabId = TableId "workflow" "public" tab
in UpdateQuery tabId flts keyVals []
toDelQuery tab flts =
let tabId = TableId "workflow" "public" tab
in DeleteQuery tabId flts
toConst :: ConstExpr t => t -> PrimExpr
toConst = getExpr . constExpr
|
17f0072668e50a18e19f67604155947fb0112a879e2859e371ecfd30a8406b89 | huiqing/percept2 | egd_primitives.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%% @doc egd_primitives
%%
-module(egd_primitives).
-export([
create/2,
color/1,
pixel/3,
polygon/3,
line/4,
line/5,
arc/4,
arc/5,
rectangle/4,
filledRectangle/4,
filledEllipse/4,
filledTriangle/5,
text/5
]).
-export([
info/1,
object_info/1,
rgb_float2byte/1
]).
-export([
arc_to_edges/3,
convex_hull/1,
edges/1
]).
-include("egd.hrl").
%% API info
info(I) ->
W = I#image.width, H = I#image.height,
io:format("Dimensions: ~p x ~p~n", [W,H]),
io:format("Number of image objects: ~p~n", [length(I#image.objects)]),
TotalPoints = info_objects(I#image.objects,0),
io:format("Total points: ~p [~p %]~n", [TotalPoints, 100*TotalPoints/(W*H)]),
ok.
info_objects([],N) -> N;
info_objects([O | Os],N) ->
Points = length(O#image_object.points),
info_objects(Os,N+Points).
object_info(O) ->
io:format("Object information: ~p~n", [O#image_object.type]),
io:format("- Number of points: ~p~n", [length(O#image_object.points)]),
io:format("- Bounding box: ~p~n", [O#image_object.span]),
io:format("- Color: ~p~n", [O#image_object.color]),
ok.
%% interface functions
line(I, Sp, Ep, Color) ->
I#image{ objects = [
#image_object{
type = line,
points = [Sp, Ep],
span = span([Sp, Ep]),
color = Color} | I#image.objects]}.
line(I, Sp, Ep, Stroke, Color) ->
I#image{ objects = [
#image_object{
type = line,
points = [Sp, Ep],
span = span([Sp, Ep]),
internals = Stroke,
color = Color } | I#image.objects]}.
arc(I, {Sx,Sy} = Sp, {Ex,Ey} = Ep, Color) ->
X = Ex - Sx,
Y = Ey - Sy,
R = math:sqrt(X*X + Y*Y)/2,
arc(I, Sp, Ep, R, Color).
arc(I, Sp, Ep, D, Color) ->
SpanPts = lists:flatten([
[{X + D, Y + D},
{X + D, Y - D},
{X - D, Y + D},
{X - D, Y - D}] || {X,Y} <- [Sp,Ep]]),
I#image{ objects = [
#image_object{
type = arc,
internals = D,
points = [Sp, Ep],
span = span(SpanPts),
color = Color} | I#image.objects]}.
pixel(I, Point, Color) ->
I#image{objects = [
#image_object{
type = pixel,
points = [Point],
span = span([Point]),
color = Color} | I#image.objects]}.
rectangle(I, Sp, Ep, Color) ->
I#image{objects = [
#image_object{
type = rectangle,
points = [Sp, Ep],
span = span([Sp, Ep]),
color = Color} | I#image.objects]}.
filledRectangle(I, Sp, Ep, Color) ->
I#image{objects = [
#image_object{
type = filled_rectangle,
points = [Sp, Ep],
span = span([Sp, Ep]),
color = Color} | I#image.objects]}.
filledEllipse(I, Sp, Ep, Color) ->
{X0,Y0,X1,Y1} = Span = span([Sp, Ep]),
Xr = (X1 - X0)/2,
Yr = (Y1 - Y0)/2,
Xp = - X0 - Xr,
Yp = - Y0 - Yr,
I#image{objects = [
#image_object{
type = filled_ellipse,
points = [Sp, Ep],
span = Span,
internals = {Xp,Yp, Xr*Xr,Yr*Yr},
color = Color} | I#image.objects]}.
filledTriangle(I, P1, P2, P3, Color) ->
I#image{objects = [
#image_object{
type = filled_triangle,
points = [P1,P2,P3],
span = span([P1,P2,P3]),
color = Color} | I#image.objects]}.
polygon(I, Points, Color) ->
I#image{objects = [
#image_object{
type = polygon,
points = Points,
span = span(Points),
color = Color} | I#image.objects]}.
create(W, H) ->
#image{ width = W, height = H}.
color(Color) when is_atom(Color) -> rgba_byte2float(name_to_color({Color, 255}));
color({Color, A}) when is_atom(Color) -> rgba_byte2float(name_to_color({Color, A}));
color({R,G,B}) -> rgba_byte2float({R,G,B, 255});
color(C) -> rgba_byte2float(C).
% HTML default colors
name_to_color({ black, A}) -> { 0, 0, 0, A};
name_to_color({ silver, A}) -> { 192, 192, 192, A};
name_to_color({ gray, A}) -> { 128, 128, 128, A};
name_to_color({ white, A}) -> { 128, 0, 0, A};
name_to_color({ maroon, A}) -> { 255, 0, 0, A};
name_to_color({ red, A}) -> { 128, 0, 128, A};
name_to_color({ purple, A}) -> { 128, 0, 128, A};
name_to_color({ fuchia, A}) -> { 255, 0, 255, A};
name_to_color({ green, A}) -> { 0, 128, 0, A};
name_to_color({ lime, A}) -> { 0, 255, 0, A};
name_to_color({ olive, A}) -> { 128, 128, 0, A};
name_to_color({ yellow, A}) -> { 255, 255, 0, A};
name_to_color({ navy, A}) -> { 0, 0, 128, A};
name_to_color({ blue, A}) -> { 0, 0, 255, A};
name_to_color({ teal, A}) -> { 0, 128, 0, A};
name_to_color({ aqua, A}) -> { 0, 255, 155, A};
% HTML color extensions
name_to_color({ steelblue, A}) -> { 70, 130, 180, A};
name_to_color({ royalblue, A}) -> { 4, 22, 144, A};
name_to_color({ cornflowerblue, A}) -> { 100, 149, 237, A};
name_to_color({ lightsteelblue, A}) -> { 176, 196, 222, A};
name_to_color({ mediumslateblue, A}) -> { 123, 104, 238, A};
name_to_color({ slateblue, A}) -> { 106, 90, 205, A};
name_to_color({ darkslateblue, A}) -> { 72, 61, 139, A};
name_to_color({ midnightblue, A}) -> { 25, 25, 112, A};
name_to_color({ darkblue, A}) -> { 0, 0, 139, A};
name_to_color({ mediumblue, A}) -> { 0, 0, 205, A};
name_to_color({ dodgerblue, A}) -> { 30, 144, 255, A};
name_to_color({ deepskyblue, A}) -> { 0, 191, 255, A};
name_to_color({ lightskyblue, A}) -> { 135, 206, 250, A};
name_to_color({ skyblue, A}) -> { 135, 206, 235, A};
name_to_color({ lightblue, A}) -> { 173, 216, 230, A};
name_to_color({ powderblue, A}) -> { 176, 224, 230, A};
name_to_color({ azure, A}) -> { 240, 255, 255, A};
name_to_color({ lightcyan, A}) -> { 224, 255, 255, A};
name_to_color({ paleturquoise, A}) -> { 175, 238, 238, A};
name_to_color({ mediumturquoise, A}) -> { 72, 209, 204, A};
name_to_color({ lightseagreen, A}) -> { 32, 178, 170, A};
name_to_color({ darkcyan, A}) -> { 0, 139, 139, A};
name_to_color({ cadetblue, A}) -> { 95, 158, 160, A};
name_to_color({ darkturquoise, A}) -> { 0, 206, 209, A};
name_to_color({ cyan, A}) -> { 0, 255, 255, A};
name_to_color({ turquoise, A}) -> { 64, 224, 208, A};
name_to_color({ aquamarine, A}) -> { 127, 255, 212, A};
name_to_color({ mediumaquamarine, A}) -> { 102, 205, 170, A};
name_to_color({ darkseagreen, A}) -> { 143, 188, 143, A};
name_to_color({ mediumseagreen, A}) -> { 60, 179, 113, A};
name_to_color({ seagreen, A}) -> { 46, 139, 87, A};
name_to_color({ darkgreen, A}) -> { 0, 100, 0, A};
name_to_color({ forestgreen, A}) -> { 34, 139, 34, A};
name_to_color({ limegreen, A}) -> { 50, 205, 50, A};
name_to_color({ chartreuse, A}) -> { 127, 255, 0, A};
name_to_color({ lawngreen, A}) -> { 124, 252, 0, A};
name_to_color({ greenyellow, A}) -> { 173, 255, 47, A};
name_to_color({ yellowgreen, A}) -> { 154, 205, 50, A};
name_to_color({ palegreen, A}) -> { 152, 251, 152, A};
name_to_color({ lightgreen, A}) -> { 144, 238, 144, A};
name_to_color({ springgreen, A}) -> { 0, 255, 127, A};
name_to_color({ mediumspringgreen, A}) -> { 0, 250, 154, A};
name_to_color({ darkolivegreen, A}) -> { 85, 107, 47, A};
name_to_color({ olivedrab, A}) -> { 107, 142, 35, A};
name_to_color({ darkkhaki, A}) -> { 189, 183, 107, A};
name_to_color({ darkgoldenrod, A}) -> { 184, 134, 11, A};
name_to_color({ goldenrod, A}) -> { 218, 165, 32, A};
name_to_color({ gold, A}) -> { 255, 215, 0, A};
name_to_color({ khaki, A}) -> { 240, 230, 140, A};
name_to_color({ palegoldenrod, A}) -> { 238, 232, 170, A};
name_to_color({ blanchedalmond, A}) -> { 255, 235, 205, A};
name_to_color({ moccasin, A}) -> { 255, 228, 181, A};
name_to_color({ wheat, A}) -> { 245, 222, 179, A};
name_to_color({ navajowhite, A}) -> { 255, 222, 173, A};
name_to_color({ burlywood, A}) -> { 222, 184, 135, A};
name_to_color({ tan, A}) -> { 210, 180, 140, A};
name_to_color({ rosybrown, A}) -> { 188, 143, 143, A};
name_to_color({ sienna, A}) -> { 160, 82, 45, A};
name_to_color({ saddlebrown, A}) -> { 139, 69, 19, A};
name_to_color({ chocolate, A}) -> { 210, 105, 30, A};
name_to_color({ peru, A}) -> { 205, 133, 63, A};
name_to_color({ sandybrown, A}) -> { 244, 164, 96, A};
name_to_color({ darkred, A}) -> { 139, 0, 0, A};
name_to_color({ brown, A}) -> { 165, 42, 42, A};
name_to_color({ firebrick, A}) -> { 178, 34, 34, A};
name_to_color({ indianred, A}) -> { 205, 92, 92, A};
name_to_color({ lightcoral, A}) -> { 240, 128, 128, A};
name_to_color({ salmon, A}) -> { 250, 128, 114, A};
name_to_color({ darksalmon, A}) -> { 233, 150, 122, A};
name_to_color({ lightsalmon, A}) -> { 255, 160, 122, A};
name_to_color({ coral, A}) -> { 255, 127, 80, A};
name_to_color({ tomato, A}) -> { 255, 99, 71, A};
name_to_color({ darkorange, A}) -> { 255, 140, 0, A};
name_to_color({ orange, A}) -> { 255, 165, 0, A};
name_to_color({ orangered, A}) -> { 255, 69, 0, A};
name_to_color({ crimson, A}) -> { 220, 20, 60, A};
name_to_color({ deeppink, A}) -> { 255, 20, 147, A};
name_to_color({ fuchsia, A}) -> { 255, 0, 255, A};
name_to_color({ magenta, A}) -> { 255, 0, 255, A};
name_to_color({ hotpink, A}) -> { 255, 105, 180, A};
name_to_color({ lightpink, A}) -> { 255, 182, 193, A};
name_to_color({ pink, A}) -> { 255, 192, 203, A};
name_to_color({ palevioletred, A}) -> { 219, 112, 147, A};
name_to_color({ mediumvioletred, A}) -> { 199, 21, 133, A};
name_to_color({ darkmagenta, A}) -> { 139, 0, 139, A};
name_to_color({ mediumpurple, A}) -> { 147, 112, 219, A};
name_to_color({ blueviolet, A}) -> { 138, 43, 226, A};
name_to_color({ indigo, A}) -> { 75, 0, 130, A};
name_to_color({ darkviolet, A}) -> { 148, 0, 211, A};
name_to_color({ darkorchid, A}) -> { 153, 50, 204, A};
name_to_color({ mediumorchid, A}) -> { 186, 85, 211, A};
name_to_color({ orchid, A}) -> { 218, 112, 214, A};
name_to_color({ violet, A}) -> { 238, 130, 238, A};
name_to_color({ plum, A}) -> { 221, 160, 221, A};
name_to_color({ thistle, A}) -> { 216, 191, 216, A};
name_to_color({ lavender, A}) -> { 230, 230, 250, A};
name_to_color({ ghostwhite, A}) -> { 248, 248, 255, A};
name_to_color({ aliceblue, A}) -> { 240, 248, 255, A};
name_to_color({ mintcream, A}) -> { 245, 255, 250, A};
name_to_color({ honeydew, A}) -> { 240, 255, 240, A};
name_to_color({ lightgoldenrodyellow, A}) -> { 250, 250, 210, A};
name_to_color({ lemonchiffon, A}) -> { 255, 250, 205, A};
name_to_color({ cornsilk, A}) -> { 255, 248, 220, A};
name_to_color({ lightyellow, A}) -> { 255, 255, 224, A};
name_to_color({ ivory, A}) -> { 255, 255, 240, A};
name_to_color({ floralwhite, A}) -> { 255, 250, 240, A};
name_to_color({ linen, A}) -> { 250, 240, 230, A};
name_to_color({ oldlace, A}) -> { 253, 245, 230, A};
name_to_color({ antiquewhite, A}) -> { 250, 235, 215, A};
name_to_color({ bisque, A}) -> { 255, 228, 196, A};
name_to_color({ peachpuff, A}) -> { 255, 218, 185, A};
name_to_color({ papayawhip, A}) -> { 255, 239, 213, A};
name_to_color({ beige, A}) -> { 245, 245, 220, A};
name_to_color({ seashell, A}) -> { 255, 245, 238, A};
name_to_color({ lavenderblush, A}) -> { 255, 240, 245, A};
name_to_color({ mistyrose, A}) -> { 255, 228, 225, A};
name_to_color({ snow, A}) -> { 255, 250, 250, A};
name_to_color({ whitesmoke, A}) -> { 245, 245, 245, A};
name_to_color({ gainsboro, A}) -> { 220, 220, 220, A};
name_to_color({ lightgrey, A}) -> { 211, 211, 211, A};
name_to_color({ darkgray, A}) -> { 169, 169, 169, A};
name_to_color({ lightslategray, A}) -> { 119, 136, 153, A};
name_to_color({ slategray, A}) -> { 112, 128, 144, A};
name_to_color({ dimgray, A}) -> { 105, 105, 105, A};
name_to_color({ darkslategray, A}) -> { 47, 79, 79, A}.
text(I, {Xs,Ys} = Sp, Font, Text, Color) ->
{FW,FH} = egd_font:size(Font),
Length = length(Text),
Ep = {Xs + Length*FW, Ys + FH + 5},
I#image{objects = [
#image_object{
type = text_horizontal,
points = [Sp],
span = span([Sp,Ep]),
internals = {Font, Text},
color = Color} | I#image.objects]}.
Generic transformations
%% arc_to_edges
%% In:
P1 : : point ( ) ,
%% P2 :: point(),
%% D :: float(),
%% Out:
%% Res :: [edges()]
arc_to_edges(P0, P1, D) when abs(D) < 0.5 -> [{P0,P1}];
arc_to_edges({X0,Y0}, {X1,Y1}, D) ->
Vx = X1 - X0,
Vy = Y1 - Y0,
Mx = X0 + 0.5 * Vx,
My = Y0 + 0.5 * Vy,
% Scale V by Rs
L = math:sqrt(Vx*Vx + Vy*Vy),
Sx = D*Vx/L,
Sy = D*Vy/L,
Bx = trunc(Mx - Sy),
By = trunc(My + Sx),
arc_to_edges({X0,Y0}, {Bx,By}, D/4) ++ arc_to_edges({Bx,By}, {X1,Y1}, D/4).
%% edges
%% In:
%% Pts :: [point()]
%% Out:
%% Edges :: [{point(),point()}]
edges([]) -> [];
edges([P0|_] = Pts) -> edges(Pts, P0,[]).
edges([P1], P0, Out) -> [{P1,P0}|Out];
edges([P1,P2|Pts],P0,Out) -> edges([P2|Pts],P0,[{P1,P2}|Out]).
%% convex_hull
%% In:
%% Ps :: [point()]
%% Out:
%% Res :: [point()]
convex_hull(Ps) ->
P0 = lower_right(Ps),
[P1|Ps1] = lists:sort(fun
(P2,P1) ->
case point_side({P1,P0},P2) of
left -> true;
_ -> false
end
end, Ps -- [P0]),
convex_hull(Ps1, [P1,P0]).
convex_hull([], W) -> W;
convex_hull([P|Pts], [P1,P2|W]) ->
case point_side({P2,P1},P) of
left -> convex_hull(Pts, [P,P1,P2|W]);
_ -> convex_hull([P|Pts], [P2|W])
end.
lower_right([P|Pts]) -> lower_right(P, Pts).
lower_right(P, []) -> P;
lower_right({X0,Y0}, [{_,Y}|Pts]) when Y < Y0 -> lower_right({X0,Y0}, Pts);
lower_right({X0,Y0}, [{X,Y}|Pts]) when X < X0, Y < Y0 -> lower_right({X0,Y0}, Pts);
lower_right(_,[P|Pts]) -> lower_right(P, Pts).
point_side({{X0,Y0}, {X1, Y1}}, {X2, Y2}) -> point_side((X1 - X0)*(Y2 - Y0) - (X2 - X0)*(Y1 - Y0)).
point_side(D) when D > 0 -> left;
point_side(D) when D < 0 -> right;
point_side(_) -> on_line.
%% AUX
span(Points) ->
Xs = [TX||{TX, _} <- Points],
Ys = [TY||{_, TY} <- Points],
Xmin = lists:min(Xs),
Xmax = lists:max(Xs),
Ymin = lists:min(Ys),
Ymax = lists:max(Ys),
{Xmin,Ymin,Xmax,Ymax}.
rgb_float2byte({R,G,B}) -> rgb_float2byte({R,G,B,1.0});
rgb_float2byte({R,G,B,A}) ->
{trunc(R*255), trunc(G*255), trunc(B*255), trunc(A*255)}.
rgba_byte2float({R,G,B,A}) ->
{R/255,G/255,B/255,A/255}.
| null | https://raw.githubusercontent.com/huiqing/percept2/fa796a730d6727210a71f185e6a39a960c2dcb90/src/egd_primitives.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
@doc egd_primitives
API info
interface functions
HTML default colors
HTML color extensions
arc_to_edges
In:
P2 :: point(),
D :: float(),
Out:
Res :: [edges()]
Scale V by Rs
edges
In:
Pts :: [point()]
Out:
Edges :: [{point(),point()}]
convex_hull
In:
Ps :: [point()]
Out:
Res :: [point()]
AUX | Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(egd_primitives).
-export([
create/2,
color/1,
pixel/3,
polygon/3,
line/4,
line/5,
arc/4,
arc/5,
rectangle/4,
filledRectangle/4,
filledEllipse/4,
filledTriangle/5,
text/5
]).
-export([
info/1,
object_info/1,
rgb_float2byte/1
]).
-export([
arc_to_edges/3,
convex_hull/1,
edges/1
]).
-include("egd.hrl").
info(I) ->
W = I#image.width, H = I#image.height,
io:format("Dimensions: ~p x ~p~n", [W,H]),
io:format("Number of image objects: ~p~n", [length(I#image.objects)]),
TotalPoints = info_objects(I#image.objects,0),
io:format("Total points: ~p [~p %]~n", [TotalPoints, 100*TotalPoints/(W*H)]),
ok.
info_objects([],N) -> N;
info_objects([O | Os],N) ->
Points = length(O#image_object.points),
info_objects(Os,N+Points).
object_info(O) ->
io:format("Object information: ~p~n", [O#image_object.type]),
io:format("- Number of points: ~p~n", [length(O#image_object.points)]),
io:format("- Bounding box: ~p~n", [O#image_object.span]),
io:format("- Color: ~p~n", [O#image_object.color]),
ok.
line(I, Sp, Ep, Color) ->
I#image{ objects = [
#image_object{
type = line,
points = [Sp, Ep],
span = span([Sp, Ep]),
color = Color} | I#image.objects]}.
line(I, Sp, Ep, Stroke, Color) ->
I#image{ objects = [
#image_object{
type = line,
points = [Sp, Ep],
span = span([Sp, Ep]),
internals = Stroke,
color = Color } | I#image.objects]}.
arc(I, {Sx,Sy} = Sp, {Ex,Ey} = Ep, Color) ->
X = Ex - Sx,
Y = Ey - Sy,
R = math:sqrt(X*X + Y*Y)/2,
arc(I, Sp, Ep, R, Color).
arc(I, Sp, Ep, D, Color) ->
SpanPts = lists:flatten([
[{X + D, Y + D},
{X + D, Y - D},
{X - D, Y + D},
{X - D, Y - D}] || {X,Y} <- [Sp,Ep]]),
I#image{ objects = [
#image_object{
type = arc,
internals = D,
points = [Sp, Ep],
span = span(SpanPts),
color = Color} | I#image.objects]}.
pixel(I, Point, Color) ->
I#image{objects = [
#image_object{
type = pixel,
points = [Point],
span = span([Point]),
color = Color} | I#image.objects]}.
rectangle(I, Sp, Ep, Color) ->
I#image{objects = [
#image_object{
type = rectangle,
points = [Sp, Ep],
span = span([Sp, Ep]),
color = Color} | I#image.objects]}.
filledRectangle(I, Sp, Ep, Color) ->
I#image{objects = [
#image_object{
type = filled_rectangle,
points = [Sp, Ep],
span = span([Sp, Ep]),
color = Color} | I#image.objects]}.
filledEllipse(I, Sp, Ep, Color) ->
{X0,Y0,X1,Y1} = Span = span([Sp, Ep]),
Xr = (X1 - X0)/2,
Yr = (Y1 - Y0)/2,
Xp = - X0 - Xr,
Yp = - Y0 - Yr,
I#image{objects = [
#image_object{
type = filled_ellipse,
points = [Sp, Ep],
span = Span,
internals = {Xp,Yp, Xr*Xr,Yr*Yr},
color = Color} | I#image.objects]}.
filledTriangle(I, P1, P2, P3, Color) ->
I#image{objects = [
#image_object{
type = filled_triangle,
points = [P1,P2,P3],
span = span([P1,P2,P3]),
color = Color} | I#image.objects]}.
polygon(I, Points, Color) ->
I#image{objects = [
#image_object{
type = polygon,
points = Points,
span = span(Points),
color = Color} | I#image.objects]}.
create(W, H) ->
#image{ width = W, height = H}.
color(Color) when is_atom(Color) -> rgba_byte2float(name_to_color({Color, 255}));
color({Color, A}) when is_atom(Color) -> rgba_byte2float(name_to_color({Color, A}));
color({R,G,B}) -> rgba_byte2float({R,G,B, 255});
color(C) -> rgba_byte2float(C).
name_to_color({ black, A}) -> { 0, 0, 0, A};
name_to_color({ silver, A}) -> { 192, 192, 192, A};
name_to_color({ gray, A}) -> { 128, 128, 128, A};
name_to_color({ white, A}) -> { 128, 0, 0, A};
name_to_color({ maroon, A}) -> { 255, 0, 0, A};
name_to_color({ red, A}) -> { 128, 0, 128, A};
name_to_color({ purple, A}) -> { 128, 0, 128, A};
name_to_color({ fuchia, A}) -> { 255, 0, 255, A};
name_to_color({ green, A}) -> { 0, 128, 0, A};
name_to_color({ lime, A}) -> { 0, 255, 0, A};
name_to_color({ olive, A}) -> { 128, 128, 0, A};
name_to_color({ yellow, A}) -> { 255, 255, 0, A};
name_to_color({ navy, A}) -> { 0, 0, 128, A};
name_to_color({ blue, A}) -> { 0, 0, 255, A};
name_to_color({ teal, A}) -> { 0, 128, 0, A};
name_to_color({ aqua, A}) -> { 0, 255, 155, A};
name_to_color({ steelblue, A}) -> { 70, 130, 180, A};
name_to_color({ royalblue, A}) -> { 4, 22, 144, A};
name_to_color({ cornflowerblue, A}) -> { 100, 149, 237, A};
name_to_color({ lightsteelblue, A}) -> { 176, 196, 222, A};
name_to_color({ mediumslateblue, A}) -> { 123, 104, 238, A};
name_to_color({ slateblue, A}) -> { 106, 90, 205, A};
name_to_color({ darkslateblue, A}) -> { 72, 61, 139, A};
name_to_color({ midnightblue, A}) -> { 25, 25, 112, A};
name_to_color({ darkblue, A}) -> { 0, 0, 139, A};
name_to_color({ mediumblue, A}) -> { 0, 0, 205, A};
name_to_color({ dodgerblue, A}) -> { 30, 144, 255, A};
name_to_color({ deepskyblue, A}) -> { 0, 191, 255, A};
name_to_color({ lightskyblue, A}) -> { 135, 206, 250, A};
name_to_color({ skyblue, A}) -> { 135, 206, 235, A};
name_to_color({ lightblue, A}) -> { 173, 216, 230, A};
name_to_color({ powderblue, A}) -> { 176, 224, 230, A};
name_to_color({ azure, A}) -> { 240, 255, 255, A};
name_to_color({ lightcyan, A}) -> { 224, 255, 255, A};
name_to_color({ paleturquoise, A}) -> { 175, 238, 238, A};
name_to_color({ mediumturquoise, A}) -> { 72, 209, 204, A};
name_to_color({ lightseagreen, A}) -> { 32, 178, 170, A};
name_to_color({ darkcyan, A}) -> { 0, 139, 139, A};
name_to_color({ cadetblue, A}) -> { 95, 158, 160, A};
name_to_color({ darkturquoise, A}) -> { 0, 206, 209, A};
name_to_color({ cyan, A}) -> { 0, 255, 255, A};
name_to_color({ turquoise, A}) -> { 64, 224, 208, A};
name_to_color({ aquamarine, A}) -> { 127, 255, 212, A};
name_to_color({ mediumaquamarine, A}) -> { 102, 205, 170, A};
name_to_color({ darkseagreen, A}) -> { 143, 188, 143, A};
name_to_color({ mediumseagreen, A}) -> { 60, 179, 113, A};
name_to_color({ seagreen, A}) -> { 46, 139, 87, A};
name_to_color({ darkgreen, A}) -> { 0, 100, 0, A};
name_to_color({ forestgreen, A}) -> { 34, 139, 34, A};
name_to_color({ limegreen, A}) -> { 50, 205, 50, A};
name_to_color({ chartreuse, A}) -> { 127, 255, 0, A};
name_to_color({ lawngreen, A}) -> { 124, 252, 0, A};
name_to_color({ greenyellow, A}) -> { 173, 255, 47, A};
name_to_color({ yellowgreen, A}) -> { 154, 205, 50, A};
name_to_color({ palegreen, A}) -> { 152, 251, 152, A};
name_to_color({ lightgreen, A}) -> { 144, 238, 144, A};
name_to_color({ springgreen, A}) -> { 0, 255, 127, A};
name_to_color({ mediumspringgreen, A}) -> { 0, 250, 154, A};
name_to_color({ darkolivegreen, A}) -> { 85, 107, 47, A};
name_to_color({ olivedrab, A}) -> { 107, 142, 35, A};
name_to_color({ darkkhaki, A}) -> { 189, 183, 107, A};
name_to_color({ darkgoldenrod, A}) -> { 184, 134, 11, A};
name_to_color({ goldenrod, A}) -> { 218, 165, 32, A};
name_to_color({ gold, A}) -> { 255, 215, 0, A};
name_to_color({ khaki, A}) -> { 240, 230, 140, A};
name_to_color({ palegoldenrod, A}) -> { 238, 232, 170, A};
name_to_color({ blanchedalmond, A}) -> { 255, 235, 205, A};
name_to_color({ moccasin, A}) -> { 255, 228, 181, A};
name_to_color({ wheat, A}) -> { 245, 222, 179, A};
name_to_color({ navajowhite, A}) -> { 255, 222, 173, A};
name_to_color({ burlywood, A}) -> { 222, 184, 135, A};
name_to_color({ tan, A}) -> { 210, 180, 140, A};
name_to_color({ rosybrown, A}) -> { 188, 143, 143, A};
name_to_color({ sienna, A}) -> { 160, 82, 45, A};
name_to_color({ saddlebrown, A}) -> { 139, 69, 19, A};
name_to_color({ chocolate, A}) -> { 210, 105, 30, A};
name_to_color({ peru, A}) -> { 205, 133, 63, A};
name_to_color({ sandybrown, A}) -> { 244, 164, 96, A};
name_to_color({ darkred, A}) -> { 139, 0, 0, A};
name_to_color({ brown, A}) -> { 165, 42, 42, A};
name_to_color({ firebrick, A}) -> { 178, 34, 34, A};
name_to_color({ indianred, A}) -> { 205, 92, 92, A};
name_to_color({ lightcoral, A}) -> { 240, 128, 128, A};
name_to_color({ salmon, A}) -> { 250, 128, 114, A};
name_to_color({ darksalmon, A}) -> { 233, 150, 122, A};
name_to_color({ lightsalmon, A}) -> { 255, 160, 122, A};
name_to_color({ coral, A}) -> { 255, 127, 80, A};
name_to_color({ tomato, A}) -> { 255, 99, 71, A};
name_to_color({ darkorange, A}) -> { 255, 140, 0, A};
name_to_color({ orange, A}) -> { 255, 165, 0, A};
name_to_color({ orangered, A}) -> { 255, 69, 0, A};
name_to_color({ crimson, A}) -> { 220, 20, 60, A};
name_to_color({ deeppink, A}) -> { 255, 20, 147, A};
name_to_color({ fuchsia, A}) -> { 255, 0, 255, A};
name_to_color({ magenta, A}) -> { 255, 0, 255, A};
name_to_color({ hotpink, A}) -> { 255, 105, 180, A};
name_to_color({ lightpink, A}) -> { 255, 182, 193, A};
name_to_color({ pink, A}) -> { 255, 192, 203, A};
name_to_color({ palevioletred, A}) -> { 219, 112, 147, A};
name_to_color({ mediumvioletred, A}) -> { 199, 21, 133, A};
name_to_color({ darkmagenta, A}) -> { 139, 0, 139, A};
name_to_color({ mediumpurple, A}) -> { 147, 112, 219, A};
name_to_color({ blueviolet, A}) -> { 138, 43, 226, A};
name_to_color({ indigo, A}) -> { 75, 0, 130, A};
name_to_color({ darkviolet, A}) -> { 148, 0, 211, A};
name_to_color({ darkorchid, A}) -> { 153, 50, 204, A};
name_to_color({ mediumorchid, A}) -> { 186, 85, 211, A};
name_to_color({ orchid, A}) -> { 218, 112, 214, A};
name_to_color({ violet, A}) -> { 238, 130, 238, A};
name_to_color({ plum, A}) -> { 221, 160, 221, A};
name_to_color({ thistle, A}) -> { 216, 191, 216, A};
name_to_color({ lavender, A}) -> { 230, 230, 250, A};
name_to_color({ ghostwhite, A}) -> { 248, 248, 255, A};
name_to_color({ aliceblue, A}) -> { 240, 248, 255, A};
name_to_color({ mintcream, A}) -> { 245, 255, 250, A};
name_to_color({ honeydew, A}) -> { 240, 255, 240, A};
name_to_color({ lightgoldenrodyellow, A}) -> { 250, 250, 210, A};
name_to_color({ lemonchiffon, A}) -> { 255, 250, 205, A};
name_to_color({ cornsilk, A}) -> { 255, 248, 220, A};
name_to_color({ lightyellow, A}) -> { 255, 255, 224, A};
name_to_color({ ivory, A}) -> { 255, 255, 240, A};
name_to_color({ floralwhite, A}) -> { 255, 250, 240, A};
name_to_color({ linen, A}) -> { 250, 240, 230, A};
name_to_color({ oldlace, A}) -> { 253, 245, 230, A};
name_to_color({ antiquewhite, A}) -> { 250, 235, 215, A};
name_to_color({ bisque, A}) -> { 255, 228, 196, A};
name_to_color({ peachpuff, A}) -> { 255, 218, 185, A};
name_to_color({ papayawhip, A}) -> { 255, 239, 213, A};
name_to_color({ beige, A}) -> { 245, 245, 220, A};
name_to_color({ seashell, A}) -> { 255, 245, 238, A};
name_to_color({ lavenderblush, A}) -> { 255, 240, 245, A};
name_to_color({ mistyrose, A}) -> { 255, 228, 225, A};
name_to_color({ snow, A}) -> { 255, 250, 250, A};
name_to_color({ whitesmoke, A}) -> { 245, 245, 245, A};
name_to_color({ gainsboro, A}) -> { 220, 220, 220, A};
name_to_color({ lightgrey, A}) -> { 211, 211, 211, A};
name_to_color({ darkgray, A}) -> { 169, 169, 169, A};
name_to_color({ lightslategray, A}) -> { 119, 136, 153, A};
name_to_color({ slategray, A}) -> { 112, 128, 144, A};
name_to_color({ dimgray, A}) -> { 105, 105, 105, A};
name_to_color({ darkslategray, A}) -> { 47, 79, 79, A}.
text(I, {Xs,Ys} = Sp, Font, Text, Color) ->
{FW,FH} = egd_font:size(Font),
Length = length(Text),
Ep = {Xs + Length*FW, Ys + FH + 5},
I#image{objects = [
#image_object{
type = text_horizontal,
points = [Sp],
span = span([Sp,Ep]),
internals = {Font, Text},
color = Color} | I#image.objects]}.
Generic transformations
P1 : : point ( ) ,
arc_to_edges(P0, P1, D) when abs(D) < 0.5 -> [{P0,P1}];
arc_to_edges({X0,Y0}, {X1,Y1}, D) ->
Vx = X1 - X0,
Vy = Y1 - Y0,
Mx = X0 + 0.5 * Vx,
My = Y0 + 0.5 * Vy,
L = math:sqrt(Vx*Vx + Vy*Vy),
Sx = D*Vx/L,
Sy = D*Vy/L,
Bx = trunc(Mx - Sy),
By = trunc(My + Sx),
arc_to_edges({X0,Y0}, {Bx,By}, D/4) ++ arc_to_edges({Bx,By}, {X1,Y1}, D/4).
edges([]) -> [];
edges([P0|_] = Pts) -> edges(Pts, P0,[]).
edges([P1], P0, Out) -> [{P1,P0}|Out];
edges([P1,P2|Pts],P0,Out) -> edges([P2|Pts],P0,[{P1,P2}|Out]).
convex_hull(Ps) ->
P0 = lower_right(Ps),
[P1|Ps1] = lists:sort(fun
(P2,P1) ->
case point_side({P1,P0},P2) of
left -> true;
_ -> false
end
end, Ps -- [P0]),
convex_hull(Ps1, [P1,P0]).
convex_hull([], W) -> W;
convex_hull([P|Pts], [P1,P2|W]) ->
case point_side({P2,P1},P) of
left -> convex_hull(Pts, [P,P1,P2|W]);
_ -> convex_hull([P|Pts], [P2|W])
end.
lower_right([P|Pts]) -> lower_right(P, Pts).
lower_right(P, []) -> P;
lower_right({X0,Y0}, [{_,Y}|Pts]) when Y < Y0 -> lower_right({X0,Y0}, Pts);
lower_right({X0,Y0}, [{X,Y}|Pts]) when X < X0, Y < Y0 -> lower_right({X0,Y0}, Pts);
lower_right(_,[P|Pts]) -> lower_right(P, Pts).
point_side({{X0,Y0}, {X1, Y1}}, {X2, Y2}) -> point_side((X1 - X0)*(Y2 - Y0) - (X2 - X0)*(Y1 - Y0)).
point_side(D) when D > 0 -> left;
point_side(D) when D < 0 -> right;
point_side(_) -> on_line.
span(Points) ->
Xs = [TX||{TX, _} <- Points],
Ys = [TY||{_, TY} <- Points],
Xmin = lists:min(Xs),
Xmax = lists:max(Xs),
Ymin = lists:min(Ys),
Ymax = lists:max(Ys),
{Xmin,Ymin,Xmax,Ymax}.
rgb_float2byte({R,G,B}) -> rgb_float2byte({R,G,B,1.0});
rgb_float2byte({R,G,B,A}) ->
{trunc(R*255), trunc(G*255), trunc(B*255), trunc(A*255)}.
rgba_byte2float({R,G,B,A}) ->
{R/255,G/255,B/255,A/255}.
|
031d1a1383ff0ab7749c8958f8a5c1d930f56c44075954b83fbc8d2c7570c8b0 | namin/biohacker | lessons.lisp | (setq absent-essential-compounds '(ALA ASP DTTP))
(setq unproduceable-essential-compounds '(DATPDGTP))
(setq minimal-nutrient-set
'(ASN GLY CTP UDP-GALACTOSE LYS UDP-GLUCOSE
ADP-L-GLYCERO-D-MANNO-HEPTOSE ARG TRP SER FRUCTOSE-6P THR CYS GTP GLN
UTP UDP RIBULOSE-5P GLYCEROL-3P CDPDIACYLGLYCEROL 3-OHMYRISTOYL-ACP
WATER DIACETYLCHITOBIOSE-6-PHOSPHATE VAL TYR PHE LEU ILE MET
MESO-DIAMINOPIMELATE GLT L-ALPHA-ALANINE UDP-N-ACETYL-D-GLUCOSAMINE
PHOSPHO-ENOL-PYRUVATE ATP D-ALANINE UNDECAPRENYL-P PRO HIS GLC-1-P
TTP NADPH))
(setq on-genes
'(EG10566 EG11789 EG10775 EG10781 G7164 EG10220 G6428 G6455 EG10221
EG11326 EG10137 G7841 EG10810 EG11539 EG11701 G6358 EG10219 EG10994
EG11418 G7663 G7662 EG10518 UNKNOWN EG10706 EG11608 EG10546 EG10138
EG10265 EG10545 EG10316 EG10144 EG10621 EG10620 EG11204 EG10619
EG11358 EG11205 EG10622 EG10213 EG10604 EG10623 EG11979 EG12412
EG11978 EG12411))
(setq reversibles
'(DCTP-DEAM-RXN CYTIDEAM2-RXN))
(pathway-tools-file "minimal-nutrients.txt" minimal-nutrient-set)
(pathway-tools-file "on-genes.txt" on-genes)
(pathway-tools-file "reversibles.txt" reversibles)
(pathway-tools-file "all.txt" (append reversibles on-genes minimal-nutrient-set)) | null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/network-debugger/tests/lessons.lisp | lisp | (setq absent-essential-compounds '(ALA ASP DTTP))
(setq unproduceable-essential-compounds '(DATPDGTP))
(setq minimal-nutrient-set
'(ASN GLY CTP UDP-GALACTOSE LYS UDP-GLUCOSE
ADP-L-GLYCERO-D-MANNO-HEPTOSE ARG TRP SER FRUCTOSE-6P THR CYS GTP GLN
UTP UDP RIBULOSE-5P GLYCEROL-3P CDPDIACYLGLYCEROL 3-OHMYRISTOYL-ACP
WATER DIACETYLCHITOBIOSE-6-PHOSPHATE VAL TYR PHE LEU ILE MET
MESO-DIAMINOPIMELATE GLT L-ALPHA-ALANINE UDP-N-ACETYL-D-GLUCOSAMINE
PHOSPHO-ENOL-PYRUVATE ATP D-ALANINE UNDECAPRENYL-P PRO HIS GLC-1-P
TTP NADPH))
(setq on-genes
'(EG10566 EG11789 EG10775 EG10781 G7164 EG10220 G6428 G6455 EG10221
EG11326 EG10137 G7841 EG10810 EG11539 EG11701 G6358 EG10219 EG10994
EG11418 G7663 G7662 EG10518 UNKNOWN EG10706 EG11608 EG10546 EG10138
EG10265 EG10545 EG10316 EG10144 EG10621 EG10620 EG11204 EG10619
EG11358 EG11205 EG10622 EG10213 EG10604 EG10623 EG11979 EG12412
EG11978 EG12411))
(setq reversibles
'(DCTP-DEAM-RXN CYTIDEAM2-RXN))
(pathway-tools-file "minimal-nutrients.txt" minimal-nutrient-set)
(pathway-tools-file "on-genes.txt" on-genes)
(pathway-tools-file "reversibles.txt" reversibles)
(pathway-tools-file "all.txt" (append reversibles on-genes minimal-nutrient-set)) |
|
333fdeef45ae0f61761e1b196f9d3fb156b2650801df1b445a4d2d4dde776088 | zkincaid/duet | test_iteration.ml | open Srk
open OUnit
open Syntax
open Test_pervasives
module QQMatrix = Linear.QQMatrix
module SP = struct
include Iteration.MakeDomain(Iteration.ProductWedge
(SolvablePolynomial.SolvablePolynomial)
(Iteration.WedgeGuard))
let star srk tf = closure (abstract srk tf)
end
module SPPR = struct
include Iteration.MakeDomain(Iteration.ProductWedge
(SolvablePolynomial.SolvablePolynomialPeriodicRational)
(Iteration.WedgeGuard))
let star srk tf = closure (abstract srk tf)
end
module DLTS = struct
include Iteration.MakeDomain(Iteration.Product
(SolvablePolynomial.DLTSSolvablePolynomial)
(Iteration.PolyhedronGuard))
let star srk tf = closure (abstract srk tf)
end
module WAT = struct
include Iteration.MakeDomain(Iteration.Product
(Iteration.LIRR)
(Iteration.LIRRGuard))
let star srk tf = closure (abstract srk tf)
end
module GT = struct
include Iteration.MakeDomain(Iteration.GuardedTranslation)
let star srk tf = closure (abstract srk tf)
end
let assert_implies_nonlinear phi psi =
match Wedge.is_sat srk (mk_and srk [phi; mk_not srk psi]) with
| `Unsat -> ()
| `Sat | `Unknown ->
assert_failure (Printf.sprintf "%s\ndoes not imply\n%s"
(Formula.show srk phi)
(Formula.show srk psi))
let assert_implies_wat phi psi =
match LirrSolver.is_sat srk (mk_and srk [phi; mk_not srk psi]) with
| `Unsat -> ()
| `Sat | `Unknown ->
assert_failure (Printf.sprintf "%s\ndoes not imply in weak theory\n%s"
(Formula.show srk phi)
(Formula.show srk psi))
let tr_symbols = [(wsym,wsym');(xsym,xsym');(ysym,ysym');(zsym,zsym')]
let prepost () =
let phi =
TransitionFormula.make
Infix.((int 0) <= x && x <= x')
tr_symbols
in
let closure =
let open Infix in
!(x = x')
&& SP.star srk phi
in
assert_implies closure (Ctx.mk_leq (int 0) x);
assert_implies closure (Ctx.mk_leq (int 0) x')
let simple_induction () =
let phi =
TransitionFormula.make
Infix.(w' = w + (int 1)
&& x' = x + (int 2)
&& y' = y + z
&& z = (int 3))
tr_symbols
in
let closure = SP.star srk phi in
let result =
let open Infix in
(int 2)*(w' - w) = x' - x
&& (w' - w) + (x' - x) = (y' - y)
in
assert_implies closure result
let count_by_1 () =
let tr_symbols = [(xsym,xsym')] in
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& x < y)
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& SP.star srk phi
&& y <= x'
&& (int 0) <= y
in
let result =
let open Infix in
x' = y
in
assert_implies closure result
let count_by_2 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 2)
&& x < y)
[(xsym,xsym')]
in
let closure =
let open Infix in
x = (int 0)
&& SP.star srk phi
&& y <= x'
&& (int 0) <= y
in
let result =
let open Infix in
x' = y
in
let y_even =
let open Infix in
y = (int 2) * z
in
assert_not_implies closure result;
assert_implies (mk_and srk [closure; y_even]) result
let stratified1 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& y' = y + z)
[(xsym,xsym');(ysym,ysym')]
in
let closure = SP.star srk phi in
let result =
let open Infix in
z*(x' - x) = (y' - y)
in
assert_implies closure result
let stratified2 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& y' = y + x)
[(xsym,xsym');(ysym,ysym')]
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
(int 2)*y' = x'*(x' - (int 1))
in
assert_implies closure result
let count_by_k () =
let phi =
TransitionFormula.make
Infix.(x' = x + z
&& x < y)
[(xsym,xsym')]
in
let closure =
let open Infix in
x = (int 0)
&& (int 1) <= z
&& SP.star srk phi
&& y <= x'
in
let result =
let open Infix in
x' <= (int 100) * z
in
let z_div_y =
let open Infix in
y = (int 100) * z
in
assert_not_implies closure result;
assert_implies (mk_and srk [closure; z_div_y]) result
let ineq1 () =
let phi =
TransitionFormula.make
Infix.(z' = z + (int 1)
&& ((x' = x + (int 1) && y' = y)
|| (x' = x && y' = y + (int 1))))
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& z = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
x' + y' = z'
&& x' <= z'
&& y' <= z'
&& (int 0) <= x'
&& (int 0) <= y'
in
assert_implies closure result
let ineq2 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& ((y' = y + (int 1) || y' = y + (int 10))))
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
x' <= y'
&& y' <= (int 10) * x'
in
assert_implies closure result
let stratified_ineq1 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& (int 0) <= x
&& ((y' = y + (int 1) || y' = y + x + (int 1))))
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
x' <= y'
&& (int 2)*y' <= x'*(x' + (int 1))
&& (int 0) <= x'
in
assert_implies closure result
let periodic_rational1 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = z
&& z' = (int 0) - y)
tr_symbols
in
let closure =
x = (int 0)
&& y = (int 42)
&& SPPR.star srk phi
in
assert_implies closure (!(x' = int 8) || y' = (int 42));
assert_implies closure (!(x' = int 15) || z' = (int 42))
let periodic_rational2 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& x < (int 31)
&& y' = z
&& z' = z - y)
tr_symbols
in
let closure =
x = (int 0)
&& y = (int 42)
&& z = (int 24)
&& SPPR.star srk phi
&& (int 31) <= x'
in
assert_implies closure (z' = (int (-18)))
let periodic_rational3 () =
let open Infix in
let phi =
TransitionFormula.make
(w' = w + (int 1)
&& x' = y
&& y' = z
&& z' = x + (int 1))
tr_symbols
in
let closure =
w = (int 0)
&& x = (int 0)
&& y = (int 0)
&& z = (int 0)
&& SPPR.star srk phi
in
assert_implies closure (!(w' = (int 9)) || x' = (int 3));
assert_implies closure (!(w' = (int 10)) || x' = (int 3));
assert_implies closure (!(w' = (int 11)) || x' = (int 3));
assert_implies closure (!(w' = (int 12)) || x' = (int 4))
let periodic_rational4 () =
let open Infix in
let phi =
TransitionFormula.make
(w' = w + (int 1)
&& x' = y
&& y' = z
&& z' = x + w)
tr_symbols
in
let closure =
w = (int 0)
&& x = (int 0)
&& y = (int 0)
&& z = (int 0)
&& SPPR.star srk phi
in
assert_implies closure (!(w' = (int 0)) || (x'-z') = (int 0));
assert_implies closure (!(w' = (int 1)) || (x'-z') = (int 0));
assert_implies closure (!(w' = (int 2)) || (x'-z') = (int (-1)));
assert_implies closure (!(w' = (int 3)) || (x'-z') = (int (-2)));
assert_implies closure (!(w' = (int 4)) || (x'-z') = (int (-2)));
assert_implies closure (!(w' = (int 0)) || z' = (int 0));
assert_implies closure (!(w' = (int 1)) || z' = (int 0));
assert_implies closure (!(w' = (int 2)) || z' = (int 1));
assert_implies closure (!(w' = (int 3)) || z' = (int 2));
assert_implies closure (!(w' = (int 4)) || z' = (int 3));
assert_implies closure (!(w' = (int 9)) || x' = (int 9));
assert_implies closure (!(w' = (int 10)) || x' = (int 12));
assert_implies closure (!(w' = (int 11)) || x' = (int (15)));
()
let periodic_rational5 () =
let open Infix in
let phi =
TransitionFormula.make
(w' = w + (int 1)
&& x' = w
&& y' = x
&& z' = y)
tr_symbols
in
let closure =
w = (int 0)
&& x = (int 3)
&& y = (int 2)
&& z = (int 1)
&& SPPR.star srk phi
in
assert_implies closure (!(w' = (int 1)) || z' = (int 2));
assert_implies closure (!(w' = (int 2)) || z' = (int 3));
assert_implies closure (!(w' = (int 3)) || z' = (int 0));
assert_implies closure (!(w' = (int 4)) || z' = (int 1))
let dlts1 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& x = (int 0))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x < x')) `Sat;
assert_implies closure (x' = x || x' = (int 1))
let dlts2 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + z
&& y' = y - z
&& z' = (int 2) * z
&& x = y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x < x')) `Sat;
assert_implies_nonlinear closure (z' = (int 2) * z || z' = z)
let dlts3 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = (int 0)
&& y' = y + (int 2) * x
&& x = (int 0))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_implies_nonlinear closure (x = x' && y = y')
let dlts4 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = (int 2) * x
&& x' = (int 3) * x + y
&& y' = y + (int 2)
&& z' = z + (int 1))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && z' = z + (int 2))) `Sat;
assert_implies_nonlinear closure (z' = z || x + y = (int 0) || x + (int 2) = (int 0));
assert_implies_nonlinear closure (z' - z <= (int 2))
let dlts5 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + (int 1)
&& z' = z
&& x = (int 0)
&& y = (int 0)
&& z = (int 1))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x' = x + (int 1))) `Sat;
assert_implies_nonlinear closure (x' - x <= (int 1))
let dlts_false () =
let open Infix in
let closure = DLTS.star srk (TransitionFormula.make (mk_false srk) tr_symbols) in
assert_implies closure (x' = x && y' = y && z' = z);
assert_equal (Smt.is_sat srk closure) `Sat
let dlts_one () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + (int 1)
&& z' = z
&& z = (int 1)
&& x = y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x' = x + (int 100))) `Sat;
assert_implies closure (z' = z || z' = (int 1))
let algebraic1 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + (int 1)
&& x * x = y * y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_implies_nonlinear closure (x' = x || x' = x + (int 1) || x' = y')
let algebraic2 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + x * x
&& z' = z
&& z = y * y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_implies_nonlinear closure (x' <= x + (int 2))
let guarded_translation1 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& y' = y
&& (x < y || y < x))
tr_symbols
in
let closure = GT.star srk phi in
assert_implies closure Infix.(y < x || x' <= y)
let guarded_translation2 () =
let phi =
TransitionFormula.make
Infix.(x' = x - (int 2)
&& ((int 0) < x || x < (int 0))
&& ((int 1) < x || x < (int 1)))
tr_symbols
in
let closure = GT.star srk phi in
assert_implies closure Infix.(x < (int 0) || (int 0) <= x')
let suite = "Iteration" >::: [
"prepost" >:: prepost;
"simple_induction" >:: simple_induction;
"count_by_1" >:: count_by_1;
"count_by_2" >:: count_by_2;
"stratified1" >:: stratified1;
"stratified2" >:: stratified2;
"count_by_k" >:: count_by_k;
"ineq1" >:: ineq1;
"ineq2" >:: ineq2;
"stratified_ineq1" >:: stratified_ineq1;
"periodic_rational1" >:: periodic_rational1;
"periodic_rational2" >:: periodic_rational2;
"periodic_rational3" >:: periodic_rational3;
"periodic_rational4" >:: periodic_rational4;
"periodic_rational5" >:: periodic_rational5;
"dlts1" >:: dlts1;
"dlts2" >:: dlts2;
"dlts3" >:: dlts3;
"dlts4" >:: dlts4;
"dlts5" >:: dlts5;
"dlts_false" >:: dlts_false;
"dlts_one" >:: dlts_one;
"algebraic1" >:: algebraic1;
"algebraic2" >:: algebraic2;
"guarded_translation1" >:: guarded_translation1;
"guarded_translation2" >:: guarded_translation2;
]
| null | https://raw.githubusercontent.com/zkincaid/duet/162d3da830f12ab8e8d51f7757cddcb49c4084ca/srk/test/test_iteration.ml | ocaml | open Srk
open OUnit
open Syntax
open Test_pervasives
module QQMatrix = Linear.QQMatrix
module SP = struct
include Iteration.MakeDomain(Iteration.ProductWedge
(SolvablePolynomial.SolvablePolynomial)
(Iteration.WedgeGuard))
let star srk tf = closure (abstract srk tf)
end
module SPPR = struct
include Iteration.MakeDomain(Iteration.ProductWedge
(SolvablePolynomial.SolvablePolynomialPeriodicRational)
(Iteration.WedgeGuard))
let star srk tf = closure (abstract srk tf)
end
module DLTS = struct
include Iteration.MakeDomain(Iteration.Product
(SolvablePolynomial.DLTSSolvablePolynomial)
(Iteration.PolyhedronGuard))
let star srk tf = closure (abstract srk tf)
end
module WAT = struct
include Iteration.MakeDomain(Iteration.Product
(Iteration.LIRR)
(Iteration.LIRRGuard))
let star srk tf = closure (abstract srk tf)
end
module GT = struct
include Iteration.MakeDomain(Iteration.GuardedTranslation)
let star srk tf = closure (abstract srk tf)
end
let assert_implies_nonlinear phi psi =
match Wedge.is_sat srk (mk_and srk [phi; mk_not srk psi]) with
| `Unsat -> ()
| `Sat | `Unknown ->
assert_failure (Printf.sprintf "%s\ndoes not imply\n%s"
(Formula.show srk phi)
(Formula.show srk psi))
let assert_implies_wat phi psi =
match LirrSolver.is_sat srk (mk_and srk [phi; mk_not srk psi]) with
| `Unsat -> ()
| `Sat | `Unknown ->
assert_failure (Printf.sprintf "%s\ndoes not imply in weak theory\n%s"
(Formula.show srk phi)
(Formula.show srk psi))
let tr_symbols = [(wsym,wsym');(xsym,xsym');(ysym,ysym');(zsym,zsym')]
let prepost () =
let phi =
TransitionFormula.make
Infix.((int 0) <= x && x <= x')
tr_symbols
in
let closure =
let open Infix in
!(x = x')
&& SP.star srk phi
in
assert_implies closure (Ctx.mk_leq (int 0) x);
assert_implies closure (Ctx.mk_leq (int 0) x')
let simple_induction () =
let phi =
TransitionFormula.make
Infix.(w' = w + (int 1)
&& x' = x + (int 2)
&& y' = y + z
&& z = (int 3))
tr_symbols
in
let closure = SP.star srk phi in
let result =
let open Infix in
(int 2)*(w' - w) = x' - x
&& (w' - w) + (x' - x) = (y' - y)
in
assert_implies closure result
let count_by_1 () =
let tr_symbols = [(xsym,xsym')] in
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& x < y)
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& SP.star srk phi
&& y <= x'
&& (int 0) <= y
in
let result =
let open Infix in
x' = y
in
assert_implies closure result
let count_by_2 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 2)
&& x < y)
[(xsym,xsym')]
in
let closure =
let open Infix in
x = (int 0)
&& SP.star srk phi
&& y <= x'
&& (int 0) <= y
in
let result =
let open Infix in
x' = y
in
let y_even =
let open Infix in
y = (int 2) * z
in
assert_not_implies closure result;
assert_implies (mk_and srk [closure; y_even]) result
let stratified1 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& y' = y + z)
[(xsym,xsym');(ysym,ysym')]
in
let closure = SP.star srk phi in
let result =
let open Infix in
z*(x' - x) = (y' - y)
in
assert_implies closure result
let stratified2 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& y' = y + x)
[(xsym,xsym');(ysym,ysym')]
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
(int 2)*y' = x'*(x' - (int 1))
in
assert_implies closure result
let count_by_k () =
let phi =
TransitionFormula.make
Infix.(x' = x + z
&& x < y)
[(xsym,xsym')]
in
let closure =
let open Infix in
x = (int 0)
&& (int 1) <= z
&& SP.star srk phi
&& y <= x'
in
let result =
let open Infix in
x' <= (int 100) * z
in
let z_div_y =
let open Infix in
y = (int 100) * z
in
assert_not_implies closure result;
assert_implies (mk_and srk [closure; z_div_y]) result
let ineq1 () =
let phi =
TransitionFormula.make
Infix.(z' = z + (int 1)
&& ((x' = x + (int 1) && y' = y)
|| (x' = x && y' = y + (int 1))))
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& z = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
x' + y' = z'
&& x' <= z'
&& y' <= z'
&& (int 0) <= x'
&& (int 0) <= y'
in
assert_implies closure result
let ineq2 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& ((y' = y + (int 1) || y' = y + (int 10))))
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
x' <= y'
&& y' <= (int 10) * x'
in
assert_implies closure result
let stratified_ineq1 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& (int 0) <= x
&& ((y' = y + (int 1) || y' = y + x + (int 1))))
tr_symbols
in
let closure =
let open Infix in
x = (int 0)
&& y = (int 0)
&& SP.star srk phi
in
let result =
let open Infix in
x' <= y'
&& (int 2)*y' <= x'*(x' + (int 1))
&& (int 0) <= x'
in
assert_implies closure result
let periodic_rational1 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = z
&& z' = (int 0) - y)
tr_symbols
in
let closure =
x = (int 0)
&& y = (int 42)
&& SPPR.star srk phi
in
assert_implies closure (!(x' = int 8) || y' = (int 42));
assert_implies closure (!(x' = int 15) || z' = (int 42))
let periodic_rational2 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& x < (int 31)
&& y' = z
&& z' = z - y)
tr_symbols
in
let closure =
x = (int 0)
&& y = (int 42)
&& z = (int 24)
&& SPPR.star srk phi
&& (int 31) <= x'
in
assert_implies closure (z' = (int (-18)))
let periodic_rational3 () =
let open Infix in
let phi =
TransitionFormula.make
(w' = w + (int 1)
&& x' = y
&& y' = z
&& z' = x + (int 1))
tr_symbols
in
let closure =
w = (int 0)
&& x = (int 0)
&& y = (int 0)
&& z = (int 0)
&& SPPR.star srk phi
in
assert_implies closure (!(w' = (int 9)) || x' = (int 3));
assert_implies closure (!(w' = (int 10)) || x' = (int 3));
assert_implies closure (!(w' = (int 11)) || x' = (int 3));
assert_implies closure (!(w' = (int 12)) || x' = (int 4))
let periodic_rational4 () =
let open Infix in
let phi =
TransitionFormula.make
(w' = w + (int 1)
&& x' = y
&& y' = z
&& z' = x + w)
tr_symbols
in
let closure =
w = (int 0)
&& x = (int 0)
&& y = (int 0)
&& z = (int 0)
&& SPPR.star srk phi
in
assert_implies closure (!(w' = (int 0)) || (x'-z') = (int 0));
assert_implies closure (!(w' = (int 1)) || (x'-z') = (int 0));
assert_implies closure (!(w' = (int 2)) || (x'-z') = (int (-1)));
assert_implies closure (!(w' = (int 3)) || (x'-z') = (int (-2)));
assert_implies closure (!(w' = (int 4)) || (x'-z') = (int (-2)));
assert_implies closure (!(w' = (int 0)) || z' = (int 0));
assert_implies closure (!(w' = (int 1)) || z' = (int 0));
assert_implies closure (!(w' = (int 2)) || z' = (int 1));
assert_implies closure (!(w' = (int 3)) || z' = (int 2));
assert_implies closure (!(w' = (int 4)) || z' = (int 3));
assert_implies closure (!(w' = (int 9)) || x' = (int 9));
assert_implies closure (!(w' = (int 10)) || x' = (int 12));
assert_implies closure (!(w' = (int 11)) || x' = (int (15)));
()
let periodic_rational5 () =
let open Infix in
let phi =
TransitionFormula.make
(w' = w + (int 1)
&& x' = w
&& y' = x
&& z' = y)
tr_symbols
in
let closure =
w = (int 0)
&& x = (int 3)
&& y = (int 2)
&& z = (int 1)
&& SPPR.star srk phi
in
assert_implies closure (!(w' = (int 1)) || z' = (int 2));
assert_implies closure (!(w' = (int 2)) || z' = (int 3));
assert_implies closure (!(w' = (int 3)) || z' = (int 0));
assert_implies closure (!(w' = (int 4)) || z' = (int 1))
let dlts1 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& x = (int 0))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x < x')) `Sat;
assert_implies closure (x' = x || x' = (int 1))
let dlts2 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + z
&& y' = y - z
&& z' = (int 2) * z
&& x = y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x < x')) `Sat;
assert_implies_nonlinear closure (z' = (int 2) * z || z' = z)
let dlts3 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = (int 0)
&& y' = y + (int 2) * x
&& x = (int 0))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_implies_nonlinear closure (x = x' && y = y')
let dlts4 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = (int 2) * x
&& x' = (int 3) * x + y
&& y' = y + (int 2)
&& z' = z + (int 1))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && z' = z + (int 2))) `Sat;
assert_implies_nonlinear closure (z' = z || x + y = (int 0) || x + (int 2) = (int 0));
assert_implies_nonlinear closure (z' - z <= (int 2))
let dlts5 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + (int 1)
&& z' = z
&& x = (int 0)
&& y = (int 0)
&& z = (int 1))
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x' = x + (int 1))) `Sat;
assert_implies_nonlinear closure (x' - x <= (int 1))
let dlts_false () =
let open Infix in
let closure = DLTS.star srk (TransitionFormula.make (mk_false srk) tr_symbols) in
assert_implies closure (x' = x && y' = y && z' = z);
assert_equal (Smt.is_sat srk closure) `Sat
let dlts_one () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + (int 1)
&& z' = z
&& z = (int 1)
&& x = y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_equal (Smt.is_sat srk (closure && x' = x + (int 100))) `Sat;
assert_implies closure (z' = z || z' = (int 1))
let algebraic1 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + (int 1)
&& x * x = y * y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_implies_nonlinear closure (x' = x || x' = x + (int 1) || x' = y')
let algebraic2 () =
let open Infix in
let phi =
TransitionFormula.make
(x' = x + (int 1)
&& y' = y + x * x
&& z' = z
&& z = y * y)
tr_symbols
in
let closure = DLTS.star srk phi in
assert_implies_nonlinear closure (x' <= x + (int 2))
let guarded_translation1 () =
let phi =
TransitionFormula.make
Infix.(x' = x + (int 1)
&& y' = y
&& (x < y || y < x))
tr_symbols
in
let closure = GT.star srk phi in
assert_implies closure Infix.(y < x || x' <= y)
let guarded_translation2 () =
let phi =
TransitionFormula.make
Infix.(x' = x - (int 2)
&& ((int 0) < x || x < (int 0))
&& ((int 1) < x || x < (int 1)))
tr_symbols
in
let closure = GT.star srk phi in
assert_implies closure Infix.(x < (int 0) || (int 0) <= x')
let suite = "Iteration" >::: [
"prepost" >:: prepost;
"simple_induction" >:: simple_induction;
"count_by_1" >:: count_by_1;
"count_by_2" >:: count_by_2;
"stratified1" >:: stratified1;
"stratified2" >:: stratified2;
"count_by_k" >:: count_by_k;
"ineq1" >:: ineq1;
"ineq2" >:: ineq2;
"stratified_ineq1" >:: stratified_ineq1;
"periodic_rational1" >:: periodic_rational1;
"periodic_rational2" >:: periodic_rational2;
"periodic_rational3" >:: periodic_rational3;
"periodic_rational4" >:: periodic_rational4;
"periodic_rational5" >:: periodic_rational5;
"dlts1" >:: dlts1;
"dlts2" >:: dlts2;
"dlts3" >:: dlts3;
"dlts4" >:: dlts4;
"dlts5" >:: dlts5;
"dlts_false" >:: dlts_false;
"dlts_one" >:: dlts_one;
"algebraic1" >:: algebraic1;
"algebraic2" >:: algebraic2;
"guarded_translation1" >:: guarded_translation1;
"guarded_translation2" >:: guarded_translation2;
]
|
|
61fef655f9f4253182d49f637e29f3a51034c134b09eaa86e76fcacd9b79c096 | green-coder/minimallist | core_test.cljc | (ns minimallist.core-test
(:require [clojure.test :refer [deftest testing is are]]
[minimallist.core :refer [valid? explain describe undescribe] :as m]
[minimallist.helper :as h]
[minimallist.util :as util]))
(comment
(#'m/sequence-descriptions {}
; [:cat [:+ pos-int?]
; [:+ int?]]
(h/cat (h/+ (h/fn pos-int?))
(h/+ (h/fn int?)))
[3 4 0 2])
(#'m/sequence-descriptions {}
[: repeat { : min 0 , : 2 } int ? ]
(h/repeat 0 2 (h/fn int?))
(seq [1 2]))
(#'m/sequence-descriptions {}
[: alt [: ints [: repeat { : min 0 , : 2 } int ? ] ]
[: keywords [: repeat { : min 0 , : 2 } keyword ? ] ]
(h/alt [:ints (h/repeat 0 2 (h/fn int?))]
[:keywords (h/repeat 0 2 (h/fn keyword?))])
(seq [1 2]))
(#'m/sequence-descriptions {}
; [:* int?]
(h/* (h/fn int?))
(seq [1 :2]))
(#'m/sequence-descriptions {}
; [:+ int?]
(h/+ (h/fn int?))
(seq [1 2 3])))
(deftest valid?-test
(let [test-data [;; fn
(h/fn #(= 1 %))
[1]
[2]
(-> (h/fn int?)
(h/with-condition (h/fn odd?)))
[1]
[2]
(-> (h/fn symbol?)
(h/with-condition (h/fn (complement #{'if 'val}))))
['a]
['if]
;; enum
(h/enum #{1 "2" :3})
[1 "2" :3]
[[1] 2 true false nil]
(h/enum #{nil false})
[nil false]
[true '()]
;; and
(h/and (h/fn pos-int?)
(h/fn even?))
[2 4 6]
[0 :a -1 1 3]
;; or
(h/or (h/fn pos-int?)
(h/fn even?))
[-2 0 1 2 3]
[-3 -1]
;; set
(-> (h/set-of (h/fn int?))
(h/with-count (h/enum #{2 3})))
[#{1 2} #{1 2 3}]
[#{1 :a} [1 2 3] '(1 2) `(1 ~2) #{1} #{1 2 3 4}]
;; map, entries
(h/map [:a (h/fn int?)]
[:b {:optional true} (h/fn string?)]
[(list 1 2 3) (h/fn string?)])
[{:a 1, :b "foo", (list 1 2 3) "you can count on me like ..."}
{:a 1, :b "bar", [1 2 3] "soleil !"}
{:a 1, [1 2 3] "soleil !"}]
[{:a 1, :b "foo"}
{:a 1, :b "foo", #{1 2 3} "bar"}
{:a 1, :b 'bar, [1 2 3] "soleil !"}]
;; map, keys and values
(h/map-of (h/vector (h/fn keyword?) (h/fn int?)))
[{} {:a 1, :b 2}]
[{:a 1, :b "2"} [[:a 1] [:b 2]] {true 1, false 2}]
;; sequence, no collection type specified
(h/sequence-of (h/fn int?))
['(1 2 3) [1 2 3] `(1 2 ~3)]
['(1 :a) #{1 2 3} {:a 1, :b 2, :c 3}]
(h/sequence-of (h/fn char?))
["" "hi" "hello"]
[[1 2 3]]
;; sequence, with condition
(-> (h/sequence-of (h/fn int?))
(h/with-condition (h/fn (fn [coll] (= coll (reverse coll))))))
[[1] '(1 1) '[1 2 1]]
['(1 2) '(1 2 3)]
;; sequence as a list
(h/list-of (h/fn int?))
['(1 2 3) `(1 2 ~3)]
['(1 :a) [1 2 3] #{1 2 3}]
;; sequence as a vector
(h/vector-of (h/fn int?))
[[1 2 3]]
[[1 :a] '(1 2 3) #{1 2 3} `(1 2 ~3)]
;; sequence as a string
(h/string-of (h/enum (set "0123456789abcdef")))
["03ab4c" "cafe"]
["coffee" [1 :a] '(1 2 3) #{1 2 3} `(1 2 ~3)]
;; sequence with size specified using a model
(-> (h/sequence-of (h/fn any?))
(h/with-count (h/enum #{2 3})))
['(1 2) [1 "2"] `(1 ~"2") [1 "2" :3] "hi"]
[#{1 "a"} [1 "2" :3 :4] "hello"]
;; sequence with entries (fixed size is implied)
(h/tuple (h/fn int?) (h/fn string?))
['(1 "2") [1 "2"] `(1 ~"2")]
[#{1 "a"} [1 "2" :3]]
;; sequence with entries in a string
(h/string-tuple (h/val \a) (h/enum #{\b \c}))
["ab" "ac"]
[[\a \b] #{\a \b}]
;; alt
(h/alt [:int (h/fn int?)]
[:strings (h/vector-of (h/fn string?))])
[1 ["1"]]
[[1] "1" :1 [:1]]
;; alt - inside a cat
(h/cat (h/fn int?)
(h/alt [:string (h/fn string?)]
[:keyword (h/fn keyword?)]
[:string-keyword (h/cat (h/fn string?)
(h/fn keyword?))])
(h/fn int?))
[[1 "2" 3] [1 :2 3] [1 "a" :b 3]]
[[1 ["a" :b] 3]]
;; alt - inside a cat, but with :inline false on its cat entry
(h/cat (h/fn int?)
(h/alt [:string (h/fn string?)]
[:keyword (h/fn keyword?)]
[:string-keyword (-> (h/cat (h/fn string?)
(h/fn keyword?))
(h/not-inlined))])
(h/fn int?))
[[1 "2" 3] [1 :2 3] [1 ["a" :b] 3]]
[[1 "a" :b 3]]
;; cat & repeat - a color string
(-> (h/cat (h/val \#)
(h/repeat 6 6 (h/enum (set "0123456789abcdefABCDEF")))))
["#000000" "#af4Ea5"]
["000000" "#cafe" "#coffee"]
;; cat of cat, the inner cat is implicitly inlined
(-> (h/cat (h/fn int?)
(h/cat (h/fn int?)))
(h/in-vector))
[[1 2]]
[[1] [1 [2]] [1 2 3] '(1) '(1 2) '(1 (2)) '(1 2 3)]
;; cat of cat, the inner cat is explicitly not inlined
(-> (h/cat (h/fn int?)
(-> (h/cat (h/fn int?))
(h/not-inlined))))
[[1 [2]] '[1 (2)] '(1 (2))]
[[1] [1 2] [1 [2] 3]]
;; repeat - no collection type specified
(h/repeat 0 2 (h/fn int?))
[[] [1] [1 2] '() '(1) '(2 3)]
[[1 2 3] '(1 2 3)]
;; repeat - inside a list
(h/in-list (h/repeat 0 2 (h/fn int?)))
['() '(1) '(2 3)]
[[] [1] [1 2] [1 2 3] '(1 2 3)]
;; repeat - inside a vector
(h/in-vector (h/repeat 0 2 (h/fn int?)))
[[] [1] [1 2]]
[[1 2 3] '() '(1) '(2 3) '(1 2 3)]
;; repeat - inside a string
(h/in-string (h/repeat 4 6 (h/fn char?)))
["hello"]
["" "hi" [] [1] '(1 2 3)]
repeat - min > 0
(h/repeat 2 3 (h/fn int?))
[[1 2] [1 2 3]]
[[] [1] [1 2 3 4]]
;; repeat - max = +Infinity
(h/repeat 2 ##Inf (h/fn int?))
[[1 2] [1 2 3] [1 2 3 4]]
[[] [1]]
;; repeat - of a cat
(h/repeat 1 2 (h/cat (h/fn int?)
(h/fn string?)))
[[1 "a"] [1 "a" 2 "b"]]
[[] [1] [1 2] [1 "a" 2 "b" 3 "c"]]
;; repeat - of a cat with :inlined false
(h/repeat 1 2 (-> (h/cat (h/fn int?)
(h/fn string?))
(h/not-inlined)))
[[[1 "a"]] [[1 "a"] [2 "b"]] ['(1 "a") [2 "b"]]]
[[] [1] [1 2] [1 "a"] [1 "a" 2 "b"] [1 "a" 2 "b" 3 "c"]]
;; char-cat & char-set
(-> (h/cat (h/char-cat "good")
(h/val \space)
(h/alt (h/char-cat "morning")
(h/char-cat "afternoon")
(h/repeat 3 10 (h/char-set "#?!@_*+%"))))
(h/in-string))
["good morning" "good afternoon" "good #@*+?!"]
["good" "good " "good day"]
;; let / ref
(h/let ['pos-even? (h/and (h/fn pos-int?)
(h/fn even?))]
(h/ref 'pos-even?))
[2 4]
[-2 -1 0 1 3]
;; let / ref - with structural recursion
(h/let ['hiccup (h/alt
[:node (h/in-vector (h/cat (h/fn keyword?)
(h/? (h/map))
(h/* (h/not-inlined (h/ref 'hiccup)))))]
[:primitive (h/alt (h/fn nil?)
(h/fn boolean?)
(h/fn number?)
(h/fn string?))])]
(h/ref 'hiccup))
[nil
false
1
"hi"
[:div]
[:div {}]
[:div "hei" [:p "bonjour"]]
[:div {:a 1} "hei" [:p "bonjour"]]]
[{}
{:a 1}
['div]
[:div {:a 1} "hei" [:p {} {} "bonjour"]]]
;; let / ref - with recursion within a sequence
(h/let ['foo (h/cat (h/fn int?)
(h/? (h/ref 'foo))
(h/fn string?))]
(h/ref 'foo))
[[1 "hi"]
[1 1 "hi" "hi"]
[1 1 1 "hi" "hi" "hi"]]
[[1 1 "hi"]
[1 "hi" "hi"]
[1 1 :no "hi" "hi"]]
; let / ref - with shadowed local model
(h/let ['foo (h/ref 'bar)
'bar (h/fn int?)]
(h/let ['bar (h/fn string?)]
(h/ref 'foo)))
[1]
["hi"]]]
(doseq [[model valid-coll invalid-coll] (partition 3 test-data)]
(doseq [data valid-coll]
(is (valid? model data)))
(doseq [data invalid-coll]
(is (not (valid? model data))))))
(is (thrown? #?(:clj Exception :cljs js/Object)
(valid? (h/let [] (h/ref 'foo)) 'bar))))
(deftest describe-test
(let [test-data [;; fn
(h/fn #(= 1 %))
[1 1
2 :invalid]
(-> (h/fn int?)
(h/with-condition (h/fn odd?)))
[1 1
2 :invalid]
(-> (h/fn symbol?)
(h/with-condition (h/fn (complement #{'if 'val}))))
['a 'a
'if :invalid]
;; enum
(h/enum #{1 "2" false nil})
[1 1
"2" "2"
false false
nil nil
true :invalid]
;; and
(h/and (h/fn pos-int?)
(h/fn even?))
[0 :invalid
1 :invalid
2 2
3 :invalid
4 4]
;; or
(h/or (h/fn int?)
(h/fn string?))
[1 1
"a" "a"
:a :invalid]
;; set
(h/set-of (h/fn int?))
[#{1 2} [1 2]]
;; map
(h/map [:a {:optional true} (h/fn int?)]
[:b (h/or (h/fn int?)
(h/fn string?))])
[{:a 1, :b 2} {:a 1, :b 2}
{:a 1, :b "foo"} {:a 1, :b "foo"}
{:a 1, :b [1 2]} :invalid
; missing optional entry
{:b 2} {:b 2}
; missing entry
{:a 1} :invalid
; extra entry
{:a 1, :b 2, :c 3} {:a 1, :b 2}]
;; map-of - entry-model
(h/map-of (h/vector (h/fn keyword?) (h/fn int?)))
[{:a 1, :b 2} [[:a 1] [:b 2]]
{"a" 1} :invalid]
;; map-of - real world use case
(h/map-of (h/alt [:symbol (h/vector (h/fn simple-symbol?) (h/fn keyword?))]
[:keys (h/vector (h/val :keys) (h/vector-of (h/fn symbol?)))]
[:as (h/vector (h/val :as) (h/fn simple-symbol?))]))
'[{first-name :first-name
last-name :last-name
:keys [foo bar]
:as foobar}
[[:symbol [first-name :first-name]]
[:symbol [last-name :last-name]]
[:keys [:keys [foo bar]]]
[:as [:as foobar]]]]
;; sequence - :elements-model
(h/sequence-of (h/fn int?))
[[1 2 3] [1 2 3]
'(1 2 3) '(1 2 3)
`(1 2 3) '(1 2 3)
[1 "2" 3] :invalid]
;; sequence - :elements-model with condition
(-> (h/sequence-of (h/fn int?))
(h/with-condition (h/fn (fn [coll] (= coll (reverse coll))))))
[[1 2 1] [1 2 1]
'(1 2 3) :invalid]
;; sequence - :coll-type vector
(h/vector-of (h/fn any?))
[[1 2 3] [1 2 3]
'(1 2 3) :invalid
`(1 2 3) :invalid]
;; sequence - :coll-type list
(h/list-of (h/fn any?))
[[1 2 3] :invalid
'(1 2 3) '(1 2 3)
`(1 2 3) '(1 2 3)]
;; sequence - :entries
(h/tuple (h/fn int?) (h/fn string?))
[[1 "a"] [1 "a"]
[1 2] :invalid
[1] :invalid]
(h/tuple (h/fn int?)
[:text (h/fn string?)])
[[1 "a"] {:text "a"}]
(h/tuple [:number (h/fn int?)]
[:text (h/fn string?)])
[[1 "a"] {:number 1, :text "a"}]
;; sequence - :count-model
(-> (h/sequence-of (h/fn any?))
(h/with-count (h/val 3)))
[[1 2] :invalid
[1 2 3] [1 2 3]
[1 2 3 4] :invalid
"12" :invalid
"123" (into [] "123")
"1234" :invalid]
;; alt - not inside a sequence
(h/alt [:number (h/fn int?)]
[:sequence (h/vector-of (h/fn string?))])
[1 [:number 1]
["1"] [:sequence ["1"]]
[1] :invalid
"1" :invalid]
;; alt - inside a cat
(h/cat (h/fn int?)
(h/alt [:option1 (h/fn string?)]
[:option2 (h/fn keyword?)]
[:option3 (h/cat (h/fn string?)
(h/fn keyword?))])
(h/fn int?))
[[1 "2" 3] [1 [:option1 "2"] 3]
[1 :2 3] [1 [:option2 :2] 3]
[1 "a" :b 3] [1 [:option3 ["a" :b]] 3]
[1 ["a" :b] 3] :invalid]
;; alt - inside a cat, but with :inline false on its cat entry
(h/cat (h/fn int?)
(h/alt [:option1 (h/fn string?)]
[:option2 (h/fn keyword?)]
[:option3 (h/not-inlined (h/cat (h/fn string?)
(h/fn keyword?)))])
(h/fn int?))
[[1 "2" 3] [1 [:option1 "2"] 3]
[1 :2 3] [1 [:option2 :2] 3]
[1 "a" :b 3] :invalid
[1 ["a" :b] 3] [1 [:option3 ["a" :b]] 3]]
;; cat of cat, the inner cat is implicitly inlined
(h/cat (h/fn int?)
(h/cat (h/fn int?)))
[[1 2] [1 [2]]
[1] :invalid
[1 [2]] :invalid
[1 2 3] :invalid]
;; cat of cat, the inner cat is explicitly not inlined
(h/cat (h/fn int?)
(h/not-inlined (h/cat (h/fn int?))))
[[1 [2]] [1 [2]]
[1 '(2)] [1 [2]]
[1] :invalid
[1 2] :invalid
[1 [2] 3] :invalid]
;; repeat - no collection type specified
(h/repeat 0 2 (h/fn int?))
[[] []
[1] [1]
[1 2] [1 2]
'() []
'(1) [1]
'(2 3) [2 3]
[1 2 3] :invalid
'(1 2 3) :invalid]
;; repeat - inside a vector
(-> (h/repeat 0 2 (h/fn int?))
(h/in-vector))
[[1] [1]
'(1) :invalid]
;; repeat - inside a list
(-> (h/repeat 0 2 (h/fn int?))
(h/in-list))
[[1] :invalid
'(1) [1]]
repeat - min > 0
(h/repeat 2 3 (h/fn int?))
[[] :invalid
[1] :invalid
[1 2] [1 2]
[1 2 3] [1 2 3]
[1 2 3 4] :invalid]
;; repeat - max = +Infinity
(h/repeat 2 ##Inf (h/fn int?))
[[] :invalid
[1] :invalid
[1 2] [1 2]
[1 2 3] [1 2 3]]
;; repeat - of a cat
(h/repeat 1 2 (h/cat (h/fn int?)
(h/fn string?)))
[[1 "a"] [[1 "a"]]
[1 "a" 2 "b"] [[1 "a"] [2 "b"]]
[] :invalid
[1] :invalid
[1 2] :invalid
[1 "a" 2 "b" 3 "c"] :invalid]
;; repeat - of a cat with :inlined false
(h/repeat 1 2 (h/not-inlined (h/cat (h/fn int?)
(h/fn string?))))
[[[1 "a"]] [[1 "a"]]
[[1 "a"] [2 "b"]] [[1 "a"] [2 "b"]]
['(1 "a") [2 "b"]] [[1 "a"] [2 "b"]]
[] :invalid
[1] :invalid
[1 2] :invalid
[1 "a"] :invalid
[1 "a" 2 "b"] :invalid
[1 "a" 2 "b" 3 "c"] :invalid]
;; let / ref
(h/let ['pos-even? (h/and (h/fn pos-int?)
(h/fn even?))]
(h/ref 'pos-even?))
[0 :invalid
1 :invalid
2 2
3 :invalid
4 4]]]
(doseq [[model data-description-pairs] (partition 2 test-data)]
(doseq [[data description] (partition 2 data-description-pairs)]
(is (= [data (describe model data)]
[data description])))))
(is (thrown? #?(:clj Exception :cljs js/Object)
(describe (h/let [] (h/ref 'foo)) 'bar))))
| null | https://raw.githubusercontent.com/green-coder/minimallist/f10ebbd3c2b93e7579295618a7ed1e870c489bc4/test/minimallist/core_test.cljc | clojure | [:cat [:+ pos-int?]
[:+ int?]]
[:* int?]
[:+ int?]
fn
enum
and
or
set
map, entries
map, keys and values
sequence, no collection type specified
sequence, with condition
sequence as a list
sequence as a vector
sequence as a string
sequence with size specified using a model
sequence with entries (fixed size is implied)
sequence with entries in a string
alt
alt - inside a cat
alt - inside a cat, but with :inline false on its cat entry
cat & repeat - a color string
cat of cat, the inner cat is implicitly inlined
cat of cat, the inner cat is explicitly not inlined
repeat - no collection type specified
repeat - inside a list
repeat - inside a vector
repeat - inside a string
repeat - max = +Infinity
repeat - of a cat
repeat - of a cat with :inlined false
char-cat & char-set
let / ref
let / ref - with structural recursion
let / ref - with recursion within a sequence
let / ref - with shadowed local model
fn
enum
and
or
set
map
missing optional entry
missing entry
extra entry
map-of - entry-model
map-of - real world use case
sequence - :elements-model
sequence - :elements-model with condition
sequence - :coll-type vector
sequence - :coll-type list
sequence - :entries
sequence - :count-model
alt - not inside a sequence
alt - inside a cat
alt - inside a cat, but with :inline false on its cat entry
cat of cat, the inner cat is implicitly inlined
cat of cat, the inner cat is explicitly not inlined
repeat - no collection type specified
repeat - inside a vector
repeat - inside a list
repeat - max = +Infinity
repeat - of a cat
repeat - of a cat with :inlined false
let / ref | (ns minimallist.core-test
(:require [clojure.test :refer [deftest testing is are]]
[minimallist.core :refer [valid? explain describe undescribe] :as m]
[minimallist.helper :as h]
[minimallist.util :as util]))
(comment
(#'m/sequence-descriptions {}
(h/cat (h/+ (h/fn pos-int?))
(h/+ (h/fn int?)))
[3 4 0 2])
(#'m/sequence-descriptions {}
[: repeat { : min 0 , : 2 } int ? ]
(h/repeat 0 2 (h/fn int?))
(seq [1 2]))
(#'m/sequence-descriptions {}
[: alt [: ints [: repeat { : min 0 , : 2 } int ? ] ]
[: keywords [: repeat { : min 0 , : 2 } keyword ? ] ]
(h/alt [:ints (h/repeat 0 2 (h/fn int?))]
[:keywords (h/repeat 0 2 (h/fn keyword?))])
(seq [1 2]))
(#'m/sequence-descriptions {}
(h/* (h/fn int?))
(seq [1 :2]))
(#'m/sequence-descriptions {}
(h/+ (h/fn int?))
(seq [1 2 3])))
(deftest valid?-test
(h/fn #(= 1 %))
[1]
[2]
(-> (h/fn int?)
(h/with-condition (h/fn odd?)))
[1]
[2]
(-> (h/fn symbol?)
(h/with-condition (h/fn (complement #{'if 'val}))))
['a]
['if]
(h/enum #{1 "2" :3})
[1 "2" :3]
[[1] 2 true false nil]
(h/enum #{nil false})
[nil false]
[true '()]
(h/and (h/fn pos-int?)
(h/fn even?))
[2 4 6]
[0 :a -1 1 3]
(h/or (h/fn pos-int?)
(h/fn even?))
[-2 0 1 2 3]
[-3 -1]
(-> (h/set-of (h/fn int?))
(h/with-count (h/enum #{2 3})))
[#{1 2} #{1 2 3}]
[#{1 :a} [1 2 3] '(1 2) `(1 ~2) #{1} #{1 2 3 4}]
(h/map [:a (h/fn int?)]
[:b {:optional true} (h/fn string?)]
[(list 1 2 3) (h/fn string?)])
[{:a 1, :b "foo", (list 1 2 3) "you can count on me like ..."}
{:a 1, :b "bar", [1 2 3] "soleil !"}
{:a 1, [1 2 3] "soleil !"}]
[{:a 1, :b "foo"}
{:a 1, :b "foo", #{1 2 3} "bar"}
{:a 1, :b 'bar, [1 2 3] "soleil !"}]
(h/map-of (h/vector (h/fn keyword?) (h/fn int?)))
[{} {:a 1, :b 2}]
[{:a 1, :b "2"} [[:a 1] [:b 2]] {true 1, false 2}]
(h/sequence-of (h/fn int?))
['(1 2 3) [1 2 3] `(1 2 ~3)]
['(1 :a) #{1 2 3} {:a 1, :b 2, :c 3}]
(h/sequence-of (h/fn char?))
["" "hi" "hello"]
[[1 2 3]]
(-> (h/sequence-of (h/fn int?))
(h/with-condition (h/fn (fn [coll] (= coll (reverse coll))))))
[[1] '(1 1) '[1 2 1]]
['(1 2) '(1 2 3)]
(h/list-of (h/fn int?))
['(1 2 3) `(1 2 ~3)]
['(1 :a) [1 2 3] #{1 2 3}]
(h/vector-of (h/fn int?))
[[1 2 3]]
[[1 :a] '(1 2 3) #{1 2 3} `(1 2 ~3)]
(h/string-of (h/enum (set "0123456789abcdef")))
["03ab4c" "cafe"]
["coffee" [1 :a] '(1 2 3) #{1 2 3} `(1 2 ~3)]
(-> (h/sequence-of (h/fn any?))
(h/with-count (h/enum #{2 3})))
['(1 2) [1 "2"] `(1 ~"2") [1 "2" :3] "hi"]
[#{1 "a"} [1 "2" :3 :4] "hello"]
(h/tuple (h/fn int?) (h/fn string?))
['(1 "2") [1 "2"] `(1 ~"2")]
[#{1 "a"} [1 "2" :3]]
(h/string-tuple (h/val \a) (h/enum #{\b \c}))
["ab" "ac"]
[[\a \b] #{\a \b}]
(h/alt [:int (h/fn int?)]
[:strings (h/vector-of (h/fn string?))])
[1 ["1"]]
[[1] "1" :1 [:1]]
(h/cat (h/fn int?)
(h/alt [:string (h/fn string?)]
[:keyword (h/fn keyword?)]
[:string-keyword (h/cat (h/fn string?)
(h/fn keyword?))])
(h/fn int?))
[[1 "2" 3] [1 :2 3] [1 "a" :b 3]]
[[1 ["a" :b] 3]]
(h/cat (h/fn int?)
(h/alt [:string (h/fn string?)]
[:keyword (h/fn keyword?)]
[:string-keyword (-> (h/cat (h/fn string?)
(h/fn keyword?))
(h/not-inlined))])
(h/fn int?))
[[1 "2" 3] [1 :2 3] [1 ["a" :b] 3]]
[[1 "a" :b 3]]
(-> (h/cat (h/val \#)
(h/repeat 6 6 (h/enum (set "0123456789abcdefABCDEF")))))
["#000000" "#af4Ea5"]
["000000" "#cafe" "#coffee"]
(-> (h/cat (h/fn int?)
(h/cat (h/fn int?)))
(h/in-vector))
[[1 2]]
[[1] [1 [2]] [1 2 3] '(1) '(1 2) '(1 (2)) '(1 2 3)]
(-> (h/cat (h/fn int?)
(-> (h/cat (h/fn int?))
(h/not-inlined))))
[[1 [2]] '[1 (2)] '(1 (2))]
[[1] [1 2] [1 [2] 3]]
(h/repeat 0 2 (h/fn int?))
[[] [1] [1 2] '() '(1) '(2 3)]
[[1 2 3] '(1 2 3)]
(h/in-list (h/repeat 0 2 (h/fn int?)))
['() '(1) '(2 3)]
[[] [1] [1 2] [1 2 3] '(1 2 3)]
(h/in-vector (h/repeat 0 2 (h/fn int?)))
[[] [1] [1 2]]
[[1 2 3] '() '(1) '(2 3) '(1 2 3)]
(h/in-string (h/repeat 4 6 (h/fn char?)))
["hello"]
["" "hi" [] [1] '(1 2 3)]
repeat - min > 0
(h/repeat 2 3 (h/fn int?))
[[1 2] [1 2 3]]
[[] [1] [1 2 3 4]]
(h/repeat 2 ##Inf (h/fn int?))
[[1 2] [1 2 3] [1 2 3 4]]
[[] [1]]
(h/repeat 1 2 (h/cat (h/fn int?)
(h/fn string?)))
[[1 "a"] [1 "a" 2 "b"]]
[[] [1] [1 2] [1 "a" 2 "b" 3 "c"]]
(h/repeat 1 2 (-> (h/cat (h/fn int?)
(h/fn string?))
(h/not-inlined)))
[[[1 "a"]] [[1 "a"] [2 "b"]] ['(1 "a") [2 "b"]]]
[[] [1] [1 2] [1 "a"] [1 "a" 2 "b"] [1 "a" 2 "b" 3 "c"]]
(-> (h/cat (h/char-cat "good")
(h/val \space)
(h/alt (h/char-cat "morning")
(h/char-cat "afternoon")
(h/repeat 3 10 (h/char-set "#?!@_*+%"))))
(h/in-string))
["good morning" "good afternoon" "good #@*+?!"]
["good" "good " "good day"]
(h/let ['pos-even? (h/and (h/fn pos-int?)
(h/fn even?))]
(h/ref 'pos-even?))
[2 4]
[-2 -1 0 1 3]
(h/let ['hiccup (h/alt
[:node (h/in-vector (h/cat (h/fn keyword?)
(h/? (h/map))
(h/* (h/not-inlined (h/ref 'hiccup)))))]
[:primitive (h/alt (h/fn nil?)
(h/fn boolean?)
(h/fn number?)
(h/fn string?))])]
(h/ref 'hiccup))
[nil
false
1
"hi"
[:div]
[:div {}]
[:div "hei" [:p "bonjour"]]
[:div {:a 1} "hei" [:p "bonjour"]]]
[{}
{:a 1}
['div]
[:div {:a 1} "hei" [:p {} {} "bonjour"]]]
(h/let ['foo (h/cat (h/fn int?)
(h/? (h/ref 'foo))
(h/fn string?))]
(h/ref 'foo))
[[1 "hi"]
[1 1 "hi" "hi"]
[1 1 1 "hi" "hi" "hi"]]
[[1 1 "hi"]
[1 "hi" "hi"]
[1 1 :no "hi" "hi"]]
(h/let ['foo (h/ref 'bar)
'bar (h/fn int?)]
(h/let ['bar (h/fn string?)]
(h/ref 'foo)))
[1]
["hi"]]]
(doseq [[model valid-coll invalid-coll] (partition 3 test-data)]
(doseq [data valid-coll]
(is (valid? model data)))
(doseq [data invalid-coll]
(is (not (valid? model data))))))
(is (thrown? #?(:clj Exception :cljs js/Object)
(valid? (h/let [] (h/ref 'foo)) 'bar))))
(deftest describe-test
(h/fn #(= 1 %))
[1 1
2 :invalid]
(-> (h/fn int?)
(h/with-condition (h/fn odd?)))
[1 1
2 :invalid]
(-> (h/fn symbol?)
(h/with-condition (h/fn (complement #{'if 'val}))))
['a 'a
'if :invalid]
(h/enum #{1 "2" false nil})
[1 1
"2" "2"
false false
nil nil
true :invalid]
(h/and (h/fn pos-int?)
(h/fn even?))
[0 :invalid
1 :invalid
2 2
3 :invalid
4 4]
(h/or (h/fn int?)
(h/fn string?))
[1 1
"a" "a"
:a :invalid]
(h/set-of (h/fn int?))
[#{1 2} [1 2]]
(h/map [:a {:optional true} (h/fn int?)]
[:b (h/or (h/fn int?)
(h/fn string?))])
[{:a 1, :b 2} {:a 1, :b 2}
{:a 1, :b "foo"} {:a 1, :b "foo"}
{:a 1, :b [1 2]} :invalid
{:b 2} {:b 2}
{:a 1} :invalid
{:a 1, :b 2, :c 3} {:a 1, :b 2}]
(h/map-of (h/vector (h/fn keyword?) (h/fn int?)))
[{:a 1, :b 2} [[:a 1] [:b 2]]
{"a" 1} :invalid]
(h/map-of (h/alt [:symbol (h/vector (h/fn simple-symbol?) (h/fn keyword?))]
[:keys (h/vector (h/val :keys) (h/vector-of (h/fn symbol?)))]
[:as (h/vector (h/val :as) (h/fn simple-symbol?))]))
'[{first-name :first-name
last-name :last-name
:keys [foo bar]
:as foobar}
[[:symbol [first-name :first-name]]
[:symbol [last-name :last-name]]
[:keys [:keys [foo bar]]]
[:as [:as foobar]]]]
(h/sequence-of (h/fn int?))
[[1 2 3] [1 2 3]
'(1 2 3) '(1 2 3)
`(1 2 3) '(1 2 3)
[1 "2" 3] :invalid]
(-> (h/sequence-of (h/fn int?))
(h/with-condition (h/fn (fn [coll] (= coll (reverse coll))))))
[[1 2 1] [1 2 1]
'(1 2 3) :invalid]
(h/vector-of (h/fn any?))
[[1 2 3] [1 2 3]
'(1 2 3) :invalid
`(1 2 3) :invalid]
(h/list-of (h/fn any?))
[[1 2 3] :invalid
'(1 2 3) '(1 2 3)
`(1 2 3) '(1 2 3)]
(h/tuple (h/fn int?) (h/fn string?))
[[1 "a"] [1 "a"]
[1 2] :invalid
[1] :invalid]
(h/tuple (h/fn int?)
[:text (h/fn string?)])
[[1 "a"] {:text "a"}]
(h/tuple [:number (h/fn int?)]
[:text (h/fn string?)])
[[1 "a"] {:number 1, :text "a"}]
(-> (h/sequence-of (h/fn any?))
(h/with-count (h/val 3)))
[[1 2] :invalid
[1 2 3] [1 2 3]
[1 2 3 4] :invalid
"12" :invalid
"123" (into [] "123")
"1234" :invalid]
(h/alt [:number (h/fn int?)]
[:sequence (h/vector-of (h/fn string?))])
[1 [:number 1]
["1"] [:sequence ["1"]]
[1] :invalid
"1" :invalid]
(h/cat (h/fn int?)
(h/alt [:option1 (h/fn string?)]
[:option2 (h/fn keyword?)]
[:option3 (h/cat (h/fn string?)
(h/fn keyword?))])
(h/fn int?))
[[1 "2" 3] [1 [:option1 "2"] 3]
[1 :2 3] [1 [:option2 :2] 3]
[1 "a" :b 3] [1 [:option3 ["a" :b]] 3]
[1 ["a" :b] 3] :invalid]
(h/cat (h/fn int?)
(h/alt [:option1 (h/fn string?)]
[:option2 (h/fn keyword?)]
[:option3 (h/not-inlined (h/cat (h/fn string?)
(h/fn keyword?)))])
(h/fn int?))
[[1 "2" 3] [1 [:option1 "2"] 3]
[1 :2 3] [1 [:option2 :2] 3]
[1 "a" :b 3] :invalid
[1 ["a" :b] 3] [1 [:option3 ["a" :b]] 3]]
(h/cat (h/fn int?)
(h/cat (h/fn int?)))
[[1 2] [1 [2]]
[1] :invalid
[1 [2]] :invalid
[1 2 3] :invalid]
(h/cat (h/fn int?)
(h/not-inlined (h/cat (h/fn int?))))
[[1 [2]] [1 [2]]
[1 '(2)] [1 [2]]
[1] :invalid
[1 2] :invalid
[1 [2] 3] :invalid]
(h/repeat 0 2 (h/fn int?))
[[] []
[1] [1]
[1 2] [1 2]
'() []
'(1) [1]
'(2 3) [2 3]
[1 2 3] :invalid
'(1 2 3) :invalid]
(-> (h/repeat 0 2 (h/fn int?))
(h/in-vector))
[[1] [1]
'(1) :invalid]
(-> (h/repeat 0 2 (h/fn int?))
(h/in-list))
[[1] :invalid
'(1) [1]]
repeat - min > 0
(h/repeat 2 3 (h/fn int?))
[[] :invalid
[1] :invalid
[1 2] [1 2]
[1 2 3] [1 2 3]
[1 2 3 4] :invalid]
(h/repeat 2 ##Inf (h/fn int?))
[[] :invalid
[1] :invalid
[1 2] [1 2]
[1 2 3] [1 2 3]]
(h/repeat 1 2 (h/cat (h/fn int?)
(h/fn string?)))
[[1 "a"] [[1 "a"]]
[1 "a" 2 "b"] [[1 "a"] [2 "b"]]
[] :invalid
[1] :invalid
[1 2] :invalid
[1 "a" 2 "b" 3 "c"] :invalid]
(h/repeat 1 2 (h/not-inlined (h/cat (h/fn int?)
(h/fn string?))))
[[[1 "a"]] [[1 "a"]]
[[1 "a"] [2 "b"]] [[1 "a"] [2 "b"]]
['(1 "a") [2 "b"]] [[1 "a"] [2 "b"]]
[] :invalid
[1] :invalid
[1 2] :invalid
[1 "a"] :invalid
[1 "a" 2 "b"] :invalid
[1 "a" 2 "b" 3 "c"] :invalid]
(h/let ['pos-even? (h/and (h/fn pos-int?)
(h/fn even?))]
(h/ref 'pos-even?))
[0 :invalid
1 :invalid
2 2
3 :invalid
4 4]]]
(doseq [[model data-description-pairs] (partition 2 test-data)]
(doseq [[data description] (partition 2 data-description-pairs)]
(is (= [data (describe model data)]
[data description])))))
(is (thrown? #?(:clj Exception :cljs js/Object)
(describe (h/let [] (h/ref 'foo)) 'bar))))
|
c37590de33f2c0bcb6b5e616bcc30dce35046513cd78683128ee1546cc84a803 | haskell-github/github | Example.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
import Prelude ()
import Prelude.Compat
import Data.Text (Text, pack)
import Data.Text.IO as T (putStrLn)
import qualified GitHub.Endpoints.Users.Followers as GitHub
main :: IO ()
main = do
possibleUsers <- GitHub.usersFollowing "mike-burns"
T.putStrLn $ either (("Error: " <>) . pack . show)
(foldMap ((<> "\n") . formatUser))
possibleUsers
formatUser :: GitHub.SimpleUser -> Text
formatUser = GitHub.untagName . GitHub.simpleUserLogin
| null | https://raw.githubusercontent.com/haskell-github/github/81d9b658c33a706f18418211a78d2690752518a4/samples/Users/Followers/Example.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE NoImplicitPrelude #
import Prelude ()
import Prelude.Compat
import Data.Text (Text, pack)
import Data.Text.IO as T (putStrLn)
import qualified GitHub.Endpoints.Users.Followers as GitHub
main :: IO ()
main = do
possibleUsers <- GitHub.usersFollowing "mike-burns"
T.putStrLn $ either (("Error: " <>) . pack . show)
(foldMap ((<> "\n") . formatUser))
possibleUsers
formatUser :: GitHub.SimpleUser -> Text
formatUser = GitHub.untagName . GitHub.simpleUserLogin
|
7719a905e04db9bb860ad826552de62bb187448aaccd17e834c09cdc1c0cc59e | ixy-languages/ixy.ml | ixy_pci.ml | open Ixy_memory
open Log
type hw =
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t
type pci_config =
{ vendor : int
; device_id : int
; class_code : int
; subclass : int
; prog_if : int
}
let vendor_intel = 0x8086
module type S = sig
type t
val map_resource : t -> hw
val get_config : t -> pci_config
val to_string : t -> string
val allocate_dma :
t -> ?require_contiguous:bool -> int -> Ixy_memory.dma_memory option
val virt_to_phys : Cstruct.t -> Cstruct.uint64
end
module type Memory = sig
include S
val allocate_mempool : t -> ?pre_fill:Cstruct.t -> num_entries:int -> mempool
val num_free_bufs : mempool -> int
val pkt_buf_alloc_batch : mempool -> num_bufs:int -> pkt_buf array
val pkt_buf_alloc : mempool -> pkt_buf option
val pkt_buf_resize : pkt_buf -> size:int -> unit
val pkt_buf_free : pkt_buf -> unit
end
module Make (S : S) = struct
include S
let allocate_mempool t ?pre_fill ~num_entries =
let entry_size = 2048 in (* entry_size is fixed for now *)
if huge_page_size mod entry_size <> 0 then
error "entry size must be a divisor of huge page size (%d)" huge_page_size;
let { virt; _ } =
match S.allocate_dma t ~require_contiguous:false (num_entries * entry_size) with
| None -> error "Could not allocate DMA memory"
| Some mem -> mem in
Cstruct.memset virt 0; (* might not be necessary *)
let mempool =
{ entry_size;
num_entries;
free = num_entries;
free_bufs = Array.make num_entries dummy
} in
let init_buf index =
let data =
Cstruct.sub virt (index * entry_size) entry_size in
let size =
match pre_fill with
| Some init ->
let len = Cstruct.len init in
Cstruct.blit init 0 data 0 len;
len
| None -> entry_size in
{ phys = S.virt_to_phys data;
mempool;
size;
data
} in
Array.iteri
(fun i _ -> mempool.free_bufs.(i) <- init_buf i)
mempool.free_bufs;
mempool
let num_free_bufs mempool = mempool.free
let pkt_buf_alloc_batch mempool ~num_bufs =
if num_bufs > mempool.num_entries then
warn
"can never allocate %d bufs in a mempool with %d bufs"
num_bufs
mempool.num_entries;
let n = min num_bufs mempool.free in
let alloc_start = mempool.free - n in
let bufs = Array.sub mempool.free_bufs alloc_start n in
mempool.free <- alloc_start;
bufs
let pkt_buf_alloc mempool =
doing " pkt_buf_alloc_batch " has a bit more overhead
if mempool.free > 0 then
let index = mempool.free - 1 in
mempool.free <- index;
Some mempool.free_bufs.(index)
else
None
let pkt_buf_free ({ mempool; _ } as buf) =
mempool.free_bufs.(mempool.free) <- buf;
mempool.free <- mempool.free + 1
let pkt_buf_resize ({ mempool; _ } as buf) ~size =
MTU is fixed at 1518 by default .
let upper = min mempool.entry_size IXGBE.default_mtu in
if size > 0 && size <= upper then
buf.size <- size
else
error "0 < size <= %d is not fulfilled; size = %d" upper size
end
| null | https://raw.githubusercontent.com/ixy-languages/ixy.ml/e79dcc4a19afd8e531346c27624c54224f942dc9/lib/ixy_pci.ml | ocaml | entry_size is fixed for now
might not be necessary | open Ixy_memory
open Log
type hw =
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t
type pci_config =
{ vendor : int
; device_id : int
; class_code : int
; subclass : int
; prog_if : int
}
let vendor_intel = 0x8086
module type S = sig
type t
val map_resource : t -> hw
val get_config : t -> pci_config
val to_string : t -> string
val allocate_dma :
t -> ?require_contiguous:bool -> int -> Ixy_memory.dma_memory option
val virt_to_phys : Cstruct.t -> Cstruct.uint64
end
module type Memory = sig
include S
val allocate_mempool : t -> ?pre_fill:Cstruct.t -> num_entries:int -> mempool
val num_free_bufs : mempool -> int
val pkt_buf_alloc_batch : mempool -> num_bufs:int -> pkt_buf array
val pkt_buf_alloc : mempool -> pkt_buf option
val pkt_buf_resize : pkt_buf -> size:int -> unit
val pkt_buf_free : pkt_buf -> unit
end
module Make (S : S) = struct
include S
let allocate_mempool t ?pre_fill ~num_entries =
if huge_page_size mod entry_size <> 0 then
error "entry size must be a divisor of huge page size (%d)" huge_page_size;
let { virt; _ } =
match S.allocate_dma t ~require_contiguous:false (num_entries * entry_size) with
| None -> error "Could not allocate DMA memory"
| Some mem -> mem in
let mempool =
{ entry_size;
num_entries;
free = num_entries;
free_bufs = Array.make num_entries dummy
} in
let init_buf index =
let data =
Cstruct.sub virt (index * entry_size) entry_size in
let size =
match pre_fill with
| Some init ->
let len = Cstruct.len init in
Cstruct.blit init 0 data 0 len;
len
| None -> entry_size in
{ phys = S.virt_to_phys data;
mempool;
size;
data
} in
Array.iteri
(fun i _ -> mempool.free_bufs.(i) <- init_buf i)
mempool.free_bufs;
mempool
let num_free_bufs mempool = mempool.free
let pkt_buf_alloc_batch mempool ~num_bufs =
if num_bufs > mempool.num_entries then
warn
"can never allocate %d bufs in a mempool with %d bufs"
num_bufs
mempool.num_entries;
let n = min num_bufs mempool.free in
let alloc_start = mempool.free - n in
let bufs = Array.sub mempool.free_bufs alloc_start n in
mempool.free <- alloc_start;
bufs
let pkt_buf_alloc mempool =
doing " pkt_buf_alloc_batch " has a bit more overhead
if mempool.free > 0 then
let index = mempool.free - 1 in
mempool.free <- index;
Some mempool.free_bufs.(index)
else
None
let pkt_buf_free ({ mempool; _ } as buf) =
mempool.free_bufs.(mempool.free) <- buf;
mempool.free <- mempool.free + 1
let pkt_buf_resize ({ mempool; _ } as buf) ~size =
MTU is fixed at 1518 by default .
let upper = min mempool.entry_size IXGBE.default_mtu in
if size > 0 && size <= upper then
buf.size <- size
else
error "0 < size <= %d is not fulfilled; size = %d" upper size
end
|
8559d097f34e36aac92d4fac17a3daf0ed0f6e6dde40daa999d67e8f3f7583ae | unison-code/uni-instr-sel | Base.hs | |
Copyright : Copyright ( c ) 2012 - 2017 , < >
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <>
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
Main authors:
Gabriel Hjort Blindell <>
-}
{-# LANGUAGE DeriveDataTypeable #-}
module UniISLLVM.Drivers.Base
( MakeAction (..)
, Options (..)
, module Language.InstrSel.DriverTools
)
where
import System.Console.CmdArgs
( Data
, Typeable
)
import Language.InstrSel.DriverTools
--------------
-- Data types
--------------
-- | Options that can be given on the command line.
data Options
= Options
{ command :: String
, functionFile :: Maybe String
, outFile :: Maybe String
, makeAction :: MakeAction
}
deriving (Data, Typeable)
-- | Represents 'make' actions.
data MakeAction
= MakeNothing
| MakeFunctionGraphFromLLVM
deriving (Eq, Typeable, Data)
| null | https://raw.githubusercontent.com/unison-code/uni-instr-sel/2edb2f3399ea43e75f33706261bd6b93bedc6762/uni-is-llvm/UniISLLVM/Drivers/Base.hs | haskell | # LANGUAGE DeriveDataTypeable #
------------
Data types
------------
| Options that can be given on the command line.
| Represents 'make' actions. | |
Copyright : Copyright ( c ) 2012 - 2017 , < >
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <>
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
Main authors:
Gabriel Hjort Blindell <>
-}
module UniISLLVM.Drivers.Base
( MakeAction (..)
, Options (..)
, module Language.InstrSel.DriverTools
)
where
import System.Console.CmdArgs
( Data
, Typeable
)
import Language.InstrSel.DriverTools
data Options
= Options
{ command :: String
, functionFile :: Maybe String
, outFile :: Maybe String
, makeAction :: MakeAction
}
deriving (Data, Typeable)
data MakeAction
= MakeNothing
| MakeFunctionGraphFromLLVM
deriving (Eq, Typeable, Data)
|
1db19c245b49c296ac81b037642226312da51daa881defd8e88d807f4c5cd487 | racket/gui | gauge.rkt | #lang racket/base
(require racket/class
ffi/unsafe
"../../syntax.rkt"
"../common/event.rkt"
"item.rkt"
"utils.rkt"
"const.rkt"
"window.rkt"
"wndclass.rkt"
"types.rkt")
(provide
(protect-out gauge%))
(define PBS_VERTICAL #x04)
(define PBM_SETRANGE (+ WM_USER 1))
(define PBM_SETRANGE32 (+ WM_USER 6))
(define PBM_SETPOS (+ WM_USER 2))
wParam = return ( TRUE ? low : high ) . lParam = PPBRANGE or NULL
(define PBM_GETPOS (+ WM_USER 8))
(define gauge%
(class item%
(inherit set-size)
(init parent
label
rng
x y w h
style
font)
(define hwnd
(CreateWindowExW/control 0
"PLTmsctls_progress32"
label
(bitwise-ior WS_CHILD WS_CLIPSIBLINGS
(if (memq 'vertical style)
PBS_VERTICAL
0))
0 0 0 0
(send parent get-content-hwnd)
#f
hInstance
#f))
(super-new [callback void]
[parent parent]
[hwnd hwnd]
[style style])
(set-range rng)
(if (memq 'horizontal style)
(set-size #f #f 100 24)
(set-size #f #f 24 100))
(define/override (size->screen v) (->screen* v))
(define/public (get-value)
(SendMessageW hwnd PBM_GETPOS 0 0))
(define/public (set-value v)
(void (SendMessageW hwnd PBM_SETPOS v 0)))
(define/public (get-range)
(SendMessageW hwnd PBM_GETRANGE 0 0))
(define/public (set-range v)
(void (SendMessageW hwnd PBM_SETRANGE32 0 v)))))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mred/private/wx/win32/gauge.rkt | racket | #lang racket/base
(require racket/class
ffi/unsafe
"../../syntax.rkt"
"../common/event.rkt"
"item.rkt"
"utils.rkt"
"const.rkt"
"window.rkt"
"wndclass.rkt"
"types.rkt")
(provide
(protect-out gauge%))
(define PBS_VERTICAL #x04)
(define PBM_SETRANGE (+ WM_USER 1))
(define PBM_SETRANGE32 (+ WM_USER 6))
(define PBM_SETPOS (+ WM_USER 2))
wParam = return ( TRUE ? low : high ) . lParam = PPBRANGE or NULL
(define PBM_GETPOS (+ WM_USER 8))
(define gauge%
(class item%
(inherit set-size)
(init parent
label
rng
x y w h
style
font)
(define hwnd
(CreateWindowExW/control 0
"PLTmsctls_progress32"
label
(bitwise-ior WS_CHILD WS_CLIPSIBLINGS
(if (memq 'vertical style)
PBS_VERTICAL
0))
0 0 0 0
(send parent get-content-hwnd)
#f
hInstance
#f))
(super-new [callback void]
[parent parent]
[hwnd hwnd]
[style style])
(set-range rng)
(if (memq 'horizontal style)
(set-size #f #f 100 24)
(set-size #f #f 24 100))
(define/override (size->screen v) (->screen* v))
(define/public (get-value)
(SendMessageW hwnd PBM_GETPOS 0 0))
(define/public (set-value v)
(void (SendMessageW hwnd PBM_SETPOS v 0)))
(define/public (get-range)
(SendMessageW hwnd PBM_GETRANGE 0 0))
(define/public (set-range v)
(void (SendMessageW hwnd PBM_SETRANGE32 0 v)))))
|
|
b7ae6cba6f7e7eb68ef9ff7cf08017d826b4b46d922e3f847ac489cae85d5096 | anycable/erlycable | anycable.erl | -*- coding : utf-8 -*-
%% Automatically generated, do not edit
Generated by gpb_compile version 3.24.4
-module(anycable).
-export([encode_msg/1, encode_msg/2]).
-export([decode_msg/2, decode_msg/3]).
-export([merge_msgs/2, merge_msgs/3]).
-export([verify_msg/1, verify_msg/2]).
-export([get_msg_defs/0]).
-export([get_msg_names/0]).
-export([get_enum_names/0]).
-export([find_msg_def/1, fetch_msg_def/1]).
-export([find_enum_def/1, fetch_enum_def/1]).
-export([enum_symbol_by_value/2, enum_value_by_symbol/2]).
-export([enum_symbol_by_value_Status/1, enum_value_by_symbol_Status/1]).
-export([get_service_names/0]).
-export([get_service_def/1]).
-export([get_rpc_names/1]).
-export([find_rpc_def/2, fetch_rpc_def/2]).
-export([get_package_name/0]).
-export([gpb_version_as_string/0, gpb_version_as_list/0]).
-include("anycable.hrl").
-include("gpb.hrl").
-record('map<string,string>',{key, value}).
-spec encode_msg(_) -> binary().
encode_msg(Msg) -> encode_msg(Msg, []).
-spec encode_msg(_, list()) -> binary().
encode_msg(Msg, Opts) ->
case proplists:get_bool(verify, Opts) of
true -> verify_msg(Msg, Opts);
false -> ok
end,
TrUserData = proplists:get_value(user_data, Opts),
case Msg of
#'DisconnectResponse'{} ->
e_msg_DisconnectResponse(Msg, TrUserData);
#'CommandResponse'{} ->
e_msg_CommandResponse(Msg, TrUserData);
#'CommandMessage'{} ->
e_msg_CommandMessage(Msg, TrUserData);
#'ConnectionResponse'{} ->
e_msg_ConnectionResponse(Msg, TrUserData);
#'ConnectionRequest'{} ->
e_msg_ConnectionRequest(Msg, TrUserData);
#'DisconnectRequest'{} ->
e_msg_DisconnectRequest(Msg, TrUserData)
end.
e_msg_DisconnectResponse(Msg, TrUserData) ->
e_msg_DisconnectResponse(Msg, <<>>, TrUserData).
e_msg_DisconnectResponse(#'DisconnectResponse'{status =
F1},
Bin, TrUserData) ->
if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_enum_Status(TrF1, <<Bin/binary, 8>>)
end.
e_msg_CommandResponse(Msg, TrUserData) ->
e_msg_CommandResponse(Msg, <<>>, TrUserData).
e_msg_CommandResponse(#'CommandResponse'{status = F1,
disconnect = F2, stop_streams = F3,
streams = F4, transmissions = F5},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_enum_Status(TrF1, <<Bin/binary, 8>>)
end,
B2 = if F2 == undefined -> B1;
true ->
TrF2 = id(F2, TrUserData),
e_type_bool(TrF2, <<B1/binary, 16>>)
end,
B3 = if F3 == undefined -> B2;
true ->
TrF3 = id(F3, TrUserData),
e_type_bool(TrF3, <<B2/binary, 24>>)
end,
B4 = begin
TrF4 = id(F4, TrUserData),
if TrF4 == [] -> B3;
true ->
e_field_CommandResponse_streams(TrF4, B3, TrUserData)
end
end,
begin
TrF5 = id(F5, TrUserData),
if TrF5 == [] -> B4;
true ->
e_field_CommandResponse_transmissions(TrF5, B4,
TrUserData)
end
end.
e_msg_CommandMessage(Msg, TrUserData) ->
e_msg_CommandMessage(Msg, <<>>, TrUserData).
e_msg_CommandMessage(#'CommandMessage'{command = F1,
identifier = F2,
connection_identifiers = F3, data = F4},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
B2 = if F2 == undefined -> B1;
true ->
TrF2 = id(F2, TrUserData),
e_type_string(TrF2, <<B1/binary, 18>>)
end,
B3 = if F3 == undefined -> B2;
true ->
TrF3 = id(F3, TrUserData),
e_type_string(TrF3, <<B2/binary, 26>>)
end,
if F4 == undefined -> B3;
true ->
TrF4 = id(F4, TrUserData),
e_type_string(TrF4, <<B3/binary, 34>>)
end.
e_msg_ConnectionResponse(Msg, TrUserData) ->
e_msg_ConnectionResponse(Msg, <<>>, TrUserData).
e_msg_ConnectionResponse(#'ConnectionResponse'{status =
F1,
identifiers = F2,
transmissions = F3},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_enum_Status(TrF1, <<Bin/binary, 8>>)
end,
B2 = if F2 == undefined -> B1;
true ->
TrF2 = id(F2, TrUserData),
e_type_string(TrF2, <<B1/binary, 18>>)
end,
begin
TrF3 = id(F3, TrUserData),
if TrF3 == [] -> B2;
true ->
e_field_ConnectionResponse_transmissions(TrF3, B2,
TrUserData)
end
end.
e_msg_ConnectionRequest(Msg, TrUserData) ->
e_msg_ConnectionRequest(Msg, <<>>, TrUserData).
e_msg_ConnectionRequest(#'ConnectionRequest'{path = F1,
headers = F2},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
begin
TrF2 = id(F2, TrUserData),
if TrF2 == [] -> B1;
true ->
e_field_ConnectionRequest_headers(TrF2, B1, TrUserData)
end
end.
e_msg_DisconnectRequest(Msg, TrUserData) ->
e_msg_DisconnectRequest(Msg, <<>>, TrUserData).
e_msg_DisconnectRequest(#'DisconnectRequest'{identifiers
= F1,
subscriptions = F2, path = F3,
headers = F4},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
B2 = begin
TrF2 = id(F2, TrUserData),
if TrF2 == [] -> B1;
true ->
e_field_DisconnectRequest_subscriptions(TrF2, B1,
TrUserData)
end
end,
B3 = if F3 == undefined -> B2;
true ->
TrF3 = id(F3, TrUserData),
e_type_string(TrF3, <<B2/binary, 26>>)
end,
begin
TrF4 = id(F4, TrUserData),
if TrF4 == [] -> B3;
true ->
e_field_DisconnectRequest_headers(TrF4, B3, TrUserData)
end
end.
e_field_CommandResponse_streams([Elem | Rest], Bin,
TrUserData) ->
Bin2 = <<Bin/binary, 34>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_CommandResponse_streams(Rest, Bin3, TrUserData);
e_field_CommandResponse_streams([], Bin, _TrUserData) ->
Bin.
e_field_CommandResponse_transmissions([Elem | Rest],
Bin, TrUserData) ->
Bin2 = <<Bin/binary, 42>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_CommandResponse_transmissions(Rest, Bin3,
TrUserData);
e_field_CommandResponse_transmissions([], Bin,
_TrUserData) ->
Bin.
e_field_ConnectionResponse_transmissions([Elem | Rest],
Bin, TrUserData) ->
Bin2 = <<Bin/binary, 26>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_ConnectionResponse_transmissions(Rest, Bin3,
TrUserData);
e_field_ConnectionResponse_transmissions([], Bin,
_TrUserData) ->
Bin.
e_mfield_ConnectionRequest_headers(Msg, Bin,
TrUserData) ->
SubBin = 'e_msg_map<string,string>'(Msg, <<>>,
TrUserData),
Bin2 = e_varint(byte_size(SubBin), Bin),
<<Bin2/binary, SubBin/binary>>.
e_field_ConnectionRequest_headers([Elem | Rest], Bin,
TrUserData) ->
Bin2 = <<Bin/binary, 18>>,
Bin3 =
e_mfield_ConnectionRequest_headers('tr_encode_ConnectionRequest.headers[x]'(Elem,
TrUserData),
Bin2, TrUserData),
e_field_ConnectionRequest_headers(Rest, Bin3,
TrUserData);
e_field_ConnectionRequest_headers([], Bin,
_TrUserData) ->
Bin.
e_field_DisconnectRequest_subscriptions([Elem | Rest],
Bin, TrUserData) ->
Bin2 = <<Bin/binary, 18>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_DisconnectRequest_subscriptions(Rest, Bin3,
TrUserData);
e_field_DisconnectRequest_subscriptions([], Bin,
_TrUserData) ->
Bin.
e_mfield_DisconnectRequest_headers(Msg, Bin,
TrUserData) ->
SubBin = 'e_msg_map<string,string>'(Msg, <<>>,
TrUserData),
Bin2 = e_varint(byte_size(SubBin), Bin),
<<Bin2/binary, SubBin/binary>>.
e_field_DisconnectRequest_headers([Elem | Rest], Bin,
TrUserData) ->
Bin2 = <<Bin/binary, 34>>,
Bin3 =
e_mfield_DisconnectRequest_headers('tr_encode_DisconnectRequest.headers[x]'(Elem,
TrUserData),
Bin2, TrUserData),
e_field_DisconnectRequest_headers(Rest, Bin3,
TrUserData);
e_field_DisconnectRequest_headers([], Bin,
_TrUserData) ->
Bin.
'e_msg_map<string,string>'(#'map<string,string>'{key =
F1,
value = F2},
Bin, TrUserData) ->
B1 = begin
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
begin
TrF2 = id(F2, TrUserData),
e_type_string(TrF2, <<B1/binary, 18>>)
end.
e_enum_Status('ERROR', Bin) -> <<Bin/binary, 0>>;
e_enum_Status('SUCCESS', Bin) -> <<Bin/binary, 1>>;
e_enum_Status(V, Bin) -> e_varint(V, Bin).
e_type_bool(true, Bin) -> <<Bin/binary, 1>>;
e_type_bool(false, Bin) -> <<Bin/binary, 0>>;
e_type_bool(1, Bin) -> <<Bin/binary, 1>>;
e_type_bool(0, Bin) -> <<Bin/binary, 0>>.
e_type_string(S, Bin) ->
Utf8 = unicode:characters_to_binary(S),
Bin2 = e_varint(byte_size(Utf8), Bin),
<<Bin2/binary, Utf8/binary>>.
e_varint(N, Bin) when N =< 127 -> <<Bin/binary, N>>;
e_varint(N, Bin) ->
Bin2 = <<Bin/binary, (N band 127 bor 128)>>,
e_varint(N bsr 7, Bin2).
decode_msg(Bin, MsgName) when is_binary(Bin) ->
decode_msg(Bin, MsgName, []).
decode_msg(Bin, MsgName, Opts) when is_binary(Bin) ->
TrUserData = proplists:get_value(user_data, Opts),
case MsgName of
'DisconnectResponse' ->
d_msg_DisconnectResponse(Bin, TrUserData);
'CommandResponse' ->
d_msg_CommandResponse(Bin, TrUserData);
'CommandMessage' ->
d_msg_CommandMessage(Bin, TrUserData);
'ConnectionResponse' ->
d_msg_ConnectionResponse(Bin, TrUserData);
'ConnectionRequest' ->
d_msg_ConnectionRequest(Bin, TrUserData);
'DisconnectRequest' ->
d_msg_DisconnectRequest(Bin, TrUserData)
end.
d_msg_DisconnectResponse(Bin, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Bin, 0, 0,
id(undefined, TrUserData),
TrUserData).
dfp_read_field_def_DisconnectResponse(<<8,
Rest/binary>>,
Z1, Z2, F1, TrUserData) ->
d_field_DisconnectResponse_status(Rest, Z1, Z2, F1,
TrUserData);
dfp_read_field_def_DisconnectResponse(<<>>, 0, 0, F1,
_) ->
#'DisconnectResponse'{status = F1};
dfp_read_field_def_DisconnectResponse(Other, Z1, Z2, F1,
TrUserData) ->
dg_read_field_def_DisconnectResponse(Other, Z1, Z2, F1,
TrUserData).
dg_read_field_def_DisconnectResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_DisconnectResponse(Rest, N + 7,
X bsl N + Acc, F1, TrUserData);
dg_read_field_def_DisconnectResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData) ->
Key = X bsl N + Acc,
case Key of
8 ->
d_field_DisconnectResponse_status(Rest, 0, 0, F1,
TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_DisconnectResponse(Rest, 0, 0, F1,
TrUserData);
1 ->
skip_64_DisconnectResponse(Rest, 0, 0, F1, TrUserData);
2 ->
skip_length_delimited_DisconnectResponse(Rest, 0, 0, F1,
TrUserData);
5 ->
skip_32_DisconnectResponse(Rest, 0, 0, F1, TrUserData)
end
end;
dg_read_field_def_DisconnectResponse(<<>>, 0, 0, F1,
_) ->
#'DisconnectResponse'{status = F1}.
d_field_DisconnectResponse_status(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData)
when N < 57 ->
d_field_DisconnectResponse_status(Rest, N + 7,
X bsl N + Acc, F1, TrUserData);
d_field_DisconnectResponse_status(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, TrUserData) ->
<<Tmp:32/signed-native>> = <<(X bsl N +
Acc):32/unsigned-native>>,
NewFValue = d_enum_Status(Tmp),
dfp_read_field_def_DisconnectResponse(Rest, 0, 0,
NewFValue, TrUserData).
skip_varint_DisconnectResponse(<<1:1, _:7,
Rest/binary>>,
Z1, Z2, F1, TrUserData) ->
skip_varint_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData);
skip_varint_DisconnectResponse(<<0:1, _:7,
Rest/binary>>,
Z1, Z2, F1, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData).
skip_length_delimited_DisconnectResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData)
when N < 57 ->
skip_length_delimited_DisconnectResponse(Rest, N + 7,
X bsl N + Acc, F1, TrUserData);
skip_length_delimited_DisconnectResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_DisconnectResponse(Rest2, 0, 0, F1,
TrUserData).
skip_32_DisconnectResponse(<<_:32, Rest/binary>>, Z1,
Z2, F1, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData).
skip_64_DisconnectResponse(<<_:64, Rest/binary>>, Z1,
Z2, F1, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData).
d_msg_CommandResponse(Bin, TrUserData) ->
dfp_read_field_def_CommandResponse(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
id(undefined, TrUserData),
id([], TrUserData), id([], TrUserData),
TrUserData).
dfp_read_field_def_CommandResponse(<<8, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_status(Rest, Z1, Z2, F1, F2, F3,
F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<16, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_disconnect(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<24, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_stop_streams(Rest, Z1, Z2, F1,
F2, F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<34, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_streams(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<42, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_transmissions(Rest, Z1, Z2, F1,
F2, F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<>>, 0, 0, F1, F2,
F3, F4, F5, TrUserData) ->
#'CommandResponse'{status = F1, disconnect = F2,
stop_streams = F3,
streams = lists_reverse(F4, TrUserData),
transmissions = lists_reverse(F5, TrUserData)};
dfp_read_field_def_CommandResponse(Other, Z1, Z2, F1,
F2, F3, F4, F5, TrUserData) ->
dg_read_field_def_CommandResponse(Other, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
dg_read_field_def_CommandResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_CommandResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
dg_read_field_def_CommandResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Key = X bsl N + Acc,
case Key of
8 ->
d_field_CommandResponse_status(Rest, 0, 0, F1, F2, F3,
F4, F5, TrUserData);
16 ->
d_field_CommandResponse_disconnect(Rest, 0, 0, F1, F2,
F3, F4, F5, TrUserData);
24 ->
d_field_CommandResponse_stop_streams(Rest, 0, 0, F1, F2,
F3, F4, F5, TrUserData);
34 ->
d_field_CommandResponse_streams(Rest, 0, 0, F1, F2, F3,
F4, F5, TrUserData);
42 ->
d_field_CommandResponse_transmissions(Rest, 0, 0, F1,
F2, F3, F4, F5, TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_CommandResponse(Rest, 0, 0, F1, F2, F3, F4,
F5, TrUserData);
1 ->
skip_64_CommandResponse(Rest, 0, 0, F1, F2, F3, F4, F5,
TrUserData);
2 ->
skip_length_delimited_CommandResponse(Rest, 0, 0, F1,
F2, F3, F4, F5,
TrUserData);
5 ->
skip_32_CommandResponse(Rest, 0, 0, F1, F2, F3, F4, F5,
TrUserData)
end
end;
dg_read_field_def_CommandResponse(<<>>, 0, 0, F1, F2,
F3, F4, F5, TrUserData) ->
#'CommandResponse'{status = F1, disconnect = F2,
stop_streams = F3,
streams = lists_reverse(F4, TrUserData),
transmissions = lists_reverse(F5, TrUserData)}.
d_field_CommandResponse_status(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_status(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_status(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, F4, F5, TrUserData) ->
<<Tmp:32/signed-native>> = <<(X bsl N +
Acc):32/unsigned-native>>,
NewFValue = d_enum_Status(Tmp),
dfp_read_field_def_CommandResponse(Rest, 0, 0,
NewFValue, F2, F3, F4, F5, TrUserData).
d_field_CommandResponse_disconnect(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_disconnect(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_disconnect(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, F3, F4, F5, TrUserData) ->
NewFValue = X bsl N + Acc =/= 0,
dfp_read_field_def_CommandResponse(Rest, 0, 0, F1,
NewFValue, F3, F4, F5, TrUserData).
d_field_CommandResponse_stop_streams(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_stop_streams(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_stop_streams(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, _, F4, F5, TrUserData) ->
NewFValue = X bsl N + Acc =/= 0,
dfp_read_field_def_CommandResponse(Rest, 0, 0, F1, F2,
NewFValue, F4, F5, TrUserData).
d_field_CommandResponse_streams(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_streams(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_streams(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandResponse(Rest2, 0, 0, F1, F2,
F3, cons(NewFValue, F4, TrUserData), F5,
TrUserData).
d_field_CommandResponse_transmissions(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_transmissions(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_transmissions(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandResponse(Rest2, 0, 0, F1, F2,
F3, F4, cons(NewFValue, F5, TrUserData),
TrUserData).
skip_varint_CommandResponse(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
skip_varint_CommandResponse(Rest, Z1, Z2, F1, F2, F3,
F4, F5, TrUserData);
skip_varint_CommandResponse(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
dfp_read_field_def_CommandResponse(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
skip_length_delimited_CommandResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
skip_length_delimited_CommandResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
skip_length_delimited_CommandResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_CommandResponse(Rest2, 0, 0, F1, F2,
F3, F4, F5, TrUserData).
skip_32_CommandResponse(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, F5, TrUserData) ->
dfp_read_field_def_CommandResponse(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
skip_64_CommandResponse(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, F5, TrUserData) ->
dfp_read_field_def_CommandResponse(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
d_msg_CommandMessage(Bin, TrUserData) ->
dfp_read_field_def_CommandMessage(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
id(undefined, TrUserData),
id(undefined, TrUserData), TrUserData).
dfp_read_field_def_CommandMessage(<<10, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_command(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
dfp_read_field_def_CommandMessage(<<18, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_identifier(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData);
dfp_read_field_def_CommandMessage(<<26, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_connection_identifiers(Rest, Z1,
Z2, F1, F2, F3, F4,
TrUserData);
dfp_read_field_def_CommandMessage(<<34, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_data(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
dfp_read_field_def_CommandMessage(<<>>, 0, 0, F1, F2,
F3, F4, _) ->
#'CommandMessage'{command = F1, identifier = F2,
connection_identifiers = F3, data = F4};
dfp_read_field_def_CommandMessage(Other, Z1, Z2, F1, F2,
F3, F4, TrUserData) ->
dg_read_field_def_CommandMessage(Other, Z1, Z2, F1, F2,
F3, F4, TrUserData).
dg_read_field_def_CommandMessage(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_CommandMessage(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, TrUserData);
dg_read_field_def_CommandMessage(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
d_field_CommandMessage_command(Rest, 0, 0, F1, F2, F3,
F4, TrUserData);
18 ->
d_field_CommandMessage_identifier(Rest, 0, 0, F1, F2,
F3, F4, TrUserData);
26 ->
d_field_CommandMessage_connection_identifiers(Rest, 0,
0, F1, F2, F3, F4,
TrUserData);
34 ->
d_field_CommandMessage_data(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_CommandMessage(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
1 ->
skip_64_CommandMessage(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
2 ->
skip_length_delimited_CommandMessage(Rest, 0, 0, F1, F2,
F3, F4, TrUserData);
5 ->
skip_32_CommandMessage(Rest, 0, 0, F1, F2, F3, F4,
TrUserData)
end
end;
dg_read_field_def_CommandMessage(<<>>, 0, 0, F1, F2, F3,
F4, _) ->
#'CommandMessage'{command = F1, identifier = F2,
connection_identifiers = F3, data = F4}.
d_field_CommandMessage_command(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_CommandMessage_command(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, TrUserData);
d_field_CommandMessage_command(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0,
NewFValue, F2, F3, F4, TrUserData).
d_field_CommandMessage_identifier(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_CommandMessage_identifier(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_CommandMessage_identifier(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1,
NewFValue, F3, F4, TrUserData).
d_field_CommandMessage_connection_identifiers(<<1:1,
X:7, Rest/binary>>,
N, Acc, F1, F2, F3, F4,
TrUserData)
when N < 57 ->
d_field_CommandMessage_connection_identifiers(Rest,
N + 7, X bsl N + Acc, F1, F2,
F3, F4, TrUserData);
d_field_CommandMessage_connection_identifiers(<<0:1,
X:7, Rest/binary>>,
N, Acc, F1, F2, _, F4,
TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1, F2,
NewFValue, F4, TrUserData).
d_field_CommandMessage_data(<<1:1, X:7, Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_CommandMessage_data(Rest, N + 7, X bsl N + Acc,
F1, F2, F3, F4, TrUserData);
d_field_CommandMessage_data(<<0:1, X:7, Rest/binary>>,
N, Acc, F1, F2, F3, _, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1, F2,
F3, NewFValue, TrUserData).
skip_varint_CommandMessage(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
skip_varint_CommandMessage(Rest, Z1, Z2, F1, F2, F3, F4,
TrUserData);
skip_varint_CommandMessage(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_CommandMessage(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData).
skip_length_delimited_CommandMessage(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
skip_length_delimited_CommandMessage(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
skip_length_delimited_CommandMessage(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1, F2,
F3, F4, TrUserData).
skip_32_CommandMessage(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_CommandMessage(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData).
skip_64_CommandMessage(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_CommandMessage(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData).
d_msg_ConnectionResponse(Bin, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
id([], TrUserData), TrUserData).
dfp_read_field_def_ConnectionResponse(<<8,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
d_field_ConnectionResponse_status(Rest, Z1, Z2, F1, F2,
F3, TrUserData);
dfp_read_field_def_ConnectionResponse(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
d_field_ConnectionResponse_identifiers(Rest, Z1, Z2, F1,
F2, F3, TrUserData);
dfp_read_field_def_ConnectionResponse(<<26,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
d_field_ConnectionResponse_transmissions(Rest, Z1, Z2,
F1, F2, F3, TrUserData);
dfp_read_field_def_ConnectionResponse(<<>>, 0, 0, F1,
F2, F3, TrUserData) ->
#'ConnectionResponse'{status = F1, identifiers = F2,
transmissions = lists_reverse(F3, TrUserData)};
dfp_read_field_def_ConnectionResponse(Other, Z1, Z2, F1,
F2, F3, TrUserData) ->
dg_read_field_def_ConnectionResponse(Other, Z1, Z2, F1,
F2, F3, TrUserData).
dg_read_field_def_ConnectionResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_ConnectionResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, TrUserData);
dg_read_field_def_ConnectionResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData) ->
Key = X bsl N + Acc,
case Key of
8 ->
d_field_ConnectionResponse_status(Rest, 0, 0, F1, F2,
F3, TrUserData);
18 ->
d_field_ConnectionResponse_identifiers(Rest, 0, 0, F1,
F2, F3, TrUserData);
26 ->
d_field_ConnectionResponse_transmissions(Rest, 0, 0, F1,
F2, F3, TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_ConnectionResponse(Rest, 0, 0, F1, F2, F3,
TrUserData);
1 ->
skip_64_ConnectionResponse(Rest, 0, 0, F1, F2, F3,
TrUserData);
2 ->
skip_length_delimited_ConnectionResponse(Rest, 0, 0, F1,
F2, F3, TrUserData);
5 ->
skip_32_ConnectionResponse(Rest, 0, 0, F1, F2, F3,
TrUserData)
end
end;
dg_read_field_def_ConnectionResponse(<<>>, 0, 0, F1, F2,
F3, TrUserData) ->
#'ConnectionResponse'{status = F1, identifiers = F2,
transmissions = lists_reverse(F3, TrUserData)}.
d_field_ConnectionResponse_status(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
d_field_ConnectionResponse_status(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, TrUserData);
d_field_ConnectionResponse_status(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, TrUserData) ->
<<Tmp:32/signed-native>> = <<(X bsl N +
Acc):32/unsigned-native>>,
NewFValue = d_enum_Status(Tmp),
dfp_read_field_def_ConnectionResponse(Rest, 0, 0,
NewFValue, F2, F3, TrUserData).
d_field_ConnectionResponse_identifiers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
d_field_ConnectionResponse_identifiers(Rest, N + 7,
X bsl N + Acc, F1, F2, F3,
TrUserData);
d_field_ConnectionResponse_identifiers(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, F3, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_ConnectionResponse(Rest2, 0, 0, F1,
NewFValue, F3, TrUserData).
d_field_ConnectionResponse_transmissions(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
d_field_ConnectionResponse_transmissions(Rest, N + 7,
X bsl N + Acc, F1, F2, F3,
TrUserData);
d_field_ConnectionResponse_transmissions(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_ConnectionResponse(Rest2, 0, 0, F1,
F2, cons(NewFValue, F3, TrUserData),
TrUserData).
skip_varint_ConnectionResponse(<<1:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
skip_varint_ConnectionResponse(Rest, Z1, Z2, F1, F2, F3,
TrUserData);
skip_varint_ConnectionResponse(<<0:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Rest, Z1, Z2, F1,
F2, F3, TrUserData).
skip_length_delimited_ConnectionResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
skip_length_delimited_ConnectionResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3,
TrUserData);
skip_length_delimited_ConnectionResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_ConnectionResponse(Rest2, 0, 0, F1,
F2, F3, TrUserData).
skip_32_ConnectionResponse(<<_:32, Rest/binary>>, Z1,
Z2, F1, F2, F3, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Rest, Z1, Z2, F1,
F2, F3, TrUserData).
skip_64_ConnectionResponse(<<_:64, Rest/binary>>, Z1,
Z2, F1, F2, F3, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Rest, Z1, Z2, F1,
F2, F3, TrUserData).
d_msg_ConnectionRequest(Bin, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Bin, 0, 0,
id(undefined, TrUserData),
'tr_decode_init_default_ConnectionRequest.headers'([],
TrUserData),
TrUserData).
dfp_read_field_def_ConnectionRequest(<<10,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
d_field_ConnectionRequest_path(Rest, Z1, Z2, F1, F2,
TrUserData);
dfp_read_field_def_ConnectionRequest(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
d_field_ConnectionRequest_headers(Rest, Z1, Z2, F1, F2,
TrUserData);
dfp_read_field_def_ConnectionRequest(<<>>, 0, 0, F1, F2,
TrUserData) ->
#'ConnectionRequest'{path = F1,
headers =
'tr_decode_repeated_finalize_ConnectionRequest.headers'(F2,
TrUserData)};
dfp_read_field_def_ConnectionRequest(Other, Z1, Z2, F1,
F2, TrUserData) ->
dg_read_field_def_ConnectionRequest(Other, Z1, Z2, F1,
F2, TrUserData).
dg_read_field_def_ConnectionRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_ConnectionRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
dg_read_field_def_ConnectionRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
d_field_ConnectionRequest_path(Rest, 0, 0, F1, F2,
TrUserData);
18 ->
d_field_ConnectionRequest_headers(Rest, 0, 0, F1, F2,
TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_ConnectionRequest(Rest, 0, 0, F1, F2,
TrUserData);
1 ->
skip_64_ConnectionRequest(Rest, 0, 0, F1, F2,
TrUserData);
2 ->
skip_length_delimited_ConnectionRequest(Rest, 0, 0, F1,
F2, TrUserData);
5 ->
skip_32_ConnectionRequest(Rest, 0, 0, F1, F2,
TrUserData)
end
end;
dg_read_field_def_ConnectionRequest(<<>>, 0, 0, F1, F2,
TrUserData) ->
#'ConnectionRequest'{path = F1,
headers =
'tr_decode_repeated_finalize_ConnectionRequest.headers'(F2,
TrUserData)}.
d_field_ConnectionRequest_path(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
d_field_ConnectionRequest_path(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
d_field_ConnectionRequest_path(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_ConnectionRequest(Rest2, 0, 0,
NewFValue, F2, TrUserData).
d_field_ConnectionRequest_headers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
d_field_ConnectionRequest_headers(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
d_field_ConnectionRequest_headers(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Len = X bsl N + Acc,
<<Bs:Len/binary, Rest2/binary>> = Rest,
NewFValue = id('d_msg_map<string,string>'(Bs,
TrUserData),
TrUserData),
dfp_read_field_def_ConnectionRequest(Rest2, 0, 0, F1,
'tr_decode_repeated_add_elem_ConnectionRequest.headers'(NewFValue,
F2,
TrUserData),
TrUserData).
skip_varint_ConnectionRequest(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
skip_varint_ConnectionRequest(Rest, Z1, Z2, F1, F2,
TrUserData);
skip_varint_ConnectionRequest(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Rest, Z1, Z2, F1,
F2, TrUserData).
skip_length_delimited_ConnectionRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
skip_length_delimited_ConnectionRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
skip_length_delimited_ConnectionRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_ConnectionRequest(Rest2, 0, 0, F1,
F2, TrUserData).
skip_32_ConnectionRequest(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Rest, Z1, Z2, F1,
F2, TrUserData).
skip_64_ConnectionRequest(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Rest, Z1, Z2, F1,
F2, TrUserData).
d_msg_DisconnectRequest(Bin, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Bin, 0, 0,
id(undefined, TrUserData),
id([], TrUserData),
id(undefined, TrUserData),
'tr_decode_init_default_DisconnectRequest.headers'([],
TrUserData),
TrUserData).
dfp_read_field_def_DisconnectRequest(<<10,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_identifiers(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_subscriptions(Rest, Z1, Z2,
F1, F2, F3, F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<26,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_path(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<34,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_headers(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<>>, 0, 0, F1, F2,
F3, F4, TrUserData) ->
#'DisconnectRequest'{identifiers = F1,
subscriptions = lists_reverse(F2, TrUserData),
path = F3,
headers =
'tr_decode_repeated_finalize_DisconnectRequest.headers'(F4,
TrUserData)};
dfp_read_field_def_DisconnectRequest(Other, Z1, Z2, F1,
F2, F3, F4, TrUserData) ->
dg_read_field_def_DisconnectRequest(Other, Z1, Z2, F1,
F2, F3, F4, TrUserData).
dg_read_field_def_DisconnectRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_DisconnectRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
dg_read_field_def_DisconnectRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
d_field_DisconnectRequest_identifiers(Rest, 0, 0, F1,
F2, F3, F4, TrUserData);
18 ->
d_field_DisconnectRequest_subscriptions(Rest, 0, 0, F1,
F2, F3, F4, TrUserData);
26 ->
d_field_DisconnectRequest_path(Rest, 0, 0, F1, F2, F3,
F4, TrUserData);
34 ->
d_field_DisconnectRequest_headers(Rest, 0, 0, F1, F2,
F3, F4, TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_DisconnectRequest(Rest, 0, 0, F1, F2, F3,
F4, TrUserData);
1 ->
skip_64_DisconnectRequest(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
2 ->
skip_length_delimited_DisconnectRequest(Rest, 0, 0, F1,
F2, F3, F4, TrUserData);
5 ->
skip_32_DisconnectRequest(Rest, 0, 0, F1, F2, F3, F4,
TrUserData)
end
end;
dg_read_field_def_DisconnectRequest(<<>>, 0, 0, F1, F2,
F3, F4, TrUserData) ->
#'DisconnectRequest'{identifiers = F1,
subscriptions = lists_reverse(F2, TrUserData),
path = F3,
headers =
'tr_decode_repeated_finalize_DisconnectRequest.headers'(F4,
TrUserData)}.
d_field_DisconnectRequest_identifiers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_identifiers(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_DisconnectRequest_identifiers(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0,
NewFValue, F2, F3, F4, TrUserData).
d_field_DisconnectRequest_subscriptions(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_subscriptions(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_DisconnectRequest_subscriptions(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
cons(NewFValue, F2, TrUserData), F3,
F4, TrUserData).
d_field_DisconnectRequest_path(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_path(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, TrUserData);
d_field_DisconnectRequest_path(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, _, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
F2, NewFValue, F4, TrUserData).
d_field_DisconnectRequest_headers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_headers(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_DisconnectRequest_headers(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Bs:Len/binary, Rest2/binary>> = Rest,
NewFValue = id('d_msg_map<string,string>'(Bs,
TrUserData),
TrUserData),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
F2, F3,
'tr_decode_repeated_add_elem_DisconnectRequest.headers'(NewFValue,
F4,
TrUserData),
TrUserData).
skip_varint_DisconnectRequest(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
skip_varint_DisconnectRequest(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
skip_varint_DisconnectRequest(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData).
skip_length_delimited_DisconnectRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
skip_length_delimited_DisconnectRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
skip_length_delimited_DisconnectRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
F2, F3, F4, TrUserData).
skip_32_DisconnectRequest(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData).
skip_64_DisconnectRequest(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData).
'd_msg_map<string,string>'(Bin, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
TrUserData).
'dfp_read_field_def_map<string,string>'(<<10,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'd_field_map<string,string>_key'(Rest, Z1, Z2, F1, F2,
TrUserData);
'dfp_read_field_def_map<string,string>'(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'd_field_map<string,string>_value'(Rest, Z1, Z2, F1, F2,
TrUserData);
'dfp_read_field_def_map<string,string>'(<<>>, 0, 0, F1,
F2, _) ->
#'map<string,string>'{key = F1, value = F2};
'dfp_read_field_def_map<string,string>'(Other, Z1, Z2,
F1, F2, TrUserData) ->
'dg_read_field_def_map<string,string>'(Other, Z1, Z2,
F1, F2, TrUserData).
'dg_read_field_def_map<string,string>'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 32 - 7 ->
'dg_read_field_def_map<string,string>'(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
'dg_read_field_def_map<string,string>'(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
'd_field_map<string,string>_key'(Rest, 0, 0, F1, F2,
TrUserData);
18 ->
'd_field_map<string,string>_value'(Rest, 0, 0, F1, F2,
TrUserData);
_ ->
case Key band 7 of
0 ->
'skip_varint_map<string,string>'(Rest, 0, 0, F1, F2,
TrUserData);
1 ->
'skip_64_map<string,string>'(Rest, 0, 0, F1, F2,
TrUserData);
2 ->
'skip_length_delimited_map<string,string>'(Rest, 0, 0,
F1, F2, TrUserData);
5 ->
'skip_32_map<string,string>'(Rest, 0, 0, F1, F2,
TrUserData)
end
end;
'dg_read_field_def_map<string,string>'(<<>>, 0, 0, F1,
F2, _) ->
#'map<string,string>'{key = F1, value = F2}.
'd_field_map<string,string>_key'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
'd_field_map<string,string>_key'(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
'd_field_map<string,string>_key'(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
'dfp_read_field_def_map<string,string>'(Rest2, 0, 0,
NewFValue, F2, TrUserData).
'd_field_map<string,string>_value'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
'd_field_map<string,string>_value'(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
'd_field_map<string,string>_value'(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
'dfp_read_field_def_map<string,string>'(Rest2, 0, 0, F1,
NewFValue, TrUserData).
'skip_varint_map<string,string>'(<<1:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'skip_varint_map<string,string>'(Rest, Z1, Z2, F1, F2,
TrUserData);
'skip_varint_map<string,string>'(<<0:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Rest, Z1, Z2,
F1, F2, TrUserData).
'skip_length_delimited_map<string,string>'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
'skip_length_delimited_map<string,string>'(Rest, N + 7,
X bsl N + Acc, F1, F2,
TrUserData);
'skip_length_delimited_map<string,string>'(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
'dfp_read_field_def_map<string,string>'(Rest2, 0, 0, F1,
F2, TrUserData).
'skip_32_map<string,string>'(<<_:32, Rest/binary>>, Z1,
Z2, F1, F2, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Rest, Z1, Z2,
F1, F2, TrUserData).
'skip_64_map<string,string>'(<<_:64, Rest/binary>>, Z1,
Z2, F1, F2, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Rest, Z1, Z2,
F1, F2, TrUserData).
d_enum_Status(0) -> 'ERROR';
d_enum_Status(1) -> 'SUCCESS';
d_enum_Status(V) -> V.
merge_msgs(Prev, New) -> merge_msgs(Prev, New, []).
merge_msgs(Prev, New, Opts)
when element(1, Prev) =:= element(1, New) ->
TrUserData = proplists:get_value(user_data, Opts),
case Prev of
#'DisconnectResponse'{} ->
merge_msg_DisconnectResponse(Prev, New, TrUserData);
#'CommandResponse'{} ->
merge_msg_CommandResponse(Prev, New, TrUserData);
#'CommandMessage'{} ->
merge_msg_CommandMessage(Prev, New, TrUserData);
#'ConnectionResponse'{} ->
merge_msg_ConnectionResponse(Prev, New, TrUserData);
#'ConnectionRequest'{} ->
merge_msg_ConnectionRequest(Prev, New, TrUserData);
#'DisconnectRequest'{} ->
merge_msg_DisconnectRequest(Prev, New, TrUserData)
end.
merge_msg_DisconnectResponse(#'DisconnectResponse'{status
= PFstatus},
#'DisconnectResponse'{status = NFstatus}, _) ->
#'DisconnectResponse'{status =
if NFstatus =:= undefined -> PFstatus;
true -> NFstatus
end}.
merge_msg_CommandResponse(#'CommandResponse'{status =
PFstatus,
disconnect = PFdisconnect,
stop_streams = PFstop_streams,
streams = PFstreams,
transmissions = PFtransmissions},
#'CommandResponse'{status = NFstatus,
disconnect = NFdisconnect,
stop_streams = NFstop_streams,
streams = NFstreams,
transmissions = NFtransmissions},
TrUserData) ->
#'CommandResponse'{status =
if NFstatus =:= undefined -> PFstatus;
true -> NFstatus
end,
disconnect =
if NFdisconnect =:= undefined -> PFdisconnect;
true -> NFdisconnect
end,
stop_streams =
if NFstop_streams =:= undefined -> PFstop_streams;
true -> NFstop_streams
end,
streams = 'erlang_++'(PFstreams, NFstreams, TrUserData),
transmissions =
'erlang_++'(PFtransmissions, NFtransmissions,
TrUserData)}.
merge_msg_CommandMessage(#'CommandMessage'{command =
PFcommand,
identifier = PFidentifier,
connection_identifiers =
PFconnection_identifiers,
data = PFdata},
#'CommandMessage'{command = NFcommand,
identifier = NFidentifier,
connection_identifiers =
NFconnection_identifiers,
data = NFdata},
_) ->
#'CommandMessage'{command =
if NFcommand =:= undefined -> PFcommand;
true -> NFcommand
end,
identifier =
if NFidentifier =:= undefined -> PFidentifier;
true -> NFidentifier
end,
connection_identifiers =
if NFconnection_identifiers =:= undefined ->
PFconnection_identifiers;
true -> NFconnection_identifiers
end,
data =
if NFdata =:= undefined -> PFdata;
true -> NFdata
end}.
merge_msg_ConnectionResponse(#'ConnectionResponse'{status
= PFstatus,
identifiers = PFidentifiers,
transmissions =
PFtransmissions},
#'ConnectionResponse'{status = NFstatus,
identifiers = NFidentifiers,
transmissions =
NFtransmissions},
TrUserData) ->
#'ConnectionResponse'{status =
if NFstatus =:= undefined -> PFstatus;
true -> NFstatus
end,
identifiers =
if NFidentifiers =:= undefined -> PFidentifiers;
true -> NFidentifiers
end,
transmissions =
'erlang_++'(PFtransmissions, NFtransmissions,
TrUserData)}.
merge_msg_ConnectionRequest(#'ConnectionRequest'{path =
PFpath,
headers = PFheaders},
#'ConnectionRequest'{path = NFpath,
headers = NFheaders},
TrUserData) ->
#'ConnectionRequest'{path =
if NFpath =:= undefined -> PFpath;
true -> NFpath
end,
headers =
'tr_merge_ConnectionRequest.headers'(PFheaders,
NFheaders,
TrUserData)}.
merge_msg_DisconnectRequest(#'DisconnectRequest'{identifiers
= PFidentifiers,
subscriptions =
PFsubscriptions,
path = PFpath,
headers = PFheaders},
#'DisconnectRequest'{identifiers = NFidentifiers,
subscriptions =
NFsubscriptions,
path = NFpath,
headers = NFheaders},
TrUserData) ->
#'DisconnectRequest'{identifiers =
if NFidentifiers =:= undefined -> PFidentifiers;
true -> NFidentifiers
end,
subscriptions =
'erlang_++'(PFsubscriptions, NFsubscriptions,
TrUserData),
path =
if NFpath =:= undefined -> PFpath;
true -> NFpath
end,
headers =
'tr_merge_DisconnectRequest.headers'(PFheaders,
NFheaders,
TrUserData)}.
verify_msg(Msg) -> verify_msg(Msg, []).
verify_msg(Msg, Opts) ->
TrUserData = proplists:get_value(user_data, Opts),
case Msg of
#'DisconnectResponse'{} ->
v_msg_DisconnectResponse(Msg, ['DisconnectResponse'],
TrUserData);
#'CommandResponse'{} ->
v_msg_CommandResponse(Msg, ['CommandResponse'],
TrUserData);
#'CommandMessage'{} ->
v_msg_CommandMessage(Msg, ['CommandMessage'],
TrUserData);
#'ConnectionResponse'{} ->
v_msg_ConnectionResponse(Msg, ['ConnectionResponse'],
TrUserData);
#'ConnectionRequest'{} ->
v_msg_ConnectionRequest(Msg, ['ConnectionRequest'],
TrUserData);
#'DisconnectRequest'{} ->
v_msg_DisconnectRequest(Msg, ['DisconnectRequest'],
TrUserData);
_ -> mk_type_error(not_a_known_message, Msg, [])
end.
-dialyzer({nowarn_function,v_msg_DisconnectResponse/3}).
v_msg_DisconnectResponse(#'DisconnectResponse'{status =
F1},
Path, _) ->
if F1 == undefined -> ok;
true -> v_enum_Status(F1, [status | Path])
end,
ok.
-dialyzer({nowarn_function,v_msg_CommandResponse/3}).
v_msg_CommandResponse(#'CommandResponse'{status = F1,
disconnect = F2, stop_streams = F3,
streams = F4, transmissions = F5},
Path, _) ->
if F1 == undefined -> ok;
true -> v_enum_Status(F1, [status | Path])
end,
if F2 == undefined -> ok;
true -> v_type_bool(F2, [disconnect | Path])
end,
if F3 == undefined -> ok;
true -> v_type_bool(F3, [stop_streams | Path])
end,
if is_list(F4) ->
_ = [v_type_string(Elem, [streams | Path])
|| Elem <- F4],
ok;
true ->
mk_type_error({invalid_list_of, string}, F4, Path)
end,
if is_list(F5) ->
_ = [v_type_string(Elem, [transmissions | Path])
|| Elem <- F5],
ok;
true ->
mk_type_error({invalid_list_of, string}, F5, Path)
end,
ok.
-dialyzer({nowarn_function,v_msg_CommandMessage/3}).
v_msg_CommandMessage(#'CommandMessage'{command = F1,
identifier = F2,
connection_identifiers = F3, data = F4},
Path, _) ->
if F1 == undefined -> ok;
true -> v_type_string(F1, [command | Path])
end,
if F2 == undefined -> ok;
true -> v_type_string(F2, [identifier | Path])
end,
if F3 == undefined -> ok;
true ->
v_type_string(F3, [connection_identifiers | Path])
end,
if F4 == undefined -> ok;
true -> v_type_string(F4, [data | Path])
end,
ok.
-dialyzer({nowarn_function,v_msg_ConnectionResponse/3}).
v_msg_ConnectionResponse(#'ConnectionResponse'{status =
F1,
identifiers = F2,
transmissions = F3},
Path, _) ->
if F1 == undefined -> ok;
true -> v_enum_Status(F1, [status | Path])
end,
if F2 == undefined -> ok;
true -> v_type_string(F2, [identifiers | Path])
end,
if is_list(F3) ->
_ = [v_type_string(Elem, [transmissions | Path])
|| Elem <- F3],
ok;
true ->
mk_type_error({invalid_list_of, string}, F3, Path)
end,
ok.
-dialyzer({nowarn_function,v_msg_ConnectionRequest/3}).
v_msg_ConnectionRequest(#'ConnectionRequest'{path = F1,
headers = F2},
Path, TrUserData) ->
if F1 == undefined -> ok;
true -> v_type_string(F1, [path | Path])
end,
'v_map<string,string>'(F2, [headers | Path],
TrUserData),
ok.
-dialyzer({nowarn_function,v_msg_DisconnectRequest/3}).
v_msg_DisconnectRequest(#'DisconnectRequest'{identifiers
= F1,
subscriptions = F2, path = F3,
headers = F4},
Path, TrUserData) ->
if F1 == undefined -> ok;
true -> v_type_string(F1, [identifiers | Path])
end,
if is_list(F2) ->
_ = [v_type_string(Elem, [subscriptions | Path])
|| Elem <- F2],
ok;
true ->
mk_type_error({invalid_list_of, string}, F2, Path)
end,
if F3 == undefined -> ok;
true -> v_type_string(F3, [path | Path])
end,
'v_map<string,string>'(F4, [headers | Path],
TrUserData),
ok.
-dialyzer({nowarn_function,v_enum_Status/2}).
v_enum_Status('ERROR', _Path) -> ok;
v_enum_Status('SUCCESS', _Path) -> ok;
v_enum_Status(V, Path) when is_integer(V) ->
v_type_sint32(V, Path);
v_enum_Status(X, Path) ->
mk_type_error({invalid_enum, 'Status'}, X, Path).
-dialyzer({nowarn_function,v_type_sint32/2}).
v_type_sint32(N, _Path)
when -2147483648 =< N, N =< 2147483647 ->
ok;
v_type_sint32(N, Path) when is_integer(N) ->
mk_type_error({value_out_of_range, sint32, signed, 32},
N, Path);
v_type_sint32(X, Path) ->
mk_type_error({bad_integer, sint32, signed, 32}, X,
Path).
-dialyzer({nowarn_function,v_type_bool/2}).
v_type_bool(false, _Path) -> ok;
v_type_bool(true, _Path) -> ok;
v_type_bool(0, _Path) -> ok;
v_type_bool(1, _Path) -> ok;
v_type_bool(X, Path) ->
mk_type_error(bad_boolean_value, X, Path).
-dialyzer({nowarn_function,v_type_string/2}).
v_type_string(S, Path) when is_list(S); is_binary(S) ->
try unicode:characters_to_binary(S) of
B when is_binary(B) -> ok;
{error, _, _} ->
mk_type_error(bad_unicode_string, S, Path)
catch
error:badarg ->
mk_type_error(bad_unicode_string, S, Path)
end;
v_type_string(X, Path) ->
mk_type_error(bad_unicode_string, X, Path).
-dialyzer({nowarn_function,'v_map<string,string>'/3}).
'v_map<string,string>'(KVs, Path, _)
when is_list(KVs) ->
[case X of
{Key, Value} ->
v_type_string(Key, [key | Path]),
v_type_string(Value, [value | Path]);
_ -> mk_type_error(invalid_key_value_tuple, X, Path)
end
|| X <- KVs],
ok;
'v_map<string,string>'(X, Path, _TrUserData) ->
mk_type_error(invalid_list_of_key_value_tuples, X,
Path).
-spec mk_type_error(_, _, list()) -> no_return().
mk_type_error(Error, ValueSeen, Path) ->
Path2 = prettify_path(Path),
erlang:error({gpb_type_error,
{Error, [{value, ValueSeen}, {path, Path2}]}}).
prettify_path([]) -> top_level;
prettify_path(PathR) ->
list_to_atom(string:join(lists:map(fun atom_to_list/1,
lists:reverse(PathR)),
".")).
-compile({nowarn_unused_function,id/2}).
-compile({inline,id/2}).
id(X, _TrUserData) -> X.
-compile({nowarn_unused_function,cons/3}).
-compile({inline,cons/3}).
cons(Elem, Acc, _TrUserData) -> [Elem | Acc].
-compile({nowarn_unused_function,lists_reverse/2}).
-compile({inline,lists_reverse/2}).
'lists_reverse'(L, _TrUserData) -> lists:reverse(L).
-compile({nowarn_unused_function,'erlang_++'/3}).
-compile({inline,'erlang_++'/3}).
'erlang_++'(A, B, _TrUserData) -> A ++ B.
-compile({inline,'tr_decode_init_default_ConnectionRequest.headers'/2}).
'tr_decode_init_default_ConnectionRequest.headers'(_,
_) ->
mt_empty_map_r().
-compile({inline,'tr_decode_repeated_add_elem_ConnectionRequest.headers'/3}).
'tr_decode_repeated_add_elem_ConnectionRequest.headers'(Elem,
L, _) ->
mt_add_item_r(Elem, L).
-compile({inline,'tr_decode_repeated_finalize_ConnectionRequest.headers'/2}).
'tr_decode_repeated_finalize_ConnectionRequest.headers'(L,
_) ->
mt_finalize_items_r(L).
-compile({inline,'tr_merge_ConnectionRequest.headers'/3}).
'tr_merge_ConnectionRequest.headers'(X1, X2, _) ->
mt_merge_maptuples_r(X1, X2).
-compile({inline,'tr_decode_init_default_DisconnectRequest.headers'/2}).
'tr_decode_init_default_DisconnectRequest.headers'(_,
_) ->
mt_empty_map_r().
-compile({inline,'tr_decode_repeated_add_elem_DisconnectRequest.headers'/3}).
'tr_decode_repeated_add_elem_DisconnectRequest.headers'(Elem,
L, _) ->
mt_add_item_r(Elem, L).
-compile({inline,'tr_decode_repeated_finalize_DisconnectRequest.headers'/2}).
'tr_decode_repeated_finalize_DisconnectRequest.headers'(L,
_) ->
mt_finalize_items_r(L).
-compile({inline,'tr_merge_DisconnectRequest.headers'/3}).
'tr_merge_DisconnectRequest.headers'(X1, X2, _) ->
mt_merge_maptuples_r(X1, X2).
-compile({inline,'tr_encode_ConnectionRequest.headers[x]'/2}).
'tr_encode_ConnectionRequest.headers[x]'(X, _) ->
mt_maptuple_to_pseudomsg_r(X, 'map<string,string>').
-compile({inline,'tr_encode_DisconnectRequest.headers[x]'/2}).
'tr_encode_DisconnectRequest.headers[x]'(X, _) ->
mt_maptuple_to_pseudomsg_r(X, 'map<string,string>').
-compile({inline,mt_maptuple_to_pseudomsg_r/2}).
mt_maptuple_to_pseudomsg_r({K, V}, RName) ->
{RName, K, V}.
-compile({inline,mt_empty_map_r/0}).
mt_empty_map_r() -> dict:new().
-compile({inline,mt_add_item_r/2}).
mt_add_item_r({_RName, K, V}, D) -> dict:store(K, V, D).
-compile({inline,mt_finalize_items_r/1}).
mt_finalize_items_r(D) -> dict:to_list(D).
-compile({inline,mt_merge_maptuples_r/2}).
mt_merge_maptuples_r(L1, L2) ->
dict:to_list(dict:merge(fun (_Key, _V1, V2) -> V2 end,
dict:from_list(L1), dict:from_list(L2))).
get_msg_defs() ->
[{{enum, 'Status'}, [{'ERROR', 0}, {'SUCCESS', 1}]},
{{msg, 'DisconnectResponse'},
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []}]},
{{msg, 'CommandResponse'},
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = disconnect, fnum = 2, rnum = 3,
type = bool, occurrence = optional, opts = []},
#field{name = stop_streams, fnum = 3, rnum = 4,
type = bool, occurrence = optional, opts = []},
#field{name = streams, fnum = 4, rnum = 5,
type = string, occurrence = repeated, opts = []},
#field{name = transmissions, fnum = 5, rnum = 6,
type = string, occurrence = repeated, opts = []}]},
{{msg, 'CommandMessage'},
[#field{name = command, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = identifier, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = connection_identifiers, fnum = 3,
rnum = 4, type = string, occurrence = optional,
opts = []},
#field{name = data, fnum = 4, rnum = 5, type = string,
occurrence = optional, opts = []}]},
{{msg, 'ConnectionResponse'},
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = identifiers, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = transmissions, fnum = 3, rnum = 4,
type = string, occurrence = repeated, opts = []}]},
{{msg, 'ConnectionRequest'},
[#field{name = path, fnum = 1, rnum = 2, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 2, rnum = 3,
type = {map, string, string}, occurrence = repeated,
opts = []}]},
{{msg, 'DisconnectRequest'},
[#field{name = identifiers, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = subscriptions, fnum = 2, rnum = 3,
type = string, occurrence = repeated, opts = []},
#field{name = path, fnum = 3, rnum = 4, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 4, rnum = 5,
type = {map, string, string}, occurrence = repeated,
opts = []}]}].
get_msg_names() ->
['DisconnectResponse', 'CommandResponse',
'CommandMessage', 'ConnectionResponse',
'ConnectionRequest', 'DisconnectRequest'].
get_enum_names() -> ['Status'].
fetch_msg_def(MsgName) ->
case find_msg_def(MsgName) of
Fs when is_list(Fs) -> Fs;
error -> erlang:error({no_such_msg, MsgName})
end.
fetch_enum_def(EnumName) ->
case find_enum_def(EnumName) of
Es when is_list(Es) -> Es;
error -> erlang:error({no_such_enum, EnumName})
end.
find_msg_def('DisconnectResponse') ->
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []}];
find_msg_def('CommandResponse') ->
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = disconnect, fnum = 2, rnum = 3,
type = bool, occurrence = optional, opts = []},
#field{name = stop_streams, fnum = 3, rnum = 4,
type = bool, occurrence = optional, opts = []},
#field{name = streams, fnum = 4, rnum = 5,
type = string, occurrence = repeated, opts = []},
#field{name = transmissions, fnum = 5, rnum = 6,
type = string, occurrence = repeated, opts = []}];
find_msg_def('CommandMessage') ->
[#field{name = command, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = identifier, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = connection_identifiers, fnum = 3,
rnum = 4, type = string, occurrence = optional,
opts = []},
#field{name = data, fnum = 4, rnum = 5, type = string,
occurrence = optional, opts = []}];
find_msg_def('ConnectionResponse') ->
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = identifiers, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = transmissions, fnum = 3, rnum = 4,
type = string, occurrence = repeated, opts = []}];
find_msg_def('ConnectionRequest') ->
[#field{name = path, fnum = 1, rnum = 2, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 2, rnum = 3,
type = {map, string, string}, occurrence = repeated,
opts = []}];
find_msg_def('DisconnectRequest') ->
[#field{name = identifiers, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = subscriptions, fnum = 2, rnum = 3,
type = string, occurrence = repeated, opts = []},
#field{name = path, fnum = 3, rnum = 4, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 4, rnum = 5,
type = {map, string, string}, occurrence = repeated,
opts = []}];
find_msg_def(_) -> error.
find_enum_def('Status') ->
[{'ERROR', 0}, {'SUCCESS', 1}];
find_enum_def(_) -> error.
enum_symbol_by_value('Status', Value) ->
enum_symbol_by_value_Status(Value).
enum_value_by_symbol('Status', Sym) ->
enum_value_by_symbol_Status(Sym).
enum_symbol_by_value_Status(0) -> 'ERROR';
enum_symbol_by_value_Status(1) -> 'SUCCESS'.
enum_value_by_symbol_Status('ERROR') -> 0;
enum_value_by_symbol_Status('SUCCESS') -> 1.
get_service_names() -> [].
get_service_def(_) -> error.
get_rpc_names(_) -> error.
find_rpc_def(_, _) -> error.
-spec fetch_rpc_def(_, _) -> no_return().
fetch_rpc_def(ServiceName, RpcName) ->
erlang:error({no_such_rpc, ServiceName, RpcName}).
get_package_name() -> anycable.
gpb_version_as_string() ->
"3.24.4".
gpb_version_as_list() ->
[3,24,4].
| null | https://raw.githubusercontent.com/anycable/erlycable/6f52a5b16c080bfa0feeb1f4f9e45fc552af71b5/src/protos/anycable.erl | erlang | Automatically generated, do not edit | -*- coding : utf-8 -*-
Generated by gpb_compile version 3.24.4
-module(anycable).
-export([encode_msg/1, encode_msg/2]).
-export([decode_msg/2, decode_msg/3]).
-export([merge_msgs/2, merge_msgs/3]).
-export([verify_msg/1, verify_msg/2]).
-export([get_msg_defs/0]).
-export([get_msg_names/0]).
-export([get_enum_names/0]).
-export([find_msg_def/1, fetch_msg_def/1]).
-export([find_enum_def/1, fetch_enum_def/1]).
-export([enum_symbol_by_value/2, enum_value_by_symbol/2]).
-export([enum_symbol_by_value_Status/1, enum_value_by_symbol_Status/1]).
-export([get_service_names/0]).
-export([get_service_def/1]).
-export([get_rpc_names/1]).
-export([find_rpc_def/2, fetch_rpc_def/2]).
-export([get_package_name/0]).
-export([gpb_version_as_string/0, gpb_version_as_list/0]).
-include("anycable.hrl").
-include("gpb.hrl").
-record('map<string,string>',{key, value}).
-spec encode_msg(_) -> binary().
encode_msg(Msg) -> encode_msg(Msg, []).
-spec encode_msg(_, list()) -> binary().
encode_msg(Msg, Opts) ->
case proplists:get_bool(verify, Opts) of
true -> verify_msg(Msg, Opts);
false -> ok
end,
TrUserData = proplists:get_value(user_data, Opts),
case Msg of
#'DisconnectResponse'{} ->
e_msg_DisconnectResponse(Msg, TrUserData);
#'CommandResponse'{} ->
e_msg_CommandResponse(Msg, TrUserData);
#'CommandMessage'{} ->
e_msg_CommandMessage(Msg, TrUserData);
#'ConnectionResponse'{} ->
e_msg_ConnectionResponse(Msg, TrUserData);
#'ConnectionRequest'{} ->
e_msg_ConnectionRequest(Msg, TrUserData);
#'DisconnectRequest'{} ->
e_msg_DisconnectRequest(Msg, TrUserData)
end.
e_msg_DisconnectResponse(Msg, TrUserData) ->
e_msg_DisconnectResponse(Msg, <<>>, TrUserData).
e_msg_DisconnectResponse(#'DisconnectResponse'{status =
F1},
Bin, TrUserData) ->
if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_enum_Status(TrF1, <<Bin/binary, 8>>)
end.
e_msg_CommandResponse(Msg, TrUserData) ->
e_msg_CommandResponse(Msg, <<>>, TrUserData).
e_msg_CommandResponse(#'CommandResponse'{status = F1,
disconnect = F2, stop_streams = F3,
streams = F4, transmissions = F5},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_enum_Status(TrF1, <<Bin/binary, 8>>)
end,
B2 = if F2 == undefined -> B1;
true ->
TrF2 = id(F2, TrUserData),
e_type_bool(TrF2, <<B1/binary, 16>>)
end,
B3 = if F3 == undefined -> B2;
true ->
TrF3 = id(F3, TrUserData),
e_type_bool(TrF3, <<B2/binary, 24>>)
end,
B4 = begin
TrF4 = id(F4, TrUserData),
if TrF4 == [] -> B3;
true ->
e_field_CommandResponse_streams(TrF4, B3, TrUserData)
end
end,
begin
TrF5 = id(F5, TrUserData),
if TrF5 == [] -> B4;
true ->
e_field_CommandResponse_transmissions(TrF5, B4,
TrUserData)
end
end.
e_msg_CommandMessage(Msg, TrUserData) ->
e_msg_CommandMessage(Msg, <<>>, TrUserData).
e_msg_CommandMessage(#'CommandMessage'{command = F1,
identifier = F2,
connection_identifiers = F3, data = F4},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
B2 = if F2 == undefined -> B1;
true ->
TrF2 = id(F2, TrUserData),
e_type_string(TrF2, <<B1/binary, 18>>)
end,
B3 = if F3 == undefined -> B2;
true ->
TrF3 = id(F3, TrUserData),
e_type_string(TrF3, <<B2/binary, 26>>)
end,
if F4 == undefined -> B3;
true ->
TrF4 = id(F4, TrUserData),
e_type_string(TrF4, <<B3/binary, 34>>)
end.
e_msg_ConnectionResponse(Msg, TrUserData) ->
e_msg_ConnectionResponse(Msg, <<>>, TrUserData).
e_msg_ConnectionResponse(#'ConnectionResponse'{status =
F1,
identifiers = F2,
transmissions = F3},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_enum_Status(TrF1, <<Bin/binary, 8>>)
end,
B2 = if F2 == undefined -> B1;
true ->
TrF2 = id(F2, TrUserData),
e_type_string(TrF2, <<B1/binary, 18>>)
end,
begin
TrF3 = id(F3, TrUserData),
if TrF3 == [] -> B2;
true ->
e_field_ConnectionResponse_transmissions(TrF3, B2,
TrUserData)
end
end.
e_msg_ConnectionRequest(Msg, TrUserData) ->
e_msg_ConnectionRequest(Msg, <<>>, TrUserData).
e_msg_ConnectionRequest(#'ConnectionRequest'{path = F1,
headers = F2},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
begin
TrF2 = id(F2, TrUserData),
if TrF2 == [] -> B1;
true ->
e_field_ConnectionRequest_headers(TrF2, B1, TrUserData)
end
end.
e_msg_DisconnectRequest(Msg, TrUserData) ->
e_msg_DisconnectRequest(Msg, <<>>, TrUserData).
e_msg_DisconnectRequest(#'DisconnectRequest'{identifiers
= F1,
subscriptions = F2, path = F3,
headers = F4},
Bin, TrUserData) ->
B1 = if F1 == undefined -> Bin;
true ->
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
B2 = begin
TrF2 = id(F2, TrUserData),
if TrF2 == [] -> B1;
true ->
e_field_DisconnectRequest_subscriptions(TrF2, B1,
TrUserData)
end
end,
B3 = if F3 == undefined -> B2;
true ->
TrF3 = id(F3, TrUserData),
e_type_string(TrF3, <<B2/binary, 26>>)
end,
begin
TrF4 = id(F4, TrUserData),
if TrF4 == [] -> B3;
true ->
e_field_DisconnectRequest_headers(TrF4, B3, TrUserData)
end
end.
e_field_CommandResponse_streams([Elem | Rest], Bin,
TrUserData) ->
Bin2 = <<Bin/binary, 34>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_CommandResponse_streams(Rest, Bin3, TrUserData);
e_field_CommandResponse_streams([], Bin, _TrUserData) ->
Bin.
e_field_CommandResponse_transmissions([Elem | Rest],
Bin, TrUserData) ->
Bin2 = <<Bin/binary, 42>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_CommandResponse_transmissions(Rest, Bin3,
TrUserData);
e_field_CommandResponse_transmissions([], Bin,
_TrUserData) ->
Bin.
e_field_ConnectionResponse_transmissions([Elem | Rest],
Bin, TrUserData) ->
Bin2 = <<Bin/binary, 26>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_ConnectionResponse_transmissions(Rest, Bin3,
TrUserData);
e_field_ConnectionResponse_transmissions([], Bin,
_TrUserData) ->
Bin.
e_mfield_ConnectionRequest_headers(Msg, Bin,
TrUserData) ->
SubBin = 'e_msg_map<string,string>'(Msg, <<>>,
TrUserData),
Bin2 = e_varint(byte_size(SubBin), Bin),
<<Bin2/binary, SubBin/binary>>.
e_field_ConnectionRequest_headers([Elem | Rest], Bin,
TrUserData) ->
Bin2 = <<Bin/binary, 18>>,
Bin3 =
e_mfield_ConnectionRequest_headers('tr_encode_ConnectionRequest.headers[x]'(Elem,
TrUserData),
Bin2, TrUserData),
e_field_ConnectionRequest_headers(Rest, Bin3,
TrUserData);
e_field_ConnectionRequest_headers([], Bin,
_TrUserData) ->
Bin.
e_field_DisconnectRequest_subscriptions([Elem | Rest],
Bin, TrUserData) ->
Bin2 = <<Bin/binary, 18>>,
Bin3 = e_type_string(id(Elem, TrUserData), Bin2),
e_field_DisconnectRequest_subscriptions(Rest, Bin3,
TrUserData);
e_field_DisconnectRequest_subscriptions([], Bin,
_TrUserData) ->
Bin.
e_mfield_DisconnectRequest_headers(Msg, Bin,
TrUserData) ->
SubBin = 'e_msg_map<string,string>'(Msg, <<>>,
TrUserData),
Bin2 = e_varint(byte_size(SubBin), Bin),
<<Bin2/binary, SubBin/binary>>.
e_field_DisconnectRequest_headers([Elem | Rest], Bin,
TrUserData) ->
Bin2 = <<Bin/binary, 34>>,
Bin3 =
e_mfield_DisconnectRequest_headers('tr_encode_DisconnectRequest.headers[x]'(Elem,
TrUserData),
Bin2, TrUserData),
e_field_DisconnectRequest_headers(Rest, Bin3,
TrUserData);
e_field_DisconnectRequest_headers([], Bin,
_TrUserData) ->
Bin.
'e_msg_map<string,string>'(#'map<string,string>'{key =
F1,
value = F2},
Bin, TrUserData) ->
B1 = begin
TrF1 = id(F1, TrUserData),
e_type_string(TrF1, <<Bin/binary, 10>>)
end,
begin
TrF2 = id(F2, TrUserData),
e_type_string(TrF2, <<B1/binary, 18>>)
end.
e_enum_Status('ERROR', Bin) -> <<Bin/binary, 0>>;
e_enum_Status('SUCCESS', Bin) -> <<Bin/binary, 1>>;
e_enum_Status(V, Bin) -> e_varint(V, Bin).
e_type_bool(true, Bin) -> <<Bin/binary, 1>>;
e_type_bool(false, Bin) -> <<Bin/binary, 0>>;
e_type_bool(1, Bin) -> <<Bin/binary, 1>>;
e_type_bool(0, Bin) -> <<Bin/binary, 0>>.
e_type_string(S, Bin) ->
Utf8 = unicode:characters_to_binary(S),
Bin2 = e_varint(byte_size(Utf8), Bin),
<<Bin2/binary, Utf8/binary>>.
e_varint(N, Bin) when N =< 127 -> <<Bin/binary, N>>;
e_varint(N, Bin) ->
Bin2 = <<Bin/binary, (N band 127 bor 128)>>,
e_varint(N bsr 7, Bin2).
decode_msg(Bin, MsgName) when is_binary(Bin) ->
decode_msg(Bin, MsgName, []).
decode_msg(Bin, MsgName, Opts) when is_binary(Bin) ->
TrUserData = proplists:get_value(user_data, Opts),
case MsgName of
'DisconnectResponse' ->
d_msg_DisconnectResponse(Bin, TrUserData);
'CommandResponse' ->
d_msg_CommandResponse(Bin, TrUserData);
'CommandMessage' ->
d_msg_CommandMessage(Bin, TrUserData);
'ConnectionResponse' ->
d_msg_ConnectionResponse(Bin, TrUserData);
'ConnectionRequest' ->
d_msg_ConnectionRequest(Bin, TrUserData);
'DisconnectRequest' ->
d_msg_DisconnectRequest(Bin, TrUserData)
end.
d_msg_DisconnectResponse(Bin, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Bin, 0, 0,
id(undefined, TrUserData),
TrUserData).
dfp_read_field_def_DisconnectResponse(<<8,
Rest/binary>>,
Z1, Z2, F1, TrUserData) ->
d_field_DisconnectResponse_status(Rest, Z1, Z2, F1,
TrUserData);
dfp_read_field_def_DisconnectResponse(<<>>, 0, 0, F1,
_) ->
#'DisconnectResponse'{status = F1};
dfp_read_field_def_DisconnectResponse(Other, Z1, Z2, F1,
TrUserData) ->
dg_read_field_def_DisconnectResponse(Other, Z1, Z2, F1,
TrUserData).
dg_read_field_def_DisconnectResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_DisconnectResponse(Rest, N + 7,
X bsl N + Acc, F1, TrUserData);
dg_read_field_def_DisconnectResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData) ->
Key = X bsl N + Acc,
case Key of
8 ->
d_field_DisconnectResponse_status(Rest, 0, 0, F1,
TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_DisconnectResponse(Rest, 0, 0, F1,
TrUserData);
1 ->
skip_64_DisconnectResponse(Rest, 0, 0, F1, TrUserData);
2 ->
skip_length_delimited_DisconnectResponse(Rest, 0, 0, F1,
TrUserData);
5 ->
skip_32_DisconnectResponse(Rest, 0, 0, F1, TrUserData)
end
end;
dg_read_field_def_DisconnectResponse(<<>>, 0, 0, F1,
_) ->
#'DisconnectResponse'{status = F1}.
d_field_DisconnectResponse_status(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData)
when N < 57 ->
d_field_DisconnectResponse_status(Rest, N + 7,
X bsl N + Acc, F1, TrUserData);
d_field_DisconnectResponse_status(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, TrUserData) ->
<<Tmp:32/signed-native>> = <<(X bsl N +
Acc):32/unsigned-native>>,
NewFValue = d_enum_Status(Tmp),
dfp_read_field_def_DisconnectResponse(Rest, 0, 0,
NewFValue, TrUserData).
skip_varint_DisconnectResponse(<<1:1, _:7,
Rest/binary>>,
Z1, Z2, F1, TrUserData) ->
skip_varint_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData);
skip_varint_DisconnectResponse(<<0:1, _:7,
Rest/binary>>,
Z1, Z2, F1, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData).
skip_length_delimited_DisconnectResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData)
when N < 57 ->
skip_length_delimited_DisconnectResponse(Rest, N + 7,
X bsl N + Acc, F1, TrUserData);
skip_length_delimited_DisconnectResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_DisconnectResponse(Rest2, 0, 0, F1,
TrUserData).
skip_32_DisconnectResponse(<<_:32, Rest/binary>>, Z1,
Z2, F1, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData).
skip_64_DisconnectResponse(<<_:64, Rest/binary>>, Z1,
Z2, F1, TrUserData) ->
dfp_read_field_def_DisconnectResponse(Rest, Z1, Z2, F1,
TrUserData).
d_msg_CommandResponse(Bin, TrUserData) ->
dfp_read_field_def_CommandResponse(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
id(undefined, TrUserData),
id([], TrUserData), id([], TrUserData),
TrUserData).
dfp_read_field_def_CommandResponse(<<8, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_status(Rest, Z1, Z2, F1, F2, F3,
F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<16, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_disconnect(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<24, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_stop_streams(Rest, Z1, Z2, F1,
F2, F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<34, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_streams(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<42, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
d_field_CommandResponse_transmissions(Rest, Z1, Z2, F1,
F2, F3, F4, F5, TrUserData);
dfp_read_field_def_CommandResponse(<<>>, 0, 0, F1, F2,
F3, F4, F5, TrUserData) ->
#'CommandResponse'{status = F1, disconnect = F2,
stop_streams = F3,
streams = lists_reverse(F4, TrUserData),
transmissions = lists_reverse(F5, TrUserData)};
dfp_read_field_def_CommandResponse(Other, Z1, Z2, F1,
F2, F3, F4, F5, TrUserData) ->
dg_read_field_def_CommandResponse(Other, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
dg_read_field_def_CommandResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_CommandResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
dg_read_field_def_CommandResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Key = X bsl N + Acc,
case Key of
8 ->
d_field_CommandResponse_status(Rest, 0, 0, F1, F2, F3,
F4, F5, TrUserData);
16 ->
d_field_CommandResponse_disconnect(Rest, 0, 0, F1, F2,
F3, F4, F5, TrUserData);
24 ->
d_field_CommandResponse_stop_streams(Rest, 0, 0, F1, F2,
F3, F4, F5, TrUserData);
34 ->
d_field_CommandResponse_streams(Rest, 0, 0, F1, F2, F3,
F4, F5, TrUserData);
42 ->
d_field_CommandResponse_transmissions(Rest, 0, 0, F1,
F2, F3, F4, F5, TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_CommandResponse(Rest, 0, 0, F1, F2, F3, F4,
F5, TrUserData);
1 ->
skip_64_CommandResponse(Rest, 0, 0, F1, F2, F3, F4, F5,
TrUserData);
2 ->
skip_length_delimited_CommandResponse(Rest, 0, 0, F1,
F2, F3, F4, F5,
TrUserData);
5 ->
skip_32_CommandResponse(Rest, 0, 0, F1, F2, F3, F4, F5,
TrUserData)
end
end;
dg_read_field_def_CommandResponse(<<>>, 0, 0, F1, F2,
F3, F4, F5, TrUserData) ->
#'CommandResponse'{status = F1, disconnect = F2,
stop_streams = F3,
streams = lists_reverse(F4, TrUserData),
transmissions = lists_reverse(F5, TrUserData)}.
d_field_CommandResponse_status(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_status(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_status(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, F4, F5, TrUserData) ->
<<Tmp:32/signed-native>> = <<(X bsl N +
Acc):32/unsigned-native>>,
NewFValue = d_enum_Status(Tmp),
dfp_read_field_def_CommandResponse(Rest, 0, 0,
NewFValue, F2, F3, F4, F5, TrUserData).
d_field_CommandResponse_disconnect(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_disconnect(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_disconnect(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, F3, F4, F5, TrUserData) ->
NewFValue = X bsl N + Acc =/= 0,
dfp_read_field_def_CommandResponse(Rest, 0, 0, F1,
NewFValue, F3, F4, F5, TrUserData).
d_field_CommandResponse_stop_streams(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_stop_streams(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_stop_streams(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, _, F4, F5, TrUserData) ->
NewFValue = X bsl N + Acc =/= 0,
dfp_read_field_def_CommandResponse(Rest, 0, 0, F1, F2,
NewFValue, F4, F5, TrUserData).
d_field_CommandResponse_streams(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_streams(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_streams(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandResponse(Rest2, 0, 0, F1, F2,
F3, cons(NewFValue, F4, TrUserData), F5,
TrUserData).
d_field_CommandResponse_transmissions(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
d_field_CommandResponse_transmissions(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
d_field_CommandResponse_transmissions(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandResponse(Rest2, 0, 0, F1, F2,
F3, F4, cons(NewFValue, F5, TrUserData),
TrUserData).
skip_varint_CommandResponse(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
skip_varint_CommandResponse(Rest, Z1, Z2, F1, F2, F3,
F4, F5, TrUserData);
skip_varint_CommandResponse(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, F5, TrUserData) ->
dfp_read_field_def_CommandResponse(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
skip_length_delimited_CommandResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData)
when N < 57 ->
skip_length_delimited_CommandResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, F5,
TrUserData);
skip_length_delimited_CommandResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, F5, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_CommandResponse(Rest2, 0, 0, F1, F2,
F3, F4, F5, TrUserData).
skip_32_CommandResponse(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, F5, TrUserData) ->
dfp_read_field_def_CommandResponse(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
skip_64_CommandResponse(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, F5, TrUserData) ->
dfp_read_field_def_CommandResponse(Rest, Z1, Z2, F1, F2,
F3, F4, F5, TrUserData).
d_msg_CommandMessage(Bin, TrUserData) ->
dfp_read_field_def_CommandMessage(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
id(undefined, TrUserData),
id(undefined, TrUserData), TrUserData).
dfp_read_field_def_CommandMessage(<<10, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_command(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
dfp_read_field_def_CommandMessage(<<18, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_identifier(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData);
dfp_read_field_def_CommandMessage(<<26, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_connection_identifiers(Rest, Z1,
Z2, F1, F2, F3, F4,
TrUserData);
dfp_read_field_def_CommandMessage(<<34, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_CommandMessage_data(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
dfp_read_field_def_CommandMessage(<<>>, 0, 0, F1, F2,
F3, F4, _) ->
#'CommandMessage'{command = F1, identifier = F2,
connection_identifiers = F3, data = F4};
dfp_read_field_def_CommandMessage(Other, Z1, Z2, F1, F2,
F3, F4, TrUserData) ->
dg_read_field_def_CommandMessage(Other, Z1, Z2, F1, F2,
F3, F4, TrUserData).
dg_read_field_def_CommandMessage(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_CommandMessage(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, TrUserData);
dg_read_field_def_CommandMessage(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
d_field_CommandMessage_command(Rest, 0, 0, F1, F2, F3,
F4, TrUserData);
18 ->
d_field_CommandMessage_identifier(Rest, 0, 0, F1, F2,
F3, F4, TrUserData);
26 ->
d_field_CommandMessage_connection_identifiers(Rest, 0,
0, F1, F2, F3, F4,
TrUserData);
34 ->
d_field_CommandMessage_data(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_CommandMessage(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
1 ->
skip_64_CommandMessage(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
2 ->
skip_length_delimited_CommandMessage(Rest, 0, 0, F1, F2,
F3, F4, TrUserData);
5 ->
skip_32_CommandMessage(Rest, 0, 0, F1, F2, F3, F4,
TrUserData)
end
end;
dg_read_field_def_CommandMessage(<<>>, 0, 0, F1, F2, F3,
F4, _) ->
#'CommandMessage'{command = F1, identifier = F2,
connection_identifiers = F3, data = F4}.
d_field_CommandMessage_command(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_CommandMessage_command(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, TrUserData);
d_field_CommandMessage_command(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0,
NewFValue, F2, F3, F4, TrUserData).
d_field_CommandMessage_identifier(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_CommandMessage_identifier(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_CommandMessage_identifier(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1,
NewFValue, F3, F4, TrUserData).
d_field_CommandMessage_connection_identifiers(<<1:1,
X:7, Rest/binary>>,
N, Acc, F1, F2, F3, F4,
TrUserData)
when N < 57 ->
d_field_CommandMessage_connection_identifiers(Rest,
N + 7, X bsl N + Acc, F1, F2,
F3, F4, TrUserData);
d_field_CommandMessage_connection_identifiers(<<0:1,
X:7, Rest/binary>>,
N, Acc, F1, F2, _, F4,
TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1, F2,
NewFValue, F4, TrUserData).
d_field_CommandMessage_data(<<1:1, X:7, Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_CommandMessage_data(Rest, N + 7, X bsl N + Acc,
F1, F2, F3, F4, TrUserData);
d_field_CommandMessage_data(<<0:1, X:7, Rest/binary>>,
N, Acc, F1, F2, F3, _, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1, F2,
F3, NewFValue, TrUserData).
skip_varint_CommandMessage(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
skip_varint_CommandMessage(Rest, Z1, Z2, F1, F2, F3, F4,
TrUserData);
skip_varint_CommandMessage(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_CommandMessage(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData).
skip_length_delimited_CommandMessage(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
skip_length_delimited_CommandMessage(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
skip_length_delimited_CommandMessage(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_CommandMessage(Rest2, 0, 0, F1, F2,
F3, F4, TrUserData).
skip_32_CommandMessage(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_CommandMessage(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData).
skip_64_CommandMessage(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_CommandMessage(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData).
d_msg_ConnectionResponse(Bin, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
id([], TrUserData), TrUserData).
dfp_read_field_def_ConnectionResponse(<<8,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
d_field_ConnectionResponse_status(Rest, Z1, Z2, F1, F2,
F3, TrUserData);
dfp_read_field_def_ConnectionResponse(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
d_field_ConnectionResponse_identifiers(Rest, Z1, Z2, F1,
F2, F3, TrUserData);
dfp_read_field_def_ConnectionResponse(<<26,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
d_field_ConnectionResponse_transmissions(Rest, Z1, Z2,
F1, F2, F3, TrUserData);
dfp_read_field_def_ConnectionResponse(<<>>, 0, 0, F1,
F2, F3, TrUserData) ->
#'ConnectionResponse'{status = F1, identifiers = F2,
transmissions = lists_reverse(F3, TrUserData)};
dfp_read_field_def_ConnectionResponse(Other, Z1, Z2, F1,
F2, F3, TrUserData) ->
dg_read_field_def_ConnectionResponse(Other, Z1, Z2, F1,
F2, F3, TrUserData).
dg_read_field_def_ConnectionResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_ConnectionResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, TrUserData);
dg_read_field_def_ConnectionResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData) ->
Key = X bsl N + Acc,
case Key of
8 ->
d_field_ConnectionResponse_status(Rest, 0, 0, F1, F2,
F3, TrUserData);
18 ->
d_field_ConnectionResponse_identifiers(Rest, 0, 0, F1,
F2, F3, TrUserData);
26 ->
d_field_ConnectionResponse_transmissions(Rest, 0, 0, F1,
F2, F3, TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_ConnectionResponse(Rest, 0, 0, F1, F2, F3,
TrUserData);
1 ->
skip_64_ConnectionResponse(Rest, 0, 0, F1, F2, F3,
TrUserData);
2 ->
skip_length_delimited_ConnectionResponse(Rest, 0, 0, F1,
F2, F3, TrUserData);
5 ->
skip_32_ConnectionResponse(Rest, 0, 0, F1, F2, F3,
TrUserData)
end
end;
dg_read_field_def_ConnectionResponse(<<>>, 0, 0, F1, F2,
F3, TrUserData) ->
#'ConnectionResponse'{status = F1, identifiers = F2,
transmissions = lists_reverse(F3, TrUserData)}.
d_field_ConnectionResponse_status(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
d_field_ConnectionResponse_status(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, TrUserData);
d_field_ConnectionResponse_status(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, TrUserData) ->
<<Tmp:32/signed-native>> = <<(X bsl N +
Acc):32/unsigned-native>>,
NewFValue = d_enum_Status(Tmp),
dfp_read_field_def_ConnectionResponse(Rest, 0, 0,
NewFValue, F2, F3, TrUserData).
d_field_ConnectionResponse_identifiers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
d_field_ConnectionResponse_identifiers(Rest, N + 7,
X bsl N + Acc, F1, F2, F3,
TrUserData);
d_field_ConnectionResponse_identifiers(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, F3, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_ConnectionResponse(Rest2, 0, 0, F1,
NewFValue, F3, TrUserData).
d_field_ConnectionResponse_transmissions(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
d_field_ConnectionResponse_transmissions(Rest, N + 7,
X bsl N + Acc, F1, F2, F3,
TrUserData);
d_field_ConnectionResponse_transmissions(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_ConnectionResponse(Rest2, 0, 0, F1,
F2, cons(NewFValue, F3, TrUserData),
TrUserData).
skip_varint_ConnectionResponse(<<1:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
skip_varint_ConnectionResponse(Rest, Z1, Z2, F1, F2, F3,
TrUserData);
skip_varint_ConnectionResponse(<<0:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, F3, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Rest, Z1, Z2, F1,
F2, F3, TrUserData).
skip_length_delimited_ConnectionResponse(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData)
when N < 57 ->
skip_length_delimited_ConnectionResponse(Rest, N + 7,
X bsl N + Acc, F1, F2, F3,
TrUserData);
skip_length_delimited_ConnectionResponse(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_ConnectionResponse(Rest2, 0, 0, F1,
F2, F3, TrUserData).
skip_32_ConnectionResponse(<<_:32, Rest/binary>>, Z1,
Z2, F1, F2, F3, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Rest, Z1, Z2, F1,
F2, F3, TrUserData).
skip_64_ConnectionResponse(<<_:64, Rest/binary>>, Z1,
Z2, F1, F2, F3, TrUserData) ->
dfp_read_field_def_ConnectionResponse(Rest, Z1, Z2, F1,
F2, F3, TrUserData).
d_msg_ConnectionRequest(Bin, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Bin, 0, 0,
id(undefined, TrUserData),
'tr_decode_init_default_ConnectionRequest.headers'([],
TrUserData),
TrUserData).
dfp_read_field_def_ConnectionRequest(<<10,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
d_field_ConnectionRequest_path(Rest, Z1, Z2, F1, F2,
TrUserData);
dfp_read_field_def_ConnectionRequest(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
d_field_ConnectionRequest_headers(Rest, Z1, Z2, F1, F2,
TrUserData);
dfp_read_field_def_ConnectionRequest(<<>>, 0, 0, F1, F2,
TrUserData) ->
#'ConnectionRequest'{path = F1,
headers =
'tr_decode_repeated_finalize_ConnectionRequest.headers'(F2,
TrUserData)};
dfp_read_field_def_ConnectionRequest(Other, Z1, Z2, F1,
F2, TrUserData) ->
dg_read_field_def_ConnectionRequest(Other, Z1, Z2, F1,
F2, TrUserData).
dg_read_field_def_ConnectionRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_ConnectionRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
dg_read_field_def_ConnectionRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
d_field_ConnectionRequest_path(Rest, 0, 0, F1, F2,
TrUserData);
18 ->
d_field_ConnectionRequest_headers(Rest, 0, 0, F1, F2,
TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_ConnectionRequest(Rest, 0, 0, F1, F2,
TrUserData);
1 ->
skip_64_ConnectionRequest(Rest, 0, 0, F1, F2,
TrUserData);
2 ->
skip_length_delimited_ConnectionRequest(Rest, 0, 0, F1,
F2, TrUserData);
5 ->
skip_32_ConnectionRequest(Rest, 0, 0, F1, F2,
TrUserData)
end
end;
dg_read_field_def_ConnectionRequest(<<>>, 0, 0, F1, F2,
TrUserData) ->
#'ConnectionRequest'{path = F1,
headers =
'tr_decode_repeated_finalize_ConnectionRequest.headers'(F2,
TrUserData)}.
d_field_ConnectionRequest_path(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
d_field_ConnectionRequest_path(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
d_field_ConnectionRequest_path(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_ConnectionRequest(Rest2, 0, 0,
NewFValue, F2, TrUserData).
d_field_ConnectionRequest_headers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
d_field_ConnectionRequest_headers(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
d_field_ConnectionRequest_headers(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Len = X bsl N + Acc,
<<Bs:Len/binary, Rest2/binary>> = Rest,
NewFValue = id('d_msg_map<string,string>'(Bs,
TrUserData),
TrUserData),
dfp_read_field_def_ConnectionRequest(Rest2, 0, 0, F1,
'tr_decode_repeated_add_elem_ConnectionRequest.headers'(NewFValue,
F2,
TrUserData),
TrUserData).
skip_varint_ConnectionRequest(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
skip_varint_ConnectionRequest(Rest, Z1, Z2, F1, F2,
TrUserData);
skip_varint_ConnectionRequest(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Rest, Z1, Z2, F1,
F2, TrUserData).
skip_length_delimited_ConnectionRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
skip_length_delimited_ConnectionRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
skip_length_delimited_ConnectionRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_ConnectionRequest(Rest2, 0, 0, F1,
F2, TrUserData).
skip_32_ConnectionRequest(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Rest, Z1, Z2, F1,
F2, TrUserData).
skip_64_ConnectionRequest(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, TrUserData) ->
dfp_read_field_def_ConnectionRequest(Rest, Z1, Z2, F1,
F2, TrUserData).
d_msg_DisconnectRequest(Bin, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Bin, 0, 0,
id(undefined, TrUserData),
id([], TrUserData),
id(undefined, TrUserData),
'tr_decode_init_default_DisconnectRequest.headers'([],
TrUserData),
TrUserData).
dfp_read_field_def_DisconnectRequest(<<10,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_identifiers(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_subscriptions(Rest, Z1, Z2,
F1, F2, F3, F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<26,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_path(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<34,
Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
d_field_DisconnectRequest_headers(Rest, Z1, Z2, F1, F2,
F3, F4, TrUserData);
dfp_read_field_def_DisconnectRequest(<<>>, 0, 0, F1, F2,
F3, F4, TrUserData) ->
#'DisconnectRequest'{identifiers = F1,
subscriptions = lists_reverse(F2, TrUserData),
path = F3,
headers =
'tr_decode_repeated_finalize_DisconnectRequest.headers'(F4,
TrUserData)};
dfp_read_field_def_DisconnectRequest(Other, Z1, Z2, F1,
F2, F3, F4, TrUserData) ->
dg_read_field_def_DisconnectRequest(Other, Z1, Z2, F1,
F2, F3, F4, TrUserData).
dg_read_field_def_DisconnectRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 32 - 7 ->
dg_read_field_def_DisconnectRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
dg_read_field_def_DisconnectRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
d_field_DisconnectRequest_identifiers(Rest, 0, 0, F1,
F2, F3, F4, TrUserData);
18 ->
d_field_DisconnectRequest_subscriptions(Rest, 0, 0, F1,
F2, F3, F4, TrUserData);
26 ->
d_field_DisconnectRequest_path(Rest, 0, 0, F1, F2, F3,
F4, TrUserData);
34 ->
d_field_DisconnectRequest_headers(Rest, 0, 0, F1, F2,
F3, F4, TrUserData);
_ ->
case Key band 7 of
0 ->
skip_varint_DisconnectRequest(Rest, 0, 0, F1, F2, F3,
F4, TrUserData);
1 ->
skip_64_DisconnectRequest(Rest, 0, 0, F1, F2, F3, F4,
TrUserData);
2 ->
skip_length_delimited_DisconnectRequest(Rest, 0, 0, F1,
F2, F3, F4, TrUserData);
5 ->
skip_32_DisconnectRequest(Rest, 0, 0, F1, F2, F3, F4,
TrUserData)
end
end;
dg_read_field_def_DisconnectRequest(<<>>, 0, 0, F1, F2,
F3, F4, TrUserData) ->
#'DisconnectRequest'{identifiers = F1,
subscriptions = lists_reverse(F2, TrUserData),
path = F3,
headers =
'tr_decode_repeated_finalize_DisconnectRequest.headers'(F4,
TrUserData)}.
d_field_DisconnectRequest_identifiers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_identifiers(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_DisconnectRequest_identifiers(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0,
NewFValue, F2, F3, F4, TrUserData).
d_field_DisconnectRequest_subscriptions(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_subscriptions(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_DisconnectRequest_subscriptions(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
cons(NewFValue, F2, TrUserData), F3,
F4, TrUserData).
d_field_DisconnectRequest_path(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_path(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4, TrUserData);
d_field_DisconnectRequest_path(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, _, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
F2, NewFValue, F4, TrUserData).
d_field_DisconnectRequest_headers(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
d_field_DisconnectRequest_headers(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
d_field_DisconnectRequest_headers(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Len = X bsl N + Acc,
<<Bs:Len/binary, Rest2/binary>> = Rest,
NewFValue = id('d_msg_map<string,string>'(Bs,
TrUserData),
TrUserData),
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
F2, F3,
'tr_decode_repeated_add_elem_DisconnectRequest.headers'(NewFValue,
F4,
TrUserData),
TrUserData).
skip_varint_DisconnectRequest(<<1:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
skip_varint_DisconnectRequest(Rest, Z1, Z2, F1, F2, F3,
F4, TrUserData);
skip_varint_DisconnectRequest(<<0:1, _:7, Rest/binary>>,
Z1, Z2, F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData).
skip_length_delimited_DisconnectRequest(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData)
when N < 57 ->
skip_length_delimited_DisconnectRequest(Rest, N + 7,
X bsl N + Acc, F1, F2, F3, F4,
TrUserData);
skip_length_delimited_DisconnectRequest(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, F3, F4, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
dfp_read_field_def_DisconnectRequest(Rest2, 0, 0, F1,
F2, F3, F4, TrUserData).
skip_32_DisconnectRequest(<<_:32, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData).
skip_64_DisconnectRequest(<<_:64, Rest/binary>>, Z1, Z2,
F1, F2, F3, F4, TrUserData) ->
dfp_read_field_def_DisconnectRequest(Rest, Z1, Z2, F1,
F2, F3, F4, TrUserData).
'd_msg_map<string,string>'(Bin, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Bin, 0, 0,
id(undefined, TrUserData),
id(undefined, TrUserData),
TrUserData).
'dfp_read_field_def_map<string,string>'(<<10,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'd_field_map<string,string>_key'(Rest, Z1, Z2, F1, F2,
TrUserData);
'dfp_read_field_def_map<string,string>'(<<18,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'd_field_map<string,string>_value'(Rest, Z1, Z2, F1, F2,
TrUserData);
'dfp_read_field_def_map<string,string>'(<<>>, 0, 0, F1,
F2, _) ->
#'map<string,string>'{key = F1, value = F2};
'dfp_read_field_def_map<string,string>'(Other, Z1, Z2,
F1, F2, TrUserData) ->
'dg_read_field_def_map<string,string>'(Other, Z1, Z2,
F1, F2, TrUserData).
'dg_read_field_def_map<string,string>'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 32 - 7 ->
'dg_read_field_def_map<string,string>'(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
'dg_read_field_def_map<string,string>'(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Key = X bsl N + Acc,
case Key of
10 ->
'd_field_map<string,string>_key'(Rest, 0, 0, F1, F2,
TrUserData);
18 ->
'd_field_map<string,string>_value'(Rest, 0, 0, F1, F2,
TrUserData);
_ ->
case Key band 7 of
0 ->
'skip_varint_map<string,string>'(Rest, 0, 0, F1, F2,
TrUserData);
1 ->
'skip_64_map<string,string>'(Rest, 0, 0, F1, F2,
TrUserData);
2 ->
'skip_length_delimited_map<string,string>'(Rest, 0, 0,
F1, F2, TrUserData);
5 ->
'skip_32_map<string,string>'(Rest, 0, 0, F1, F2,
TrUserData)
end
end;
'dg_read_field_def_map<string,string>'(<<>>, 0, 0, F1,
F2, _) ->
#'map<string,string>'{key = F1, value = F2}.
'd_field_map<string,string>_key'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
'd_field_map<string,string>_key'(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
'd_field_map<string,string>_key'(<<0:1, X:7,
Rest/binary>>,
N, Acc, _, F2, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
'dfp_read_field_def_map<string,string>'(Rest2, 0, 0,
NewFValue, F2, TrUserData).
'd_field_map<string,string>_value'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
'd_field_map<string,string>_value'(Rest, N + 7,
X bsl N + Acc, F1, F2, TrUserData);
'd_field_map<string,string>_value'(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, _, TrUserData) ->
Len = X bsl N + Acc,
<<Utf8:Len/binary, Rest2/binary>> = Rest,
NewFValue = unicode:characters_to_list(Utf8, unicode),
'dfp_read_field_def_map<string,string>'(Rest2, 0, 0, F1,
NewFValue, TrUserData).
'skip_varint_map<string,string>'(<<1:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'skip_varint_map<string,string>'(Rest, Z1, Z2, F1, F2,
TrUserData);
'skip_varint_map<string,string>'(<<0:1, _:7,
Rest/binary>>,
Z1, Z2, F1, F2, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Rest, Z1, Z2,
F1, F2, TrUserData).
'skip_length_delimited_map<string,string>'(<<1:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData)
when N < 57 ->
'skip_length_delimited_map<string,string>'(Rest, N + 7,
X bsl N + Acc, F1, F2,
TrUserData);
'skip_length_delimited_map<string,string>'(<<0:1, X:7,
Rest/binary>>,
N, Acc, F1, F2, TrUserData) ->
Length = X bsl N + Acc,
<<_:Length/binary, Rest2/binary>> = Rest,
'dfp_read_field_def_map<string,string>'(Rest2, 0, 0, F1,
F2, TrUserData).
'skip_32_map<string,string>'(<<_:32, Rest/binary>>, Z1,
Z2, F1, F2, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Rest, Z1, Z2,
F1, F2, TrUserData).
'skip_64_map<string,string>'(<<_:64, Rest/binary>>, Z1,
Z2, F1, F2, TrUserData) ->
'dfp_read_field_def_map<string,string>'(Rest, Z1, Z2,
F1, F2, TrUserData).
d_enum_Status(0) -> 'ERROR';
d_enum_Status(1) -> 'SUCCESS';
d_enum_Status(V) -> V.
merge_msgs(Prev, New) -> merge_msgs(Prev, New, []).
merge_msgs(Prev, New, Opts)
when element(1, Prev) =:= element(1, New) ->
TrUserData = proplists:get_value(user_data, Opts),
case Prev of
#'DisconnectResponse'{} ->
merge_msg_DisconnectResponse(Prev, New, TrUserData);
#'CommandResponse'{} ->
merge_msg_CommandResponse(Prev, New, TrUserData);
#'CommandMessage'{} ->
merge_msg_CommandMessage(Prev, New, TrUserData);
#'ConnectionResponse'{} ->
merge_msg_ConnectionResponse(Prev, New, TrUserData);
#'ConnectionRequest'{} ->
merge_msg_ConnectionRequest(Prev, New, TrUserData);
#'DisconnectRequest'{} ->
merge_msg_DisconnectRequest(Prev, New, TrUserData)
end.
merge_msg_DisconnectResponse(#'DisconnectResponse'{status
= PFstatus},
#'DisconnectResponse'{status = NFstatus}, _) ->
#'DisconnectResponse'{status =
if NFstatus =:= undefined -> PFstatus;
true -> NFstatus
end}.
merge_msg_CommandResponse(#'CommandResponse'{status =
PFstatus,
disconnect = PFdisconnect,
stop_streams = PFstop_streams,
streams = PFstreams,
transmissions = PFtransmissions},
#'CommandResponse'{status = NFstatus,
disconnect = NFdisconnect,
stop_streams = NFstop_streams,
streams = NFstreams,
transmissions = NFtransmissions},
TrUserData) ->
#'CommandResponse'{status =
if NFstatus =:= undefined -> PFstatus;
true -> NFstatus
end,
disconnect =
if NFdisconnect =:= undefined -> PFdisconnect;
true -> NFdisconnect
end,
stop_streams =
if NFstop_streams =:= undefined -> PFstop_streams;
true -> NFstop_streams
end,
streams = 'erlang_++'(PFstreams, NFstreams, TrUserData),
transmissions =
'erlang_++'(PFtransmissions, NFtransmissions,
TrUserData)}.
merge_msg_CommandMessage(#'CommandMessage'{command =
PFcommand,
identifier = PFidentifier,
connection_identifiers =
PFconnection_identifiers,
data = PFdata},
#'CommandMessage'{command = NFcommand,
identifier = NFidentifier,
connection_identifiers =
NFconnection_identifiers,
data = NFdata},
_) ->
#'CommandMessage'{command =
if NFcommand =:= undefined -> PFcommand;
true -> NFcommand
end,
identifier =
if NFidentifier =:= undefined -> PFidentifier;
true -> NFidentifier
end,
connection_identifiers =
if NFconnection_identifiers =:= undefined ->
PFconnection_identifiers;
true -> NFconnection_identifiers
end,
data =
if NFdata =:= undefined -> PFdata;
true -> NFdata
end}.
merge_msg_ConnectionResponse(#'ConnectionResponse'{status
= PFstatus,
identifiers = PFidentifiers,
transmissions =
PFtransmissions},
#'ConnectionResponse'{status = NFstatus,
identifiers = NFidentifiers,
transmissions =
NFtransmissions},
TrUserData) ->
#'ConnectionResponse'{status =
if NFstatus =:= undefined -> PFstatus;
true -> NFstatus
end,
identifiers =
if NFidentifiers =:= undefined -> PFidentifiers;
true -> NFidentifiers
end,
transmissions =
'erlang_++'(PFtransmissions, NFtransmissions,
TrUserData)}.
merge_msg_ConnectionRequest(#'ConnectionRequest'{path =
PFpath,
headers = PFheaders},
#'ConnectionRequest'{path = NFpath,
headers = NFheaders},
TrUserData) ->
#'ConnectionRequest'{path =
if NFpath =:= undefined -> PFpath;
true -> NFpath
end,
headers =
'tr_merge_ConnectionRequest.headers'(PFheaders,
NFheaders,
TrUserData)}.
merge_msg_DisconnectRequest(#'DisconnectRequest'{identifiers
= PFidentifiers,
subscriptions =
PFsubscriptions,
path = PFpath,
headers = PFheaders},
#'DisconnectRequest'{identifiers = NFidentifiers,
subscriptions =
NFsubscriptions,
path = NFpath,
headers = NFheaders},
TrUserData) ->
#'DisconnectRequest'{identifiers =
if NFidentifiers =:= undefined -> PFidentifiers;
true -> NFidentifiers
end,
subscriptions =
'erlang_++'(PFsubscriptions, NFsubscriptions,
TrUserData),
path =
if NFpath =:= undefined -> PFpath;
true -> NFpath
end,
headers =
'tr_merge_DisconnectRequest.headers'(PFheaders,
NFheaders,
TrUserData)}.
verify_msg(Msg) -> verify_msg(Msg, []).
verify_msg(Msg, Opts) ->
TrUserData = proplists:get_value(user_data, Opts),
case Msg of
#'DisconnectResponse'{} ->
v_msg_DisconnectResponse(Msg, ['DisconnectResponse'],
TrUserData);
#'CommandResponse'{} ->
v_msg_CommandResponse(Msg, ['CommandResponse'],
TrUserData);
#'CommandMessage'{} ->
v_msg_CommandMessage(Msg, ['CommandMessage'],
TrUserData);
#'ConnectionResponse'{} ->
v_msg_ConnectionResponse(Msg, ['ConnectionResponse'],
TrUserData);
#'ConnectionRequest'{} ->
v_msg_ConnectionRequest(Msg, ['ConnectionRequest'],
TrUserData);
#'DisconnectRequest'{} ->
v_msg_DisconnectRequest(Msg, ['DisconnectRequest'],
TrUserData);
_ -> mk_type_error(not_a_known_message, Msg, [])
end.
-dialyzer({nowarn_function,v_msg_DisconnectResponse/3}).
v_msg_DisconnectResponse(#'DisconnectResponse'{status =
F1},
Path, _) ->
if F1 == undefined -> ok;
true -> v_enum_Status(F1, [status | Path])
end,
ok.
-dialyzer({nowarn_function,v_msg_CommandResponse/3}).
v_msg_CommandResponse(#'CommandResponse'{status = F1,
disconnect = F2, stop_streams = F3,
streams = F4, transmissions = F5},
Path, _) ->
if F1 == undefined -> ok;
true -> v_enum_Status(F1, [status | Path])
end,
if F2 == undefined -> ok;
true -> v_type_bool(F2, [disconnect | Path])
end,
if F3 == undefined -> ok;
true -> v_type_bool(F3, [stop_streams | Path])
end,
if is_list(F4) ->
_ = [v_type_string(Elem, [streams | Path])
|| Elem <- F4],
ok;
true ->
mk_type_error({invalid_list_of, string}, F4, Path)
end,
if is_list(F5) ->
_ = [v_type_string(Elem, [transmissions | Path])
|| Elem <- F5],
ok;
true ->
mk_type_error({invalid_list_of, string}, F5, Path)
end,
ok.
-dialyzer({nowarn_function,v_msg_CommandMessage/3}).
v_msg_CommandMessage(#'CommandMessage'{command = F1,
identifier = F2,
connection_identifiers = F3, data = F4},
Path, _) ->
if F1 == undefined -> ok;
true -> v_type_string(F1, [command | Path])
end,
if F2 == undefined -> ok;
true -> v_type_string(F2, [identifier | Path])
end,
if F3 == undefined -> ok;
true ->
v_type_string(F3, [connection_identifiers | Path])
end,
if F4 == undefined -> ok;
true -> v_type_string(F4, [data | Path])
end,
ok.
-dialyzer({nowarn_function,v_msg_ConnectionResponse/3}).
v_msg_ConnectionResponse(#'ConnectionResponse'{status =
F1,
identifiers = F2,
transmissions = F3},
Path, _) ->
if F1 == undefined -> ok;
true -> v_enum_Status(F1, [status | Path])
end,
if F2 == undefined -> ok;
true -> v_type_string(F2, [identifiers | Path])
end,
if is_list(F3) ->
_ = [v_type_string(Elem, [transmissions | Path])
|| Elem <- F3],
ok;
true ->
mk_type_error({invalid_list_of, string}, F3, Path)
end,
ok.
-dialyzer({nowarn_function,v_msg_ConnectionRequest/3}).
v_msg_ConnectionRequest(#'ConnectionRequest'{path = F1,
headers = F2},
Path, TrUserData) ->
if F1 == undefined -> ok;
true -> v_type_string(F1, [path | Path])
end,
'v_map<string,string>'(F2, [headers | Path],
TrUserData),
ok.
-dialyzer({nowarn_function,v_msg_DisconnectRequest/3}).
v_msg_DisconnectRequest(#'DisconnectRequest'{identifiers
= F1,
subscriptions = F2, path = F3,
headers = F4},
Path, TrUserData) ->
if F1 == undefined -> ok;
true -> v_type_string(F1, [identifiers | Path])
end,
if is_list(F2) ->
_ = [v_type_string(Elem, [subscriptions | Path])
|| Elem <- F2],
ok;
true ->
mk_type_error({invalid_list_of, string}, F2, Path)
end,
if F3 == undefined -> ok;
true -> v_type_string(F3, [path | Path])
end,
'v_map<string,string>'(F4, [headers | Path],
TrUserData),
ok.
-dialyzer({nowarn_function,v_enum_Status/2}).
v_enum_Status('ERROR', _Path) -> ok;
v_enum_Status('SUCCESS', _Path) -> ok;
v_enum_Status(V, Path) when is_integer(V) ->
v_type_sint32(V, Path);
v_enum_Status(X, Path) ->
mk_type_error({invalid_enum, 'Status'}, X, Path).
-dialyzer({nowarn_function,v_type_sint32/2}).
v_type_sint32(N, _Path)
when -2147483648 =< N, N =< 2147483647 ->
ok;
v_type_sint32(N, Path) when is_integer(N) ->
mk_type_error({value_out_of_range, sint32, signed, 32},
N, Path);
v_type_sint32(X, Path) ->
mk_type_error({bad_integer, sint32, signed, 32}, X,
Path).
-dialyzer({nowarn_function,v_type_bool/2}).
v_type_bool(false, _Path) -> ok;
v_type_bool(true, _Path) -> ok;
v_type_bool(0, _Path) -> ok;
v_type_bool(1, _Path) -> ok;
v_type_bool(X, Path) ->
mk_type_error(bad_boolean_value, X, Path).
-dialyzer({nowarn_function,v_type_string/2}).
v_type_string(S, Path) when is_list(S); is_binary(S) ->
try unicode:characters_to_binary(S) of
B when is_binary(B) -> ok;
{error, _, _} ->
mk_type_error(bad_unicode_string, S, Path)
catch
error:badarg ->
mk_type_error(bad_unicode_string, S, Path)
end;
v_type_string(X, Path) ->
mk_type_error(bad_unicode_string, X, Path).
-dialyzer({nowarn_function,'v_map<string,string>'/3}).
'v_map<string,string>'(KVs, Path, _)
when is_list(KVs) ->
[case X of
{Key, Value} ->
v_type_string(Key, [key | Path]),
v_type_string(Value, [value | Path]);
_ -> mk_type_error(invalid_key_value_tuple, X, Path)
end
|| X <- KVs],
ok;
'v_map<string,string>'(X, Path, _TrUserData) ->
mk_type_error(invalid_list_of_key_value_tuples, X,
Path).
-spec mk_type_error(_, _, list()) -> no_return().
mk_type_error(Error, ValueSeen, Path) ->
Path2 = prettify_path(Path),
erlang:error({gpb_type_error,
{Error, [{value, ValueSeen}, {path, Path2}]}}).
prettify_path([]) -> top_level;
prettify_path(PathR) ->
list_to_atom(string:join(lists:map(fun atom_to_list/1,
lists:reverse(PathR)),
".")).
-compile({nowarn_unused_function,id/2}).
-compile({inline,id/2}).
id(X, _TrUserData) -> X.
-compile({nowarn_unused_function,cons/3}).
-compile({inline,cons/3}).
cons(Elem, Acc, _TrUserData) -> [Elem | Acc].
-compile({nowarn_unused_function,lists_reverse/2}).
-compile({inline,lists_reverse/2}).
'lists_reverse'(L, _TrUserData) -> lists:reverse(L).
-compile({nowarn_unused_function,'erlang_++'/3}).
-compile({inline,'erlang_++'/3}).
'erlang_++'(A, B, _TrUserData) -> A ++ B.
-compile({inline,'tr_decode_init_default_ConnectionRequest.headers'/2}).
'tr_decode_init_default_ConnectionRequest.headers'(_,
_) ->
mt_empty_map_r().
-compile({inline,'tr_decode_repeated_add_elem_ConnectionRequest.headers'/3}).
'tr_decode_repeated_add_elem_ConnectionRequest.headers'(Elem,
L, _) ->
mt_add_item_r(Elem, L).
-compile({inline,'tr_decode_repeated_finalize_ConnectionRequest.headers'/2}).
'tr_decode_repeated_finalize_ConnectionRequest.headers'(L,
_) ->
mt_finalize_items_r(L).
-compile({inline,'tr_merge_ConnectionRequest.headers'/3}).
'tr_merge_ConnectionRequest.headers'(X1, X2, _) ->
mt_merge_maptuples_r(X1, X2).
-compile({inline,'tr_decode_init_default_DisconnectRequest.headers'/2}).
'tr_decode_init_default_DisconnectRequest.headers'(_,
_) ->
mt_empty_map_r().
-compile({inline,'tr_decode_repeated_add_elem_DisconnectRequest.headers'/3}).
'tr_decode_repeated_add_elem_DisconnectRequest.headers'(Elem,
L, _) ->
mt_add_item_r(Elem, L).
-compile({inline,'tr_decode_repeated_finalize_DisconnectRequest.headers'/2}).
'tr_decode_repeated_finalize_DisconnectRequest.headers'(L,
_) ->
mt_finalize_items_r(L).
-compile({inline,'tr_merge_DisconnectRequest.headers'/3}).
'tr_merge_DisconnectRequest.headers'(X1, X2, _) ->
mt_merge_maptuples_r(X1, X2).
-compile({inline,'tr_encode_ConnectionRequest.headers[x]'/2}).
'tr_encode_ConnectionRequest.headers[x]'(X, _) ->
mt_maptuple_to_pseudomsg_r(X, 'map<string,string>').
-compile({inline,'tr_encode_DisconnectRequest.headers[x]'/2}).
'tr_encode_DisconnectRequest.headers[x]'(X, _) ->
mt_maptuple_to_pseudomsg_r(X, 'map<string,string>').
-compile({inline,mt_maptuple_to_pseudomsg_r/2}).
mt_maptuple_to_pseudomsg_r({K, V}, RName) ->
{RName, K, V}.
-compile({inline,mt_empty_map_r/0}).
mt_empty_map_r() -> dict:new().
-compile({inline,mt_add_item_r/2}).
mt_add_item_r({_RName, K, V}, D) -> dict:store(K, V, D).
-compile({inline,mt_finalize_items_r/1}).
mt_finalize_items_r(D) -> dict:to_list(D).
-compile({inline,mt_merge_maptuples_r/2}).
mt_merge_maptuples_r(L1, L2) ->
dict:to_list(dict:merge(fun (_Key, _V1, V2) -> V2 end,
dict:from_list(L1), dict:from_list(L2))).
get_msg_defs() ->
[{{enum, 'Status'}, [{'ERROR', 0}, {'SUCCESS', 1}]},
{{msg, 'DisconnectResponse'},
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []}]},
{{msg, 'CommandResponse'},
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = disconnect, fnum = 2, rnum = 3,
type = bool, occurrence = optional, opts = []},
#field{name = stop_streams, fnum = 3, rnum = 4,
type = bool, occurrence = optional, opts = []},
#field{name = streams, fnum = 4, rnum = 5,
type = string, occurrence = repeated, opts = []},
#field{name = transmissions, fnum = 5, rnum = 6,
type = string, occurrence = repeated, opts = []}]},
{{msg, 'CommandMessage'},
[#field{name = command, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = identifier, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = connection_identifiers, fnum = 3,
rnum = 4, type = string, occurrence = optional,
opts = []},
#field{name = data, fnum = 4, rnum = 5, type = string,
occurrence = optional, opts = []}]},
{{msg, 'ConnectionResponse'},
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = identifiers, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = transmissions, fnum = 3, rnum = 4,
type = string, occurrence = repeated, opts = []}]},
{{msg, 'ConnectionRequest'},
[#field{name = path, fnum = 1, rnum = 2, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 2, rnum = 3,
type = {map, string, string}, occurrence = repeated,
opts = []}]},
{{msg, 'DisconnectRequest'},
[#field{name = identifiers, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = subscriptions, fnum = 2, rnum = 3,
type = string, occurrence = repeated, opts = []},
#field{name = path, fnum = 3, rnum = 4, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 4, rnum = 5,
type = {map, string, string}, occurrence = repeated,
opts = []}]}].
get_msg_names() ->
['DisconnectResponse', 'CommandResponse',
'CommandMessage', 'ConnectionResponse',
'ConnectionRequest', 'DisconnectRequest'].
get_enum_names() -> ['Status'].
fetch_msg_def(MsgName) ->
case find_msg_def(MsgName) of
Fs when is_list(Fs) -> Fs;
error -> erlang:error({no_such_msg, MsgName})
end.
fetch_enum_def(EnumName) ->
case find_enum_def(EnumName) of
Es when is_list(Es) -> Es;
error -> erlang:error({no_such_enum, EnumName})
end.
find_msg_def('DisconnectResponse') ->
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []}];
find_msg_def('CommandResponse') ->
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = disconnect, fnum = 2, rnum = 3,
type = bool, occurrence = optional, opts = []},
#field{name = stop_streams, fnum = 3, rnum = 4,
type = bool, occurrence = optional, opts = []},
#field{name = streams, fnum = 4, rnum = 5,
type = string, occurrence = repeated, opts = []},
#field{name = transmissions, fnum = 5, rnum = 6,
type = string, occurrence = repeated, opts = []}];
find_msg_def('CommandMessage') ->
[#field{name = command, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = identifier, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = connection_identifiers, fnum = 3,
rnum = 4, type = string, occurrence = optional,
opts = []},
#field{name = data, fnum = 4, rnum = 5, type = string,
occurrence = optional, opts = []}];
find_msg_def('ConnectionResponse') ->
[#field{name = status, fnum = 1, rnum = 2,
type = {enum, 'Status'}, occurrence = optional,
opts = []},
#field{name = identifiers, fnum = 2, rnum = 3,
type = string, occurrence = optional, opts = []},
#field{name = transmissions, fnum = 3, rnum = 4,
type = string, occurrence = repeated, opts = []}];
find_msg_def('ConnectionRequest') ->
[#field{name = path, fnum = 1, rnum = 2, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 2, rnum = 3,
type = {map, string, string}, occurrence = repeated,
opts = []}];
find_msg_def('DisconnectRequest') ->
[#field{name = identifiers, fnum = 1, rnum = 2,
type = string, occurrence = optional, opts = []},
#field{name = subscriptions, fnum = 2, rnum = 3,
type = string, occurrence = repeated, opts = []},
#field{name = path, fnum = 3, rnum = 4, type = string,
occurrence = optional, opts = []},
#field{name = headers, fnum = 4, rnum = 5,
type = {map, string, string}, occurrence = repeated,
opts = []}];
find_msg_def(_) -> error.
find_enum_def('Status') ->
[{'ERROR', 0}, {'SUCCESS', 1}];
find_enum_def(_) -> error.
enum_symbol_by_value('Status', Value) ->
enum_symbol_by_value_Status(Value).
enum_value_by_symbol('Status', Sym) ->
enum_value_by_symbol_Status(Sym).
enum_symbol_by_value_Status(0) -> 'ERROR';
enum_symbol_by_value_Status(1) -> 'SUCCESS'.
enum_value_by_symbol_Status('ERROR') -> 0;
enum_value_by_symbol_Status('SUCCESS') -> 1.
get_service_names() -> [].
get_service_def(_) -> error.
get_rpc_names(_) -> error.
find_rpc_def(_, _) -> error.
-spec fetch_rpc_def(_, _) -> no_return().
fetch_rpc_def(ServiceName, RpcName) ->
erlang:error({no_such_rpc, ServiceName, RpcName}).
get_package_name() -> anycable.
gpb_version_as_string() ->
"3.24.4".
gpb_version_as_list() ->
[3,24,4].
|
215d042a7b67fca23c6af3c1a9cc56163bef910922f0c79344ec118831cc6f5e | onedata/op-worker | atm_workflow_execution_api.erl | %%%-------------------------------------------------------------------
@author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% API module for performing operations on automation workflow executions.
%%% An execution is created according to specified automation workflow schema
%%% revision - to learn more about overall workflow concept @see automation.erl
Those schemas ( workflow and all used lambdas ) are fetched from Onezone and
%%% saved at the beginning of execution (they can be changed so to ensure proper
%%% execution snapshot of concrete version must be made).
%%% Automation workflow execution consists of execution of lanes each of which
is made of one or more runs . Lane execution * run * is an attempt of execution
%%% of particular lane schema. A run may fail and then a new run is created for
%%% this lane - up to max retries limit specified in schema. With this (new run
%%% is created rather than clearing and restarting the failed one) it is possible
%%% to view details of all lane execution runs.
%%% Beside automatic retries lanes can also be repeated after execution ended.
Two types of manual repeat is supported :
%%% - retry - new lane run execution is created for retried lane which will
%%% operate only on failed items.
%%% - rerun - new lane run execution is created for rerun lane which will
%%% operate on all items from iterated store.
%%% When repeating lanes entire workflow execution is started anew (new workflow
%%% execution incarnation) but it is not cleared from accumulated data
%%% (e.g. store content).
%%% To learn more about stages of execution:
%%% - @see atm_workflow_execution_status.erl - for overall workflow execution
%%% - @see atm_lane_execution_status.erl - for particular lane execution
%%% - @see atm_task_execution_handler.erl - for particular task execution
%%% @end
%%%-------------------------------------------------------------------
-module(atm_workflow_execution_api).
-author("Bartosz Walkowicz").
-include("modules/automation/atm_execution.hrl").
-include_lib("ctool/include/errors.hrl").
-include_lib("ctool/include/logging.hrl").
%% API
-export([
init_engine/0
]).
-export([
list/4,
foreach/3,
foldl/4
]).
-export([
schedule/6,
get/1, get_summary/2,
init_cancel/2,
init_pause/2,
resume/2,
repeat/4,
discard/1
]).
-export([report_openfaas_down/2]).
-type listing_mode() :: basic | summary.
-type basic_entries() :: atm_workflow_executions_forest:entries().
-type summary_entries() :: [{atm_workflow_executions_forest:index(), atm_workflow_execution:summary()}].
-type entries() :: basic_entries() | summary_entries().
-type store_initial_content_overlay() :: #{AtmStoreSchemaId :: automation:id() => json_utils:json_term()}.
-export_type([listing_mode/0, basic_entries/0, summary_entries/0, entries/0]).
-export_type([store_initial_content_overlay/0]).
%%%===================================================================
%%% API
%%%===================================================================
-spec init_engine() -> ok.
init_engine() ->
atm_workflow_execution_handler:init_engine().
-spec list(
od_space:id(),
atm_workflow_execution:phase(),
listing_mode(),
atm_workflow_executions_forest:listing_opts()
) ->
{ok, entries(), IsLast :: boolean()}.
list(SpaceId, Phase, basic, ListingOpts) ->
AtmWorkflowExecutionBasicEntries = list_basic_entries(SpaceId, Phase, ListingOpts),
IsLast = maps:get(limit, ListingOpts) > length(AtmWorkflowExecutionBasicEntries),
{ok, AtmWorkflowExecutionBasicEntries, IsLast};
list(SpaceId, Phase, summary, ListingOpts) ->
AtmWorkflowExecutionBasicEntries = list_basic_entries(SpaceId, Phase, ListingOpts),
IsLast = maps:get(limit, ListingOpts) > length(AtmWorkflowExecutionBasicEntries),
AtmWorkflowExecutionSummaryEntries = lists_utils:pfiltermap(fun({Index, AtmWorkflowExecutionId}) ->
{ok, #document{value = AtmWorkflowExecution}} = atm_workflow_execution:get(
AtmWorkflowExecutionId
),
case atm_workflow_execution_status:infer_phase(AtmWorkflowExecution) of
Phase ->
{true, {Index, get_summary(AtmWorkflowExecutionId, AtmWorkflowExecution)}};
_ ->
false
end
end, AtmWorkflowExecutionBasicEntries),
{ok, AtmWorkflowExecutionSummaryEntries, IsLast}.
-spec foreach(
od_space:id(),
atm_workflow_execution:phase(),
fun((atm_workflow_execution:id()) -> term())
) ->
ok.
foreach(SpaceId, Phase, Callback) ->
foldl(SpaceId, Phase, fun(AtmWorkflowExecutionId, _) -> Callback(AtmWorkflowExecutionId) end, ok),
ok.
-spec foldl(
od_space:id(),
atm_workflow_execution:phase(),
fun((atm_workflow_execution:id(), AccIn :: term()) -> AccOut :: term()),
InitialAcc :: term()
) ->
term().
foldl(SpaceId, Phase, Callback, InitialAcc) ->
foldl(SpaceId, Phase, Callback, InitialAcc, #{limit => 1000, start_index => <<>>}).
-spec schedule(
user_ctx:ctx(),
od_space:id(),
od_atm_workflow_schema:id(),
atm_workflow_schema_revision:revision_number(),
store_initial_content_overlay(),
undefined | http_client:url()
) ->
{atm_workflow_execution:id(), atm_workflow_execution:record()} | no_return().
schedule(
UserCtx,
SpaceId,
AtmWorkflowSchemaId,
AtmWorkflowSchemaRevisionNum,
AtmStoreInitialContentOverlay,
CallbackUrl
) ->
{AtmWorkflowExecutionDoc, AtmWorkflowExecutionEnv} = atm_workflow_execution_factory:create(
UserCtx,
SpaceId,
AtmWorkflowSchemaId,
AtmWorkflowSchemaRevisionNum,
AtmStoreInitialContentOverlay,
CallbackUrl
),
atm_workflow_execution_handler:start(UserCtx, AtmWorkflowExecutionEnv, AtmWorkflowExecutionDoc),
{AtmWorkflowExecutionDoc#document.key, AtmWorkflowExecutionDoc#document.value}.
-spec get(atm_workflow_execution:id()) ->
{ok, atm_workflow_execution:record()} | ?ERROR_NOT_FOUND.
get(AtmWorkflowExecutionId) ->
case atm_workflow_execution:get(AtmWorkflowExecutionId) of
{ok, #document{value = AtmWorkflowExecution}} ->
{ok, AtmWorkflowExecution};
?ERROR_NOT_FOUND ->
?ERROR_NOT_FOUND
end.
-spec get_summary(atm_workflow_execution:id(), atm_workflow_execution:record()) ->
atm_workflow_execution:summary().
get_summary(AtmWorkflowExecutionId, #atm_workflow_execution{
name = Name,
schema_snapshot_id = AtmWorkflowSchemaSnapshotId,
atm_inventory_id = AtmInventoryId,
status = AtmWorkflowExecutionStatus,
schedule_time = ScheduleTime,
start_time = StartTime,
suspend_time = SuspendTime,
finish_time = FinishTime
}) ->
{ok, #document{
value = #atm_workflow_schema_snapshot{
revision_number = RevisionNum
}
}} = atm_workflow_schema_snapshot:get(AtmWorkflowSchemaSnapshotId),
#atm_workflow_execution_summary{
atm_workflow_execution_id = AtmWorkflowExecutionId,
name = Name,
atm_workflow_schema_revision_num = RevisionNum,
atm_inventory_id = AtmInventoryId,
status = AtmWorkflowExecutionStatus,
schedule_time = ScheduleTime,
start_time = StartTime,
suspend_time = SuspendTime,
finish_time = FinishTime
}.
-spec init_cancel(user_ctx:ctx(), atm_workflow_execution:id()) -> ok | errors:error().
init_cancel(UserCtx, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:init_stop(UserCtx, AtmWorkflowExecutionId, cancel).
-spec init_pause(user_ctx:ctx(), atm_workflow_execution:id()) -> ok | errors:error().
init_pause(UserCtx, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:init_stop(UserCtx, AtmWorkflowExecutionId, pause).
-spec resume(user_ctx:ctx(), atm_workflow_execution:id()) -> ok | errors:error().
resume(UserCtx, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:resume(UserCtx, AtmWorkflowExecutionId).
-spec repeat(
user_ctx:ctx(),
atm_workflow_execution:repeat_type(),
atm_lane_execution:lane_run_selector(),
atm_workflow_execution:id()
) ->
ok | errors:error().
repeat(UserCtx, Type, AtmLaneRunSelector, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:repeat(
UserCtx, Type, AtmLaneRunSelector, AtmWorkflowExecutionId
).
-spec discard(atm_workflow_execution:id()) -> ok | errors:error().
discard(AtmWorkflowExecutionId) ->
atm_workflow_execution_status:handle_discard(AtmWorkflowExecutionId).
-spec report_openfaas_down(od_space:id(), errors:error()) -> ok.
report_openfaas_down(SpaceId, Error) ->
CallbackFun = fun(AtmWorkflowExecutionId) ->
try
atm_workflow_execution_handler:on_openfaas_down(AtmWorkflowExecutionId, Error)
catch Type:Reason:Stacktrace ->
?examine_exception(Type, Reason, Stacktrace)
end
end,
foreach(SpaceId, ?WAITING_PHASE, CallbackFun),
foreach(SpaceId, ?ONGOING_PHASE, CallbackFun).
%%%===================================================================
Internal functions
%%%===================================================================
@private
-spec list_basic_entries(
od_space:id(),
atm_workflow_execution:phase(),
atm_workflow_executions_forest:listing_opts()
) ->
basic_entries().
list_basic_entries(SpaceId, ?WAITING_PHASE, ListingOpts) ->
atm_waiting_workflow_executions:list(SpaceId, ListingOpts);
list_basic_entries(SpaceId, ?ONGOING_PHASE, ListingOpts) ->
atm_ongoing_workflow_executions:list(SpaceId, ListingOpts);
list_basic_entries(SpaceId, ?SUSPENDED_PHASE, ListingOpts) ->
atm_suspended_workflow_executions:list(SpaceId, ListingOpts);
list_basic_entries(SpaceId, ?ENDED_PHASE, ListingOpts) ->
atm_ended_workflow_executions:list(SpaceId, ListingOpts).
@private
-spec foldl(
od_space:id(),
atm_workflow_execution:phase(),
fun((atm_workflow_execution:id(), AccIn :: term()) -> AccOut :: term()),
InitialAcc :: term(),
atm_workflow_executions_forest:listing_opts()
) ->
term().
foldl(SpaceId, Phase, Callback, InitialAcc, ListingOpts) ->
{ok, AtmWorkflowExecutionBasicEntries, IsLast} = list(SpaceId, Phase, basic, ListingOpts),
{LastEntryIndex, NewAcc} = lists:foldl(fun({Index, AtmWorkflowExecutionId}, {_, AccIn}) ->
{Index, Callback(AtmWorkflowExecutionId, AccIn)}
end, {<<>>, InitialAcc}, AtmWorkflowExecutionBasicEntries),
case IsLast of
true ->
NewAcc;
false ->
foldl(SpaceId, Phase, Callback, NewAcc, ListingOpts#{
start_index => LastEntryIndex, offset => 1
})
end.
| null | https://raw.githubusercontent.com/onedata/op-worker/171b05ac629acb4fc337b7dc2f5bf7c433d2c23f/src/modules/automation/atm_workflow_execution_api.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
API module for performing operations on automation workflow executions.
An execution is created according to specified automation workflow schema
revision - to learn more about overall workflow concept @see automation.erl
saved at the beginning of execution (they can be changed so to ensure proper
execution snapshot of concrete version must be made).
Automation workflow execution consists of execution of lanes each of which
of particular lane schema. A run may fail and then a new run is created for
this lane - up to max retries limit specified in schema. With this (new run
is created rather than clearing and restarting the failed one) it is possible
to view details of all lane execution runs.
Beside automatic retries lanes can also be repeated after execution ended.
- retry - new lane run execution is created for retried lane which will
operate only on failed items.
- rerun - new lane run execution is created for rerun lane which will
operate on all items from iterated store.
When repeating lanes entire workflow execution is started anew (new workflow
execution incarnation) but it is not cleared from accumulated data
(e.g. store content).
To learn more about stages of execution:
- @see atm_workflow_execution_status.erl - for overall workflow execution
- @see atm_lane_execution_status.erl - for particular lane execution
- @see atm_task_execution_handler.erl - for particular task execution
@end
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
===================================================================
=================================================================== | @author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
Those schemas ( workflow and all used lambdas ) are fetched from Onezone and
is made of one or more runs . Lane execution * run * is an attempt of execution
Two types of manual repeat is supported :
-module(atm_workflow_execution_api).
-author("Bartosz Walkowicz").
-include("modules/automation/atm_execution.hrl").
-include_lib("ctool/include/errors.hrl").
-include_lib("ctool/include/logging.hrl").
-export([
init_engine/0
]).
-export([
list/4,
foreach/3,
foldl/4
]).
-export([
schedule/6,
get/1, get_summary/2,
init_cancel/2,
init_pause/2,
resume/2,
repeat/4,
discard/1
]).
-export([report_openfaas_down/2]).
-type listing_mode() :: basic | summary.
-type basic_entries() :: atm_workflow_executions_forest:entries().
-type summary_entries() :: [{atm_workflow_executions_forest:index(), atm_workflow_execution:summary()}].
-type entries() :: basic_entries() | summary_entries().
-type store_initial_content_overlay() :: #{AtmStoreSchemaId :: automation:id() => json_utils:json_term()}.
-export_type([listing_mode/0, basic_entries/0, summary_entries/0, entries/0]).
-export_type([store_initial_content_overlay/0]).
-spec init_engine() -> ok.
init_engine() ->
atm_workflow_execution_handler:init_engine().
-spec list(
od_space:id(),
atm_workflow_execution:phase(),
listing_mode(),
atm_workflow_executions_forest:listing_opts()
) ->
{ok, entries(), IsLast :: boolean()}.
list(SpaceId, Phase, basic, ListingOpts) ->
AtmWorkflowExecutionBasicEntries = list_basic_entries(SpaceId, Phase, ListingOpts),
IsLast = maps:get(limit, ListingOpts) > length(AtmWorkflowExecutionBasicEntries),
{ok, AtmWorkflowExecutionBasicEntries, IsLast};
list(SpaceId, Phase, summary, ListingOpts) ->
AtmWorkflowExecutionBasicEntries = list_basic_entries(SpaceId, Phase, ListingOpts),
IsLast = maps:get(limit, ListingOpts) > length(AtmWorkflowExecutionBasicEntries),
AtmWorkflowExecutionSummaryEntries = lists_utils:pfiltermap(fun({Index, AtmWorkflowExecutionId}) ->
{ok, #document{value = AtmWorkflowExecution}} = atm_workflow_execution:get(
AtmWorkflowExecutionId
),
case atm_workflow_execution_status:infer_phase(AtmWorkflowExecution) of
Phase ->
{true, {Index, get_summary(AtmWorkflowExecutionId, AtmWorkflowExecution)}};
_ ->
false
end
end, AtmWorkflowExecutionBasicEntries),
{ok, AtmWorkflowExecutionSummaryEntries, IsLast}.
-spec foreach(
od_space:id(),
atm_workflow_execution:phase(),
fun((atm_workflow_execution:id()) -> term())
) ->
ok.
foreach(SpaceId, Phase, Callback) ->
foldl(SpaceId, Phase, fun(AtmWorkflowExecutionId, _) -> Callback(AtmWorkflowExecutionId) end, ok),
ok.
-spec foldl(
od_space:id(),
atm_workflow_execution:phase(),
fun((atm_workflow_execution:id(), AccIn :: term()) -> AccOut :: term()),
InitialAcc :: term()
) ->
term().
foldl(SpaceId, Phase, Callback, InitialAcc) ->
foldl(SpaceId, Phase, Callback, InitialAcc, #{limit => 1000, start_index => <<>>}).
-spec schedule(
user_ctx:ctx(),
od_space:id(),
od_atm_workflow_schema:id(),
atm_workflow_schema_revision:revision_number(),
store_initial_content_overlay(),
undefined | http_client:url()
) ->
{atm_workflow_execution:id(), atm_workflow_execution:record()} | no_return().
schedule(
UserCtx,
SpaceId,
AtmWorkflowSchemaId,
AtmWorkflowSchemaRevisionNum,
AtmStoreInitialContentOverlay,
CallbackUrl
) ->
{AtmWorkflowExecutionDoc, AtmWorkflowExecutionEnv} = atm_workflow_execution_factory:create(
UserCtx,
SpaceId,
AtmWorkflowSchemaId,
AtmWorkflowSchemaRevisionNum,
AtmStoreInitialContentOverlay,
CallbackUrl
),
atm_workflow_execution_handler:start(UserCtx, AtmWorkflowExecutionEnv, AtmWorkflowExecutionDoc),
{AtmWorkflowExecutionDoc#document.key, AtmWorkflowExecutionDoc#document.value}.
-spec get(atm_workflow_execution:id()) ->
{ok, atm_workflow_execution:record()} | ?ERROR_NOT_FOUND.
get(AtmWorkflowExecutionId) ->
case atm_workflow_execution:get(AtmWorkflowExecutionId) of
{ok, #document{value = AtmWorkflowExecution}} ->
{ok, AtmWorkflowExecution};
?ERROR_NOT_FOUND ->
?ERROR_NOT_FOUND
end.
-spec get_summary(atm_workflow_execution:id(), atm_workflow_execution:record()) ->
atm_workflow_execution:summary().
get_summary(AtmWorkflowExecutionId, #atm_workflow_execution{
name = Name,
schema_snapshot_id = AtmWorkflowSchemaSnapshotId,
atm_inventory_id = AtmInventoryId,
status = AtmWorkflowExecutionStatus,
schedule_time = ScheduleTime,
start_time = StartTime,
suspend_time = SuspendTime,
finish_time = FinishTime
}) ->
{ok, #document{
value = #atm_workflow_schema_snapshot{
revision_number = RevisionNum
}
}} = atm_workflow_schema_snapshot:get(AtmWorkflowSchemaSnapshotId),
#atm_workflow_execution_summary{
atm_workflow_execution_id = AtmWorkflowExecutionId,
name = Name,
atm_workflow_schema_revision_num = RevisionNum,
atm_inventory_id = AtmInventoryId,
status = AtmWorkflowExecutionStatus,
schedule_time = ScheduleTime,
start_time = StartTime,
suspend_time = SuspendTime,
finish_time = FinishTime
}.
-spec init_cancel(user_ctx:ctx(), atm_workflow_execution:id()) -> ok | errors:error().
init_cancel(UserCtx, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:init_stop(UserCtx, AtmWorkflowExecutionId, cancel).
-spec init_pause(user_ctx:ctx(), atm_workflow_execution:id()) -> ok | errors:error().
init_pause(UserCtx, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:init_stop(UserCtx, AtmWorkflowExecutionId, pause).
-spec resume(user_ctx:ctx(), atm_workflow_execution:id()) -> ok | errors:error().
resume(UserCtx, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:resume(UserCtx, AtmWorkflowExecutionId).
-spec repeat(
user_ctx:ctx(),
atm_workflow_execution:repeat_type(),
atm_lane_execution:lane_run_selector(),
atm_workflow_execution:id()
) ->
ok | errors:error().
repeat(UserCtx, Type, AtmLaneRunSelector, AtmWorkflowExecutionId) ->
atm_workflow_execution_handler:repeat(
UserCtx, Type, AtmLaneRunSelector, AtmWorkflowExecutionId
).
-spec discard(atm_workflow_execution:id()) -> ok | errors:error().
discard(AtmWorkflowExecutionId) ->
atm_workflow_execution_status:handle_discard(AtmWorkflowExecutionId).
-spec report_openfaas_down(od_space:id(), errors:error()) -> ok.
report_openfaas_down(SpaceId, Error) ->
CallbackFun = fun(AtmWorkflowExecutionId) ->
try
atm_workflow_execution_handler:on_openfaas_down(AtmWorkflowExecutionId, Error)
catch Type:Reason:Stacktrace ->
?examine_exception(Type, Reason, Stacktrace)
end
end,
foreach(SpaceId, ?WAITING_PHASE, CallbackFun),
foreach(SpaceId, ?ONGOING_PHASE, CallbackFun).
Internal functions
@private
-spec list_basic_entries(
od_space:id(),
atm_workflow_execution:phase(),
atm_workflow_executions_forest:listing_opts()
) ->
basic_entries().
list_basic_entries(SpaceId, ?WAITING_PHASE, ListingOpts) ->
atm_waiting_workflow_executions:list(SpaceId, ListingOpts);
list_basic_entries(SpaceId, ?ONGOING_PHASE, ListingOpts) ->
atm_ongoing_workflow_executions:list(SpaceId, ListingOpts);
list_basic_entries(SpaceId, ?SUSPENDED_PHASE, ListingOpts) ->
atm_suspended_workflow_executions:list(SpaceId, ListingOpts);
list_basic_entries(SpaceId, ?ENDED_PHASE, ListingOpts) ->
atm_ended_workflow_executions:list(SpaceId, ListingOpts).
@private
-spec foldl(
od_space:id(),
atm_workflow_execution:phase(),
fun((atm_workflow_execution:id(), AccIn :: term()) -> AccOut :: term()),
InitialAcc :: term(),
atm_workflow_executions_forest:listing_opts()
) ->
term().
foldl(SpaceId, Phase, Callback, InitialAcc, ListingOpts) ->
{ok, AtmWorkflowExecutionBasicEntries, IsLast} = list(SpaceId, Phase, basic, ListingOpts),
{LastEntryIndex, NewAcc} = lists:foldl(fun({Index, AtmWorkflowExecutionId}, {_, AccIn}) ->
{Index, Callback(AtmWorkflowExecutionId, AccIn)}
end, {<<>>, InitialAcc}, AtmWorkflowExecutionBasicEntries),
case IsLast of
true ->
NewAcc;
false ->
foldl(SpaceId, Phase, Callback, NewAcc, ListingOpts#{
start_index => LastEntryIndex, offset => 1
})
end.
|
ac4e50a79876eea91770533172c5786c850e10d7201e9b26459bbff5dd3fb3eb | jafingerhut/clojure-benchmarks | spectralnorm.clj | The Computer Language Benchmarks Game
;; /
;;
ported from Java # 2
provided by
(ns spectralnorm
(:import [java.util.concurrent CyclicBarrier]
[clojure.lang Numbers])
(:gen-class))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true)
(defmacro a [i j]
`(/ 1.0 (double (+ (Numbers/unsignedShiftRightInt (* (+ ~i ~j) (+ ~i ~j 1)) 1) (inc ~i)))))
(defn mul-av [^doubles v ^doubles av ^long begin ^long end]
(let [vl (alength v)]
(loop [i begin
j 0
sum 0.0]
(when (< i end)
(if (< j vl)
(recur i (inc j) (+ sum (* (a i j) (aget v j))))
(do
(aset av i sum)
(recur (inc i) 0 0.0)))))))
(defn mul-atv [^doubles v ^doubles atv ^long begin ^long end]
(let [vl (alength v)]
(loop [i begin
j 0
sum 0.0]
(when (< i end)
(if (< j vl)
(recur i (inc j) (+ sum (* (a j i) (aget v j))))
(do
(aset atv i sum)
(recur (inc i) 0 0.0)))))))
(defn approximate [^doubles u ^doubles v ^doubles tmp
begin end ^CyclicBarrier barrier
t ^doubles mvbvs ^doubles mvvs]
(let [begin (long begin)
end (long end)
t (int t)]
(loop [i 0]
(when (< i 10)
(mul-av u tmp begin end)
(.await barrier)
(mul-atv tmp v begin end)
(.await barrier)
(mul-av v tmp begin end)
(.await barrier)
(mul-atv tmp u begin end)
(.await barrier)
(recur (inc i))))
(loop [i begin
mvbv 0.0
mvv 0.0]
(if (< i end)
(let [vi (aget v i)]
(recur (inc i)
(+ mvbv (* (aget u i) vi))
(+ mvv (* vi vi))))
(do
(aset mvbvs t mvbv)
(aset mvvs t mvv))))))
(defn game [^long n]
(let [u (double-array n)
v (double-array n)
tmp (double-array n)
nthread (.availableProcessors (Runtime/getRuntime))
nthread' (dec nthread)
th (object-array nthread)
mvbv (double-array nthread)
mvv (double-array nthread)
barrier (CyclicBarrier. nthread)
chunk (quot n nthread)]
(loop [i 0]
(when (< i n)
(aset u i 1.0)
(recur (inc i))))
(loop [i 0]
(when (< i nthread)
(let [r1 (* i chunk)
r2 (long (if (< i nthread') (+ r1 chunk) n))
thr (Thread. ^Runnable (fn [] (approximate u v tmp r1 r2 barrier i mvbv mvv)))]
(aset th i thr)
(.start thr)
(recur (inc i)))))
(loop [i 0
vBv 0.0
vv 0.0]
(if (< i nthread)
(let [t ^Thread (nth th i)]
(.join t)
(recur (inc i) (+ vBv (aget mvbv i)) (+ vv (aget mvv i))))
(println (format "%.9f" (Math/sqrt (/ vBv vv))))))))
(defn -main [& args]
(let [n (long (if (empty? args)
1000
(Long/parseLong ^String (first args))))]
(game n)))
| null | https://raw.githubusercontent.com/jafingerhut/clojure-benchmarks/474a8a4823727dd371f1baa9809517f9e0b508d4/2017-mar-31-benchmarks-game-site-versions/spectralnorm.clj | clojure | /
| The Computer Language Benchmarks Game
ported from Java # 2
provided by
(ns spectralnorm
(:import [java.util.concurrent CyclicBarrier]
[clojure.lang Numbers])
(:gen-class))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true)
(defmacro a [i j]
`(/ 1.0 (double (+ (Numbers/unsignedShiftRightInt (* (+ ~i ~j) (+ ~i ~j 1)) 1) (inc ~i)))))
(defn mul-av [^doubles v ^doubles av ^long begin ^long end]
(let [vl (alength v)]
(loop [i begin
j 0
sum 0.0]
(when (< i end)
(if (< j vl)
(recur i (inc j) (+ sum (* (a i j) (aget v j))))
(do
(aset av i sum)
(recur (inc i) 0 0.0)))))))
(defn mul-atv [^doubles v ^doubles atv ^long begin ^long end]
(let [vl (alength v)]
(loop [i begin
j 0
sum 0.0]
(when (< i end)
(if (< j vl)
(recur i (inc j) (+ sum (* (a j i) (aget v j))))
(do
(aset atv i sum)
(recur (inc i) 0 0.0)))))))
(defn approximate [^doubles u ^doubles v ^doubles tmp
begin end ^CyclicBarrier barrier
t ^doubles mvbvs ^doubles mvvs]
(let [begin (long begin)
end (long end)
t (int t)]
(loop [i 0]
(when (< i 10)
(mul-av u tmp begin end)
(.await barrier)
(mul-atv tmp v begin end)
(.await barrier)
(mul-av v tmp begin end)
(.await barrier)
(mul-atv tmp u begin end)
(.await barrier)
(recur (inc i))))
(loop [i begin
mvbv 0.0
mvv 0.0]
(if (< i end)
(let [vi (aget v i)]
(recur (inc i)
(+ mvbv (* (aget u i) vi))
(+ mvv (* vi vi))))
(do
(aset mvbvs t mvbv)
(aset mvvs t mvv))))))
(defn game [^long n]
(let [u (double-array n)
v (double-array n)
tmp (double-array n)
nthread (.availableProcessors (Runtime/getRuntime))
nthread' (dec nthread)
th (object-array nthread)
mvbv (double-array nthread)
mvv (double-array nthread)
barrier (CyclicBarrier. nthread)
chunk (quot n nthread)]
(loop [i 0]
(when (< i n)
(aset u i 1.0)
(recur (inc i))))
(loop [i 0]
(when (< i nthread)
(let [r1 (* i chunk)
r2 (long (if (< i nthread') (+ r1 chunk) n))
thr (Thread. ^Runnable (fn [] (approximate u v tmp r1 r2 barrier i mvbv mvv)))]
(aset th i thr)
(.start thr)
(recur (inc i)))))
(loop [i 0
vBv 0.0
vv 0.0]
(if (< i nthread)
(let [t ^Thread (nth th i)]
(.join t)
(recur (inc i) (+ vBv (aget mvbv i)) (+ vv (aget mvv i))))
(println (format "%.9f" (Math/sqrt (/ vBv vv))))))))
(defn -main [& args]
(let [n (long (if (empty? args)
1000
(Long/parseLong ^String (first args))))]
(game n)))
|
98a0bdf640d18eeef06f210616baae76950ad6f1b7e57d20cc83c66305eee3a2 | Ramarren/png-read | png-state.lisp | (in-package :png-read)
(defclass png-state ()
((file :accessor png-file :initform nil)
(finished :accessor finished :initform nil)
(width :accessor width)
(height :accessor height)
(bit-depth :accessor bit-depth)
(colour-type :accessor colour-type)
(compression :accessor compression)
(filter-method :accessor filter-method)
(interlace-method :accessor interlace-method)
(palette :accessor palette)
(datastream :accessor datastream :initform nil)
(image-data :accessor image-data)
(index-data :accessor index-data :initform nil)
;ancillaries
(postprocess-ancillaries :accessor postprocess-ancillaries :initform nil)
(transparency :accessor transparency :initform nil)
(gamma :accessor gamma :initform nil)
(significant-bits :accessor significant-bits :initform nil)
(rendering-intent :accessor rendering-intent :initform nil)
(textual-data :accessor textual-data :initform nil)
(preferred-background :accessor preferred-background :initform nil)
(image-histogram :accessor image-histogram :initform nil)
(physical-dimensions :accessor physical-dimensions :initform nil)
(last-modification :accessor last-modification :initform nil)))
(defvar *png-state* nil) | null | https://raw.githubusercontent.com/Ramarren/png-read/ec29f38a689972b9f1373f13bbbcd6b05deada88/png-state.lisp | lisp | ancillaries | (in-package :png-read)
(defclass png-state ()
((file :accessor png-file :initform nil)
(finished :accessor finished :initform nil)
(width :accessor width)
(height :accessor height)
(bit-depth :accessor bit-depth)
(colour-type :accessor colour-type)
(compression :accessor compression)
(filter-method :accessor filter-method)
(interlace-method :accessor interlace-method)
(palette :accessor palette)
(datastream :accessor datastream :initform nil)
(image-data :accessor image-data)
(index-data :accessor index-data :initform nil)
(postprocess-ancillaries :accessor postprocess-ancillaries :initform nil)
(transparency :accessor transparency :initform nil)
(gamma :accessor gamma :initform nil)
(significant-bits :accessor significant-bits :initform nil)
(rendering-intent :accessor rendering-intent :initform nil)
(textual-data :accessor textual-data :initform nil)
(preferred-background :accessor preferred-background :initform nil)
(image-histogram :accessor image-histogram :initform nil)
(physical-dimensions :accessor physical-dimensions :initform nil)
(last-modification :accessor last-modification :initform nil)))
(defvar *png-state* nil) |
09685078b9a85a75c2b35f836fc4e51e5016849e096a5a27271ceb7b90e24d5d | adamliesko/dynamo | vector_clock.erl | -module (vector_clock).
-export ([new/1, fix/2, incr/2, prune/1, diff/2, join/2,leq/2,equal/2]).
-define(PRUNE_LIMIT, 5).
new(Node) -> [{Node, 1}].
resolve key value from two ppossibly different vector clocks
fix({FClock, FValues} = First, {SClock, SValues} = Second) ->
ComparisonResult = diff(FClock,SClock),
case ComparisonResult of
leq ->
Second;
geq ->
First;
eq ->
First;
_ ->
{join(FClock,SClock), FValues ++ SValues}
end.
keytake(Key , N , TupleList1 ) - > { value , Tuple , TupleList2 } | false
%% Searches the list of tuples TupleList1 for a tuple whose Nth element
compares equal to Key . % % Returns { value , Tuple , TupleList2 } if such a tuple
%% is found, otherwise false. TupleList2 is a copy of TupleList1 where the
first occurrence of Tuple has been removed .
%% keymerge(N, TupleList1, TupleList2) -> TupleList3
Returns the sorted list formed by merging TupleList1 and TupleList2 . The
merge is performed on the element of each tuple . Both TupleList1 and
TupleList2 must be key - sorted prior to evaluating this function . When two
%% tuples compare equal, the tuple from TupleList1 is picked before the tuple
%% from TupleList2.
%% keysort(N, TupleList1) -> TupleList2
%% Returns a list containing the sorted elements of the list TupleList1
Sorting is performed on the element of the tuples . The sort is stable .
join(First, Second) ->
join([], First, Second).
join(Acc, [], Second) ->
lists:keysort(1, Acc ++ Second);
join(Acc, First, [] )->
lists:keysort(1, Acc ++ First);
join(Acc, [{FNode, FVersion}|FClock], SClock) ->
case lists:keytake(FNode, 1, SClock) of
{value, {FNode, SVersion}, ClockS} when FVersion > SVersion ->
join([{FNode,FVersion}|Acc],FClock,ClockS);
{value, {FNode, SVersion}, ClockS} ->
join([{FNode,SVersion}|Acc],FClock, ClockS);
false ->
join([{FNode,FVersion}|Acc],FClock,SClock)
end.
%['[email protected]',{'[email protected]',[{'[email protected]',1}]}],
incr(Node, [{Node, Context}|VectorClocks]) ->
[{Node, Context+1}|VectorClocks];
incr(Node, [VectorClock|VectorClocks]) ->
[VectorClock|incr(Node, VectorClocks)];
incr(_Node, []) ->
[{node(), 1}].
equal(First,Second) ->
if length(First) == length(Second) ->
lists:all(fun(FirstClock) -> lists:member(FirstClock,Second) end, First);
true ->
false
end.
%% just helper function which assess the compare result
diff(First,Second) ->
Eq = equal(First,Second),
Leq = leq(First,Second),
Geq = leq(Second,First),
if
Leq -> leq;
Geq -> geq;
Eq -> eq;
true -> to_join
end.
%% check if <=, can be used as => with arg switching
leq(First, Second) ->
%% first vector clock is shorter
Shorter = length(First) < length(Second),
%% it contains the same element but the version is lower
LessOne = less_one(First,Second),
%% if all are less or equal
LessOrEqAll = less_or_eq_all(First,Second),
(Shorter or LessOne) and LessOrEqAll.
is there one , whcih is less
less_or_eq_all(First, Second) ->
lists:all(fun({FirstNode,FirstVersion}) ->
Returned = lists:keysearch(FirstNode, 1, Second),
case Returned of
{value,{_SecondNode,SecondVersion}} ->
SecondVersion >= FirstVersion;
false -> false
end end, First).
%% are all less or equal?
less_one(First,Second) ->
lists:any(fun({FNode, FVersion}) ->
case lists:keysearch(FNode, 1, Second) of
{value, {_Sec, SVersion}} -> FVersion /= SVersion;
false -> true
end
end, First).
shorten prune truncate loooooooong vector clock
prune(VectorClock) ->
VClockLength = length(VectorClock),
if VClockLength > ?PRUNE_LIMIT ->
ContextPos = 2,
SortedVectorClock = lists:keysort(ContextPos, VectorClock),
lists:nthtail(VClockLength - ?PRUNE_LIMIT, SortedVectorClock);
true ->
VectorClock
end.
| null | https://raw.githubusercontent.com/adamliesko/dynamo/cd97a96d1ce250e93f39cd16f9a3ef6c7030678d/src/vector_clock.erl | erlang | Searches the list of tuples TupleList1 for a tuple whose Nth element
% Returns { value , Tuple , TupleList2 } if such a tuple
is found, otherwise false. TupleList2 is a copy of TupleList1 where the
keymerge(N, TupleList1, TupleList2) -> TupleList3
tuples compare equal, the tuple from TupleList1 is picked before the tuple
from TupleList2.
keysort(N, TupleList1) -> TupleList2
Returns a list containing the sorted elements of the list TupleList1
['[email protected]',{'[email protected]',[{'[email protected]',1}]}],
just helper function which assess the compare result
check if <=, can be used as => with arg switching
first vector clock is shorter
it contains the same element but the version is lower
if all are less or equal
are all less or equal? | -module (vector_clock).
-export ([new/1, fix/2, incr/2, prune/1, diff/2, join/2,leq/2,equal/2]).
-define(PRUNE_LIMIT, 5).
new(Node) -> [{Node, 1}].
resolve key value from two ppossibly different vector clocks
fix({FClock, FValues} = First, {SClock, SValues} = Second) ->
ComparisonResult = diff(FClock,SClock),
case ComparisonResult of
leq ->
Second;
geq ->
First;
eq ->
First;
_ ->
{join(FClock,SClock), FValues ++ SValues}
end.
keytake(Key , N , TupleList1 ) - > { value , Tuple , TupleList2 } | false
first occurrence of Tuple has been removed .
Returns the sorted list formed by merging TupleList1 and TupleList2 . The
merge is performed on the element of each tuple . Both TupleList1 and
TupleList2 must be key - sorted prior to evaluating this function . When two
Sorting is performed on the element of the tuples . The sort is stable .
join(First, Second) ->
join([], First, Second).
join(Acc, [], Second) ->
lists:keysort(1, Acc ++ Second);
join(Acc, First, [] )->
lists:keysort(1, Acc ++ First);
join(Acc, [{FNode, FVersion}|FClock], SClock) ->
case lists:keytake(FNode, 1, SClock) of
{value, {FNode, SVersion}, ClockS} when FVersion > SVersion ->
join([{FNode,FVersion}|Acc],FClock,ClockS);
{value, {FNode, SVersion}, ClockS} ->
join([{FNode,SVersion}|Acc],FClock, ClockS);
false ->
join([{FNode,FVersion}|Acc],FClock,SClock)
end.
incr(Node, [{Node, Context}|VectorClocks]) ->
[{Node, Context+1}|VectorClocks];
incr(Node, [VectorClock|VectorClocks]) ->
[VectorClock|incr(Node, VectorClocks)];
incr(_Node, []) ->
[{node(), 1}].
equal(First,Second) ->
if length(First) == length(Second) ->
lists:all(fun(FirstClock) -> lists:member(FirstClock,Second) end, First);
true ->
false
end.
diff(First,Second) ->
Eq = equal(First,Second),
Leq = leq(First,Second),
Geq = leq(Second,First),
if
Leq -> leq;
Geq -> geq;
Eq -> eq;
true -> to_join
end.
leq(First, Second) ->
Shorter = length(First) < length(Second),
LessOne = less_one(First,Second),
LessOrEqAll = less_or_eq_all(First,Second),
(Shorter or LessOne) and LessOrEqAll.
is there one , whcih is less
less_or_eq_all(First, Second) ->
lists:all(fun({FirstNode,FirstVersion}) ->
Returned = lists:keysearch(FirstNode, 1, Second),
case Returned of
{value,{_SecondNode,SecondVersion}} ->
SecondVersion >= FirstVersion;
false -> false
end end, First).
less_one(First,Second) ->
lists:any(fun({FNode, FVersion}) ->
case lists:keysearch(FNode, 1, Second) of
{value, {_Sec, SVersion}} -> FVersion /= SVersion;
false -> true
end
end, First).
shorten prune truncate loooooooong vector clock
prune(VectorClock) ->
VClockLength = length(VectorClock),
if VClockLength > ?PRUNE_LIMIT ->
ContextPos = 2,
SortedVectorClock = lists:keysort(ContextPos, VectorClock),
lists:nthtail(VClockLength - ?PRUNE_LIMIT, SortedVectorClock);
true ->
VectorClock
end.
|
8f61b91c64302d196046c0c0cbb13d8bbcadbd4b486cc6d4c7eb2eb06ec8fe06 | mbj/mhs | OpenApi.hs | module OpenApi where
import OpenApi.OpenApi
import OpenApi.Prelude
import qualified Data.Aeson as JSON
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Yaml as YAML
import qualified System.Path as Path
loadSpecFileJSON
:: forall m .(MonadFail m, MonadIO m)
=> Path.AbsRelFile
-> m OpenApi
loadSpecFileJSON = loadSpec <=< (liftIO . LBS.readFile . Path.toString)
where
loadSpec :: LBS.ByteString -> m OpenApi
loadSpec
= either (fail . ("OpenApi JSON decode failed: " <>)) pure
. JSON.eitherDecode'
loadSpecFileYAML
:: forall m .(MonadFail m, MonadIO m)
=> Path.AbsRelFile
-> m OpenApi
loadSpecFileYAML = loadSpec <=< (liftIO . BS.readFile . Path.toString)
where
loadSpec :: BS.ByteString -> m OpenApi
loadSpec
= either (fail . ("OpenApi YAML decode failed: " <>). show) pure
. YAML.decodeEither'
| null | https://raw.githubusercontent.com/mbj/mhs/71d96825e92df3549c2ca5b0058acbb91fc2a6e7/openapi/src/OpenApi.hs | haskell | module OpenApi where
import OpenApi.OpenApi
import OpenApi.Prelude
import qualified Data.Aeson as JSON
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Yaml as YAML
import qualified System.Path as Path
loadSpecFileJSON
:: forall m .(MonadFail m, MonadIO m)
=> Path.AbsRelFile
-> m OpenApi
loadSpecFileJSON = loadSpec <=< (liftIO . LBS.readFile . Path.toString)
where
loadSpec :: LBS.ByteString -> m OpenApi
loadSpec
= either (fail . ("OpenApi JSON decode failed: " <>)) pure
. JSON.eitherDecode'
loadSpecFileYAML
:: forall m .(MonadFail m, MonadIO m)
=> Path.AbsRelFile
-> m OpenApi
loadSpecFileYAML = loadSpec <=< (liftIO . BS.readFile . Path.toString)
where
loadSpec :: BS.ByteString -> m OpenApi
loadSpec
= either (fail . ("OpenApi YAML decode failed: " <>). show) pure
. YAML.decodeEither'
|
|
e57e112a16ac68bfd2d2fe6349a40091e857a41883e19a9f56bd1142ee73238b | caisah/sicp-exercises-and-examples | ex_2.66.scm | ;; Implement the lookup procedure for the case where the set of records is structured as
;; a binary tree, ordered by the numerical values of the keys.
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) false)
((= given-key (key (entry set-of-records)))
(entry set-of-records))
((< given-key (key (entry set-of-records)))
(lookup given-key (left-branch set-of-records)))
(else (lookup given-key (right-branch set-of-records)))))
| null | https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/2.3.3-representing_sets/ex_2.66.scm | scheme | Implement the lookup procedure for the case where the set of records is structured as
a binary tree, ordered by the numerical values of the keys. |
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) false)
((= given-key (key (entry set-of-records)))
(entry set-of-records))
((< given-key (key (entry set-of-records)))
(lookup given-key (left-branch set-of-records)))
(else (lookup given-key (right-branch set-of-records)))))
|
657d700a20e096feb38a51a19f53ee226051fc29b5cd694624745f512daf203d | dleslie/allegro-egg | utf8.scm | (define make-utf-string* (foreign-lambda utf-string "al_ustr_new" c-string))
(define (make-utf-string-from-buffer* b) ((foreign-lambda utf-string "al_ustr_new_from_buffer" blob integer) b (blob-size b)))
(define (make-utf-string str)
(let ((s (make-utf-string* str)))
(set-finalizer! s free-utf-string!)
s))
(define (make-utf-string-from-buffer b)
(let ((s (make-utf-string-from-buffer* b)))
(set-finalizer! b free-utf-string!)
s))
(define free-utf-string! (foreign-lambda void "al_ustr_free" utf-string))
(define utf->string (foreign-lambda c-string "al_cstr" utf-string))
(define (utf->buffer! s b) ((foreign-lambda void "al_ustr_to_buffer" utf-string blob integer) s b (blob-size b)))
(define utf->string-copy (foreign-lambda c-string "al_cstr_dup" utf-string))
(define utf-copy* (foreign-lambda utf-string "al_ustr_dup" utf-string))
(define (utf-copy str)
(let ((s (utf-copy* str)))
(set-finalizer! s free-utf-string!)
s))
(define utf-substring* (foreign-lambda utf-string "al_ustr_dup_substr" utf-string integer integer))
(define (utf-substring str i1 i2)
(let ((s (utf-substring str i1 i2)))
(set-finalizer! s free-utf-string!)
s))
(define utf-empty-string (foreign-lambda utf-string "al_ustr_empty_string"))
(define make-utf-null-string* (foreign-safe-lambda* utf-string () "
ALLEGRO_USTR *str = (ALLEGRO_USTR *)C_malloc(sizeof(ALLEGRO_USTR));
C_memset(str, 0, sizeof(ALLEGRO_USTR));
C_return(str);"))
(define (make-utf-null-string)
(let ((str (make-utf-null-string*)))
(set-finalizer! str free-utf-string!)
str))
(define (utf-reference-cstr* cstr)
(let ((str (make-utf-null-string*)))
((foreign-lambda utf-string "al_ref_cstr" utf-string (const c-string)) str cstr)
str))
(define (utf-reference-cstr cstr)
(let ((str (make-utf-null-string)))
((foreign-lambda utf-string "al_ref_cstr" utf-string (const c-string)) str cstr)
str))
(define (utf-reference-buffer* b)
(let ((str (make-utf-null-string*)))
((foreign-lambda utf-string "al_ref_buffer" utf-string (const c-string) unsigned-integer32) str b (blob-size b))
str))
(define (utf-reference-buffer b)
(let ((str (make-utf-null-string)))
((foreign-lambda utf-string "al_ref_buffer" utf-string (const c-string) unsigned-integer32) str b (blob-size b))
str))
(define (utf-reference-utf-string* ustr start end)
(let ((str (make-utf-null-string*)))
((foreign-lambda utf-string "al_ref_ustr" utf-string (const utf-string) integer integer) str ustr start end)
str))
(define (utf-reference-utf-string ustr start end)
(let ((str (make-utf-null-string)))
((foreign-lambda utf-string "al_ref_ustr" utf-string (const utf-string) integer integer) str ustr start end)
str))
(define utf-size (foreign-lambda integer "al_ustr_size" utf-string))
(define utf-length (foreign-lambda integer "al_ustr_length" utf-string))
(define utf-offset (foreign-lambda integer "al_ustr_offset" utf-string integer))
(define utf-next (foreign-lambda* integer ((utf-string us) (integer pos)) "
if (al_ustr_next(us, &pos))
C_return(pos);
else
C_return(C_SCHEME_FALSE);
"))
(define utf-previous (foreign-lambda* integer ((utf-string us) (integer pos)) "
if (al_ustr_prev(us, &pos))
C_return(pos);
else
C_return(C_SCHEME_FALSE);
"))
(define utf-get (foreign-lambda integer32 "al_ustr_get" utf-string integer))
(define utf-get-next (foreign-primitive integer32 ((utf-string us) (integer pos)) "
int32_t val = al_ustr_get_next(us, &pos);
if (val >= 0)
{
C_word *ptr = C_alloc(C_SIZEOF_LIST (2));
C_return(C_list(&ptr, 2, C_fix(val), C_fix(pos)));
}
else
C_return(C_SCHEME_FALSE);
"))
(define utf-get-prev (foreign-primitive integer32 ((utf-string us) (integer pos)) "
int32_t val = al_ustr_prev_get(us, &pos);
if (val >= 0)
{
C_word *ptr = C_alloc(C_SIZEOF_LIST (2));
C_return(C_list(&ptr, 2, C_fix(val), C_fix(pos)));
}
else
C_return(C_SCHEME_FALSE);
"))
(define utf-insert! (foreign-lambda bool "al_ustr_insert" utf-string integer utf-string))
(define utf-insert-string! (foreign-lambda bool "al_ustr_insert_cstr" utf-string integer c-string))
(define utf-insert-char! (foreign-lambda integer "al_ustr_insert_chr" utf-string integer integer32))
(define utf-append! (foreign-lambda bool "al_ustr_append" utf-string utf-string))
(define utf-append-string! (foreign-lambda bool "al_ustr_append_cstr" utf-string c-string))
(define utf-append-char! (foreign-lambda integer "al_ustr_append_chr" utf-string integer))
AL_PRINTFUNC(bool , al_ustr_appendf , ( ALLEGRO_USTR * us , const char * fmt , ... ) ,
2 , 3 ) ;
AL_FUNC(bool , al_ustr_vappendf , ( ALLEGRO_USTR * us , const char * fmt ,
;; va_list ap));
(define utf-remove-char! (foreign-lambda bool "al_ustr_remove_chr" utf-string integer))
(define utf-remove-range! (foreign-lambda bool "al_ustr_remove_range" utf-string integer integer))
(define utf-truncate! (foreign-lambda bool "al_ustr_truncate" utf-string integer))
(define utf-ltrim! (foreign-lambda bool "al_ustr_ltrim_ws" utf-string))
(define utf-rtrim! (foreign-lambda bool "al_ustr_rtrim_ws" utf-string))
(define utf-trim! (foreign-lambda bool "al_ustr_trim_ws" utf-string))
(define utf-assign! (foreign-lambda bool "al_ustr_assign" utf-string utf-string))
(define utf-assign-substring! (foreign-lambda bool "al_ustr_assign_substr" utf-string utf-string integer integer))
(define utf-assign-string! (foreign-lambda bool "al_ustr_assign_cstr" utf-string c-string))
(define utf-set-char! (foreign-lambda integer "al_ustr_set_chr" utf-string integer integer32))
(define utf-replace-range! (foreign-lambda bool "al_ustr_replace_range" utf-string integer integer utf-string))
(define utf-find (foreign-lambda integer "al_ustr_find_str" utf-string integer utf-string))
(define utf-find-string (foreign-lambda integer "al_ustr_find_cstr" utf-string integer c-string))
(define utf-find-char (foreign-lambda integer "al_ustr_find_chr" utf-string integer integer32))
(define utf-find-set (foreign-lambda integer "al_ustr_find_set" utf-string integer utf-string))
(define utf-find-set-string (foreign-lambda integer "al_ustr_find_set_cstr" utf-string integer c-string))
(define utf-find-cset (foreign-lambda integer "al_ustr_find_cset" utf-string integer utf-string))
(define utf-find-cset-string (foreign-lambda integer "al_ustr_find_cset_cstr" utf-string integer c-string))
(define utf-rfind (foreign-lambda integer "al_ustr_rfind_str" utf-string integer utf-string))
(define utf-rfind-char (foreign-lambda integer "al_ustr_rfind_chr" utf-string integer integer32))
(define utf-rfind-string (foreign-lambda integer "al_ustr_rfind_cstr" utf-string integer c-string))
(define utf-find&replace! (foreign-lambda bool "al_ustr_find_replace" utf-string integer utf-string utf-string))
(define utf-find&replace-string! (foreign-lambda bool "al_ustr_find_replace_cstr" utf-string integer c-string c-string))
(define utf-equal? (foreign-lambda bool "al_ustr_equal" utf-string utf-string))
(define utf-compare (foreign-lambda integer "al_ustr_compare" utf-string utf-string))
(define utf-ncompare (foreign-lambda integer "al_ustr_ncompare" utf-string utf-string integer))
(define utf-prefix? (foreign-lambda bool "al_ustr_has_prefix" utf-string utf-string))
(define utf-prefix-string? (foreign-lambda bool "al_ustr_has_prefix_cstr" utf-string c-string))
(define utf-suffix? (foreign-lambda bool "al_ustr_has_suffix" utf-string utf-string))
(define utf-suffix-string? (foreign-lambda bool "al_ustr_has_suffix_cstr" utf-string c-string))
(define utf8-width (foreign-lambda integer "al_utf8_width" integer32))
(define utf8-encode! (foreign-lambda integer "al_utf8_encode" blob integer32))
(define utf-string-utf16-size (foreign-lambda integer "al_ustr_size_utf16" (const utf-string)))
(define utf-string-utf16-encode (foreign-lambda* integer (((const utf-string) str) (blob data) (integer count)) "C_return(al_ustr_encode_utf16(str, (uint16_t *)data, count));"))
(define utf16-width (foreign-lambda integer "al_utf16_width" integer))
(define utf16-encode (foreign-lambda integer "al_utf16_encode" u16vector integer32))
| null | https://raw.githubusercontent.com/dleslie/allegro-egg/0435fb891dda5c64e95aa9dedccddd31b17e27da/utf8.scm | scheme |
"))
va_list ap)); | (define make-utf-string* (foreign-lambda utf-string "al_ustr_new" c-string))
(define (make-utf-string-from-buffer* b) ((foreign-lambda utf-string "al_ustr_new_from_buffer" blob integer) b (blob-size b)))
(define (make-utf-string str)
(let ((s (make-utf-string* str)))
(set-finalizer! s free-utf-string!)
s))
(define (make-utf-string-from-buffer b)
(let ((s (make-utf-string-from-buffer* b)))
(set-finalizer! b free-utf-string!)
s))
(define free-utf-string! (foreign-lambda void "al_ustr_free" utf-string))
(define utf->string (foreign-lambda c-string "al_cstr" utf-string))
(define (utf->buffer! s b) ((foreign-lambda void "al_ustr_to_buffer" utf-string blob integer) s b (blob-size b)))
(define utf->string-copy (foreign-lambda c-string "al_cstr_dup" utf-string))
(define utf-copy* (foreign-lambda utf-string "al_ustr_dup" utf-string))
(define (utf-copy str)
(let ((s (utf-copy* str)))
(set-finalizer! s free-utf-string!)
s))
(define utf-substring* (foreign-lambda utf-string "al_ustr_dup_substr" utf-string integer integer))
(define (utf-substring str i1 i2)
(let ((s (utf-substring str i1 i2)))
(set-finalizer! s free-utf-string!)
s))
(define utf-empty-string (foreign-lambda utf-string "al_ustr_empty_string"))
(define make-utf-null-string* (foreign-safe-lambda* utf-string () "
(define (make-utf-null-string)
(let ((str (make-utf-null-string*)))
(set-finalizer! str free-utf-string!)
str))
(define (utf-reference-cstr* cstr)
(let ((str (make-utf-null-string*)))
((foreign-lambda utf-string "al_ref_cstr" utf-string (const c-string)) str cstr)
str))
(define (utf-reference-cstr cstr)
(let ((str (make-utf-null-string)))
((foreign-lambda utf-string "al_ref_cstr" utf-string (const c-string)) str cstr)
str))
(define (utf-reference-buffer* b)
(let ((str (make-utf-null-string*)))
((foreign-lambda utf-string "al_ref_buffer" utf-string (const c-string) unsigned-integer32) str b (blob-size b))
str))
(define (utf-reference-buffer b)
(let ((str (make-utf-null-string)))
((foreign-lambda utf-string "al_ref_buffer" utf-string (const c-string) unsigned-integer32) str b (blob-size b))
str))
(define (utf-reference-utf-string* ustr start end)
(let ((str (make-utf-null-string*)))
((foreign-lambda utf-string "al_ref_ustr" utf-string (const utf-string) integer integer) str ustr start end)
str))
(define (utf-reference-utf-string ustr start end)
(let ((str (make-utf-null-string)))
((foreign-lambda utf-string "al_ref_ustr" utf-string (const utf-string) integer integer) str ustr start end)
str))
(define utf-size (foreign-lambda integer "al_ustr_size" utf-string))
(define utf-length (foreign-lambda integer "al_ustr_length" utf-string))
(define utf-offset (foreign-lambda integer "al_ustr_offset" utf-string integer))
(define utf-next (foreign-lambda* integer ((utf-string us) (integer pos)) "
if (al_ustr_next(us, &pos))
else
"))
(define utf-previous (foreign-lambda* integer ((utf-string us) (integer pos)) "
if (al_ustr_prev(us, &pos))
else
"))
(define utf-get (foreign-lambda integer32 "al_ustr_get" utf-string integer))
(define utf-get-next (foreign-primitive integer32 ((utf-string us) (integer pos)) "
if (val >= 0)
{
}
else
"))
(define utf-get-prev (foreign-primitive integer32 ((utf-string us) (integer pos)) "
if (val >= 0)
{
}
else
"))
(define utf-insert! (foreign-lambda bool "al_ustr_insert" utf-string integer utf-string))
(define utf-insert-string! (foreign-lambda bool "al_ustr_insert_cstr" utf-string integer c-string))
(define utf-insert-char! (foreign-lambda integer "al_ustr_insert_chr" utf-string integer integer32))
(define utf-append! (foreign-lambda bool "al_ustr_append" utf-string utf-string))
(define utf-append-string! (foreign-lambda bool "al_ustr_append_cstr" utf-string c-string))
(define utf-append-char! (foreign-lambda integer "al_ustr_append_chr" utf-string integer))
AL_PRINTFUNC(bool , al_ustr_appendf , ( ALLEGRO_USTR * us , const char * fmt , ... ) ,
AL_FUNC(bool , al_ustr_vappendf , ( ALLEGRO_USTR * us , const char * fmt ,
(define utf-remove-char! (foreign-lambda bool "al_ustr_remove_chr" utf-string integer))
(define utf-remove-range! (foreign-lambda bool "al_ustr_remove_range" utf-string integer integer))
(define utf-truncate! (foreign-lambda bool "al_ustr_truncate" utf-string integer))
(define utf-ltrim! (foreign-lambda bool "al_ustr_ltrim_ws" utf-string))
(define utf-rtrim! (foreign-lambda bool "al_ustr_rtrim_ws" utf-string))
(define utf-trim! (foreign-lambda bool "al_ustr_trim_ws" utf-string))
(define utf-assign! (foreign-lambda bool "al_ustr_assign" utf-string utf-string))
(define utf-assign-substring! (foreign-lambda bool "al_ustr_assign_substr" utf-string utf-string integer integer))
(define utf-assign-string! (foreign-lambda bool "al_ustr_assign_cstr" utf-string c-string))
(define utf-set-char! (foreign-lambda integer "al_ustr_set_chr" utf-string integer integer32))
(define utf-replace-range! (foreign-lambda bool "al_ustr_replace_range" utf-string integer integer utf-string))
(define utf-find (foreign-lambda integer "al_ustr_find_str" utf-string integer utf-string))
(define utf-find-string (foreign-lambda integer "al_ustr_find_cstr" utf-string integer c-string))
(define utf-find-char (foreign-lambda integer "al_ustr_find_chr" utf-string integer integer32))
(define utf-find-set (foreign-lambda integer "al_ustr_find_set" utf-string integer utf-string))
(define utf-find-set-string (foreign-lambda integer "al_ustr_find_set_cstr" utf-string integer c-string))
(define utf-find-cset (foreign-lambda integer "al_ustr_find_cset" utf-string integer utf-string))
(define utf-find-cset-string (foreign-lambda integer "al_ustr_find_cset_cstr" utf-string integer c-string))
(define utf-rfind (foreign-lambda integer "al_ustr_rfind_str" utf-string integer utf-string))
(define utf-rfind-char (foreign-lambda integer "al_ustr_rfind_chr" utf-string integer integer32))
(define utf-rfind-string (foreign-lambda integer "al_ustr_rfind_cstr" utf-string integer c-string))
(define utf-find&replace! (foreign-lambda bool "al_ustr_find_replace" utf-string integer utf-string utf-string))
(define utf-find&replace-string! (foreign-lambda bool "al_ustr_find_replace_cstr" utf-string integer c-string c-string))
(define utf-equal? (foreign-lambda bool "al_ustr_equal" utf-string utf-string))
(define utf-compare (foreign-lambda integer "al_ustr_compare" utf-string utf-string))
(define utf-ncompare (foreign-lambda integer "al_ustr_ncompare" utf-string utf-string integer))
(define utf-prefix? (foreign-lambda bool "al_ustr_has_prefix" utf-string utf-string))
(define utf-prefix-string? (foreign-lambda bool "al_ustr_has_prefix_cstr" utf-string c-string))
(define utf-suffix? (foreign-lambda bool "al_ustr_has_suffix" utf-string utf-string))
(define utf-suffix-string? (foreign-lambda bool "al_ustr_has_suffix_cstr" utf-string c-string))
(define utf8-width (foreign-lambda integer "al_utf8_width" integer32))
(define utf8-encode! (foreign-lambda integer "al_utf8_encode" blob integer32))
(define utf-string-utf16-size (foreign-lambda integer "al_ustr_size_utf16" (const utf-string)))
(define utf-string-utf16-encode (foreign-lambda* integer (((const utf-string) str) (blob data) (integer count)) "C_return(al_ustr_encode_utf16(str, (uint16_t *)data, count));"))
(define utf16-width (foreign-lambda integer "al_utf16_width" integer))
(define utf16-encode (foreign-lambda integer "al_utf16_encode" u16vector integer32))
|
3f9d2d1252e6e73ec4cf0d764246b42b380258084e980d1f049187e0061d16a5 | alanz/ghc-exactprint | records-check-sels.hs | # LANGUAGE PatternSynonyms #
module Qux where
-- Make sure selectors aren't generated for normal synonyms
pattern Uni a = Just a
pattern a :+: b = (a, b)
qux = a (Just True)
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/records-check-sels.hs | haskell | Make sure selectors aren't generated for normal synonyms | # LANGUAGE PatternSynonyms #
module Qux where
pattern Uni a = Just a
pattern a :+: b = (a, b)
qux = a (Just True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.