_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 |
|---|---|---|---|---|---|---|---|---|
9443b6d457e0c40bf55a830a10cf88f3c2ce85918340358cff4c628d3c8b50b1 | batterseapower/haskell-kata | DelayedApplicativeGADTModular2.hs | # LANGUAGE GADTs , ScopedTypeVariables #
module Process2 where
import Control.Applicative (Applicative(..), liftA2, (<$>))
import Control.Monad (liftM, liftM2, ap, join)
import Data.Foldable (Foldable(..), toList)
import Data.Traversable (Traversable(..), fmapDefault, foldMapDefault)
import Debug.Trace
data DelayStructure sh a where
Leaf :: a -> DelayStructure () a
Branch :: DelayStructure sh1 a -> DelayStructure sh2 a -> DelayStructure (sh1, sh2) a
instance Show a => Show (DelayStructure sh a) where
show (Leaf x) = "Leaf (" ++ show x ++ ")"
show (Branch t1 t2) = "Branch (" ++ show t1 ++ ") (" ++ show t2 ++ ")"
instance Functor (DelayStructure sh) where
fmap = fmapDefault
instance Foldable (DelayStructure sh) where
foldMap = foldMapDefault
instance Traversable (DelayStructure sh) where
traverse f (Leaf x) = Leaf <$> f x
traverse f (Branch t1 t2) = Branch <$> traverse f t1 <*> traverse f t2
If you do n't want DelayM to have Monad structure , you can nuke the nested use of DelayM ,
-- and make some of the consumers simpler. I actually want this generalisation, though.
data DelayM q a r = Done r
| forall sh. Delayed (DelayStructure sh q) (DelayStructure sh a -> DelayM q a r)
instance Functor (DelayM q a) where
fmap f x = pure f <*> x
instance Applicative (DelayM q a) where
pure = return
Done f <*> Done x = Done (f x)
Delayed qs k <*> Done x = Delayed qs (\as -> k as <*> Done x)
Done f <*> Delayed qs k = Delayed qs (\as -> Done f <*> k as)
Delayed qs1 k1 <*> Delayed qs2 k2 = Delayed (Branch qs1 qs2) (\(Branch as1 as2) -> k1 as1 <*> k2 as2)
instance Monad (DelayM q a) where
return = Done
Done x >>= fxmy = fxmy x
Delayed qs k >>= fxmy = Delayed qs (\as -> k as >>= fxmy)
delay :: q -> DelayM q a a
delay q = Delayed (Leaf q) (\(Leaf a) -> pure a)
runDelayM :: forall memom q a r.
(Applicative memom, Monad memom,
Show q) -- Debugging only
=> (DelayM q a r -> DelayM q a r) -- ^ Chooses the evaluation strategy
-> (q -> memom (DelayM q a a)) -- ^ How to answer questions in the monad (possibly generating new requests in the process)
-> DelayM q a r -> memom r
runDelayM choose_some sc = go
where
go = go' . choose_some
go' (Done x) = pure x
go' (Delayed (qs :: DelayStructure sh q) (k :: DelayStructure sh a -> DelayM q a r))
= -- trace ("iteration: " ++ show qs) $
mungeDS sc qs >>= \mx -> go (mx >>= k)
mungeDS :: forall memom sh q a.
(Applicative memom, Monad memom)
=> (q -> memom (DelayM q a a))
-> DelayStructure sh q
-> memom (DelayM q a (DelayStructure sh a))
mungeDS sc qs = (traverse sc qs :: memom (DelayStructure sh (DelayM q a a))) >>= \fs -> return (sequenceA fs :: DelayM q a (DelayStructure sh a))
depthFirst :: DelayM q a r -> DelayM q a r
depthFirst (Done x) = Done x
depthFirst (Delayed qs k) = delayTail qs >>= k
where
delayTail :: DelayStructure sh q -> DelayM q a (DelayStructure sh a)
delayTail (Leaf q) = fmap Leaf (delay q)
delayTail (Branch qs1 (qs2 :: DelayStructure sh2 q)) = liftM2 Branch (delayTail qs1) (traverse delay qs2 :: DelayM q a (DelayStructure sh2 a))
breadthFirst :: DelayM q a r -> DelayM q a r
breadthFirst = id
-- Simple example supercompiler-alike to show that it all works:
type HFunction = Int
data State = State deriving ( Eq )
type State = Int
data Term = Tieback HFunction | Base Int | Split Term Term deriving (Show)
type ScpM = DelayM State Term
-- Execution trace:
10 = > 9
4 = > 3
-- 1 => 0 BASE
2 = > 1 BASE
5 = > 4
2 = > 1 BASE
3 = > 2 BASE
split :: Applicative t
=> (State -> t Term)
-> State -> t Term
--split = undefined
split f x | x <= 2 = pure (Base x)
Change A2 to M2 to linearise the search :-)
reduce :: State -> State
--reduce = undefined
reduce x = x-1
supercompile :: State -> ([(State, HFunction)], Term)
supercompile state = unMemoM (sc state >>= runDelayM eval_strat sc) []
where
eval_strat = depthFirst
eval_strat = breadthFirst
-- A simplified version of a supercompiler: no sc-history.
Generates requests for States
sc' :: State -> ScpM Term
sc' state = split delay (reduce state)
Allows us to answer requests for States in the memoisation monad ,
-- possibly generating new requests in the process (hence the nested ScpM)
sc :: State -> MemoM (ScpM Term)
sc = memo sc'
memo :: (State -> ScpM Term)
-> State -> MemoM (ScpM Term)
memo opt state = modify $ \memo -> case lookup state memo of
Just h -> (memo, pure (Tieback h))
Nothing -> ((state, h'):memo, opt state)
where h' = 1 + maximum (0:map snd memo)
newtype MemoM a = MemoM { unMemoM :: [(State, HFunction)] -> ([(State, HFunction)], a) }
instance Functor MemoM where
fmap = liftM
instance Applicative MemoM where
pure = return
(<*>) = ap
instance Monad MemoM where
return x = MemoM $ \s -> (s, x)
MemoM xf >>= fxmy = MemoM $ \s -> case xf s of (s', x) -> unMemoM (fxmy x) s'
modify :: ([(State, HFunction)] -> ([(State, HFunction)], a))
-> MemoM a
modify = MemoM
main = print $ supercompile 10 | null | https://raw.githubusercontent.com/batterseapower/haskell-kata/49c0c5cf48f8e5549131c78d026e4f2aa73d8a7a/DelayedApplicativeGADTModular2.hs | haskell | and make some of the consumers simpler. I actually want this generalisation, though.
Debugging only
^ Chooses the evaluation strategy
^ How to answer questions in the monad (possibly generating new requests in the process)
trace ("iteration: " ++ show qs) $
Simple example supercompiler-alike to show that it all works:
Execution trace:
1 => 0 BASE
split = undefined
reduce = undefined
A simplified version of a supercompiler: no sc-history.
possibly generating new requests in the process (hence the nested ScpM) | # LANGUAGE GADTs , ScopedTypeVariables #
module Process2 where
import Control.Applicative (Applicative(..), liftA2, (<$>))
import Control.Monad (liftM, liftM2, ap, join)
import Data.Foldable (Foldable(..), toList)
import Data.Traversable (Traversable(..), fmapDefault, foldMapDefault)
import Debug.Trace
data DelayStructure sh a where
Leaf :: a -> DelayStructure () a
Branch :: DelayStructure sh1 a -> DelayStructure sh2 a -> DelayStructure (sh1, sh2) a
instance Show a => Show (DelayStructure sh a) where
show (Leaf x) = "Leaf (" ++ show x ++ ")"
show (Branch t1 t2) = "Branch (" ++ show t1 ++ ") (" ++ show t2 ++ ")"
instance Functor (DelayStructure sh) where
fmap = fmapDefault
instance Foldable (DelayStructure sh) where
foldMap = foldMapDefault
instance Traversable (DelayStructure sh) where
traverse f (Leaf x) = Leaf <$> f x
traverse f (Branch t1 t2) = Branch <$> traverse f t1 <*> traverse f t2
If you do n't want DelayM to have Monad structure , you can nuke the nested use of DelayM ,
data DelayM q a r = Done r
| forall sh. Delayed (DelayStructure sh q) (DelayStructure sh a -> DelayM q a r)
instance Functor (DelayM q a) where
fmap f x = pure f <*> x
instance Applicative (DelayM q a) where
pure = return
Done f <*> Done x = Done (f x)
Delayed qs k <*> Done x = Delayed qs (\as -> k as <*> Done x)
Done f <*> Delayed qs k = Delayed qs (\as -> Done f <*> k as)
Delayed qs1 k1 <*> Delayed qs2 k2 = Delayed (Branch qs1 qs2) (\(Branch as1 as2) -> k1 as1 <*> k2 as2)
instance Monad (DelayM q a) where
return = Done
Done x >>= fxmy = fxmy x
Delayed qs k >>= fxmy = Delayed qs (\as -> k as >>= fxmy)
delay :: q -> DelayM q a a
delay q = Delayed (Leaf q) (\(Leaf a) -> pure a)
runDelayM :: forall memom q a r.
(Applicative memom, Monad memom,
-> DelayM q a r -> memom r
runDelayM choose_some sc = go
where
go = go' . choose_some
go' (Done x) = pure x
go' (Delayed (qs :: DelayStructure sh q) (k :: DelayStructure sh a -> DelayM q a r))
mungeDS sc qs >>= \mx -> go (mx >>= k)
mungeDS :: forall memom sh q a.
(Applicative memom, Monad memom)
=> (q -> memom (DelayM q a a))
-> DelayStructure sh q
-> memom (DelayM q a (DelayStructure sh a))
mungeDS sc qs = (traverse sc qs :: memom (DelayStructure sh (DelayM q a a))) >>= \fs -> return (sequenceA fs :: DelayM q a (DelayStructure sh a))
depthFirst :: DelayM q a r -> DelayM q a r
depthFirst (Done x) = Done x
depthFirst (Delayed qs k) = delayTail qs >>= k
where
delayTail :: DelayStructure sh q -> DelayM q a (DelayStructure sh a)
delayTail (Leaf q) = fmap Leaf (delay q)
delayTail (Branch qs1 (qs2 :: DelayStructure sh2 q)) = liftM2 Branch (delayTail qs1) (traverse delay qs2 :: DelayM q a (DelayStructure sh2 a))
breadthFirst :: DelayM q a r -> DelayM q a r
breadthFirst = id
type HFunction = Int
data State = State deriving ( Eq )
type State = Int
data Term = Tieback HFunction | Base Int | Split Term Term deriving (Show)
type ScpM = DelayM State Term
10 = > 9
4 = > 3
2 = > 1 BASE
5 = > 4
2 = > 1 BASE
3 = > 2 BASE
split :: Applicative t
=> (State -> t Term)
-> State -> t Term
split f x | x <= 2 = pure (Base x)
Change A2 to M2 to linearise the search :-)
reduce :: State -> State
reduce x = x-1
supercompile :: State -> ([(State, HFunction)], Term)
supercompile state = unMemoM (sc state >>= runDelayM eval_strat sc) []
where
eval_strat = depthFirst
eval_strat = breadthFirst
Generates requests for States
sc' :: State -> ScpM Term
sc' state = split delay (reduce state)
Allows us to answer requests for States in the memoisation monad ,
sc :: State -> MemoM (ScpM Term)
sc = memo sc'
memo :: (State -> ScpM Term)
-> State -> MemoM (ScpM Term)
memo opt state = modify $ \memo -> case lookup state memo of
Just h -> (memo, pure (Tieback h))
Nothing -> ((state, h'):memo, opt state)
where h' = 1 + maximum (0:map snd memo)
newtype MemoM a = MemoM { unMemoM :: [(State, HFunction)] -> ([(State, HFunction)], a) }
instance Functor MemoM where
fmap = liftM
instance Applicative MemoM where
pure = return
(<*>) = ap
instance Monad MemoM where
return x = MemoM $ \s -> (s, x)
MemoM xf >>= fxmy = MemoM $ \s -> case xf s of (s', x) -> unMemoM (fxmy x) s'
modify :: ([(State, HFunction)] -> ([(State, HFunction)], a))
-> MemoM a
modify = MemoM
main = print $ supercompile 10 |
674f765dbed169610571184c95c86c53614a1b2dede06e4fd7ddb1e95dcd7056 | spurious/sagittarius-scheme-mirror | simplex.scm | ;;; SIMPLEX -- Simplex algorithm.
(define (matrix-rows a) (vector-length a))
(define (matrix-columns a) (FLOATvector-length (vector-ref a 0)))
(define (matrix-ref a i j) (FLOATvector-ref (vector-ref a i) j))
(define (matrix-set! a i j x) (FLOATvector-set! (vector-ref a i) j x))
(define (fuck-up)
(fatal-error "This shouldn't happen"))
(define (simplex a m1 m2 m3)
(define *epsilon* 1e-6)
(if (not (and (>= m1 0)
(>= m2 0)
(>= m3 0)
(= (matrix-rows a) (+ m1 m2 m3 2))))
(fuck-up))
(let* ((m12 (+ m1 m2 1))
(m (- (matrix-rows a) 2))
(n (- (matrix-columns a) 1))
(l1 (make-vector n))
(l2 (make-vector m))
(l3 (make-vector m2))
(nl1 n)
(iposv (make-vector m))
(izrov (make-vector n))
(ip 0)
(kp 0)
(bmax 0.0)
(one? #f)
(pass2? #t))
(define (simp1 mm abs?)
(set! kp (vector-ref l1 0))
(set! bmax (matrix-ref a mm kp))
(do ((k 1 (+ k 1))) ((>= k nl1))
(if (FLOATpositive?
(if abs?
(FLOAT- (FLOATabs (matrix-ref a mm (vector-ref l1 k)))
(FLOATabs bmax))
(FLOAT- (matrix-ref a mm (vector-ref l1 k)) bmax)))
(begin
(set! kp (vector-ref l1 k))
(set! bmax (matrix-ref a mm (vector-ref l1 k)))))))
(define (simp2)
(set! ip 0)
(let ((q1 0.0)
(flag? #f))
(do ((i 0 (+ i 1))) ((= i m))
(if flag?
(if (FLOAT< (matrix-ref a (vector-ref l2 i) kp) (FLOAT- *epsilon*))
(begin
(let ((q (FLOAT/ (FLOAT- (matrix-ref a (vector-ref l2 i) 0))
(matrix-ref a (vector-ref l2 i) kp))))
(cond
((FLOAT< q q1)
(set! ip (vector-ref l2 i))
(set! q1 q))
((FLOAT= q q1)
(let ((qp 0.0)
(q0 0.0))
(let loop ((k 1))
(if (<= k n)
(begin
(set! qp (FLOAT/ (FLOAT- (matrix-ref a ip k))
(matrix-ref a ip kp)))
(set! q0 (FLOAT/ (FLOAT-
(matrix-ref a (vector-ref l2 i) k))
(matrix-ref a (vector-ref l2 i) kp)))
(if (FLOAT= q0 qp)
(loop (+ k 1))))))
(if (FLOAT< q0 qp)
(set! ip (vector-ref l2 i)))))))))
(if (FLOAT< (matrix-ref a (vector-ref l2 i) kp) (FLOAT- *epsilon*))
(begin
(set! q1 (FLOAT/ (FLOAT- (matrix-ref a (vector-ref l2 i) 0))
(matrix-ref a (vector-ref l2 i) kp)))
(set! ip (vector-ref l2 i))
(set! flag? #t)))))))
(define (simp3 one?)
(let ((piv (FLOAT/ (matrix-ref a ip kp))))
(do ((ii 0 (+ ii 1))) ((= ii (+ m (if one? 2 1))))
(if (not (= ii ip))
(begin
(matrix-set! a ii kp (FLOAT* piv (matrix-ref a ii kp)))
(do ((kk 0 (+ kk 1))) ((= kk (+ n 1)))
(if (not (= kk kp))
(matrix-set! a ii kk (FLOAT- (matrix-ref a ii kk)
(FLOAT* (matrix-ref a ip kk)
(matrix-ref a ii kp)))))))))
(do ((kk 0 (+ kk 1))) ((= kk (+ n 1)))
(if (not (= kk kp))
(matrix-set! a ip kk (FLOAT* (FLOAT- piv) (matrix-ref a ip kk)))))
(matrix-set! a ip kp piv)))
(do ((k 0 (+ k 1))) ((= k n))
(vector-set! l1 k (+ k 1))
(vector-set! izrov k k))
(do ((i 0 (+ i 1))) ((= i m))
(if (FLOATnegative? (matrix-ref a (+ i 1) 0))
(fuck-up))
(vector-set! l2 i (+ i 1))
(vector-set! iposv i (+ n i)))
(do ((i 0 (+ i 1))) ((= i m2)) (vector-set! l3 i #t))
(if (positive? (+ m2 m3))
(begin
(do ((k 0 (+ k 1))) ((= k (+ n 1)))
(do ((i (+ m1 1) (+ i 1)) (sum 0.0 (FLOAT+ sum (matrix-ref a i k))))
((> i m) (matrix-set! a (+ m 1) k (FLOAT- sum)))))
(let loop ()
(simp1 (+ m 1) #f)
(cond
((FLOAT<= bmax *epsilon*)
(cond ((FLOAT< (matrix-ref a (+ m 1) 0) (FLOAT- *epsilon*))
(set! pass2? #f))
((FLOAT<= (matrix-ref a (+ m 1) 0) *epsilon*)
(let loop ((ip1 m12))
(if (<= ip1 m)
(cond ((= (vector-ref iposv (- ip1 1)) (+ ip n -1))
(simp1 ip1 #t)
(cond ((FLOATpositive? bmax)
(set! ip ip1)
(set! one? #t))
(else
(loop (+ ip1 1)))))
(else
(loop (+ ip1 1))))
(do ((i (+ m1 1) (+ i 1))) ((>= i m12))
(if (vector-ref l3 (- i (+ m1 1)))
(do ((k 0 (+ k 1))) ((= k (+ n 1)))
(matrix-set! a i k (FLOAT- (matrix-ref a i k)))))))))
(else (simp2) (if (zero? ip) (set! pass2? #f) (set! one? #t)))))
(else (simp2) (if (zero? ip) (set! pass2? #f) (set! one? #t))))
(if one?
(begin
(set! one? #f)
(simp3 #t)
(cond
((>= (vector-ref iposv (- ip 1)) (+ n m12 -1))
(let loop ((k 0))
(cond
((and (< k nl1) (not (= kp (vector-ref l1 k))))
(loop (+ k 1)))
(else
(set! nl1 (- nl1 1))
(do ((is k (+ is 1))) ((>= is nl1))
(vector-set! l1 is (vector-ref l1 (+ is 1))))
(matrix-set! a (+ m 1) kp (FLOAT+ (matrix-ref a (+ m 1) kp) 1.0))
(do ((i 0 (+ i 1))) ((= i (+ m 2)))
(matrix-set! a i kp (FLOAT- (matrix-ref a i kp))))))))
((and (>= (vector-ref iposv (- ip 1)) (+ n m1))
(vector-ref l3 (- (vector-ref iposv (- ip 1)) (+ m1 n))))
(vector-set! l3 (- (vector-ref iposv (- ip 1)) (+ m1 n)) #f)
(matrix-set! a (+ m 1) kp (FLOAT+ (matrix-ref a (+ m 1) kp) 1.0))
(do ((i 0 (+ i 1))) ((= i (+ m 2)))
(matrix-set! a i kp (FLOAT- (matrix-ref a i kp))))))
(let ((t (vector-ref izrov (- kp 1))))
(vector-set! izrov (- kp 1) (vector-ref iposv (- ip 1)))
(vector-set! iposv (- ip 1) t))
(loop))))))
(and pass2?
(let loop ()
(simp1 0 #f)
(cond
((FLOATpositive? bmax)
(simp2)
(cond ((zero? ip) #t)
(else (simp3 #f)
(let ((t (vector-ref izrov (- kp 1))))
(vector-set! izrov (- kp 1) (vector-ref iposv (- ip 1)))
(vector-set! iposv (- ip 1) t))
(loop))))
(else (list iposv izrov)))))))
(define (test)
(simplex (vector (FLOATvector 0.0 1.0 1.0 3.0 -0.5)
(FLOATvector 740.0 -1.0 0.0 -2.0 0.0)
(FLOATvector 0.0 0.0 -2.0 0.0 7.0)
(FLOATvector 0.5 0.0 -1.0 1.0 -2.0)
(FLOATvector 9.0 -1.0 -1.0 -1.0 -1.0)
(FLOATvector 0.0 0.0 0.0 0.0 0.0))
2 1 1))
(define (main . args)
(run-benchmark
"simplex"
simplex-iters
(lambda (result) (equal? result '(#(4 1 3 2) #(0 5 7 6))))
(lambda () (lambda () (test)))))
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/bench/gambit-benchmarks/simplex.scm | scheme | SIMPLEX -- Simplex algorithm. |
(define (matrix-rows a) (vector-length a))
(define (matrix-columns a) (FLOATvector-length (vector-ref a 0)))
(define (matrix-ref a i j) (FLOATvector-ref (vector-ref a i) j))
(define (matrix-set! a i j x) (FLOATvector-set! (vector-ref a i) j x))
(define (fuck-up)
(fatal-error "This shouldn't happen"))
(define (simplex a m1 m2 m3)
(define *epsilon* 1e-6)
(if (not (and (>= m1 0)
(>= m2 0)
(>= m3 0)
(= (matrix-rows a) (+ m1 m2 m3 2))))
(fuck-up))
(let* ((m12 (+ m1 m2 1))
(m (- (matrix-rows a) 2))
(n (- (matrix-columns a) 1))
(l1 (make-vector n))
(l2 (make-vector m))
(l3 (make-vector m2))
(nl1 n)
(iposv (make-vector m))
(izrov (make-vector n))
(ip 0)
(kp 0)
(bmax 0.0)
(one? #f)
(pass2? #t))
(define (simp1 mm abs?)
(set! kp (vector-ref l1 0))
(set! bmax (matrix-ref a mm kp))
(do ((k 1 (+ k 1))) ((>= k nl1))
(if (FLOATpositive?
(if abs?
(FLOAT- (FLOATabs (matrix-ref a mm (vector-ref l1 k)))
(FLOATabs bmax))
(FLOAT- (matrix-ref a mm (vector-ref l1 k)) bmax)))
(begin
(set! kp (vector-ref l1 k))
(set! bmax (matrix-ref a mm (vector-ref l1 k)))))))
(define (simp2)
(set! ip 0)
(let ((q1 0.0)
(flag? #f))
(do ((i 0 (+ i 1))) ((= i m))
(if flag?
(if (FLOAT< (matrix-ref a (vector-ref l2 i) kp) (FLOAT- *epsilon*))
(begin
(let ((q (FLOAT/ (FLOAT- (matrix-ref a (vector-ref l2 i) 0))
(matrix-ref a (vector-ref l2 i) kp))))
(cond
((FLOAT< q q1)
(set! ip (vector-ref l2 i))
(set! q1 q))
((FLOAT= q q1)
(let ((qp 0.0)
(q0 0.0))
(let loop ((k 1))
(if (<= k n)
(begin
(set! qp (FLOAT/ (FLOAT- (matrix-ref a ip k))
(matrix-ref a ip kp)))
(set! q0 (FLOAT/ (FLOAT-
(matrix-ref a (vector-ref l2 i) k))
(matrix-ref a (vector-ref l2 i) kp)))
(if (FLOAT= q0 qp)
(loop (+ k 1))))))
(if (FLOAT< q0 qp)
(set! ip (vector-ref l2 i)))))))))
(if (FLOAT< (matrix-ref a (vector-ref l2 i) kp) (FLOAT- *epsilon*))
(begin
(set! q1 (FLOAT/ (FLOAT- (matrix-ref a (vector-ref l2 i) 0))
(matrix-ref a (vector-ref l2 i) kp)))
(set! ip (vector-ref l2 i))
(set! flag? #t)))))))
(define (simp3 one?)
(let ((piv (FLOAT/ (matrix-ref a ip kp))))
(do ((ii 0 (+ ii 1))) ((= ii (+ m (if one? 2 1))))
(if (not (= ii ip))
(begin
(matrix-set! a ii kp (FLOAT* piv (matrix-ref a ii kp)))
(do ((kk 0 (+ kk 1))) ((= kk (+ n 1)))
(if (not (= kk kp))
(matrix-set! a ii kk (FLOAT- (matrix-ref a ii kk)
(FLOAT* (matrix-ref a ip kk)
(matrix-ref a ii kp)))))))))
(do ((kk 0 (+ kk 1))) ((= kk (+ n 1)))
(if (not (= kk kp))
(matrix-set! a ip kk (FLOAT* (FLOAT- piv) (matrix-ref a ip kk)))))
(matrix-set! a ip kp piv)))
(do ((k 0 (+ k 1))) ((= k n))
(vector-set! l1 k (+ k 1))
(vector-set! izrov k k))
(do ((i 0 (+ i 1))) ((= i m))
(if (FLOATnegative? (matrix-ref a (+ i 1) 0))
(fuck-up))
(vector-set! l2 i (+ i 1))
(vector-set! iposv i (+ n i)))
(do ((i 0 (+ i 1))) ((= i m2)) (vector-set! l3 i #t))
(if (positive? (+ m2 m3))
(begin
(do ((k 0 (+ k 1))) ((= k (+ n 1)))
(do ((i (+ m1 1) (+ i 1)) (sum 0.0 (FLOAT+ sum (matrix-ref a i k))))
((> i m) (matrix-set! a (+ m 1) k (FLOAT- sum)))))
(let loop ()
(simp1 (+ m 1) #f)
(cond
((FLOAT<= bmax *epsilon*)
(cond ((FLOAT< (matrix-ref a (+ m 1) 0) (FLOAT- *epsilon*))
(set! pass2? #f))
((FLOAT<= (matrix-ref a (+ m 1) 0) *epsilon*)
(let loop ((ip1 m12))
(if (<= ip1 m)
(cond ((= (vector-ref iposv (- ip1 1)) (+ ip n -1))
(simp1 ip1 #t)
(cond ((FLOATpositive? bmax)
(set! ip ip1)
(set! one? #t))
(else
(loop (+ ip1 1)))))
(else
(loop (+ ip1 1))))
(do ((i (+ m1 1) (+ i 1))) ((>= i m12))
(if (vector-ref l3 (- i (+ m1 1)))
(do ((k 0 (+ k 1))) ((= k (+ n 1)))
(matrix-set! a i k (FLOAT- (matrix-ref a i k)))))))))
(else (simp2) (if (zero? ip) (set! pass2? #f) (set! one? #t)))))
(else (simp2) (if (zero? ip) (set! pass2? #f) (set! one? #t))))
(if one?
(begin
(set! one? #f)
(simp3 #t)
(cond
((>= (vector-ref iposv (- ip 1)) (+ n m12 -1))
(let loop ((k 0))
(cond
((and (< k nl1) (not (= kp (vector-ref l1 k))))
(loop (+ k 1)))
(else
(set! nl1 (- nl1 1))
(do ((is k (+ is 1))) ((>= is nl1))
(vector-set! l1 is (vector-ref l1 (+ is 1))))
(matrix-set! a (+ m 1) kp (FLOAT+ (matrix-ref a (+ m 1) kp) 1.0))
(do ((i 0 (+ i 1))) ((= i (+ m 2)))
(matrix-set! a i kp (FLOAT- (matrix-ref a i kp))))))))
((and (>= (vector-ref iposv (- ip 1)) (+ n m1))
(vector-ref l3 (- (vector-ref iposv (- ip 1)) (+ m1 n))))
(vector-set! l3 (- (vector-ref iposv (- ip 1)) (+ m1 n)) #f)
(matrix-set! a (+ m 1) kp (FLOAT+ (matrix-ref a (+ m 1) kp) 1.0))
(do ((i 0 (+ i 1))) ((= i (+ m 2)))
(matrix-set! a i kp (FLOAT- (matrix-ref a i kp))))))
(let ((t (vector-ref izrov (- kp 1))))
(vector-set! izrov (- kp 1) (vector-ref iposv (- ip 1)))
(vector-set! iposv (- ip 1) t))
(loop))))))
(and pass2?
(let loop ()
(simp1 0 #f)
(cond
((FLOATpositive? bmax)
(simp2)
(cond ((zero? ip) #t)
(else (simp3 #f)
(let ((t (vector-ref izrov (- kp 1))))
(vector-set! izrov (- kp 1) (vector-ref iposv (- ip 1)))
(vector-set! iposv (- ip 1) t))
(loop))))
(else (list iposv izrov)))))))
(define (test)
(simplex (vector (FLOATvector 0.0 1.0 1.0 3.0 -0.5)
(FLOATvector 740.0 -1.0 0.0 -2.0 0.0)
(FLOATvector 0.0 0.0 -2.0 0.0 7.0)
(FLOATvector 0.5 0.0 -1.0 1.0 -2.0)
(FLOATvector 9.0 -1.0 -1.0 -1.0 -1.0)
(FLOATvector 0.0 0.0 0.0 0.0 0.0))
2 1 1))
(define (main . args)
(run-benchmark
"simplex"
simplex-iters
(lambda (result) (equal? result '(#(4 1 3 2) #(0 5 7 6))))
(lambda () (lambda () (test)))))
|
156f69626011e6707a7792e02b9279aed0bb55dc9fcf971dfd7f19952aecf1c3 | IvanRublev/year_progress_bot | endpoint.erl | -module(endpoint).
-export([init/2]).
-compile([{parse_transform, lager_transform}]).
read_body(Req0, Acc) ->
case cowboy_req:read_body(Req0) of
{ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
{more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
end.
init(Req0, Opts) ->
lager:debug("Endpoint requested ->"),
case read_body(Req0, <<"">>) of
{ok, <<"">>, _} ->
reply_bad_request_error(Req0, Opts);
{ok, Body, _} ->
lager:debug("-> Body: ~s", formatter:gun_request_body_printable(Body)),
BodyJson = jiffy:decode(Body, [return_maps]),
reply_on(BodyJson, Req0, Opts);
_ ->
reply_bad_request_error(Req0, Opts)
end.
reply_on(BodyJson, Req0, Opts) ->
case parse_update(BodyJson) of
{Type, ChatId, Text} ->
case Text of
<<"/start">> ->
db:add_notified_chat(ChatId, date:end_of_today()),
reply_on_start(ChatId, Req0, Opts);
<<"/progress">> -> reply_on_progress(ChatId, Req0, Opts);
<<"/help">> -> reply_on_help(ChatId, Req0, Opts);
_ ->
if
Type == channel -> reply_ignore(Req0, Opts);
true -> reply_dont_know(ChatId, Req0, Opts)
end
end;
{dm, ChatId} ->
reply_dont_know(ChatId, Req0, Opts);
{channel, _ChatId} ->
reply_ignore(Req0, Opts);
_ ->
reply_bad_request_error(Req0, Opts)
end.
parse_update(Message) ->
case Message of
#{<<"message">> := #{
<<"chat">> := #{<<"id">> := ChatId},
<<"text">> := Text
}} ->
{dm, ChatId, Text};
#{<<"message">> := #{
<<"chat">> := #{<<"id">> := ChatId}
}} ->
{dm, ChatId};
#{<<"channel_post">> := #{
<<"chat">> := #{<<"id">> := ChatId},
<<"text">> := Text
}} ->
parse_address_in_channel({ChatId, Text});
#{<<"channel_post">> := #{
<<"chat">> := #{<<"id">> := ChatId}
}} ->
{channel, ChatId};
_ ->
error
end.
parse_address_in_channel({ChatId, Text}) ->
{ok, BotName} = application:get_env(year_progress_bot, tel_bot_name),
Address = <<"@", (list_to_binary(BotName))/binary>>,
TextSize = byte_size(Text),
AddressSize = byte_size(Address),
if
TextSize-AddressSize < 0 -> {channel, ChatId, Text};
true ->
AddrMatch = binary:match(Text, [Address], [{scope, {TextSize, -AddressSize}}]),
case AddrMatch of
nomatch -> {channel, ChatId, Text};
_ -> {channel_dm, ChatId, binary:part(Text, 0, TextSize-AddressSize)}
end
end.
cowboy_reply_fun(Status, Headers, Body, Req0, Opts) ->
lager:debug("<- Endpoint reply with status: ~p body: ~s", [Status, Body]),
Req = cowboy_req:reply(Status, Headers, Body, Req0),
{ok, Req, Opts}.
reply_on_start(ChatId, Req0, Opts) ->
Top = <<"Bot will send you the year progress bar daily.\nLike the following.\n"/utf8>>,
Bar = formatter:year_progress_bar(date:now()),
Closing = <<"\n\nYou can add this bot to a channel as well, and it will post progress bar there."/utf8>>,
Msg = <<Top/binary, Bar/binary, Closing/binary>>,
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, Msg},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_on_progress(ChatId, Req0, Opts) ->
Msg = formatter:year_progress_bar(date:now()),
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, Msg},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_on_help(ChatId, Req0, Opts) ->
{ok, BotName} = application:get_env(year_progress_bot, tel_bot_name),
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, <<(list_to_binary(BotName))/binary, " sends the year progress bar. The following commands are supported:\n/start - start the bot\n/progress - show today's progress of the year\n/help - this message">>},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_dont_know(ChatId, Req0, Opts) ->
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, <<"🤷♂️"/utf8>>},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_bad_request_error(Req0, Opts) ->
cowboy_reply_fun(400, #{<<"content-type">> => <<"text/html">>}, "Bad request", Req0, Opts).
reply_ignore(Req0, Opts) ->
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, <<"">>, Req0, Opts).
| null | https://raw.githubusercontent.com/IvanRublev/year_progress_bot/c3e85a5598d768933d5fb676c74d92fa8033cf60/apps/year_progress_bot/src/endpoint.erl | erlang | -module(endpoint).
-export([init/2]).
-compile([{parse_transform, lager_transform}]).
read_body(Req0, Acc) ->
case cowboy_req:read_body(Req0) of
{ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req};
{more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
end.
init(Req0, Opts) ->
lager:debug("Endpoint requested ->"),
case read_body(Req0, <<"">>) of
{ok, <<"">>, _} ->
reply_bad_request_error(Req0, Opts);
{ok, Body, _} ->
lager:debug("-> Body: ~s", formatter:gun_request_body_printable(Body)),
BodyJson = jiffy:decode(Body, [return_maps]),
reply_on(BodyJson, Req0, Opts);
_ ->
reply_bad_request_error(Req0, Opts)
end.
reply_on(BodyJson, Req0, Opts) ->
case parse_update(BodyJson) of
{Type, ChatId, Text} ->
case Text of
<<"/start">> ->
db:add_notified_chat(ChatId, date:end_of_today()),
reply_on_start(ChatId, Req0, Opts);
<<"/progress">> -> reply_on_progress(ChatId, Req0, Opts);
<<"/help">> -> reply_on_help(ChatId, Req0, Opts);
_ ->
if
Type == channel -> reply_ignore(Req0, Opts);
true -> reply_dont_know(ChatId, Req0, Opts)
end
end;
{dm, ChatId} ->
reply_dont_know(ChatId, Req0, Opts);
{channel, _ChatId} ->
reply_ignore(Req0, Opts);
_ ->
reply_bad_request_error(Req0, Opts)
end.
parse_update(Message) ->
case Message of
#{<<"message">> := #{
<<"chat">> := #{<<"id">> := ChatId},
<<"text">> := Text
}} ->
{dm, ChatId, Text};
#{<<"message">> := #{
<<"chat">> := #{<<"id">> := ChatId}
}} ->
{dm, ChatId};
#{<<"channel_post">> := #{
<<"chat">> := #{<<"id">> := ChatId},
<<"text">> := Text
}} ->
parse_address_in_channel({ChatId, Text});
#{<<"channel_post">> := #{
<<"chat">> := #{<<"id">> := ChatId}
}} ->
{channel, ChatId};
_ ->
error
end.
parse_address_in_channel({ChatId, Text}) ->
{ok, BotName} = application:get_env(year_progress_bot, tel_bot_name),
Address = <<"@", (list_to_binary(BotName))/binary>>,
TextSize = byte_size(Text),
AddressSize = byte_size(Address),
if
TextSize-AddressSize < 0 -> {channel, ChatId, Text};
true ->
AddrMatch = binary:match(Text, [Address], [{scope, {TextSize, -AddressSize}}]),
case AddrMatch of
nomatch -> {channel, ChatId, Text};
_ -> {channel_dm, ChatId, binary:part(Text, 0, TextSize-AddressSize)}
end
end.
cowboy_reply_fun(Status, Headers, Body, Req0, Opts) ->
lager:debug("<- Endpoint reply with status: ~p body: ~s", [Status, Body]),
Req = cowboy_req:reply(Status, Headers, Body, Req0),
{ok, Req, Opts}.
reply_on_start(ChatId, Req0, Opts) ->
Top = <<"Bot will send you the year progress bar daily.\nLike the following.\n"/utf8>>,
Bar = formatter:year_progress_bar(date:now()),
Closing = <<"\n\nYou can add this bot to a channel as well, and it will post progress bar there."/utf8>>,
Msg = <<Top/binary, Bar/binary, Closing/binary>>,
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, Msg},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_on_progress(ChatId, Req0, Opts) ->
Msg = formatter:year_progress_bar(date:now()),
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, Msg},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_on_help(ChatId, Req0, Opts) ->
{ok, BotName} = application:get_env(year_progress_bot, tel_bot_name),
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, <<(list_to_binary(BotName))/binary, " sends the year progress bar. The following commands are supported:\n/start - start the bot\n/progress - show today's progress of the year\n/help - this message">>},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_dont_know(ChatId, Req0, Opts) ->
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, jiffy:encode({[
{<<"method">>, <<"sendMessage">>},
{<<"text">>, <<"🤷♂️"/utf8>>},
{<<"chat_id">>, ChatId}
]}), Req0, Opts).
reply_bad_request_error(Req0, Opts) ->
cowboy_reply_fun(400, #{<<"content-type">> => <<"text/html">>}, "Bad request", Req0, Opts).
reply_ignore(Req0, Opts) ->
cowboy_reply_fun(200, #{
<<"content-type">> => <<"application/json">>
}, <<"">>, Req0, Opts).
| |
bbda8f963e3cd0090b23a4171c548e9ccfa42d874c146f3d132a3263d1310c9a | adamwalker/clash-riscv | Pipeline.hs | # LANGUAGE DeriveGeneric , , ScopedTypeVariables #
module Core.Pipeline where
import GHC.Generics
import Clash.Prelude
import Data.Bool
import Core.RegFile
import Core.Decode
import Core.ALU
import Core.Compare
import Core.Mem
import qualified Core.Debug as D
import Core.Debug (ForwardingSource(..))
# ANN module ( " HLint : ignore Functor law " : : String ) #
data FromInstructionMem = FromInstructionMem {
instruction :: BitVector 32,
instructionStall :: Bool
}
data ToInstructionMem = ToInstructionMem {
instructionAddress :: Unsigned 30
}
data FromDataMem = FromDataMem {
memoryData :: BitVector 32
}
data ToDataMem = ToDataMem {
readAddress :: Unsigned 32,
writeAddress :: Unsigned 32,
writeData :: BitVector 32,
writeStrobe :: BitVector 4
} deriving (Show, Generic, ShowX)
calcForwardingAddress :: Index 32 -> BitVector 32 -> BitVector 32 -> ForwardingSource
calcForwardingAddress sourceAddr instr_2 instr_3
| sourceAddr == 0 = NoForwarding
| unpack (rd instr_2) == sourceAddr && enableRegWrite instr_2 = ForwardingSourceALU
| unpack (rd instr_3) == sourceAddr && enableRegWrite instr_3 = ForwardingSourceMem
| otherwise = NoForwarding
topEntity :: HiddenClockReset dom gated sync => Signal dom FromInstructionMem -> Signal dom FromDataMem -> (Signal dom ToInstructionMem, Signal dom ToDataMem)
topEntity fim fdm = (tim, tdm)
where (tim, tdm, _) = pipeline fim fdm
pipeline
:: forall dom sync gated. HiddenClockReset dom gated sync
=> Signal dom FromInstructionMem
-> Signal dom FromDataMem
-> (Signal dom ToInstructionMem, Signal dom ToDataMem, Signal dom D.PipelineState)
pipeline fromInstructionMem fromDataMem = (ToInstructionMem . unpack . slice d31 d2 . pack <$> nextPC_0, toDataMem, pipelineState)
where
---------------------------------------------
--Stage 0
--Instruction fetch
---------------------------------------------
instrStall = instructionStall <$> fromInstructionMem
pc_0 :: Signal dom (Unsigned 32)
pc_0 = regEn (-4) (fmap not stallStage2OrEarlier) nextPC_0
nextPC_0 :: Signal dom (Unsigned 32)
nextPC_0 = calcNextPC <$> pc_0 <*> pc_1 <*> instr_1 <*> branchTaken_2 <*> pc_2 <*> isBranching_2 <*> isJumpingViaRegister_2 <*> aluAddSub <*> instrStall
where
calcNextPC pc_0 pc_1 instr_1 branchTaken_2 pc_2 isBranching_2 isJumpingViaRegister_2 aluRes_2 instrStall
Branch predicted incorrectly - resume from branch PC plus 4
| not branchTaken_2 && isBranching_2 = pc_2 + 4
--Jumping via register - results is ready in ALU output - load it
| isJumpingViaRegister_2 = unpack aluRes_2
--Predict branches taken
| branch instr_1 = pc_1 + unpack (signExtendImmediate (sbImm instr_1)) `shiftL` 1 :: Unsigned 32
--Jumps always taken
| jal instr_1 = pc_1 + unpack (signExtendImmediate (ujImm instr_1)) `shiftL` 1 :: Unsigned 32
| instrStall = pc_0
--Business as usual
| otherwise = pc_0 + 4
instr_0' = instruction <$> fromInstructionMem
instr_0'' = mux (register False (stallStage2OrEarlier .&&. fmap not instrStall)) (register 0 instr_0'') instr_0'
--inject nops for all branches and jumps because they are assumed taken
Also inject NOP for branch predicted incorrectly
instr_0 = mux
( isJumping_1
.||. isJumpingViaRegister_1
.||. isBranching_1
.||. (fmap not branchTaken_2 .&&. isBranching_2)
.||. isJumpingViaRegister_2
.||. instrStall
)
0
instr_0''
stage0
= D.Stage0
<$> pc_0
<*> nextPC_0
<*> instr_0
---------------------------------------------
Stage 1
--Decode / Register access
---------------------------------------------
Delay the signals computed in stage 0
pc_1 = regEn 0 (fmap not stallStage2OrEarlier) pc_0
instr_1 = regEn 0 (fmap not stallStage2OrEarlier) instr_0
--decode the register addresses and immediate
rs1Addr_1, rs2Addr_1 :: Signal dom (Index 32)
rs1Addr_1 = (unpack . rs1) <$> instr_1
rs2Addr_1 = (unpack . rs2) <$> instr_1
imm_1 = extractImmediate <$> instr_1
--The ALU bypass
aluBypass_1 = mux (lui <$> instr_1) (alignUpperImmediate . uImm <$> instr_1) ((pack . (+ 4)) <$> pc_1)
bypassALU_1 = lui <$> instr_1 .||. jalr <$> instr_1 .||. jal <$> instr_1
--is this instruction a jump, and we therefore need to replace the previous stage with a bubble
--TODO: replace this with unconditional or backwards jump check
isJumping_1 = jal <$> instr_1
isJumpingViaRegister_1 = jalr <$> instr_1
isBranching_1 = branch <$> instr_1
Figure out where the first ALU operand comes from
aluOp1IsRegister_1 = firstOpIsRegister <$> instr_1
Figure out where the second ALU operand comes from
aluOp2IsRegister_1 = secondOpIsRegister <$> instr_1
--The regfile
theRegFile_1 = regFile rdAddr_4 regWriteEn_4 rdData_4
rs1Data_1 = readReg <$> theRegFile_1 <*> rs1Addr_1
rs2Data_1 = readReg <$> theRegFile_1 <*> rs2Addr_1
--Will either of the ALU operands be forwarded?
forwardALUOp1_1 = calcForwardingAddress <$> rs1Addr_1 <*> instr_2 <*> instr_3
forwardALUOp2_1 = calcForwardingAddress <$> rs2Addr_1 <*> instr_2 <*> instr_3
--When the preceeding instruction is a memory load to a register that is used by this instruction, we need to stall
memToAluHazard_1
= (
(((rs1 <$> instr_1) .==. (rd <$> instr_2)) .&&. (usesRegister1 <$> instr_1)) --The previous instruction is writing rs1 and rs1 is used by this instruction
.||. (((rs2 <$> instr_1) .==. (rd <$> instr_2)) .&&. (usesRegister2 <$> instr_1)) --The previous instruction is writing rs2 and rs2 is used by this instruction
)
.&&. (load <$> instr_2) --And, the previous instruction is a memory load
stage1
= D.Stage1
<$> instr_1
<*> pc_1
<*> rs1Addr_1
<*> rs2Addr_1
<*> imm_1
<*> aluOp1IsRegister_1
<*> aluOp2IsRegister_1
<*> theRegFile_1
<*> rs1Data_1
<*> rs2Data_1
<*> forwardALUOp1_1
<*> forwardALUOp2_1
---------------------------------------------
Stage 2
--Execute
---------------------------------------------
If there is a mem to ALU hazard we :
- stall stage 0 and 1 ,
- insert a bubble in stage 2 ,
- let stage 3 and 4 execute as before
Letting stage 3 execute will resolve the hazard .
If there is a mem to ALU hazard we:
- stall stage 0 and 1,
- insert a bubble in stage 2,
- let stage 3 and 4 execute as before
Letting stage 3 execute will resolve the hazard.
-}
stallStage2OrEarlier = memToAluHazard_1
Delay the signals computed in stage 1 and insert bubbles in the relevant ones if we are stalled
pc_2 = register 0 pc_1
instr_2 = register 0 $ mux stallStage2OrEarlier 0 instr_1
rs1Data_2 = register 0 rs1Data_1
rs2Data_2 = register 0 rs2Data_1
aluOp1IsRegister_2 = register False aluOp1IsRegister_1
aluOp2IsRegister_2 = register False aluOp2IsRegister_1
imm_2 = register 0 imm_1
isBranching_2 = register False $ mux stallStage2OrEarlier (pure False) isBranching_1
isJumpingViaRegister_2 = register False $ mux stallStage2OrEarlier (pure False) isJumpingViaRegister_1
aluBypass_2 = register 0 aluBypass_1
bypassALU_2 = register False bypassALU_1
forwardALUOp1_2 = register NoForwarding forwardALUOp1_1
forwardALUOp2_2 = register NoForwarding forwardALUOp2_1
decode the alu operation
primaryOp_2 = decodeAluPrimaryOp <$> instr_2
secondaryOp_2 = decodeAluSecondaryOp <$> instr_2
--Extract the comparison operator
compareOp_2 = extractBranchType <$> instr_2
--Is the next cycle a register write
regWriteEn_2 = enableRegWrite <$> instr_2
--Will the next cycle write to memory
memWriteEnable_2 = enableMemWrite <$> instr_2
--Mem stage input forwarding
forwardMemToStage3_2 = (rs2 <$> instr_2) .==. (rd <$> instr_3) .&&. regWriteEn_3
forwardMemToStage2_2 = (rs2 <$> instr_2) .==. (rd <$> instr_4) .&&. regWriteEn_4
forwardedRs2 = mux forwardMemToStage2_2 rdData_4 rs2Data_2
regMux :: ForwardingSource -> BitVector 32 -> BitVector 32 -> BitVector 32 -> BitVector 32
regMux ForwardingSourceALU _ forwardedAlu _ = forwardedAlu
regMux ForwardingSourceMem _ _ forwardedMem = forwardedMem
regMux NoForwarding regFileOperand _ _ = regFileOperand
Mux the ALU operands
effectiveR1_2
= regMux
<$> forwardALUOp1_2
<*> rs1Data_2
<*> execRes_3
<*> rdData_4
effectiveR2_2
= regMux
<$> forwardALUOp2_2
<*> rs2Data_2
<*> execRes_3
<*> rdData_4
aluOperand1_2 = mux aluOp1IsRegister_2 effectiveR1_2 ((resize . pack) <$> pc_2)
aluOperand2_2 = mux aluOp2IsRegister_2 effectiveR2_2 imm_2
--The ALU
(aluAddSub, aluRes_2) = unbundle $ alu <$> primaryOp_2 <*> secondaryOp_2 <*> aluOperand1_2 <*> aluOperand2_2
execRes_2 = mux bypassALU_2 aluBypass_2 aluRes_2
--The compare unit for branching
branchTaken_2 = branchCompare <$> compareOp_2 <*> aluOperand1_2 <*> aluOperand2_2
stage2
= D.Stage2
<$> pc_2
<*> instr_2
<*> rs1Data_2
<*> rs2Data_2
<*> aluOp1IsRegister_2
<*> aluOp2IsRegister_2
<*> imm_2
<*> primaryOp_2
<*> secondaryOp_2
<*> memWriteEnable_2
<*> regWriteEn_2
<*> compareOp_2
<*> aluOperand1_2
<*> aluOperand2_2
<*> execRes_2
<*> branchTaken_2
<*> forwardALUOp1_2
<*> forwardALUOp2_2
<*> forwardMemToStage3_2
<*> forwardMemToStage2_2
---------------------------------------------
Stage 3
--Memory
---------------------------------------------
If the memory access is not ready in this cycle we :
- stall stages 0 , 1 , 2 and 3
- let stage 4 execute as usual
- insert a bubble into stage 4 in the next cycle
If the memory access is not ready in this cycle we:
- stall stages 0, 1, 2 and 3
- let stage 4 execute as usual
- insert a bubble into stage 4 in the next cycle
-}
Delay the signals computed in stage 2
pc_3 = register 0 pc_2
instr_3 = register 0 instr_2
execRes_3 = register 0 execRes_2
rs2Data_3 = register 0 forwardedRs2
memWriteEnable_3 = register False memWriteEnable_2
regWriteEn_3 = register False regWriteEn_2
forwardMemToStage3_3 = register False forwardMemToStage3_2
destRegSource_3 = decodeDestRegSource <$> instr_3
memDataToWrite_3 = mux forwardMemToStage3_3 rdData_4 rs2Data_3
--Extract the mem word addresses
wordAddressWrite_3 = slice d31 d2 <$> execRes_3
wordAddressRead_3 = slice d31 d2 <$> aluAddSub
writeStrobe_3 = calcWriteStrobe <$> (extractMemSize <$> instr_3) <*> (slice d1 d0 <$> execRes_3)
--The memory
memReadData_3' = memoryData <$> fromDataMem
toDataMem
= ToDataMem
<$> ((unpack . resize) <$> wordAddressRead_3) --read address
<*> ((unpack . resize) <$> wordAddressWrite_3) --write address
<*> memDataToWrite_3
<*> mux memWriteEnable_3 writeStrobe_3 0
memReadData_3 = doLoad <$> (extractMemSize <$> instr_3) <*> (loadUnsigned <$> instr_3) <*> (slice d1 d0 <$> execRes_3) <*> memReadData_3'
stage3
= D.Stage3
<$> pc_3
<*> instr_3
<*> execRes_3
<*> rs2Data_3
<*> memWriteEnable_3
<*> regWriteEn_3
<*> forwardMemToStage3_3
<*> destRegSource_3
<*> memReadData_3
<*> memDataToWrite_3
---------------------------------------------
Stage 4
--Writeback
---------------------------------------------
Delay the signals computed in stage 3
pc_4 = register 0 pc_3
instr_4 = register 0 instr_3
execRes_4 = register 0 execRes_3
rdAddr_4 = (unpack . rd) <$> instr_4
regWriteEn_4 = register False regWriteEn_3
destRegSource_4 = register SourceALU destRegSource_3
memReadData_4 = register 0 memReadData_3
--Special registers
cycle, time, retired :: Signal dom (BitVector 64)
cycle = register 0 (cycle + 1)
time = register 0 (time + 1)
retired = register 0 (retired + 1)
specialRegAll = func <$> instr_4 <*> cycle <*> time <*> retired
where
func instr cycle time retired = case decodeSpecialReg (extractSpecialReg instr) of
Cycle -> cycle
Time -> time
Retired -> retired
specialReg = mux (specialRegHigh <$> instr_4) (slice d63 d32 <$> specialRegAll) (slice d31 d0 <$> specialRegAll)
--Calculate the writeback signals for the register file
( used in stage 1 )
rdData_4 = func <$> execRes_4 <*> memReadData_4 <*> specialReg <*> destRegSource_4
where func a m sr s =
case s of
SourceALU -> a
SourceMem -> m
SourceSpec -> errorX "special reg"
stage4
= D.Stage4
<$> pc_4
<*> instr_4
<*> execRes_4
<*> rdAddr_4
<*> regWriteEn_4
<*> destRegSource_4
<*> memReadData_4
<*> rdData_4
pipelineState
= D.PipelineState
<$> stage0
<*> stage1
<*> stage2
<*> stage3
<*> stage4
| null | https://raw.githubusercontent.com/adamwalker/clash-riscv/84a90731a07c3427695b4926d7159f9e9902c1a1/src/Core/Pipeline.hs | haskell | -------------------------------------------
Stage 0
Instruction fetch
-------------------------------------------
Jumping via register - results is ready in ALU output - load it
Predict branches taken
Jumps always taken
Business as usual
inject nops for all branches and jumps because they are assumed taken
-------------------------------------------
Decode / Register access
-------------------------------------------
decode the register addresses and immediate
The ALU bypass
is this instruction a jump, and we therefore need to replace the previous stage with a bubble
TODO: replace this with unconditional or backwards jump check
The regfile
Will either of the ALU operands be forwarded?
When the preceeding instruction is a memory load to a register that is used by this instruction, we need to stall
The previous instruction is writing rs1 and rs1 is used by this instruction
The previous instruction is writing rs2 and rs2 is used by this instruction
And, the previous instruction is a memory load
-------------------------------------------
Execute
-------------------------------------------
Extract the comparison operator
Is the next cycle a register write
Will the next cycle write to memory
Mem stage input forwarding
The ALU
The compare unit for branching
-------------------------------------------
Memory
-------------------------------------------
Extract the mem word addresses
The memory
read address
write address
-------------------------------------------
Writeback
-------------------------------------------
Special registers
Calculate the writeback signals for the register file | # LANGUAGE DeriveGeneric , , ScopedTypeVariables #
module Core.Pipeline where
import GHC.Generics
import Clash.Prelude
import Data.Bool
import Core.RegFile
import Core.Decode
import Core.ALU
import Core.Compare
import Core.Mem
import qualified Core.Debug as D
import Core.Debug (ForwardingSource(..))
# ANN module ( " HLint : ignore Functor law " : : String ) #
data FromInstructionMem = FromInstructionMem {
instruction :: BitVector 32,
instructionStall :: Bool
}
data ToInstructionMem = ToInstructionMem {
instructionAddress :: Unsigned 30
}
data FromDataMem = FromDataMem {
memoryData :: BitVector 32
}
data ToDataMem = ToDataMem {
readAddress :: Unsigned 32,
writeAddress :: Unsigned 32,
writeData :: BitVector 32,
writeStrobe :: BitVector 4
} deriving (Show, Generic, ShowX)
calcForwardingAddress :: Index 32 -> BitVector 32 -> BitVector 32 -> ForwardingSource
calcForwardingAddress sourceAddr instr_2 instr_3
| sourceAddr == 0 = NoForwarding
| unpack (rd instr_2) == sourceAddr && enableRegWrite instr_2 = ForwardingSourceALU
| unpack (rd instr_3) == sourceAddr && enableRegWrite instr_3 = ForwardingSourceMem
| otherwise = NoForwarding
topEntity :: HiddenClockReset dom gated sync => Signal dom FromInstructionMem -> Signal dom FromDataMem -> (Signal dom ToInstructionMem, Signal dom ToDataMem)
topEntity fim fdm = (tim, tdm)
where (tim, tdm, _) = pipeline fim fdm
pipeline
:: forall dom sync gated. HiddenClockReset dom gated sync
=> Signal dom FromInstructionMem
-> Signal dom FromDataMem
-> (Signal dom ToInstructionMem, Signal dom ToDataMem, Signal dom D.PipelineState)
pipeline fromInstructionMem fromDataMem = (ToInstructionMem . unpack . slice d31 d2 . pack <$> nextPC_0, toDataMem, pipelineState)
where
instrStall = instructionStall <$> fromInstructionMem
pc_0 :: Signal dom (Unsigned 32)
pc_0 = regEn (-4) (fmap not stallStage2OrEarlier) nextPC_0
nextPC_0 :: Signal dom (Unsigned 32)
nextPC_0 = calcNextPC <$> pc_0 <*> pc_1 <*> instr_1 <*> branchTaken_2 <*> pc_2 <*> isBranching_2 <*> isJumpingViaRegister_2 <*> aluAddSub <*> instrStall
where
calcNextPC pc_0 pc_1 instr_1 branchTaken_2 pc_2 isBranching_2 isJumpingViaRegister_2 aluRes_2 instrStall
Branch predicted incorrectly - resume from branch PC plus 4
| not branchTaken_2 && isBranching_2 = pc_2 + 4
| isJumpingViaRegister_2 = unpack aluRes_2
| branch instr_1 = pc_1 + unpack (signExtendImmediate (sbImm instr_1)) `shiftL` 1 :: Unsigned 32
| jal instr_1 = pc_1 + unpack (signExtendImmediate (ujImm instr_1)) `shiftL` 1 :: Unsigned 32
| instrStall = pc_0
| otherwise = pc_0 + 4
instr_0' = instruction <$> fromInstructionMem
instr_0'' = mux (register False (stallStage2OrEarlier .&&. fmap not instrStall)) (register 0 instr_0'') instr_0'
Also inject NOP for branch predicted incorrectly
instr_0 = mux
( isJumping_1
.||. isJumpingViaRegister_1
.||. isBranching_1
.||. (fmap not branchTaken_2 .&&. isBranching_2)
.||. isJumpingViaRegister_2
.||. instrStall
)
0
instr_0''
stage0
= D.Stage0
<$> pc_0
<*> nextPC_0
<*> instr_0
Stage 1
Delay the signals computed in stage 0
pc_1 = regEn 0 (fmap not stallStage2OrEarlier) pc_0
instr_1 = regEn 0 (fmap not stallStage2OrEarlier) instr_0
rs1Addr_1, rs2Addr_1 :: Signal dom (Index 32)
rs1Addr_1 = (unpack . rs1) <$> instr_1
rs2Addr_1 = (unpack . rs2) <$> instr_1
imm_1 = extractImmediate <$> instr_1
aluBypass_1 = mux (lui <$> instr_1) (alignUpperImmediate . uImm <$> instr_1) ((pack . (+ 4)) <$> pc_1)
bypassALU_1 = lui <$> instr_1 .||. jalr <$> instr_1 .||. jal <$> instr_1
isJumping_1 = jal <$> instr_1
isJumpingViaRegister_1 = jalr <$> instr_1
isBranching_1 = branch <$> instr_1
Figure out where the first ALU operand comes from
aluOp1IsRegister_1 = firstOpIsRegister <$> instr_1
Figure out where the second ALU operand comes from
aluOp2IsRegister_1 = secondOpIsRegister <$> instr_1
theRegFile_1 = regFile rdAddr_4 regWriteEn_4 rdData_4
rs1Data_1 = readReg <$> theRegFile_1 <*> rs1Addr_1
rs2Data_1 = readReg <$> theRegFile_1 <*> rs2Addr_1
forwardALUOp1_1 = calcForwardingAddress <$> rs1Addr_1 <*> instr_2 <*> instr_3
forwardALUOp2_1 = calcForwardingAddress <$> rs2Addr_1 <*> instr_2 <*> instr_3
memToAluHazard_1
= (
)
stage1
= D.Stage1
<$> instr_1
<*> pc_1
<*> rs1Addr_1
<*> rs2Addr_1
<*> imm_1
<*> aluOp1IsRegister_1
<*> aluOp2IsRegister_1
<*> theRegFile_1
<*> rs1Data_1
<*> rs2Data_1
<*> forwardALUOp1_1
<*> forwardALUOp2_1
Stage 2
If there is a mem to ALU hazard we :
- stall stage 0 and 1 ,
- insert a bubble in stage 2 ,
- let stage 3 and 4 execute as before
Letting stage 3 execute will resolve the hazard .
If there is a mem to ALU hazard we:
- stall stage 0 and 1,
- insert a bubble in stage 2,
- let stage 3 and 4 execute as before
Letting stage 3 execute will resolve the hazard.
-}
stallStage2OrEarlier = memToAluHazard_1
Delay the signals computed in stage 1 and insert bubbles in the relevant ones if we are stalled
pc_2 = register 0 pc_1
instr_2 = register 0 $ mux stallStage2OrEarlier 0 instr_1
rs1Data_2 = register 0 rs1Data_1
rs2Data_2 = register 0 rs2Data_1
aluOp1IsRegister_2 = register False aluOp1IsRegister_1
aluOp2IsRegister_2 = register False aluOp2IsRegister_1
imm_2 = register 0 imm_1
isBranching_2 = register False $ mux stallStage2OrEarlier (pure False) isBranching_1
isJumpingViaRegister_2 = register False $ mux stallStage2OrEarlier (pure False) isJumpingViaRegister_1
aluBypass_2 = register 0 aluBypass_1
bypassALU_2 = register False bypassALU_1
forwardALUOp1_2 = register NoForwarding forwardALUOp1_1
forwardALUOp2_2 = register NoForwarding forwardALUOp2_1
decode the alu operation
primaryOp_2 = decodeAluPrimaryOp <$> instr_2
secondaryOp_2 = decodeAluSecondaryOp <$> instr_2
compareOp_2 = extractBranchType <$> instr_2
regWriteEn_2 = enableRegWrite <$> instr_2
memWriteEnable_2 = enableMemWrite <$> instr_2
forwardMemToStage3_2 = (rs2 <$> instr_2) .==. (rd <$> instr_3) .&&. regWriteEn_3
forwardMemToStage2_2 = (rs2 <$> instr_2) .==. (rd <$> instr_4) .&&. regWriteEn_4
forwardedRs2 = mux forwardMemToStage2_2 rdData_4 rs2Data_2
regMux :: ForwardingSource -> BitVector 32 -> BitVector 32 -> BitVector 32 -> BitVector 32
regMux ForwardingSourceALU _ forwardedAlu _ = forwardedAlu
regMux ForwardingSourceMem _ _ forwardedMem = forwardedMem
regMux NoForwarding regFileOperand _ _ = regFileOperand
Mux the ALU operands
effectiveR1_2
= regMux
<$> forwardALUOp1_2
<*> rs1Data_2
<*> execRes_3
<*> rdData_4
effectiveR2_2
= regMux
<$> forwardALUOp2_2
<*> rs2Data_2
<*> execRes_3
<*> rdData_4
aluOperand1_2 = mux aluOp1IsRegister_2 effectiveR1_2 ((resize . pack) <$> pc_2)
aluOperand2_2 = mux aluOp2IsRegister_2 effectiveR2_2 imm_2
(aluAddSub, aluRes_2) = unbundle $ alu <$> primaryOp_2 <*> secondaryOp_2 <*> aluOperand1_2 <*> aluOperand2_2
execRes_2 = mux bypassALU_2 aluBypass_2 aluRes_2
branchTaken_2 = branchCompare <$> compareOp_2 <*> aluOperand1_2 <*> aluOperand2_2
stage2
= D.Stage2
<$> pc_2
<*> instr_2
<*> rs1Data_2
<*> rs2Data_2
<*> aluOp1IsRegister_2
<*> aluOp2IsRegister_2
<*> imm_2
<*> primaryOp_2
<*> secondaryOp_2
<*> memWriteEnable_2
<*> regWriteEn_2
<*> compareOp_2
<*> aluOperand1_2
<*> aluOperand2_2
<*> execRes_2
<*> branchTaken_2
<*> forwardALUOp1_2
<*> forwardALUOp2_2
<*> forwardMemToStage3_2
<*> forwardMemToStage2_2
Stage 3
If the memory access is not ready in this cycle we :
- stall stages 0 , 1 , 2 and 3
- let stage 4 execute as usual
- insert a bubble into stage 4 in the next cycle
If the memory access is not ready in this cycle we:
- stall stages 0, 1, 2 and 3
- let stage 4 execute as usual
- insert a bubble into stage 4 in the next cycle
-}
Delay the signals computed in stage 2
pc_3 = register 0 pc_2
instr_3 = register 0 instr_2
execRes_3 = register 0 execRes_2
rs2Data_3 = register 0 forwardedRs2
memWriteEnable_3 = register False memWriteEnable_2
regWriteEn_3 = register False regWriteEn_2
forwardMemToStage3_3 = register False forwardMemToStage3_2
destRegSource_3 = decodeDestRegSource <$> instr_3
memDataToWrite_3 = mux forwardMemToStage3_3 rdData_4 rs2Data_3
wordAddressWrite_3 = slice d31 d2 <$> execRes_3
wordAddressRead_3 = slice d31 d2 <$> aluAddSub
writeStrobe_3 = calcWriteStrobe <$> (extractMemSize <$> instr_3) <*> (slice d1 d0 <$> execRes_3)
memReadData_3' = memoryData <$> fromDataMem
toDataMem
= ToDataMem
<*> memDataToWrite_3
<*> mux memWriteEnable_3 writeStrobe_3 0
memReadData_3 = doLoad <$> (extractMemSize <$> instr_3) <*> (loadUnsigned <$> instr_3) <*> (slice d1 d0 <$> execRes_3) <*> memReadData_3'
stage3
= D.Stage3
<$> pc_3
<*> instr_3
<*> execRes_3
<*> rs2Data_3
<*> memWriteEnable_3
<*> regWriteEn_3
<*> forwardMemToStage3_3
<*> destRegSource_3
<*> memReadData_3
<*> memDataToWrite_3
Stage 4
Delay the signals computed in stage 3
pc_4 = register 0 pc_3
instr_4 = register 0 instr_3
execRes_4 = register 0 execRes_3
rdAddr_4 = (unpack . rd) <$> instr_4
regWriteEn_4 = register False regWriteEn_3
destRegSource_4 = register SourceALU destRegSource_3
memReadData_4 = register 0 memReadData_3
cycle, time, retired :: Signal dom (BitVector 64)
cycle = register 0 (cycle + 1)
time = register 0 (time + 1)
retired = register 0 (retired + 1)
specialRegAll = func <$> instr_4 <*> cycle <*> time <*> retired
where
func instr cycle time retired = case decodeSpecialReg (extractSpecialReg instr) of
Cycle -> cycle
Time -> time
Retired -> retired
specialReg = mux (specialRegHigh <$> instr_4) (slice d63 d32 <$> specialRegAll) (slice d31 d0 <$> specialRegAll)
( used in stage 1 )
rdData_4 = func <$> execRes_4 <*> memReadData_4 <*> specialReg <*> destRegSource_4
where func a m sr s =
case s of
SourceALU -> a
SourceMem -> m
SourceSpec -> errorX "special reg"
stage4
= D.Stage4
<$> pc_4
<*> instr_4
<*> execRes_4
<*> rdAddr_4
<*> regWriteEn_4
<*> destRegSource_4
<*> memReadData_4
<*> rdData_4
pipelineState
= D.PipelineState
<$> stage0
<*> stage1
<*> stage2
<*> stage3
<*> stage4
|
072034d081ca6c764bed8a568b2b492ce4a69bbf8faa3b1e28f138ab221f3a0c | typelead/eta | Type.hs | ( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1998
--
-- Type - public interface
# LANGUAGE CPP , OverloadedStrings , MultiWayIf #
# OPTIONS_GHC -fno - warn - orphans #
-- | Main functions for manipulating types and type-related things
module Eta.Types.Type (
-- Note some of this is just re-exports from TyCon..
-- * Main data types representing Types
-- $type_classification
-- $representation_types
TyThing(..), Type, KindOrType, PredType, ThetaType,
Var, TyVar, isTyVar,
-- ** Constructing and deconstructing types
mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
mkAppTy, mkAppTys, splitAppTy, splitAppTys,
splitAppTy_maybe, repSplitAppTy_maybe,
mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
splitFunTys, splitFunTysN,
funResultTy, funArgTy, zipFunTys,
mkTyConApp, mkTyConTy,
tyConAppTyCon_maybe, tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs,
splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole,
splitListTyConApp_maybe,
mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
mkPiKinds, mkPiType, mkPiTypes,
piResultTy,
applyTy, applyTys, applyTysD, applyTysX, dropForAlls,
mkNumLitTy, isNumLitTy,
mkStrLitTy, isStrLitTy,
isUserErrorTy, pprUserTypeErrorTy,
coAxNthLHS,
-- (Newtypes)
newTyConInstRhs,
-- Pred types
mkFamilyTyConApp,
isDictLikeTy,
mkEqPred, mkCoerciblePred, mkPrimEqPred, mkReprPrimEqPred,
mkClassPred,
isClassPred, isEqPred,
isIPPred, isIPPred_maybe, isIPTyCon, isIPClass,
-- Deconstructing predicate types
PredTree(..), EqRel(..), eqRelRole, classifyPredType,
getClassPredTys, getClassPredTys_maybe,
getEqPredTys, getEqPredTys_maybe, getEqPredRole,
predTypeEqRel,
-- ** Common type constructors
funTyCon,
-- ** Predicates on types
isTypeVar, isKindVar, allDistinctTyVars, isForAllTy,
isTyVarTy, isFunTy, isDictTy, isPredTy, isVoidTy,
-- (Lifting and boxity)
isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
isPrimitiveType, isStrictType,
ETA - specific
isObjectType,
-- * Main data types representing Kinds
-- $kind_subtyping
Kind, SimpleKind, MetaKindVar,
-- ** Finding the kind of a type
typeKind,
-- ** Common Kinds and SuperKinds
anyKind, liftedTypeKind, unliftedTypeKind, openTypeKind,
constraintKind, superKind,
-- ** Common Kind type constructors
liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
constraintKindTyCon, anyKindTyCon,
-- * Type free variables
tyVarsOfType, tyVarsOfTypes, closeOverKinds,
expandTypeSynonyms,
typeSize, varSetElemsKvsFirst,
-- * Type comparison
eqType, eqTypeX, eqTypes, cmpType, cmpTypes,
eqPred, eqPredX, cmpPred, eqKind, eqTyVarBndrs,
-- * Forcing evaluation of types
seqType, seqTypes,
-- * Other views onto Types
coreView, tcView,
UnaryType, RepType(..), flattenRepType, repType,
tyConsOfType,
-- * Type representation for the code generator
typePrimRep, stypePrimRep, typePrimRepMany, typeRepArity,
tagTypeToText, stagTypeToText, rawTagTypeToText,
-- * Main type substitution data types
TvSubstEnv, -- Representation widely visible
TvSubst(..), -- Representation visible to a few friends
-- ** Manipulating type substitutions
emptyTvSubstEnv, emptyTvSubst,
mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
getTvSubstEnv, setTvSubstEnv,
zapTvSubstEnv, getTvInScope,
extendTvInScope, extendTvInScopeList,
extendTvSubst, extendTvSubstList,
isInScope, composeTvSubst, zipTyEnv,
isEmptyTvSubst, unionTvSubst,
-- ** Performing substitution on types and kinds
substTy, substTyAddInScope, substTys, substTyWith, substTysWith, substTheta,
substTyVar, substTyVars, substTyVarBndr,
cloneTyVarBndr, cloneTyVarBndrs, deShadowTy, lookupTyVar,
substKiWith, substKisWith,
-- * Pretty-printing
pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing,
pprTvBndr, pprTvBndrs, pprForAll, pprUserForAll, pprSigmaType,
pprTheta, pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprSourceTyCon,
TyPrec(..), maybeParen, pprSigmaTypeExtraCts,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyVarBndr, tidyTyVarBndrs, tidyFreeTyVars,
tidyOpenTyVar, tidyOpenTyVars,
tidyTyVarOcc,
tidyTopType,
tidyKind,
) where
#include "HsVersions.h"
We import the representation and primitive functions from TypeRep .
-- Many things are reexported, but not the representation!
import Eta.Types.Kind
import Eta.Types.TypeRep
-- friends:
import Eta.BasicTypes.Var
import Eta.BasicTypes.VarEnv
import Eta.BasicTypes.VarSet
import Eta.BasicTypes.NameEnv
import Eta.Types.Class
import Eta.Types.TyCon
import Eta.Prelude.TysPrim
import {-# SOURCE #-} Eta.Prelude.TysWiredIn ( eqTyCon, listTyCon,
coercibleTyCon, typeNatKind, typeSymbolKind )
import Eta.Prelude.PrelNames ( eqTyConKey, coercibleTyConKey, ipTyConKey,
openTypeKindTyConKey,
constraintKindTyConKey, liftedTypeKindTyConKey,
sobjectTyConKey,
errorMessageTypeErrorFamName,
typeErrorTextDataConName,
typeErrorShowTypeDataConName,
typeErrorAppendDataConName,
typeErrorVAppendDataConName)
import Eta.Prelude.ForeignCall
import Eta.Types.CoAxiom
import Eta.BasicTypes.UniqSupply ( UniqSupply, takeUniqFromSupply )
-- others
import Eta.BasicTypes.Unique ( Unique, hasKey )
import Eta.BasicTypes.BasicTypes ( Arity, RepArity )
import Eta.Utils.Util
import Eta.Utils.ListSetOps ( getNth )
import Eta.Utils.Outputable
import Eta.Utils.FastString
import Eta.Utils.Maybes ( orElse )
import Data.Text (Text)
import qualified Data.Text as T
import Data.Maybe ( isJust)
import Control.Monad ( guard )
infixr 3 `mkFunTy` -- Associates to the right
-- $type_classification
-- #type_classification#
--
Types are one of :
--
[ ] Iff its representation is other than a pointer
types are also unlifted .
--
-- [Lifted] Iff it has bottom as an element.
-- Closures always have lifted types: i.e. any
let - bound identifier in Core must have a lifted
-- type. Operationally, a lifted object is one that
-- can be entered.
-- Only lifted types may be unified with a type variable.
--
[ Algebraic ] it is a type with one or more constructors , whether
-- declared with @data@ or @newtype@.
-- An algebraic type is one that can be deconstructed
with a case expression . This is /not/ the same as
-- lifted types, because we also include unboxed
-- tuples in this classification.
--
-- [Data] Iff it is a type declared with @data@, or a boxed tuple.
--
[ Primitive ] it is a built - in type that ca n't be expressed in Haskell .
--
-- Currently, all primitive types are unlifted, but that's not necessarily
the case : for example , @Int@ could be primitive .
--
Some primitive types are unboxed , such as @Int#@ , whereas some are boxed
-- but unlifted (such as @ByteArray#@). The only primitive types that we
-- classify as algebraic are the unboxed tuples.
--
-- Some examples of type classifications that may make this a bit clearer are:
--
-- @
-- Type primitive boxed lifted algebraic
-- -----------------------------------------------------------------------------
-- Int# Yes No No No
-- ByteArray# Yes Yes No No
-- (\# a, b \#) Yes No No Yes
-- ( a, b ) No Yes Yes Yes
-- [a] No Yes Yes Yes
-- @
-- $representation_types
-- A /source type/ is a type that is a separate type as far as the type checker is
concerned , but which has a more low - level representation as far as Core - to - Core
-- passes and the rest of the back end is concerned.
--
-- You don't normally have to worry about this, as the utility functions in
-- this module will automatically convert a source into a representation type
-- if they are spotted, to the best of it's abilities. If you don't want this
to happen , use the equivalent functions from the " TcType " module .
{-
************************************************************************
* *
Type representation
* *
************************************************************************
-}
# INLINE coreView #
coreView :: Type -> Maybe Type
^ In Core , we \"look through\ " non - recursive newtypes and ' PredTypes ' : this
-- function tries to obtain a different view of the supplied type given this
--
-- Strips off the /top layer only/ of a type to give
-- its underlying representation type.
-- Returns Nothing if there is nothing to look through.
--
-- By being non-recursive and inlined, this case analysis gets efficiently
-- joined onto the case analysis that the caller is already doing
coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
= Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
Its important to use mkAppTys , rather than ( foldl AppTy ) ,
-- because the function part might well return a
-- partially-applied type constructor; indeed, usually will!
coreView _ = Nothing
-----------------------------------------------
# INLINE tcView #
tcView :: Type -> Maybe Type
-- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
= Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
tcView _ = Nothing
You might think that tcView belows in TcType rather than Type , but unfortunately
it is needed by Unify , which is turn imported by Coercion ( for MatchEnv and matchList ) .
-- So we will leave it here to avoid module loops.
-----------------------------------------------
expandTypeSynonyms :: Type -> Type
-- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
-- just the ones that discard type variables (e.g. type Funny a = Int)
-- But we don't know which those are currently, so we just expand all.
expandTypeSynonyms ty
= go ty
where
go (TyConApp tc tys)
| Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
= go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
| otherwise
= TyConApp tc (map go tys)
go (LitTy l) = LitTy l
go (TyVarTy tv) = TyVarTy tv
go (AppTy t1 t2) = mkAppTy (go t1) (go t2)
go (FunTy t1 t2) = FunTy (go t1) (go t2)
go (ForAllTy tv t) = ForAllTy tv (go t)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection{Constructor - specific functions }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
---------------------------------------------------------------------
TyVarTy
~~~~~~~
************************************************************************
* *
\subsection{Constructor-specific functions}
* *
************************************************************************
---------------------------------------------------------------------
TyVarTy
~~~~~~~
-}
-- | Attempts to obtain the type variable underlying a 'Type', and panics with the
-- given message if this is not a type variable type. See also 'getTyVar_maybe'
getTyVar :: String -> Type -> TyVar
getTyVar msg ty = case getTyVar_maybe ty of
Just tv -> tv
Nothing -> panic ("getTyVar: " ++ msg)
isTyVarTy :: Type -> Bool
isTyVarTy ty = isJust (getTyVar_maybe ty)
-- | Attempts to obtain the type variable underlying a 'Type'
getTyVar_maybe :: Type -> Maybe TyVar
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
getTyVar_maybe (TyVarTy tv) = Just tv
getTyVar_maybe _ = Nothing
allDistinctTyVars :: [KindOrType] -> Bool
allDistinctTyVars tkvs = go emptyVarSet tkvs
where
go _ [] = True
go so_far (ty : tys)
= case getTyVar_maybe ty of
Nothing -> False
Just tv | tv `elemVarSet` so_far -> False
| otherwise -> go (so_far `extendVarSet` tv) tys
---------------------------------------------------------------------
AppTy
~~~~~
We need to be pretty careful with AppTy to make sure we obey the
invariant that a TyConApp is always visibly so . mkAppTy maintains the
invariant : use it .
Note [ Decomposing fat arrow c=>t ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify ( a b ) with ( Eq a = > ty ) ? If we do so , we end up with
a partial application like ( (= > ) Eq a ) which does n't make sense in
source . In constrast , we * can * unify ( a b ) with ( t1 - > t2 ) .
Here 's an example ( Trac # 9858 ) of how you might do it :
i : : ( a , b ) = > Proxy ( a b ) - > TypeRep
i p = typeRep p
j = i ( Proxy : : Proxy ( Eq Int = > Int ) )
The type ( Proxy ( Eq Int = > Int ) ) is only accepted with -XImpredicativeTypes ,
but suppose we want that . But then in the call to ' i ' , we end
up decomposing ( Eq Int = > Int ) , and we definitely do n't want that .
This really only applies to the type checker ; in Core , ' = > ' and ' - > '
are the same , as are ' Constraint ' and ' * ' . But for now I 've put
the test in repSplitAppTy_maybe , which applies throughout , because
the other calls to splitAppTy are in Unify , which is also used by
the type checker ( e.g. when matching type - function equations ) .
---------------------------------------------------------------------
AppTy
~~~~~
We need to be pretty careful with AppTy to make sure we obey the
invariant that a TyConApp is always visibly so. mkAppTy maintains the
invariant: use it.
Note [Decomposing fat arrow c=>t]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify (a b) with (Eq a => ty)? If we do so, we end up with
a partial application like ((=>) Eq a) which doesn't make sense in
source Haskell. In constrast, we *can* unify (a b) with (t1 -> t2).
Here's an example (Trac #9858) of how you might do it:
i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep
i p = typeRep p
j = i (Proxy :: Proxy (Eq Int => Int))
The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes,
but suppose we want that. But then in the call to 'i', we end
up decomposing (Eq Int => Int), and we definitely don't want that.
This really only applies to the type checker; in Core, '=>' and '->'
are the same, as are 'Constraint' and '*'. But for now I've put
the test in repSplitAppTy_maybe, which applies throughout, because
the other calls to splitAppTy are in Unify, which is also used by
the type checker (e.g. when matching type-function equations).
-}
| Applies a type to another , as in e.g. @k a@
mkAppTy :: Type -> Type -> Type
mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2])
mkAppTy ty1 ty2 = AppTy ty1 ty2
-- Note that the TyConApp could be an
under - saturated type synonym . GHC allows that ; e.g.
type k a
-- type Id x = x
-- foo :: Foo Id -> Foo Id
--
Here I d is partially applied in the type sig for ,
-- but once the type synonyms are expanded all is well
mkAppTys :: Type -> [Type] -> Type
mkAppTys ty1 [] = ty1
mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
mkAppTys ty1 tys2 = foldl AppTy ty1 tys2
-------------
splitAppTy_maybe :: Type -> Maybe (Type, Type)
-- ^ Attempt to take a type application apart, whether it is a
-- function, type constructor, or plain type application. Note
-- that type family applications are NEVER unsaturated by this!
splitAppTy_maybe ty | Just ty' <- coreView ty
= splitAppTy_maybe ty'
splitAppTy_maybe ty = repSplitAppTy_maybe ty
-------------
repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
^ Does the AppTy split as in ' splitAppTy_maybe ' , but assumes that
any Core view stuff is already done
repSplitAppTy_maybe (FunTy ty1 ty2)
| isConstraintKind (typeKind ty1) = Nothing -- See Note [Decomposing fat arrow c=>t]
| otherwise = Just (TyConApp funTyCon [ty1], ty2)
repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
repSplitAppTy_maybe (TyConApp tc tys)
| isDecomposableTyCon tc || tys `lengthExceeds` tyConArity tc
, Just (tys', ty') <- snocView tys
= Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
repSplitAppTy_maybe _other = Nothing
-------------
splitAppTy :: Type -> (Type, Type)
-- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
-- and panics if this is not possible
splitAppTy ty = case splitAppTy_maybe ty of
Just pr -> pr
Nothing -> panic "splitAppTy"
-------------
splitAppTys :: Type -> (Type, [Type])
-- ^ Recursively splits a type as far as is possible, leaving a residual
-- type being applied to and the type arguments applied to it. Never fails,
-- even if that means returning an empty list of type applications.
splitAppTys ty = split ty ty []
where
split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
split _ (AppTy ty arg) args = split ty ty (arg:args)
split _ (TyConApp tc tc_args) args
= let -- keep type families saturated
n | isDecomposableTyCon tc = 0
| otherwise = tyConArity tc
(tc_args1, tc_args2) = splitAt n tc_args
in
(TyConApp tc tc_args1, tc_args2 ++ args)
split _ (FunTy ty1 ty2) args = ASSERT( null args )
(TyConApp funTyCon [], [ty1,ty2])
split orig_ty _ args = (orig_ty, args)
~~~~~
LitTy
~~~~~
-}
mkNumLitTy :: Integer -> Type
mkNumLitTy n = LitTy (NumTyLit n)
-- | Is this a numeric literal. We also look through type synonyms.
isNumLitTy :: Type -> Maybe Integer
isNumLitTy ty | Just ty1 <- tcView ty = isNumLitTy ty1
isNumLitTy (LitTy (NumTyLit n)) = Just n
isNumLitTy _ = Nothing
mkStrLitTy :: FastString -> Type
mkStrLitTy s = LitTy (StrTyLit s)
-- | Is this a symbol literal. We also look through type synonyms.
isStrLitTy :: Type -> Maybe FastString
isStrLitTy ty | Just ty1 <- tcView ty = isStrLitTy ty1
isStrLitTy (LitTy (StrTyLit s)) = Just s
isStrLitTy _ = Nothing
-- | Is this type a custom user error?
-- If so, give us the kind and the error message.
isUserErrorTy :: Type -> Maybe (Kind,Type)
isUserErrorTy t = do (tc,[k,msg]) <- splitTyConApp_maybe t
guard (tyConName tc == errorMessageTypeErrorFamName)
return (k,msg)
| Render a type corresponding to a user type error into a SDoc .
pprUserTypeErrorTy :: Type -> SDoc
pprUserTypeErrorTy ty =
case splitTyConApp_maybe ty of
-- Text "Something"
Just (tc,[txt])
| tyConName tc == typeErrorTextDataConName
, Just str <- isStrLitTy txt -> ftext str
ShowType t
Just (tc,[_k,t])
| tyConName tc == typeErrorShowTypeDataConName -> ppr t
-- t1 :<>: t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorAppendDataConName ->
pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2
-- t1 :$$: t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorVAppendDataConName ->
pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2
-- An uneavaluated type function
_ -> ppr ty
---------------------------------------------------------------------
FunTy
~~~~~
---------------------------------------------------------------------
FunTy
~~~~~
-}
mkFunTy :: Type -> Type -> Type
-- ^ Creates a function type from the given argument and result type
mkFunTy arg res = FunTy arg res
mkFunTys :: [Type] -> Type -> Type
mkFunTys tys ty = foldr mkFunTy ty tys
isFunTy :: Type -> Bool
isFunTy ty = isJust (splitFunTy_maybe ty)
splitFunTy :: Type -> (Type, Type)
-- ^ Attempts to extract the argument and result types from a type, and
-- panics if that is not possible. See also 'splitFunTy_maybe'
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
splitFunTy (FunTy arg res) = (arg, res)
splitFunTy other = pprPanic "splitFunTy" (ppr other)
splitFunTy_maybe :: Type -> Maybe (Type, Type)
-- ^ Attempts to extract the argument and result types from a type
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
splitFunTy_maybe (FunTy arg res) = Just (arg, res)
splitFunTy_maybe _ = Nothing
splitFunTys :: Type -> ([Type], Type)
splitFunTys ty = split [] ty ty
where
split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
split args _ (FunTy arg res) = split (arg:args) res res
split args orig_ty _ = (reverse args, orig_ty)
splitFunTysN :: Int -> Type -> ([Type], Type)
-- ^ Split off exactly the given number argument types, and panics if that is not possible
splitFunTysN 0 ty = ([], ty)
splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
case splitFunTy ty of { (arg, res) ->
case splitFunTysN (n-1) res of { (args, res) ->
(arg:args, res) }}
-- | Splits off argument types from the given type and associating
-- them with the things in the input list from left to right. The
-- final result type is returned, along with the resulting pairs of
-- objects and types, albeit with the list of pairs in reverse order.
-- Panics if there are not enough argument types for the input list.
zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
where
split acc [] nty _ = (reverse acc, nty)
split acc xs nty ty
| Just ty' <- coreView ty = split acc xs nty ty'
split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
funResultTy :: Type -> Type
-- ^ Extract the function result type and panic if that is not possible
funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
funResultTy (FunTy _arg res) = res
funResultTy ty = pprPanic "funResultTy" (ppr ty)
funArgTy :: Type -> Type
-- ^ Extract the function argument type and panic if that is not possible
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
funArgTy (FunTy arg _res) = arg
funArgTy ty = pprPanic "funArgTy" (ppr ty)
piResultTy :: Type -> Type -> Type
piResultTy ty arg = case piResultTy_maybe ty arg of
Just res -> res
Nothing -> pprPanic "piResultTy" (ppr ty $$ ppr arg)
piResultTy_maybe :: Type -> Type -> Maybe Type
-- ^ Just like 'piResultTys' but for a single argument
-- Try not to iterate 'piResultTy', because it's inefficient to substitute
one variable at a time ; instead use ' piResultTys "
piResultTy_maybe ty arg
| Just ty' <- coreView ty = piResultTy_maybe ty' arg
| FunTy _ res <- ty
= Just res
| ForAllTy tv res <- ty
= let empty_subst = extendTvInScopeList emptyTvSubst
$ varSetElems $ tyVarsOfTypes [arg,res]
in Just (substTy (extendTvSubst empty_subst tv arg) res)
| otherwise
= Nothing
{-
---------------------------------------------------------------------
TyConApp
~~~~~~~~
-}
-- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
-- its arguments. Applies its arguments to the constructor from left to right.
mkTyConApp :: TyCon -> [Type] -> Type
mkTyConApp tycon tys
| isFunTyCon tycon, [ty1,ty2] <- tys
= FunTy ty1 ty2
| otherwise
= TyConApp tycon tys
-- splitTyConApp "looks through" synonyms, because they don't
-- mean a distinct type, but all other type-constructor applications
-- including functions are returned as Just ..
| The same as @fst . splitTyConApp@
tyConAppTyCon_maybe :: Type -> Maybe TyCon
tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty'
tyConAppTyCon_maybe (TyConApp tc _) = Just tc
tyConAppTyCon_maybe (FunTy {}) = Just funTyCon
tyConAppTyCon_maybe _ = Nothing
tyConAppTyCon :: Type -> TyCon
tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty)
| The same as @snd . splitTyConApp@
tyConAppArgs_maybe :: Type -> Maybe [Type]
tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty'
tyConAppArgs_maybe (TyConApp _ tys) = Just tys
tyConAppArgs_maybe (FunTy arg res) = Just [arg,res]
tyConAppArgs_maybe _ = Nothing
tyConAppArgs :: Type -> [Type]
tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty)
tyConAppArgN :: Int -> Type -> Type
-- Executing Nth
tyConAppArgN n ty
= case tyConAppArgs_maybe ty of
Just tys -> ASSERT2( n < length tys, ppr n <+> ppr tys ) tys !! n
Nothing -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty)
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor. Panics if that is not possible.
-- See also 'splitTyConApp_maybe'
splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
Just stuff -> stuff
Nothing -> pprPanic "splitTyConApp" (ppr ty)
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
splitTyConApp_maybe _ = Nothing
-- | Attempts to tease a list type apart and gives the type of the elements if
-- successful (looks through type synonyms)
splitListTyConApp_maybe :: Type -> Maybe Type
splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of
Just (tc,[e]) | tc == listTyCon -> Just e
_other -> Nothing
-- | What is the role assigned to the next parameter of this type? Usually,
-- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to
-- do better. The type does *not* have to be well-kinded when applied for this
-- to work!
nextRole :: Type -> Role
nextRole ty
| Just (tc, tys) <- splitTyConApp_maybe ty
, let num_tys = length tys
, num_tys < tyConArity tc
= tyConRoles tc `getNth` num_tys
| otherwise
= Nominal
newTyConInstRhs :: TyCon -> [Type] -> Type
-- ^ Unwrap one 'layer' of newtype on a type constructor and its
-- arguments, using an eta-reduced version of the @newtype@ if possible.
-- This requires tys to have at least @newTyConInstArity tycon@ elements.
newTyConInstRhs tycon tys
= ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs )
applyTysX tvs rhs tys
where
(tvs, rhs) = newTyConEtadRhs tycon
---------------------------------------------------------------------
~~~~~
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various " split " functions ( splitFunTy , splitRhoTy , splitForAllTy ) try
to return type synonyms wherever possible . Thus
type a = a - > a
we want
splitFunTys ( a - > Foo a ) = ( [ a ] , a )
not ( [ a ] , a - > a )
The reason is that we then get better ( shorter ) type signatures in
interfaces . Notably this plays a role in tcTySigs in TcBinds.lhs .
Representation types
~~~~~~~~~~~~~~~~~~~~
Note [ Nullary unboxed tuple ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We represent the nullary unboxed tuple as the unary ( but void ) type
Void # . The reason for this is that the ReprArity is never
less than the Arity ( as it would otherwise be for a function type like
( # # ) - > Int ) .
As a result , ReprArity is always strictly positive if Arity is . This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument !
---------------------------------------------------------------------
SynTy
~~~~~
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
to return type synonyms wherever possible. Thus
type Foo a = a -> a
we want
splitFunTys (a -> Foo a) = ([a], Foo a)
not ([a], a -> a)
The reason is that we then get better (shorter) type signatures in
interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
Representation types
~~~~~~~~~~~~~~~~~~~~
Note [Nullary unboxed tuple]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We represent the nullary unboxed tuple as the unary (but void) type
Void#. The reason for this is that the ReprArity is never
less than the Arity (as it would otherwise be for a function type like
(# #) -> Int).
As a result, ReprArity is always strictly positive if Arity is. This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument!
-}
type UnaryType = Type
INVARIANT : never an empty list ( see Note [ Nullary unboxed tuple ] )
| UnaryRep UnaryType
flattenRepType :: RepType -> [UnaryType]
flattenRepType (UbxTupleRep tys) = tys
flattenRepType (UnaryRep ty) = [ty]
-- | Looks through:
--
1 . For - alls
2 . Synonyms
3 . Predicates
4 . All newtypes , including recursive ones , but not newtype families
--
-- It's useful in the back end of the compiler.
repType :: Type -> RepType
repType ty
= go initRecTc ty
where
go :: RecTcChecker -> Type -> RepType
go rec_nts ty -- Expand predicates and synonyms
| Just ty' <- coreView ty
= go rec_nts ty'
go rec_nts (ForAllTy _ ty) -- Drop foralls
= go rec_nts ty
go rec_nts (TyConApp tc tys) -- Expand newtypes
| isNewTyCon tc
, tys `lengthAtLeast` tyConArity tc
, Just rec_nts' <- checkRecTc rec_nts tc -- See Note [Expanding newtypes] in TyCon
= go rec_nts' (newTyConInstRhs tc tys)
| isUnboxedTupleTyCon tc
= if null tys
See Note [ Nullary unboxed tuple ]
else UbxTupleRep (concatMap (flattenRepType . go rec_nts) tys)
go _ ty = UnaryRep ty
-- | All type constructors occurring in the type; looking through type
-- synonyms, but not newtypes.
When it finds a Class , it returns the class .
tyConsOfType :: Type -> NameEnv TyCon
tyConsOfType ty
= go ty
where
The NameEnv does duplicate elim
go ty | Just ty' <- tcView ty = go ty'
go (TyVarTy {}) = emptyNameEnv
go (LitTy {}) = emptyNameEnv
go (TyConApp tc tys) = go_tc tc tys
go (AppTy a b) = go a `plusNameEnv` go b
go (FunTy a b) = go a `plusNameEnv` go b
go (ForAllTy _ ty) = go ty
go_tc tc tys = extendNameEnv (go_s tys) (tyConName tc) tc
go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
ToDo : this could be moved to the code generator , using instead
-- of inspecting the type directly.
| Discovers the primitive representation of a more abstract ' UnaryType '
typePrimRep :: UnaryType -> PrimRep
typePrimRep = typePrimRep' False
typePrimRep' :: Bool -> UnaryType -> PrimRep
typePrimRep' sobject ty
= case repType ty of
UbxTupleRep _ -> pprPanic "typePrimRep: UbxTupleRep" (ppr ty)
UnaryRep rep -> case rep of
TyConApp tc tys ->
case primRep of
ObjectRep x
| T.null x -> objRep
| otherwise -> primRep
_ -> primRep
where primRep = tyConPrimRep tc
objRep = mkObjectRep (tagTypeToText' sobject (head tys))
FunTy _ _ -> PtrRep
AppTy _ _ -> PtrRep -- See Note [AppTy rep]
TyVarTy _ -> PtrRep
_ -> pprPanic "typePrimRep: UnaryRep" (ppr ty)
stypePrimRep :: UnaryType -> PrimRep
stypePrimRep = typePrimRep' True
typePrimRepMany :: Type -> [PrimRep]
typePrimRepMany ty
= case repType ty of
UbxTupleRep utys -> map typePrimRep utys
UnaryRep uty -> [typePrimRep uty]
mkObjectRep :: Text -> PrimRep
mkObjectRep text
| T.takeEnd 2 text == "[]" = ArrayRep (mkObjectRep (T.dropEnd 2 text))
| otherwise = checkPrimitiveType text
where checkPrimitiveType "boolean" = BoolRep
checkPrimitiveType "byte" = ByteRep
checkPrimitiveType "short" = ShortRep
checkPrimitiveType "char" = CharRep
checkPrimitiveType "int" = IntRep
checkPrimitiveType "long" = Int64Rep
checkPrimitiveType "float" = FloatRep
checkPrimitiveType "double" = DoubleRep
checkPrimitiveType text = ObjectRep text
tagTypeToText :: Type -> Text
tagTypeToText = tagTypeToText' False
stagTypeToText :: Type -> Text
stagTypeToText = tagTypeToText' True
tagTypeToText' :: Bool -> Type -> Text
tagTypeToText' sobject ty = transform $
maybe ( T.pack "java/lang/Object" )
( T.map (\c -> if c == '.' then '/' else c)
. head
. T.words )
where transform f = either (uncurry pprPanic) f $ rawTagTypeToText' sobject ty
symbolLitToText :: Type -> Maybe Text
symbolLitToText ty | Just ty' <- coreView ty = symbolLitToText ty'
symbolLitToText (LitTy (StrTyLit fs)) = Just $ fastStringToText fs
symbolLitToText _ = Nothing
rawTagTypeToText :: Type -> Either (String, SDoc) (Maybe Text)
rawTagTypeToText = rawTagTypeToText' False
rawTagTypeToText' :: Bool -> Type -> Either (String, SDoc) (Maybe Text)
rawTagTypeToText' sobject ty
| Just (tc1, tys) <- splitTyConApp_maybe ty
, not (isFamilyTyCon tc1)
= if | sobject && tc1 `hasKey` sobjectTyConKey -> Right $ symbolLitToText (head tys)
| otherwise ->
case tyConCType_maybe tc1 of
Just (CType _ _ fs) -> Right . Just $ fastStringToText fs
Nothing -> Left ("rawTagTypeToText: You should annotate ", ppr ty)
| otherwise = Right Nothing
typeRepArity :: Arity -> Type -> RepArity
typeRepArity 0 _ = 0
typeRepArity n ty = case repType ty of
UnaryRep (FunTy ty1 ty2) -> length (flattenRepType (repType ty1)) + typeRepArity (n - 1) ty2
_ -> pprPanic "typeRepArity: arity greater than type can handle" (ppr (n, ty))
isVoidTy :: Type -> Bool
True if the type has zero width
isVoidTy ty = case repType ty of
UnaryRep (TyConApp tc _) -> isVoidRep (tyConPrimRep tc)
_ -> False
Note [ AppTy rep ]
~~~~~~~~~~~~~~~~
Types of the form ' f a ' must be of kind * , not # , so we are guaranteed
that they are represented by pointers . The reason is that f must have
kind ( kk - > kk ) and kk can not be unlifted ; see Note [ The kind invariant ]
in TypeRep .
---------------------------------------------------------------------
ForAllTy
~~~~~~~~
Note [AppTy rep]
~~~~~~~~~~~~~~~~
Types of the form 'f a' must be of kind *, not #, so we are guaranteed
that they are represented by pointers. The reason is that f must have
kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant]
in TypeRep.
---------------------------------------------------------------------
ForAllTy
~~~~~~~~
-}
mkForAllTy :: TyVar -> Type -> Type
mkForAllTy tyvar ty
= ForAllTy tyvar ty
| Wraps foralls over the type using the provided ' TyVar 's from left to right
mkForAllTys :: [TyVar] -> Type -> Type
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
mkPiKinds :: [TyVar] -> Kind -> Kind
-- mkPiKinds [k1, k2, (a:k1 -> *)] k2
-- returns forall k1 k2. (k1 -> *) -> k2
mkPiKinds [] res = res
mkPiKinds (tv:tvs) res
| isKindVar tv = ForAllTy tv (mkPiKinds tvs res)
| otherwise = FunTy (tyVarKind tv) (mkPiKinds tvs res)
mkPiType :: Var -> Type -> Type
^ Makes a type or a forall type , depending
-- on whether it is given a type variable or a term variable.
mkPiTypes :: [Var] -> Type -> Type
^ ' mkPiType ' for multiple type or value arguments
mkPiType v ty
| isId v = mkFunTy (varType v) ty
| otherwise = mkForAllTy v ty
mkPiTypes vs ty = foldr mkPiType ty vs
isForAllTy :: Type -> Bool
isForAllTy (ForAllTy _ _) = True
isForAllTy _ = False
-- | Attempts to take a forall type apart, returning the bound type variable
-- and the remainder of the type
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
splitForAllTy_maybe ty = splitFAT_m ty
where
splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
splitFAT_m _ = Nothing
-- | Attempts to take a forall type apart, returning all the immediate such bound
type variables and the remainder of the type . Always suceeds , even if that means
returning an empty list of ' TyVar 's
splitForAllTys :: Type -> ([TyVar], Type)
splitForAllTys ty = split ty ty []
where
split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
split orig_ty _ tvs = (reverse tvs, orig_ty)
-- | Equivalent to @snd . splitForAllTys@
dropForAlls :: Type -> Type
dropForAlls ty = snd (splitForAllTys ty)
-- ( mkPiType now in CoreUtils )
applyTy , applyTys
~~~~~~~~~~~~~~~~~
-- (mkPiType now in CoreUtils)
applyTy, applyTys
~~~~~~~~~~~~~~~~~
-}
| Instantiate a forall type with one or more type arguments .
-- Used when we have a polymorphic function applied to type args:
--
-- > f t1 t2
--
-- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
-- Panics if no application is possible.
applyTy :: Type -> KindOrType -> Type
applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
applyTy _ _ = panic "applyTy"
applyTys :: Type -> [KindOrType] -> Type
-- ^ This function is interesting because:
--
1 . The function may have more for - alls than there are args
--
2 . Less obviously , it may have fewer for - alls
--
For case 2 . think of :
--
-- > applyTys (forall a.a) [forall b.b, Int]
--
-- This really can happen, but only (I think) in situations involving
-- undefined. For example:
-- undefined :: forall a. a
-- Term: undefined @(forall b. b->b) @Int
-- This term should have type (Int -> Int), but notice that
-- there are more type args than foralls in 'undefined's type.
If you edit this function , you may need to update the GHC formalism
See Note [ GHC Formalism ] in coreSyn / CoreLint.lhs
applyTys ty args = applyTysD empty ty args
applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version
applyTysD _ orig_fun_ty [] = orig_fun_ty
applyTysD doc orig_fun_ty arg_tys
| n_tvs == n_args -- The vastly common case
= substTyWith tvs arg_tys rho_ty
| n_tvs > n_args -- Too many for-alls
= substTyWith (take n_args tvs) arg_tys
(mkForAllTys (drop n_args tvs) rho_ty)
| otherwise -- Too many type args
Zero case gives infinite loop !
applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
(drop n_tvs arg_tys)
where
(tvs, rho_ty) = splitForAllTys orig_fun_ty
n_tvs = length tvs
n_args = length arg_tys
applyTysX :: [TyVar] -> Type -> [Type] -> Type
-- applyTyxX beta-reduces (/\tvs. body_ty) arg_tys
applyTysX tvs body_ty arg_tys
= ASSERT2( length arg_tys >= n_tvs, ppr tvs $$ ppr body_ty $$ ppr arg_tys )
mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty)
(drop n_tvs arg_tys)
where
n_tvs = length tvs
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Pred
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Predicates on PredType
************************************************************************
* *
Pred
* *
************************************************************************
Predicates on PredType
-}
isPredTy :: Type -> Bool
-- NB: isPredTy is used when printing types, which can happen in debug printing
-- during type checking of not-fully-zonked types. So it's not cool to say
-- isConstraintKind (typeKind ty) because absent zonking the type might
-- be ill-kinded, and typeKind crashes
-- Hence the rather tiresome story here
isPredTy ty = go ty []
where
go :: Type -> [KindOrType] -> Bool
go (AppTy ty1 ty2) args = go ty1 (ty2 : args)
go (TyConApp tc tys) args = go_k (tyConKind tc) (tys ++ args)
go (TyVarTy tv) args = go_k (tyVarKind tv) args
go _ _ = False
go_k :: Kind -> [KindOrType] -> Bool
-- True <=> kind is k1 -> .. -> kn -> Constraint
go_k k [] = isConstraintKind k
go_k (FunTy _ k1) (_ :args) = go_k k1 args
go_k (ForAllTy kv k1) (k2:args) = go_k (substKiWith [kv] [k2] k1) args
go_k _ _ = False -- Typeable * Int :: Constraint
isClassPred, isEqPred, isIPPred :: PredType -> Bool
isClassPred ty = case tyConAppTyCon_maybe ty of
Just tyCon | isClassTyCon tyCon -> True
_ -> False
isEqPred ty = case tyConAppTyCon_maybe ty of
Just tyCon -> tyCon `hasKey` eqTyConKey
_ -> False
isIPPred ty = case tyConAppTyCon_maybe ty of
Just tc -> isIPTyCon tc
_ -> False
isIPTyCon :: TyCon -> Bool
isIPTyCon tc = tc `hasKey` ipTyConKey
isIPClass :: Class -> Bool
isIPClass cls = cls `hasKey` ipTyConKey
Class and it corresponding have the same Unique
isIPPred_maybe :: Type -> Maybe (FastString, Type)
isIPPred_maybe ty =
do (tc,[t1,t2]) <- splitTyConApp_maybe ty
guard (isIPTyCon tc)
x <- isStrLitTy t1
return (x,t2)
Make PredTypes
--------------------- Equality types ---------------------------------
Make PredTypes
--------------------- Equality types ---------------------------------
-}
-- | Creates a type equality predicate
mkEqPred :: Type -> Type -> PredType
mkEqPred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 $$ ppr k $$ ppr (typeKind ty2) )
TyConApp eqTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkCoerciblePred :: Type -> Type -> PredType
mkCoerciblePred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 $$ ppr k $$ ppr (typeKind ty2) )
TyConApp coercibleTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkPrimEqPred :: Type -> Type -> Type
mkPrimEqPred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 )
TyConApp eqPrimTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkReprPrimEqPred :: Type -> Type -> Type
mkReprPrimEqPred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 )
TyConApp eqReprPrimTyCon [k, ty1, ty2]
where
k = typeKind ty1
-- --------------------- Dictionary types ---------------------------------
mkClassPred :: Class -> [Type] -> PredType
mkClassPred clas tys = TyConApp (classTyCon clas) tys
isDictTy :: Type -> Bool
isDictTy = isClassPred
isDictLikeTy :: Type -> Bool
-- Note [Dictionary-like types]
isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty'
isDictLikeTy ty = case splitTyConApp_maybe ty of
Just (tc, tys) | isClassTyCon tc -> True
| isTupleTyCon tc -> all isDictLikeTy tys
_other -> False
Note [ Dictionary - like types ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being " dictionary - like " means either a dictionary type or a tuple thereof .
In GHC 6.10 we build implication constraints which construct such tuples ,
and if we land up with a binding
t : : ( C [ a ] , [ a ] )
t = blah
then we want to treat t as cheap under " -fdicts - cheap " for example .
( Implication constraints are normally inlined , but sadly not if the
occurrence is itself inside an INLINE function ! Until we revise the
handling of implication constraints , that is . ) This turned out to
be important in getting good arities in DPH code . Example :
class C a
class D a where { foo : : a - > a }
instance C a = > D ( Maybe a ) where { foo x = x }
bar : : ( C a , C b ) = > a - > b - > ( Maybe a , Maybe b )
{ - # INLINE bar #
Note [Dictionary-like types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being "dictionary-like" means either a dictionary type or a tuple thereof.
In GHC 6.10 we build implication constraints which construct such tuples,
and if we land up with a binding
t :: (C [a], Eq [a])
t = blah
then we want to treat t as cheap under "-fdicts-cheap" for example.
(Implication constraints are normally inlined, but sadly not if the
occurrence is itself inside an INLINE function! Until we revise the
handling of implication constraints, that is.) This turned out to
be important in getting good arities in DPH code. Example:
class C a
class D a where { foo :: a -> a }
instance C a => D (Maybe a) where { foo x = x }
bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
{-# INLINE bar #-}
bar x y = (foo (Just x), foo (Just y))
Then 'bar' should jolly well have arity 4 (two dicts, two args), but
we ended up with something like
bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
in \x,y. <blah>)
This is all a bit ad-hoc; eg it relies on knowing that implication
constraints build tuples.
Decomposing PredType
-}
-- | A choice of equality relation. This is separate from the type 'Role'
because ' Phantom ' does not define a ( non - trivial ) equality relation .
data EqRel = NomEq | ReprEq
deriving (Eq, Ord)
instance Outputable EqRel where
ppr NomEq = text "nominal equality"
ppr ReprEq = text "representational equality"
eqRelRole :: EqRel -> Role
eqRelRole NomEq = Nominal
eqRelRole ReprEq = Representational
data PredTree = ClassPred Class [Type]
| EqPred EqRel Type Type
| TuplePred [PredType]
| IrredPred PredType
classifyPredType :: PredType -> PredTree
classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
Just (tc, tys) | tc `hasKey` coercibleTyConKey
, let [_, ty1, ty2] = tys
-> EqPred ReprEq ty1 ty2
Just (tc, tys) | tc `hasKey` eqTyConKey
, let [_, ty1, ty2] = tys
-> EqPred NomEq ty1 ty2
-- NB: Coercible is also a class, so this check must come *after*
-- the Coercible check
Just (tc, tys) | Just clas <- tyConClass_maybe tc
-> ClassPred clas tys
Just (tc, tys) | isTupleTyCon tc
-> TuplePred tys
_ -> IrredPred ev_ty
getClassPredTys :: PredType -> (Class, [Type])
getClassPredTys ty = case getClassPredTys_maybe ty of
Just (clas, tys) -> (clas, tys)
Nothing -> pprPanic "getClassPredTys" (ppr ty)
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
_ -> Nothing
getEqPredTys :: PredType -> (Type, Type)
getEqPredTys ty
= case splitTyConApp_maybe ty of
Just (tc, (_ : ty1 : ty2 : tys)) ->
ASSERT( null tys && (tc `hasKey` eqTyConKey
|| tc `hasKey` coercibleTyConKey) )
(ty1, ty2)
_ -> pprPanic "getEqPredTys" (ppr ty)
getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
getEqPredTys_maybe ty
= case splitTyConApp_maybe ty of
Just (tc, [_, ty1, ty2])
| tc `hasKey` eqTyConKey -> Just (Nominal, ty1, ty2)
| tc `hasKey` coercibleTyConKey -> Just (Representational, ty1, ty2)
_ -> Nothing
getEqPredRole :: PredType -> Role
getEqPredRole ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, _])
| tc `hasKey` eqTyConKey -> Nominal
| tc `hasKey` coercibleTyConKey -> Representational
_ -> pprPanic "getEqPredRole" (ppr ty)
-- | Get the equality relation relevant for a pred type.
predTypeEqRel :: PredType -> EqRel
predTypeEqRel ty
| Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` coercibleTyConKey
= ReprEq
| otherwise
= NomEq
{-
%************************************************************************
%* *
Size
* *
************************************************************************
-}
typeSize :: Type -> Int
typeSize (LitTy {}) = 1
typeSize (TyVarTy {}) = 1
typeSize (AppTy t1 t2) = typeSize t1 + typeSize t2
typeSize (FunTy t1 t2) = typeSize t1 + typeSize t2
typeSize (ForAllTy _ t) = 1 + typeSize t
typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts)
{-
************************************************************************
* *
\subsection{Type families}
* *
************************************************************************
-}
mkFamilyTyConApp :: TyCon -> [Type] -> Type
^ Given a family instance and its arg types , return the
-- corresponding family type. E.g:
--
-- > data family T a
-- > data instance T (Maybe b) = MkT b
--
Where the instance tycon is : RTL , so :
--
> mkFamilyTyConApp : RTL Int = T ( Maybe Int )
mkFamilyTyConApp tc tys
| Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
, let tvs = tyConTyVars tc
fam_subst = ASSERT2( length tvs == length tys, ppr tc <+> ppr tys )
zipTopTvSubst tvs tys
= mkTyConApp fam_tc (substTys fam_subst fam_tys)
| otherwise
= mkTyConApp tc tys
| Get the type on the LHS of a coercion induced by a type / data
-- family instance.
coAxNthLHS :: CoAxiom br -> Int -> Type
coAxNthLHS ax ind =
mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind))
| Pretty prints a ' ' , using the family instance in case of a
-- representation tycon. For example:
--
-- > data T [a] = ...
--
In that case we want to print @T [ a]@ , where @T@ is the family ' '
pprSourceTyCon :: TyCon -> SDoc
pprSourceTyCon tycon
| Just (fam_tc, tys) <- tyConFamInst_maybe tycon
ca n't be
| otherwise
= ppr tycon
{-
************************************************************************
* *
\subsection{Liftedness}
* *
************************************************************************
-}
-- | See "Type#type_classification" for what an unlifted type is
isUnLiftedType :: Type -> Bool
-- isUnLiftedType returns True for forall'd unlifted types:
-- x :: forall a. Int#
-- I found bindings like these were getting floated to the top level.
-- They are pretty bogus types, mind you. It would be better never to
-- construct them
isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
isUnLiftedType _ = False
isUnboxedTupleType :: Type -> Bool
isUnboxedTupleType ty = case tyConAppTyCon_maybe ty of
Just tc -> isUnboxedTupleTyCon tc
_ -> False
-- | See "Type#type_classification" for what an algebraic type is.
-- Should only be applied to /types/, as opposed to e.g. partially
-- saturated type constructors
isAlgType :: Type -> Bool
isAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isAlgTyCon tc
_other -> False
-- | See "Type#type_classification" for what an algebraic type is.
-- Should only be applied to /types/, as opposed to e.g. partially
-- saturated type constructors. Closed type constructors are those
-- with a fixed right hand side, as opposed to e.g. associated types
isClosedAlgType :: Type -> Bool
isClosedAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc)
-> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
_other -> False
-- | Computes whether an argument (or let right hand side) should
-- be computed strictly or lazily, based only on its type.
-- Currently, it's just 'isUnLiftedType'.
isStrictType :: Type -> Bool
isStrictType = isUnLiftedType
isPrimitiveType :: Type -> Bool
^ Returns true of types that are opaque to Haskell .
isPrimitiveType ty = case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isPrimTyCon tc
_ -> False
isObjectType :: Type -> Bool
isObjectType ty = case splitTyConApp_maybe ty of
Just (tc, _) -> isObjectTyCon tc
_ -> False
{-
************************************************************************
* *
\subsection{Sequencing on types}
* *
************************************************************************
-}
seqType :: Type -> ()
seqType (LitTy n) = n `seq` ()
seqType (TyVarTy tv) = tv `seq` ()
seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
seqType (TyConApp tc tys) = tc `seq` seqTypes tys
seqType (ForAllTy tv ty) = seqType (tyVarKind tv) `seq` seqType ty
seqTypes :: [Type] -> ()
seqTypes [] = ()
seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
{-
************************************************************************
* *
Comparison for types
(We don't use instances so that we know where it happens)
* *
************************************************************************
-}
eqKind :: Kind -> Kind -> Bool
-- Watch out for horrible hack: See Note [Comparison with OpenTypeKind]
eqKind = eqType
eqType :: Type -> Type -> Bool
-- ^ Type equality on source types. Does not look through @newtypes@ or
' PredType 's , but it does look through type synonyms .
-- Watch out for horrible hack: See Note [Comparison with OpenTypeKind]
eqType t1 t2 = isEqual $ cmpType t1 t2
instance Eq Type where
(==) = eqType
eqTypeX :: RnEnv2 -> Type -> Type -> Bool
eqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
eqTypes :: [Type] -> [Type] -> Bool
eqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
eqPred :: PredType -> PredType -> Bool
eqPred = eqType
eqPredX :: RnEnv2 -> PredType -> PredType -> Bool
eqPredX env p1 p2 = isEqual $ cmpTypeX env p1 p2
eqTyVarBndrs :: RnEnv2 -> [TyVar] -> [TyVar] -> Maybe RnEnv2
Check that the tyvar lists are the same length
and have matching kinds ; if so , extend the RnEnv2
-- Returns Nothing if they don't match
eqTyVarBndrs env [] []
= Just env
eqTyVarBndrs env (tv1:tvs1) (tv2:tvs2)
| eqTypeX env (tyVarKind tv1) (tyVarKind tv2)
= eqTyVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2
eqTyVarBndrs _ _ _= Nothing
-- Now here comes the real worker
cmpType :: Type -> Type -> Ordering
-- Watch out for horrible hack: See Note [Comparison with OpenTypeKind]
cmpType t1 t2 = cmpTypeX rn_env t1 t2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
cmpTypes :: [Type] -> [Type] -> Ordering
cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
cmpPred :: PredType -> PredType -> Ordering
cmpPred p1 p2 = cmpTypeX rn_env p1 p2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType p1 `unionVarSet` tyVarsOfType p2))
cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
cmpTypeX env t1 t2 | Just t1' <- coreView t1 = cmpTypeX env t1' t2
| Just t2' <- coreView t2 = cmpTypeX env t1 t2'
We expand predicate types , because in Core - land we have
-- lots of definitions like
fOrdBool : :
-- fOrdBool = D:Ord .. .. ..
So the RHS has a data type
cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX env (tyVarKind tv1) (tyVarKind tv2)
`thenCmp` cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `cmpTc` tc2) `thenCmp` cmpTypesX env tys1 tys2
cmpTypeX _ (LitTy l1) (LitTy l2) = compare l1 l2
Deal with the rest : TyVarTy < AppTy < FunTy < LitTy < TyConApp < ForAllTy < PredTy
cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
cmpTypeX _ (LitTy _) (TyVarTy _) = GT
cmpTypeX _ (LitTy _) (AppTy _ _) = GT
cmpTypeX _ (LitTy _) (FunTy _ _) = GT
cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
cmpTypeX _ (TyConApp _ _) (LitTy _) = GT
cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
cmpTypeX _ (ForAllTy _ _) (LitTy _) = GT
cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
cmpTypeX _ _ _ = LT
-------------
cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
cmpTypesX _ [] [] = EQ
cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
cmpTypesX _ [] _ = LT
cmpTypesX _ _ [] = GT
-------------
cmpTc :: TyCon -> TyCon -> Ordering
Here we treat * and Constraint as equal
See Note [ Kind Constraint and kind * ] in Kinds.lhs
--
-- Also we treat OpenTypeKind as equal to either * or #
-- See Note [Comparison with OpenTypeKind]
cmpTc tc1 tc2
| u1 == openTypeKindTyConKey, isSubOpenTypeKindKey u2 = EQ
| u2 == openTypeKindTyConKey, isSubOpenTypeKindKey u1 = EQ
| otherwise = nu1 `compare` nu2
where
u1 = tyConUnique tc1
nu1 = if u1==constraintKindTyConKey then liftedTypeKindTyConKey else u1
u2 = tyConUnique tc2
nu2 = if u2==constraintKindTyConKey then liftedTypeKindTyConKey else u2
Note [ Comparison with OpenTypeKind ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In PrimOpWrappers we have things like
PrimOpWrappers.mkWeak # = /\ a b c. Prim.mkWeak # a b c
where
Prim.mkWeak # : : forall ( a : Open ) b c. a - > b - > c
- > State # RealWorld - > ( # State # RealWorld , Weak # b # )
Now , eta reduction will turn the definition into
PrimOpWrappers.mkWeak # = Prim.mkWeak #
which is kind - of OK , but now the types are n't really equal . So HACK HACK
we pretend ( in Core ) that Open is equal to * or # . I hate this .
Note [ cmpTypeX ]
~~~~~~~~~~~~~~~
When we compare foralls , we should look at the kinds . But if we do so ,
we get a corelint error like the following ( in
libraries / ghc - prim / GHC / PrimopWrappers.hs ):
Binder 's type : forall ( o_abY : : * ) .
o_abY
- > GHC.Prim . State # GHC.Prim . RealWorld
- > GHC.Prim . State # GHC.Prim . RealWorld
Rhs type : forall ( a_12 : : ? ) .
a_12
- > GHC.Prim . State # GHC.Prim . RealWorld
- > GHC.Prim . State # GHC.Prim . RealWorld
This is why we do n't look at the kind . Maybe we should look if the
kinds are compatible .
-- cmpTypeX env ( ForAllTy t1 ) ( ForAllTy tv2 t2 )
-- = cmpTypeX env ( tyVarKind ) ( tyVarKind tv2 ) ` thenCmp `
-- cmpTypeX ( rnBndr2 env tv2 ) t1 t2
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Type substitutions
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Note [Comparison with OpenTypeKind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In PrimOpWrappers we have things like
PrimOpWrappers.mkWeak# = /\ a b c. Prim.mkWeak# a b c
where
Prim.mkWeak# :: forall (a:Open) b c. a -> b -> c
-> State# RealWorld -> (# State# RealWorld, Weak# b #)
Now, eta reduction will turn the definition into
PrimOpWrappers.mkWeak# = Prim.mkWeak#
which is kind-of OK, but now the types aren't really equal. So HACK HACK
we pretend (in Core) that Open is equal to * or #. I hate this.
Note [cmpTypeX]
~~~~~~~~~~~~~~~
When we compare foralls, we should look at the kinds. But if we do so,
we get a corelint error like the following (in
libraries/ghc-prim/GHC/PrimopWrappers.hs):
Binder's type: forall (o_abY :: *).
o_abY
-> GHC.Prim.State# GHC.Prim.RealWorld
-> GHC.Prim.State# GHC.Prim.RealWorld
Rhs type: forall (a_12 :: ?).
a_12
-> GHC.Prim.State# GHC.Prim.RealWorld
-> GHC.Prim.State# GHC.Prim.RealWorld
This is why we don't look at the kind. Maybe we should look if the
kinds are compatible.
-- cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2)
-- = cmpTypeX env (tyVarKind tv1) (tyVarKind tv2) `thenCmp`
-- cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
************************************************************************
* *
Type substitutions
* *
************************************************************************
-}
emptyTvSubstEnv :: TvSubstEnv
emptyTvSubstEnv = emptyVarEnv
composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
^ @(compose env1 env2)(x)@ is @env1(env2(x))@ ; i.e. apply @env2@ then @env1@.
-- It assumes that both are idempotent.
-- Typically, @env1@ is the refinement to a base substitution @env2@
composeTvSubst in_scope env1 env2
= env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
First apply env1 to the range of env2
Then combine the two , making sure that env1 loses if
both bind the same variable ; that 's why env1 is the
-- *left* argument to plusVarEnv, because the right arg wins
where
subst1 = TvSubst in_scope env1
emptyTvSubst :: TvSubst
emptyTvSubst = TvSubst emptyInScopeSet emptyTvSubstEnv
isEmptyTvSubst :: TvSubst -> Bool
See Note [ Extending the TvSubstEnv ] in TypeRep
isEmptyTvSubst (TvSubst _ tenv) = isEmptyVarEnv tenv
mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
mkTvSubst = TvSubst
getTvSubstEnv :: TvSubst -> TvSubstEnv
getTvSubstEnv (TvSubst _ env) = env
getTvInScope :: TvSubst -> InScopeSet
getTvInScope (TvSubst in_scope _) = in_scope
isInScope :: Var -> TvSubst -> Bool
isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
notElemTvSubst :: CoVar -> TvSubst -> Bool
notElemTvSubst v (TvSubst _ tenv) = not (v `elemVarEnv` tenv)
setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
setTvSubstEnv (TvSubst in_scope _) tenv = TvSubst in_scope tenv
zapTvSubstEnv :: TvSubst -> TvSubst
zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
extendTvInScope :: TvSubst -> Var -> TvSubst
extendTvInScope (TvSubst in_scope tenv) var = TvSubst (extendInScopeSet in_scope var) tenv
extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
extendTvInScopeList (TvSubst in_scope tenv) vars = TvSubst (extendInScopeSetList in_scope vars) tenv
extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
extendTvSubst (TvSubst in_scope tenv) tv ty = TvSubst in_scope (extendVarEnv tenv tv ty)
extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
extendTvSubstList (TvSubst in_scope tenv) tvs tys
= TvSubst in_scope (extendVarEnvList tenv (tvs `zip` tys))
unionTvSubst :: TvSubst -> TvSubst -> TvSubst
-- Works when the ranges are disjoint
unionTvSubst (TvSubst in_scope1 tenv1) (TvSubst in_scope2 tenv2)
= ASSERT( not (tenv1 `intersectsVarEnv` tenv2) )
TvSubst (in_scope1 `unionInScope` in_scope2)
(tenv1 `plusVarEnv` tenv2)
mkOpenTvSubst and zipOpenTvSubst generate the in - scope set from
-- the types given; but it's just a thunk so with a bit of luck
-- it'll never be evaluated
-- Note [Generating the in-scope set for a substitution]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we want to substitute [ a - > , b - > ty2 ] I used to
-- think it was enough to generate an in-scope set that includes
-- fv(ty1,ty2). But that's not enough; we really should also take the
-- free vars of the type we are substituting into! Example:
-- (forall b. (a,b,x)) [a -> List b]
-- Then if we use the in-scope set {b}, there is a danger we will rename
-- the forall'd variable to 'x' by mistake, getting this:
-- (forall x. (List b, x, x)
! This means looking at all the calls to mkOpenTvSubst ....
| Generates the in - scope set for the ' ' from the types in the incoming
-- environment, hence "open"
mkOpenTvSubst :: TvSubstEnv -> TvSubst
mkOpenTvSubst tenv = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts tenv))) tenv
| Generates the in - scope set for the ' ' from the types in the incoming
-- environment, hence "open"
zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
zipOpenTvSubst tyvars tys
| debugIsOn && (length tyvars /= length tys)
= pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
| otherwise
= TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
-- | Called when doing top-level substitutions. Here we expect that the
-- free vars of the range of the substitution will be empty.
mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
zipTopTvSubst tyvars tys
| debugIsOn && (length tyvars /= length tys)
= pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
| otherwise
= TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
zipTyEnv tyvars tys
| debugIsOn && (length tyvars /= length tys)
= pprTrace "zipTyEnv" (ppr tyvars $$ ppr tys) emptyVarEnv
| otherwise
= zip_ty_env tyvars tys emptyVarEnv
-- Later substitutions in the list over-ride earlier ones,
-- but there should be no loops
zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
zip_ty_env [] [] env = env
zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
-- There used to be a special case for when
ty = = TyVarTy tv
-- (a not-uncommon case) in which case the substitution was dropped.
-- But the type-tidier changes the print-name of a type variable without
-- changing the unique, and that led to a bug. Why? Pre-tidying, we had
a type { Foo t } , where is a one - method class . So is really a newtype .
-- And it happened that t was the type variable of the class. Post-tiding,
-- it got turned into {Foo t2}. The ext-core printer expanded this using
-- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
-- and so generated a rep type mentioning t not t2.
--
-- Simplest fix is to nuke the "optimisation"
zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
-- zip_ty_env _ _ env = env
instance Outputable TvSubst where
ppr (TvSubst ins tenv)
= brackets $ sep[ ptext (sLit "TvSubst"),
nest 2 (ptext (sLit "In scope:") <+> ppr ins),
nest 2 (ptext (sLit "Type env:") <+> ppr tenv) ]
{-
************************************************************************
* *
Performing type or kind substitutions
* *
************************************************************************
-}
| Type substitution making use of an ' ' that
is assumed to be open , see ' zipOpenTvSubst '
substTyWith :: [TyVar] -> [Type] -> Type -> Type
substTyWith tvs tys = ASSERT( length tvs == length tys )
substTy (zipOpenTvSubst tvs tys)
substKiWith :: [KindVar] -> [Kind] -> Kind -> Kind
substKiWith = substTyWith
| Type substitution making use of an ' ' that
is assumed to be open , see ' zipOpenTvSubst '
substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
substTysWith tvs tys = ASSERT( length tvs == length tys )
substTys (zipOpenTvSubst tvs tys)
substKisWith :: [KindVar] -> [Kind] -> [Kind] -> [Kind]
substKisWith = substTysWith
-- | Substitute within a 'Type' after adding the free variables of the type
-- to the in-scope set. This is useful for the case when the free variables
-- aren't already in the in-scope set or easily available.
-- See also Note [The substitution invariant].
substTyAddInScope :: TvSubst -> Type -> Type
substTyAddInScope subst ty =
substTy (extendTvInScopeList subst $ varSetElems $ tyVarsOfType ty) ty
-- | Substitute within a 'Type'
substTy :: TvSubst -> Type -> Type
substTy subst ty | isEmptyTvSubst subst = ty
| otherwise = subst_ty subst ty
-- | Substitute within several 'Type's
substTys :: TvSubst -> [Type] -> [Type]
substTys subst tys | isEmptyTvSubst subst = tys
| otherwise = map (subst_ty subst) tys
| Substitute within a ' ThetaType '
substTheta :: TvSubst -> ThetaType -> ThetaType
substTheta subst theta
| isEmptyTvSubst subst = theta
| otherwise = map (substTy subst) theta
| Remove any nested binders mentioning the ' TyVar 's in the ' TyVarSet '
deShadowTy :: TyVarSet -> Type -> Type
deShadowTy tvs ty
= subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
where
in_scope = mkInScopeSet tvs
subst_ty :: TvSubst -> Type -> Type
-- subst_ty is the main workhorse for type substitution
--
-- Note that the in_scope set is poked only if we hit a forall
-- so it may often never be fully computed
subst_ty subst ty
= go ty
where
go (LitTy n) = n `seq` LitTy n
go (TyVarTy tv) = substTyVar subst tv
go (TyConApp tc tys) = let args = map go tys
in args `seqList` TyConApp tc args
go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
The mkAppTy smart constructor is important
-- we might be replacing (a Int), represented with App
-- by [Int], represented with TyConApp
go (ForAllTy tv ty) = case substTyVarBndr subst tv of
(subst', tv') ->
ForAllTy tv' $! (subst_ty subst' ty)
substTyVar :: TvSubst -> TyVar -> Type
substTyVar (TvSubst _ tenv) tv
| Just ty <- lookupVarEnv tenv tv = ty -- See Note [Apply Once]
in TypeRep
We do not require that the tyvar is in scope
-- Reason: we do quite a bit of (substTyWith [tv] [ty] tau)
-- and it's a nuisance to bring all the free vars of tau into
-- scope --- and then force that thunk at every tyvar
Instead we have an ASSERT in substTyVarBndr to check for capture
substTyVars :: TvSubst -> [TyVar] -> [Type]
substTyVars subst tvs = map (substTyVar subst) tvs
lookupTyVar :: TvSubst -> TyVar -> Maybe Type
See Note [ Extending the TvSubst ] in TypeRep
lookupTyVar (TvSubst _ tenv) tv = lookupVarEnv tenv tv
substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
substTyVarBndr subst@(TvSubst in_scope tenv) old_var
= ASSERT2( _no_capture, ppr old_var $$ ppr subst )
(TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
where
new_env | no_change = delVarEnv tenv old_var
| otherwise = extendVarEnv tenv old_var (TyVarTy new_var)
_no_capture = not (new_var `elemVarSet` tyVarsOfTypes (varEnvElts tenv))
-- Assertion check that we are not capturing something in the substitution
old_ki = tyVarKind old_var
no_kind_change = isEmptyVarSet (tyVarsOfType old_ki) -- verify that kind is closed
no_change = no_kind_change && (new_var == old_var)
-- no_change means that the new_var is identical in
-- all respects to the old_var (same unique, same kind)
See Note [ Extending the TvSubst ] in TypeRep
--
-- In that case we don't need to extend the substitution
-- to map old to new. But instead we must zap any
-- current substitution for the variable. For example:
-- (\x.e) with id_subst = [x |-> e']
-- Here we must simply zap the substitution for x
new_var | no_kind_change = uniqAway in_scope old_var
| otherwise = uniqAway in_scope $ updateTyVarKind (substTy subst) old_var
-- The uniqAway part makes sure the new variable is not already in scope
cloneTyVarBndr :: TvSubst -> TyVar -> Unique -> (TvSubst, TyVar)
cloneTyVarBndr (TvSubst in_scope tv_env) tv uniq
= (TvSubst (extendInScopeSet in_scope tv')
(extendVarEnv tv_env tv (mkTyVarTy tv')), tv')
where
tv' = setVarUnique tv uniq -- Simply set the unique; the kind
-- has no type variables to worry about
cloneTyVarBndrs :: TvSubst -> [TyVar] -> UniqSupply -> (TvSubst, [TyVar])
cloneTyVarBndrs subst [] _usupply = (subst, [])
cloneTyVarBndrs subst (t:ts) usupply = (subst'', tv:tvs)
where
(uniq, usupply') = takeUniqFromSupply usupply
(subst' , tv ) = cloneTyVarBndr subst t uniq
(subst'', tvs) = cloneTyVarBndrs subst' ts usupply'
----------------------------------------------------
-- Kind Stuff
Kinds
~~~~~
For the description of subkinding in GHC , see
#Kinds
----------------------------------------------------
-- Kind Stuff
Kinds
~~~~~
For the description of subkinding in GHC, see
#Kinds
-}
invariant : MetaKindVar will always be a
TcTyVar with details ( TauTv ... ) ...
meta kind var constructors and functions are in TcType
type SimpleKind = Kind
{-
************************************************************************
* *
The kind of a type
* *
************************************************************************
-}
typeKind :: Type -> Kind
typeKind orig_ty = go orig_ty
where
go ty@(TyConApp tc tys)
| isPromotedTyCon tc
= ASSERT( tyConArity tc == length tys ) superKind
| otherwise
= kindAppResult (ptext (sLit "typeKind 1") <+> ppr ty $$ ppr orig_ty)
(tyConKind tc) tys
go ty@(AppTy fun arg) = kindAppResult (ptext (sLit "typeKind 2") <+> ppr ty $$ ppr orig_ty)
(go fun) [arg]
go (LitTy l) = typeLiteralKind l
go (ForAllTy _ ty) = go ty
go (TyVarTy tyvar) = tyVarKind tyvar
go _ty@(FunTy _arg res)
-- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
-- not unliftedTypeKind (#)
-- The only things that can be after a function arrow are
-- (a) types (of kind openTypeKind or its sub-kinds)
( b ) kinds ( of super - kind TY ) ( e.g. * - > ( * - > * ) )
| isSuperKind k = k
| otherwise = ASSERT2( isSubOpenTypeKind k, ppr _ty $$ ppr k ) liftedTypeKind
where
k = go res
typeLiteralKind :: TyLit -> Kind
typeLiteralKind l =
case l of
NumTyLit _ -> typeNatKind
StrTyLit _ -> typeSymbolKind
Kind inference
~~~~~~~~~~~~~~
During kind inference , a kind variable unifies only with
a " simple kind " , sk
sk : : = * | sk1 - > sk2
For example
data T a = MkT a ( T Int # )
fails . We give T the kind ( k - > * ) , and the kind variable k wo n't unify
with # ( the kind of Int # ) .
Type inference
~~~~~~~~~~~~~~
When creating a fresh internal type variable , we give it a kind to express
constraints on it . E.g. in ( \x->e ) we make up a fresh type variable for x ,
with kind ? ? .
During unification we only bind an internal type variable to a type
whose kind is lower in the sub - kind hierarchy than the kind of the tyvar .
When unifying two internal type variables , we collect their kind constraints by
finding the GLB of the two . Since the partial order is a tree , they only
have a glb if one is a sub - kind of the other . In that case , we bind the
less - informative one to the more informative one . Neat , eh ?
Kind inference
~~~~~~~~~~~~~~
During kind inference, a kind variable unifies only with
a "simple kind", sk
sk ::= * | sk1 -> sk2
For example
data T a = MkT a (T Int#)
fails. We give T the kind (k -> *), and the kind variable k won't unify
with # (the kind of Int#).
Type inference
~~~~~~~~~~~~~~
When creating a fresh internal type variable, we give it a kind to express
constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
with kind ??.
During unification we only bind an internal type variable to a type
whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
When unifying two internal type variables, we collect their kind constraints by
finding the GLB of the two. Since the partial order is a tree, they only
have a glb if one is a sub-kind of the other. In that case, we bind the
less-informative one to the more informative one. Neat, eh?
-}
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/compiler/Eta/Types/Type.hs | haskell |
Type - public interface
| Main functions for manipulating types and type-related things
Note some of this is just re-exports from TyCon..
* Main data types representing Types
$type_classification
$representation_types
** Constructing and deconstructing types
(Newtypes)
Pred types
Deconstructing predicate types
** Common type constructors
** Predicates on types
(Lifting and boxity)
* Main data types representing Kinds
$kind_subtyping
** Finding the kind of a type
** Common Kinds and SuperKinds
** Common Kind type constructors
* Type free variables
* Type comparison
* Forcing evaluation of types
* Other views onto Types
* Type representation for the code generator
* Main type substitution data types
Representation widely visible
Representation visible to a few friends
** Manipulating type substitutions
** Performing substitution on types and kinds
* Pretty-printing
* Tidying type related things up for printing
Many things are reexported, but not the representation!
friends:
# SOURCE #
others
Associates to the right
$type_classification
#type_classification#
[Lifted] Iff it has bottom as an element.
Closures always have lifted types: i.e. any
type. Operationally, a lifted object is one that
can be entered.
Only lifted types may be unified with a type variable.
declared with @data@ or @newtype@.
An algebraic type is one that can be deconstructed
lifted types, because we also include unboxed
tuples in this classification.
[Data] Iff it is a type declared with @data@, or a boxed tuple.
Currently, all primitive types are unlifted, but that's not necessarily
but unlifted (such as @ByteArray#@). The only primitive types that we
classify as algebraic are the unboxed tuples.
Some examples of type classifications that may make this a bit clearer are:
@
Type primitive boxed lifted algebraic
-----------------------------------------------------------------------------
Int# Yes No No No
ByteArray# Yes Yes No No
(\# a, b \#) Yes No No Yes
( a, b ) No Yes Yes Yes
[a] No Yes Yes Yes
@
$representation_types
A /source type/ is a type that is a separate type as far as the type checker is
passes and the rest of the back end is concerned.
You don't normally have to worry about this, as the utility functions in
this module will automatically convert a source into a representation type
if they are spotted, to the best of it's abilities. If you don't want this
************************************************************************
* *
Type representation
* *
************************************************************************
function tries to obtain a different view of the supplied type given this
Strips off the /top layer only/ of a type to give
its underlying representation type.
Returns Nothing if there is nothing to look through.
By being non-recursive and inlined, this case analysis gets efficiently
joined onto the case analysis that the caller is already doing
because the function part might well return a
partially-applied type constructor; indeed, usually will!
---------------------------------------------
^ Similar to 'coreView', but for the type checker, which just looks through synonyms
So we will leave it here to avoid module loops.
---------------------------------------------
^ Expand out all type synonyms. Actually, it'd suffice to expand out
just the ones that discard type variables (e.g. type Funny a = Int)
But we don't know which those are currently, so we just expand all.
-------------------------------------------------------------------
-------------------------------------------------------------------
| Attempts to obtain the type variable underlying a 'Type', and panics with the
given message if this is not a type variable type. See also 'getTyVar_maybe'
| Attempts to obtain the type variable underlying a 'Type'
-------------------------------------------------------------------
-------------------------------------------------------------------
Note that the TyConApp could be an
type Id x = x
foo :: Foo Id -> Foo Id
but once the type synonyms are expanded all is well
-----------
^ Attempt to take a type application apart, whether it is a
function, type constructor, or plain type application. Note
that type family applications are NEVER unsaturated by this!
-----------
See Note [Decomposing fat arrow c=>t]
Never create unsaturated type family apps!
-----------
^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
and panics if this is not possible
-----------
^ Recursively splits a type as far as is possible, leaving a residual
type being applied to and the type arguments applied to it. Never fails,
even if that means returning an empty list of type applications.
keep type families saturated
| Is this a numeric literal. We also look through type synonyms.
| Is this a symbol literal. We also look through type synonyms.
| Is this type a custom user error?
If so, give us the kind and the error message.
Text "Something"
t1 :<>: t2
t1 :$$: t2
An uneavaluated type function
-------------------------------------------------------------------
-------------------------------------------------------------------
^ Creates a function type from the given argument and result type
^ Attempts to extract the argument and result types from a type, and
panics if that is not possible. See also 'splitFunTy_maybe'
^ Attempts to extract the argument and result types from a type
^ Split off exactly the given number argument types, and panics if that is not possible
| Splits off argument types from the given type and associating
them with the things in the input list from left to right. The
final result type is returned, along with the resulting pairs of
objects and types, albeit with the list of pairs in reverse order.
Panics if there are not enough argument types for the input list.
^ Extract the function result type and panic if that is not possible
^ Extract the function argument type and panic if that is not possible
^ Just like 'piResultTys' but for a single argument
Try not to iterate 'piResultTy', because it's inefficient to substitute
---------------------------------------------------------------------
TyConApp
~~~~~~~~
| A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
its arguments. Applies its arguments to the constructor from left to right.
splitTyConApp "looks through" synonyms, because they don't
mean a distinct type, but all other type-constructor applications
including functions are returned as Just ..
Executing Nth
| Attempts to tease a type apart into a type constructor and the application
of a number of arguments to that constructor. Panics if that is not possible.
See also 'splitTyConApp_maybe'
| Attempts to tease a type apart into a type constructor and the application
of a number of arguments to that constructor
| Attempts to tease a list type apart and gives the type of the elements if
successful (looks through type synonyms)
| What is the role assigned to the next parameter of this type? Usually,
this will be 'Nominal', but if the type is a 'TyConApp', we may be able to
do better. The type does *not* have to be well-kinded when applied for this
to work!
^ Unwrap one 'layer' of newtype on a type constructor and its
arguments, using an eta-reduced version of the @newtype@ if possible.
This requires tys to have at least @newTyConInstArity tycon@ elements.
-------------------------------------------------------------------
-------------------------------------------------------------------
| Looks through:
It's useful in the back end of the compiler.
Expand predicates and synonyms
Drop foralls
Expand newtypes
See Note [Expanding newtypes] in TyCon
| All type constructors occurring in the type; looking through type
synonyms, but not newtypes.
of inspecting the type directly.
See Note [AppTy rep]
-------------------------------------------------------------------
-------------------------------------------------------------------
mkPiKinds [k1, k2, (a:k1 -> *)] k2
returns forall k1 k2. (k1 -> *) -> k2
on whether it is given a type variable or a term variable.
| Attempts to take a forall type apart, returning the bound type variable
and the remainder of the type
| Attempts to take a forall type apart, returning all the immediate such bound
| Equivalent to @snd . splitForAllTys@
( mkPiType now in CoreUtils )
(mkPiType now in CoreUtils)
Used when we have a polymorphic function applied to type args:
> f t1 t2
We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
Panics if no application is possible.
^ This function is interesting because:
> applyTys (forall a.a) [forall b.b, Int]
This really can happen, but only (I think) in situations involving
undefined. For example:
undefined :: forall a. a
Term: undefined @(forall b. b->b) @Int
This term should have type (Int -> Int), but notice that
there are more type args than foralls in 'undefined's type.
Debug version
The vastly common case
Too many for-alls
Too many type args
applyTyxX beta-reduces (/\tvs. body_ty) arg_tys
NB: isPredTy is used when printing types, which can happen in debug printing
during type checking of not-fully-zonked types. So it's not cool to say
isConstraintKind (typeKind ty) because absent zonking the type might
be ill-kinded, and typeKind crashes
Hence the rather tiresome story here
True <=> kind is k1 -> .. -> kn -> Constraint
Typeable * Int :: Constraint
------------------- Equality types ---------------------------------
------------------- Equality types ---------------------------------
| Creates a type equality predicate
--------------------- Dictionary types ---------------------------------
Note [Dictionary-like types]
# INLINE bar #
| A choice of equality relation. This is separate from the type 'Role'
NB: Coercible is also a class, so this check must come *after*
the Coercible check
| Get the equality relation relevant for a pred type.
%************************************************************************
%* *
Size
* *
************************************************************************
************************************************************************
* *
\subsection{Type families}
* *
************************************************************************
corresponding family type. E.g:
> data family T a
> data instance T (Maybe b) = MkT b
family instance.
representation tycon. For example:
> data T [a] = ...
************************************************************************
* *
\subsection{Liftedness}
* *
************************************************************************
| See "Type#type_classification" for what an unlifted type is
isUnLiftedType returns True for forall'd unlifted types:
x :: forall a. Int#
I found bindings like these were getting floated to the top level.
They are pretty bogus types, mind you. It would be better never to
construct them
| See "Type#type_classification" for what an algebraic type is.
Should only be applied to /types/, as opposed to e.g. partially
saturated type constructors
| See "Type#type_classification" for what an algebraic type is.
Should only be applied to /types/, as opposed to e.g. partially
saturated type constructors. Closed type constructors are those
with a fixed right hand side, as opposed to e.g. associated types
| Computes whether an argument (or let right hand side) should
be computed strictly or lazily, based only on its type.
Currently, it's just 'isUnLiftedType'.
************************************************************************
* *
\subsection{Sequencing on types}
* *
************************************************************************
************************************************************************
* *
Comparison for types
(We don't use instances so that we know where it happens)
* *
************************************************************************
Watch out for horrible hack: See Note [Comparison with OpenTypeKind]
^ Type equality on source types. Does not look through @newtypes@ or
Watch out for horrible hack: See Note [Comparison with OpenTypeKind]
Returns Nothing if they don't match
Now here comes the real worker
Watch out for horrible hack: See Note [Comparison with OpenTypeKind]
Main workhorse
lots of definitions like
fOrdBool = D:Ord .. .. ..
-----------
-----------
Also we treat OpenTypeKind as equal to either * or #
See Note [Comparison with OpenTypeKind]
cmpTypeX env ( ForAllTy t1 ) ( ForAllTy tv2 t2 )
= cmpTypeX env ( tyVarKind ) ( tyVarKind tv2 ) ` thenCmp `
cmpTypeX ( rnBndr2 env tv2 ) t1 t2
cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2)
= cmpTypeX env (tyVarKind tv1) (tyVarKind tv2) `thenCmp`
cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
It assumes that both are idempotent.
Typically, @env1@ is the refinement to a base substitution @env2@
*left* argument to plusVarEnv, because the right arg wins
Works when the ranges are disjoint
the types given; but it's just a thunk so with a bit of luck
it'll never be evaluated
Note [Generating the in-scope set for a substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
think it was enough to generate an in-scope set that includes
fv(ty1,ty2). But that's not enough; we really should also take the
free vars of the type we are substituting into! Example:
(forall b. (a,b,x)) [a -> List b]
Then if we use the in-scope set {b}, there is a danger we will rename
the forall'd variable to 'x' by mistake, getting this:
(forall x. (List b, x, x)
environment, hence "open"
environment, hence "open"
| Called when doing top-level substitutions. Here we expect that the
free vars of the range of the substitution will be empty.
Later substitutions in the list over-ride earlier ones,
but there should be no loops
There used to be a special case for when
(a not-uncommon case) in which case the substitution was dropped.
But the type-tidier changes the print-name of a type variable without
changing the unique, and that led to a bug. Why? Pre-tidying, we had
And it happened that t was the type variable of the class. Post-tiding,
it got turned into {Foo t2}. The ext-core printer expanded this using
sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
and so generated a rep type mentioning t not t2.
Simplest fix is to nuke the "optimisation"
zip_ty_env _ _ env = env
************************************************************************
* *
Performing type or kind substitutions
* *
************************************************************************
| Substitute within a 'Type' after adding the free variables of the type
to the in-scope set. This is useful for the case when the free variables
aren't already in the in-scope set or easily available.
See also Note [The substitution invariant].
| Substitute within a 'Type'
| Substitute within several 'Type's
subst_ty is the main workhorse for type substitution
Note that the in_scope set is poked only if we hit a forall
so it may often never be fully computed
we might be replacing (a Int), represented with App
by [Int], represented with TyConApp
See Note [Apply Once]
Reason: we do quite a bit of (substTyWith [tv] [ty] tau)
and it's a nuisance to bring all the free vars of tau into
scope --- and then force that thunk at every tyvar
Assertion check that we are not capturing something in the substitution
verify that kind is closed
no_change means that the new_var is identical in
all respects to the old_var (same unique, same kind)
In that case we don't need to extend the substitution
to map old to new. But instead we must zap any
current substitution for the variable. For example:
(\x.e) with id_subst = [x |-> e']
Here we must simply zap the substitution for x
The uniqAway part makes sure the new variable is not already in scope
Simply set the unique; the kind
has no type variables to worry about
--------------------------------------------------
Kind Stuff
--------------------------------------------------
Kind Stuff
************************************************************************
* *
The kind of a type
* *
************************************************************************
Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*),
not unliftedTypeKind (#)
The only things that can be after a function arrow are
(a) types (of kind openTypeKind or its sub-kinds) | ( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1998
# LANGUAGE CPP , OverloadedStrings , MultiWayIf #
# OPTIONS_GHC -fno - warn - orphans #
module Eta.Types.Type (
TyThing(..), Type, KindOrType, PredType, ThetaType,
Var, TyVar, isTyVar,
mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
mkAppTy, mkAppTys, splitAppTy, splitAppTys,
splitAppTy_maybe, repSplitAppTy_maybe,
mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
splitFunTys, splitFunTysN,
funResultTy, funArgTy, zipFunTys,
mkTyConApp, mkTyConTy,
tyConAppTyCon_maybe, tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs,
splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole,
splitListTyConApp_maybe,
mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys,
mkPiKinds, mkPiType, mkPiTypes,
piResultTy,
applyTy, applyTys, applyTysD, applyTysX, dropForAlls,
mkNumLitTy, isNumLitTy,
mkStrLitTy, isStrLitTy,
isUserErrorTy, pprUserTypeErrorTy,
coAxNthLHS,
newTyConInstRhs,
mkFamilyTyConApp,
isDictLikeTy,
mkEqPred, mkCoerciblePred, mkPrimEqPred, mkReprPrimEqPred,
mkClassPred,
isClassPred, isEqPred,
isIPPred, isIPPred_maybe, isIPTyCon, isIPClass,
PredTree(..), EqRel(..), eqRelRole, classifyPredType,
getClassPredTys, getClassPredTys_maybe,
getEqPredTys, getEqPredTys_maybe, getEqPredRole,
predTypeEqRel,
funTyCon,
isTypeVar, isKindVar, allDistinctTyVars, isForAllTy,
isTyVarTy, isFunTy, isDictTy, isPredTy, isVoidTy,
isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
isPrimitiveType, isStrictType,
ETA - specific
isObjectType,
Kind, SimpleKind, MetaKindVar,
typeKind,
anyKind, liftedTypeKind, unliftedTypeKind, openTypeKind,
constraintKind, superKind,
liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
constraintKindTyCon, anyKindTyCon,
tyVarsOfType, tyVarsOfTypes, closeOverKinds,
expandTypeSynonyms,
typeSize, varSetElemsKvsFirst,
eqType, eqTypeX, eqTypes, cmpType, cmpTypes,
eqPred, eqPredX, cmpPred, eqKind, eqTyVarBndrs,
seqType, seqTypes,
coreView, tcView,
UnaryType, RepType(..), flattenRepType, repType,
tyConsOfType,
typePrimRep, stypePrimRep, typePrimRepMany, typeRepArity,
tagTypeToText, stagTypeToText, rawTagTypeToText,
emptyTvSubstEnv, emptyTvSubst,
mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
getTvSubstEnv, setTvSubstEnv,
zapTvSubstEnv, getTvInScope,
extendTvInScope, extendTvInScopeList,
extendTvSubst, extendTvSubstList,
isInScope, composeTvSubst, zipTyEnv,
isEmptyTvSubst, unionTvSubst,
substTy, substTyAddInScope, substTys, substTyWith, substTysWith, substTheta,
substTyVar, substTyVars, substTyVarBndr,
cloneTyVarBndr, cloneTyVarBndrs, deShadowTy, lookupTyVar,
substKiWith, substKisWith,
pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing,
pprTvBndr, pprTvBndrs, pprForAll, pprUserForAll, pprSigmaType,
pprTheta, pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprSourceTyCon,
TyPrec(..), maybeParen, pprSigmaTypeExtraCts,
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyVarBndr, tidyTyVarBndrs, tidyFreeTyVars,
tidyOpenTyVar, tidyOpenTyVars,
tidyTyVarOcc,
tidyTopType,
tidyKind,
) where
#include "HsVersions.h"
We import the representation and primitive functions from TypeRep .
import Eta.Types.Kind
import Eta.Types.TypeRep
import Eta.BasicTypes.Var
import Eta.BasicTypes.VarEnv
import Eta.BasicTypes.VarSet
import Eta.BasicTypes.NameEnv
import Eta.Types.Class
import Eta.Types.TyCon
import Eta.Prelude.TysPrim
coercibleTyCon, typeNatKind, typeSymbolKind )
import Eta.Prelude.PrelNames ( eqTyConKey, coercibleTyConKey, ipTyConKey,
openTypeKindTyConKey,
constraintKindTyConKey, liftedTypeKindTyConKey,
sobjectTyConKey,
errorMessageTypeErrorFamName,
typeErrorTextDataConName,
typeErrorShowTypeDataConName,
typeErrorAppendDataConName,
typeErrorVAppendDataConName)
import Eta.Prelude.ForeignCall
import Eta.Types.CoAxiom
import Eta.BasicTypes.UniqSupply ( UniqSupply, takeUniqFromSupply )
import Eta.BasicTypes.Unique ( Unique, hasKey )
import Eta.BasicTypes.BasicTypes ( Arity, RepArity )
import Eta.Utils.Util
import Eta.Utils.ListSetOps ( getNth )
import Eta.Utils.Outputable
import Eta.Utils.FastString
import Eta.Utils.Maybes ( orElse )
import Data.Text (Text)
import qualified Data.Text as T
import Data.Maybe ( isJust)
import Control.Monad ( guard )
Types are one of :
[ ] Iff its representation is other than a pointer
types are also unlifted .
let - bound identifier in Core must have a lifted
[ Algebraic ] it is a type with one or more constructors , whether
with a case expression . This is /not/ the same as
[ Primitive ] it is a built - in type that ca n't be expressed in Haskell .
the case : for example , @Int@ could be primitive .
Some primitive types are unboxed , such as @Int#@ , whereas some are boxed
concerned , but which has a more low - level representation as far as Core - to - Core
to happen , use the equivalent functions from the " TcType " module .
# INLINE coreView #
coreView :: Type -> Maybe Type
^ In Core , we \"look through\ " non - recursive newtypes and ' PredTypes ' : this
coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys
= Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
Its important to use mkAppTys , rather than ( foldl AppTy ) ,
coreView _ = Nothing
# INLINE tcView #
tcView :: Type -> Maybe Type
tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
= Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
tcView _ = Nothing
You might think that tcView belows in TcType rather than Type , but unfortunately
it is needed by Unify , which is turn imported by Coercion ( for MatchEnv and matchList ) .
expandTypeSynonyms :: Type -> Type
expandTypeSynonyms ty
= go ty
where
go (TyConApp tc tys)
| Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
= go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
| otherwise
= TyConApp tc (map go tys)
go (LitTy l) = LitTy l
go (TyVarTy tv) = TyVarTy tv
go (AppTy t1 t2) = mkAppTy (go t1) (go t2)
go (FunTy t1 t2) = FunTy (go t1) (go t2)
go (ForAllTy tv t) = ForAllTy tv (go t)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
\subsection{Constructor - specific functions }
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
TyVarTy
~~~~~~~
************************************************************************
* *
\subsection{Constructor-specific functions}
* *
************************************************************************
TyVarTy
~~~~~~~
-}
getTyVar :: String -> Type -> TyVar
getTyVar msg ty = case getTyVar_maybe ty of
Just tv -> tv
Nothing -> panic ("getTyVar: " ++ msg)
isTyVarTy :: Type -> Bool
isTyVarTy ty = isJust (getTyVar_maybe ty)
getTyVar_maybe :: Type -> Maybe TyVar
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
getTyVar_maybe (TyVarTy tv) = Just tv
getTyVar_maybe _ = Nothing
allDistinctTyVars :: [KindOrType] -> Bool
allDistinctTyVars tkvs = go emptyVarSet tkvs
where
go _ [] = True
go so_far (ty : tys)
= case getTyVar_maybe ty of
Nothing -> False
Just tv | tv `elemVarSet` so_far -> False
| otherwise -> go (so_far `extendVarSet` tv) tys
AppTy
~~~~~
We need to be pretty careful with AppTy to make sure we obey the
invariant that a TyConApp is always visibly so . mkAppTy maintains the
invariant : use it .
Note [ Decomposing fat arrow c=>t ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify ( a b ) with ( Eq a = > ty ) ? If we do so , we end up with
a partial application like ( (= > ) Eq a ) which does n't make sense in
source . In constrast , we * can * unify ( a b ) with ( t1 - > t2 ) .
Here 's an example ( Trac # 9858 ) of how you might do it :
i : : ( a , b ) = > Proxy ( a b ) - > TypeRep
i p = typeRep p
j = i ( Proxy : : Proxy ( Eq Int = > Int ) )
The type ( Proxy ( Eq Int = > Int ) ) is only accepted with -XImpredicativeTypes ,
but suppose we want that . But then in the call to ' i ' , we end
up decomposing ( Eq Int = > Int ) , and we definitely do n't want that .
This really only applies to the type checker ; in Core , ' = > ' and ' - > '
are the same , as are ' Constraint ' and ' * ' . But for now I 've put
the test in repSplitAppTy_maybe , which applies throughout , because
the other calls to splitAppTy are in Unify , which is also used by
the type checker ( e.g. when matching type - function equations ) .
AppTy
~~~~~
We need to be pretty careful with AppTy to make sure we obey the
invariant that a TyConApp is always visibly so. mkAppTy maintains the
invariant: use it.
Note [Decomposing fat arrow c=>t]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify (a b) with (Eq a => ty)? If we do so, we end up with
a partial application like ((=>) Eq a) which doesn't make sense in
source Haskell. In constrast, we *can* unify (a b) with (t1 -> t2).
Here's an example (Trac #9858) of how you might do it:
i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep
i p = typeRep p
j = i (Proxy :: Proxy (Eq Int => Int))
The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes,
but suppose we want that. But then in the call to 'i', we end
up decomposing (Eq Int => Int), and we definitely don't want that.
This really only applies to the type checker; in Core, '=>' and '->'
are the same, as are 'Constraint' and '*'. But for now I've put
the test in repSplitAppTy_maybe, which applies throughout, because
the other calls to splitAppTy are in Unify, which is also used by
the type checker (e.g. when matching type-function equations).
-}
| Applies a type to another , as in e.g. @k a@
mkAppTy :: Type -> Type -> Type
mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2])
mkAppTy ty1 ty2 = AppTy ty1 ty2
under - saturated type synonym . GHC allows that ; e.g.
type k a
Here I d is partially applied in the type sig for ,
mkAppTys :: Type -> [Type] -> Type
mkAppTys ty1 [] = ty1
mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
mkAppTys ty1 tys2 = foldl AppTy ty1 tys2
splitAppTy_maybe :: Type -> Maybe (Type, Type)
splitAppTy_maybe ty | Just ty' <- coreView ty
= splitAppTy_maybe ty'
splitAppTy_maybe ty = repSplitAppTy_maybe ty
repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
^ Does the AppTy split as in ' splitAppTy_maybe ' , but assumes that
any Core view stuff is already done
repSplitAppTy_maybe (FunTy ty1 ty2)
| otherwise = Just (TyConApp funTyCon [ty1], ty2)
repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
repSplitAppTy_maybe (TyConApp tc tys)
| isDecomposableTyCon tc || tys `lengthExceeds` tyConArity tc
, Just (tys', ty') <- snocView tys
repSplitAppTy_maybe _other = Nothing
splitAppTy :: Type -> (Type, Type)
splitAppTy ty = case splitAppTy_maybe ty of
Just pr -> pr
Nothing -> panic "splitAppTy"
splitAppTys :: Type -> (Type, [Type])
splitAppTys ty = split ty ty []
where
split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
split _ (AppTy ty arg) args = split ty ty (arg:args)
split _ (TyConApp tc tc_args) args
n | isDecomposableTyCon tc = 0
| otherwise = tyConArity tc
(tc_args1, tc_args2) = splitAt n tc_args
in
(TyConApp tc tc_args1, tc_args2 ++ args)
split _ (FunTy ty1 ty2) args = ASSERT( null args )
(TyConApp funTyCon [], [ty1,ty2])
split orig_ty _ args = (orig_ty, args)
~~~~~
LitTy
~~~~~
-}
mkNumLitTy :: Integer -> Type
mkNumLitTy n = LitTy (NumTyLit n)
isNumLitTy :: Type -> Maybe Integer
isNumLitTy ty | Just ty1 <- tcView ty = isNumLitTy ty1
isNumLitTy (LitTy (NumTyLit n)) = Just n
isNumLitTy _ = Nothing
mkStrLitTy :: FastString -> Type
mkStrLitTy s = LitTy (StrTyLit s)
isStrLitTy :: Type -> Maybe FastString
isStrLitTy ty | Just ty1 <- tcView ty = isStrLitTy ty1
isStrLitTy (LitTy (StrTyLit s)) = Just s
isStrLitTy _ = Nothing
isUserErrorTy :: Type -> Maybe (Kind,Type)
isUserErrorTy t = do (tc,[k,msg]) <- splitTyConApp_maybe t
guard (tyConName tc == errorMessageTypeErrorFamName)
return (k,msg)
| Render a type corresponding to a user type error into a SDoc .
pprUserTypeErrorTy :: Type -> SDoc
pprUserTypeErrorTy ty =
case splitTyConApp_maybe ty of
Just (tc,[txt])
| tyConName tc == typeErrorTextDataConName
, Just str <- isStrLitTy txt -> ftext str
ShowType t
Just (tc,[_k,t])
| tyConName tc == typeErrorShowTypeDataConName -> ppr t
Just (tc,[t1,t2])
| tyConName tc == typeErrorAppendDataConName ->
pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorVAppendDataConName ->
pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2
_ -> ppr ty
FunTy
~~~~~
FunTy
~~~~~
-}
mkFunTy :: Type -> Type -> Type
mkFunTy arg res = FunTy arg res
mkFunTys :: [Type] -> Type -> Type
mkFunTys tys ty = foldr mkFunTy ty tys
isFunTy :: Type -> Bool
isFunTy ty = isJust (splitFunTy_maybe ty)
splitFunTy :: Type -> (Type, Type)
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
splitFunTy (FunTy arg res) = (arg, res)
splitFunTy other = pprPanic "splitFunTy" (ppr other)
splitFunTy_maybe :: Type -> Maybe (Type, Type)
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
splitFunTy_maybe (FunTy arg res) = Just (arg, res)
splitFunTy_maybe _ = Nothing
splitFunTys :: Type -> ([Type], Type)
splitFunTys ty = split [] ty ty
where
split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
split args _ (FunTy arg res) = split (arg:args) res res
split args orig_ty _ = (reverse args, orig_ty)
splitFunTysN :: Int -> Type -> ([Type], Type)
splitFunTysN 0 ty = ([], ty)
splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
case splitFunTy ty of { (arg, res) ->
case splitFunTysN (n-1) res of { (args, res) ->
(arg:args, res) }}
zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
where
split acc [] nty _ = (reverse acc, nty)
split acc xs nty ty
| Just ty' <- coreView ty = split acc xs nty ty'
split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res
split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
funResultTy :: Type -> Type
funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
funResultTy (FunTy _arg res) = res
funResultTy ty = pprPanic "funResultTy" (ppr ty)
funArgTy :: Type -> Type
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
funArgTy (FunTy arg _res) = arg
funArgTy ty = pprPanic "funArgTy" (ppr ty)
piResultTy :: Type -> Type -> Type
piResultTy ty arg = case piResultTy_maybe ty arg of
Just res -> res
Nothing -> pprPanic "piResultTy" (ppr ty $$ ppr arg)
piResultTy_maybe :: Type -> Type -> Maybe Type
one variable at a time ; instead use ' piResultTys "
piResultTy_maybe ty arg
| Just ty' <- coreView ty = piResultTy_maybe ty' arg
| FunTy _ res <- ty
= Just res
| ForAllTy tv res <- ty
= let empty_subst = extendTvInScopeList emptyTvSubst
$ varSetElems $ tyVarsOfTypes [arg,res]
in Just (substTy (extendTvSubst empty_subst tv arg) res)
| otherwise
= Nothing
mkTyConApp :: TyCon -> [Type] -> Type
mkTyConApp tycon tys
| isFunTyCon tycon, [ty1,ty2] <- tys
= FunTy ty1 ty2
| otherwise
= TyConApp tycon tys
| The same as @fst . splitTyConApp@
tyConAppTyCon_maybe :: Type -> Maybe TyCon
tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty'
tyConAppTyCon_maybe (TyConApp tc _) = Just tc
tyConAppTyCon_maybe (FunTy {}) = Just funTyCon
tyConAppTyCon_maybe _ = Nothing
tyConAppTyCon :: Type -> TyCon
tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty)
| The same as @snd . splitTyConApp@
tyConAppArgs_maybe :: Type -> Maybe [Type]
tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty'
tyConAppArgs_maybe (TyConApp _ tys) = Just tys
tyConAppArgs_maybe (FunTy arg res) = Just [arg,res]
tyConAppArgs_maybe _ = Nothing
tyConAppArgs :: Type -> [Type]
tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty)
tyConAppArgN :: Int -> Type -> Type
tyConAppArgN n ty
= case tyConAppArgs_maybe ty of
Just tys -> ASSERT2( n < length tys, ppr n <+> ppr tys ) tys !! n
Nothing -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty)
splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
Just stuff -> stuff
Nothing -> pprPanic "splitTyConApp" (ppr ty)
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
splitTyConApp_maybe _ = Nothing
splitListTyConApp_maybe :: Type -> Maybe Type
splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of
Just (tc,[e]) | tc == listTyCon -> Just e
_other -> Nothing
nextRole :: Type -> Role
nextRole ty
| Just (tc, tys) <- splitTyConApp_maybe ty
, let num_tys = length tys
, num_tys < tyConArity tc
= tyConRoles tc `getNth` num_tys
| otherwise
= Nominal
newTyConInstRhs :: TyCon -> [Type] -> Type
newTyConInstRhs tycon tys
= ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs )
applyTysX tvs rhs tys
where
(tvs, rhs) = newTyConEtadRhs tycon
~~~~~
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various " split " functions ( splitFunTy , splitRhoTy , splitForAllTy ) try
to return type synonyms wherever possible . Thus
type a = a - > a
we want
splitFunTys ( a - > Foo a ) = ( [ a ] , a )
not ( [ a ] , a - > a )
The reason is that we then get better ( shorter ) type signatures in
interfaces . Notably this plays a role in tcTySigs in TcBinds.lhs .
Representation types
~~~~~~~~~~~~~~~~~~~~
Note [ Nullary unboxed tuple ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We represent the nullary unboxed tuple as the unary ( but void ) type
Void # . The reason for this is that the ReprArity is never
less than the Arity ( as it would otherwise be for a function type like
( # # ) - > Int ) .
As a result , ReprArity is always strictly positive if Arity is . This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument !
SynTy
~~~~~
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
to return type synonyms wherever possible. Thus
type Foo a = a -> a
we want
splitFunTys (a -> Foo a) = ([a], Foo a)
not ([a], a -> a)
The reason is that we then get better (shorter) type signatures in
interfaces. Notably this plays a role in tcTySigs in TcBinds.lhs.
Representation types
~~~~~~~~~~~~~~~~~~~~
Note [Nullary unboxed tuple]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We represent the nullary unboxed tuple as the unary (but void) type
Void#. The reason for this is that the ReprArity is never
less than the Arity (as it would otherwise be for a function type like
(# #) -> Int).
As a result, ReprArity is always strictly positive if Arity is. This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument!
-}
type UnaryType = Type
INVARIANT : never an empty list ( see Note [ Nullary unboxed tuple ] )
| UnaryRep UnaryType
flattenRepType :: RepType -> [UnaryType]
flattenRepType (UbxTupleRep tys) = tys
flattenRepType (UnaryRep ty) = [ty]
1 . For - alls
2 . Synonyms
3 . Predicates
4 . All newtypes , including recursive ones , but not newtype families
repType :: Type -> RepType
repType ty
= go initRecTc ty
where
go :: RecTcChecker -> Type -> RepType
| Just ty' <- coreView ty
= go rec_nts ty'
= go rec_nts ty
| isNewTyCon tc
, tys `lengthAtLeast` tyConArity tc
= go rec_nts' (newTyConInstRhs tc tys)
| isUnboxedTupleTyCon tc
= if null tys
See Note [ Nullary unboxed tuple ]
else UbxTupleRep (concatMap (flattenRepType . go rec_nts) tys)
go _ ty = UnaryRep ty
When it finds a Class , it returns the class .
tyConsOfType :: Type -> NameEnv TyCon
tyConsOfType ty
= go ty
where
The NameEnv does duplicate elim
go ty | Just ty' <- tcView ty = go ty'
go (TyVarTy {}) = emptyNameEnv
go (LitTy {}) = emptyNameEnv
go (TyConApp tc tys) = go_tc tc tys
go (AppTy a b) = go a `plusNameEnv` go b
go (FunTy a b) = go a `plusNameEnv` go b
go (ForAllTy _ ty) = go ty
go_tc tc tys = extendNameEnv (go_s tys) (tyConName tc) tc
go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
ToDo : this could be moved to the code generator , using instead
| Discovers the primitive representation of a more abstract ' UnaryType '
typePrimRep :: UnaryType -> PrimRep
typePrimRep = typePrimRep' False
typePrimRep' :: Bool -> UnaryType -> PrimRep
typePrimRep' sobject ty
= case repType ty of
UbxTupleRep _ -> pprPanic "typePrimRep: UbxTupleRep" (ppr ty)
UnaryRep rep -> case rep of
TyConApp tc tys ->
case primRep of
ObjectRep x
| T.null x -> objRep
| otherwise -> primRep
_ -> primRep
where primRep = tyConPrimRep tc
objRep = mkObjectRep (tagTypeToText' sobject (head tys))
FunTy _ _ -> PtrRep
TyVarTy _ -> PtrRep
_ -> pprPanic "typePrimRep: UnaryRep" (ppr ty)
stypePrimRep :: UnaryType -> PrimRep
stypePrimRep = typePrimRep' True
typePrimRepMany :: Type -> [PrimRep]
typePrimRepMany ty
= case repType ty of
UbxTupleRep utys -> map typePrimRep utys
UnaryRep uty -> [typePrimRep uty]
mkObjectRep :: Text -> PrimRep
mkObjectRep text
| T.takeEnd 2 text == "[]" = ArrayRep (mkObjectRep (T.dropEnd 2 text))
| otherwise = checkPrimitiveType text
where checkPrimitiveType "boolean" = BoolRep
checkPrimitiveType "byte" = ByteRep
checkPrimitiveType "short" = ShortRep
checkPrimitiveType "char" = CharRep
checkPrimitiveType "int" = IntRep
checkPrimitiveType "long" = Int64Rep
checkPrimitiveType "float" = FloatRep
checkPrimitiveType "double" = DoubleRep
checkPrimitiveType text = ObjectRep text
tagTypeToText :: Type -> Text
tagTypeToText = tagTypeToText' False
stagTypeToText :: Type -> Text
stagTypeToText = tagTypeToText' True
tagTypeToText' :: Bool -> Type -> Text
tagTypeToText' sobject ty = transform $
maybe ( T.pack "java/lang/Object" )
( T.map (\c -> if c == '.' then '/' else c)
. head
. T.words )
where transform f = either (uncurry pprPanic) f $ rawTagTypeToText' sobject ty
symbolLitToText :: Type -> Maybe Text
symbolLitToText ty | Just ty' <- coreView ty = symbolLitToText ty'
symbolLitToText (LitTy (StrTyLit fs)) = Just $ fastStringToText fs
symbolLitToText _ = Nothing
rawTagTypeToText :: Type -> Either (String, SDoc) (Maybe Text)
rawTagTypeToText = rawTagTypeToText' False
rawTagTypeToText' :: Bool -> Type -> Either (String, SDoc) (Maybe Text)
rawTagTypeToText' sobject ty
| Just (tc1, tys) <- splitTyConApp_maybe ty
, not (isFamilyTyCon tc1)
= if | sobject && tc1 `hasKey` sobjectTyConKey -> Right $ symbolLitToText (head tys)
| otherwise ->
case tyConCType_maybe tc1 of
Just (CType _ _ fs) -> Right . Just $ fastStringToText fs
Nothing -> Left ("rawTagTypeToText: You should annotate ", ppr ty)
| otherwise = Right Nothing
typeRepArity :: Arity -> Type -> RepArity
typeRepArity 0 _ = 0
typeRepArity n ty = case repType ty of
UnaryRep (FunTy ty1 ty2) -> length (flattenRepType (repType ty1)) + typeRepArity (n - 1) ty2
_ -> pprPanic "typeRepArity: arity greater than type can handle" (ppr (n, ty))
isVoidTy :: Type -> Bool
True if the type has zero width
isVoidTy ty = case repType ty of
UnaryRep (TyConApp tc _) -> isVoidRep (tyConPrimRep tc)
_ -> False
Note [ AppTy rep ]
~~~~~~~~~~~~~~~~
Types of the form ' f a ' must be of kind * , not # , so we are guaranteed
that they are represented by pointers . The reason is that f must have
kind ( kk - > kk ) and kk can not be unlifted ; see Note [ The kind invariant ]
in TypeRep .
ForAllTy
~~~~~~~~
Note [AppTy rep]
~~~~~~~~~~~~~~~~
Types of the form 'f a' must be of kind *, not #, so we are guaranteed
that they are represented by pointers. The reason is that f must have
kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant]
in TypeRep.
ForAllTy
~~~~~~~~
-}
mkForAllTy :: TyVar -> Type -> Type
mkForAllTy tyvar ty
= ForAllTy tyvar ty
| Wraps foralls over the type using the provided ' TyVar 's from left to right
mkForAllTys :: [TyVar] -> Type -> Type
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
mkPiKinds :: [TyVar] -> Kind -> Kind
mkPiKinds [] res = res
mkPiKinds (tv:tvs) res
| isKindVar tv = ForAllTy tv (mkPiKinds tvs res)
| otherwise = FunTy (tyVarKind tv) (mkPiKinds tvs res)
mkPiType :: Var -> Type -> Type
^ Makes a type or a forall type , depending
mkPiTypes :: [Var] -> Type -> Type
^ ' mkPiType ' for multiple type or value arguments
mkPiType v ty
| isId v = mkFunTy (varType v) ty
| otherwise = mkForAllTy v ty
mkPiTypes vs ty = foldr mkPiType ty vs
isForAllTy :: Type -> Bool
isForAllTy (ForAllTy _ _) = True
isForAllTy _ = False
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
splitForAllTy_maybe ty = splitFAT_m ty
where
splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
splitFAT_m _ = Nothing
type variables and the remainder of the type . Always suceeds , even if that means
returning an empty list of ' TyVar 's
splitForAllTys :: Type -> ([TyVar], Type)
splitForAllTys ty = split ty ty []
where
split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
split orig_ty _ tvs = (reverse tvs, orig_ty)
dropForAlls :: Type -> Type
dropForAlls ty = snd (splitForAllTys ty)
applyTy , applyTys
~~~~~~~~~~~~~~~~~
applyTy, applyTys
~~~~~~~~~~~~~~~~~
-}
| Instantiate a forall type with one or more type arguments .
applyTy :: Type -> KindOrType -> Type
applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
applyTy _ _ = panic "applyTy"
applyTys :: Type -> [KindOrType] -> Type
1 . The function may have more for - alls than there are args
2 . Less obviously , it may have fewer for - alls
For case 2 . think of :
If you edit this function , you may need to update the GHC formalism
See Note [ GHC Formalism ] in coreSyn / CoreLint.lhs
applyTys ty args = applyTysD empty ty args
applyTysD _ orig_fun_ty [] = orig_fun_ty
applyTysD doc orig_fun_ty arg_tys
= substTyWith tvs arg_tys rho_ty
= substTyWith (take n_args tvs) arg_tys
(mkForAllTys (drop n_args tvs) rho_ty)
Zero case gives infinite loop !
applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
(drop n_tvs arg_tys)
where
(tvs, rho_ty) = splitForAllTys orig_fun_ty
n_tvs = length tvs
n_args = length arg_tys
applyTysX :: [TyVar] -> Type -> [Type] -> Type
applyTysX tvs body_ty arg_tys
= ASSERT2( length arg_tys >= n_tvs, ppr tvs $$ ppr body_ty $$ ppr arg_tys )
mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty)
(drop n_tvs arg_tys)
where
n_tvs = length tvs
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Pred
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Predicates on PredType
************************************************************************
* *
Pred
* *
************************************************************************
Predicates on PredType
-}
isPredTy :: Type -> Bool
isPredTy ty = go ty []
where
go :: Type -> [KindOrType] -> Bool
go (AppTy ty1 ty2) args = go ty1 (ty2 : args)
go (TyConApp tc tys) args = go_k (tyConKind tc) (tys ++ args)
go (TyVarTy tv) args = go_k (tyVarKind tv) args
go _ _ = False
go_k :: Kind -> [KindOrType] -> Bool
go_k k [] = isConstraintKind k
go_k (FunTy _ k1) (_ :args) = go_k k1 args
go_k (ForAllTy kv k1) (k2:args) = go_k (substKiWith [kv] [k2] k1) args
isClassPred, isEqPred, isIPPred :: PredType -> Bool
isClassPred ty = case tyConAppTyCon_maybe ty of
Just tyCon | isClassTyCon tyCon -> True
_ -> False
isEqPred ty = case tyConAppTyCon_maybe ty of
Just tyCon -> tyCon `hasKey` eqTyConKey
_ -> False
isIPPred ty = case tyConAppTyCon_maybe ty of
Just tc -> isIPTyCon tc
_ -> False
isIPTyCon :: TyCon -> Bool
isIPTyCon tc = tc `hasKey` ipTyConKey
isIPClass :: Class -> Bool
isIPClass cls = cls `hasKey` ipTyConKey
Class and it corresponding have the same Unique
isIPPred_maybe :: Type -> Maybe (FastString, Type)
isIPPred_maybe ty =
do (tc,[t1,t2]) <- splitTyConApp_maybe ty
guard (isIPTyCon tc)
x <- isStrLitTy t1
return (x,t2)
Make PredTypes
Make PredTypes
-}
mkEqPred :: Type -> Type -> PredType
mkEqPred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 $$ ppr k $$ ppr (typeKind ty2) )
TyConApp eqTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkCoerciblePred :: Type -> Type -> PredType
mkCoerciblePred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 $$ ppr k $$ ppr (typeKind ty2) )
TyConApp coercibleTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkPrimEqPred :: Type -> Type -> Type
mkPrimEqPred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 )
TyConApp eqPrimTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkReprPrimEqPred :: Type -> Type -> Type
mkReprPrimEqPred ty1 ty2
= WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 )
TyConApp eqReprPrimTyCon [k, ty1, ty2]
where
k = typeKind ty1
mkClassPred :: Class -> [Type] -> PredType
mkClassPred clas tys = TyConApp (classTyCon clas) tys
isDictTy :: Type -> Bool
isDictTy = isClassPred
isDictLikeTy :: Type -> Bool
isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty'
isDictLikeTy ty = case splitTyConApp_maybe ty of
Just (tc, tys) | isClassTyCon tc -> True
| isTupleTyCon tc -> all isDictLikeTy tys
_other -> False
Note [ Dictionary - like types ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being " dictionary - like " means either a dictionary type or a tuple thereof .
In GHC 6.10 we build implication constraints which construct such tuples ,
and if we land up with a binding
t : : ( C [ a ] , [ a ] )
t = blah
then we want to treat t as cheap under " -fdicts - cheap " for example .
( Implication constraints are normally inlined , but sadly not if the
occurrence is itself inside an INLINE function ! Until we revise the
handling of implication constraints , that is . ) This turned out to
be important in getting good arities in DPH code . Example :
class C a
class D a where { foo : : a - > a }
instance C a = > D ( Maybe a ) where { foo x = x }
bar : : ( C a , C b ) = > a - > b - > ( Maybe a , Maybe b )
{ - # INLINE bar #
Note [Dictionary-like types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being "dictionary-like" means either a dictionary type or a tuple thereof.
In GHC 6.10 we build implication constraints which construct such tuples,
and if we land up with a binding
t :: (C [a], Eq [a])
t = blah
then we want to treat t as cheap under "-fdicts-cheap" for example.
(Implication constraints are normally inlined, but sadly not if the
occurrence is itself inside an INLINE function! Until we revise the
handling of implication constraints, that is.) This turned out to
be important in getting good arities in DPH code. Example:
class C a
class D a where { foo :: a -> a }
instance C a => D (Maybe a) where { foo x = x }
bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
bar x y = (foo (Just x), foo (Just y))
Then 'bar' should jolly well have arity 4 (two dicts, two args), but
we ended up with something like
bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
in \x,y. <blah>)
This is all a bit ad-hoc; eg it relies on knowing that implication
constraints build tuples.
Decomposing PredType
-}
because ' Phantom ' does not define a ( non - trivial ) equality relation .
data EqRel = NomEq | ReprEq
deriving (Eq, Ord)
instance Outputable EqRel where
ppr NomEq = text "nominal equality"
ppr ReprEq = text "representational equality"
eqRelRole :: EqRel -> Role
eqRelRole NomEq = Nominal
eqRelRole ReprEq = Representational
data PredTree = ClassPred Class [Type]
| EqPred EqRel Type Type
| TuplePred [PredType]
| IrredPred PredType
classifyPredType :: PredType -> PredTree
classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
Just (tc, tys) | tc `hasKey` coercibleTyConKey
, let [_, ty1, ty2] = tys
-> EqPred ReprEq ty1 ty2
Just (tc, tys) | tc `hasKey` eqTyConKey
, let [_, ty1, ty2] = tys
-> EqPred NomEq ty1 ty2
Just (tc, tys) | Just clas <- tyConClass_maybe tc
-> ClassPred clas tys
Just (tc, tys) | isTupleTyCon tc
-> TuplePred tys
_ -> IrredPred ev_ty
getClassPredTys :: PredType -> (Class, [Type])
getClassPredTys ty = case getClassPredTys_maybe ty of
Just (clas, tys) -> (clas, tys)
Nothing -> pprPanic "getClassPredTys" (ppr ty)
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
_ -> Nothing
getEqPredTys :: PredType -> (Type, Type)
getEqPredTys ty
= case splitTyConApp_maybe ty of
Just (tc, (_ : ty1 : ty2 : tys)) ->
ASSERT( null tys && (tc `hasKey` eqTyConKey
|| tc `hasKey` coercibleTyConKey) )
(ty1, ty2)
_ -> pprPanic "getEqPredTys" (ppr ty)
getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
getEqPredTys_maybe ty
= case splitTyConApp_maybe ty of
Just (tc, [_, ty1, ty2])
| tc `hasKey` eqTyConKey -> Just (Nominal, ty1, ty2)
| tc `hasKey` coercibleTyConKey -> Just (Representational, ty1, ty2)
_ -> Nothing
getEqPredRole :: PredType -> Role
getEqPredRole ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, _])
| tc `hasKey` eqTyConKey -> Nominal
| tc `hasKey` coercibleTyConKey -> Representational
_ -> pprPanic "getEqPredRole" (ppr ty)
predTypeEqRel :: PredType -> EqRel
predTypeEqRel ty
| Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` coercibleTyConKey
= ReprEq
| otherwise
= NomEq
typeSize :: Type -> Int
typeSize (LitTy {}) = 1
typeSize (TyVarTy {}) = 1
typeSize (AppTy t1 t2) = typeSize t1 + typeSize t2
typeSize (FunTy t1 t2) = typeSize t1 + typeSize t2
typeSize (ForAllTy _ t) = 1 + typeSize t
typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts)
mkFamilyTyConApp :: TyCon -> [Type] -> Type
^ Given a family instance and its arg types , return the
Where the instance tycon is : RTL , so :
> mkFamilyTyConApp : RTL Int = T ( Maybe Int )
mkFamilyTyConApp tc tys
| Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
, let tvs = tyConTyVars tc
fam_subst = ASSERT2( length tvs == length tys, ppr tc <+> ppr tys )
zipTopTvSubst tvs tys
= mkTyConApp fam_tc (substTys fam_subst fam_tys)
| otherwise
= mkTyConApp tc tys
| Get the type on the LHS of a coercion induced by a type / data
coAxNthLHS :: CoAxiom br -> Int -> Type
coAxNthLHS ax ind =
mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind))
| Pretty prints a ' ' , using the family instance in case of a
In that case we want to print @T [ a]@ , where @T@ is the family ' '
pprSourceTyCon :: TyCon -> SDoc
pprSourceTyCon tycon
| Just (fam_tc, tys) <- tyConFamInst_maybe tycon
ca n't be
| otherwise
= ppr tycon
isUnLiftedType :: Type -> Bool
isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty
isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc
isUnLiftedType _ = False
isUnboxedTupleType :: Type -> Bool
isUnboxedTupleType ty = case tyConAppTyCon_maybe ty of
Just tc -> isUnboxedTupleTyCon tc
_ -> False
isAlgType :: Type -> Bool
isAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isAlgTyCon tc
_other -> False
isClosedAlgType :: Type -> Bool
isClosedAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc)
-> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
_other -> False
isStrictType :: Type -> Bool
isStrictType = isUnLiftedType
isPrimitiveType :: Type -> Bool
^ Returns true of types that are opaque to Haskell .
isPrimitiveType ty = case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isPrimTyCon tc
_ -> False
isObjectType :: Type -> Bool
isObjectType ty = case splitTyConApp_maybe ty of
Just (tc, _) -> isObjectTyCon tc
_ -> False
seqType :: Type -> ()
seqType (LitTy n) = n `seq` ()
seqType (TyVarTy tv) = tv `seq` ()
seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2
seqType (TyConApp tc tys) = tc `seq` seqTypes tys
seqType (ForAllTy tv ty) = seqType (tyVarKind tv) `seq` seqType ty
seqTypes :: [Type] -> ()
seqTypes [] = ()
seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
eqKind :: Kind -> Kind -> Bool
eqKind = eqType
eqType :: Type -> Type -> Bool
' PredType 's , but it does look through type synonyms .
eqType t1 t2 = isEqual $ cmpType t1 t2
instance Eq Type where
(==) = eqType
eqTypeX :: RnEnv2 -> Type -> Type -> Bool
eqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
eqTypes :: [Type] -> [Type] -> Bool
eqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
eqPred :: PredType -> PredType -> Bool
eqPred = eqType
eqPredX :: RnEnv2 -> PredType -> PredType -> Bool
eqPredX env p1 p2 = isEqual $ cmpTypeX env p1 p2
eqTyVarBndrs :: RnEnv2 -> [TyVar] -> [TyVar] -> Maybe RnEnv2
Check that the tyvar lists are the same length
and have matching kinds ; if so , extend the RnEnv2
eqTyVarBndrs env [] []
= Just env
eqTyVarBndrs env (tv1:tvs1) (tv2:tvs2)
| eqTypeX env (tyVarKind tv1) (tyVarKind tv2)
= eqTyVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2
eqTyVarBndrs _ _ _= Nothing
cmpType :: Type -> Type -> Ordering
cmpType t1 t2 = cmpTypeX rn_env t1 t2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
cmpTypes :: [Type] -> [Type] -> Ordering
cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
cmpPred :: PredType -> PredType -> Ordering
cmpPred p1 p2 = cmpTypeX rn_env p1 p2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType p1 `unionVarSet` tyVarsOfType p2))
cmpTypeX env t1 t2 | Just t1' <- coreView t1 = cmpTypeX env t1' t2
| Just t2' <- coreView t2 = cmpTypeX env t1 t2'
We expand predicate types , because in Core - land we have
fOrdBool : :
So the RHS has a data type
cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2
cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX env (tyVarKind tv1) (tyVarKind tv2)
`thenCmp` cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `cmpTc` tc2) `thenCmp` cmpTypesX env tys1 tys2
cmpTypeX _ (LitTy l1) (LitTy l2) = compare l1 l2
Deal with the rest : TyVarTy < AppTy < FunTy < LitTy < TyConApp < ForAllTy < PredTy
cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT
cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT
cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT
cmpTypeX _ (LitTy _) (TyVarTy _) = GT
cmpTypeX _ (LitTy _) (AppTy _ _) = GT
cmpTypeX _ (LitTy _) (FunTy _ _) = GT
cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT
cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT
cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT
cmpTypeX _ (TyConApp _ _) (LitTy _) = GT
cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT
cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT
cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT
cmpTypeX _ (ForAllTy _ _) (LitTy _) = GT
cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
cmpTypeX _ _ _ = LT
cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
cmpTypesX _ [] [] = EQ
cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
cmpTypesX _ [] _ = LT
cmpTypesX _ _ [] = GT
cmpTc :: TyCon -> TyCon -> Ordering
Here we treat * and Constraint as equal
See Note [ Kind Constraint and kind * ] in Kinds.lhs
cmpTc tc1 tc2
| u1 == openTypeKindTyConKey, isSubOpenTypeKindKey u2 = EQ
| u2 == openTypeKindTyConKey, isSubOpenTypeKindKey u1 = EQ
| otherwise = nu1 `compare` nu2
where
u1 = tyConUnique tc1
nu1 = if u1==constraintKindTyConKey then liftedTypeKindTyConKey else u1
u2 = tyConUnique tc2
nu2 = if u2==constraintKindTyConKey then liftedTypeKindTyConKey else u2
Note [ Comparison with OpenTypeKind ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In PrimOpWrappers we have things like
PrimOpWrappers.mkWeak # = /\ a b c. Prim.mkWeak # a b c
where
Prim.mkWeak # : : forall ( a : Open ) b c. a - > b - > c
- > State # RealWorld - > ( # State # RealWorld , Weak # b # )
Now , eta reduction will turn the definition into
PrimOpWrappers.mkWeak # = Prim.mkWeak #
which is kind - of OK , but now the types are n't really equal . So HACK HACK
we pretend ( in Core ) that Open is equal to * or # . I hate this .
Note [ cmpTypeX ]
~~~~~~~~~~~~~~~
When we compare foralls , we should look at the kinds . But if we do so ,
we get a corelint error like the following ( in
libraries / ghc - prim / GHC / PrimopWrappers.hs ):
Binder 's type : forall ( o_abY : : * ) .
o_abY
- > GHC.Prim . State # GHC.Prim . RealWorld
- > GHC.Prim . State # GHC.Prim . RealWorld
Rhs type : forall ( a_12 : : ? ) .
a_12
- > GHC.Prim . State # GHC.Prim . RealWorld
- > GHC.Prim . State # GHC.Prim . RealWorld
This is why we do n't look at the kind . Maybe we should look if the
kinds are compatible .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Type substitutions
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Note [Comparison with OpenTypeKind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In PrimOpWrappers we have things like
PrimOpWrappers.mkWeak# = /\ a b c. Prim.mkWeak# a b c
where
Prim.mkWeak# :: forall (a:Open) b c. a -> b -> c
-> State# RealWorld -> (# State# RealWorld, Weak# b #)
Now, eta reduction will turn the definition into
PrimOpWrappers.mkWeak# = Prim.mkWeak#
which is kind-of OK, but now the types aren't really equal. So HACK HACK
we pretend (in Core) that Open is equal to * or #. I hate this.
Note [cmpTypeX]
~~~~~~~~~~~~~~~
When we compare foralls, we should look at the kinds. But if we do so,
we get a corelint error like the following (in
libraries/ghc-prim/GHC/PrimopWrappers.hs):
Binder's type: forall (o_abY :: *).
o_abY
-> GHC.Prim.State# GHC.Prim.RealWorld
-> GHC.Prim.State# GHC.Prim.RealWorld
Rhs type: forall (a_12 :: ?).
a_12
-> GHC.Prim.State# GHC.Prim.RealWorld
-> GHC.Prim.State# GHC.Prim.RealWorld
This is why we don't look at the kind. Maybe we should look if the
kinds are compatible.
************************************************************************
* *
Type substitutions
* *
************************************************************************
-}
emptyTvSubstEnv :: TvSubstEnv
emptyTvSubstEnv = emptyVarEnv
composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
^ @(compose env1 env2)(x)@ is @env1(env2(x))@ ; i.e. apply @env2@ then @env1@.
composeTvSubst in_scope env1 env2
= env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
First apply env1 to the range of env2
Then combine the two , making sure that env1 loses if
both bind the same variable ; that 's why env1 is the
where
subst1 = TvSubst in_scope env1
emptyTvSubst :: TvSubst
emptyTvSubst = TvSubst emptyInScopeSet emptyTvSubstEnv
isEmptyTvSubst :: TvSubst -> Bool
See Note [ Extending the TvSubstEnv ] in TypeRep
isEmptyTvSubst (TvSubst _ tenv) = isEmptyVarEnv tenv
mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
mkTvSubst = TvSubst
getTvSubstEnv :: TvSubst -> TvSubstEnv
getTvSubstEnv (TvSubst _ env) = env
getTvInScope :: TvSubst -> InScopeSet
getTvInScope (TvSubst in_scope _) = in_scope
isInScope :: Var -> TvSubst -> Bool
isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
notElemTvSubst :: CoVar -> TvSubst -> Bool
notElemTvSubst v (TvSubst _ tenv) = not (v `elemVarEnv` tenv)
setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
setTvSubstEnv (TvSubst in_scope _) tenv = TvSubst in_scope tenv
zapTvSubstEnv :: TvSubst -> TvSubst
zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
extendTvInScope :: TvSubst -> Var -> TvSubst
extendTvInScope (TvSubst in_scope tenv) var = TvSubst (extendInScopeSet in_scope var) tenv
extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
extendTvInScopeList (TvSubst in_scope tenv) vars = TvSubst (extendInScopeSetList in_scope vars) tenv
extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
extendTvSubst (TvSubst in_scope tenv) tv ty = TvSubst in_scope (extendVarEnv tenv tv ty)
extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
extendTvSubstList (TvSubst in_scope tenv) tvs tys
= TvSubst in_scope (extendVarEnvList tenv (tvs `zip` tys))
unionTvSubst :: TvSubst -> TvSubst -> TvSubst
unionTvSubst (TvSubst in_scope1 tenv1) (TvSubst in_scope2 tenv2)
= ASSERT( not (tenv1 `intersectsVarEnv` tenv2) )
TvSubst (in_scope1 `unionInScope` in_scope2)
(tenv1 `plusVarEnv` tenv2)
mkOpenTvSubst and zipOpenTvSubst generate the in - scope set from
If we want to substitute [ a - > , b - > ty2 ] I used to
! This means looking at all the calls to mkOpenTvSubst ....
| Generates the in - scope set for the ' ' from the types in the incoming
mkOpenTvSubst :: TvSubstEnv -> TvSubst
mkOpenTvSubst tenv = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts tenv))) tenv
| Generates the in - scope set for the ' ' from the types in the incoming
zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
zipOpenTvSubst tyvars tys
| debugIsOn && (length tyvars /= length tys)
= pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
| otherwise
= TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
zipTopTvSubst tyvars tys
| debugIsOn && (length tyvars /= length tys)
= pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
| otherwise
= TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
zipTyEnv tyvars tys
| debugIsOn && (length tyvars /= length tys)
= pprTrace "zipTyEnv" (ppr tyvars $$ ppr tys) emptyVarEnv
| otherwise
= zip_ty_env tyvars tys emptyVarEnv
zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
zip_ty_env [] [] env = env
zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
ty = = TyVarTy tv
a type { Foo t } , where is a one - method class . So is really a newtype .
zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
instance Outputable TvSubst where
ppr (TvSubst ins tenv)
= brackets $ sep[ ptext (sLit "TvSubst"),
nest 2 (ptext (sLit "In scope:") <+> ppr ins),
nest 2 (ptext (sLit "Type env:") <+> ppr tenv) ]
| Type substitution making use of an ' ' that
is assumed to be open , see ' zipOpenTvSubst '
substTyWith :: [TyVar] -> [Type] -> Type -> Type
substTyWith tvs tys = ASSERT( length tvs == length tys )
substTy (zipOpenTvSubst tvs tys)
substKiWith :: [KindVar] -> [Kind] -> Kind -> Kind
substKiWith = substTyWith
| Type substitution making use of an ' ' that
is assumed to be open , see ' zipOpenTvSubst '
substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
substTysWith tvs tys = ASSERT( length tvs == length tys )
substTys (zipOpenTvSubst tvs tys)
substKisWith :: [KindVar] -> [Kind] -> [Kind] -> [Kind]
substKisWith = substTysWith
substTyAddInScope :: TvSubst -> Type -> Type
substTyAddInScope subst ty =
substTy (extendTvInScopeList subst $ varSetElems $ tyVarsOfType ty) ty
substTy :: TvSubst -> Type -> Type
substTy subst ty | isEmptyTvSubst subst = ty
| otherwise = subst_ty subst ty
substTys :: TvSubst -> [Type] -> [Type]
substTys subst tys | isEmptyTvSubst subst = tys
| otherwise = map (subst_ty subst) tys
| Substitute within a ' ThetaType '
substTheta :: TvSubst -> ThetaType -> ThetaType
substTheta subst theta
| isEmptyTvSubst subst = theta
| otherwise = map (substTy subst) theta
| Remove any nested binders mentioning the ' TyVar 's in the ' TyVarSet '
deShadowTy :: TyVarSet -> Type -> Type
deShadowTy tvs ty
= subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
where
in_scope = mkInScopeSet tvs
subst_ty :: TvSubst -> Type -> Type
subst_ty subst ty
= go ty
where
go (LitTy n) = n `seq` LitTy n
go (TyVarTy tv) = substTyVar subst tv
go (TyConApp tc tys) = let args = map go tys
in args `seqList` TyConApp tc args
go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
The mkAppTy smart constructor is important
go (ForAllTy tv ty) = case substTyVarBndr subst tv of
(subst', tv') ->
ForAllTy tv' $! (subst_ty subst' ty)
substTyVar :: TvSubst -> TyVar -> Type
substTyVar (TvSubst _ tenv) tv
in TypeRep
We do not require that the tyvar is in scope
Instead we have an ASSERT in substTyVarBndr to check for capture
substTyVars :: TvSubst -> [TyVar] -> [Type]
substTyVars subst tvs = map (substTyVar subst) tvs
lookupTyVar :: TvSubst -> TyVar -> Maybe Type
See Note [ Extending the TvSubst ] in TypeRep
lookupTyVar (TvSubst _ tenv) tv = lookupVarEnv tenv tv
substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)
substTyVarBndr subst@(TvSubst in_scope tenv) old_var
= ASSERT2( _no_capture, ppr old_var $$ ppr subst )
(TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
where
new_env | no_change = delVarEnv tenv old_var
| otherwise = extendVarEnv tenv old_var (TyVarTy new_var)
_no_capture = not (new_var `elemVarSet` tyVarsOfTypes (varEnvElts tenv))
old_ki = tyVarKind old_var
no_change = no_kind_change && (new_var == old_var)
See Note [ Extending the TvSubst ] in TypeRep
new_var | no_kind_change = uniqAway in_scope old_var
| otherwise = uniqAway in_scope $ updateTyVarKind (substTy subst) old_var
cloneTyVarBndr :: TvSubst -> TyVar -> Unique -> (TvSubst, TyVar)
cloneTyVarBndr (TvSubst in_scope tv_env) tv uniq
= (TvSubst (extendInScopeSet in_scope tv')
(extendVarEnv tv_env tv (mkTyVarTy tv')), tv')
where
cloneTyVarBndrs :: TvSubst -> [TyVar] -> UniqSupply -> (TvSubst, [TyVar])
cloneTyVarBndrs subst [] _usupply = (subst, [])
cloneTyVarBndrs subst (t:ts) usupply = (subst'', tv:tvs)
where
(uniq, usupply') = takeUniqFromSupply usupply
(subst' , tv ) = cloneTyVarBndr subst t uniq
(subst'', tvs) = cloneTyVarBndrs subst' ts usupply'
Kinds
~~~~~
For the description of subkinding in GHC , see
#Kinds
Kinds
~~~~~
For the description of subkinding in GHC, see
#Kinds
-}
invariant : MetaKindVar will always be a
TcTyVar with details ( TauTv ... ) ...
meta kind var constructors and functions are in TcType
type SimpleKind = Kind
typeKind :: Type -> Kind
typeKind orig_ty = go orig_ty
where
go ty@(TyConApp tc tys)
| isPromotedTyCon tc
= ASSERT( tyConArity tc == length tys ) superKind
| otherwise
= kindAppResult (ptext (sLit "typeKind 1") <+> ppr ty $$ ppr orig_ty)
(tyConKind tc) tys
go ty@(AppTy fun arg) = kindAppResult (ptext (sLit "typeKind 2") <+> ppr ty $$ ppr orig_ty)
(go fun) [arg]
go (LitTy l) = typeLiteralKind l
go (ForAllTy _ ty) = go ty
go (TyVarTy tyvar) = tyVarKind tyvar
go _ty@(FunTy _arg res)
( b ) kinds ( of super - kind TY ) ( e.g. * - > ( * - > * ) )
| isSuperKind k = k
| otherwise = ASSERT2( isSubOpenTypeKind k, ppr _ty $$ ppr k ) liftedTypeKind
where
k = go res
typeLiteralKind :: TyLit -> Kind
typeLiteralKind l =
case l of
NumTyLit _ -> typeNatKind
StrTyLit _ -> typeSymbolKind
Kind inference
~~~~~~~~~~~~~~
During kind inference , a kind variable unifies only with
a " simple kind " , sk
sk : : = * | sk1 - > sk2
For example
data T a = MkT a ( T Int # )
fails . We give T the kind ( k - > * ) , and the kind variable k wo n't unify
with # ( the kind of Int # ) .
Type inference
~~~~~~~~~~~~~~
When creating a fresh internal type variable , we give it a kind to express
constraints on it . E.g. in ( \x->e ) we make up a fresh type variable for x ,
with kind ? ? .
During unification we only bind an internal type variable to a type
whose kind is lower in the sub - kind hierarchy than the kind of the tyvar .
When unifying two internal type variables , we collect their kind constraints by
finding the GLB of the two . Since the partial order is a tree , they only
have a glb if one is a sub - kind of the other . In that case , we bind the
less - informative one to the more informative one . Neat , eh ?
Kind inference
~~~~~~~~~~~~~~
During kind inference, a kind variable unifies only with
a "simple kind", sk
sk ::= * | sk1 -> sk2
For example
data T a = MkT a (T Int#)
fails. We give T the kind (k -> *), and the kind variable k won't unify
with # (the kind of Int#).
Type inference
~~~~~~~~~~~~~~
When creating a fresh internal type variable, we give it a kind to express
constraints on it. E.g. in (\x->e) we make up a fresh type variable for x,
with kind ??.
During unification we only bind an internal type variable to a type
whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
When unifying two internal type variables, we collect their kind constraints by
finding the GLB of the two. Since the partial order is a tree, they only
have a glb if one is a sub-kind of the other. In that case, we bind the
less-informative one to the more informative one. Neat, eh?
-}
|
7dea11f49a80b371da83b622cf23795fbe5e79804e1474bb3921ab902a7fcab5 | mtravers/wuwei | error.lisp | (in-package :wu)
;;; +=========================================================================+
| Copyright ( c ) 2009 , 2010 and CollabRx , Inc |
;;; | |
| Released under the MIT Open Source License |
;;; | -license.php |
;;; | |
;;; | Permission is hereby granted, free of charge, to any person obtaining |
;;; | a copy of this software and associated documentation files (the |
| " Software " ) , to deal in the Software without restriction , including |
;;; | without limitation the rights to use, copy, modify, merge, publish, |
| distribute , sublicense , and/or sell copies of the Software , and to |
| permit persons to whom the Software is furnished to do so , subject to |
;;; | the following conditions: |
;;; | |
;;; | The above copyright notice and this permission notice shall be included |
| in all copies or substantial portions of the Software . |
;;; | |
| THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , |
;;; | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
;;; | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
;;; | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , |
;;; | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
;;; | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
;;; +=========================================================================+
Author : and
(export '(error-box render-error clear-error
with-html-error-handling
with-json-error-handling
with-html-safe-error-handling
with-ajax-error-handler
))
(defun system-info ()
"Replace with commands to get your system version info, eg by running 'hg log -l 1' in a shell")
(defun report-bug-button (&optional (info ""))
(html
((:a :href (format nil "~a?description=~A" *bug-report-url* (uriencode-string (format nil "In ~A:~%~%~a" (system-info) info)))
:target "error") "Report a bug")))
;;; Insert an error box for use by the error handler (++ should have a clear button)
(defun error-box ()
(html ((:div :id "error_box" :style "display:none;")))) ;invisible until replaced
;;; This isn't called anywhere (and should :update and set invisible rather than :replace)
(defun clear-error ()
(render-update
(:replace "error_box" (html ((:div :id "error_box"))))))
;;; This isn't called anywhere (and should :update rather than :replace)
(defun render-error (msg &key stack-trace user-error?)
(render-update
(:replace "error_box"
(html
((:div :class (if user-error? "uerror" "error") :id "error_box") ;!!! have to keep this id or later errors won't work
(:princ-safe msg)
(unless user-error?
(html
(report-bug-button stack-trace)
((:a :onclick "toggle_visibility('error_box_stack_trace');") " Show stack ")
((:div :id "error_box_stack_trace" :style "display:none;") ;:class "error"
(:pre
(:princ-safe stack-trace))
))))))))
;;; Set to T to use the error box rather than alert method.
(def-session-variable *ajax-error-box?* nil)
;;; ++ needs better name: this composes, logs, and sends it back to client
(defun compose-error-message (path &key error stack-trace extra-js)
(let ((message (format nil "Lisp error while servicing ~a: ~A~:[~;~a~]" path error *developer-mode* stack-trace)))
(log-message message)
;;; This doesn't work; the header is already generated and sent.
( setf ( request - reply - code * ajax - request * ) 400 )
(if *multipart-request*
(html
(:princ (json:encode-json-to-string `((failure . true)
;;(success . false)
(records ((data . ,(clean-upload-js-string message))))))))
(let ((estring (princ-to-string error)))
(if *ajax-error-box?*
(render-update
(:update "error_box" (:princ-safe estring))
(:show "error_box"))
;; alertbox method
(render-update
(:alert (clean-js-string estring))))
(when extra-js
(render-update
(:js extra-js)))
))))
;; --> conditionalize to use html or javascript, depending on context.
;; Scrub the string more vigorously!
(defun html-report-error (&key error stack-trace)
;; Log this?
(log-message (format nil "~%Unhandled exception caught by with-html-error-handling: ~a~%~a~%" error stack-trace))
(html
((:div :class "error")
(:b
(:princ-safe (string+ "Error: " (princ-to-string error))
))
(if (and stack-trace *developer-mode*)
(html
(:pre
(:princ-safe stack-trace))
)
)
)
))
(defun create-block-for-error (&key error stack-trace)
(html-report-error :error error :stack-trace stack-trace)
(write-string (html-string
(html-report-error :error error))))
;;; Another method: do all generation to a string; if an error occurs catch it and make a error block instead
(defmacro with-html-safe-error-handling (&body body)
`(without-unwinding-restart (create-block-for-error)
(write-string (html-string ,@body) *html-stream*)))
(defmacro with-ajax-error-handler ((name &key extra-js) &body body)
`(without-unwinding-restart (compose-error-message ,name :extra-js ,extra-js)
,@body
))
(defun json-report-error (&key error stack-trace)
(log-message (format nil "~%Unhandled exception caught by with-html-error-handling: ~a~%~a~%" error stack-trace))
(html
(:princ (json:encode-json-to-string `((failure . true)
(success . false)
(message . ,(format nil "~A" error)))))))
(defmacro with-json-error-handling (&body body)
`(without-unwinding-restart (json-report-error)
,@body))
;;; Note: has to be inside of with-http-response-and-body or equivalent
unfortunately this means that errors ca n't cause a 404 or 500 or whatever HTTP response like they should + + + rethinking needed
;;; If you want to close off html elements in case of an error, I think you need to add unwind-protects to html-body-key-form
in /misc / downloads / cl - portable - aserve-1.2.42 / aserve / htmlgen / htmlgen.cl
;;; get-frames-list for a backtrace (but probably need a different kind of handler in that case)
(defmacro with-html-error-handling (&body body)
`(without-unwinding-restart (html-report-error)
,@body))
(defvar *logging* t)
(defvar *logging-stream* *standard-output*)
(defun log-message (message)
(if *logging*
(format *logging-stream* "~a ~a~%" (net.aserve::universal-time-to-date (get-universal-time)) message)))
| null | https://raw.githubusercontent.com/mtravers/wuwei/c0968cca10554fa12567d48be6f932bf4418dbe1/src/error.lisp | lisp | +=========================================================================+
| |
| -license.php |
| |
| Permission is hereby granted, free of charge, to any person obtaining |
| a copy of this software and associated documentation files (the |
| without limitation the rights to use, copy, modify, merge, publish, |
| the following conditions: |
| |
| The above copyright notice and this permission notice shall be included |
| |
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
+=========================================================================+
Insert an error box for use by the error handler (++ should have a clear button)
invisible until replaced
This isn't called anywhere (and should :update and set invisible rather than :replace)
This isn't called anywhere (and should :update rather than :replace)
!!! have to keep this id or later errors won't work
:class "error"
Set to T to use the error box rather than alert method.
++ needs better name: this composes, logs, and sends it back to client
This doesn't work; the header is already generated and sent.
(success . false)
alertbox method
--> conditionalize to use html or javascript, depending on context.
Scrub the string more vigorously!
Log this?
Another method: do all generation to a string; if an error occurs catch it and make a error block instead
Note: has to be inside of with-http-response-and-body or equivalent
If you want to close off html elements in case of an error, I think you need to add unwind-protects to html-body-key-form
get-frames-list for a backtrace (but probably need a different kind of handler in that case) | (in-package :wu)
| Copyright ( c ) 2009 , 2010 and CollabRx , Inc |
| Released under the MIT Open Source License |
| " Software " ) , to deal in the Software without restriction , including |
| distribute , sublicense , and/or sell copies of the Software , and to |
| permit persons to whom the Software is furnished to do so , subject to |
| in all copies or substantial portions of the Software . |
| THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , |
| CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , |
Author : and
(export '(error-box render-error clear-error
with-html-error-handling
with-json-error-handling
with-html-safe-error-handling
with-ajax-error-handler
))
(defun system-info ()
"Replace with commands to get your system version info, eg by running 'hg log -l 1' in a shell")
(defun report-bug-button (&optional (info ""))
(html
((:a :href (format nil "~a?description=~A" *bug-report-url* (uriencode-string (format nil "In ~A:~%~%~a" (system-info) info)))
:target "error") "Report a bug")))
(defun error-box ()
(defun clear-error ()
(render-update
(:replace "error_box" (html ((:div :id "error_box"))))))
(defun render-error (msg &key stack-trace user-error?)
(render-update
(:replace "error_box"
(html
(:princ-safe msg)
(unless user-error?
(html
(report-bug-button stack-trace)
((:a :onclick "toggle_visibility('error_box_stack_trace');") " Show stack ")
(:pre
(:princ-safe stack-trace))
))))))))
(def-session-variable *ajax-error-box?* nil)
(defun compose-error-message (path &key error stack-trace extra-js)
(let ((message (format nil "Lisp error while servicing ~a: ~A~:[~;~a~]" path error *developer-mode* stack-trace)))
(log-message message)
( setf ( request - reply - code * ajax - request * ) 400 )
(if *multipart-request*
(html
(:princ (json:encode-json-to-string `((failure . true)
(records ((data . ,(clean-upload-js-string message))))))))
(let ((estring (princ-to-string error)))
(if *ajax-error-box?*
(render-update
(:update "error_box" (:princ-safe estring))
(:show "error_box"))
(render-update
(:alert (clean-js-string estring))))
(when extra-js
(render-update
(:js extra-js)))
))))
(defun html-report-error (&key error stack-trace)
(log-message (format nil "~%Unhandled exception caught by with-html-error-handling: ~a~%~a~%" error stack-trace))
(html
((:div :class "error")
(:b
(:princ-safe (string+ "Error: " (princ-to-string error))
))
(if (and stack-trace *developer-mode*)
(html
(:pre
(:princ-safe stack-trace))
)
)
)
))
(defun create-block-for-error (&key error stack-trace)
(html-report-error :error error :stack-trace stack-trace)
(write-string (html-string
(html-report-error :error error))))
(defmacro with-html-safe-error-handling (&body body)
`(without-unwinding-restart (create-block-for-error)
(write-string (html-string ,@body) *html-stream*)))
(defmacro with-ajax-error-handler ((name &key extra-js) &body body)
`(without-unwinding-restart (compose-error-message ,name :extra-js ,extra-js)
,@body
))
(defun json-report-error (&key error stack-trace)
(log-message (format nil "~%Unhandled exception caught by with-html-error-handling: ~a~%~a~%" error stack-trace))
(html
(:princ (json:encode-json-to-string `((failure . true)
(success . false)
(message . ,(format nil "~A" error)))))))
(defmacro with-json-error-handling (&body body)
`(without-unwinding-restart (json-report-error)
,@body))
unfortunately this means that errors ca n't cause a 404 or 500 or whatever HTTP response like they should + + + rethinking needed
in /misc / downloads / cl - portable - aserve-1.2.42 / aserve / htmlgen / htmlgen.cl
(defmacro with-html-error-handling (&body body)
`(without-unwinding-restart (html-report-error)
,@body))
(defvar *logging* t)
(defvar *logging-stream* *standard-output*)
(defun log-message (message)
(if *logging*
(format *logging-stream* "~a ~a~%" (net.aserve::universal-time-to-date (get-universal-time)) message)))
|
3a211c5b2a1502083b2d1788eabeeebeae711ed1e7af3741d441b3e5e599b94d | FranklinChen/hugs98-plus-Sep2006 | Format.hs | -- #hide
--------------------------------------------------------------------------------
-- |
-- Module : Sound.OpenAL.AL.Format
Copyright : ( c ) 2003 - 2005
-- License : BSD-style (see the file libraries/OpenAL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
This is a purely internal module for ( un-)marshaling Format .
--
--------------------------------------------------------------------------------
module Sound.OpenAL.AL.Format (
Format(..), marshalFormat, unmarshalFormat
) where
import Sound.OpenAL.AL.BasicTypes ( ALenum )
import Sound.OpenAL.Constants (
al_FORMAT_MONO8, al_FORMAT_MONO16, al_FORMAT_STEREO8, al_FORMAT_STEREO16 )
--------------------------------------------------------------------------------
-- | Valid sound formats. An implementation may expose other formats, see
" Sound . " for information on determining if additional
-- formats are supported.
data Format =
Mono8
| Mono16
| Stereo8
| Stereo16
deriving ( Eq, Ord, Show )
marshalFormat :: Format -> ALenum
marshalFormat x = case x of
Mono8 -> al_FORMAT_MONO8
Mono16 -> al_FORMAT_MONO16
Stereo8 -> al_FORMAT_STEREO8
Stereo16 -> al_FORMAT_STEREO16
unmarshalFormat :: ALenum -> Format
unmarshalFormat x
| x == al_FORMAT_MONO8 = Mono8
| x == al_FORMAT_MONO16 = Mono16
| x == al_FORMAT_STEREO8 = Stereo8
| x == al_FORMAT_STEREO16 = Stereo16
| otherwise = error ("unmarshalFormat: illegal value " ++ show x)
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/OpenAL/Sound/OpenAL/AL/Format.hs | haskell | #hide
------------------------------------------------------------------------------
|
Module : Sound.OpenAL.AL.Format
License : BSD-style (see the file libraries/OpenAL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Valid sound formats. An implementation may expose other formats, see
formats are supported. | Copyright : ( c ) 2003 - 2005
This is a purely internal module for ( un-)marshaling Format .
module Sound.OpenAL.AL.Format (
Format(..), marshalFormat, unmarshalFormat
) where
import Sound.OpenAL.AL.BasicTypes ( ALenum )
import Sound.OpenAL.Constants (
al_FORMAT_MONO8, al_FORMAT_MONO16, al_FORMAT_STEREO8, al_FORMAT_STEREO16 )
" Sound . " for information on determining if additional
data Format =
Mono8
| Mono16
| Stereo8
| Stereo16
deriving ( Eq, Ord, Show )
marshalFormat :: Format -> ALenum
marshalFormat x = case x of
Mono8 -> al_FORMAT_MONO8
Mono16 -> al_FORMAT_MONO16
Stereo8 -> al_FORMAT_STEREO8
Stereo16 -> al_FORMAT_STEREO16
unmarshalFormat :: ALenum -> Format
unmarshalFormat x
| x == al_FORMAT_MONO8 = Mono8
| x == al_FORMAT_MONO16 = Mono16
| x == al_FORMAT_STEREO8 = Stereo8
| x == al_FORMAT_STEREO16 = Stereo16
| otherwise = error ("unmarshalFormat: illegal value " ++ show x)
|
a8e2aa784d114a70b6a6bdf175ddd25959bf1651ffd8142e9f5f05348b59cdeb | rickeyski/slack-api | ChannelOpt.hs | # LANGUAGE OverloadedStrings , TemplateHaskell #
module Web.Slack.Types.ChannelOpt where
import Data.Aeson
import Control.Lens.TH
import Control.Applicative
import Web.Slack.Types.Event
import Web.Slack.Types.Time
import Prelude
data ChannelOpt = ChannelOpt
{ _channelOptLastRead :: SlackTimeStamp
, _channelOptUnreadCount :: Int
, _channelOptLatest :: Event
} deriving (Show)
makeLenses ''ChannelOpt
instance FromJSON ChannelOpt where
parseJSON = withObject "ChannelOpt"
(\o -> ChannelOpt
<$> o .: "last_read"
<*> o .: "unread_count"
<*> o .: "latest")
| null | https://raw.githubusercontent.com/rickeyski/slack-api/5f6659e09bce19fe0ca9dfce8743bec7de518d77/src/Web/Slack/Types/ChannelOpt.hs | haskell | # LANGUAGE OverloadedStrings , TemplateHaskell #
module Web.Slack.Types.ChannelOpt where
import Data.Aeson
import Control.Lens.TH
import Control.Applicative
import Web.Slack.Types.Event
import Web.Slack.Types.Time
import Prelude
data ChannelOpt = ChannelOpt
{ _channelOptLastRead :: SlackTimeStamp
, _channelOptUnreadCount :: Int
, _channelOptLatest :: Event
} deriving (Show)
makeLenses ''ChannelOpt
instance FromJSON ChannelOpt where
parseJSON = withObject "ChannelOpt"
(\o -> ChannelOpt
<$> o .: "last_read"
<*> o .: "unread_count"
<*> o .: "latest")
| |
51c12a65fd53a8812f4ade8f7614b62b897764b2948b2c9aebeb65f0bef679ba | krisajenkins/petrol | view.cljs | (ns petrol-examples.spotify.view
(:require [petrol.core :refer [send! send-value!]]
[petrol-examples.spotify.messages :as m]))
(defn- get-track-image-url
[track]
(-> track :album :images first :url))
(defn- track-view
[{:keys [name]
:as track}]
[:div.thumbnail
(when-let [img-src (get-track-image-url track)]
[:img.img-responsive
{:alt name
:src img-src}])
[:div.caption
(when-let [audio-src (:preview_url track)]
[:audio {:src audio-src
:controls :controls}])
[:h4 name]]])
(defn- search-form
[ui-channel term]
[:div
[:input {:type :text
:placeholder "Song name..."
:defaultValue term
:on-change (send-value! ui-channel m/->ChangeSearchTerm)}]
[:button.btn.btn-success
{:on-click (send! ui-channel (m/->Search))}
"Go"]])
(defn root
[ui-channel {:keys [term tracks]
:as app}]
[:div {:style {:display :flex
:flex-direction :column
:align-items :center}}
[:h1 "Simple Spotify Client"]
[search-form ui-channel term]
[:div
(for [track tracks]
[:div {:key (:id track)
:style {:height "420px"
:float :left
:margin "20px"
:width "330px"}}
[track-view track]])]])
| null | https://raw.githubusercontent.com/krisajenkins/petrol/607166ab48cf6193b6ad00bcd63bd3ff7f3958f7/examples/src/petrol-examples/spotify/view.cljs | clojure | (ns petrol-examples.spotify.view
(:require [petrol.core :refer [send! send-value!]]
[petrol-examples.spotify.messages :as m]))
(defn- get-track-image-url
[track]
(-> track :album :images first :url))
(defn- track-view
[{:keys [name]
:as track}]
[:div.thumbnail
(when-let [img-src (get-track-image-url track)]
[:img.img-responsive
{:alt name
:src img-src}])
[:div.caption
(when-let [audio-src (:preview_url track)]
[:audio {:src audio-src
:controls :controls}])
[:h4 name]]])
(defn- search-form
[ui-channel term]
[:div
[:input {:type :text
:placeholder "Song name..."
:defaultValue term
:on-change (send-value! ui-channel m/->ChangeSearchTerm)}]
[:button.btn.btn-success
{:on-click (send! ui-channel (m/->Search))}
"Go"]])
(defn root
[ui-channel {:keys [term tracks]
:as app}]
[:div {:style {:display :flex
:flex-direction :column
:align-items :center}}
[:h1 "Simple Spotify Client"]
[search-form ui-channel term]
[:div
(for [track tracks]
[:div {:key (:id track)
:style {:height "420px"
:float :left
:margin "20px"
:width "330px"}}
[track-view track]])]])
| |
225c88addb06b57ab43a93dce228551ab62ca1204a71f6dc9734f39ae787a397 | danielsz/sketching-with-css-in-clojure | core.clj | (ns fioritto.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| null | https://raw.githubusercontent.com/danielsz/sketching-with-css-in-clojure/1d71297b626e4841cb15c44f7f3b2cc6d5e25f56/src/fioritto/core.clj | clojure | (ns fioritto.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| |
f3ef6bafd9fbcf7d36957a31ea495da94f33cbd1c55f41e5bb17299f04e760de | ygrek/mldonkey | gui_config.ml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(** Configuration panel. *)
open Printf2
open Gettext
open Gui_global
module GO = Gui_options
open Configwin
module M = Gui_messages
let (!!) = Options.(!!)
let (=:=) = Options.(=:=)
let safe_int_of_string option s =
try option =:= int_of_string s
with _ -> ()
let create_gui_params () =
(** Server options *)
let gui_port = string
~help: (gettext M.h_gui_port)
~f: (fun s -> safe_int_of_string GO.port s)
(gettext M.o_gui_port) (string_of_int !!GO.port)
in
let gui_hostname = string
~help: (gettext M.h_hostname)
~f: (fun s -> GO.hostname =:= s)
(gettext M.o_hostname) !!GO.hostname
in
let gui_login = string
~help: "Your login"
~f: (fun s -> GO.login =:= s)
"Login:" !!GO.login
in
let gui_password = password
~help: (gettext M.h_gui_password)
~f: (fun s -> GO.password =:= s)
(gettext M.o_password) !!GO.password
in
let server_options = Section
((gettext M.o_gui_server),
[
gui_port ; gui_hostname ; gui_login ; gui_password ;
]
)
in
(** Colors *)
let color_default = color
~help: (gettext M.h_col_default)
~f: (fun s -> GO.color_default =:= s)
(gettext M.o_col_default) !!GO.color_default
in
let color_downloaded = color
~help: (gettext M.h_col_downloaded)
~f: (fun s -> GO.color_downloaded =:= s)
(gettext M.o_col_downloaded) !!GO.color_downloaded
in
let color_downloading = color
~help: (gettext M.h_col_downloading)
~f: (fun s -> GO.color_downloading =:= s)
(gettext M.o_col_downloading) !!GO.color_downloading
in
let color_available = color
~help: (gettext M.h_col_avail)
~f: (fun s -> GO.color_available =:= s)
(gettext M.o_col_avail) !!GO.color_available
in
let color_not_available = color
~help: (gettext M.h_col_not_avail)
~f: (fun s -> GO.color_not_available =:= s)
(gettext M.o_col_not_avail) !!GO.color_not_available
in
let color_connected = color
~help: (gettext M.h_col_connected)
~f: (fun s -> GO.color_connected =:= s)
(gettext M.o_col_connected) !!GO.color_connected
in
let color_not_connected = color
~help: (gettext M.h_col_not_connected)
~f: (fun s -> GO.color_not_connected =:= s)
(gettext M.o_col_not_connected) !!GO.color_not_connected
in
let color_connecting = color
~help: M.h_col_connecting
~f: (fun s -> GO.color_connecting =:= s)
(gettext M.o_col_connecting) !!GO.color_connecting
in
let color_files_listed = color
~help: (M.h_col_files_listed)
~f: (fun s -> GO.color_files_listed =:= s)
(gettext M.o_col_files_listed) !!GO.color_files_listed
in
let colors_options = Section
((gettext M.o_colors),
[
color_default ; color_downloaded ;
color_downloading ; color_available ;
color_not_available ;
color_connected ; color_not_connected ;
color_connecting ; color_files_listed ;
]
)
in
* Layout options
let tb_style = combo
~expand:false
~help: (gettext M.h_toolbars_style)
~f:(fun s -> GO.toolbars_style =:= GO.string_to_tbstyle s)
~new_allowed:false ~blank_allowed:false
(gettext M.o_toolbars_style)
(List.map fst GO.tb_styles)
(GO.tbstyle_to_string !!GO.toolbars_style)
in
let tb_icons = bool
~help: "Mini icons in toolbars:"
~f: (fun b -> GO.mini_toolbars =:= b)
"Mini icons in toolbars:" !!GO.mini_toolbars
in
let tab_pos = combo
~expand:false
~help: "Position of main tab"
~f:(fun s -> GO.notebook_tab =:= GO.TabPosition.string_to_pos s)
~new_allowed:false ~blank_allowed:false
"Tab Position:"
GO.TabPosition.values
(GO.TabPosition.pos_to_string !!GO.notebook_tab)
in
let layout_options = Section
((gettext M.o_layout),
[
tb_style ;
tb_icons;
tab_pos;
]
)
in
let sel l f_string () =
let menu = GMenu.menu () in
let choice = ref None in
let entries = List.map
(fun ele ->
`I (f_string ele, fun () -> choice := Some ele))
l
in
GToolbox.build_menu menu ~entries;
ignore (menu#connect#deactivate GMain.Main.quit);
menu#popup 0 0;
GMain.Main.main ();
match !choice with
None -> []
| Some c -> [c]
in
(** Columns options *)
let servers_cols = list
~help: (gettext M.h_servers_columns)
~f: (fun l -> GO.servers_columns =:= l)
~add: (sel
(List.map fst Gui_columns.server_column_strings)
Gui_columns.Server.string_of_column)
""
(fun c -> [Gui_columns.Server.string_of_column c])
!!GO.servers_columns
in
let dls_cols = list
~help: (gettext M.h_downloads_columns)
~f: (fun l -> GO.downloads_columns =:= l)
~add: (sel
(List.map fst Gui_columns.file_column_strings)
Gui_columns.File.string_of_column)
""
(fun c -> [Gui_columns.File.string_of_column c])
!!GO.downloads_columns
in
let dled_cols = list
~help: (gettext M.h_downloaded_columns)
~f: (fun l -> GO.downloaded_columns =:= l)
~add: (sel
(List.map fst Gui_columns.file_column_strings)
Gui_columns.File.string_of_column)
""
(fun c -> [Gui_columns.File.string_of_column c])
!!GO.downloaded_columns
in
let friends_cols = list
~help: (gettext M.h_friends_columns)
~f: (fun l -> GO.friends_columns =:= l)
~add: (sel
(List.map fst Gui_columns.client_column_strings)
Gui_columns.Client.string_of_column)
""
(fun c -> [Gui_columns.Client.string_of_column c])
!!GO.friends_columns
in
let file_locs_cols = list
~help: (gettext M.h_file_locations_columns)
~f: (fun l -> GO.file_locations_columns =:= l)
~add: (sel
(List.map fst Gui_columns.client_column_strings)
Gui_columns.Client.string_of_column)
""
(fun c -> [Gui_columns.Client.string_of_column c])
!!GO.file_locations_columns
in
let results_cols = list
~help: (gettext M.h_results_columns)
~f: (fun l -> GO.results_columns =:= l)
~add: (sel
(List.map fst Gui_columns.result_column_strings)
Gui_columns.Result.string_of_column)
""
(fun c -> [Gui_columns.Result.string_of_column c])
!!GO.results_columns
in
let shared_cols = list
~help: (M.h_shared_files_up_columns)
~f: (fun l -> GO.shared_files_up_columns =:= l)
~add: (sel
(List.map fst Gui_columns.shared_file_up_column_strings)
Gui_columns.Shared_files_up.string_of_column)
""
(fun c -> [Gui_columns.Shared_files_up.string_of_column c])
!!GO.shared_files_up_columns
in
let columns_options = Section_list
((gettext M.o_columns),
[
Section ((gettext M.o_servers_columns) ,[servers_cols]) ;
Section ((gettext M.o_downloads_columns) ,[dls_cols]);
Section ((gettext M.o_downloaded_columns) ,[dled_cols]);
Section ((gettext M.o_results_columns) ,[results_cols]);
Section ((gettext M.o_friends_columns) ,[friends_cols]) ;
Section ((gettext M.o_file_locations_columns) ,[file_locs_cols]) ;
Section ((gettext M.o_shared_files_up_colums) ,[shared_cols]) ;
]
)
in
let files_auto_expand_depth = string
~f: (safe_int_of_string GO.files_auto_expand_depth)
~help: (M.h_files_auto_expand_depth)
(gettext M.o_files_auto_expand_depth)
(string_of_int !!GO.files_auto_expand_depth)
in
let use_size_suffixes = bool
~f: (fun b -> GO.use_size_suffixes =:= b)
~help: (M.h_use_size_suffixes)
(gettext M.o_use_size_suffixes)
!!GO.use_size_suffixes
in
let use_availability_height = bool
~f: (fun b -> GO.use_availability_height =:= b)
~help: (gettext M.h_use_availability_height)
(gettext M.o_use_availability_height)
!!GO.use_availability_height
in
let use_relative_availability = bool
~f: (fun b -> GO.use_relative_availability =:= b)
~help: (gettext M.h_use_relative_availability)
(gettext M.o_use_relative_availability)
!!GO.use_relative_availability
in
let chunk_width = string
~f: (safe_int_of_string GO.chunk_width)
~help: (gettext M.h_chunk_width)
(gettext M.o_chunk_width)
(string_of_int !!GO.chunk_width)
in
let misc_options = Section
((gettext M.o_misc),
[
files_auto_expand_depth ;
use_size_suffixes ;
use_availability_height ;
use_relative_availability ;
chunk_width ;
]
)
in
[ server_options ; colors_options ; layout_options ; columns_options ; misc_options ]
let create_string_option ?help label ref = string ?help ~f: (fun s -> ref := s) label !ref
let create_file_option ?help label ref = filename ?help ~f: (fun s -> ref := s) label !ref
let create_bool_option ?help label ref = bool ?help ~f: (fun s -> ref := string_of_bool s) label (bool_of_string !ref)
let add_option_value option value =
try
let o = Hashtbl.find options_values option in
o.option_value := !value;
o.option_old_value <- !value;
with _ ->
Hashtbl.add options_values option {
option_value = value;
option_old_value = !value;
}
let create_sections_params sections =
List.map (fun (name, options) ->
Section (name,
List.fold_left (fun list (message, optype, option) ->
try
(match optype with
| GuiTypes.StringEntry ->
create_string_option message
(Hashtbl.find options_values option).option_value
| GuiTypes.BoolEntry ->
create_bool_option message
(Hashtbl.find options_values option).option_value
| GuiTypes.FileEntry ->
create_file_option message
(Hashtbl.find options_values option).option_value
) :: list
with Not_found ->
list
) [] !options)
) sections
let update_toolbars_style gui =
gui#tab_downloads#set_tb_style !!GO.toolbars_style;
gui#tab_servers#set_tb_style !!GO.toolbars_style ;
gui#tab_friends#set_tb_style !!GO.toolbars_style ;
gui#tab_queries#set_tb_style !!GO.toolbars_style ;
gui#tab_uploads#set_tb_style !!GO.toolbars_style
let save_options gui =
let module P = GuiProto in
try
let list = ref [] in
Hashtbl.iter (fun option o ->
if !(o.option_value) <> o.option_old_value then begin
o.option_old_value <- !(o.option_value);
list := (option, o.option_old_value) :: !list;
end)
options_values;
Gui_com.send (P.SaveOptions_query !list)
( List.map
( fun ( name , r ) - > ( name , ! r ) )
Gui_options.client_options_assocs
)
) ;
(List.map
(fun (name, r) -> (name, !r))
Gui_options.client_options_assocs
)
);
*)
with _ ->
lprintf "ERROR SAVING OPTIONS (but port/password/host correctly set for GUI)"; lprint_newline ()
let edit_options gui =
try
lprintf "edit_options\n";
let gui_params = create_gui_params () in
let client_params = create_sections_params !client_sections in
let plugins_params = create_sections_params
(List.sort (fun (n1,_) (n2,_) ->
compare (String.lowercase n1) (String.lowercase n2)
) !plugins_sections) in
let structure = [
Section_list ((gettext M.o_gui), gui_params) ;
Section_list ((gettext M.o_client), client_params) ;
Section_list ("Plugins", plugins_params) ;
]
in
match Configwin.get ~height: 600 ~width: 400
(gettext M.o_options) structure
with
Return_ok | Return_apply ->
Gui_misc.save_gui_options gui;
save_options gui ;
gui#tab_servers#box_servers#set_columns
GO.servers_columns;
gui#tab_downloads#box_downloads#set_columns
GO.downloads_columns;
gui#tab_downloads#box_downloaded#set_columns
GO.downloaded_columns;
gui#tab_friends#box_friends#set_columns
GO.friends_columns;
gui#tab_downloads#box_locations#set_columns
GO.file_locations_columns;
gui#tab_friends#box_files#box_results#set_columns
GO.results_columns;
gui#tab_uploads#upstats_box#set_columns
GO.shared_files_up_columns;
update_toolbars_style gui
| Return_cancel -> ()
with e ->
lprintf "Exception %s in edit_options" (Printexc2.to_string e);
lprint_newline ();
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/gtk/gui/gui_config.ml | ocaml | * Configuration panel.
* Server options
* Colors
* Columns options | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf2
open Gettext
open Gui_global
module GO = Gui_options
open Configwin
module M = Gui_messages
let (!!) = Options.(!!)
let (=:=) = Options.(=:=)
let safe_int_of_string option s =
try option =:= int_of_string s
with _ -> ()
let create_gui_params () =
let gui_port = string
~help: (gettext M.h_gui_port)
~f: (fun s -> safe_int_of_string GO.port s)
(gettext M.o_gui_port) (string_of_int !!GO.port)
in
let gui_hostname = string
~help: (gettext M.h_hostname)
~f: (fun s -> GO.hostname =:= s)
(gettext M.o_hostname) !!GO.hostname
in
let gui_login = string
~help: "Your login"
~f: (fun s -> GO.login =:= s)
"Login:" !!GO.login
in
let gui_password = password
~help: (gettext M.h_gui_password)
~f: (fun s -> GO.password =:= s)
(gettext M.o_password) !!GO.password
in
let server_options = Section
((gettext M.o_gui_server),
[
gui_port ; gui_hostname ; gui_login ; gui_password ;
]
)
in
let color_default = color
~help: (gettext M.h_col_default)
~f: (fun s -> GO.color_default =:= s)
(gettext M.o_col_default) !!GO.color_default
in
let color_downloaded = color
~help: (gettext M.h_col_downloaded)
~f: (fun s -> GO.color_downloaded =:= s)
(gettext M.o_col_downloaded) !!GO.color_downloaded
in
let color_downloading = color
~help: (gettext M.h_col_downloading)
~f: (fun s -> GO.color_downloading =:= s)
(gettext M.o_col_downloading) !!GO.color_downloading
in
let color_available = color
~help: (gettext M.h_col_avail)
~f: (fun s -> GO.color_available =:= s)
(gettext M.o_col_avail) !!GO.color_available
in
let color_not_available = color
~help: (gettext M.h_col_not_avail)
~f: (fun s -> GO.color_not_available =:= s)
(gettext M.o_col_not_avail) !!GO.color_not_available
in
let color_connected = color
~help: (gettext M.h_col_connected)
~f: (fun s -> GO.color_connected =:= s)
(gettext M.o_col_connected) !!GO.color_connected
in
let color_not_connected = color
~help: (gettext M.h_col_not_connected)
~f: (fun s -> GO.color_not_connected =:= s)
(gettext M.o_col_not_connected) !!GO.color_not_connected
in
let color_connecting = color
~help: M.h_col_connecting
~f: (fun s -> GO.color_connecting =:= s)
(gettext M.o_col_connecting) !!GO.color_connecting
in
let color_files_listed = color
~help: (M.h_col_files_listed)
~f: (fun s -> GO.color_files_listed =:= s)
(gettext M.o_col_files_listed) !!GO.color_files_listed
in
let colors_options = Section
((gettext M.o_colors),
[
color_default ; color_downloaded ;
color_downloading ; color_available ;
color_not_available ;
color_connected ; color_not_connected ;
color_connecting ; color_files_listed ;
]
)
in
* Layout options
let tb_style = combo
~expand:false
~help: (gettext M.h_toolbars_style)
~f:(fun s -> GO.toolbars_style =:= GO.string_to_tbstyle s)
~new_allowed:false ~blank_allowed:false
(gettext M.o_toolbars_style)
(List.map fst GO.tb_styles)
(GO.tbstyle_to_string !!GO.toolbars_style)
in
let tb_icons = bool
~help: "Mini icons in toolbars:"
~f: (fun b -> GO.mini_toolbars =:= b)
"Mini icons in toolbars:" !!GO.mini_toolbars
in
let tab_pos = combo
~expand:false
~help: "Position of main tab"
~f:(fun s -> GO.notebook_tab =:= GO.TabPosition.string_to_pos s)
~new_allowed:false ~blank_allowed:false
"Tab Position:"
GO.TabPosition.values
(GO.TabPosition.pos_to_string !!GO.notebook_tab)
in
let layout_options = Section
((gettext M.o_layout),
[
tb_style ;
tb_icons;
tab_pos;
]
)
in
let sel l f_string () =
let menu = GMenu.menu () in
let choice = ref None in
let entries = List.map
(fun ele ->
`I (f_string ele, fun () -> choice := Some ele))
l
in
GToolbox.build_menu menu ~entries;
ignore (menu#connect#deactivate GMain.Main.quit);
menu#popup 0 0;
GMain.Main.main ();
match !choice with
None -> []
| Some c -> [c]
in
let servers_cols = list
~help: (gettext M.h_servers_columns)
~f: (fun l -> GO.servers_columns =:= l)
~add: (sel
(List.map fst Gui_columns.server_column_strings)
Gui_columns.Server.string_of_column)
""
(fun c -> [Gui_columns.Server.string_of_column c])
!!GO.servers_columns
in
let dls_cols = list
~help: (gettext M.h_downloads_columns)
~f: (fun l -> GO.downloads_columns =:= l)
~add: (sel
(List.map fst Gui_columns.file_column_strings)
Gui_columns.File.string_of_column)
""
(fun c -> [Gui_columns.File.string_of_column c])
!!GO.downloads_columns
in
let dled_cols = list
~help: (gettext M.h_downloaded_columns)
~f: (fun l -> GO.downloaded_columns =:= l)
~add: (sel
(List.map fst Gui_columns.file_column_strings)
Gui_columns.File.string_of_column)
""
(fun c -> [Gui_columns.File.string_of_column c])
!!GO.downloaded_columns
in
let friends_cols = list
~help: (gettext M.h_friends_columns)
~f: (fun l -> GO.friends_columns =:= l)
~add: (sel
(List.map fst Gui_columns.client_column_strings)
Gui_columns.Client.string_of_column)
""
(fun c -> [Gui_columns.Client.string_of_column c])
!!GO.friends_columns
in
let file_locs_cols = list
~help: (gettext M.h_file_locations_columns)
~f: (fun l -> GO.file_locations_columns =:= l)
~add: (sel
(List.map fst Gui_columns.client_column_strings)
Gui_columns.Client.string_of_column)
""
(fun c -> [Gui_columns.Client.string_of_column c])
!!GO.file_locations_columns
in
let results_cols = list
~help: (gettext M.h_results_columns)
~f: (fun l -> GO.results_columns =:= l)
~add: (sel
(List.map fst Gui_columns.result_column_strings)
Gui_columns.Result.string_of_column)
""
(fun c -> [Gui_columns.Result.string_of_column c])
!!GO.results_columns
in
let shared_cols = list
~help: (M.h_shared_files_up_columns)
~f: (fun l -> GO.shared_files_up_columns =:= l)
~add: (sel
(List.map fst Gui_columns.shared_file_up_column_strings)
Gui_columns.Shared_files_up.string_of_column)
""
(fun c -> [Gui_columns.Shared_files_up.string_of_column c])
!!GO.shared_files_up_columns
in
let columns_options = Section_list
((gettext M.o_columns),
[
Section ((gettext M.o_servers_columns) ,[servers_cols]) ;
Section ((gettext M.o_downloads_columns) ,[dls_cols]);
Section ((gettext M.o_downloaded_columns) ,[dled_cols]);
Section ((gettext M.o_results_columns) ,[results_cols]);
Section ((gettext M.o_friends_columns) ,[friends_cols]) ;
Section ((gettext M.o_file_locations_columns) ,[file_locs_cols]) ;
Section ((gettext M.o_shared_files_up_colums) ,[shared_cols]) ;
]
)
in
let files_auto_expand_depth = string
~f: (safe_int_of_string GO.files_auto_expand_depth)
~help: (M.h_files_auto_expand_depth)
(gettext M.o_files_auto_expand_depth)
(string_of_int !!GO.files_auto_expand_depth)
in
let use_size_suffixes = bool
~f: (fun b -> GO.use_size_suffixes =:= b)
~help: (M.h_use_size_suffixes)
(gettext M.o_use_size_suffixes)
!!GO.use_size_suffixes
in
let use_availability_height = bool
~f: (fun b -> GO.use_availability_height =:= b)
~help: (gettext M.h_use_availability_height)
(gettext M.o_use_availability_height)
!!GO.use_availability_height
in
let use_relative_availability = bool
~f: (fun b -> GO.use_relative_availability =:= b)
~help: (gettext M.h_use_relative_availability)
(gettext M.o_use_relative_availability)
!!GO.use_relative_availability
in
let chunk_width = string
~f: (safe_int_of_string GO.chunk_width)
~help: (gettext M.h_chunk_width)
(gettext M.o_chunk_width)
(string_of_int !!GO.chunk_width)
in
let misc_options = Section
((gettext M.o_misc),
[
files_auto_expand_depth ;
use_size_suffixes ;
use_availability_height ;
use_relative_availability ;
chunk_width ;
]
)
in
[ server_options ; colors_options ; layout_options ; columns_options ; misc_options ]
let create_string_option ?help label ref = string ?help ~f: (fun s -> ref := s) label !ref
let create_file_option ?help label ref = filename ?help ~f: (fun s -> ref := s) label !ref
let create_bool_option ?help label ref = bool ?help ~f: (fun s -> ref := string_of_bool s) label (bool_of_string !ref)
let add_option_value option value =
try
let o = Hashtbl.find options_values option in
o.option_value := !value;
o.option_old_value <- !value;
with _ ->
Hashtbl.add options_values option {
option_value = value;
option_old_value = !value;
}
let create_sections_params sections =
List.map (fun (name, options) ->
Section (name,
List.fold_left (fun list (message, optype, option) ->
try
(match optype with
| GuiTypes.StringEntry ->
create_string_option message
(Hashtbl.find options_values option).option_value
| GuiTypes.BoolEntry ->
create_bool_option message
(Hashtbl.find options_values option).option_value
| GuiTypes.FileEntry ->
create_file_option message
(Hashtbl.find options_values option).option_value
) :: list
with Not_found ->
list
) [] !options)
) sections
let update_toolbars_style gui =
gui#tab_downloads#set_tb_style !!GO.toolbars_style;
gui#tab_servers#set_tb_style !!GO.toolbars_style ;
gui#tab_friends#set_tb_style !!GO.toolbars_style ;
gui#tab_queries#set_tb_style !!GO.toolbars_style ;
gui#tab_uploads#set_tb_style !!GO.toolbars_style
let save_options gui =
let module P = GuiProto in
try
let list = ref [] in
Hashtbl.iter (fun option o ->
if !(o.option_value) <> o.option_old_value then begin
o.option_old_value <- !(o.option_value);
list := (option, o.option_old_value) :: !list;
end)
options_values;
Gui_com.send (P.SaveOptions_query !list)
( List.map
( fun ( name , r ) - > ( name , ! r ) )
Gui_options.client_options_assocs
)
) ;
(List.map
(fun (name, r) -> (name, !r))
Gui_options.client_options_assocs
)
);
*)
with _ ->
lprintf "ERROR SAVING OPTIONS (but port/password/host correctly set for GUI)"; lprint_newline ()
let edit_options gui =
try
lprintf "edit_options\n";
let gui_params = create_gui_params () in
let client_params = create_sections_params !client_sections in
let plugins_params = create_sections_params
(List.sort (fun (n1,_) (n2,_) ->
compare (String.lowercase n1) (String.lowercase n2)
) !plugins_sections) in
let structure = [
Section_list ((gettext M.o_gui), gui_params) ;
Section_list ((gettext M.o_client), client_params) ;
Section_list ("Plugins", plugins_params) ;
]
in
match Configwin.get ~height: 600 ~width: 400
(gettext M.o_options) structure
with
Return_ok | Return_apply ->
Gui_misc.save_gui_options gui;
save_options gui ;
gui#tab_servers#box_servers#set_columns
GO.servers_columns;
gui#tab_downloads#box_downloads#set_columns
GO.downloads_columns;
gui#tab_downloads#box_downloaded#set_columns
GO.downloaded_columns;
gui#tab_friends#box_friends#set_columns
GO.friends_columns;
gui#tab_downloads#box_locations#set_columns
GO.file_locations_columns;
gui#tab_friends#box_files#box_results#set_columns
GO.results_columns;
gui#tab_uploads#upstats_box#set_columns
GO.shared_files_up_columns;
update_toolbars_style gui
| Return_cancel -> ()
with e ->
lprintf "Exception %s in edit_options" (Printexc2.to_string e);
lprint_newline ();
|
86d59ce9a1260b848265519b2cd907312b11e8d834ce853716b401567c04f768 | IBM/probzelus | run.ml |
* Copyright 2018 - 2020 IBM Corporation
*
* Licensed under the Apache License , Version 2.0 ( the " License " ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* -2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an " AS IS " BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* Copyright 2018-2020 IBM Corporation
*
* 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 Benchlib
module M = struct
let name = "Gaussian Tree"
let algo = "PF"
type input = (float * float) * (float * float)
type output = (float * float) Probzelus.Distribution.t
let read_input () = Scanf.scanf ("%f, %f, %f, %f\n") (fun a b c d -> ((a, b), (c, d)))
let main = Gtree_particles.main
let string_of_output out =
let a_d, b_d = Probzelus.Distribution.split out in
Format.sprintf "%f, %f\n" (Probzelus.Distribution.mean_float a_d) (Probzelus.Distribution.mean_float b_d)
end
module H = Harness.Make(M)
let () =
H.run ()
| null | https://raw.githubusercontent.com/IBM/probzelus/c56573201b43780b9c103e5616bb193ababa3399/benchmarks/gtree/particles/run.ml | ocaml |
* Copyright 2018 - 2020 IBM Corporation
*
* Licensed under the Apache License , Version 2.0 ( the " License " ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* -2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an " AS IS " BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* Copyright 2018-2020 IBM Corporation
*
* 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 Benchlib
module M = struct
let name = "Gaussian Tree"
let algo = "PF"
type input = (float * float) * (float * float)
type output = (float * float) Probzelus.Distribution.t
let read_input () = Scanf.scanf ("%f, %f, %f, %f\n") (fun a b c d -> ((a, b), (c, d)))
let main = Gtree_particles.main
let string_of_output out =
let a_d, b_d = Probzelus.Distribution.split out in
Format.sprintf "%f, %f\n" (Probzelus.Distribution.mean_float a_d) (Probzelus.Distribution.mean_float b_d)
end
module H = Harness.Make(M)
let () =
H.run ()
| |
340b7557463e0588701a0576f797efadf62396fd515e71b192d0b1c561b57d15 | 3b/cl-opengl | clip.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
clip.lisp --- Lisp version of clip.c ( Red Book examples )
;;;
;;; Original C version contains the following copyright notice:
Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc.
;;; ALL RIGHTS RESERVED
;;; This program demonstrates arbitrary clipping planes.
(in-package #:cl-glut-examples)
(defclass clip-window (glut:window)
()
(:default-initargs :pos-x 100 :pos-y 100 :width 500 :height 500
:mode '(:single :rgb) :title "clip.lisp"))
(defmethod glut:display-window :before ((w clip-window))
(gl:clear-color 0 0 0 0)
(gl:shade-model :flat))
(defmethod glut:display ((w clip-window))
(gl:clear :color-buffer)
(gl:color 1 1 1)
(gl:with-pushed-matrix
(gl:translate 0 0 -5)
clip lower half -- y < 0
(gl:clip-plane :clip-plane0 '(0 1 0 0))
(gl:enable :clip-plane0)
clip left half -- x < 0
(gl:clip-plane :clip-plane1 '(1 0 0 0))
(gl:enable :clip-plane1)
;; sphere
(gl:rotate 90 1 0 0)
(glut:wire-sphere 1 20 16))
(gl:flush))
(defmethod glut:reshape ((w clip-window) width height)
(gl:viewport 0 0 width height)
(gl:matrix-mode :projection)
(gl:load-identity)
(glu:perspective 60 (/ width height) 1 20)
(gl:matrix-mode :modelview))
(defmethod glut:keyboard ((w clip-window) key x y)
(declare (ignore x y))
(when (eql key #\Esc)
(glut:destroy-current-window)))
(defun rb-clip ()
(glut:display-window (make-instance 'clip-window)))
| null | https://raw.githubusercontent.com/3b/cl-opengl/e2d83e0977b7e7ac3f3d348d8ccc7ccd04e74d59/examples/redbook/clip.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
Original C version contains the following copyright notice:
ALL RIGHTS RESERVED
This program demonstrates arbitrary clipping planes.
sphere | clip.lisp --- Lisp version of clip.c ( Red Book examples )
Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc.
(in-package #:cl-glut-examples)
(defclass clip-window (glut:window)
()
(:default-initargs :pos-x 100 :pos-y 100 :width 500 :height 500
:mode '(:single :rgb) :title "clip.lisp"))
(defmethod glut:display-window :before ((w clip-window))
(gl:clear-color 0 0 0 0)
(gl:shade-model :flat))
(defmethod glut:display ((w clip-window))
(gl:clear :color-buffer)
(gl:color 1 1 1)
(gl:with-pushed-matrix
(gl:translate 0 0 -5)
clip lower half -- y < 0
(gl:clip-plane :clip-plane0 '(0 1 0 0))
(gl:enable :clip-plane0)
clip left half -- x < 0
(gl:clip-plane :clip-plane1 '(1 0 0 0))
(gl:enable :clip-plane1)
(gl:rotate 90 1 0 0)
(glut:wire-sphere 1 20 16))
(gl:flush))
(defmethod glut:reshape ((w clip-window) width height)
(gl:viewport 0 0 width height)
(gl:matrix-mode :projection)
(gl:load-identity)
(glu:perspective 60 (/ width height) 1 20)
(gl:matrix-mode :modelview))
(defmethod glut:keyboard ((w clip-window) key x y)
(declare (ignore x y))
(when (eql key #\Esc)
(glut:destroy-current-window)))
(defun rb-clip ()
(glut:display-window (make-instance 'clip-window)))
|
028b596499816cc2fac59fdac7a4ad6f9d43221b08780487c77cce464dccf0e6 | phantomics/april | loader.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Coding : utf-8 ; Package : AprilDemo . Ncurses -*-
;; loader.lisp
(asdf:load-system 'april-demo.ncurses)
(april-demo.ncurses::main)
(cl-user::quit)
| null | https://raw.githubusercontent.com/phantomics/april/395b37db943133272da30411af324e371a7fccce/demos/ncurses/loader.lisp | lisp | Syntax : ANSI - Common - Lisp ; Coding : utf-8 ; Package : AprilDemo . Ncurses -*-
loader.lisp |
(asdf:load-system 'april-demo.ncurses)
(april-demo.ncurses::main)
(cl-user::quit)
|
94a022e2b35f57b2e819d4bdd8e04ed84148c3868831c3a8d7b5d386a2c6b69d | josefs/Gradualizer | filename.specs.erl | -module(filename).
-type deep_list() :: lists:deep_list(char() | atom()).
-spec basename(binary()) -> binary();
(string() | atom() | deep_list()) -> string().
-spec dirname(binary()) -> binary();
(string() | atom() | deep_list()) -> string().
-spec rootname(binary()) -> binary();
(string() | atom() | deep_list()) -> string().
-type name() :: string() | atom() | deep_list().
-spec join([name()]) -> string();
([binary()]) -> binary().
-spec join(name(), name()) -> string();
(binary(), name()) -> binary();
(name(), binary()) -> binary();
(binary(), binary()) -> binary().
| null | https://raw.githubusercontent.com/josefs/Gradualizer/ba4476fd4ef8e715e49ddf038d5f9f08901a25da/priv/prelude/filename.specs.erl | erlang | -module(filename).
-type deep_list() :: lists:deep_list(char() | atom()).
-spec basename(binary()) -> binary();
(string() | atom() | deep_list()) -> string().
-spec dirname(binary()) -> binary();
(string() | atom() | deep_list()) -> string().
-spec rootname(binary()) -> binary();
(string() | atom() | deep_list()) -> string().
-type name() :: string() | atom() | deep_list().
-spec join([name()]) -> string();
([binary()]) -> binary().
-spec join(name(), name()) -> string();
(binary(), name()) -> binary();
(name(), binary()) -> binary();
(binary(), binary()) -> binary().
| |
6e90e1e5263e21c4b3fcfd41e9431f5d32e728f6416f439ba68b647711993cf6 | rabbitmq/rabbitmq-erlang-client | amqp_channel_sup_sup.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
@private
-module(amqp_channel_sup_sup).
-include("amqp_client.hrl").
-behaviour(supervisor2).
-export([start_link/3, start_channel_sup/4]).
-export([init/1]).
%%---------------------------------------------------------------------------
Interface
%%---------------------------------------------------------------------------
start_link(Type, Connection, ConnName) ->
supervisor2:start_link(?MODULE, [Type, Connection, ConnName]).
start_channel_sup(Sup, InfraArgs, ChannelNumber, Consumer) ->
supervisor2:start_child(Sup, [InfraArgs, ChannelNumber, Consumer]).
%%---------------------------------------------------------------------------
supervisor2 callbacks
%%---------------------------------------------------------------------------
init([Type, Connection, ConnName]) ->
{ok, {{simple_one_for_one, 0, 1},
[{channel_sup,
{amqp_channel_sup, start_link, [Type, Connection, ConnName]},
temporary, infinity, supervisor, [amqp_channel_sup]}]}}.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-erlang-client/2022e01c515d93ed1883e9e9e987be2e58fe15c9/src/amqp_channel_sup_sup.erl | erlang |
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--------------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
@private
-module(amqp_channel_sup_sup).
-include("amqp_client.hrl").
-behaviour(supervisor2).
-export([start_link/3, start_channel_sup/4]).
-export([init/1]).
Interface
start_link(Type, Connection, ConnName) ->
supervisor2:start_link(?MODULE, [Type, Connection, ConnName]).
start_channel_sup(Sup, InfraArgs, ChannelNumber, Consumer) ->
supervisor2:start_child(Sup, [InfraArgs, ChannelNumber, Consumer]).
supervisor2 callbacks
init([Type, Connection, ConnName]) ->
{ok, {{simple_one_for_one, 0, 1},
[{channel_sup,
{amqp_channel_sup, start_link, [Type, Connection, ConnName]},
temporary, infinity, supervisor, [amqp_channel_sup]}]}}.
|
ab89da2991b193634a8f70fdd4c749255d0c242a31f920d7ced34d053f2baa16 | dannypsnl/k | info.rkt | #lang info
(define collection 'multi)
(define deps '("base" "k-core"))
(define build-deps '("rackunit-lib"))
(define pkg-desc "library of k")
(define pkg-authors '(dannypsnl cybai))
| null | https://raw.githubusercontent.com/dannypsnl/k/2b5f5066806a5bbd0733b781a2ed5fce6956a4f5/k-lib/info.rkt | racket | #lang info
(define collection 'multi)
(define deps '("base" "k-core"))
(define build-deps '("rackunit-lib"))
(define pkg-desc "library of k")
(define pkg-authors '(dannypsnl cybai))
| |
15a08cb12709c02b57538eb05690654f83576e58bfd904c0f091cb2085235637 | haskell/cabal | Build.hs | # LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Setup.Build
Copyright : 2003 - 2004
2007
-- License : BSD3
--
-- Maintainer :
-- Portability : portable
--
-- Definition of the build command-line options.
-- See: @Distribution.Simple.Setup@
module Distribution.Simple.Setup.Build (
BuildFlags(..), emptyBuildFlags, defaultBuildFlags, buildCommand,
DumpBuildInfo(..),
buildOptions,
) where
import Prelude ()
import Distribution.Compat.Prelude hiding (get)
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import Distribution.Simple.Flag
import Distribution.Simple.Utils
import Distribution.Simple.Program
import Distribution.Verbosity
import Distribution.Types.DumpBuildInfo
import Distribution.Simple.Setup.Common
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------
data BuildFlags = BuildFlags {
buildProgramPaths :: [(String, FilePath)],
buildProgramArgs :: [(String, [String])],
buildDistPref :: Flag FilePath,
buildVerbosity :: Flag Verbosity,
buildNumJobs :: Flag (Maybe Int),
-- TODO: this one should not be here, it's just that the silly
UserHooks stop us from passing extra info in other ways
buildArgs :: [String],
buildCabalFilePath :: Flag FilePath
}
deriving (Read, Show, Generic, Typeable)
defaultBuildFlags :: BuildFlags
defaultBuildFlags = BuildFlags {
buildProgramPaths = mempty,
buildProgramArgs = [],
buildDistPref = mempty,
buildVerbosity = Flag normal,
buildNumJobs = mempty,
buildArgs = [],
buildCabalFilePath = mempty
}
buildCommand :: ProgramDb -> CommandUI BuildFlags
buildCommand progDb = CommandUI
{ commandName = "build"
, commandSynopsis = "Compile all/specific components."
, commandDescription = Just $ \_ -> wrapText $
"Components encompass executables, tests, and benchmarks.\n"
++ "\n"
++ "Affected by configuration options, see `configure`.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " build "
++ " All the components in the package\n"
++ " " ++ pname ++ " build foo "
++ " A component (i.e. lib, exe, test suite)\n\n"
++ programFlagsDescription progDb
--TODO: re-enable once we have support for module/file targets
+ + " " + + pname + + " build . Bar "
-- ++ " A module\n"
+ + " " + + pname + + " build / Bar.hs "
-- ++ " A file\n\n"
-- ++ "If a target is ambiguous it can be qualified with the component "
+ + " name , e.g.\n "
+ + " " + + pname + + " build foo : . "
+ + " " + + pname + + " build : "
, commandUsage = usageAlternatives "build" $
[ "[FLAGS]"
, "COMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBuildFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity
buildVerbosity (\v flags -> flags { buildVerbosity = v })
, optionDistPref
buildDistPref (\d flags -> flags { buildDistPref = d }) showOrParseArgs
]
++ buildOptions progDb showOrParseArgs
}
buildOptions :: ProgramDb -> ShowOrParseArgs
-> [OptionField BuildFlags]
buildOptions progDb showOrParseArgs =
[ optionNumJobs
buildNumJobs (\v flags -> flags { buildNumJobs = v })
]
++ programDbPaths progDb showOrParseArgs
buildProgramPaths (\v flags -> flags { buildProgramPaths = v})
++ programDbOption progDb showOrParseArgs
buildProgramArgs (\v fs -> fs { buildProgramArgs = v })
++ programDbOptions progDb showOrParseArgs
buildProgramArgs (\v flags -> flags { buildProgramArgs = v})
emptyBuildFlags :: BuildFlags
emptyBuildFlags = mempty
instance Monoid BuildFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup BuildFlags where
(<>) = gmappend
| null | https://raw.githubusercontent.com/haskell/cabal/ab24689731e9fb45efa6277f290624622a6c214f/Cabal/src/Distribution/Simple/Setup/Build.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE RankNTypes #
---------------------------------------------------------------------------
|
Module : Distribution.Simple.Setup.Build
License : BSD3
Maintainer :
Portability : portable
Definition of the build command-line options.
See: @Distribution.Simple.Setup@
------------------------------------------------------------
* Build flags
------------------------------------------------------------
TODO: this one should not be here, it's just that the silly
TODO: re-enable once we have support for module/file targets
++ " A module\n"
++ " A file\n\n"
++ "If a target is ambiguous it can be qualified with the component " | # LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
Copyright : 2003 - 2004
2007
module Distribution.Simple.Setup.Build (
BuildFlags(..), emptyBuildFlags, defaultBuildFlags, buildCommand,
DumpBuildInfo(..),
buildOptions,
) where
import Prelude ()
import Distribution.Compat.Prelude hiding (get)
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import Distribution.Simple.Flag
import Distribution.Simple.Utils
import Distribution.Simple.Program
import Distribution.Verbosity
import Distribution.Types.DumpBuildInfo
import Distribution.Simple.Setup.Common
data BuildFlags = BuildFlags {
buildProgramPaths :: [(String, FilePath)],
buildProgramArgs :: [(String, [String])],
buildDistPref :: Flag FilePath,
buildVerbosity :: Flag Verbosity,
buildNumJobs :: Flag (Maybe Int),
UserHooks stop us from passing extra info in other ways
buildArgs :: [String],
buildCabalFilePath :: Flag FilePath
}
deriving (Read, Show, Generic, Typeable)
defaultBuildFlags :: BuildFlags
defaultBuildFlags = BuildFlags {
buildProgramPaths = mempty,
buildProgramArgs = [],
buildDistPref = mempty,
buildVerbosity = Flag normal,
buildNumJobs = mempty,
buildArgs = [],
buildCabalFilePath = mempty
}
buildCommand :: ProgramDb -> CommandUI BuildFlags
buildCommand progDb = CommandUI
{ commandName = "build"
, commandSynopsis = "Compile all/specific components."
, commandDescription = Just $ \_ -> wrapText $
"Components encompass executables, tests, and benchmarks.\n"
++ "\n"
++ "Affected by configuration options, see `configure`.\n"
, commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " build "
++ " All the components in the package\n"
++ " " ++ pname ++ " build foo "
++ " A component (i.e. lib, exe, test suite)\n\n"
++ programFlagsDescription progDb
+ + " " + + pname + + " build . Bar "
+ + " " + + pname + + " build / Bar.hs "
+ + " name , e.g.\n "
+ + " " + + pname + + " build foo : . "
+ + " " + + pname + + " build : "
, commandUsage = usageAlternatives "build" $
[ "[FLAGS]"
, "COMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBuildFlags
, commandOptions = \showOrParseArgs ->
[ optionVerbosity
buildVerbosity (\v flags -> flags { buildVerbosity = v })
, optionDistPref
buildDistPref (\d flags -> flags { buildDistPref = d }) showOrParseArgs
]
++ buildOptions progDb showOrParseArgs
}
buildOptions :: ProgramDb -> ShowOrParseArgs
-> [OptionField BuildFlags]
buildOptions progDb showOrParseArgs =
[ optionNumJobs
buildNumJobs (\v flags -> flags { buildNumJobs = v })
]
++ programDbPaths progDb showOrParseArgs
buildProgramPaths (\v flags -> flags { buildProgramPaths = v})
++ programDbOption progDb showOrParseArgs
buildProgramArgs (\v fs -> fs { buildProgramArgs = v })
++ programDbOptions progDb showOrParseArgs
buildProgramArgs (\v flags -> flags { buildProgramArgs = v})
emptyBuildFlags :: BuildFlags
emptyBuildFlags = mempty
instance Monoid BuildFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup BuildFlags where
(<>) = gmappend
|
574205813008a3ef2327b7ae64caa30bdfbcda4395fec3f8db5b1e20f4e7b6d9 | well-typed/large-records | R050.hs | #if PROFILE_CORESIZE
{-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-}
#endif
#if PROFILE_TIMING
{-# OPTIONS_GHC -ddump-to-file -ddump-timings #-}
#endif
# LANGUAGE OverloadedLabels #
{-# OPTIONS_GHC -fplugin=Data.Record.Anon.Plugin #-}
module Experiment.UpdateOne.Sized.R050 where
import Data.Record.Anon.Simple (Record)
import qualified Data.Record.Anon.Simple as Anon
import Bench.Types
import Common.RowOfSize.Row050
updateOne :: Record ExampleRow -> Record ExampleRow
updateOne = Anon.set #t00 (MkT 0) | null | https://raw.githubusercontent.com/well-typed/large-records/cbeb9e710f297a2afd579b8d475e3734b80a9ccc/large-records-benchmarks/bench/large-anon/Experiment/UpdateOne/Sized/R050.hs | haskell | # OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #
# OPTIONS_GHC -ddump-to-file -ddump-timings #
# OPTIONS_GHC -fplugin=Data.Record.Anon.Plugin # | #if PROFILE_CORESIZE
#endif
#if PROFILE_TIMING
#endif
# LANGUAGE OverloadedLabels #
module Experiment.UpdateOne.Sized.R050 where
import Data.Record.Anon.Simple (Record)
import qualified Data.Record.Anon.Simple as Anon
import Bench.Types
import Common.RowOfSize.Row050
updateOne :: Record ExampleRow -> Record ExampleRow
updateOne = Anon.set #t00 (MkT 0) |
83e572a40fb34da31eeebe6d33292895c9481bf440692abbbd6c2ef1c4b1fa17 | onedata/op-worker | atm_list_store_content_browse_result.erl | %%%-------------------------------------------------------------------
@author
( C ) 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% Record expressing store content browse result specialization for
%%% list store used in automation machinery.
%%% @end
%%%-------------------------------------------------------------------
-module(atm_list_store_content_browse_result).
-author("Bartosz Walkowicz").
-behaviour(atm_store_content_browse_result).
-include("modules/automation/atm_execution.hrl").
%% API
-export([to_json/1]).
-type record() :: #atm_list_store_content_browse_result{}.
-export_type([record/0]).
%%%===================================================================
%%% API
%%%===================================================================
-spec to_json(record()) -> json_utils:json_map().
to_json(#atm_list_store_content_browse_result{
items = Items,
is_last = IsLast
}) ->
#{
<<"items">> => lists:map(
fun atm_store_container_infinite_log_backend:entry_to_json/1,
Items
),
<<"isLast">> => IsLast
}.
| null | https://raw.githubusercontent.com/onedata/op-worker/2db1516da782d8acc6bdd2418a3791819ff19581/src/modules/automation/store/container/list/atm_list_store_content_browse_result.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
Record expressing store content browse result specialization for
list store used in automation machinery.
@end
-------------------------------------------------------------------
API
===================================================================
API
=================================================================== | @author
( C ) 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(atm_list_store_content_browse_result).
-author("Bartosz Walkowicz").
-behaviour(atm_store_content_browse_result).
-include("modules/automation/atm_execution.hrl").
-export([to_json/1]).
-type record() :: #atm_list_store_content_browse_result{}.
-export_type([record/0]).
-spec to_json(record()) -> json_utils:json_map().
to_json(#atm_list_store_content_browse_result{
items = Items,
is_last = IsLast
}) ->
#{
<<"items">> => lists:map(
fun atm_store_container_infinite_log_backend:entry_to_json/1,
Items
),
<<"isLast">> => IsLast
}.
|
a6c0e660c7db1378ed37453b52ba26a78245e1cdc61bec38253c8dffc48e4615 | berke/aurochs | html.ml | (* Html *)
Copyright ( C)2000 - 2006
Released under the GNU Lesser General Public License version 2.1
open Entity;;
let sf = Printf.sprintf;;
type html_document =
{ head: html_head;
body: html_element * html_properties }
and html_head =
{ title: string;
author: string;
charset: html_charset;
style_sheet: string option }
and html_properties = (string * string) list
and html_charset = ASCII | ISO_8859_1 | UTF8
and html_method = GET | POST
and html_element =
| I_button of string * string (* name, value *)
| I_hidden of string * string
name , value , size , maxlength
name , value , size , maxlength
| I_text_area of string * int * int * string
| I_checkbox of string * string * bool
| I_radio of string * string * bool
| I_select of string * bool * int * (string * string * bool) list
| I_reset of string
| Img of string * int * int * string
| Form of html_method * string * html_element
| Anchor of url * html_element
| Seq of html_element list
| UL of html_element list
| P of html_element
| H of int * html_element
| T of string (* ISO-8859-1 text *)
| BT of string (* ISO-8859-1 text *)
| IT of string (* ISO-8859-1 text *)
| TT of string (* ISO-8859-1 text *)
| Pre of string (* pre-formatted text *)
| HR
| Table of html_table_row list
| Nop
| BR
| Div of string * html_element list
| Span of string * html_element
| Script of string * string
| With of html_properties * html_element
and html_table_row = html_table_cell list
and html_table_cell =
| C_contents of html_element
| C_halign of html_table_cell_halign * html_table_cell
| C_valign of html_table_cell_valign * html_table_cell
| C_rowspan of int * html_table_cell
| C_colspan of int * html_table_cell
| C_header of html_table_cell
| C_color of Rgb.t * html_table_cell
| C_width of int * html_table_cell
and html_table_cell_halign =
| Cha_left
| Cha_center
| Cha_right
| Cha_justify
| Cha_char of char
and html_table_cell_valign =
| Cva_top
| Cva_middle
| Cva_bottom
| Cva_baseline
and url = string
;;
let default_head =
{ title = "Untitled";
author = "Ara HTTPD";
charset = ISO_8859_1;
style_sheet = None }
;;
let string_of_charset = function
| ASCII -> "ascii"
| ISO_8859_1 -> "iso-8859-1"
| UTF8 -> "utf-8"
;;
let output (f : string -> unit) (fc : char -> unit) x =
let indent = ref 0 in
let put_indent () =
for i = 1 to !indent do
f " "
done
in
let text_avec_table t y =
for i = 0 to String.length y - 1 do
f t.(Char.code y.[i])
done
in
let text = text_avec_table character_table in
let gui = text in
let ife f = function
| Some x -> ignore (f x)
| None -> () in
let launch_tag x =
put_indent ();
f ("<"^x)
and end_tag_linear x = f ("</"^x^">")
in
and flush_tag_without_nl ( ) = f " > " ;
and x = f ( " < /"^x^ " > " )
and launch_linear_tag x = f ( " < " ^x )
and end_tag_without_nl x = f ("</"^x^">")
and launch_linear_tag x = f ("<"^x)*)
let spaces = ref true in
let flush_tag () = if !spaces then begin f ">\n"; incr indent end else f ">"
and flush_linear_tag () = if !spaces then f ">\n" else f ">"
and end_tag x =
if !spaces then
begin
decr indent;
put_indent ();
f ("</"^x^">\n")
end
else
begin
f ("</"^x^">")
end
in
let flush_tag_without_nl () = f ">"
and launch_linear_tag x = f ("<"^x)
in
let put_properties l =
List.iter
begin fun (k,v) ->
f " ";
f k;
f "=\"";
gui v;
f "\""
end
l
in
let text_or_password ?(properties=[]) kind n v s m =
launch_tag "INPUT";
f " TYPE=";
f kind;
f " NAME=\"";
gui n;
f "\" VALUE=\"";
gui v;
f "\"";
begin
match s with
| Some(s) -> f (" SIZE="^(string_of_int s))
| None -> ();
end;
begin
match m with
| Some(m) -> f (" MAXLENGTH="^(string_of_int m))
| None -> ();
end;
put_properties properties;
flush_linear_tag ()
in
let start_tag ?(properties=[]) x =
launch_tag x;
put_properties properties;
flush_tag ()
(*and start_tag_lineaire x =
launch_tag x;
flush_linear_tag ()*)
and start_tag_without_nl x =
launch_tag x;
flush_tag_without_nl ()
in
let linear_tag ?(properties=[]) x =
launch_tag x;
put_properties properties;
flush_linear_tag ()
in
let rec cellule c i j =
let rec loop he ha va rs cs rgb w c =
match c with
| C_header (c) -> loop true ha va rs cs rgb w c
| C_halign (ha,c) -> loop he (Some ha) va rs cs rgb w c
| C_valign (va,c) -> loop he ha (Some va) rs cs rgb w c
| C_rowspan (rs,c) -> loop he ha va (Some rs) cs rgb w c
| C_colspan (cs,c) -> loop he ha va rs (Some cs) rgb w c
| C_color (rgb,c) -> loop he ha va rs cs (Some rgb) w c
| C_width (w,c) -> loop he ha va rs cs rgb (Some w) c
| C_contents e ->
launch_tag (if he then "TH" else "TD");
begin
let coefficient_parity_row = -2
and coefficient_parity_column = -1
and coefficient_head = -4
and shift = 11
and coefficient_total = 12
in
match rgb with
Some(rgb) ->
f (Printf.sprintf " BGCOLOR=\"%s\""
(Rgb.to_string
(let alpha =
(float_of_int
(((if he then 0 else coefficient_head)
+ coefficient_parity_row * (i mod 2)
+ coefficient_parity_column * (j mod 2)) + shift)) /.
(float_of_int coefficient_total)
in
Rgb.mix alpha Rgb.white rgb)));
| _ -> ()
end;
ife
(fun ha ->
f " ALIGN=";
match ha with
| Cha_left -> f "LEFT"
| Cha_center -> f "CENTER"
| Cha_right -> f "RIGHT"
| Cha_justify -> f "JUSTIFY"
| Cha_char c -> f "\""; gui (String.make 1 c); f "\"")
ha;
ife
(fun va ->
f " VALIGN=";
match va with
| Cva_top -> f "TOP"
| Cva_middle -> f "MIDDLE"
| Cva_bottom -> f "BOTTOM"
| Cva_baseline -> f "BASELINE")
va;
ife (fun rs -> f (" ROWSPAN="^(string_of_int rs))) rs;
ife (fun cs -> f (" COLSPAN="^(string_of_int cs))) cs;
ife (fun w -> f (" WIDTH="^(string_of_int w))) w;
flush_tag ();
element e;
end_tag (if he then "TH" else "TD")
in
loop false None None None None None None c
and element ?(properties=[]) y =
match y with
| With(p',y') -> element ~properties:(p' @ properties) y'
| Script(ty,src) ->
launch_tag "SCRIPT";
f " TYPE=\"";
gui ty;
f "\" SRC=\"";
gui src;
f "\"";
put_properties properties;
flush_tag_without_nl ();
end_tag "SCRIPT"
| Anchor(u,e) ->
launch_tag "A";
f " HREF=\"";
gui u;
f "\"";
put_properties properties;
flush_tag_without_nl ();
let spaces' = !spaces in
spaces := false;
element e;
spaces := spaces';
end_tag "A"
| Img(path, width, height, alt) ->
launch_linear_tag "IMG";
f (sf " SRC=%S WIDTH=%d HEIGHT=%d ALT=\"" path width height);
text_avec_table character_table alt;
f "\"";
put_properties properties;
flush_tag_without_nl ()
| Form(m,u,e) ->
launch_tag "FORM";
f (" METHOD="^(match m with POST -> "POST" | GET -> "GET")^" ACTION=\"");
f u;
f "\" ENCTYPE=\"application/x-www-form-urlencoded\"";
put_properties properties;
flush_tag ();
element e;
end_tag "FORM";
| Div(c, z) ->
launch_tag "DIV";
f (sf " CLASS=%S" c);
put_properties properties;
flush_tag ();
List.iter (fun t -> element t) z;
end_tag "DIV"
| Span(c, z) ->
launch_linear_tag "SPAN";
f (sf " CLASS=%S" c);
put_properties properties;
flush_tag_without_nl ();
element z;
end_tag_linear "SPAN"
| Seq z -> List.iter (fun t -> element t) z
| UL l ->
start_tag ~properties "UL";
List.iter (fun t ->
start_tag ~properties "LI";
element t;
end_tag "LI") l;
end_tag "UL"
| H(i, z) ->
start_tag ~properties ("H"^(string_of_int i));
element z;
end_tag ("H"^(string_of_int i))
| T z ->
if !spaces then put_indent ();
text_avec_table character_table_nl_to_br z;
if !spaces then f "\n"
| BT z -> start_tag ~properties "B"; text z; end_tag "B"
| TT z -> start_tag ~properties "TT"; text z; end_tag "TT"
| IT z -> start_tag ~properties "I"; text z; end_tag "I"
| Pre z ->
start_tag_without_nl "PRE"; text z;
end_tag_linear "PRE"
| HR -> linear_tag ~properties "HR"
| BR -> linear_tag ~properties "BR"
start_tag ~properties " P " ; element z ; end_tag " P "
| Nop -> f " "
| I_select (n,m,s,l) ->
launch_tag "SELECT";
f " SIZE="; f (string_of_int s);
f " NAME=\""; gui n; f (if m then "\" MULTIPLE" else "\"");
put_properties properties;
flush_tag ();
List.iter (fun (n,v,s) ->
launch_tag "OPTION";
f " VALUE=\""; gui n; f (if s then "\" SELECTED" else "\"");
flush_linear_tag ();
text v;
f " ") l;
end_tag "SELECT"
| I_reset (v) ->
launch_tag "INPUT";
f " TYPE=RESET VALUE=\""; gui v; f "\"";
put_properties properties;
flush_linear_tag ()
| I_button (n,v) ->
launch_tag "INPUT";
f " TYPE=SUBMIT NAME=\""; gui n; f "\" VALUE=\""; gui v; f "\"";
put_properties properties;
flush_linear_tag ()
| I_hidden (n,v) ->
launch_tag "INPUT";
f " TYPE=HIDDEN NAME=\""; gui n; f "\" VALUE=\""; gui v; f "\"";
put_properties properties;
flush_linear_tag ()
| I_text (n,v,s,m) -> text_or_password ~properties "TEXT" n v s m
| I_password (n,v,s,m) -> text_or_password ~properties "PASSWORD" n v s m
| I_text_area (n,r,c,v) ->
launch_tag "TEXTAREA";
f (Printf.sprintf " ROWS=%d COLS=%d NAME=\"" r c); gui n; f "\"";
put_properties properties;
flush_linear_tag ();
text v;
end_tag_linear "TEXTAREA"
| I_checkbox (n,v,c) ->
launch_tag "INPUT";
f " TYPE=CHECKBOX NAME=\""; gui n; f "\" VALUE=\""; gui v;
f "\"";
if c then f " CHECKED";
put_properties properties;
flush_linear_tag ();
| I_radio (n,v,c) ->
launch_tag "INPUT";
f " TYPE=RADIO NAME=\""; gui n; f "\" VALUE=\""; gui v;
f "\"";
if c then f " CHECKED";
put_properties properties;
flush_linear_tag ();
| Table l ->
start_tag ~properties "TABLE";
let (i,j) = (ref 0, ref 0) in
List.iter
(fun r ->
start_tag ~properties "TR";
j := 0;
List.iter (fun r' -> cellule r' !i !j; incr j) r;
incr i;
end_tag "TR") l;
end_tag "TABLE"
in
begin
f "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
start_tag "HTML";
begin
start_tag "HEAD";
(* title *)
begin
start_tag "TITLE";
put_indent (); text x.head.title;
if !spaces then f "\n";
end_tag "TITLE";
(* css *)
begin
match x.head.style_sheet with
| None -> ()
| Some css ->
launch_tag "LINK";
f " REL=\"stylesheet\" TYPE=\"text/css\" HREF=\"";
text css;
f "\"";
flush_linear_tag ()
end;
(* meta *)
begin
launch_tag "META";
f (sf " HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=%s\""
(string_of_charset x.head.charset));
flush_linear_tag ();
launch_tag "META";
f " NAME=\"Author\" CONTENT=\"";
text x.head.author;
f "\"";
flush_linear_tag ()
end;
end;
end_tag "HEAD";
end;
(* body *)
begin
let (body, properties) = x.body in
start_tag ~properties "BODY";
element body;
end_tag "BODY";
end;
end_tag "HTML";
end
;;
let rec map_text f = function
| Form(a,b,e) -> Form(a,b,map_text f e)
| Seq l -> Seq(List.map (map_text f) l)
| UL l -> UL(List.map (map_text f) l)
| P e -> P(map_text f e)
| H(x,e) -> H(x,map_text f e)
| T t -> f (fun x -> T x) t
| BT t -> f (fun x -> BT x) t
| IT t -> f (fun x -> BT x) t
| TT t -> f (fun x -> BT x) t
| Div(c,l) -> Div(c,List.map (map_text f) l)
| Span(c,e) -> Span(c,map_text f e)
| Table(l) -> Table(List.map (List.map (map_cell f)) l)
| x -> x
and map_cell f = function
| C_contents(e) -> C_contents(map_text f e)
| C_halign(h,c) -> C_halign(h,map_cell f c)
| C_valign(v,c) -> C_valign(v,map_cell f c)
| C_rowspan(x,c) -> C_rowspan(x,map_cell f c)
| C_colspan(x,c) -> C_colspan(x,map_cell f c)
| C_header(c) -> C_header(map_cell f c)
| C_color(x,c) -> C_color(x,map_cell f c)
| C_width(x,c) -> C_width(x,map_cell f c)
;;
let output_to_channel oc = output (output_string oc) (output_char oc);;
let output_to_buffer b x = output (Buffer.add_string b) (Buffer.add_char b) x;;
| null | https://raw.githubusercontent.com/berke/aurochs/637bdc0d4682772837f9e44112212e7f20ab96ff/examples/cgidemo/html.ml | ocaml | Html
name, value
ISO-8859-1 text
ISO-8859-1 text
ISO-8859-1 text
ISO-8859-1 text
pre-formatted text
and start_tag_lineaire x =
launch_tag x;
flush_linear_tag ()
title
css
meta
body | Copyright ( C)2000 - 2006
Released under the GNU Lesser General Public License version 2.1
open Entity;;
let sf = Printf.sprintf;;
type html_document =
{ head: html_head;
body: html_element * html_properties }
and html_head =
{ title: string;
author: string;
charset: html_charset;
style_sheet: string option }
and html_properties = (string * string) list
and html_charset = ASCII | ISO_8859_1 | UTF8
and html_method = GET | POST
and html_element =
| I_hidden of string * string
name , value , size , maxlength
name , value , size , maxlength
| I_text_area of string * int * int * string
| I_checkbox of string * string * bool
| I_radio of string * string * bool
| I_select of string * bool * int * (string * string * bool) list
| I_reset of string
| Img of string * int * int * string
| Form of html_method * string * html_element
| Anchor of url * html_element
| Seq of html_element list
| UL of html_element list
| P of html_element
| H of int * html_element
| HR
| Table of html_table_row list
| Nop
| BR
| Div of string * html_element list
| Span of string * html_element
| Script of string * string
| With of html_properties * html_element
and html_table_row = html_table_cell list
and html_table_cell =
| C_contents of html_element
| C_halign of html_table_cell_halign * html_table_cell
| C_valign of html_table_cell_valign * html_table_cell
| C_rowspan of int * html_table_cell
| C_colspan of int * html_table_cell
| C_header of html_table_cell
| C_color of Rgb.t * html_table_cell
| C_width of int * html_table_cell
and html_table_cell_halign =
| Cha_left
| Cha_center
| Cha_right
| Cha_justify
| Cha_char of char
and html_table_cell_valign =
| Cva_top
| Cva_middle
| Cva_bottom
| Cva_baseline
and url = string
;;
let default_head =
{ title = "Untitled";
author = "Ara HTTPD";
charset = ISO_8859_1;
style_sheet = None }
;;
let string_of_charset = function
| ASCII -> "ascii"
| ISO_8859_1 -> "iso-8859-1"
| UTF8 -> "utf-8"
;;
let output (f : string -> unit) (fc : char -> unit) x =
let indent = ref 0 in
let put_indent () =
for i = 1 to !indent do
f " "
done
in
let text_avec_table t y =
for i = 0 to String.length y - 1 do
f t.(Char.code y.[i])
done
in
let text = text_avec_table character_table in
let gui = text in
let ife f = function
| Some x -> ignore (f x)
| None -> () in
let launch_tag x =
put_indent ();
f ("<"^x)
and end_tag_linear x = f ("</"^x^">")
in
and flush_tag_without_nl ( ) = f " > " ;
and x = f ( " < /"^x^ " > " )
and launch_linear_tag x = f ( " < " ^x )
and end_tag_without_nl x = f ("</"^x^">")
and launch_linear_tag x = f ("<"^x)*)
let spaces = ref true in
let flush_tag () = if !spaces then begin f ">\n"; incr indent end else f ">"
and flush_linear_tag () = if !spaces then f ">\n" else f ">"
and end_tag x =
if !spaces then
begin
decr indent;
put_indent ();
f ("</"^x^">\n")
end
else
begin
f ("</"^x^">")
end
in
let flush_tag_without_nl () = f ">"
and launch_linear_tag x = f ("<"^x)
in
let put_properties l =
List.iter
begin fun (k,v) ->
f " ";
f k;
f "=\"";
gui v;
f "\""
end
l
in
let text_or_password ?(properties=[]) kind n v s m =
launch_tag "INPUT";
f " TYPE=";
f kind;
f " NAME=\"";
gui n;
f "\" VALUE=\"";
gui v;
f "\"";
begin
match s with
| Some(s) -> f (" SIZE="^(string_of_int s))
| None -> ();
end;
begin
match m with
| Some(m) -> f (" MAXLENGTH="^(string_of_int m))
| None -> ();
end;
put_properties properties;
flush_linear_tag ()
in
let start_tag ?(properties=[]) x =
launch_tag x;
put_properties properties;
flush_tag ()
and start_tag_without_nl x =
launch_tag x;
flush_tag_without_nl ()
in
let linear_tag ?(properties=[]) x =
launch_tag x;
put_properties properties;
flush_linear_tag ()
in
let rec cellule c i j =
let rec loop he ha va rs cs rgb w c =
match c with
| C_header (c) -> loop true ha va rs cs rgb w c
| C_halign (ha,c) -> loop he (Some ha) va rs cs rgb w c
| C_valign (va,c) -> loop he ha (Some va) rs cs rgb w c
| C_rowspan (rs,c) -> loop he ha va (Some rs) cs rgb w c
| C_colspan (cs,c) -> loop he ha va rs (Some cs) rgb w c
| C_color (rgb,c) -> loop he ha va rs cs (Some rgb) w c
| C_width (w,c) -> loop he ha va rs cs rgb (Some w) c
| C_contents e ->
launch_tag (if he then "TH" else "TD");
begin
let coefficient_parity_row = -2
and coefficient_parity_column = -1
and coefficient_head = -4
and shift = 11
and coefficient_total = 12
in
match rgb with
Some(rgb) ->
f (Printf.sprintf " BGCOLOR=\"%s\""
(Rgb.to_string
(let alpha =
(float_of_int
(((if he then 0 else coefficient_head)
+ coefficient_parity_row * (i mod 2)
+ coefficient_parity_column * (j mod 2)) + shift)) /.
(float_of_int coefficient_total)
in
Rgb.mix alpha Rgb.white rgb)));
| _ -> ()
end;
ife
(fun ha ->
f " ALIGN=";
match ha with
| Cha_left -> f "LEFT"
| Cha_center -> f "CENTER"
| Cha_right -> f "RIGHT"
| Cha_justify -> f "JUSTIFY"
| Cha_char c -> f "\""; gui (String.make 1 c); f "\"")
ha;
ife
(fun va ->
f " VALIGN=";
match va with
| Cva_top -> f "TOP"
| Cva_middle -> f "MIDDLE"
| Cva_bottom -> f "BOTTOM"
| Cva_baseline -> f "BASELINE")
va;
ife (fun rs -> f (" ROWSPAN="^(string_of_int rs))) rs;
ife (fun cs -> f (" COLSPAN="^(string_of_int cs))) cs;
ife (fun w -> f (" WIDTH="^(string_of_int w))) w;
flush_tag ();
element e;
end_tag (if he then "TH" else "TD")
in
loop false None None None None None None c
and element ?(properties=[]) y =
match y with
| With(p',y') -> element ~properties:(p' @ properties) y'
| Script(ty,src) ->
launch_tag "SCRIPT";
f " TYPE=\"";
gui ty;
f "\" SRC=\"";
gui src;
f "\"";
put_properties properties;
flush_tag_without_nl ();
end_tag "SCRIPT"
| Anchor(u,e) ->
launch_tag "A";
f " HREF=\"";
gui u;
f "\"";
put_properties properties;
flush_tag_without_nl ();
let spaces' = !spaces in
spaces := false;
element e;
spaces := spaces';
end_tag "A"
| Img(path, width, height, alt) ->
launch_linear_tag "IMG";
f (sf " SRC=%S WIDTH=%d HEIGHT=%d ALT=\"" path width height);
text_avec_table character_table alt;
f "\"";
put_properties properties;
flush_tag_without_nl ()
| Form(m,u,e) ->
launch_tag "FORM";
f (" METHOD="^(match m with POST -> "POST" | GET -> "GET")^" ACTION=\"");
f u;
f "\" ENCTYPE=\"application/x-www-form-urlencoded\"";
put_properties properties;
flush_tag ();
element e;
end_tag "FORM";
| Div(c, z) ->
launch_tag "DIV";
f (sf " CLASS=%S" c);
put_properties properties;
flush_tag ();
List.iter (fun t -> element t) z;
end_tag "DIV"
| Span(c, z) ->
launch_linear_tag "SPAN";
f (sf " CLASS=%S" c);
put_properties properties;
flush_tag_without_nl ();
element z;
end_tag_linear "SPAN"
| Seq z -> List.iter (fun t -> element t) z
| UL l ->
start_tag ~properties "UL";
List.iter (fun t ->
start_tag ~properties "LI";
element t;
end_tag "LI") l;
end_tag "UL"
| H(i, z) ->
start_tag ~properties ("H"^(string_of_int i));
element z;
end_tag ("H"^(string_of_int i))
| T z ->
if !spaces then put_indent ();
text_avec_table character_table_nl_to_br z;
if !spaces then f "\n"
| BT z -> start_tag ~properties "B"; text z; end_tag "B"
| TT z -> start_tag ~properties "TT"; text z; end_tag "TT"
| IT z -> start_tag ~properties "I"; text z; end_tag "I"
| Pre z ->
start_tag_without_nl "PRE"; text z;
end_tag_linear "PRE"
| HR -> linear_tag ~properties "HR"
| BR -> linear_tag ~properties "BR"
start_tag ~properties " P " ; element z ; end_tag " P "
| Nop -> f " "
| I_select (n,m,s,l) ->
launch_tag "SELECT";
f " SIZE="; f (string_of_int s);
f " NAME=\""; gui n; f (if m then "\" MULTIPLE" else "\"");
put_properties properties;
flush_tag ();
List.iter (fun (n,v,s) ->
launch_tag "OPTION";
f " VALUE=\""; gui n; f (if s then "\" SELECTED" else "\"");
flush_linear_tag ();
text v;
f " ") l;
end_tag "SELECT"
| I_reset (v) ->
launch_tag "INPUT";
f " TYPE=RESET VALUE=\""; gui v; f "\"";
put_properties properties;
flush_linear_tag ()
| I_button (n,v) ->
launch_tag "INPUT";
f " TYPE=SUBMIT NAME=\""; gui n; f "\" VALUE=\""; gui v; f "\"";
put_properties properties;
flush_linear_tag ()
| I_hidden (n,v) ->
launch_tag "INPUT";
f " TYPE=HIDDEN NAME=\""; gui n; f "\" VALUE=\""; gui v; f "\"";
put_properties properties;
flush_linear_tag ()
| I_text (n,v,s,m) -> text_or_password ~properties "TEXT" n v s m
| I_password (n,v,s,m) -> text_or_password ~properties "PASSWORD" n v s m
| I_text_area (n,r,c,v) ->
launch_tag "TEXTAREA";
f (Printf.sprintf " ROWS=%d COLS=%d NAME=\"" r c); gui n; f "\"";
put_properties properties;
flush_linear_tag ();
text v;
end_tag_linear "TEXTAREA"
| I_checkbox (n,v,c) ->
launch_tag "INPUT";
f " TYPE=CHECKBOX NAME=\""; gui n; f "\" VALUE=\""; gui v;
f "\"";
if c then f " CHECKED";
put_properties properties;
flush_linear_tag ();
| I_radio (n,v,c) ->
launch_tag "INPUT";
f " TYPE=RADIO NAME=\""; gui n; f "\" VALUE=\""; gui v;
f "\"";
if c then f " CHECKED";
put_properties properties;
flush_linear_tag ();
| Table l ->
start_tag ~properties "TABLE";
let (i,j) = (ref 0, ref 0) in
List.iter
(fun r ->
start_tag ~properties "TR";
j := 0;
List.iter (fun r' -> cellule r' !i !j; incr j) r;
incr i;
end_tag "TR") l;
end_tag "TABLE"
in
begin
f "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
start_tag "HTML";
begin
start_tag "HEAD";
begin
start_tag "TITLE";
put_indent (); text x.head.title;
if !spaces then f "\n";
end_tag "TITLE";
begin
match x.head.style_sheet with
| None -> ()
| Some css ->
launch_tag "LINK";
f " REL=\"stylesheet\" TYPE=\"text/css\" HREF=\"";
text css;
f "\"";
flush_linear_tag ()
end;
begin
launch_tag "META";
f (sf " HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=%s\""
(string_of_charset x.head.charset));
flush_linear_tag ();
launch_tag "META";
f " NAME=\"Author\" CONTENT=\"";
text x.head.author;
f "\"";
flush_linear_tag ()
end;
end;
end_tag "HEAD";
end;
begin
let (body, properties) = x.body in
start_tag ~properties "BODY";
element body;
end_tag "BODY";
end;
end_tag "HTML";
end
;;
let rec map_text f = function
| Form(a,b,e) -> Form(a,b,map_text f e)
| Seq l -> Seq(List.map (map_text f) l)
| UL l -> UL(List.map (map_text f) l)
| P e -> P(map_text f e)
| H(x,e) -> H(x,map_text f e)
| T t -> f (fun x -> T x) t
| BT t -> f (fun x -> BT x) t
| IT t -> f (fun x -> BT x) t
| TT t -> f (fun x -> BT x) t
| Div(c,l) -> Div(c,List.map (map_text f) l)
| Span(c,e) -> Span(c,map_text f e)
| Table(l) -> Table(List.map (List.map (map_cell f)) l)
| x -> x
and map_cell f = function
| C_contents(e) -> C_contents(map_text f e)
| C_halign(h,c) -> C_halign(h,map_cell f c)
| C_valign(v,c) -> C_valign(v,map_cell f c)
| C_rowspan(x,c) -> C_rowspan(x,map_cell f c)
| C_colspan(x,c) -> C_colspan(x,map_cell f c)
| C_header(c) -> C_header(map_cell f c)
| C_color(x,c) -> C_color(x,map_cell f c)
| C_width(x,c) -> C_width(x,map_cell f c)
;;
let output_to_channel oc = output (output_string oc) (output_char oc);;
let output_to_buffer b x = output (Buffer.add_string b) (Buffer.add_char b) x;;
|
900b5057d47509b9757cac538667f7778d9b795fe9ae0838edfffb28f63253d5 | tisnik/clojure-examples | core.clj | (ns enlive2.core
(:gen-class))
(require '[net.cgrand.enlive-html :as html])
(html/deftemplate test-page "test.html"
[data-for-page]
[:title] (html/content (:title data-for-page))
[:h1] (html/content (:title data-for-page))
[:div#paragraph1] (html/content (:paragraph1 data-for-page))
[:div#paragraph2] (html/content (:paragraph2 data-for-page))
[:div.paragraphs] (html/content (:paragraphs data-for-page))
)
(def new-data
{:title "Zcela novy titulek stranky"
:paragraph1 "xyzzy"
:paragraph2 ""
:paragraphs "42"
})
(defn -main
[& args]
(println (reduce str (test-page new-data))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/enlive2/src/enlive2/core.clj | clojure | (ns enlive2.core
(:gen-class))
(require '[net.cgrand.enlive-html :as html])
(html/deftemplate test-page "test.html"
[data-for-page]
[:title] (html/content (:title data-for-page))
[:h1] (html/content (:title data-for-page))
[:div#paragraph1] (html/content (:paragraph1 data-for-page))
[:div#paragraph2] (html/content (:paragraph2 data-for-page))
[:div.paragraphs] (html/content (:paragraphs data-for-page))
)
(def new-data
{:title "Zcela novy titulek stranky"
:paragraph1 "xyzzy"
:paragraph2 ""
:paragraphs "42"
})
(defn -main
[& args]
(println (reduce str (test-page new-data))))
| |
d11d81623504903a1b02f4eb1bbf5f57dbfadf5d4d90af2ca1423a339a237b30 | pixlsus/registry.gimp.org_static | batch-color-contrast.scm | (define (batch-color-contrast filepath file-extension keep-original apply-highlight highlight-cyan-red highlight-magenta-green highlight-yellow-blue
apply-midtone midtone-cyan-red midtone-magenta-green midtone-yellow-blue
apply-shadow shadow-cyan-red shadow-magenta-green shadow-yellow-blue
preserve-lum apply-cont brightness contrast)
(let*
(
(filelist (cadr (file-glob (string-append filepath DIR-SEPARATOR "*." file-extension) 1)))
)
(while (not (null? filelist))
(let*
(
(filename (car filelist)
)
(image (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
(drawable (car (gimp-image-get-active-layer image)))
(Ouiche (car (gimp-drawable-is-indexed drawable)))) ; \
(if (= Ouiche TRUE) ; Enable indexed images to be edited. Thanks to bakalex92 ()
(begin (gimp-image-convert-rgb image)) ; /
)
;Apply filters
(if (< 0 apply-highlight)
(gimp-color-balance
drawable
2
preserve-lum
highlight-cyan-red
highlight-magenta-green
highlight-yellow-blue)
)
(if (< 0 apply-midtone)
(gimp-color-balance
drawable
1
preserve-lum
midtone-cyan-red
midtone-magenta-green
midtone-yellow-blue)
)
(if (< 0 apply-shadow)
(gimp-color-balance
drawable
0
preserve-lum
shadow-cyan-red
shadow-magenta-green
shadow-yellow-blue)
)
(if (< 0 apply-cont)
(gimp-brightness-contrast
drawable brightness contrast)
)
(if (= Ouiche TRUE) ; \
(begin (gimp-image-convert-indexed image 0 0 255 FALSE FALSE "")) ; Enable indexed images to be edited. Thanks to bakalex92 ()
) ; /
;Save to file
(if (< 0 keep-original)
;if true
(gimp-file-save RUN-NONINTERACTIVE
image drawable (string-append filepath DIR-SEPARATOR "_" (substring filename (+ (string-length filepath) 1)))
(string-append filepath DIR-SEPARATOR "_" (substring filename (+ (string-length filepath) 1))))
;if false
(gimp-file-save RUN-NONINTERACTIVE
image drawable filename filename)
)
(gimp-image-delete image)
)
(set! filelist (cdr filelist))
)
)
)
; Register with script-fu.
(script-fu-register "batch-color-contrast"
"Batch Color Balance and Contrast"
"Applys Color balance, brightness and contrast adjustments to all files in the selected folder"
"Kristoffer Myskja <>"
"Kristoffer Myskja"
"2010-2-8 (last updated 2010-11-16)"
""
SF-DIRNAME "Folder" "C:\\"
SF-STRING "File type (use * for all types)" "jpg"
SF-TOGGLE _"Keep original files and save new files with prefix \' _ \'" TRUE
;Highlights
SF-TOGGLE _"Make changes to Highlights" FALSE
SF-ADJUSTMENT "Cyan-Red color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Magenta-Green color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Yellow-Blue color balance" '(0 -100 100 1 5 0 SF-SLIDER)
;Midtones
SF-TOGGLE _"Make changes to Midtones" FALSE
SF-ADJUSTMENT "Cyan-Red color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Magenta-Green color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Yellow-Blue color balance" '(0 -100 100 1 5 0 SF-SLIDER)
;Shadows
SF-TOGGLE _"Make changes to Shadows" FALSE
SF-ADJUSTMENT "Cyan-Red color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Magenta-Green color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Yellow-Blue color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-TOGGLE _"Preserve luminosity values at each pixel" TRUE
Brightness & Contrast
SF-TOGGLE _"Make changes to Brightness and Contrast" FALSE
SF-ADJUSTMENT "Brightness" '(0 -127 127 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Contrast" '(0 -127 127 1 5 0 SF-SLIDER)
)
(script-fu-menu-register "batch-color-contrast"
"<Toolbox>/Xtns/Misc/")
| null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/batch-color-contrast.scm | scheme | \
Enable indexed images to be edited. Thanks to bakalex92 ()
/
Apply filters
\
Enable indexed images to be edited. Thanks to bakalex92 ()
/
Save to file
if true
if false
Register with script-fu.
Highlights
Midtones
Shadows | (define (batch-color-contrast filepath file-extension keep-original apply-highlight highlight-cyan-red highlight-magenta-green highlight-yellow-blue
apply-midtone midtone-cyan-red midtone-magenta-green midtone-yellow-blue
apply-shadow shadow-cyan-red shadow-magenta-green shadow-yellow-blue
preserve-lum apply-cont brightness contrast)
(let*
(
(filelist (cadr (file-glob (string-append filepath DIR-SEPARATOR "*." file-extension) 1)))
)
(while (not (null? filelist))
(let*
(
(filename (car filelist)
)
(image (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
(drawable (car (gimp-image-get-active-layer image)))
)
(if (< 0 apply-highlight)
(gimp-color-balance
drawable
2
preserve-lum
highlight-cyan-red
highlight-magenta-green
highlight-yellow-blue)
)
(if (< 0 apply-midtone)
(gimp-color-balance
drawable
1
preserve-lum
midtone-cyan-red
midtone-magenta-green
midtone-yellow-blue)
)
(if (< 0 apply-shadow)
(gimp-color-balance
drawable
0
preserve-lum
shadow-cyan-red
shadow-magenta-green
shadow-yellow-blue)
)
(if (< 0 apply-cont)
(gimp-brightness-contrast
drawable brightness contrast)
)
(if (< 0 keep-original)
(gimp-file-save RUN-NONINTERACTIVE
image drawable (string-append filepath DIR-SEPARATOR "_" (substring filename (+ (string-length filepath) 1)))
(string-append filepath DIR-SEPARATOR "_" (substring filename (+ (string-length filepath) 1))))
(gimp-file-save RUN-NONINTERACTIVE
image drawable filename filename)
)
(gimp-image-delete image)
)
(set! filelist (cdr filelist))
)
)
)
(script-fu-register "batch-color-contrast"
"Batch Color Balance and Contrast"
"Applys Color balance, brightness and contrast adjustments to all files in the selected folder"
"Kristoffer Myskja <>"
"Kristoffer Myskja"
"2010-2-8 (last updated 2010-11-16)"
""
SF-DIRNAME "Folder" "C:\\"
SF-STRING "File type (use * for all types)" "jpg"
SF-TOGGLE _"Keep original files and save new files with prefix \' _ \'" TRUE
SF-TOGGLE _"Make changes to Highlights" FALSE
SF-ADJUSTMENT "Cyan-Red color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Magenta-Green color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Yellow-Blue color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-TOGGLE _"Make changes to Midtones" FALSE
SF-ADJUSTMENT "Cyan-Red color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Magenta-Green color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Yellow-Blue color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-TOGGLE _"Make changes to Shadows" FALSE
SF-ADJUSTMENT "Cyan-Red color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Magenta-Green color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Yellow-Blue color balance" '(0 -100 100 1 5 0 SF-SLIDER)
SF-TOGGLE _"Preserve luminosity values at each pixel" TRUE
Brightness & Contrast
SF-TOGGLE _"Make changes to Brightness and Contrast" FALSE
SF-ADJUSTMENT "Brightness" '(0 -127 127 1 5 0 SF-SLIDER)
SF-ADJUSTMENT "Contrast" '(0 -127 127 1 5 0 SF-SLIDER)
)
(script-fu-menu-register "batch-color-contrast"
"<Toolbox>/Xtns/Misc/")
|
4d5bf3dbe24496dcd358f52a510f0c85d99ac63fb27fd0b159f0bf347e275969 | rowangithub/DOrder | 313_nest-len.ml | let rec loopb i n =
if i < n then
loopb (i+1) n
else ()
let rec loopa k n =
(assert (1 <= k);
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;)
let main n =
loopa 1 n | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/mochi2/benchs/313_nest-len.ml | ocaml | let rec loopb i n =
if i < n then
loopb (i+1) n
else ()
let rec loopa k n =
(assert (1 <= k);
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;
loopb 1 n;)
let main n =
loopa 1 n | |
32e92ac10de9505ee922f58d894bffb853e0a650c7cf3cdace0c63dba78158cb | janestreet/sexplib | conv_error.ml | include Sexplib0.Sexp_conv_error
| null | https://raw.githubusercontent.com/janestreet/sexplib/b4c3a03b671afadc5d4180224b97f034bec9764f/src/conv_error.ml | ocaml | include Sexplib0.Sexp_conv_error
| |
f0e8020ca2774dfef16dfc7080a8da59933d52e7d8fcc0bef3a5cb14ff81584c | kuchenkruste/lambda-m | Tree.hs | module Tree(Tree(..), Tree.parse, pretty) where
import Utility
import Text.ParserCombinators.Parsec
import Data.Bifunctor
import Control.Monad
import Data.List
data Tree = Var String
| Ign
| App Tree Tree
| Abs Tree Tree
| Num Integer
| Chr Char
| Tuple [Tree]
| Match Tree [Tree]
| Let [(Tree, Tree)] Tree
| Data [Tree] Tree
| Macro Tree Tree String
deriving (Show, Eq)
pretty :: Tree -> String
pretty (Var name) = name
pretty Ign = "_"
pretty (Tuple values) = "(" ++ (intercalate ", " (fmap pretty values)) ++ ")"
pretty (Num num) = show num
pretty (Chr chr) = show chr
pretty (Let binders tree) = "let " ++ (intercalate ", " (fmap f binders)) ++ " in " ++ pretty tree where
f :: (Tree, Tree) -> String
f (left, right) = pretty left ++ " = " ++ pretty right
pretty (Data constructors tree) = "data " ++ (intercalate " | " (fmap pretty constructors)) ++ " in " ++ pretty tree
pretty (Macro left right content) = "macro " ++ pretty left ++ " = " ++ pretty right ++ " in " ++ content
pretty (Match value @ (App _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Abs _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Let _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Data _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Macro _ _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value cases) = pretty value ++ " match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (App left right @ (Abs _ _)) = pretty left ++ " (" ++ pretty right ++ ")"
pretty (App left @ (Abs _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left @ (Let _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left @ (Data _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left @ (Macro _ _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left right) = pretty left ++ " " ++ pretty right
pretty (Abs left @ (Abs _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left @ (Let _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left @ (Data _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left @ (Macro _ _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left right) = pretty left ++ " => " ++ pretty right
operatorSymbols :: [Char]
operatorSymbols = "+*~#-:.$%&/\\=?!^°<>|@"
keywords :: [String]
keywords = ["let", "in", "data", "case", "match", "=>", "=", "|"]
parse :: String -> Try Tree
parse input = first show $ Text.ParserCombinators.Parsec.parse parseTree "(unknown)" input
parseTree :: Parser Tree
parseTree = between spaces spaces (try parseMacro <|> try parseData <|> try parseLet <|> parseAbs False)
parseData :: Parser Tree
parseData = do
parseKeyword "data"
spaces
constructors <- sepBy1 parseApp (between spaces spaces $ char '|')
spaces
parseKeyword "in"
spaces
tree <- parseTree
return $ Data constructors tree
parseLet :: Parser Tree
parseLet = do
parseKeyword "let"
spaces
let parseBinder = do
binder <- parseApp
spaces
parseKeyword "="
spaces
expression <- parseTree
return (binder, expression)
binders <- sepBy1 parseBinder (between spaces spaces $ char ',')
spaces
parseKeyword "in"
spaces
tree <- parseTree
return $ Let binders tree
parseMacro :: Parser Tree
parseMacro = do
parseKeyword "macro"
spaces
binder <- parseApp
spaces
parseKeyword "="
spaces
expression <- parseTree
spaces
parseKeyword "in"
spaces
content <- many anyChar
return $ Macro binder expression content
parseAbs :: Bool -> Parser Tree
parseAbs force = do
left <- parseApp
spaces
let rhsParser = do
parseKeyword "=>"
spaces
right <- parseTree
return $ Abs left right
if force
then rhsParser
else option left rhsParser
parseApp :: Parser Tree
parseApp = do
let trySepBy1 parser separator = do
head <- parser
tail <- many $ try $ do
separator
parser
return $ head : tail
apps <- trySepBy1 parseValue spaces
return $ foldl1 App apps
parseValue :: Parser Tree
parseValue = try $ do
value <- choice [ try parseList, try parseString, try parseNum, try parseChr, try parseTuple, try parseIgnore, parseVar ]
spaces
result <- option value $ try $ do
parseKeyword "match"
spaces
char '{'
spaces
let caseParser = do
parseKeyword "case"
spaces
parseAbs True
cases <- sepBy caseParser spaces
spaces
char '}'
return $ Match value cases
return result
parseIgnore :: Parser Tree
parseIgnore = do
char '_'
return Ign
parseNum :: Parser Tree
parseNum = do
num <- many1 digit
return $ Num (read num)
escape :: Bool -> Parser Char
escape stringMode = do
char '\\'
c <- if stringMode then oneOf "\\\"0nrvtbf" else oneOf "\\'0nrvtbf"
return $ case c of
'0' -> '\0'
'n' -> '\n'
'r' -> '\r'
'v' -> '\v'
't' -> '\t'
'b' -> '\b'
'f' -> '\f'
c -> c
nonEscape :: Bool -> Parser Char
nonEscape True = noneOf "\\\"\0\n\r\v\t\b\f"
nonEscape False = noneOf "\\'\0\n\r\v\t\b\f"
character :: Bool -> Parser Char
character stringMode = (nonEscape stringMode) <|> (escape stringMode)
parseChr :: Parser Tree
parseChr = do
char '\''
c <- character False
char '\''
return $ Chr c
parseString :: Parser Tree
parseString = do
char '"'
string <- many $ character True
char '"'
return $ Data.List.foldr (\next acc -> App (App (Var "Cons") (Chr next)) acc) (Var "Nil") string
parseList :: Parser Tree
parseList = do
char '['
values <- sepBy parseTree (char ',')
char ']'
return $ Data.List.foldr (\next acc -> App (App (Var "Cons") next) acc) (Var "Nil") values
parseVar :: Parser Tree
parseVar = fmap Var (try parseAlphaNumericIdentifier <|> parseSymbolicIdentifier)
parseTuple :: Parser Tree
parseTuple = do
values <- between (char '(') (char ')') $ do
spaces
result <- sepBy parseTree (char ',')
spaces
return result
return $ Tuple values
parseIdentifier :: Parser Char -> Parser String
parseIdentifier symbols = try $ do
let identifierParser = try $ do
head <- symbols
tail <- many (try symbols <|> digit)
primes <- many $ char '\''
return $ (head : tail) ++ primes
identifier <- try $ lookAhead identifierParser
if identifier `elem` keywords
then unexpected ("'" ++ identifier ++ "' is a reserved keyword")
else identifierParser
parseAlphaNumericIdentifier :: Parser String
parseAlphaNumericIdentifier = parseIdentifier letter
parseSymbolicIdentifier :: Parser String
parseSymbolicIdentifier = parseIdentifier (oneOf operatorSymbols)
parseKeyword :: String -> Parser ()
parseKeyword keyword = do
string keyword
notFollowedBy (choice [ try alphaNum, try (oneOf operatorSymbols), char '\'' ])
| null | https://raw.githubusercontent.com/kuchenkruste/lambda-m/dec69313d550cb2e7fa391ea9f08a5d238f9f582/src/Tree.hs | haskell | module Tree(Tree(..), Tree.parse, pretty) where
import Utility
import Text.ParserCombinators.Parsec
import Data.Bifunctor
import Control.Monad
import Data.List
data Tree = Var String
| Ign
| App Tree Tree
| Abs Tree Tree
| Num Integer
| Chr Char
| Tuple [Tree]
| Match Tree [Tree]
| Let [(Tree, Tree)] Tree
| Data [Tree] Tree
| Macro Tree Tree String
deriving (Show, Eq)
pretty :: Tree -> String
pretty (Var name) = name
pretty Ign = "_"
pretty (Tuple values) = "(" ++ (intercalate ", " (fmap pretty values)) ++ ")"
pretty (Num num) = show num
pretty (Chr chr) = show chr
pretty (Let binders tree) = "let " ++ (intercalate ", " (fmap f binders)) ++ " in " ++ pretty tree where
f :: (Tree, Tree) -> String
f (left, right) = pretty left ++ " = " ++ pretty right
pretty (Data constructors tree) = "data " ++ (intercalate " | " (fmap pretty constructors)) ++ " in " ++ pretty tree
pretty (Macro left right content) = "macro " ++ pretty left ++ " = " ++ pretty right ++ " in " ++ content
pretty (Match value @ (App _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Abs _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Let _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Data _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value @ (Macro _ _ _) cases) = "(" ++ pretty value ++ ") match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (Match value cases) = pretty value ++ " match {" ++ (intercalate "" (fmap ((++) " case ") (fmap pretty cases))) ++ " }"
pretty (App left right @ (Abs _ _)) = pretty left ++ " (" ++ pretty right ++ ")"
pretty (App left @ (Abs _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left @ (Let _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left @ (Data _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left @ (Macro _ _ _) right) = "(" ++ pretty left ++ ") " ++ pretty right
pretty (App left right) = pretty left ++ " " ++ pretty right
pretty (Abs left @ (Abs _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left @ (Let _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left @ (Data _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left @ (Macro _ _ _) right) = "(" ++ pretty left ++ ") => " ++ pretty right
pretty (Abs left right) = pretty left ++ " => " ++ pretty right
operatorSymbols :: [Char]
operatorSymbols = "+*~#-:.$%&/\\=?!^°<>|@"
keywords :: [String]
keywords = ["let", "in", "data", "case", "match", "=>", "=", "|"]
parse :: String -> Try Tree
parse input = first show $ Text.ParserCombinators.Parsec.parse parseTree "(unknown)" input
parseTree :: Parser Tree
parseTree = between spaces spaces (try parseMacro <|> try parseData <|> try parseLet <|> parseAbs False)
parseData :: Parser Tree
parseData = do
parseKeyword "data"
spaces
constructors <- sepBy1 parseApp (between spaces spaces $ char '|')
spaces
parseKeyword "in"
spaces
tree <- parseTree
return $ Data constructors tree
parseLet :: Parser Tree
parseLet = do
parseKeyword "let"
spaces
let parseBinder = do
binder <- parseApp
spaces
parseKeyword "="
spaces
expression <- parseTree
return (binder, expression)
binders <- sepBy1 parseBinder (between spaces spaces $ char ',')
spaces
parseKeyword "in"
spaces
tree <- parseTree
return $ Let binders tree
parseMacro :: Parser Tree
parseMacro = do
parseKeyword "macro"
spaces
binder <- parseApp
spaces
parseKeyword "="
spaces
expression <- parseTree
spaces
parseKeyword "in"
spaces
content <- many anyChar
return $ Macro binder expression content
parseAbs :: Bool -> Parser Tree
parseAbs force = do
left <- parseApp
spaces
let rhsParser = do
parseKeyword "=>"
spaces
right <- parseTree
return $ Abs left right
if force
then rhsParser
else option left rhsParser
parseApp :: Parser Tree
parseApp = do
let trySepBy1 parser separator = do
head <- parser
tail <- many $ try $ do
separator
parser
return $ head : tail
apps <- trySepBy1 parseValue spaces
return $ foldl1 App apps
parseValue :: Parser Tree
parseValue = try $ do
value <- choice [ try parseList, try parseString, try parseNum, try parseChr, try parseTuple, try parseIgnore, parseVar ]
spaces
result <- option value $ try $ do
parseKeyword "match"
spaces
char '{'
spaces
let caseParser = do
parseKeyword "case"
spaces
parseAbs True
cases <- sepBy caseParser spaces
spaces
char '}'
return $ Match value cases
return result
parseIgnore :: Parser Tree
parseIgnore = do
char '_'
return Ign
parseNum :: Parser Tree
parseNum = do
num <- many1 digit
return $ Num (read num)
escape :: Bool -> Parser Char
escape stringMode = do
char '\\'
c <- if stringMode then oneOf "\\\"0nrvtbf" else oneOf "\\'0nrvtbf"
return $ case c of
'0' -> '\0'
'n' -> '\n'
'r' -> '\r'
'v' -> '\v'
't' -> '\t'
'b' -> '\b'
'f' -> '\f'
c -> c
nonEscape :: Bool -> Parser Char
nonEscape True = noneOf "\\\"\0\n\r\v\t\b\f"
nonEscape False = noneOf "\\'\0\n\r\v\t\b\f"
character :: Bool -> Parser Char
character stringMode = (nonEscape stringMode) <|> (escape stringMode)
parseChr :: Parser Tree
parseChr = do
char '\''
c <- character False
char '\''
return $ Chr c
parseString :: Parser Tree
parseString = do
char '"'
string <- many $ character True
char '"'
return $ Data.List.foldr (\next acc -> App (App (Var "Cons") (Chr next)) acc) (Var "Nil") string
parseList :: Parser Tree
parseList = do
char '['
values <- sepBy parseTree (char ',')
char ']'
return $ Data.List.foldr (\next acc -> App (App (Var "Cons") next) acc) (Var "Nil") values
parseVar :: Parser Tree
parseVar = fmap Var (try parseAlphaNumericIdentifier <|> parseSymbolicIdentifier)
parseTuple :: Parser Tree
parseTuple = do
values <- between (char '(') (char ')') $ do
spaces
result <- sepBy parseTree (char ',')
spaces
return result
return $ Tuple values
parseIdentifier :: Parser Char -> Parser String
parseIdentifier symbols = try $ do
let identifierParser = try $ do
head <- symbols
tail <- many (try symbols <|> digit)
primes <- many $ char '\''
return $ (head : tail) ++ primes
identifier <- try $ lookAhead identifierParser
if identifier `elem` keywords
then unexpected ("'" ++ identifier ++ "' is a reserved keyword")
else identifierParser
parseAlphaNumericIdentifier :: Parser String
parseAlphaNumericIdentifier = parseIdentifier letter
parseSymbolicIdentifier :: Parser String
parseSymbolicIdentifier = parseIdentifier (oneOf operatorSymbols)
parseKeyword :: String -> Parser ()
parseKeyword keyword = do
string keyword
notFollowedBy (choice [ try alphaNum, try (oneOf operatorSymbols), char '\'' ])
| |
f8e5fa1d4ed5750d6591b8c82f771488a829550a32400fe6067a756f203a5ae7 | glguy/advent2019 | Day07.hs | |
Module : Main
Description : Day 5 solution
Copyright : ( c ) , 2019
License : ISC
Maintainer :
< >
To compute our thrust controller feedback loop I evaluate the
given Intcode program as a function from input values to output
values . Connecting the outputs of one instance of the program
to the inputs of the next is as simple as composing the two
functions together . Thanks to non - strict evaluation I can
pass the output of a composition of these functions back in
as its own input !
Module : Main
Description : Day 5 solution
Copyright : (c) Eric Mertens, 2019
License : ISC
Maintainer :
<>
To compute our thrust controller feedback loop I evaluate the
given Intcode program as a function from input values to output
values. Connecting the outputs of one instance of the program
to the inputs of the next is as simple as composing the two
functions together. Thanks to non-strict evaluation I can
pass the output of a composition of these functions back in
as its own input!
-}
module Main (main) where
import Advent (getIntcodeInput)
import Data.Function (fix)
import Data.List (permutations)
import Intcode (intcodeToList)
-- | A function from a list of input values to a list of output values.
type ListFn = [Int] -> [Int]
main :: IO ()
main =
do pgm <- intcodeToList <$> getIntcodeInput 7
print (part1 pgm)
print (part2 pgm)
-- | Run the given amplitude controller in a feedback loop across
all permutations of the settings 0 through 4 . Returns the
-- maximum initial thruster output.
--
> > > part1 ( intcodeToList [ 3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0 ] )
43210
-- >>> part1 (intcodeToList [3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0])
54321
-- >>> part1 (intcodeToList [3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0])
-- 65210
part1 ::
ListFn {- ^ amplifier controller software -} ->
Int {- ^ maximum initial thruster output -}
part1 = optimize head [0..4]
-- | Run the given amplitude controller in a feedback loop across
all permutations of the settings 5 through 9 . Returns the
-- maximum final thruster output.
--
> > > part2 ( intcodeToList [ 3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5 ] )
139629729
-- >>> :{
> > > part2 ( intcodeToList [ 3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54 ,
-- >>> -5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,
> > > 53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10 ] )
-- >>> :}
18216
part2 ::
ListFn {- ^ amplifier controller software -} ->
Int {- ^ maximum final thruster output -}
part2 = optimize last [5..9]
optimize ::
Ord a =>
([Int] -> a) {- ^ output characterization -} ->
[Int] {- ^ phase available -} ->
ListFn {- ^ phases to outputs -} ->
a {- ^ maximized characterization -}
optimize f phases pgm = maximum [f (thrustController pgm p) | p <- permutations phases]
-- | Given a amplifier controller software function and a list of
-- phase settings, generate the resulting list of thruster outputs.
--
-- Once instances of the control software is started for each phase setting,
-- the instances are all sequenced together into a single loop. A starting
@0@ element is added as an initial input .
--
> > > ( intcodeToList [ 3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0 ] ) [ 4,3,2,1,0 ]
-- [43210]
> > > ( intcodeToList [ 3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5 ] ) [ 9,8,7,6,5 ]
-- [129,4257,136353,4363425,139629729]
thrustController ::
ListFn {- ^ amplifier controller software -} ->
ListFn {- ^ thrust controller -}
thrustController ctrl phases = tieknot [ctrl << p | p <- phases]
-- | Create a feedback loop given the initialized controllers
and return the thruster outputs . Feed an initial @0@ value
-- into the loop.
--
> > > tieknot [ map ( 2 * ) , map ( 1 + ) , take 5 ]
-- [1,3,7,15,31]
tieknot ::
[ListFn] {- ^ initialized amplifier controllers -} ->
[Int] {- ^ thruster outputs -}
tieknot fs = fix (composeLR fs << 0)
-- | Compose list functions from left-to-right. Inputs go into
-- first function and outputs come from last function.
--
> > > composeLR [ ( 2*),(1 + ) ] 3
7
composeLR :: [a -> a] -> (a -> a)
composeLR = foldl (flip (.)) id
-- | Feed a single input into a list function.
--
> > > ( map ( * 2 ) < < 10 ) [ 5,6,7 ]
[ 20,10,12,14 ]
(<<) :: ListFn -> Int -> ListFn
(f << x) xs = f (x:xs)
| null | https://raw.githubusercontent.com/glguy/advent2019/13f3be89535c12cbae761a6d4165432a2459ccd5/execs/Day07.hs | haskell | | A function from a list of input values to a list of output values.
| Run the given amplitude controller in a feedback loop across
maximum initial thruster output.
>>> part1 (intcodeToList [3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0])
>>> part1 (intcodeToList [3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0])
65210
^ amplifier controller software
^ maximum initial thruster output
| Run the given amplitude controller in a feedback loop across
maximum final thruster output.
>>> :{
>>> -5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,
>>> :}
^ amplifier controller software
^ maximum final thruster output
^ output characterization
^ phase available
^ phases to outputs
^ maximized characterization
| Given a amplifier controller software function and a list of
phase settings, generate the resulting list of thruster outputs.
Once instances of the control software is started for each phase setting,
the instances are all sequenced together into a single loop. A starting
[43210]
[129,4257,136353,4363425,139629729]
^ amplifier controller software
^ thrust controller
| Create a feedback loop given the initialized controllers
into the loop.
[1,3,7,15,31]
^ initialized amplifier controllers
^ thruster outputs
| Compose list functions from left-to-right. Inputs go into
first function and outputs come from last function.
| Feed a single input into a list function.
| |
Module : Main
Description : Day 5 solution
Copyright : ( c ) , 2019
License : ISC
Maintainer :
< >
To compute our thrust controller feedback loop I evaluate the
given Intcode program as a function from input values to output
values . Connecting the outputs of one instance of the program
to the inputs of the next is as simple as composing the two
functions together . Thanks to non - strict evaluation I can
pass the output of a composition of these functions back in
as its own input !
Module : Main
Description : Day 5 solution
Copyright : (c) Eric Mertens, 2019
License : ISC
Maintainer :
<>
To compute our thrust controller feedback loop I evaluate the
given Intcode program as a function from input values to output
values. Connecting the outputs of one instance of the program
to the inputs of the next is as simple as composing the two
functions together. Thanks to non-strict evaluation I can
pass the output of a composition of these functions back in
as its own input!
-}
module Main (main) where
import Advent (getIntcodeInput)
import Data.Function (fix)
import Data.List (permutations)
import Intcode (intcodeToList)
type ListFn = [Int] -> [Int]
main :: IO ()
main =
do pgm <- intcodeToList <$> getIntcodeInput 7
print (part1 pgm)
print (part2 pgm)
all permutations of the settings 0 through 4 . Returns the
> > > part1 ( intcodeToList [ 3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0 ] )
43210
54321
part1 ::
part1 = optimize head [0..4]
all permutations of the settings 5 through 9 . Returns the
> > > part2 ( intcodeToList [ 3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5 ] )
139629729
> > > part2 ( intcodeToList [ 3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54 ,
> > > 53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10 ] )
18216
part2 ::
part2 = optimize last [5..9]
optimize ::
Ord a =>
optimize f phases pgm = maximum [f (thrustController pgm p) | p <- permutations phases]
@0@ element is added as an initial input .
> > > ( intcodeToList [ 3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0 ] ) [ 4,3,2,1,0 ]
> > > ( intcodeToList [ 3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5 ] ) [ 9,8,7,6,5 ]
thrustController ::
thrustController ctrl phases = tieknot [ctrl << p | p <- phases]
and return the thruster outputs . Feed an initial @0@ value
> > > tieknot [ map ( 2 * ) , map ( 1 + ) , take 5 ]
tieknot ::
tieknot fs = fix (composeLR fs << 0)
> > > composeLR [ ( 2*),(1 + ) ] 3
7
composeLR :: [a -> a] -> (a -> a)
composeLR = foldl (flip (.)) id
> > > ( map ( * 2 ) < < 10 ) [ 5,6,7 ]
[ 20,10,12,14 ]
(<<) :: ListFn -> Int -> ListFn
(f << x) xs = f (x:xs)
|
6ccabf2b134532bde115058e15838cae5379b697b1226988119034908a8d5cc7 | dpiponi/Moodler | moodlerrc.hs | do
bind "⌫" "delete"
bind "h" "hide"
bind "⇧H" "unhide"
bind "⇧P" "unparent"
bind "⇧<" "setmin"
bind "⇧>" "setmax"
bind "\\" "nolimits"
bind "k" "addknob"
bind "s" "addslider"
bind ' K ' " "
bind "m" "relocate"
bind "n" "rename"
bind "z" "check"
bind "⎋" "up"
bind "=" "setvalue"
bind "0" "setzero"
bind "1" "setone"
bind "⇧+=" "plusequals"
bind "-=" "minusequals"
bind "⇧*=" "timesequals"
bind "/=" "divideequals"
bind "⇧|" "quantise"
bind "⇧!" "alert"
bind "⇧%" "setcolour"
bind "⇧~" "setpicture"
bind "⇧⌥F" "bringFront"
bind "⇧⌥B" "sendBack"
bind "⇧\"" "showhidden"
bind "⇧A" "noteA"
bind "⇧B" "noteB"
bind "⇧C" "noteC"
bind "⇧D" "noteD"
bind "⇧E" "noteE"
bind "⇧F" "noteF"
bind "⇧G" "noteG"
bind "b" "flatten"
bind "⇧#" "sharpen"
bind "⌥/" "splitcable"
return ()
| null | https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/moodlerrc.hs | haskell | do
bind "⌫" "delete"
bind "h" "hide"
bind "⇧H" "unhide"
bind "⇧P" "unparent"
bind "⇧<" "setmin"
bind "⇧>" "setmax"
bind "\\" "nolimits"
bind "k" "addknob"
bind "s" "addslider"
bind ' K ' " "
bind "m" "relocate"
bind "n" "rename"
bind "z" "check"
bind "⎋" "up"
bind "=" "setvalue"
bind "0" "setzero"
bind "1" "setone"
bind "⇧+=" "plusequals"
bind "-=" "minusequals"
bind "⇧*=" "timesequals"
bind "/=" "divideequals"
bind "⇧|" "quantise"
bind "⇧!" "alert"
bind "⇧%" "setcolour"
bind "⇧~" "setpicture"
bind "⇧⌥F" "bringFront"
bind "⇧⌥B" "sendBack"
bind "⇧\"" "showhidden"
bind "⇧A" "noteA"
bind "⇧B" "noteB"
bind "⇧C" "noteC"
bind "⇧D" "noteD"
bind "⇧E" "noteE"
bind "⇧F" "noteF"
bind "⇧G" "noteG"
bind "b" "flatten"
bind "⇧#" "sharpen"
bind "⌥/" "splitcable"
return ()
| |
94fec733cf4d8041a4af2c87fcfef725bb4061c867ea0fe7cf1ae421b62af83a | astrada/ocaml-extjs | ext_grid_Panel.mli | * Grids are an excellent way of showing large amount ...
{ % < p > Grids are an excellent way of showing large amounts of tabular data on the client side . Essentially a supercharged
< code><table></code > , GridPanel makes it easy to fetch , sort and filter large amounts of data.</p >
< p > Grids are composed of two main pieces - a < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Store</a > full of data and a set of columns to render.</p >
< h2 > Basic GridPanel</h2 >
< pre class='inline - example ' > < code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > ' , \ {
storeId:'simpsonsStore ' ,
fields:['name ' , ' email ' , ' phone ' ] ,
data:\{'items ' : [
\ { ' name ' : ' Lisa ' , " email":"lisa\@simpsons.com " , " phone":"555 - 111 - 1224 " \ } ,
\ { ' name ' : ' ' , " email":"bart\@simpsons.com " , " phone":"555 - 222 - 1234 " \ } ,
\ { ' name ' : ' Homer ' , " email":"home\@simpsons.com " , " phone":"555 - 222 - 1244 " \ } ,
\ { ' name ' : ' Marge ' , " email":"marge\@simpsons.com " , " phone":"555 - 222 - 1254 " \ }
] \ } ,
proxy : \ {
type : ' memory ' ,
reader : \ {
type : ' json ' ,
root : ' items '
\ }
\ }
\ } ) ;
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
title : ' Simpsons ' ,
store : < a href="#!/api / Ext.data . StoreManager - method - lookup " rel="Ext.data . StoreManager - method - lookup " class="docClass">Ext.data . StoreManager.lookup</a>('simpsonsStore ' ) ,
columns : [
\ { text : ' Name ' , dataIndex : ' name ' \ } ,
\ { text : ' Email ' , : ' email ' , flex : 1 \ } ,
\ { text : ' Phone ' , : ' phone ' \ }
] ,
height : 200 ,
width : 400 ,
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( )
\ } ) ;
< /code></pre >
< p > The code above produces a simple grid with three columns . We specified a Store which will load JSON data inline .
In most apps we would be placing the grid inside another container and would n't need to use the
< a href="#!/api / Ext.grid . Panel - cfg - height " rel="Ext.grid . Panel - cfg - height " class="docClass">height</a > , < a href="#!/api / Ext.grid . Panel - cfg - width " rel="Ext.grid . Panel - cfg - width " > and < a href="#!/api / Ext.grid . Panel - cfg - renderTo " rel="Ext.grid . Panel - cfg - renderTo " > configurations but they are included here to make it easy to get
up and p > The grid we created above will contain a header bar with a title ( ' Simpsons ' ) , a row of column headers directly underneath
and finally the grid rows under the >
< h2 > Configuring columns</h2 >
< p > By default , each column is sortable and will toggle between ASC and DESC sorting when you click on its header . Each
column header is also reorderable by default , and each gains a drop - down menu with options to hide and show columns .
It 's easy to configure each column - here we use the same example as above and just modify the columns config:</p >
< pre><code > columns : [
\ {
text : ' Name ' ,
: ' name ' ,
sortable : false ,
hideable : false ,
flex : 1
\ } ,
\ {
text : ' Email ' ,
: ' email ' ,
hidden : true
\ } ,
\ {
text : ' Phone ' ,
: ' phone ' ,
width : 100
\ }
]
< /code></pre >
< p > We turned off sorting and hiding on the ' Name ' column so clicking its header now has no effect . We also made the Email
column hidden by default ( it can be shown again by using the menu on any other column ) . We also set the Phone column to
a fixed with of 100px and flexed the Name column , which means it takes up all remaining width after the other columns
have been accounted for . See the < a href="#!/api / Ext.grid.column . Column " rel="Ext.grid.column . Column " class="docClass">column docs</a > for more details.</p >
< h2 > Renderers</h2 >
< p > As well as customizing columns , it 's easy to alter the rendering of individual cells using renderers . A renderer is
tied to a particular column and is passed the value that would be rendered into each cell in that column . For example ,
we could define a renderer function for the email column to turn each email address into a mailto link:</p >
< pre><code > columns : [
\ {
text : ' Email ' ,
: ' email ' ,
renderer : function(value ) \ {
return < a href="#!/api / Ext . String - method - format " rel="Ext . String - method - format " class="docClass">Ext . String.format</a>('<a href="mailto:\{0\}">\{1\}</a> ; ' , value , value ) ;
\ }
\ }
]
< /code></pre >
< p > See the < a href="#!/api / Ext.grid.column . Column " rel="Ext.grid.column . Column " class="docClass">column docs</a > for more information on renderers.</p >
< h2 > Selection Models</h2 >
< p > Sometimes all you want is to render data onto the screen for viewing , but usually it 's necessary to interact with or
update that data . Grids use a concept called a Selection Model , which is simply a mechanism for selecting some part of
the data in the grid . The two main types of Selection Model are RowSelectionModel , where entire rows are selected , and
CellSelectionModel , where individual cells are selected.</p >
< p > Grids use a Row Selection Model by default , but this is easy to customise like >
< pre><code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
selType : ' cellmodel ' ,
store : ...
\ } ) ;
< /code></pre >
< p > Specifying the < code > cellmodel</code > changes a couple of things . Firstly , clicking on a cell now
selects just that cell ( using a < a href="#!/api / Ext.selection . RowModel " rel="Ext.selection . RowModel " class="docClass">rowmodel</a > will select the entire row ) , and secondly the
keyboard navigation will walk from cell to cell instead of row to row . Cell - based selection models are usually used in
conjunction with editing.</p >
< h2 > Sorting & amp ; Filtering</h2 >
< p > Every grid is attached to a < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Store</a > , which provides multi - sort and filtering capabilities . It 's
easy to set up a grid to be sorted from the start:</p >
< pre><code > var myGrid = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
store : \ {
fields : [ ' name ' , ' email ' , ' phone ' ] ,
sorters : [ ' name ' , ' phone ' ]
\ } ,
columns : [
\ { text : ' Name ' , dataIndex : ' name ' \ } ,
\ { text : ' Email ' , : ' email ' \ }
]
\ } ) ;
< /code></pre >
< p > Sorting at run time is easily accomplished by simply clicking each column header . If you need to perform sorting on
more than one field at run time it 's easy to do so by adding new sorters to the store:</p >
< pre><code > ( [
\ { property : ' name ' , direction : ' ASC ' \ } ,
\ { property : ' email ' , direction : ' DESC ' \ }
] ) ;
< /code></pre >
< p > See < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > for examples of filtering.</p >
< h2 > State p > When configured < a href="#!/api / Ext.grid . Panel - cfg - stateful " rel="Ext.grid . Panel - cfg - stateful " class="docClass">stateful</a > , grids save their column state ( order and width ) encapsulated within the default
Panel state of changed width and height and collapsed / expanded state.</p >
< p > Each < a href="#!/api / Ext.grid . Panel - cfg - columns " rel="Ext.grid . Panel - cfg - columns " class="docClass">column</a > of the grid may be configured with a < a href="#!/api / Ext.grid.column . Column - cfg - stateId " rel="Ext.grid.column . Column - cfg - stateId " class="docClass">stateId</a > which
identifies that column locally within the grid.</p >
< h2 > Plugins and Features</h2 >
< p > Grid supports addition of extra functionality through features and plugins:</p >
< ul >
< li><p><a href="#!/api / Ext.grid.plugin . " class="docClass">CellEditing</a > - editing grid contents one cell at a time.</p></li >
< li><p><a href="#!/api / Ext.grid.plugin . RowEditing " rel="Ext.grid.plugin . RowEditing " class="docClass">RowEditing</a > - editing grid contents an entire row at a time.</p></li >
< li><p><a href="#!/api / Ext.grid.plugin . DragDrop " rel="Ext.grid.plugin . DragDrop " class="docClass">DragDrop</a > - drag - drop reordering of grid rows.</p></li >
< / Ext.toolbar . Paging " rel="Ext.toolbar . Paging " class="docClass">Paging toolbar</a > - paging through large sets of data.</p></li >
< li><p><a href="#!/api / Ext.grid.plugin . BufferedRenderer " rel="Ext.grid.plugin . BufferedRenderer " class="docClass">Infinite scrolling</a > - another way to handle large sets of data.</p></li >
< li><p><a href="#!/api / Ext.grid.column . " rel="Ext.grid.column . " class="docClass">RowNumberer</a > - automatically numbered rows.</p></li >
< / Ext.grid.feature . Grouping " rel="Ext.grid.feature . Grouping " class="docClass">Grouping</a > - grouping together rows having the same value in a particular field.</p></li >
< / Ext.grid.feature . Summary " rel="Ext.grid.feature . Summary " class="docClass">Summary</a > - a summary row at the bottom of a grid.</p></li >
< / Ext.grid.feature . GroupingSummary " rel="Ext.grid.feature . GroupingSummary " class="docClass">GroupingSummary</a > - a summary row at the bottom of each group.</p></li >
< /ul > % }
{% <p>Grids are an excellent way of showing large amounts of tabular data on the client side. Essentially a supercharged
<code><table></code>, GridPanel makes it easy to fetch, sort and filter large amounts of data.</p>
<p>Grids are composed of two main pieces - a <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Store</a> full of data and a set of columns to render.</p>
<h2>Basic GridPanel</h2>
<pre class='inline-example '><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a>', \{
storeId:'simpsonsStore',
fields:['name', 'email', 'phone'],
data:\{'items':[
\{ 'name': 'Lisa', "email":"lisa\@simpsons.com", "phone":"555-111-1224" \},
\{ 'name': 'Bart', "email":"bart\@simpsons.com", "phone":"555-222-1234" \},
\{ 'name': 'Homer', "email":"home\@simpsons.com", "phone":"555-222-1244" \},
\{ 'name': 'Marge', "email":"marge\@simpsons.com", "phone":"555-222-1254" \}
]\},
proxy: \{
type: 'memory',
reader: \{
type: 'json',
root: 'items'
\}
\}
\});
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
title: 'Simpsons',
store: <a href="#!/api/Ext.data.StoreManager-method-lookup" rel="Ext.data.StoreManager-method-lookup" class="docClass">Ext.data.StoreManager.lookup</a>('simpsonsStore'),
columns: [
\{ text: 'Name', dataIndex: 'name' \},
\{ text: 'Email', dataIndex: 'email', flex: 1 \},
\{ text: 'Phone', dataIndex: 'phone' \}
],
height: 200,
width: 400,
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>()
\});
</code></pre>
<p>The code above produces a simple grid with three columns. We specified a Store which will load JSON data inline.
In most apps we would be placing the grid inside another container and wouldn't need to use the
<a href="#!/api/Ext.grid.Panel-cfg-height" rel="Ext.grid.Panel-cfg-height" class="docClass">height</a>, <a href="#!/api/Ext.grid.Panel-cfg-width" rel="Ext.grid.Panel-cfg-width" class="docClass">width</a> and <a href="#!/api/Ext.grid.Panel-cfg-renderTo" rel="Ext.grid.Panel-cfg-renderTo" class="docClass">renderTo</a> configurations but they are included here to make it easy to get
up and running.</p>
<p>The grid we created above will contain a header bar with a title ('Simpsons'), a row of column headers directly underneath
and finally the grid rows under the headers.</p>
<h2>Configuring columns</h2>
<p>By default, each column is sortable and will toggle between ASC and DESC sorting when you click on its header. Each
column header is also reorderable by default, and each gains a drop-down menu with options to hide and show columns.
It's easy to configure each column - here we use the same example as above and just modify the columns config:</p>
<pre><code>columns: [
\{
text: 'Name',
dataIndex: 'name',
sortable: false,
hideable: false,
flex: 1
\},
\{
text: 'Email',
dataIndex: 'email',
hidden: true
\},
\{
text: 'Phone',
dataIndex: 'phone',
width: 100
\}
]
</code></pre>
<p>We turned off sorting and hiding on the 'Name' column so clicking its header now has no effect. We also made the Email
column hidden by default (it can be shown again by using the menu on any other column). We also set the Phone column to
a fixed with of 100px and flexed the Name column, which means it takes up all remaining width after the other columns
have been accounted for. See the <a href="#!/api/Ext.grid.column.Column" rel="Ext.grid.column.Column" class="docClass">column docs</a> for more details.</p>
<h2>Renderers</h2>
<p>As well as customizing columns, it's easy to alter the rendering of individual cells using renderers. A renderer is
tied to a particular column and is passed the value that would be rendered into each cell in that column. For example,
we could define a renderer function for the email column to turn each email address into a mailto link:</p>
<pre><code>columns: [
\{
text: 'Email',
dataIndex: 'email',
renderer: function(value) \{
return <a href="#!/api/Ext.String-method-format" rel="Ext.String-method-format" class="docClass">Ext.String.format</a>('<a href="mailto:\{0\}">\{1\}</a>', value, value);
\}
\}
]
</code></pre>
<p>See the <a href="#!/api/Ext.grid.column.Column" rel="Ext.grid.column.Column" class="docClass">column docs</a> for more information on renderers.</p>
<h2>Selection Models</h2>
<p>Sometimes all you want is to render data onto the screen for viewing, but usually it's necessary to interact with or
update that data. Grids use a concept called a Selection Model, which is simply a mechanism for selecting some part of
the data in the grid. The two main types of Selection Model are RowSelectionModel, where entire rows are selected, and
CellSelectionModel, where individual cells are selected.</p>
<p>Grids use a Row Selection Model by default, but this is easy to customise like so:</p>
<pre><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
selType: 'cellmodel',
store: ...
\});
</code></pre>
<p>Specifying the <code>cellmodel</code> changes a couple of things. Firstly, clicking on a cell now
selects just that cell (using a <a href="#!/api/Ext.selection.RowModel" rel="Ext.selection.RowModel" class="docClass">rowmodel</a> will select the entire row), and secondly the
keyboard navigation will walk from cell to cell instead of row to row. Cell-based selection models are usually used in
conjunction with editing.</p>
<h2>Sorting & Filtering</h2>
<p>Every grid is attached to a <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Store</a>, which provides multi-sort and filtering capabilities. It's
easy to set up a grid to be sorted from the start:</p>
<pre><code>var myGrid = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
store: \{
fields: ['name', 'email', 'phone'],
sorters: ['name', 'phone']
\},
columns: [
\{ text: 'Name', dataIndex: 'name' \},
\{ text: 'Email', dataIndex: 'email' \}
]
\});
</code></pre>
<p>Sorting at run time is easily accomplished by simply clicking each column header. If you need to perform sorting on
more than one field at run time it's easy to do so by adding new sorters to the store:</p>
<pre><code>myGrid.store.sort([
\{ property: 'name', direction: 'ASC' \},
\{ property: 'email', direction: 'DESC' \}
]);
</code></pre>
<p>See <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a> for examples of filtering.</p>
<h2>State saving</h2>
<p>When configured <a href="#!/api/Ext.grid.Panel-cfg-stateful" rel="Ext.grid.Panel-cfg-stateful" class="docClass">stateful</a>, grids save their column state (order and width) encapsulated within the default
Panel state of changed width and height and collapsed/expanded state.</p>
<p>Each <a href="#!/api/Ext.grid.Panel-cfg-columns" rel="Ext.grid.Panel-cfg-columns" class="docClass">column</a> of the grid may be configured with a <a href="#!/api/Ext.grid.column.Column-cfg-stateId" rel="Ext.grid.column.Column-cfg-stateId" class="docClass">stateId</a> which
identifies that column locally within the grid.</p>
<h2>Plugins and Features</h2>
<p>Grid supports addition of extra functionality through features and plugins:</p>
<ul>
<li><p><a href="#!/api/Ext.grid.plugin.CellEditing" rel="Ext.grid.plugin.CellEditing" class="docClass">CellEditing</a> - editing grid contents one cell at a time.</p></li>
<li><p><a href="#!/api/Ext.grid.plugin.RowEditing" rel="Ext.grid.plugin.RowEditing" class="docClass">RowEditing</a> - editing grid contents an entire row at a time.</p></li>
<li><p><a href="#!/api/Ext.grid.plugin.DragDrop" rel="Ext.grid.plugin.DragDrop" class="docClass">DragDrop</a> - drag-drop reordering of grid rows.</p></li>
<li><p><a href="#!/api/Ext.toolbar.Paging" rel="Ext.toolbar.Paging" class="docClass">Paging toolbar</a> - paging through large sets of data.</p></li>
<li><p><a href="#!/api/Ext.grid.plugin.BufferedRenderer" rel="Ext.grid.plugin.BufferedRenderer" class="docClass">Infinite scrolling</a> - another way to handle large sets of data.</p></li>
<li><p><a href="#!/api/Ext.grid.column.RowNumberer" rel="Ext.grid.column.RowNumberer" class="docClass">RowNumberer</a> - automatically numbered rows.</p></li>
<li><p><a href="#!/api/Ext.grid.feature.Grouping" rel="Ext.grid.feature.Grouping" class="docClass">Grouping</a> - grouping together rows having the same value in a particular field.</p></li>
<li><p><a href="#!/api/Ext.grid.feature.Summary" rel="Ext.grid.feature.Summary" class="docClass">Summary</a> - a summary row at the bottom of a grid.</p></li>
<li><p><a href="#!/api/Ext.grid.feature.GroupingSummary" rel="Ext.grid.feature.GroupingSummary" class="docClass">GroupingSummary</a> - a summary row at the bottom of each group.</p></li>
</ul> %}
*)
class type t =
object('self)
inherit Ext_panel_Table.t
method reconfigure : Ext_data_Store.t Js.t Js.optdef ->
_ Js.t Js.js_array Js.t Js.optdef -> unit Js.meth
(** {% <p>Reconfigures the grid with a new store/columns. Either the store or the columns can be omitted if you don't wish
to change them.</p> %}
{b Parameters}:
{ul {- store: [Ext_data_Store.t Js.t] (optional)
{% <p>The new store.</p> %}
}
{- columns: [_ Js.t Js.js_array Js.t] (optional)
{% <p>An array of column configs</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_panel_Table.configs
method columns : _ Js.t Js.prop
* { % < p > An array of < a href="#!/api / Ext.grid.column . Column " rel="Ext.grid.column . Column " class="docClass">column</a > definition objects which define all columns that appear in this
grid . Each column definition provides the header text for the column , and a definition of where the data for that
column comes from.</p >
< p > This can also be a configuration object for a \{<a href="#!/api / Ext.grid.header . Container " rel="Ext.grid.header . Container " class="docClass">Ext.grid.header . Container</a > HeaderContainer\ } which may override
certain default configurations if necessary . For example , the special layout may be overridden to use a simpler
layout , or one can set default values shared by all columns:</p >
< pre><code > columns : \ {
items : [
\ {
text : " Column A "
: " field_A "
\},\ {
text : " Column B " ,
dataIndex : " field_B "
\ } ,
...
] ,
defaults : \ {
flex : 1
\ }
\ }
< /code></pre > % }
grid. Each column definition provides the header text for the column, and a definition of where the data for that
column comes from.</p>
<p>This can also be a configuration object for a \{<a href="#!/api/Ext.grid.header.Container" rel="Ext.grid.header.Container" class="docClass">Ext.grid.header.Container</a> HeaderContainer\} which may override
certain default configurations if necessary. For example, the special layout may be overridden to use a simpler
layout, or one can set default values shared by all columns:</p>
<pre><code>columns: \{
items: [
\{
text: "Column A"
dataIndex: "field_A"
\},\{
text: "Column B",
dataIndex: "field_B"
\},
...
],
defaults: \{
flex: 1
\}
\}
</code></pre> %}
*)
method rowLines : bool Js.t Js.prop
* { % < p > False to remove row line styling</p > % }
Defaults to : [ true ]
Defaults to: [true]
*)
method viewType : Js.js_string Js.t Js.prop
* { % < p > An xtype of view to use . This is automatically set to ' gridview ' by < a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Grid</a >
and to ' treeview ' by < a href="#!/api / Ext.tree . Panel " rel="Ext.tree . Panel " class="docClass">Tree</a>.</p > % }
Defaults to : [ ' gridview ' ]
and to 'treeview' by <a href="#!/api/Ext.tree.Panel" rel="Ext.tree.Panel" class="docClass">Tree</a>.</p> %}
Defaults to: ['gridview']
*)
end
class type events =
object
inherit Ext_panel_Table.events
method beforereconfigure : (t Js.t -> Ext_data_Store.t Js.t ->
_ Js.t Js.js_array Js.t -> Ext_data_Store.t Js.t ->
Ext_grid_column_Column.t Js.js_array Js.t -> _ Js.t -> unit) Js.callback
Js.writeonly_prop
* { % < p > Fires before a reconfigure to enable modification of incoming Store and > % }
{ b Parameters } :
{ ul { - this : [ Ext_grid_Panel.t Js.t ]
}
{ - store : [ Ext_data_Store.t Js.t ]
{ % < p > The store that was passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - columns : [ _ Js.t Js.js_array Js.t ]
{ % < p > The column configs that were passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - oldStore : [ Ext_data_Store.t Js.t ]
{ % < p > The store that will be replaced</p > % }
}
{ - the : [ Ext_grid_column_Column.t Js.js_array Js.t ]
{ % < p > column headers that will be replaced.</p > % }
}
{ - eOpts : [ _ Js.t ]
{ % < p > The options object passed to < a href="#!/api / Ext.util . Observable - method - addListener " rel="Ext.util . Observable - method - addListener " class="docClass">Ext.util . Observable.addListener</a>.</p > % }
}
}
{b Parameters}:
{ul {- this: [Ext_grid_Panel.t Js.t]
}
{- store: [Ext_data_Store.t Js.t]
{% <p>The store that was passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- columns: [_ Js.t Js.js_array Js.t]
{% <p>The column configs that were passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- oldStore: [Ext_data_Store.t Js.t]
{% <p>The store that will be replaced</p> %}
}
{- the: [Ext_grid_column_Column.t Js.js_array Js.t]
{% <p>column headers that will be replaced.</p> %}
}
{- eOpts: [_ Js.t]
{% <p>The options object passed to <a href="#!/api/Ext.util.Observable-method-addListener" rel="Ext.util.Observable-method-addListener" class="docClass">Ext.util.Observable.addListener</a>.</p> %}
}
}
*)
method reconfigure : (t Js.t -> Ext_data_Store.t Js.t ->
_ Js.t Js.js_array Js.t -> Ext_data_Store.t Js.t ->
Ext_grid_column_Column.t Js.js_array Js.t -> _ Js.t -> unit) Js.callback
Js.writeonly_prop
* { % < p > Fires after a reconfigure.</p > % }
{ b Parameters } :
{ ul { - this : [ Ext_grid_Panel.t Js.t ]
}
{ - store : [ Ext_data_Store.t Js.t ]
{ % < p > The store that was passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - columns : [ _ Js.t Js.js_array Js.t ]
{ % < p > The column configs that were passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - oldStore : [ Ext_data_Store.t Js.t ]
{ % < p > The store that was replaced</p > % }
}
{ - the : [ Ext_grid_column_Column.t Js.js_array Js.t ]
{ % < p > column headers that were replaced.</p > % }
}
{ - eOpts : [ _ Js.t ]
{ % < p > The options object passed to < a href="#!/api / Ext.util . Observable - method - addListener " rel="Ext.util . Observable - method - addListener " class="docClass">Ext.util . Observable.addListener</a>.</p > % }
}
}
{b Parameters}:
{ul {- this: [Ext_grid_Panel.t Js.t]
}
{- store: [Ext_data_Store.t Js.t]
{% <p>The store that was passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- columns: [_ Js.t Js.js_array Js.t]
{% <p>The column configs that were passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- oldStore: [Ext_data_Store.t Js.t]
{% <p>The store that was replaced</p> %}
}
{- the: [Ext_grid_column_Column.t Js.js_array Js.t]
{% <p>column headers that were replaced.</p> %}
}
{- eOpts: [_ Js.t]
{% <p>The options object passed to <a href="#!/api/Ext.util.Observable-method-addListener" rel="Ext.util.Observable-method-addListener" class="docClass">Ext.util.Observable.addListener</a>.</p> %}
}
}
*)
end
class type statics =
object
inherit Ext_panel_Table.statics
end
val of_configs : configs Js.t -> t Js.t
(** [of_configs c] casts a config object [c] to an instance of class [t] *)
val to_configs : t Js.t -> configs Js.t
(** [to_configs o] casts instance [o] of class [t] to a config object *)
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_grid_Panel.mli | ocaml | * {% <p>Reconfigures the grid with a new store/columns. Either the store or the columns can be omitted if you don't wish
to change them.</p> %}
{b Parameters}:
{ul {- store: [Ext_data_Store.t Js.t] (optional)
{% <p>The new store.</p> %}
}
{- columns: [_ Js.t Js.js_array Js.t] (optional)
{% <p>An array of column configs</p> %}
}
}
* [of_configs c] casts a config object [c] to an instance of class [t]
* [to_configs o] casts instance [o] of class [t] to a config object | * Grids are an excellent way of showing large amount ...
{ % < p > Grids are an excellent way of showing large amounts of tabular data on the client side . Essentially a supercharged
< code><table></code > , GridPanel makes it easy to fetch , sort and filter large amounts of data.</p >
< p > Grids are composed of two main pieces - a < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Store</a > full of data and a set of columns to render.</p >
< h2 > Basic GridPanel</h2 >
< pre class='inline - example ' > < code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > ' , \ {
storeId:'simpsonsStore ' ,
fields:['name ' , ' email ' , ' phone ' ] ,
data:\{'items ' : [
\ { ' name ' : ' Lisa ' , " email":"lisa\@simpsons.com " , " phone":"555 - 111 - 1224 " \ } ,
\ { ' name ' : ' ' , " email":"bart\@simpsons.com " , " phone":"555 - 222 - 1234 " \ } ,
\ { ' name ' : ' Homer ' , " email":"home\@simpsons.com " , " phone":"555 - 222 - 1244 " \ } ,
\ { ' name ' : ' Marge ' , " email":"marge\@simpsons.com " , " phone":"555 - 222 - 1254 " \ }
] \ } ,
proxy : \ {
type : ' memory ' ,
reader : \ {
type : ' json ' ,
root : ' items '
\ }
\ }
\ } ) ;
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
title : ' Simpsons ' ,
store : < a href="#!/api / Ext.data . StoreManager - method - lookup " rel="Ext.data . StoreManager - method - lookup " class="docClass">Ext.data . StoreManager.lookup</a>('simpsonsStore ' ) ,
columns : [
\ { text : ' Name ' , dataIndex : ' name ' \ } ,
\ { text : ' Email ' , : ' email ' , flex : 1 \ } ,
\ { text : ' Phone ' , : ' phone ' \ }
] ,
height : 200 ,
width : 400 ,
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( )
\ } ) ;
< /code></pre >
< p > The code above produces a simple grid with three columns . We specified a Store which will load JSON data inline .
In most apps we would be placing the grid inside another container and would n't need to use the
< a href="#!/api / Ext.grid . Panel - cfg - height " rel="Ext.grid . Panel - cfg - height " class="docClass">height</a > , < a href="#!/api / Ext.grid . Panel - cfg - width " rel="Ext.grid . Panel - cfg - width " > and < a href="#!/api / Ext.grid . Panel - cfg - renderTo " rel="Ext.grid . Panel - cfg - renderTo " > configurations but they are included here to make it easy to get
up and p > The grid we created above will contain a header bar with a title ( ' Simpsons ' ) , a row of column headers directly underneath
and finally the grid rows under the >
< h2 > Configuring columns</h2 >
< p > By default , each column is sortable and will toggle between ASC and DESC sorting when you click on its header . Each
column header is also reorderable by default , and each gains a drop - down menu with options to hide and show columns .
It 's easy to configure each column - here we use the same example as above and just modify the columns config:</p >
< pre><code > columns : [
\ {
text : ' Name ' ,
: ' name ' ,
sortable : false ,
hideable : false ,
flex : 1
\ } ,
\ {
text : ' Email ' ,
: ' email ' ,
hidden : true
\ } ,
\ {
text : ' Phone ' ,
: ' phone ' ,
width : 100
\ }
]
< /code></pre >
< p > We turned off sorting and hiding on the ' Name ' column so clicking its header now has no effect . We also made the Email
column hidden by default ( it can be shown again by using the menu on any other column ) . We also set the Phone column to
a fixed with of 100px and flexed the Name column , which means it takes up all remaining width after the other columns
have been accounted for . See the < a href="#!/api / Ext.grid.column . Column " rel="Ext.grid.column . Column " class="docClass">column docs</a > for more details.</p >
< h2 > Renderers</h2 >
< p > As well as customizing columns , it 's easy to alter the rendering of individual cells using renderers . A renderer is
tied to a particular column and is passed the value that would be rendered into each cell in that column . For example ,
we could define a renderer function for the email column to turn each email address into a mailto link:</p >
< pre><code > columns : [
\ {
text : ' Email ' ,
: ' email ' ,
renderer : function(value ) \ {
return < a href="#!/api / Ext . String - method - format " rel="Ext . String - method - format " class="docClass">Ext . String.format</a>('<a href="mailto:\{0\}">\{1\}</a> ; ' , value , value ) ;
\ }
\ }
]
< /code></pre >
< p > See the < a href="#!/api / Ext.grid.column . Column " rel="Ext.grid.column . Column " class="docClass">column docs</a > for more information on renderers.</p >
< h2 > Selection Models</h2 >
< p > Sometimes all you want is to render data onto the screen for viewing , but usually it 's necessary to interact with or
update that data . Grids use a concept called a Selection Model , which is simply a mechanism for selecting some part of
the data in the grid . The two main types of Selection Model are RowSelectionModel , where entire rows are selected , and
CellSelectionModel , where individual cells are selected.</p >
< p > Grids use a Row Selection Model by default , but this is easy to customise like >
< pre><code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
selType : ' cellmodel ' ,
store : ...
\ } ) ;
< /code></pre >
< p > Specifying the < code > cellmodel</code > changes a couple of things . Firstly , clicking on a cell now
selects just that cell ( using a < a href="#!/api / Ext.selection . RowModel " rel="Ext.selection . RowModel " class="docClass">rowmodel</a > will select the entire row ) , and secondly the
keyboard navigation will walk from cell to cell instead of row to row . Cell - based selection models are usually used in
conjunction with editing.</p >
< h2 > Sorting & amp ; Filtering</h2 >
< p > Every grid is attached to a < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Store</a > , which provides multi - sort and filtering capabilities . It 's
easy to set up a grid to be sorted from the start:</p >
< pre><code > var myGrid = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
store : \ {
fields : [ ' name ' , ' email ' , ' phone ' ] ,
sorters : [ ' name ' , ' phone ' ]
\ } ,
columns : [
\ { text : ' Name ' , dataIndex : ' name ' \ } ,
\ { text : ' Email ' , : ' email ' \ }
]
\ } ) ;
< /code></pre >
< p > Sorting at run time is easily accomplished by simply clicking each column header . If you need to perform sorting on
more than one field at run time it 's easy to do so by adding new sorters to the store:</p >
< pre><code > ( [
\ { property : ' name ' , direction : ' ASC ' \ } ,
\ { property : ' email ' , direction : ' DESC ' \ }
] ) ;
< /code></pre >
< p > See < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > for examples of filtering.</p >
< h2 > State p > When configured < a href="#!/api / Ext.grid . Panel - cfg - stateful " rel="Ext.grid . Panel - cfg - stateful " class="docClass">stateful</a > , grids save their column state ( order and width ) encapsulated within the default
Panel state of changed width and height and collapsed / expanded state.</p >
< p > Each < a href="#!/api / Ext.grid . Panel - cfg - columns " rel="Ext.grid . Panel - cfg - columns " class="docClass">column</a > of the grid may be configured with a < a href="#!/api / Ext.grid.column . Column - cfg - stateId " rel="Ext.grid.column . Column - cfg - stateId " class="docClass">stateId</a > which
identifies that column locally within the grid.</p >
< h2 > Plugins and Features</h2 >
< p > Grid supports addition of extra functionality through features and plugins:</p >
< ul >
< li><p><a href="#!/api / Ext.grid.plugin . " class="docClass">CellEditing</a > - editing grid contents one cell at a time.</p></li >
< li><p><a href="#!/api / Ext.grid.plugin . RowEditing " rel="Ext.grid.plugin . RowEditing " class="docClass">RowEditing</a > - editing grid contents an entire row at a time.</p></li >
< li><p><a href="#!/api / Ext.grid.plugin . DragDrop " rel="Ext.grid.plugin . DragDrop " class="docClass">DragDrop</a > - drag - drop reordering of grid rows.</p></li >
< / Ext.toolbar . Paging " rel="Ext.toolbar . Paging " class="docClass">Paging toolbar</a > - paging through large sets of data.</p></li >
< li><p><a href="#!/api / Ext.grid.plugin . BufferedRenderer " rel="Ext.grid.plugin . BufferedRenderer " class="docClass">Infinite scrolling</a > - another way to handle large sets of data.</p></li >
< li><p><a href="#!/api / Ext.grid.column . " rel="Ext.grid.column . " class="docClass">RowNumberer</a > - automatically numbered rows.</p></li >
< / Ext.grid.feature . Grouping " rel="Ext.grid.feature . Grouping " class="docClass">Grouping</a > - grouping together rows having the same value in a particular field.</p></li >
< / Ext.grid.feature . Summary " rel="Ext.grid.feature . Summary " class="docClass">Summary</a > - a summary row at the bottom of a grid.</p></li >
< / Ext.grid.feature . GroupingSummary " rel="Ext.grid.feature . GroupingSummary " class="docClass">GroupingSummary</a > - a summary row at the bottom of each group.</p></li >
< /ul > % }
{% <p>Grids are an excellent way of showing large amounts of tabular data on the client side. Essentially a supercharged
<code><table></code>, GridPanel makes it easy to fetch, sort and filter large amounts of data.</p>
<p>Grids are composed of two main pieces - a <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Store</a> full of data and a set of columns to render.</p>
<h2>Basic GridPanel</h2>
<pre class='inline-example '><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a>', \{
storeId:'simpsonsStore',
fields:['name', 'email', 'phone'],
data:\{'items':[
\{ 'name': 'Lisa', "email":"lisa\@simpsons.com", "phone":"555-111-1224" \},
\{ 'name': 'Bart', "email":"bart\@simpsons.com", "phone":"555-222-1234" \},
\{ 'name': 'Homer', "email":"home\@simpsons.com", "phone":"555-222-1244" \},
\{ 'name': 'Marge', "email":"marge\@simpsons.com", "phone":"555-222-1254" \}
]\},
proxy: \{
type: 'memory',
reader: \{
type: 'json',
root: 'items'
\}
\}
\});
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
title: 'Simpsons',
store: <a href="#!/api/Ext.data.StoreManager-method-lookup" rel="Ext.data.StoreManager-method-lookup" class="docClass">Ext.data.StoreManager.lookup</a>('simpsonsStore'),
columns: [
\{ text: 'Name', dataIndex: 'name' \},
\{ text: 'Email', dataIndex: 'email', flex: 1 \},
\{ text: 'Phone', dataIndex: 'phone' \}
],
height: 200,
width: 400,
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>()
\});
</code></pre>
<p>The code above produces a simple grid with three columns. We specified a Store which will load JSON data inline.
In most apps we would be placing the grid inside another container and wouldn't need to use the
<a href="#!/api/Ext.grid.Panel-cfg-height" rel="Ext.grid.Panel-cfg-height" class="docClass">height</a>, <a href="#!/api/Ext.grid.Panel-cfg-width" rel="Ext.grid.Panel-cfg-width" class="docClass">width</a> and <a href="#!/api/Ext.grid.Panel-cfg-renderTo" rel="Ext.grid.Panel-cfg-renderTo" class="docClass">renderTo</a> configurations but they are included here to make it easy to get
up and running.</p>
<p>The grid we created above will contain a header bar with a title ('Simpsons'), a row of column headers directly underneath
and finally the grid rows under the headers.</p>
<h2>Configuring columns</h2>
<p>By default, each column is sortable and will toggle between ASC and DESC sorting when you click on its header. Each
column header is also reorderable by default, and each gains a drop-down menu with options to hide and show columns.
It's easy to configure each column - here we use the same example as above and just modify the columns config:</p>
<pre><code>columns: [
\{
text: 'Name',
dataIndex: 'name',
sortable: false,
hideable: false,
flex: 1
\},
\{
text: 'Email',
dataIndex: 'email',
hidden: true
\},
\{
text: 'Phone',
dataIndex: 'phone',
width: 100
\}
]
</code></pre>
<p>We turned off sorting and hiding on the 'Name' column so clicking its header now has no effect. We also made the Email
column hidden by default (it can be shown again by using the menu on any other column). We also set the Phone column to
a fixed with of 100px and flexed the Name column, which means it takes up all remaining width after the other columns
have been accounted for. See the <a href="#!/api/Ext.grid.column.Column" rel="Ext.grid.column.Column" class="docClass">column docs</a> for more details.</p>
<h2>Renderers</h2>
<p>As well as customizing columns, it's easy to alter the rendering of individual cells using renderers. A renderer is
tied to a particular column and is passed the value that would be rendered into each cell in that column. For example,
we could define a renderer function for the email column to turn each email address into a mailto link:</p>
<pre><code>columns: [
\{
text: 'Email',
dataIndex: 'email',
renderer: function(value) \{
return <a href="#!/api/Ext.String-method-format" rel="Ext.String-method-format" class="docClass">Ext.String.format</a>('<a href="mailto:\{0\}">\{1\}</a>', value, value);
\}
\}
]
</code></pre>
<p>See the <a href="#!/api/Ext.grid.column.Column" rel="Ext.grid.column.Column" class="docClass">column docs</a> for more information on renderers.</p>
<h2>Selection Models</h2>
<p>Sometimes all you want is to render data onto the screen for viewing, but usually it's necessary to interact with or
update that data. Grids use a concept called a Selection Model, which is simply a mechanism for selecting some part of
the data in the grid. The two main types of Selection Model are RowSelectionModel, where entire rows are selected, and
CellSelectionModel, where individual cells are selected.</p>
<p>Grids use a Row Selection Model by default, but this is easy to customise like so:</p>
<pre><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
selType: 'cellmodel',
store: ...
\});
</code></pre>
<p>Specifying the <code>cellmodel</code> changes a couple of things. Firstly, clicking on a cell now
selects just that cell (using a <a href="#!/api/Ext.selection.RowModel" rel="Ext.selection.RowModel" class="docClass">rowmodel</a> will select the entire row), and secondly the
keyboard navigation will walk from cell to cell instead of row to row. Cell-based selection models are usually used in
conjunction with editing.</p>
<h2>Sorting & Filtering</h2>
<p>Every grid is attached to a <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Store</a>, which provides multi-sort and filtering capabilities. It's
easy to set up a grid to be sorted from the start:</p>
<pre><code>var myGrid = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
store: \{
fields: ['name', 'email', 'phone'],
sorters: ['name', 'phone']
\},
columns: [
\{ text: 'Name', dataIndex: 'name' \},
\{ text: 'Email', dataIndex: 'email' \}
]
\});
</code></pre>
<p>Sorting at run time is easily accomplished by simply clicking each column header. If you need to perform sorting on
more than one field at run time it's easy to do so by adding new sorters to the store:</p>
<pre><code>myGrid.store.sort([
\{ property: 'name', direction: 'ASC' \},
\{ property: 'email', direction: 'DESC' \}
]);
</code></pre>
<p>See <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a> for examples of filtering.</p>
<h2>State saving</h2>
<p>When configured <a href="#!/api/Ext.grid.Panel-cfg-stateful" rel="Ext.grid.Panel-cfg-stateful" class="docClass">stateful</a>, grids save their column state (order and width) encapsulated within the default
Panel state of changed width and height and collapsed/expanded state.</p>
<p>Each <a href="#!/api/Ext.grid.Panel-cfg-columns" rel="Ext.grid.Panel-cfg-columns" class="docClass">column</a> of the grid may be configured with a <a href="#!/api/Ext.grid.column.Column-cfg-stateId" rel="Ext.grid.column.Column-cfg-stateId" class="docClass">stateId</a> which
identifies that column locally within the grid.</p>
<h2>Plugins and Features</h2>
<p>Grid supports addition of extra functionality through features and plugins:</p>
<ul>
<li><p><a href="#!/api/Ext.grid.plugin.CellEditing" rel="Ext.grid.plugin.CellEditing" class="docClass">CellEditing</a> - editing grid contents one cell at a time.</p></li>
<li><p><a href="#!/api/Ext.grid.plugin.RowEditing" rel="Ext.grid.plugin.RowEditing" class="docClass">RowEditing</a> - editing grid contents an entire row at a time.</p></li>
<li><p><a href="#!/api/Ext.grid.plugin.DragDrop" rel="Ext.grid.plugin.DragDrop" class="docClass">DragDrop</a> - drag-drop reordering of grid rows.</p></li>
<li><p><a href="#!/api/Ext.toolbar.Paging" rel="Ext.toolbar.Paging" class="docClass">Paging toolbar</a> - paging through large sets of data.</p></li>
<li><p><a href="#!/api/Ext.grid.plugin.BufferedRenderer" rel="Ext.grid.plugin.BufferedRenderer" class="docClass">Infinite scrolling</a> - another way to handle large sets of data.</p></li>
<li><p><a href="#!/api/Ext.grid.column.RowNumberer" rel="Ext.grid.column.RowNumberer" class="docClass">RowNumberer</a> - automatically numbered rows.</p></li>
<li><p><a href="#!/api/Ext.grid.feature.Grouping" rel="Ext.grid.feature.Grouping" class="docClass">Grouping</a> - grouping together rows having the same value in a particular field.</p></li>
<li><p><a href="#!/api/Ext.grid.feature.Summary" rel="Ext.grid.feature.Summary" class="docClass">Summary</a> - a summary row at the bottom of a grid.</p></li>
<li><p><a href="#!/api/Ext.grid.feature.GroupingSummary" rel="Ext.grid.feature.GroupingSummary" class="docClass">GroupingSummary</a> - a summary row at the bottom of each group.</p></li>
</ul> %}
*)
class type t =
object('self)
inherit Ext_panel_Table.t
method reconfigure : Ext_data_Store.t Js.t Js.optdef ->
_ Js.t Js.js_array Js.t Js.optdef -> unit Js.meth
end
class type configs =
object('self)
inherit Ext_panel_Table.configs
method columns : _ Js.t Js.prop
* { % < p > An array of < a href="#!/api / Ext.grid.column . Column " rel="Ext.grid.column . Column " class="docClass">column</a > definition objects which define all columns that appear in this
grid . Each column definition provides the header text for the column , and a definition of where the data for that
column comes from.</p >
< p > This can also be a configuration object for a \{<a href="#!/api / Ext.grid.header . Container " rel="Ext.grid.header . Container " class="docClass">Ext.grid.header . Container</a > HeaderContainer\ } which may override
certain default configurations if necessary . For example , the special layout may be overridden to use a simpler
layout , or one can set default values shared by all columns:</p >
< pre><code > columns : \ {
items : [
\ {
text : " Column A "
: " field_A "
\},\ {
text : " Column B " ,
dataIndex : " field_B "
\ } ,
...
] ,
defaults : \ {
flex : 1
\ }
\ }
< /code></pre > % }
grid. Each column definition provides the header text for the column, and a definition of where the data for that
column comes from.</p>
<p>This can also be a configuration object for a \{<a href="#!/api/Ext.grid.header.Container" rel="Ext.grid.header.Container" class="docClass">Ext.grid.header.Container</a> HeaderContainer\} which may override
certain default configurations if necessary. For example, the special layout may be overridden to use a simpler
layout, or one can set default values shared by all columns:</p>
<pre><code>columns: \{
items: [
\{
text: "Column A"
dataIndex: "field_A"
\},\{
text: "Column B",
dataIndex: "field_B"
\},
...
],
defaults: \{
flex: 1
\}
\}
</code></pre> %}
*)
method rowLines : bool Js.t Js.prop
* { % < p > False to remove row line styling</p > % }
Defaults to : [ true ]
Defaults to: [true]
*)
method viewType : Js.js_string Js.t Js.prop
* { % < p > An xtype of view to use . This is automatically set to ' gridview ' by < a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Grid</a >
and to ' treeview ' by < a href="#!/api / Ext.tree . Panel " rel="Ext.tree . Panel " class="docClass">Tree</a>.</p > % }
Defaults to : [ ' gridview ' ]
and to 'treeview' by <a href="#!/api/Ext.tree.Panel" rel="Ext.tree.Panel" class="docClass">Tree</a>.</p> %}
Defaults to: ['gridview']
*)
end
class type events =
object
inherit Ext_panel_Table.events
method beforereconfigure : (t Js.t -> Ext_data_Store.t Js.t ->
_ Js.t Js.js_array Js.t -> Ext_data_Store.t Js.t ->
Ext_grid_column_Column.t Js.js_array Js.t -> _ Js.t -> unit) Js.callback
Js.writeonly_prop
* { % < p > Fires before a reconfigure to enable modification of incoming Store and > % }
{ b Parameters } :
{ ul { - this : [ Ext_grid_Panel.t Js.t ]
}
{ - store : [ Ext_data_Store.t Js.t ]
{ % < p > The store that was passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - columns : [ _ Js.t Js.js_array Js.t ]
{ % < p > The column configs that were passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - oldStore : [ Ext_data_Store.t Js.t ]
{ % < p > The store that will be replaced</p > % }
}
{ - the : [ Ext_grid_column_Column.t Js.js_array Js.t ]
{ % < p > column headers that will be replaced.</p > % }
}
{ - eOpts : [ _ Js.t ]
{ % < p > The options object passed to < a href="#!/api / Ext.util . Observable - method - addListener " rel="Ext.util . Observable - method - addListener " class="docClass">Ext.util . Observable.addListener</a>.</p > % }
}
}
{b Parameters}:
{ul {- this: [Ext_grid_Panel.t Js.t]
}
{- store: [Ext_data_Store.t Js.t]
{% <p>The store that was passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- columns: [_ Js.t Js.js_array Js.t]
{% <p>The column configs that were passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- oldStore: [Ext_data_Store.t Js.t]
{% <p>The store that will be replaced</p> %}
}
{- the: [Ext_grid_column_Column.t Js.js_array Js.t]
{% <p>column headers that will be replaced.</p> %}
}
{- eOpts: [_ Js.t]
{% <p>The options object passed to <a href="#!/api/Ext.util.Observable-method-addListener" rel="Ext.util.Observable-method-addListener" class="docClass">Ext.util.Observable.addListener</a>.</p> %}
}
}
*)
method reconfigure : (t Js.t -> Ext_data_Store.t Js.t ->
_ Js.t Js.js_array Js.t -> Ext_data_Store.t Js.t ->
Ext_grid_column_Column.t Js.js_array Js.t -> _ Js.t -> unit) Js.callback
Js.writeonly_prop
* { % < p > Fires after a reconfigure.</p > % }
{ b Parameters } :
{ ul { - this : [ Ext_grid_Panel.t Js.t ]
}
{ - store : [ Ext_data_Store.t Js.t ]
{ % < p > The store that was passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - columns : [ _ Js.t Js.js_array Js.t ]
{ % < p > The column configs that were passed to the < a href="#!/api / Ext.grid . Panel - method - reconfigure " rel="Ext.grid . Panel - method - reconfigure " class="docClass">reconfigure</a > method</p > % }
}
{ - oldStore : [ Ext_data_Store.t Js.t ]
{ % < p > The store that was replaced</p > % }
}
{ - the : [ Ext_grid_column_Column.t Js.js_array Js.t ]
{ % < p > column headers that were replaced.</p > % }
}
{ - eOpts : [ _ Js.t ]
{ % < p > The options object passed to < a href="#!/api / Ext.util . Observable - method - addListener " rel="Ext.util . Observable - method - addListener " class="docClass">Ext.util . Observable.addListener</a>.</p > % }
}
}
{b Parameters}:
{ul {- this: [Ext_grid_Panel.t Js.t]
}
{- store: [Ext_data_Store.t Js.t]
{% <p>The store that was passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- columns: [_ Js.t Js.js_array Js.t]
{% <p>The column configs that were passed to the <a href="#!/api/Ext.grid.Panel-method-reconfigure" rel="Ext.grid.Panel-method-reconfigure" class="docClass">reconfigure</a> method</p> %}
}
{- oldStore: [Ext_data_Store.t Js.t]
{% <p>The store that was replaced</p> %}
}
{- the: [Ext_grid_column_Column.t Js.js_array Js.t]
{% <p>column headers that were replaced.</p> %}
}
{- eOpts: [_ Js.t]
{% <p>The options object passed to <a href="#!/api/Ext.util.Observable-method-addListener" rel="Ext.util.Observable-method-addListener" class="docClass">Ext.util.Observable.addListener</a>.</p> %}
}
}
*)
end
class type statics =
object
inherit Ext_panel_Table.statics
end
val of_configs : configs Js.t -> t Js.t
val to_configs : t Js.t -> configs Js.t
|
76685981de938e400de1e0d7125f4a296647904a28dfd3a45bfa60f887d28313 | tschady/advent-of-code | d12.clj | (ns aoc.2017.d12
(:require [aoc.file-util :as file-util]
[clojure.string :as str]
[ubergraph.alg :as alg]
[ubergraph.core :as uber]))
(def input (file-util/read-lines "2017/d12.txt"))
(defn parse-line [s] (read-string (str "{" (str/replace s #"<->" "[") "]}")))
(defn make-graph [lines] (uber/graph (apply merge (map parse-line lines))))
(defn find-groups [graph] (alg/connected-components graph))
(defn part-1 [input]
(count (set (first (filter #(some #{0} %) (find-groups (make-graph input)))))))
(defn part-2 [input] (count (find-groups (make-graph input))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/9cd0cbbbbeadd083b9030f21e49ca1ac26aee53a/src/aoc/2017/d12.clj | clojure | (ns aoc.2017.d12
(:require [aoc.file-util :as file-util]
[clojure.string :as str]
[ubergraph.alg :as alg]
[ubergraph.core :as uber]))
(def input (file-util/read-lines "2017/d12.txt"))
(defn parse-line [s] (read-string (str "{" (str/replace s #"<->" "[") "]}")))
(defn make-graph [lines] (uber/graph (apply merge (map parse-line lines))))
(defn find-groups [graph] (alg/connected-components graph))
(defn part-1 [input]
(count (set (first (filter #(some #{0} %) (find-groups (make-graph input)))))))
(defn part-2 [input] (count (find-groups (make-graph input))))
| |
c2a89f29a938daa92f7017a82410f8a1f354357aeb348817f2883ad992fdd02b | azimut/shiny | render.lisp | (in-package :shiny)
;;--------------------------------------------------
;; 3D - g-pnt with tangent info in tb-data AND textures
(defun-g vert-with-tbdata
((vert g-pnt) (tb tb-data)
&uniform
(model-world :mat4)
(world-view :mat4)
(view-clip :mat4)
(scale :float)
Parallax vars
(light-pos :vec3)
(cam-pos :vec3))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(uv (treat-uvs (tex vert)))
(norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos))
(t0 (normalize
(s~ (* model-world (v! (tb-data-tangent tb) 0))
:xyz)))
(n0 (normalize
(s~ (* model-world (v! norm 0))
:xyz)))
(t0 (normalize (- t0 (* (dot t0 n0) n0))))
(b0 (cross n0 t0))
(tbn (mat3 t0 b0 n0)))
(values clip-pos
(treat-uvs uv)
norm
(s~ world-pos :xyz)
tbn
(* tbn light-pos)
(* tbn cam-pos)
(* tbn (s~ world-pos :xyz)))))
(defun-g frag-tex-tbn ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d)
(normap :sampler-2d)
(height-map :sampler-2d))
(let* ((light-pos *pointlight-pos*)
Parallax
(tan-cam-dir (- tan-cam-pos tan-frag-pos))
(newuv (parallax-mapping uv tan-cam-dir height-map .1))
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (expt (s~ (texture albedo newuv) :xyz)
(vec3 2.2)))
(normal (norm-from-map normap newuv))
(normal (normalize (* tbn normal))))
(values
( v ! final - color 1 )
( v ! 1 1 1 1 )
;;frag-pos
(normalize frag-norm))))
(defpipeline-g generic-tex-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (frag-tex-tbn :vec2 :vec3 :vec3 :mat3
Parallax
:vec3 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - g-pnt mesh without tangents
(defun-g vert
((vert g-pnt) &uniform
(model-world :mat4) (world-view :mat4) (view-clip :mat4)
(scale :float))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(tex (tex vert))
(world-norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos)))
(values clip-pos
tex
world-norm
(s~ world-pos :xyz))))
;; -index.php?page=-Point+Light+Attenuation
(defun-g frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(time :float)
(color :vec3)
(cam-pos :vec3))
(let* (
;;--------------------
(final-color color)
(final-color
(dir-light-apply final-color
(v! 20 20 20)
(v! 0 1000 1000)
frag-pos
frag-norm))
(final-color
(point-light-apply final-color
(v! 10 10 10)
*light-pos*
frag-pos
frag-norm
1f0
0.014 0.07)))
(values (v! final-color 1)
(v! 0 1 0 1))))
;;--------------------------------------------------
2D - Post Processing
(defun-g frag-2d ((uv :vec2)
&uniform
(sam :sampler-2d)
(sam2 :sampler-2d)
(samd :sampler-2d))
(let* (;; (color (defered-fog
; ; ( v ! .5 .6 .7 )
( v ! )
;; uv
;; samd))
(color (s~ (texture sam uv) :xyz))
(color2 (s~ (texture sam2 uv) :xyz))
;; (color
( s~ ( nineveh.anti - aliasing : ( v2 ! ( / 1 320f0 ) ) ) : xyz ) )
(final-color (+ color color2))
(ldr (tone-map-reinhard final-color *exposure*))
(luma (rgb->luma-bt601 ldr))
)
( v ! ( pow ldr ( vec3 2.2 ) ) 1 )
(v! ldr luma)
;;(v! (- 1 (x color)) 0 0 1)
( v ! color 1 )
( v ! ldr 1 )
))
(defpipeline-g generic-2d-pipe (:points)
:fragment (frag-2d :vec2))
;;--------------------------------------------------
;; 3D - g-pnt mesh with light shading
(defpipeline-g generic-pipe ()
:vertex (vert g-pnt)
:fragment (frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
(defun-g frag-tex ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d))
(let* ((light-pos *pointlight-pos*)
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (expt (s~ (texture albedo (* 20 uv)) :xyz)
(vec3 2.2)))
;;--------------------
;;(normal (normalize frag-norm))
;;(nfm (norm-from-map normap uv))
(color (apply-fog color
(v! .5 .6 .7)
(length (- frag-pos cam-pos))
cam-pos
(normalize (- frag-pos cam-pos)))))
(v! color 1)))
(defpipeline-g tex-pipe ()
:vertex (vert g-pnt)
:fragment (frag-tex :vec2 :vec3 :vec3))
;;--------------------------------------------------
(defun-g pbr-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(samd :sampler-2d)
(uv-repeat :float)
(uv-speed :float)
(time :float)
(color :vec3)
;; Lighting
(light-pos :vec3)
(cam-pos :vec3)
;; PBR
(metallic :float)
(albedo :sampler-2d)
(ao-map :sampler-2d)
(height-map :sampler-2d)
(normal-map :sampler-2d)
(rough-map :sampler-2d)
IBL
(brdf-lut :sampler-2d)
(prefilter-map :sampler-cube)
(irradiance-map :sampler-cube))
(let* (;; First change UV, then parallax!
(uv (+ (* uv uv-repeat)
(v! 0 (* uv-speed time))))
(uv (parallax-mapping-offset-flipped
uv
(normalize (- tan-cam-pos tan-frag-pos))
height-map
.03))
(roughness (x (texture rough-map uv)))
(ao (x (texture ao-map uv)))
(color (* color (expt (s~ (texture albedo uv) :xyz)
(vec3 2.2))))
;; Normal Mapping
;;(normal (normalize frag-norm))
(normal (norm-from-map normal-map uv))
(normal (normalize (* tbn normal)))
;;----------------------------------------
;; PBR
;; metallic
(n normal)
(v (normalize (- cam-pos frag-pos)))
(metallic .1)
(f0 (vec3 .04))
;;(f0 color)
(f0 (mix f0 color metallic))
;; pbr - reflectance equation
(lo (vec3 0f0))
;; lights START
(lo (+ lo (pbr-direct-lum light-pos
frag-pos
v
n
roughness
f0
metallic
color)))
( lo ( ( pbr - point - lum light - pos
;; frag-pos
;; v
;; n
;; roughness
;; f0
;; metallic
;; color)))
;; ---------- END
;;(ambient (* color ao (vec3 .03)))
;; (ambient (pbr-ambient-map-r irradiance-map
;; color
;; ao n v f0
;; roughness))
(r (reflect (- v) n))
(f (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(ks f)
(kd (* (- 1 ks) (- 1 metallic)))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance color))
(prefiltered-color (s~ (texture-lod prefilter-map
r
(* roughness 4f0))
:xyz))
(env-brdf (texture brdf-lut (v! (max (dot n v) 0) (* roughness 4f0))))
(specular (* prefiltered-color (+ (* f (x env-brdf)) (y env-brdf))))
(ambient (* (+ specular (* kd diffuse)) ao))
(final-color (+ ambient lo))
;; Fog
(final-color
(fog-exp2-apply final-color
(v! .18 .17843138 .1552941)
;;(v! .2 .3 .4)
frag-pos
cam-pos .03))
)
(v! final-color 1)
;;(v! uv 0 1)
( v ! color 1 )
))
(defpipeline-g pbr-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (pbr-frag :vec2 :vec3 :vec3
:mat3 :vec3 :vec3 :vec3))
;;--------------------------------------------------
(defun-g pbr-simple-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(light-pos :vec3)
(time :float)
(roughness :float)
(metallic :float)
(color :vec3)
(cam-pos :vec3)
IBL
(irradiance-map :sampler-cube)
(prefilter-map :sampler-cube)
(brdf-lut :sampler-2d))
(let* (;; First change UV, then parallax!
(uv (treat-uvs uv))
(normal (normalize frag-norm))
(ao 1f0)
(color color)
;;----------------------------------------
;; PBR
;; metallic
;;(f0 (vec3 .04))
(f0 color)
(f0 (mix f0 color metallic))
;; pbr - reflectance equation
(n normal)
(v (normalize (- cam-pos frag-pos)))
(lo (vec3 0f0))
;; lights START
(lo (+ lo (pbr-direct-lum light-pos
frag-pos
v
n
roughness
f0
metallic
color)))
;; ---------- END
(r (reflect (- v) n))
(f (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(ks f)
(kd (* (- 1 ks) (- 1 metallic)))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance color))
(prefiltered-color (s~ (texture-lod prefilter-map
r
(* roughness 4f0))
:xyz))
(env-brdf (texture brdf-lut (v! (max (dot n v) 0) (* roughness 4f0))))
(specular (* prefiltered-color (+ (* f (x env-brdf)) (y env-brdf))))
(ambient (* (+ specular (* kd diffuse)) ao))
;; (ambient (pbr-ambient-map-r irradiance-map
;; color
;; ao n v f0
;; roughness))
;;(ambient (* color ao (vec3 .3)))
(final-color (+ ambient lo))
;; Fog
;; (final-color
( fog - exp2 - apply final - color
;; (v! 0 0 0)
;; frag-pos
;; cam-pos .03))
)
(v! final-color 1)))
;;----------------------------------------
;; Functions to apply the Irradiance Map ONLY
(defun-g pbr-ambient-map ((irradiance-map :sampler-cube)
(albedo :vec3)
(ao :float)
(n :vec3)
(v :vec3)
(f0 :vec3))
(let* ((ks (fresnel-schlick (max (dot n v) 0) f0))
(kd (- 1 ks))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance albedo)))
(* diffuse kd ao)))
(defun-g fresnel-schlick-roughness ((cos-theta :float)
(f0 :vec3)
(roughness :float))
(+ f0
(* (- (max (vec3 (- 1 roughness))
f0)
f0)
(pow (- 1 cos-theta) 5f0))))
(defun-g pbr-ambient-map-r ((irradiance-map :sampler-cube)
(albedo :vec3)
(ao :float)
(n :vec3)
(v :vec3)
(f0 :vec3)
(roughness :float))
(let* ((ks (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(kd (- 1 ks))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance albedo)))
(* diffuse kd ao)))
(defpipeline-g pbr-simple-pipe ()
:vertex (vert g-pnt)
:fragment (pbr-simple-frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
;; Wind - Raymarching
;;
(defun-g height ((p :vec2))
(multf p (vec2 .2))
(+ (* .4 (sin (y p)))
(* .4 (sin (x p)))))
;;--------------------------------------------------
(defun-g tri ((x :float))
(abs (- (fract x) .5)))
(defun-g tri3 ((p :vec3))
(v! (tri (+ (z p) (tri (y p))))
(tri (+ (z p) (tri (x p))))
(tri (+ (y p) (tri (x p))))))
(defun-g tri-noise-3d ((p :vec3))
(let ((z 1.4)
(rz 0f0)
(bp (vec3 0f0)))
(dotimes (i 4)
(let ((dg (tri3 bp)))
(incf p dg)
(multf bp (vec3 2f0))
(multf z 1.5)
(multf p (vec3 1.2))
(incf rz (/ (tri (+ (z p) (tri (+ (x p) (tri (y p))))))
z))
(incf bp (vec3 .14))))
rz))
(defun-g fogmap ((p :vec3)
(d :float)
(time :float))
(incf (x p) time)
(incf (z p) (* time .5))
(* (tri-noise-3d (/ (* p 2.2) (+ d 8f0)))
(smoothstep .7 .0 (y p))))
(defun-g fog ((col :vec3)
(ro :vec3)
(rd :vec3)
(mt :float)
(time :float))
(let ((d .5))
(dotimes (i 7)
(let* ((pos (+ ro (* d rd)))
(rz (fogmap pos d time)))
(setf col (mix col (v! .85 .65 .5) (clamp (* rz (smoothstep d (* 1.8 d) mt)) 0f0 1f0)))
(multf d 1.8)
(if (> d mt) (break))))
col))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/examples/room/render.lisp | lisp | --------------------------------------------------
3D - g-pnt with tangent info in tb-data AND textures
---------
--------------------
--------------------
frag-pos
--------------------------------------------------
3D - g-pnt mesh without tangents
-index.php?page=-Point+Light+Attenuation
--------------------
--------------------------------------------------
(color (defered-fog
; ( v ! .5 .6 .7 )
uv
samd))
(color
(v! (- 1 (x color)) 0 0 1)
--------------------------------------------------
3D - g-pnt mesh with light shading
--------------------------------------------------
---------
--------------------
--------------------
--------------------
(normal (normalize frag-norm))
(nfm (norm-from-map normap uv))
--------------------------------------------------
Lighting
PBR
First change UV, then parallax!
Normal Mapping
(normal (normalize frag-norm))
----------------------------------------
PBR
metallic
(f0 color)
pbr - reflectance equation
lights START
frag-pos
v
n
roughness
f0
metallic
color)))
---------- END
(ambient (* color ao (vec3 .03)))
(ambient (pbr-ambient-map-r irradiance-map
color
ao n v f0
roughness))
Fog
(v! .2 .3 .4)
(v! uv 0 1)
--------------------------------------------------
First change UV, then parallax!
----------------------------------------
PBR
metallic
(f0 (vec3 .04))
pbr - reflectance equation
lights START
---------- END
(ambient (pbr-ambient-map-r irradiance-map
color
ao n v f0
roughness))
(ambient (* color ao (vec3 .3)))
Fog
(final-color
(v! 0 0 0)
frag-pos
cam-pos .03))
----------------------------------------
Functions to apply the Irradiance Map ONLY
--------------------------------------------------
Wind - Raymarching
-------------------------------------------------- | (in-package :shiny)
(defun-g vert-with-tbdata
((vert g-pnt) (tb tb-data)
&uniform
(model-world :mat4)
(world-view :mat4)
(view-clip :mat4)
(scale :float)
Parallax vars
(light-pos :vec3)
(cam-pos :vec3))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(uv (treat-uvs (tex vert)))
(norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos))
(t0 (normalize
(s~ (* model-world (v! (tb-data-tangent tb) 0))
:xyz)))
(n0 (normalize
(s~ (* model-world (v! norm 0))
:xyz)))
(t0 (normalize (- t0 (* (dot t0 n0) n0))))
(b0 (cross n0 t0))
(tbn (mat3 t0 b0 n0)))
(values clip-pos
(treat-uvs uv)
norm
(s~ world-pos :xyz)
tbn
(* tbn light-pos)
(* tbn cam-pos)
(* tbn (s~ world-pos :xyz)))))
(defun-g frag-tex-tbn ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d)
(normap :sampler-2d)
(height-map :sampler-2d))
(let* ((light-pos *pointlight-pos*)
Parallax
(tan-cam-dir (- tan-cam-pos tan-frag-pos))
(newuv (parallax-mapping uv tan-cam-dir height-map .1))
(light-color (v! 1 1 1))
(light-strength 1f0)
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
(color (expt (s~ (texture albedo newuv) :xyz)
(vec3 2.2)))
(normal (norm-from-map normap newuv))
(normal (normalize (* tbn normal))))
(values
( v ! final - color 1 )
( v ! 1 1 1 1 )
(normalize frag-norm))))
(defpipeline-g generic-tex-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (frag-tex-tbn :vec2 :vec3 :vec3 :mat3
Parallax
:vec3 :vec3 :vec3))
(defun-g vert
((vert g-pnt) &uniform
(model-world :mat4) (world-view :mat4) (view-clip :mat4)
(scale :float))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(tex (tex vert))
(world-norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos)))
(values clip-pos
tex
world-norm
(s~ world-pos :xyz))))
(defun-g frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(time :float)
(color :vec3)
(cam-pos :vec3))
(let* (
(final-color color)
(final-color
(dir-light-apply final-color
(v! 20 20 20)
(v! 0 1000 1000)
frag-pos
frag-norm))
(final-color
(point-light-apply final-color
(v! 10 10 10)
*light-pos*
frag-pos
frag-norm
1f0
0.014 0.07)))
(values (v! final-color 1)
(v! 0 1 0 1))))
2D - Post Processing
(defun-g frag-2d ((uv :vec2)
&uniform
(sam :sampler-2d)
(sam2 :sampler-2d)
(samd :sampler-2d))
( v ! )
(color (s~ (texture sam uv) :xyz))
(color2 (s~ (texture sam2 uv) :xyz))
( s~ ( nineveh.anti - aliasing : ( v2 ! ( / 1 320f0 ) ) ) : xyz ) )
(final-color (+ color color2))
(ldr (tone-map-reinhard final-color *exposure*))
(luma (rgb->luma-bt601 ldr))
)
( v ! ( pow ldr ( vec3 2.2 ) ) 1 )
(v! ldr luma)
( v ! color 1 )
( v ! ldr 1 )
))
(defpipeline-g generic-2d-pipe (:points)
:fragment (frag-2d :vec2))
(defpipeline-g generic-pipe ()
:vertex (vert g-pnt)
:fragment (frag :vec2 :vec3 :vec3))
(defun-g frag-tex ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d))
(let* ((light-pos *pointlight-pos*)
(light-color (v! 1 1 1))
(light-strength 1f0)
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
(color (expt (s~ (texture albedo (* 20 uv)) :xyz)
(vec3 2.2)))
(color (apply-fog color
(v! .5 .6 .7)
(length (- frag-pos cam-pos))
cam-pos
(normalize (- frag-pos cam-pos)))))
(v! color 1)))
(defpipeline-g tex-pipe ()
:vertex (vert g-pnt)
:fragment (frag-tex :vec2 :vec3 :vec3))
(defun-g pbr-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(samd :sampler-2d)
(uv-repeat :float)
(uv-speed :float)
(time :float)
(color :vec3)
(light-pos :vec3)
(cam-pos :vec3)
(metallic :float)
(albedo :sampler-2d)
(ao-map :sampler-2d)
(height-map :sampler-2d)
(normal-map :sampler-2d)
(rough-map :sampler-2d)
IBL
(brdf-lut :sampler-2d)
(prefilter-map :sampler-cube)
(irradiance-map :sampler-cube))
(uv (+ (* uv uv-repeat)
(v! 0 (* uv-speed time))))
(uv (parallax-mapping-offset-flipped
uv
(normalize (- tan-cam-pos tan-frag-pos))
height-map
.03))
(roughness (x (texture rough-map uv)))
(ao (x (texture ao-map uv)))
(color (* color (expt (s~ (texture albedo uv) :xyz)
(vec3 2.2))))
(normal (norm-from-map normal-map uv))
(normal (normalize (* tbn normal)))
(n normal)
(v (normalize (- cam-pos frag-pos)))
(metallic .1)
(f0 (vec3 .04))
(f0 (mix f0 color metallic))
(lo (vec3 0f0))
(lo (+ lo (pbr-direct-lum light-pos
frag-pos
v
n
roughness
f0
metallic
color)))
( lo ( ( pbr - point - lum light - pos
(r (reflect (- v) n))
(f (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(ks f)
(kd (* (- 1 ks) (- 1 metallic)))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance color))
(prefiltered-color (s~ (texture-lod prefilter-map
r
(* roughness 4f0))
:xyz))
(env-brdf (texture brdf-lut (v! (max (dot n v) 0) (* roughness 4f0))))
(specular (* prefiltered-color (+ (* f (x env-brdf)) (y env-brdf))))
(ambient (* (+ specular (* kd diffuse)) ao))
(final-color (+ ambient lo))
(final-color
(fog-exp2-apply final-color
(v! .18 .17843138 .1552941)
frag-pos
cam-pos .03))
)
(v! final-color 1)
( v ! color 1 )
))
(defpipeline-g pbr-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (pbr-frag :vec2 :vec3 :vec3
:mat3 :vec3 :vec3 :vec3))
(defun-g pbr-simple-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(light-pos :vec3)
(time :float)
(roughness :float)
(metallic :float)
(color :vec3)
(cam-pos :vec3)
IBL
(irradiance-map :sampler-cube)
(prefilter-map :sampler-cube)
(brdf-lut :sampler-2d))
(uv (treat-uvs uv))
(normal (normalize frag-norm))
(ao 1f0)
(color color)
(f0 color)
(f0 (mix f0 color metallic))
(n normal)
(v (normalize (- cam-pos frag-pos)))
(lo (vec3 0f0))
(lo (+ lo (pbr-direct-lum light-pos
frag-pos
v
n
roughness
f0
metallic
color)))
(r (reflect (- v) n))
(f (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(ks f)
(kd (* (- 1 ks) (- 1 metallic)))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance color))
(prefiltered-color (s~ (texture-lod prefilter-map
r
(* roughness 4f0))
:xyz))
(env-brdf (texture brdf-lut (v! (max (dot n v) 0) (* roughness 4f0))))
(specular (* prefiltered-color (+ (* f (x env-brdf)) (y env-brdf))))
(ambient (* (+ specular (* kd diffuse)) ao))
(final-color (+ ambient lo))
( fog - exp2 - apply final - color
)
(v! final-color 1)))
(defun-g pbr-ambient-map ((irradiance-map :sampler-cube)
(albedo :vec3)
(ao :float)
(n :vec3)
(v :vec3)
(f0 :vec3))
(let* ((ks (fresnel-schlick (max (dot n v) 0) f0))
(kd (- 1 ks))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance albedo)))
(* diffuse kd ao)))
(defun-g fresnel-schlick-roughness ((cos-theta :float)
(f0 :vec3)
(roughness :float))
(+ f0
(* (- (max (vec3 (- 1 roughness))
f0)
f0)
(pow (- 1 cos-theta) 5f0))))
(defun-g pbr-ambient-map-r ((irradiance-map :sampler-cube)
(albedo :vec3)
(ao :float)
(n :vec3)
(v :vec3)
(f0 :vec3)
(roughness :float))
(let* ((ks (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(kd (- 1 ks))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance albedo)))
(* diffuse kd ao)))
(defpipeline-g pbr-simple-pipe ()
:vertex (vert g-pnt)
:fragment (pbr-simple-frag :vec2 :vec3 :vec3))
(defun-g height ((p :vec2))
(multf p (vec2 .2))
(+ (* .4 (sin (y p)))
(* .4 (sin (x p)))))
(defun-g tri ((x :float))
(abs (- (fract x) .5)))
(defun-g tri3 ((p :vec3))
(v! (tri (+ (z p) (tri (y p))))
(tri (+ (z p) (tri (x p))))
(tri (+ (y p) (tri (x p))))))
(defun-g tri-noise-3d ((p :vec3))
(let ((z 1.4)
(rz 0f0)
(bp (vec3 0f0)))
(dotimes (i 4)
(let ((dg (tri3 bp)))
(incf p dg)
(multf bp (vec3 2f0))
(multf z 1.5)
(multf p (vec3 1.2))
(incf rz (/ (tri (+ (z p) (tri (+ (x p) (tri (y p))))))
z))
(incf bp (vec3 .14))))
rz))
(defun-g fogmap ((p :vec3)
(d :float)
(time :float))
(incf (x p) time)
(incf (z p) (* time .5))
(* (tri-noise-3d (/ (* p 2.2) (+ d 8f0)))
(smoothstep .7 .0 (y p))))
(defun-g fog ((col :vec3)
(ro :vec3)
(rd :vec3)
(mt :float)
(time :float))
(let ((d .5))
(dotimes (i 7)
(let* ((pos (+ ro (* d rd)))
(rz (fogmap pos d time)))
(setf col (mix col (v! .85 .65 .5) (clamp (* rz (smoothstep d (* 1.8 d) mt)) 0f0 1f0)))
(multf d 1.8)
(if (> d mt) (break))))
col))
|
10b4ef4d7132d06c85b29ac3ae4a61b9053204f6e6616d552ab077b6ffaa94b6 | devaspot/games | tavla_paired.erl | %%% -------------------------------------------------------------------
Author : < >
%%% Description : The paired tavla logic
%%%
Created : Feb 01 , 2013
%%% -------------------------------------------------------------------
%%% Terms explanation:
%%% GameId - uniq identifier of the tournament. Type: integer().
PlayerId - registration number of a player in the tournament . Type : integer ( )
%%% UserId - cross system identifier of a physical user. Type: binary() (or string()?).
TableId - uniq identifier of a table in the tournament . Used by the
%%% tournament logic. Type: integer().
%%% TableGlobalId - uniq identifier of a table in the system. Can be used
%%% to refer to a table directly - without pointing to a tournament.
%%% Type: integer()
-module(tavla_paired).
-behaviour(gen_fsm).
%% --------------------------------------------------------------------
%% Include files
%% --------------------------------------------------------------------
-include_lib("server/include/basic_types.hrl").
-include_lib("db/include/table.hrl").
-include_lib("db/include/transaction.hrl").
-include_lib("db/include/scoring.hrl").
-include_lib("server/include/game_tavla.hrl").
%% --------------------------------------------------------------------
%% External exports
-export([start/1, start/2, start_link/2, reg/2]).
%% gen_fsm callbacks
-export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
-export([table_message/3, client_message/2, client_request/2, client_request/3]).
-record(state,
{%% Static values
game_id :: pos_integer(),
game_type :: atom(),
game_mode :: atom(),
params :: proplists:proplist(),
1 - 5
seats_per_table :: integer(),
table_module :: atom(),
bot_module :: atom(),
quota_per_round :: integer(),
kakush_for_winners :: integer(),
kakush_for_loser :: integer(),
win_game_points :: integer(),
mul_factor :: integer(),
registrants :: list(), %% [robot | binary()]
bots_replacement_mode :: enabled | disabled,
common_params :: proplists:proplist(),
%% Dynamic values
players, %% The register of tournament players
tables, %% The register of tournament tables
seats, %% Stores relation between players and tables seats
tour :: pos_integer(),
[ { TurnNum , TurnRes } ] , TurnRes = [ { , CommonPos , Points , Status } ]
table_id_counter :: pos_integer(),
player_id_counter :: pos_integer(),
cr_tab_requests,
reg_requests,
tab_requests,
timer :: undefined | reference(),
timer_magic :: undefined | reference(),
tables_wl :: list(), %% Tables waiting list
[ { TableId , TableResult } ]
[ { TableId , SeriesResult } ]
start_color :: white | black,
cur_color :: white | black,
next_turn_wl :: list() %% [TableId]
}).
-record(player,
{
id :: pos_integer(),
user_id,
user_info :: #'PlayerInfo'{},
is_bot :: boolean()
}).
-record(table,
{
id :: pos_integer(),
global_id :: pos_integer(),
pid :: pid(),
{ RelayMod , RelayPid }
mon_ref :: reference(),
state :: initializing | ready | in_process | finished,
context :: term(), %% Context term of a table. For failover proposes.
timer :: reference()
}).
-record(seat,
{
table :: pos_integer(),
seat_num :: integer(),
player_id :: undefined | pos_integer(),
is_bot :: undefined | boolean(),
registered_by_table :: undefined | boolean(),
connected :: undefined | boolean(),
free :: boolean()
}).
-define(STATE_INIT, state_init).
-define(STATE_WAITING_FOR_TABLES, state_waiting_for_tables).
-define(STATE_EMPTY_SEATS_FILLING, state_empty_seats_filling).
-define(STATE_WAITING_FOR_PLAYERS, state_waiting_for_players).
-define(STATE_TOUR_PROCESSING, state_tour_processing).
-define(STATE_TOUR_FINISHED, state_tour_finished).
-define(STATE_SHOW_TOUR_RESULT, state_show_tour_result).
-define(STATE_FINISHED, state_finished).
-define(TAB_MOD, okey_table). % ?
-define(TABLE_STATE_INITIALIZING, initializing).
-define(TABLE_STATE_READY, ready).
-define(TABLE_STATE_IN_PROGRESS, in_progress).
-define(TABLE_STATE_WAITING_NEW_ROUND, waiting_new_round).
-define(TABLE_STATE_FINISHED, finished).
Time between all table was created and starting a turn
Time between a round finish and start of a new one
Time between a tour finish and start of a new one
-define(SHOW_TOURNAMENT_RESULT_TIMEOUT , 15000 ) . % % Time between last tour result showing and the tournament finish
-define(TOURNAMENT_TYPE, paired).
-define(GAME_TYPE, game_tavla).
-define(SEATS_NUM, 2). %% TODO: Define this by a parameter. Number of seats per table
-define(WHITE, white).
-define(BLACK, black).
%% ====================================================================
%% External functions
%% ====================================================================
start([GameId, Params]) -> start(GameId, Params).
start(GameId, Params) ->
gen_fsm:start(?MODULE, [GameId, Params, self()], []).
start_link(GameId, Params) ->
gen_fsm:start_link(?MODULE, [GameId, Params, self()], []).
reg(Pid, User) ->
client_request(Pid, {join, User}, 10000).
table_message(Pid, TableId, Message) ->
gen_fsm:send_all_state_event(Pid, {table_message, TableId, Message}).
client_message(Pid, Message) ->
gen_fsm:send_all_state_event(Pid, {client_message, Message}).
client_request(Pid, Message) ->
client_request(Pid, Message, 5000).
client_request(Pid, Message, Timeout) ->
gen_fsm:sync_send_all_state_event(Pid, {client_request, Message}, Timeout).
%% ====================================================================
%% Server functions
%% ====================================================================
init([GameId, Params, _Manager]) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Init started",[GameId]),
Registrants = get_param(registrants, Params),
GameMode = get_param(game_mode, Params),
GameName = get_param(game_name, Params),
TablesNum = get_param(tables_num, Params),
QuotaPerRound = get_param(quota_per_round, Params),
KakushForWinners = get_param(kakush_for_winners, Params),
KakushForLoser = get_param(kakush_for_loser, Params),
WinGamePoints = get_param(win_game_points, Params),
MulFactor = get_param(mul_factor, Params),
TableParams = get_param(table_params, Params),
TableModule = get_param(table_module, Params),
BotModule = get_param(bot_module, Params),
BotsReplacementMode = get_param(bots_replacement_mode, Params),
CommonParams = get_param(common_params, Params),
[gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Parameter <~p> : ~p", [GameId, P, V]) || {P, V} <- Params],
gas:info(?MODULE,"TRN_PAIRED <~p> started. Pid:~p", [GameId, self()]),
gen_fsm:send_all_state_event(self(), go),
{ok, ?STATE_INIT, #state{game_id = GameId,
game_type = ?GAME_TYPE,
game_mode = GameMode,
params = TableParams,
tables_num = TablesNum,
seats_per_table = ?SEATS_NUM,
table_module = TableModule,
bot_module = BotModule,
quota_per_round = QuotaPerRound,
kakush_for_winners = KakushForWinners,
kakush_for_loser = KakushForLoser,
win_game_points = WinGamePoints,
mul_factor = MulFactor,
registrants = Registrants,
bots_replacement_mode = BotsReplacementMode,
common_params = CommonParams,
table_id_counter = 1
}}.
%%===================================================================
handle_event(go, ?STATE_INIT, #state{game_id = GameId, registrants = Registrants,
game_type = GameType, bot_module = BotModule,
common_params = CommonParams} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Received a directive to starting the game.", [GameId]),
DeclRec = create_decl_rec(GameType, CommonParams, GameId, Registrants),
gproc:reg({p,l,self()}, DeclRec),
{Players, PlayerIdCounter} = setup_players(Registrants, GameId, BotModule),
NewStateData = StateData#state{players = Players,
player_id_counter = PlayerIdCounter},
init_tour(1, NewStateData);
handle_event({client_message, Message}, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Received the message from a client: ~p.", [GameId, Message]),
handle_client_message(Message, StateName, StateData);
handle_event({table_message, TableId, Message}, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Received the message from table <~p>: ~p.", [GameId, TableId, Message]),
handle_table_message(TableId, Message, StateName, StateData);
handle_event(Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Unhandled message(event) received in state <~p>: ~p.",
[GameId, StateName, Message]),
{next_state, StateName, StateData}.
handle_sync_event({client_request, Request}, From, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Received the request from a client: ~p.", [GameId, Request]),
handle_client_request(Request, From, StateName, StateData);
handle_sync_event(Request, From, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Unhandled request(event) received in state <~p> from ~p: ~p.",
[GameId, StateName, From, Request]),
{reply, {error, unknown_request}, StateName, StateData}.
%%===================================================================
handle_info({'DOWN', MonRef, process, _Pid, _}, StateName,
#state{game_id = GameId, tables = Tables} = StateData) ->
case get_table_by_mon_ref(MonRef, Tables) of
#table{id = TableId} ->
gas:info(?MODULE,"TRN_PAIRED <~p> Table <~p> is down. Stopping", [GameId, TableId]),
%% TODO: More smart handling (failover) needed
{stop, {one_of_tables_down, TableId}, StateData};
not_found ->
{next_state, StateName, StateData}
end;
handle_info({timeout, Magic}, ?STATE_WAITING_FOR_PLAYERS,
#state{timer_magic = Magic, game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to start the tour.", [GameId]),
start_tour(StateData);
handle_info({timeout, Magic}, ?STATE_TOUR_PROCESSING,
#state{timer_magic = Magic, game_id = GameId, tables = Tables,
seats = Seats, players = Players, table_module = TableModule,
bot_module = BotModule, player_id_counter = PlayerIdCounter,
game_type = GameType, common_params = CommonParams,
tab_requests = Requests} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to start new round. Checking start conditions...", [GameId]),
DisconnectedSeats = find_disconnected_seats(Seats),
DisconnectedPlayers = [PlayerId || #seat{player_id = PlayerId} <- DisconnectedSeats],
ConnectedRealPlayers = [PlayerId || #player{id = PlayerId, is_bot = false} <- players_to_list(Players),
not lists:member(PlayerId, DisconnectedPlayers)],
case ConnectedRealPlayers of
Finish game
gas:info(?MODULE,"TRN_PAIRED <~p> No real players left in tournament. "
"Stopping the game.", [GameId]),
finalize_tables_with_disconnect(TableModule, Tables),
{stop, normal, StateData#state{tables = [], seats = []}};
_ -> %% Replace disconnected players by bots and start the round
gas:info(?MODULE,"TRN_PAIRED <~p> Enough real players in the game to continue. "
"Replacing disconnected players by bots.", [GameId]),
{Replacements, NewPlayers, NewSeats, NewPlayerIdCounter} =
replace_by_bots(DisconnectedSeats, GameId, BotModule, Players, Seats, PlayerIdCounter),
NewRequests = req_replace_players(TableModule, Tables, Replacements, Requests),
update_gproc(GameId, GameType, CommonParams, NewPlayers),
gas:info(?MODULE,"TRN_PAIRED <~p> The replacement is completed.", [GameId]),
start_round(StateData#state{tab_requests = NewRequests,
players = NewPlayers,
seats = NewSeats,
player_id_counter = NewPlayerIdCounter})
end;
handle_info({timeout, Magic}, ?STATE_TOUR_FINISHED,
#state{timer_magic = Magic, game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to finalize the tour.", [GameId]),
finalize_tour(StateData);
handle_info({timeout, Magic}, ?STATE_SHOW_TOUR_RESULT,
#state{timer_magic = Magic, game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to finalize the game.", [GameId]),
finalize_tournament(StateData);
handle_info({publish_series_result, TableId}, StateName,
#state{game_id = GameId, tables = Tables, table_module = TableModule,
series_results = SeriesResults} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to publish the series result for table <~p>.", [GameId, TableId]),
case fetch_table(TableId, Tables) of
#table{state = ?TABLE_STATE_FINISHED, pid = TablePid} ->
{_, SeriesResult} = lists:keyfind(TableId, 1, SeriesResults),
send_to_table(TableModule, TablePid, {show_series_result, SeriesResult});
_ ->
gas:info(?MODULE,"TRN_PAIRED <~p> Don't publish the series result because the state of table <~p> "
"is not 'finished'.", [GameId, TableId])
end,
{next_state, StateName, StateData};
%% handle_info({timeout, Magic}, ?STATE_FINISHED,
%% #state{timer_magic = Magic, tables = Tables, game_id = GameId,
%% table_module = TableModule} = StateData) ->
%% gas:info(?MODULE,"TRN_PAIRED <~p> Time to stopping the tournament.", [GameId]),
%% finalize_tables_with_disconnect(TableModule, Tables),
{ stop , normal , StateData#state{tables = [ ] , seats = [ ] } } ;
handle_info(Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled message(info) received in state <~p>: ~p.",
[GameId, StateName, Message]),
{next_state, StateName, StateData}.
%%===================================================================
terminate(_Reason, _StateName, #state{game_id=GameId}=_StatData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Shutting down at state: <~p>. Reason: ~p",
[GameId, _StateName, _Reason]),
ok.
%%===================================================================
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
%% --------------------------------------------------------------------
Internal functions
%% --------------------------------------------------------------------
handle_client_message(Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled client message received in "
"state <~p>: ~p.", [GameId, StateName, Message]),
{next_state, StateName, StateData}.
%%===================================================================
handle_table_message(TableId, {player_connected, PlayerId},
StateName,
#state{seats = Seats} = StateData) ->
case find_seats_by_player_id(PlayerId, Seats) of
[#seat{seat_num = SeatNum}] ->
NewSeats = update_seat_connect_status(TableId, SeatNum, true, Seats),
{next_state, StateName, StateData#state{seats = NewSeats}};
[] -> %% Ignoring the message
{next_state, StateName, StateData}
end;
handle_table_message(TableId, {player_disconnected, PlayerId},
StateName, #state{seats = Seats} = StateData) ->
case find_seats_by_player_id(PlayerId, Seats) of
[#seat{seat_num = SeatNum}] ->
NewSeats = update_seat_connect_status(TableId, SeatNum, false, Seats),
{next_state, StateName, StateData#state{seats = NewSeats}};
[] -> %% Ignoring the message
{next_state, StateName, StateData}
end;
handle_table_message(TableId, {get_tables_states, PlayerId, Ref},
StateName,
#state{tables = Tables, table_module = TableModule} = StateData) ->
[send_to_table(TableModule, TPid, {send_table_state, TableId, PlayerId, Ref}) ||
#table{id = TId, pid = TPid} <- tables_to_list(Tables), TId =/= TableId],
{next_state, StateName, StateData};
handle_table_message(TableId, {table_created, Relay},
?STATE_WAITING_FOR_TABLES,
#state{tables = Tables, seats = Seats, seats_per_table = SeatsPerTable,
cr_tab_requests = TCrRequests, tables_num = TablesNum,
reg_requests = RegRequests} = StateData) ->
TabInitPlayers = dict:fetch(TableId, TCrRequests),
NewTCrRequests = dict:erase(TableId, TCrRequests),
%% Update status of players
TabSeats = find_seats_by_table_id(TableId, Seats),
F = fun(#seat{player_id = PlayerId} = S, Acc) ->
case lists:member(PlayerId, TabInitPlayers) of
true -> store_seat(S#seat{registered_by_table = true}, Acc);
false -> Acc
end
end,
NewSeats = lists:foldl(F, Seats, TabSeats),
%% Process delayed registration requests
TablePid = get_table_pid(TableId, Tables),
F2 = fun(PlayerId, Acc) ->
case dict:find(PlayerId, Acc) of
{ok, From} ->
gen_fsm:reply(From, {ok, {PlayerId, Relay, {?TAB_MOD, TablePid}}}),
dict:erase(PlayerId, Acc);
error -> Acc
end
end,
NewRegRequests = lists:foldl(F2, RegRequests, TabInitPlayers),
NewTables = update_created_table(TableId, Relay, Tables),
case dict:size(NewTCrRequests) of
0 ->
case enough_players(NewSeats, TablesNum*SeatsPerTable) of
true ->
{TRef, Magic} = start_timer(?WAITING_PLAYERS_TIMEOUT),
{next_state, ?STATE_WAITING_FOR_PLAYERS,
StateData#state{tables = NewTables, seats = NewSeats, cr_tab_requests = NewTCrRequests,
reg_requests = NewRegRequests, timer = TRef, timer_magic = Magic}};
false ->
{next_state, ?STATE_EMPTY_SEATS_FILLING,
StateData#state{tables = NewTables, seats = NewSeats, cr_tab_requests = NewTCrRequests,
reg_requests = NewRegRequests}}
end;
_ -> {next_state, ?STATE_WAITING_FOR_TABLES,
StateData#state{tables = NewTables, seats = NewSeats,
cr_tab_requests = NewTCrRequests, reg_requests = NewRegRequests}}
end;
handle_table_message(TableId, {round_finished, NewScoringState, _RoundScore, _TotalScore},
?STATE_TOUR_PROCESSING = StateName,
#state{game_id = GameId, tables = Tables, table_module = TableModule,
tables_wl = WL} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Round is finished (table <~p>).", [GameId, TableId]),
#table{pid = TablePid} = Table = fetch_table(TableId, Tables),
NewTable = Table#table{context = NewScoringState, state = ?TABLE_STATE_WAITING_NEW_ROUND},
NewTables = store_table(NewTable, Tables),
send_to_table(TableModule, TablePid, show_round_result),
NewWL = lists:delete(TableId, WL),
[send_to_table(TableModule, TPid, {playing_tables_num, length(NewWL)})
|| #table{pid = TPid, state = ?TABLE_STATE_WAITING_NEW_ROUND} <- tables_to_list(Tables)],
NewStateData = StateData#state{tables = NewTables,
tables_wl = NewWL},
if NewWL == [] ->
{TRef, Magic} = start_timer(?REST_TIMEOUT),
{next_state, StateName, NewStateData#state{timer = TRef,
timer_magic = Magic}};
true ->
remove_table_from_next_turn_wl(TableId, StateName, NewStateData)
end;
handle_table_message(TableId, {game_finished, TableContext, _RoundScore, TableScore},
?STATE_TOUR_PROCESSING = StateName,
#state{game_id = GameId, tables = Tables, tables_wl = WL,
table_module = TableModule, tables_results = TablesResults,
game_type = GameType, game_mode = GameMode, mul_factor = MulFactor,
kakush_for_winners = KakushForWinners, kakush_for_loser = KakushForLoser,
win_game_points = WinGamePoints, players = Players,
series_results = SeriesResults} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Last round of the set is finished (table <~p>).", [GameId, TableId]),
NewTablesResults = [{TableId, TableScore} | TablesResults],
#table{pid = TablePid} = Table = fetch_table(TableId, Tables),
NewTable = Table#table{context = TableContext, state = ?TABLE_STATE_FINISHED},
NewTables = store_table(NewTable, Tables),
send_to_table(TableModule, TablePid, show_round_result),
NewWL = lists:delete(TableId, WL),
[send_to_table(TableModule, TPid, {playing_tables_num, length(NewWL)})
|| #table{pid = TPid, state = ?TABLE_STATE_FINISHED} <- tables_to_list(Tables)],
SeriesResult = series_result(TableScore),
NewSeriesResults = [{TableId, SeriesResult} | SeriesResults],
gas:info(?MODULE,"TRN_PAIRED <~p> Set result: ~p", [GameId, SeriesResult]),
Points = calc_players_prize_points(SeriesResult, KakushForWinners, KakushForLoser, WinGamePoints, MulFactor, Players),
UsersPrizePoints = prepare_users_prize_points(Points, Players),
gas:info(?MODULE,"TRN_PAIRED <~p> Prizes: ~p", [GameId, UsersPrizePoints]),
add_points_to_accounts(UsersPrizePoints, GameId, GameType, GameMode, MulFactor),
NewStateData = StateData#state{tables = NewTables,
tables_results = NewTablesResults,
series_results = NewSeriesResults,
tables_wl = NewWL},
erlang:send_after(?REST_TIMEOUT, self(), {publish_series_result, TableId}),
if NewWL == [] ->
{TRef, Magic} = start_timer(?REST_TIMEOUT),
{next_state, ?STATE_TOUR_FINISHED, NewStateData#state{timer = TRef,
timer_magic = Magic}};
true ->
remove_table_from_next_turn_wl(TableId, StateName, NewStateData)
end;
handle_table_message(TableId, {response, RequestId, Response},
StateName,
#state{game_id = GameId, tab_requests = TabRequests} = StateData) ->
NewTabRequests = dict:erase(RequestId, TabRequests),
case dict:find(RequestId, TabRequests) of
{ok, ReqContext} ->
gas:info(?MODULE,"TRN_PAIRED <~p> The a response received from table <~p>. "
"RequestId: ~p. Request context: ~p. Response: ~p",
[GameId, TableId, RequestId, ReqContext, Response]),
handle_table_response(TableId, ReqContext, Response, StateName,
StateData#state{tab_requests = NewTabRequests});
error ->
gas:error(?MODULE,"TRN_PAIRED <~p> Table <~p> sent a response for unknown request. "
"RequestId: ~p. Response", []),
{next_state, StateName, StateData#state{tab_requests = NewTabRequests}}
end;
handle_table_message(TableId, {game_event, #tavla_next_turn{table_id = TableId,
color = ExtColor}},
?STATE_TOUR_PROCESSING = StateName,
#state{cur_color = CurColor, next_turn_wl = NextTurnWL,
game_id = GameId} = StateData) ->
Color = ext_to_color(ExtColor),
gas:info(?MODULE,"TRN_PAIRED <~p> The 'tavla_next_turn event' received from table <~p>. "
"Color: ~p. CurColor: ~p, WaitList: ~p",
[GameId, TableId, Color, CurColor, NextTurnWL]),
Assert
Assert
remove_table_from_next_turn_wl(TableId, StateName, StateData);
handle_table_message(TableId, {game_event, GameEvent},
?STATE_TOUR_PROCESSING = StateName,
#state{tables = Tables, table_module = TableModule} = StateData) ->
[send_to_table(TableModule, TablePid, {game_event, GameEvent}) ||
#table{pid = TablePid, id = TId} <- tables_to_list(Tables), TId =/= TableId],
{next_state, StateName, StateData};
handle_table_message(_TableId, {table_state_event, DestTableId, PlayerId, Ref, StateEvent},
StateName,
#state{tables = Tables, table_module = TableModule} = StateData) ->
case get_table(DestTableId, Tables) of
{ok, #table{pid = TPid}} ->
send_to_table(TableModule, TPid, {table_state_event, PlayerId, Ref, StateEvent});
error -> do_nothing
end,
{next_state, StateName, StateData};
handle_table_message(TableId, Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled table message received from table <~p> in "
"state <~p>: ~p.", [GameId, TableId, StateName, Message]),
{next_state, StateName, StateData}.
%%===================================================================
handle_table_response(_TableId , { register_player , , TableId , SeatNum } , ok = _ Response ,
%% StateName,
# state{reg_requests = RegRequests , seats = Seats ,
%% tables = Tables} = StateData) ->
Seat = fetch_seat(TableId , SeatNum , Seats ) ,
%% NewSeats = store_seat(Seat#seat{registered_by_table = true}, Seats),
%% %% Send response to a client for a delayed request
%% NewRegRequests =
case dict : find(PlayerId , RegRequests ) of
%% {ok, From} ->
# table{relay = Relay , pid = TablePid } = fetch_table(TableId , Tables ) ,
gen_fsm : reply(From , { ok , { PlayerId , Relay , { ? TAB_MOD , TablePid } } } ) ,
dict : erase(PlayerId , RegRequests ) ;
error - > RegRequests
%% end,
{ next_state , StateName , StateData#state{seats = NewSeats ,
%% reg_requests = NewRegRequests}};
handle_table_response(_TableId, {replace_player, PlayerId, TableId, SeatNum}, ok = _Response,
StateName,
#state{reg_requests = RegRequests, seats = Seats,
tables = Tables, table_module = TableMod} = StateData) ->
Seat = fetch_seat(TableId, SeatNum, Seats),
NewSeats = store_seat(Seat#seat{registered_by_table = true}, Seats),
%% Send response to a client for a delayed request
NewRegRequests =
case dict:find(PlayerId, RegRequests) of
{ok, From} ->
#table{relay = Relay, pid = TablePid} = fetch_table(TableId, Tables),
gen_fsm:reply(From, {ok, {PlayerId, Relay, {TableMod, TablePid}}}),
dict:erase(PlayerId, RegRequests);
error -> RegRequests
end,
{next_state, StateName, StateData#state{seats = NewSeats,
reg_requests = NewRegRequests}};
handle_table_response(TableId, RequestContext, Response, StateName,
#state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled 'table response' received from table <~p> "
"in state <~p>. Request context: ~p. Response: ~p.",
[GameId, TableId, StateName, RequestContext, Response]),
{next_state, StateName, StateData}.
%%===================================================================
handle_client_request({join, UserInfo}, From, StateName,
#state{game_id = GameId, reg_requests = RegRequests,
seats = Seats, players=Players, tables = Tables,
bots_replacement_mode = BotsReplacementMode,
table_module = TableMod} = StateData) ->
#'PlayerInfo'{id = UserId, robot = _IsBot} = UserInfo,
gas:info(?MODULE,"TRN_PAIRED <~p> The 'Join' request received from user: ~p.", [GameId, UserId]),
if StateName == ?STATE_FINISHED ->
gas:info(?MODULE,"TRN_PAIRED <~p> The game is finished. "
"Reject to join user ~p.", [GameId, UserId]),
{reply, {error, finished}, StateName, StateData};
true -> %% Game in progress. Find a seat for the user
case get_player_by_user_id(UserId, Players) of
{ok, #player{id = PlayerId}} -> %% The user is a registered member of the game (player)
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p is a registered member of the game. "
"Allow to join.", [GameId, UserId]),
[#seat{table = TableId, registered_by_table = RegByTable}] = find_seats_by_player_id(PlayerId, Seats),
case RegByTable of
false -> %% The player is not registered by the table yet
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p not yet regirested by the table. "
"Add the request to the waiting pool.", [GameId, UserId]),
NewRegRequests = dict:store(PlayerId, From, RegRequests),
{next_state, StateName, StateData#state{reg_requests = NewRegRequests}};
_ -> %% The player is registered by the table. Return the table requisites
gas:info(?MODULE,"TRN_PAIRED <~p> Return the join response for player ~p immediately.",
[GameId, UserId]),
#table{relay = Relay, pid = TPid} = fetch_table(TableId, Tables),
{reply, {ok, {PlayerId, Relay, {TableMod, TPid}}}, StateName, StateData}
end;
error -> %% Not a member yet
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p is not a member of the game.", [GameId, UserId]),
case find_free_seats(Seats) of
[] when BotsReplacementMode == disabled ->
gas:info(?MODULE,"TRN_PAIRED <~p> No free seats for user ~p. Robots replacement is disabled. "
"Reject to join.", [GameId, UserId]),
{reply, {error, not_allowed}, StateName, StateData};
[] when BotsReplacementMode == enabled ->
gas:info(?MODULE,"TRN_PAIRED <~p> No free seats for user ~p. Robots replacement is enabled. "
"Tring to find a robot for replace.", [GameId, UserId]),
case find_registered_robot_seats(Seats) of
[] ->
gas:info(?MODULE,"TRN_PAIRED <~p> No robots for replacement by user ~p. "
"Reject to join.", [GameId, UserId]),
{reply, {error, not_allowed}, StateName, StateData};
[#seat{table = TableId, seat_num = SeatNum, player_id = OldPlayerId} | _] ->
gas:info(?MODULE,"TRN_PAIRED <~p> There is a robot for replacement by user ~p. "
"Registering.", [GameId, UserId]),
reg_player_with_replace(UserInfo, TableId, SeatNum, OldPlayerId, From, StateName, StateData)
end;
[#seat{table = TableId, seat_num = SeatNum} | _] ->
gas:info(?MODULE,"TRN_PAIRED <~p> There is a free seat for user ~p. "
"Registering.", [GameId, UserId]),
reg_new_player(UserInfo, TableId, SeatNum, From, StateName, StateData)
end
end
end;
handle_client_request(Request, From, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled client request received from ~p in "
"state <~p>: ~p.", [GameId, From, StateName, Request]),
{reply, {error, unexpected_request}, StateName, StateData}.
%%===================================================================
init_tour(Tour, #state{game_id = GameId, table_module = TableModule,
params = TableParams, players = Players, tables_num = TablesNum,
table_id_counter = TableIdCounter, tables = OldTables,
seats_per_table = SeatsPerTable} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Initializing tour <~p>...", [GameId, Tour]),
PlayersList = prepare_players_for_new_tour(0, Players),
{NewTables, Seats, NewTableIdCounter, CrRequests} =
setup_tables(TableModule, PlayersList, SeatsPerTable, TablesNum, _TTable = undefined,
Tour, _Tours = undefined, TableIdCounter, GameId, TableParams),
if Tour > 1 -> finalize_tables_with_rejoin(TableModule, OldTables);
true -> do_nothing
end,
gas:info(?MODULE,"TRN_PAIRED <~p> Initializing of tour <~p> is finished. "
"Waiting creating confirmations from the tours' tables...",
[GameId, Tour]),
{next_state, ?STATE_WAITING_FOR_TABLES, StateData#state{tables = NewTables,
seats = Seats,
table_id_counter = NewTableIdCounter,
cr_tab_requests = CrRequests,
tour = Tour,
reg_requests = dict:new(),
tab_requests = dict:new(),
tables_results = [],
series_results = []
}}.
start_tour(#state{game_id = GameId, tour = Tour} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Starting tour <~p>...", [GameId, Tour]),
start_round(StateData#state{start_color = undefined}).
start_round(#state{game_id = GameId, game_type = GameType, game_mode = GameMode,
mul_factor = MulFactor, quota_per_round = Amount,
tables = Tables, players = Players, table_module = TableModule,
start_color = StartColor} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Starting new round...", [GameId]),
UsersIds = [UserId || #player{user_id = UserId, is_bot = false} <- players_to_list(Players)],
deduct_quota(GameId, GameType, GameMode, Amount, MulFactor, UsersIds),
TablesList = tables_to_list(Tables),
[send_to_table(TableModule, Pid, start_round) || #table{pid = Pid} <- TablesList],
F = fun(Table, Acc) ->
store_table(Table#table{state = ?TABLE_STATE_IN_PROGRESS}, Acc)
end,
NewTables = lists:foldl(F, Tables, TablesList),
WL = [T#table.id || T <- TablesList],
gas:info(?MODULE,"TRN_PAIRED <~p> The round is started. Processing...", [GameId]),
NewStartColor =
if StartColor == undefined ->
{Die1, Die2} = competition_roll(),
[send_to_table(TableModule, Pid, {action, {competition_rolls, Die1, Die2}})
|| #table{pid = Pid} <- TablesList],
if Die1 > Die2 -> ?WHITE;
true -> ?BLACK end;
true ->
OppColor = opponent(StartColor),
{Die1, Die2} = roll(),
[send_to_table(TableModule, Pid, {action, {rolls, OppColor, Die1, Die2}})
|| #table{pid = Pid} <- TablesList],
OppColor
end,
gas:info(?MODULE,"TRN_PAIRED <~p> Start color is ~p", [GameId, NewStartColor]),
{next_state, ?STATE_TOUR_PROCESSING, StateData#state{tables = NewTables,
tables_wl = WL,
start_color = NewStartColor,
cur_color = NewStartColor,
next_turn_wl = WL}}.
finalize_tour(#state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Finalizing the tour...", [GameId]),
{TRef, Magic} = start_timer(?SHOW_SERIES_RESULT_TIMEOUT),
gas:info(?MODULE,"TRN_PAIRED <~p> The tour is finalized. "
"Waiting some time (~p secs) before continue...",
[GameId, ?SHOW_SERIES_RESULT_TIMEOUT div 1000]),
{next_state, ?STATE_SHOW_TOUR_RESULT, StateData#state{timer = TRef, timer_magic = Magic}}.
finalize_tournament(#state{game_id = GameId, table_module = TableModule,
tables = Tables} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Finalizing the tournament...", [GameId]),
finalize_tables_with_disconnect(TableModule, Tables),
gas:info(?MODULE,"TRN_PAIRED <~p> Finalization completed. Stopping...", [GameId]),
{stop, normal, StateData#state{tables = [], seats = []}}.
%% series_result(TableResult) -> WithPlaceAndStatus
Types : TableResult = [ { PlayerId , Points } ]
WithPlaceAndStatus = [ { PlayerId , Place , Points , Status } ]
%% Status = winner | looser
series_result(TableResult) ->
{_, PointsList} = lists:unzip(TableResult),
Max = lists:max(PointsList),
F = fun({Pl, Points}, {CurPlace, CurPos, LastPoints}) ->
if Points == LastPoints ->
{{Pl, CurPlace, Points, if Points == Max -> winner; true -> looser end},
{CurPlace, CurPos + 1, Points}};
true ->
{{Pl, CurPos, Points, looser},
{CurPos, CurPos + 1, Points}}
end
end,
{WithPlaceAndStatus, _} = lists:mapfoldl(F, {1, 1, Max}, lists:reverse(lists:keysort(2, TableResult))),
WithPlaceAndStatus.
deduct_quota(GameId, GameType, GameMode, Amount, MulFactor, UsersIds) ->
RealAmount = Amount * MulFactor,
[begin
TI = #ti_game_event{game_name = GameType, game_mode = GameMode,
id = GameId, double_points = MulFactor,
type = start_round, tournament_type = ?TOURNAMENT_TYPE},
kvs:add(#transaction{id=kvs:next_id(transaction,1),
feed_id={quota,binary_to_list(UserId)},amount=-RealAmount,comment=TI})
% nsm_accounts:transaction(binary_to_list(UserId), ?CURRENCY_QUOTA, -RealAmount, TI)
end || UserId <- UsersIds],
ok.
calc_players_prize_points(SeriesResult , KakushForWinner , KakushForLoser ,
WinGamePoints , MulFactor , Players ) - > Points
%% Types:
SeriesResult = [ { , _ Pos , _ Points , Status } ]
%% Status = winner | looser
Points = [ { , KakushPoints , GamePoints } ]
calc_players_prize_points(SeriesResult, KakushForWinners, KakushForLoser, WinGamePoints, MulFactor, Players) ->
SeriesResult1 = [begin
#'PlayerInfo'{id = UserId, robot = Robot} = get_user_info(PlayerId, Players),
Paid = is_paid(user_id_to_string(UserId)),
Winner = Status == winner,
{PlayerId, Winner, Robot, Paid}
end || {PlayerId, _Pos, _Points, Status} <- SeriesResult],
Paids = [PlayerId || {PlayerId, _Winner, _Robot, _Paid = true} <- SeriesResult1],
Winners = [PlayerId || {PlayerId, _Winner = true, _Robot, _Paid} <- SeriesResult1],
TotalNum = length(SeriesResult),
PaidsNum = length(Paids),
WinnersNum = length(Winners),
KakushPerWinner = round(((KakushForWinners * MulFactor) * PaidsNum div TotalNum) / WinnersNum),
KakushPerLoser = (KakushForLoser * MulFactor) * PaidsNum div TotalNum,
WinGamePoints1 = WinGamePoints * MulFactor,
[begin
{KakushPoints, GamePoints} = calc_points(KakushPerWinner, KakushPerLoser, WinGamePoints1, Paid, Robot, Winner),
{PlayerId, KakushPoints, GamePoints}
end || {PlayerId, Winner, Robot, Paid} <- SeriesResult1].
calc_points(KakushPerWinner, KakushPerLoser, WinGamePoints, Paid, Robot, Winner) ->
if Robot -> {0, 0};
not Paid andalso Winner -> {0, WinGamePoints};
not Paid -> {0, 0};
Paid andalso Winner -> {KakushPerWinner, WinGamePoints};
Paid -> {KakushPerLoser, 0}
end.
%% prepare_users_prize_points(Points, Players) -> UsersPrizePoints
%% Types:
Points = [ { , KakushPoints , GamePoints } ]
UserPrizePoints = [ { UserIdStr , KakushPoints , GamePoints } ]
prepare_users_prize_points(Points, Players) ->
[{user_id_to_string(get_user_id(PlayerId, Players)), K, G} || {PlayerId, K, G} <- Points].
is_paid(UserId) -> nsm_accounts:user_paid(UserId).
add_points_to_accounts(Points , GameId , GameType , , MulFactor ) - > ok
Types : Points = [ { UserId , KakushPoints , GamePoints } ]
add_points_to_accounts(Points, GameId, GameType, GameMode, MulFactor) ->
TI = #ti_game_event{game_name = GameType, game_mode = GameMode,
id = GameId, double_points = MulFactor,
type = game_end, tournament_type = ?TOURNAMENT_TYPE},
[begin
if KakushPoints =/= 0 ->
kvs:add(#transaction{id=kvs:next_id(transaction,1),
feed_id={kakush,UserId},amount=KakushPoints,comment=TI});
ok = nsm_accounts : , ? CURRENCY_KAKUSH , KakushPoints , TI ) ;
true -> do_nothing
end,
if GamePoints =/= 0 ->
kvs:add(#transaction{id=kvs:next_id(transaction,1),
feed_id={game_points,UserId},amount=GamePoints,comment=TI});
ok = nsm_accounts : , ? CURRENCY_GAME_POINTS , GamePoints , TI ) ;
true -> do_nothing
end
end || {UserId, KakushPoints, GamePoints} <- Points],
ok.
%% TODO: Deduct quota if replaces in the middle of a round
reg_player_with_replace(UserInfo, TableId, SeatNum, OldPlayerId, From, StateName,
#state{game_id = GameId, players = Players, tables = Tables,
game_type = GameType, seats = Seats, player_id_counter = PlayerId,
tab_requests = TabRequests, reg_requests = RegRequests,
table_module = TableModule, common_params = CommonParams,
game_mode = GameMode, mul_factor = MulFactor,
quota_per_round = Amount} = StateData) ->
#'PlayerInfo'{id = UserId, robot = IsBot} = UserInfo,
NewPlayers = del_player(OldPlayerId, Players),
NewPlayers2 = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = IsBot}, NewPlayers),
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p registered as player <~p>.", [GameId, UserId, PlayerId]),
NewSeats = set_seat(TableId, SeatNum, PlayerId, _Bot = false, _RegByTable = false,
_Connected = false, _Free = false, Seats),
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p assigned to seat <~p> of table <~p>.", [GameId, UserId, SeatNum, TableId]),
NewRegRequests = dict:store(PlayerId, From, RegRequests),
#table{pid = TablePid, state = TableStateName} = fetch_table(TableId, Tables),
NewTabRequests = table_req_replace_player(TableModule, TablePid, PlayerId, UserInfo, TableId, SeatNum, TabRequests),
case TableStateName of
?TABLE_STATE_IN_PROGRESS when not IsBot->
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p is a real player <~p> and he was registered in the middle of the round."
"So deduct some quota.", [GameId, UserId, PlayerId]),
deduct_quota(GameId, GameType, GameMode, Amount, MulFactor, [UserId]);
_ -> do_nothing
end,
update_gproc(GameId, GameType, CommonParams, NewPlayers2),
{next_state, StateName, StateData#state{players = NewPlayers2,
seats = NewSeats,
player_id_counter = PlayerId + 1,
tab_requests = NewTabRequests,
reg_requests = NewRegRequests}}.
reg_new_player(UserInfo, TableId, SeatNum, From, StateName,
#state{game_id = GameId, players = Players, tables = Tables,
game_type = GameType, seats = Seats, player_id_counter = PlayerId,
tab_requests = TabRequests, reg_requests = RegRequests,
table_module = TableModule, common_params = CommonParams,
tables_num = TablesNum, seats_per_table = SeatsPerTable
} = StateData) ->
{SeatNum, NewPlayers, NewSeats} =
register_new_player(UserInfo, TableId, Players, Seats, PlayerId),
TablePid = get_table_pid(TableId, Tables),
NewTabRequests = table_req_replace_player(TableModule, TablePid, PlayerId, UserInfo,
TableId, SeatNum, TabRequests),
NewRegRequests = dict:store(PlayerId, From, RegRequests),
update_gproc(GameId, GameType, CommonParams, NewPlayers),
NewStateData = StateData#state{reg_requests = NewRegRequests, tab_requests = NewTabRequests,
players = NewPlayers, seats = NewSeats,
player_id_counter = PlayerId + 1},
EnoughPlayers = enough_players(NewSeats, TablesNum*SeatsPerTable),
if StateName == ?STATE_EMPTY_SEATS_FILLING andalso EnoughPlayers ->
gas:info(?MODULE,"TRN_PAIRED <~p> It's enough players registered to start the game. "
"Initiating the procedure.", [GameId]),
start_tour(NewStateData);
true ->
gas:info(?MODULE,"TRN_PAIRED <~p> Not enough players registered to start the game. "
"Waiting for more registrations.", [GameId]),
{next_state, StateName, NewStateData}
end.
register_new_player(UserInfo , TableId , Players , Seats , ) - > { SeatNum , NewPlayers , NewSeats }
register_new_player(UserInfo, TableId, Players, Seats, PlayerId) ->
#'PlayerInfo'{id = UserId, robot = Bot} = UserInfo,
[#seat{seat_num = SeatNum} |_] = find_free_seats(TableId, Seats),
NewSeats = set_seat(TableId, SeatNum, PlayerId, Bot, _RegByTable = false,
_Connected = false, _Free = false, Seats),
NewPlayers = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = Bot}, Players),
{SeatNum, NewPlayers, NewSeats}.
replace_by_bots(DisconnectedSeats , GameId , BotModule , Players , Seats , PlayerIdCounter ) - >
{ Replacements , NewPlayers , NewSeats , }
%% Types: Disconnected = [#seat{}]
Replacements = [ { PlayerId , UserInfo , TableId , SeatNum } ]
replace_by_bots(DisconnectedSeats, GameId, BotModule, Players, Seats, PlayerIdCounter) ->
F = fun(#seat{player_id = PlayerId,
table = TableId,
seat_num = SeatNum}, {RAcc, PAcc, SAcc, Counter}) ->
NewPAcc1 = del_player(PlayerId, PAcc),
NewSAcc = set_seat(TableId, SeatNum, _PlayerId = Counter, _Bot = true,
_RegByTable = false, _Connected = false, _Free = false, SAcc),
#'PlayerInfo'{id = UserId} = UserInfo = spawn_bot(GameId, BotModule),
NewPAcc = store_player(#player{id = Counter, user_id = UserId,
user_info = UserInfo, is_bot = true}, NewPAcc1),
NewRAcc = [{Counter, UserInfo, TableId, SeatNum} | RAcc],
{NewRAcc, NewPAcc, NewSAcc, Counter + 1}
end,
lists:foldl(F, {[], Players, Seats, PlayerIdCounter}, DisconnectedSeats).
enough_players(Seats, Threshold) ->
NonEmptySeats = find_non_free_seats(Seats),
length(NonEmptySeats) >= Threshold.
update_gproc(GameId, GameType, CommonParams, Players) ->
Users = [if Bot -> robot; true -> UId end || #player{user_id = UId, is_bot = Bot}
<- players_to_list(Players)],
DeclRec = create_decl_rec(GameType, CommonParams, GameId, Users),
gproc:set_value({p,l,self()}, DeclRec).
prepare_players_for_new_tour(InitialPoints , Players ) - > [ { PlayerId , UserInfo , Points } ]
prepare_players_for_new_tour(InitialPoints, Players) ->
[{PlayerId, UserInfo, InitialPoints}
|| #player{id = PlayerId, user_info = UserInfo} <- players_to_list(Players)].
setup_tables(Players , TTable , TableIdCounter , GameId , TableParams ) - >
{ Tables , Seats , , CrRequests }
Types : Players = [ { PlayerId , UserInfo , Points } | empty ]
TTable = [ { Tour , [ { UserId , CommonPos , Score , Status } ] } ]
setup_tables(TableMod, Players, SeatsPerTable, TablesNum, TTable, Tour, Tours, TableIdCounter, GameId, TableParams) ->
EmptySeatsNum = SeatsPerTable*TablesNum - length(Players),
Players2 = lists:duplicate(EmptySeatsNum, empty) ++ Players,
SPlayers = shuffle(Players2),
Groups = split_by_num(SeatsPerTable, SPlayers),
F = fun(Group, {TAcc, SAcc, TableId, TCrRequestsAcc}) ->
TPlayers = prepare_table_players(Group),
TableParams2 = [{players, TPlayers}, {ttable, TTable}, {tour, Tour},
{tours, Tours}, {parent, {?MODULE, self()}} | TableParams],
{ok, TabPid} = spawn_table(TableMod, GameId, TableId, TableParams2),
MonRef = erlang:monitor(process, TabPid),
NewTAcc = reg_table(TableId, TabPid, MonRef, TAcc),
NewSAcc = reg_seats(TableId, TPlayers, SAcc),
PlayersIds = [PlId || {PlId, _, _} <- Group, PlId =/= empty],
NewTCrRequestsAcc = dict:store(TableId, PlayersIds, TCrRequestsAcc),
{NewTAcc, NewSAcc, TableId + 1, NewTCrRequestsAcc}
end,
lists:foldl(F, {tables_init(), seats_init(), TableIdCounter, dict:new()}, Groups).
reg_seats(TableId, TPlayers, Seats) ->
F = fun({{empty, _}, _PlayerInfo, SNum, _Points}, Acc) ->
set_seat(TableId, SNum, _PlId = undefined, _Bot = undefined, _Reg = false, _Conn = false, _Free = true, Acc);
({PlId, #'PlayerInfo'{robot = Bot}, SNum, _Points}, Acc) ->
set_seat(TableId, SNum, PlId, Bot, _Reg = false, _Conn = false, _Free = false, Acc)
end,
lists:foldl(F, Seats, TPlayers).
%% prepare_table_players(PlayersList) -> TPlayersList
PlayersList = { PlayerId , UserInfo , Points } | empty
TPlayersList = { APlayerId , UserInfo , SeatNum , Points }
%% APlayerId = PlayerId | {empty, integer()}
prepare_table_players(PlayersList) ->
F = fun({PlayerId, UserInfo, Points}, SeatNum) ->
{{PlayerId, UserInfo, SeatNum, Points}, SeatNum+1};
(empty, SeatNum) ->
{{_PlayerId = {empty, SeatNum}, empty_seat_userinfo(SeatNum), SeatNum, _Points=0}, SeatNum+1}
end,
{TPlayers, _} = lists:mapfoldl(F, 1, PlayersList),
TPlayers.
empty_seat_userinfo(Num) ->
#'PlayerInfo'{id = list_to_binary(["empty_", integer_to_list(Num)]),
login = <<"">>,
name = <<"empty">>,
surname = <<" ">>,
age = 0,
skill = 0,
score = 0,
avatar_url = null,
robot = true }.
setup_players(Registrants , GameId , BotModule ) - > { Players , PlayerIdCounter }
setup_players(Registrants, GameId, BotModule) ->
F = fun(robot, {Acc, PlayerId}) ->
#'PlayerInfo'{id = UserId} = UserInfo = spawn_bot(GameId, BotModule),
NewAcc = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = true}, Acc),
{NewAcc, PlayerId + 1};
(UserId, {Acc, PlayerId}) ->
UserInfo = auth_server:get_user_info_by_user_id(UserId),
NewAcc = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = false}, Acc),
{NewAcc, PlayerId + 1}
end,
lists:foldl(F, {players_init(), 1}, Registrants).
%% finalize_tables_with_rejoin(TableModule, Tables) -> ok
finalize_tables_with_rejoin(TableModule, Tables) ->
F = fun(#table{mon_ref = MonRef, pid = TablePid}) ->
erlang:demonitor(MonRef, [flush]),
send_to_table(TableModule, TablePid, rejoin_players),
send_to_table(TableModule, TablePid, stop)
end,
lists:foreach(F, tables_to_list(Tables)).
%% finalize_tables_with_rejoin(TableModule, Tables) -> ok
finalize_tables_with_disconnect(TableModule, Tables) ->
F = fun(#table{mon_ref = MonRef, pid = TablePid}) ->
erlang:demonitor(MonRef, [flush]),
send_to_table(TableModule, TablePid, disconnect_players),
send_to_table(TableModule, TablePid, stop)
end,
lists:foreach(F, tables_to_list(Tables)).
req_replace_players(TableMod , Tables , Replacements , TabRequests ) - > NewRequests
req_replace_players(TableMod, Tables, Replacements, TabRequests) ->
F = fun({NewPlayerId, UserInfo, TableId, SeatNum}, Acc) ->
#table{pid = TablePid} = fetch_table(TableId, Tables),
table_req_replace_player(TableMod, TablePid, NewPlayerId, UserInfo, TableId, SeatNum, Acc)
end,
lists:foldl(F, TabRequests, Replacements).
table_req_replace_player(TableMod , TablePid , , UserInfo , TableId , SeatNum , TabRequests ) - > NewRequests
table_req_replace_player(TableMod, TablePid, PlayerId, UserInfo, TableId, SeatNum, TabRequests) ->
RequestId = make_ref(),
NewRequests = dict:store(RequestId, {replace_player, PlayerId, TableId, SeatNum}, TabRequests),
send_to_table(TableMod, TablePid, {replace_player, RequestId, UserInfo, PlayerId, SeatNum}),
NewRequests.
remove_table_from_next_turn_wl(TableId, StateName,
#state{game_id = GameId, cur_color = CurColor,
next_turn_wl = NextTurnWL, table_module = TableModule,
tables = Tables, tables_wl = TablesWL} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Removing table <~p> from the next turn waiting list: ~p.",
[GameId, TableId, NextTurnWL]),
NewNextTurnWL = lists:delete(TableId, NextTurnWL),
if NewNextTurnWL == [] ->
OppColor = opponent(CurColor),
{Die1, Die2} = roll(),
gas:info(?MODULE,"TRN_PAIRED <~p> The next turn waiting list is empty. Rolling dice for color ~p: ~p",
[GameId, OppColor, [Die1, Die2]]),
[send_to_table(TableModule, TablePid, {action, {rolls, OppColor, Die1, Die2}}) ||
#table{pid = TablePid} <- tables_to_list(Tables)],
gas:info(?MODULE,"TRN_PAIRED <~p> New next turn waiting list is ~p",
[GameId, TablesWL]),
{next_state, StateName, StateData#state{next_turn_wl = TablesWL,
cur_color = OppColor}};
true ->
gas:info(?MODULE,"TRN_PAIRED <~p> The next turn waiting list is not empty:~p. Waiting for the rest players.",
[GameId, NewNextTurnWL]),
{next_state, StateName, StateData#state{next_turn_wl = NewNextTurnWL}}
end.
%% players_init() -> players()
players_init() -> midict:new().
store_player(#player { } , Players ) - > NewPlayers
store_player(#player{id =Id, user_id = UserId} = Player, Players) ->
midict:store(Id, Player, [{user_id, UserId}], Players).
get_players_ids(Players) ->
[P#player.id || P <- players_to_list(Players)].
get_player_by_user_id(UserId, Players) ->
case midict:geti(UserId, user_id, Players) of
[Player] -> {ok, Player};
[] -> error
end.
%% players_to_list(Players) -> List
players_to_list(Players) -> midict:all_values(Players).
get_user_info(PlayerId, Players) ->
#player{user_info = UserInfo} = midict:fetch(PlayerId, Players),
UserInfo.
get_user_id(PlayerId, Players) ->
#player{user_id = UserId} = midict:fetch(PlayerId, Players),
UserId.
del_player(PlayerId , Players ) - > NewPlayers
del_player(PlayerId, Players) ->
midict:erase(PlayerId, Players).
tables_init() -> midict:new().
reg_table(TableId, Pid, MonRef, Tables) ->
reg_table(TableId, Pid, MonRef, _GlobalId = 0, _TableContext = undefined, Tables).
reg_table(TableId, Pid, MonRef, GlobalId, TableContext, Tables) ->
Table = #table{id = TableId, pid = Pid, mon_ref = MonRef, global_id = GlobalId,
state = initializing, context = TableContext},
store_table(Table, Tables).
update_created_table(TableId, Relay, Tables) ->
Table = midict:fetch(TableId, Tables),
NewTable = Table#table{relay = Relay, state = ?TABLE_STATE_READY},
store_table(NewTable, Tables).
store_table(#table{id = TableId, pid = Pid, mon_ref = MonRef, global_id = GlobalId} = Table, Tables) ->
midict:store(TableId, Table, [{pid, Pid}, {global_id, GlobalId}, {mon_ref, MonRef}], Tables).
fetch_table(TableId, Tables) -> midict:fetch(TableId, Tables).
%% get_table(TableId, Tables) -> {ok, Table} | error
get_table(TableId, Tables) -> midict:find(TableId, Tables).
get_table_pid(TabId, Tables) ->
#table{pid = TabPid} = midict:fetch(TabId, Tables),
TabPid.
get_table_by_mon_ref(MonRef, Tables) ->
case midict:geti(MonRef, mon_ref, Tables) of
[Table] -> Table;
[] -> not_found
end.
tables_to_list(Tables) -> midict:all_values(Tables).
seats_init() -> midict:new().
find_seats_by_player_id(PlayerId, Seats) ->
midict:geti(PlayerId, player_id, Seats).
find_seats_by_table_id(TabId, Seats) ->
midict:geti(TabId, table_id, Seats).
find_disconnected_seats(Seats) ->
midict:geti(false, connected, Seats).
find_free_seats(TableId, Seats) ->
midict:geti(true, {free_at_tab, TableId}, Seats).
find_free_seats(Seats) ->
midict:geti(true, free, Seats).
find_non_free_seats(Seats) ->
midict:geti(false, free, Seats).
find_registered_robot_seats(Seats) ->
[S || S = #seat{registered_by_table = true, is_bot = true} <- find_non_free_seats(Seats)].
fetch_seat(TableId, SeatNum, Seats) -> midict:fetch({TableId, SeatNum}, Seats).
set_seat(TabId , SeatNum , , IsBot , RegByTable , Connected , Free , Seats ) - > NewSeats
%% PlayerId = integer()
IsBot = RegByTable = Connected = undefined | boolean ( )
set_seat(TabId, SeatNum, PlayerId, IsBot, RegByTable, Connected, Free, Seats) ->
Seat = #seat{table = TabId, seat_num = SeatNum, player_id = PlayerId, is_bot = IsBot,
registered_by_table = RegByTable, connected = Connected, free = Free},
store_seat(Seat, Seats).
update_seat_connect_status(TableId, SeatNum, ConnStatus, Seats) ->
Seat = midict:fetch({TableId, SeatNum}, Seats),
NewSeat = Seat#seat{connected = ConnStatus},
store_seat(NewSeat, Seats).
store_seat(#seat{table = TabId, seat_num = SeatNum, player_id = PlayerId,
is_bot = _IsBot, registered_by_table = _RegByTable,
connected = Connected, free = Free} = Seat, Seats) ->
Indices = if Free == true ->
[{table_id, TabId}, {free, true}, {{free_at_tab, TabId}, true}];
true ->
[{table_id, TabId}, {free, false}, {{free_at_tab, TabId}, false},
{player_at_table, {PlayerId, TabId}}, {player_id, PlayerId},
{{connected, TabId}, Connected}, {connected, Connected}]
end,
midict:store({TabId, SeatNum}, Seat, Indices, Seats).
user_id_to_string(UserId) -> binary_to_list(UserId).
shuffle(List) -> deck:to_list(deck:shuffle(deck:from_list(List))).
split_by_num(Num, List) -> split_by_num(Num, List, []).
split_by_num(_, [], Acc) -> lists:reverse(Acc);
split_by_num(Num, List, Acc) ->
{Group, Rest} = lists:split(Num, List),
split_by_num(Num, Rest, [Group | Acc]).
start_timer(Timeout ) - > { TRef , Magic }
start_timer(Timeout) ->
Magic = make_ref(),
TRef = erlang:send_after(Timeout, self(), {timeout, Magic}),
{TRef, Magic}.
spawn_table(TableModule, GameId, TableId, Params) ->
TableModule:start(GameId, TableId, Params).
send_to_table(TableModule, TablePid, Message) ->
TableModule:parent_message(TablePid, Message).
get_param(ParamId, Params) ->
gas:info(?MODULE,"get_param/2 ParamId:~p", [ParamId]),
{_, Value} = lists:keyfind(ParamId, 1, Params),
Value.
get_option(OptionId, Params, DefValue) ->
proplists:get_value(OptionId, Params, DefValue).
create_decl_rec(GameType, CParams, GameId, Users) ->
#game_table{id = GameId,
name = proplists:get_value(table_name, CParams),
,
% trn_id,
game_type = GameType,
rounds = proplists:get_value(rounds, CParams),
sets = proplists:get_value(sets, CParams),
owner = proplists:get_value(owner, CParams),
timestamp = now(),
users = Users,
users_options = proplists:get_value(users_options, CParams),
game_mode = proplists:get_value(game_mode, CParams),
% game_options,
game_speed = proplists:get_value(speed, CParams),
friends_only = proplists:get_value(friends_only, CParams),
% invited_users = [],
private = proplists:get_value(private, CParams),
feel_lucky = false,
% creator,
age_limit = proplists:get_value(age, CParams),
% groups_only = [],
gender_limit = proplists:get_value(gender_limit, CParams),
% location_limit = "",
paid_only = proplists:get_value(paid_only, CParams),
deny_robots = proplists:get_value(deny_robots, CParams),
slang = proplists:get_value(slang, CParams),
deny_observers = proplists:get_value(deny_observers, CParams),
gosterge_finish = proplists:get_value(gosterge_finish, CParams),
double_points = proplists:get_value(double_points, CParams),
game_state = started,
game_process = self(),
game_module = ?MODULE,
pointing_rules = proplists:get_value(pointing_rules, CParams),
pointing_rules_ex = proplists:get_value(pointing_rules, CParams),
% game_process_monitor =
% tournament_type =
robots_replacement_allowed = proplists:get_value(robots_replacement_allowed, CParams)
}.
spawn_bot(GameId , BotModule ) - > UserInfo
spawn_bot(GameId, BotModule) ->
{NPid, UserInfo} = create_robot(BotModule, GameId),
BotModule:join_game(NPid),
UserInfo.
create_robot(BM, GameId) ->
UserInfo = auth_server:robot_credentials(),
{ok, NPid} = BM:start(self(), UserInfo, GameId),
{NPid, UserInfo}.
competition_roll() ->
{Die1, Die2} = roll(),
if Die1 == Die2 -> competition_roll();
true -> {Die1, Die2}
end.
roll() ->
Die1 = crypto:rand_uniform(1, 7),
Die2 = crypto:rand_uniform(1, 7),
{Die1, Die2}.
opponent(?WHITE) -> ?BLACK;
opponent(?BLACK) -> ?WHITE.
ext_to_color(1) -> ?WHITE;
ext_to_color(2) -> ?BLACK. | null | https://raw.githubusercontent.com/devaspot/games/a1f7c3169c53d31e56049e90e0094a3f309603ae/apps/server/src/tavla/tavla_paired.erl | erlang | -------------------------------------------------------------------
Description : The paired tavla logic
-------------------------------------------------------------------
Terms explanation:
GameId - uniq identifier of the tournament. Type: integer().
UserId - cross system identifier of a physical user. Type: binary() (or string()?).
tournament logic. Type: integer().
TableGlobalId - uniq identifier of a table in the system. Can be used
to refer to a table directly - without pointing to a tournament.
Type: integer()
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
External exports
gen_fsm callbacks
Static values
[robot | binary()]
Dynamic values
The register of tournament players
The register of tournament tables
Stores relation between players and tables seats
Tables waiting list
[TableId]
Context term of a table. For failover proposes.
?
% Time between last tour result showing and the tournament finish
TODO: Define this by a parameter. Number of seats per table
====================================================================
External functions
====================================================================
====================================================================
Server functions
====================================================================
===================================================================
===================================================================
TODO: More smart handling (failover) needed
Replace disconnected players by bots and start the round
handle_info({timeout, Magic}, ?STATE_FINISHED,
#state{timer_magic = Magic, tables = Tables, game_id = GameId,
table_module = TableModule} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to stopping the tournament.", [GameId]),
finalize_tables_with_disconnect(TableModule, Tables),
===================================================================
===================================================================
--------------------------------------------------------------------
--------------------------------------------------------------------
===================================================================
Ignoring the message
Ignoring the message
Update status of players
Process delayed registration requests
===================================================================
StateName,
tables = Tables} = StateData) ->
NewSeats = store_seat(Seat#seat{registered_by_table = true}, Seats),
%% Send response to a client for a delayed request
NewRegRequests =
{ok, From} ->
end,
reg_requests = NewRegRequests}};
Send response to a client for a delayed request
===================================================================
Game in progress. Find a seat for the user
The user is a registered member of the game (player)
The player is not registered by the table yet
The player is registered by the table. Return the table requisites
Not a member yet
===================================================================
series_result(TableResult) -> WithPlaceAndStatus
Status = winner | looser
nsm_accounts:transaction(binary_to_list(UserId), ?CURRENCY_QUOTA, -RealAmount, TI)
Types:
Status = winner | looser
prepare_users_prize_points(Points, Players) -> UsersPrizePoints
Types:
TODO: Deduct quota if replaces in the middle of a round
Types: Disconnected = [#seat{}]
prepare_table_players(PlayersList) -> TPlayersList
APlayerId = PlayerId | {empty, integer()}
finalize_tables_with_rejoin(TableModule, Tables) -> ok
finalize_tables_with_rejoin(TableModule, Tables) -> ok
players_init() -> players()
players_to_list(Players) -> List
get_table(TableId, Tables) -> {ok, Table} | error
PlayerId = integer()
trn_id,
game_options,
invited_users = [],
creator,
groups_only = [],
location_limit = "",
game_process_monitor =
tournament_type = | Author : < >
Created : Feb 01 , 2013
PlayerId - registration number of a player in the tournament . Type : integer ( )
TableId - uniq identifier of a table in the tournament . Used by the
-module(tavla_paired).
-behaviour(gen_fsm).
-include_lib("server/include/basic_types.hrl").
-include_lib("db/include/table.hrl").
-include_lib("db/include/transaction.hrl").
-include_lib("db/include/scoring.hrl").
-include_lib("server/include/game_tavla.hrl").
-export([start/1, start/2, start_link/2, reg/2]).
-export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
-export([table_message/3, client_message/2, client_request/2, client_request/3]).
-record(state,
game_id :: pos_integer(),
game_type :: atom(),
game_mode :: atom(),
params :: proplists:proplist(),
1 - 5
seats_per_table :: integer(),
table_module :: atom(),
bot_module :: atom(),
quota_per_round :: integer(),
kakush_for_winners :: integer(),
kakush_for_loser :: integer(),
win_game_points :: integer(),
mul_factor :: integer(),
bots_replacement_mode :: enabled | disabled,
common_params :: proplists:proplist(),
tour :: pos_integer(),
[ { TurnNum , TurnRes } ] , TurnRes = [ { , CommonPos , Points , Status } ]
table_id_counter :: pos_integer(),
player_id_counter :: pos_integer(),
cr_tab_requests,
reg_requests,
tab_requests,
timer :: undefined | reference(),
timer_magic :: undefined | reference(),
[ { TableId , TableResult } ]
[ { TableId , SeriesResult } ]
start_color :: white | black,
cur_color :: white | black,
}).
-record(player,
{
id :: pos_integer(),
user_id,
user_info :: #'PlayerInfo'{},
is_bot :: boolean()
}).
-record(table,
{
id :: pos_integer(),
global_id :: pos_integer(),
pid :: pid(),
{ RelayMod , RelayPid }
mon_ref :: reference(),
state :: initializing | ready | in_process | finished,
timer :: reference()
}).
-record(seat,
{
table :: pos_integer(),
seat_num :: integer(),
player_id :: undefined | pos_integer(),
is_bot :: undefined | boolean(),
registered_by_table :: undefined | boolean(),
connected :: undefined | boolean(),
free :: boolean()
}).
-define(STATE_INIT, state_init).
-define(STATE_WAITING_FOR_TABLES, state_waiting_for_tables).
-define(STATE_EMPTY_SEATS_FILLING, state_empty_seats_filling).
-define(STATE_WAITING_FOR_PLAYERS, state_waiting_for_players).
-define(STATE_TOUR_PROCESSING, state_tour_processing).
-define(STATE_TOUR_FINISHED, state_tour_finished).
-define(STATE_SHOW_TOUR_RESULT, state_show_tour_result).
-define(STATE_FINISHED, state_finished).
-define(TABLE_STATE_INITIALIZING, initializing).
-define(TABLE_STATE_READY, ready).
-define(TABLE_STATE_IN_PROGRESS, in_progress).
-define(TABLE_STATE_WAITING_NEW_ROUND, waiting_new_round).
-define(TABLE_STATE_FINISHED, finished).
Time between all table was created and starting a turn
Time between a round finish and start of a new one
Time between a tour finish and start of a new one
-define(TOURNAMENT_TYPE, paired).
-define(GAME_TYPE, game_tavla).
-define(WHITE, white).
-define(BLACK, black).
start([GameId, Params]) -> start(GameId, Params).
start(GameId, Params) ->
gen_fsm:start(?MODULE, [GameId, Params, self()], []).
start_link(GameId, Params) ->
gen_fsm:start_link(?MODULE, [GameId, Params, self()], []).
reg(Pid, User) ->
client_request(Pid, {join, User}, 10000).
table_message(Pid, TableId, Message) ->
gen_fsm:send_all_state_event(Pid, {table_message, TableId, Message}).
client_message(Pid, Message) ->
gen_fsm:send_all_state_event(Pid, {client_message, Message}).
client_request(Pid, Message) ->
client_request(Pid, Message, 5000).
client_request(Pid, Message, Timeout) ->
gen_fsm:sync_send_all_state_event(Pid, {client_request, Message}, Timeout).
init([GameId, Params, _Manager]) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Init started",[GameId]),
Registrants = get_param(registrants, Params),
GameMode = get_param(game_mode, Params),
GameName = get_param(game_name, Params),
TablesNum = get_param(tables_num, Params),
QuotaPerRound = get_param(quota_per_round, Params),
KakushForWinners = get_param(kakush_for_winners, Params),
KakushForLoser = get_param(kakush_for_loser, Params),
WinGamePoints = get_param(win_game_points, Params),
MulFactor = get_param(mul_factor, Params),
TableParams = get_param(table_params, Params),
TableModule = get_param(table_module, Params),
BotModule = get_param(bot_module, Params),
BotsReplacementMode = get_param(bots_replacement_mode, Params),
CommonParams = get_param(common_params, Params),
[gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Parameter <~p> : ~p", [GameId, P, V]) || {P, V} <- Params],
gas:info(?MODULE,"TRN_PAIRED <~p> started. Pid:~p", [GameId, self()]),
gen_fsm:send_all_state_event(self(), go),
{ok, ?STATE_INIT, #state{game_id = GameId,
game_type = ?GAME_TYPE,
game_mode = GameMode,
params = TableParams,
tables_num = TablesNum,
seats_per_table = ?SEATS_NUM,
table_module = TableModule,
bot_module = BotModule,
quota_per_round = QuotaPerRound,
kakush_for_winners = KakushForWinners,
kakush_for_loser = KakushForLoser,
win_game_points = WinGamePoints,
mul_factor = MulFactor,
registrants = Registrants,
bots_replacement_mode = BotsReplacementMode,
common_params = CommonParams,
table_id_counter = 1
}}.
handle_event(go, ?STATE_INIT, #state{game_id = GameId, registrants = Registrants,
game_type = GameType, bot_module = BotModule,
common_params = CommonParams} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Received a directive to starting the game.", [GameId]),
DeclRec = create_decl_rec(GameType, CommonParams, GameId, Registrants),
gproc:reg({p,l,self()}, DeclRec),
{Players, PlayerIdCounter} = setup_players(Registrants, GameId, BotModule),
NewStateData = StateData#state{players = Players,
player_id_counter = PlayerIdCounter},
init_tour(1, NewStateData);
handle_event({client_message, Message}, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Received the message from a client: ~p.", [GameId, Message]),
handle_client_message(Message, StateName, StateData);
handle_event({table_message, TableId, Message}, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Received the message from table <~p>: ~p.", [GameId, TableId, Message]),
handle_table_message(TableId, Message, StateName, StateData);
handle_event(Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Unhandled message(event) received in state <~p>: ~p.",
[GameId, StateName, Message]),
{next_state, StateName, StateData}.
handle_sync_event({client_request, Request}, From, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Received the request from a client: ~p.", [GameId, Request]),
handle_client_request(Request, From, StateName, StateData);
handle_sync_event(Request, From, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED_DBG <~p> Unhandled request(event) received in state <~p> from ~p: ~p.",
[GameId, StateName, From, Request]),
{reply, {error, unknown_request}, StateName, StateData}.
handle_info({'DOWN', MonRef, process, _Pid, _}, StateName,
#state{game_id = GameId, tables = Tables} = StateData) ->
case get_table_by_mon_ref(MonRef, Tables) of
#table{id = TableId} ->
gas:info(?MODULE,"TRN_PAIRED <~p> Table <~p> is down. Stopping", [GameId, TableId]),
{stop, {one_of_tables_down, TableId}, StateData};
not_found ->
{next_state, StateName, StateData}
end;
handle_info({timeout, Magic}, ?STATE_WAITING_FOR_PLAYERS,
#state{timer_magic = Magic, game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to start the tour.", [GameId]),
start_tour(StateData);
handle_info({timeout, Magic}, ?STATE_TOUR_PROCESSING,
#state{timer_magic = Magic, game_id = GameId, tables = Tables,
seats = Seats, players = Players, table_module = TableModule,
bot_module = BotModule, player_id_counter = PlayerIdCounter,
game_type = GameType, common_params = CommonParams,
tab_requests = Requests} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to start new round. Checking start conditions...", [GameId]),
DisconnectedSeats = find_disconnected_seats(Seats),
DisconnectedPlayers = [PlayerId || #seat{player_id = PlayerId} <- DisconnectedSeats],
ConnectedRealPlayers = [PlayerId || #player{id = PlayerId, is_bot = false} <- players_to_list(Players),
not lists:member(PlayerId, DisconnectedPlayers)],
case ConnectedRealPlayers of
Finish game
gas:info(?MODULE,"TRN_PAIRED <~p> No real players left in tournament. "
"Stopping the game.", [GameId]),
finalize_tables_with_disconnect(TableModule, Tables),
{stop, normal, StateData#state{tables = [], seats = []}};
gas:info(?MODULE,"TRN_PAIRED <~p> Enough real players in the game to continue. "
"Replacing disconnected players by bots.", [GameId]),
{Replacements, NewPlayers, NewSeats, NewPlayerIdCounter} =
replace_by_bots(DisconnectedSeats, GameId, BotModule, Players, Seats, PlayerIdCounter),
NewRequests = req_replace_players(TableModule, Tables, Replacements, Requests),
update_gproc(GameId, GameType, CommonParams, NewPlayers),
gas:info(?MODULE,"TRN_PAIRED <~p> The replacement is completed.", [GameId]),
start_round(StateData#state{tab_requests = NewRequests,
players = NewPlayers,
seats = NewSeats,
player_id_counter = NewPlayerIdCounter})
end;
handle_info({timeout, Magic}, ?STATE_TOUR_FINISHED,
#state{timer_magic = Magic, game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to finalize the tour.", [GameId]),
finalize_tour(StateData);
handle_info({timeout, Magic}, ?STATE_SHOW_TOUR_RESULT,
#state{timer_magic = Magic, game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to finalize the game.", [GameId]),
finalize_tournament(StateData);
handle_info({publish_series_result, TableId}, StateName,
#state{game_id = GameId, tables = Tables, table_module = TableModule,
series_results = SeriesResults} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Time to publish the series result for table <~p>.", [GameId, TableId]),
case fetch_table(TableId, Tables) of
#table{state = ?TABLE_STATE_FINISHED, pid = TablePid} ->
{_, SeriesResult} = lists:keyfind(TableId, 1, SeriesResults),
send_to_table(TableModule, TablePid, {show_series_result, SeriesResult});
_ ->
gas:info(?MODULE,"TRN_PAIRED <~p> Don't publish the series result because the state of table <~p> "
"is not 'finished'.", [GameId, TableId])
end,
{next_state, StateName, StateData};
{ stop , normal , StateData#state{tables = [ ] , seats = [ ] } } ;
handle_info(Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled message(info) received in state <~p>: ~p.",
[GameId, StateName, Message]),
{next_state, StateName, StateData}.
terminate(_Reason, _StateName, #state{game_id=GameId}=_StatData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Shutting down at state: <~p>. Reason: ~p",
[GameId, _StateName, _Reason]),
ok.
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
Internal functions
handle_client_message(Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled client message received in "
"state <~p>: ~p.", [GameId, StateName, Message]),
{next_state, StateName, StateData}.
handle_table_message(TableId, {player_connected, PlayerId},
StateName,
#state{seats = Seats} = StateData) ->
case find_seats_by_player_id(PlayerId, Seats) of
[#seat{seat_num = SeatNum}] ->
NewSeats = update_seat_connect_status(TableId, SeatNum, true, Seats),
{next_state, StateName, StateData#state{seats = NewSeats}};
{next_state, StateName, StateData}
end;
handle_table_message(TableId, {player_disconnected, PlayerId},
StateName, #state{seats = Seats} = StateData) ->
case find_seats_by_player_id(PlayerId, Seats) of
[#seat{seat_num = SeatNum}] ->
NewSeats = update_seat_connect_status(TableId, SeatNum, false, Seats),
{next_state, StateName, StateData#state{seats = NewSeats}};
{next_state, StateName, StateData}
end;
handle_table_message(TableId, {get_tables_states, PlayerId, Ref},
StateName,
#state{tables = Tables, table_module = TableModule} = StateData) ->
[send_to_table(TableModule, TPid, {send_table_state, TableId, PlayerId, Ref}) ||
#table{id = TId, pid = TPid} <- tables_to_list(Tables), TId =/= TableId],
{next_state, StateName, StateData};
handle_table_message(TableId, {table_created, Relay},
?STATE_WAITING_FOR_TABLES,
#state{tables = Tables, seats = Seats, seats_per_table = SeatsPerTable,
cr_tab_requests = TCrRequests, tables_num = TablesNum,
reg_requests = RegRequests} = StateData) ->
TabInitPlayers = dict:fetch(TableId, TCrRequests),
NewTCrRequests = dict:erase(TableId, TCrRequests),
TabSeats = find_seats_by_table_id(TableId, Seats),
F = fun(#seat{player_id = PlayerId} = S, Acc) ->
case lists:member(PlayerId, TabInitPlayers) of
true -> store_seat(S#seat{registered_by_table = true}, Acc);
false -> Acc
end
end,
NewSeats = lists:foldl(F, Seats, TabSeats),
TablePid = get_table_pid(TableId, Tables),
F2 = fun(PlayerId, Acc) ->
case dict:find(PlayerId, Acc) of
{ok, From} ->
gen_fsm:reply(From, {ok, {PlayerId, Relay, {?TAB_MOD, TablePid}}}),
dict:erase(PlayerId, Acc);
error -> Acc
end
end,
NewRegRequests = lists:foldl(F2, RegRequests, TabInitPlayers),
NewTables = update_created_table(TableId, Relay, Tables),
case dict:size(NewTCrRequests) of
0 ->
case enough_players(NewSeats, TablesNum*SeatsPerTable) of
true ->
{TRef, Magic} = start_timer(?WAITING_PLAYERS_TIMEOUT),
{next_state, ?STATE_WAITING_FOR_PLAYERS,
StateData#state{tables = NewTables, seats = NewSeats, cr_tab_requests = NewTCrRequests,
reg_requests = NewRegRequests, timer = TRef, timer_magic = Magic}};
false ->
{next_state, ?STATE_EMPTY_SEATS_FILLING,
StateData#state{tables = NewTables, seats = NewSeats, cr_tab_requests = NewTCrRequests,
reg_requests = NewRegRequests}}
end;
_ -> {next_state, ?STATE_WAITING_FOR_TABLES,
StateData#state{tables = NewTables, seats = NewSeats,
cr_tab_requests = NewTCrRequests, reg_requests = NewRegRequests}}
end;
handle_table_message(TableId, {round_finished, NewScoringState, _RoundScore, _TotalScore},
?STATE_TOUR_PROCESSING = StateName,
#state{game_id = GameId, tables = Tables, table_module = TableModule,
tables_wl = WL} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Round is finished (table <~p>).", [GameId, TableId]),
#table{pid = TablePid} = Table = fetch_table(TableId, Tables),
NewTable = Table#table{context = NewScoringState, state = ?TABLE_STATE_WAITING_NEW_ROUND},
NewTables = store_table(NewTable, Tables),
send_to_table(TableModule, TablePid, show_round_result),
NewWL = lists:delete(TableId, WL),
[send_to_table(TableModule, TPid, {playing_tables_num, length(NewWL)})
|| #table{pid = TPid, state = ?TABLE_STATE_WAITING_NEW_ROUND} <- tables_to_list(Tables)],
NewStateData = StateData#state{tables = NewTables,
tables_wl = NewWL},
if NewWL == [] ->
{TRef, Magic} = start_timer(?REST_TIMEOUT),
{next_state, StateName, NewStateData#state{timer = TRef,
timer_magic = Magic}};
true ->
remove_table_from_next_turn_wl(TableId, StateName, NewStateData)
end;
handle_table_message(TableId, {game_finished, TableContext, _RoundScore, TableScore},
?STATE_TOUR_PROCESSING = StateName,
#state{game_id = GameId, tables = Tables, tables_wl = WL,
table_module = TableModule, tables_results = TablesResults,
game_type = GameType, game_mode = GameMode, mul_factor = MulFactor,
kakush_for_winners = KakushForWinners, kakush_for_loser = KakushForLoser,
win_game_points = WinGamePoints, players = Players,
series_results = SeriesResults} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Last round of the set is finished (table <~p>).", [GameId, TableId]),
NewTablesResults = [{TableId, TableScore} | TablesResults],
#table{pid = TablePid} = Table = fetch_table(TableId, Tables),
NewTable = Table#table{context = TableContext, state = ?TABLE_STATE_FINISHED},
NewTables = store_table(NewTable, Tables),
send_to_table(TableModule, TablePid, show_round_result),
NewWL = lists:delete(TableId, WL),
[send_to_table(TableModule, TPid, {playing_tables_num, length(NewWL)})
|| #table{pid = TPid, state = ?TABLE_STATE_FINISHED} <- tables_to_list(Tables)],
SeriesResult = series_result(TableScore),
NewSeriesResults = [{TableId, SeriesResult} | SeriesResults],
gas:info(?MODULE,"TRN_PAIRED <~p> Set result: ~p", [GameId, SeriesResult]),
Points = calc_players_prize_points(SeriesResult, KakushForWinners, KakushForLoser, WinGamePoints, MulFactor, Players),
UsersPrizePoints = prepare_users_prize_points(Points, Players),
gas:info(?MODULE,"TRN_PAIRED <~p> Prizes: ~p", [GameId, UsersPrizePoints]),
add_points_to_accounts(UsersPrizePoints, GameId, GameType, GameMode, MulFactor),
NewStateData = StateData#state{tables = NewTables,
tables_results = NewTablesResults,
series_results = NewSeriesResults,
tables_wl = NewWL},
erlang:send_after(?REST_TIMEOUT, self(), {publish_series_result, TableId}),
if NewWL == [] ->
{TRef, Magic} = start_timer(?REST_TIMEOUT),
{next_state, ?STATE_TOUR_FINISHED, NewStateData#state{timer = TRef,
timer_magic = Magic}};
true ->
remove_table_from_next_turn_wl(TableId, StateName, NewStateData)
end;
handle_table_message(TableId, {response, RequestId, Response},
StateName,
#state{game_id = GameId, tab_requests = TabRequests} = StateData) ->
NewTabRequests = dict:erase(RequestId, TabRequests),
case dict:find(RequestId, TabRequests) of
{ok, ReqContext} ->
gas:info(?MODULE,"TRN_PAIRED <~p> The a response received from table <~p>. "
"RequestId: ~p. Request context: ~p. Response: ~p",
[GameId, TableId, RequestId, ReqContext, Response]),
handle_table_response(TableId, ReqContext, Response, StateName,
StateData#state{tab_requests = NewTabRequests});
error ->
gas:error(?MODULE,"TRN_PAIRED <~p> Table <~p> sent a response for unknown request. "
"RequestId: ~p. Response", []),
{next_state, StateName, StateData#state{tab_requests = NewTabRequests}}
end;
handle_table_message(TableId, {game_event, #tavla_next_turn{table_id = TableId,
color = ExtColor}},
?STATE_TOUR_PROCESSING = StateName,
#state{cur_color = CurColor, next_turn_wl = NextTurnWL,
game_id = GameId} = StateData) ->
Color = ext_to_color(ExtColor),
gas:info(?MODULE,"TRN_PAIRED <~p> The 'tavla_next_turn event' received from table <~p>. "
"Color: ~p. CurColor: ~p, WaitList: ~p",
[GameId, TableId, Color, CurColor, NextTurnWL]),
Assert
Assert
remove_table_from_next_turn_wl(TableId, StateName, StateData);
handle_table_message(TableId, {game_event, GameEvent},
?STATE_TOUR_PROCESSING = StateName,
#state{tables = Tables, table_module = TableModule} = StateData) ->
[send_to_table(TableModule, TablePid, {game_event, GameEvent}) ||
#table{pid = TablePid, id = TId} <- tables_to_list(Tables), TId =/= TableId],
{next_state, StateName, StateData};
handle_table_message(_TableId, {table_state_event, DestTableId, PlayerId, Ref, StateEvent},
StateName,
#state{tables = Tables, table_module = TableModule} = StateData) ->
case get_table(DestTableId, Tables) of
{ok, #table{pid = TPid}} ->
send_to_table(TableModule, TPid, {table_state_event, PlayerId, Ref, StateEvent});
error -> do_nothing
end,
{next_state, StateName, StateData};
handle_table_message(TableId, Message, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled table message received from table <~p> in "
"state <~p>: ~p.", [GameId, TableId, StateName, Message]),
{next_state, StateName, StateData}.
handle_table_response(_TableId , { register_player , , TableId , SeatNum } , ok = _ Response ,
# state{reg_requests = RegRequests , seats = Seats ,
Seat = fetch_seat(TableId , SeatNum , Seats ) ,
case dict : find(PlayerId , RegRequests ) of
# table{relay = Relay , pid = TablePid } = fetch_table(TableId , Tables ) ,
gen_fsm : reply(From , { ok , { PlayerId , Relay , { ? TAB_MOD , TablePid } } } ) ,
dict : erase(PlayerId , RegRequests ) ;
error - > RegRequests
{ next_state , StateName , StateData#state{seats = NewSeats ,
handle_table_response(_TableId, {replace_player, PlayerId, TableId, SeatNum}, ok = _Response,
StateName,
#state{reg_requests = RegRequests, seats = Seats,
tables = Tables, table_module = TableMod} = StateData) ->
Seat = fetch_seat(TableId, SeatNum, Seats),
NewSeats = store_seat(Seat#seat{registered_by_table = true}, Seats),
NewRegRequests =
case dict:find(PlayerId, RegRequests) of
{ok, From} ->
#table{relay = Relay, pid = TablePid} = fetch_table(TableId, Tables),
gen_fsm:reply(From, {ok, {PlayerId, Relay, {TableMod, TablePid}}}),
dict:erase(PlayerId, RegRequests);
error -> RegRequests
end,
{next_state, StateName, StateData#state{seats = NewSeats,
reg_requests = NewRegRequests}};
handle_table_response(TableId, RequestContext, Response, StateName,
#state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled 'table response' received from table <~p> "
"in state <~p>. Request context: ~p. Response: ~p.",
[GameId, TableId, StateName, RequestContext, Response]),
{next_state, StateName, StateData}.
handle_client_request({join, UserInfo}, From, StateName,
#state{game_id = GameId, reg_requests = RegRequests,
seats = Seats, players=Players, tables = Tables,
bots_replacement_mode = BotsReplacementMode,
table_module = TableMod} = StateData) ->
#'PlayerInfo'{id = UserId, robot = _IsBot} = UserInfo,
gas:info(?MODULE,"TRN_PAIRED <~p> The 'Join' request received from user: ~p.", [GameId, UserId]),
if StateName == ?STATE_FINISHED ->
gas:info(?MODULE,"TRN_PAIRED <~p> The game is finished. "
"Reject to join user ~p.", [GameId, UserId]),
{reply, {error, finished}, StateName, StateData};
case get_player_by_user_id(UserId, Players) of
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p is a registered member of the game. "
"Allow to join.", [GameId, UserId]),
[#seat{table = TableId, registered_by_table = RegByTable}] = find_seats_by_player_id(PlayerId, Seats),
case RegByTable of
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p not yet regirested by the table. "
"Add the request to the waiting pool.", [GameId, UserId]),
NewRegRequests = dict:store(PlayerId, From, RegRequests),
{next_state, StateName, StateData#state{reg_requests = NewRegRequests}};
gas:info(?MODULE,"TRN_PAIRED <~p> Return the join response for player ~p immediately.",
[GameId, UserId]),
#table{relay = Relay, pid = TPid} = fetch_table(TableId, Tables),
{reply, {ok, {PlayerId, Relay, {TableMod, TPid}}}, StateName, StateData}
end;
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p is not a member of the game.", [GameId, UserId]),
case find_free_seats(Seats) of
[] when BotsReplacementMode == disabled ->
gas:info(?MODULE,"TRN_PAIRED <~p> No free seats for user ~p. Robots replacement is disabled. "
"Reject to join.", [GameId, UserId]),
{reply, {error, not_allowed}, StateName, StateData};
[] when BotsReplacementMode == enabled ->
gas:info(?MODULE,"TRN_PAIRED <~p> No free seats for user ~p. Robots replacement is enabled. "
"Tring to find a robot for replace.", [GameId, UserId]),
case find_registered_robot_seats(Seats) of
[] ->
gas:info(?MODULE,"TRN_PAIRED <~p> No robots for replacement by user ~p. "
"Reject to join.", [GameId, UserId]),
{reply, {error, not_allowed}, StateName, StateData};
[#seat{table = TableId, seat_num = SeatNum, player_id = OldPlayerId} | _] ->
gas:info(?MODULE,"TRN_PAIRED <~p> There is a robot for replacement by user ~p. "
"Registering.", [GameId, UserId]),
reg_player_with_replace(UserInfo, TableId, SeatNum, OldPlayerId, From, StateName, StateData)
end;
[#seat{table = TableId, seat_num = SeatNum} | _] ->
gas:info(?MODULE,"TRN_PAIRED <~p> There is a free seat for user ~p. "
"Registering.", [GameId, UserId]),
reg_new_player(UserInfo, TableId, SeatNum, From, StateName, StateData)
end
end
end;
handle_client_request(Request, From, StateName, #state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Unhandled client request received from ~p in "
"state <~p>: ~p.", [GameId, From, StateName, Request]),
{reply, {error, unexpected_request}, StateName, StateData}.
init_tour(Tour, #state{game_id = GameId, table_module = TableModule,
params = TableParams, players = Players, tables_num = TablesNum,
table_id_counter = TableIdCounter, tables = OldTables,
seats_per_table = SeatsPerTable} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Initializing tour <~p>...", [GameId, Tour]),
PlayersList = prepare_players_for_new_tour(0, Players),
{NewTables, Seats, NewTableIdCounter, CrRequests} =
setup_tables(TableModule, PlayersList, SeatsPerTable, TablesNum, _TTable = undefined,
Tour, _Tours = undefined, TableIdCounter, GameId, TableParams),
if Tour > 1 -> finalize_tables_with_rejoin(TableModule, OldTables);
true -> do_nothing
end,
gas:info(?MODULE,"TRN_PAIRED <~p> Initializing of tour <~p> is finished. "
"Waiting creating confirmations from the tours' tables...",
[GameId, Tour]),
{next_state, ?STATE_WAITING_FOR_TABLES, StateData#state{tables = NewTables,
seats = Seats,
table_id_counter = NewTableIdCounter,
cr_tab_requests = CrRequests,
tour = Tour,
reg_requests = dict:new(),
tab_requests = dict:new(),
tables_results = [],
series_results = []
}}.
start_tour(#state{game_id = GameId, tour = Tour} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Starting tour <~p>...", [GameId, Tour]),
start_round(StateData#state{start_color = undefined}).
start_round(#state{game_id = GameId, game_type = GameType, game_mode = GameMode,
mul_factor = MulFactor, quota_per_round = Amount,
tables = Tables, players = Players, table_module = TableModule,
start_color = StartColor} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Starting new round...", [GameId]),
UsersIds = [UserId || #player{user_id = UserId, is_bot = false} <- players_to_list(Players)],
deduct_quota(GameId, GameType, GameMode, Amount, MulFactor, UsersIds),
TablesList = tables_to_list(Tables),
[send_to_table(TableModule, Pid, start_round) || #table{pid = Pid} <- TablesList],
F = fun(Table, Acc) ->
store_table(Table#table{state = ?TABLE_STATE_IN_PROGRESS}, Acc)
end,
NewTables = lists:foldl(F, Tables, TablesList),
WL = [T#table.id || T <- TablesList],
gas:info(?MODULE,"TRN_PAIRED <~p> The round is started. Processing...", [GameId]),
NewStartColor =
if StartColor == undefined ->
{Die1, Die2} = competition_roll(),
[send_to_table(TableModule, Pid, {action, {competition_rolls, Die1, Die2}})
|| #table{pid = Pid} <- TablesList],
if Die1 > Die2 -> ?WHITE;
true -> ?BLACK end;
true ->
OppColor = opponent(StartColor),
{Die1, Die2} = roll(),
[send_to_table(TableModule, Pid, {action, {rolls, OppColor, Die1, Die2}})
|| #table{pid = Pid} <- TablesList],
OppColor
end,
gas:info(?MODULE,"TRN_PAIRED <~p> Start color is ~p", [GameId, NewStartColor]),
{next_state, ?STATE_TOUR_PROCESSING, StateData#state{tables = NewTables,
tables_wl = WL,
start_color = NewStartColor,
cur_color = NewStartColor,
next_turn_wl = WL}}.
finalize_tour(#state{game_id = GameId} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Finalizing the tour...", [GameId]),
{TRef, Magic} = start_timer(?SHOW_SERIES_RESULT_TIMEOUT),
gas:info(?MODULE,"TRN_PAIRED <~p> The tour is finalized. "
"Waiting some time (~p secs) before continue...",
[GameId, ?SHOW_SERIES_RESULT_TIMEOUT div 1000]),
{next_state, ?STATE_SHOW_TOUR_RESULT, StateData#state{timer = TRef, timer_magic = Magic}}.
finalize_tournament(#state{game_id = GameId, table_module = TableModule,
tables = Tables} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Finalizing the tournament...", [GameId]),
finalize_tables_with_disconnect(TableModule, Tables),
gas:info(?MODULE,"TRN_PAIRED <~p> Finalization completed. Stopping...", [GameId]),
{stop, normal, StateData#state{tables = [], seats = []}}.
Types : TableResult = [ { PlayerId , Points } ]
WithPlaceAndStatus = [ { PlayerId , Place , Points , Status } ]
series_result(TableResult) ->
{_, PointsList} = lists:unzip(TableResult),
Max = lists:max(PointsList),
F = fun({Pl, Points}, {CurPlace, CurPos, LastPoints}) ->
if Points == LastPoints ->
{{Pl, CurPlace, Points, if Points == Max -> winner; true -> looser end},
{CurPlace, CurPos + 1, Points}};
true ->
{{Pl, CurPos, Points, looser},
{CurPos, CurPos + 1, Points}}
end
end,
{WithPlaceAndStatus, _} = lists:mapfoldl(F, {1, 1, Max}, lists:reverse(lists:keysort(2, TableResult))),
WithPlaceAndStatus.
deduct_quota(GameId, GameType, GameMode, Amount, MulFactor, UsersIds) ->
RealAmount = Amount * MulFactor,
[begin
TI = #ti_game_event{game_name = GameType, game_mode = GameMode,
id = GameId, double_points = MulFactor,
type = start_round, tournament_type = ?TOURNAMENT_TYPE},
kvs:add(#transaction{id=kvs:next_id(transaction,1),
feed_id={quota,binary_to_list(UserId)},amount=-RealAmount,comment=TI})
end || UserId <- UsersIds],
ok.
calc_players_prize_points(SeriesResult , KakushForWinner , KakushForLoser ,
WinGamePoints , MulFactor , Players ) - > Points
SeriesResult = [ { , _ Pos , _ Points , Status } ]
Points = [ { , KakushPoints , GamePoints } ]
calc_players_prize_points(SeriesResult, KakushForWinners, KakushForLoser, WinGamePoints, MulFactor, Players) ->
SeriesResult1 = [begin
#'PlayerInfo'{id = UserId, robot = Robot} = get_user_info(PlayerId, Players),
Paid = is_paid(user_id_to_string(UserId)),
Winner = Status == winner,
{PlayerId, Winner, Robot, Paid}
end || {PlayerId, _Pos, _Points, Status} <- SeriesResult],
Paids = [PlayerId || {PlayerId, _Winner, _Robot, _Paid = true} <- SeriesResult1],
Winners = [PlayerId || {PlayerId, _Winner = true, _Robot, _Paid} <- SeriesResult1],
TotalNum = length(SeriesResult),
PaidsNum = length(Paids),
WinnersNum = length(Winners),
KakushPerWinner = round(((KakushForWinners * MulFactor) * PaidsNum div TotalNum) / WinnersNum),
KakushPerLoser = (KakushForLoser * MulFactor) * PaidsNum div TotalNum,
WinGamePoints1 = WinGamePoints * MulFactor,
[begin
{KakushPoints, GamePoints} = calc_points(KakushPerWinner, KakushPerLoser, WinGamePoints1, Paid, Robot, Winner),
{PlayerId, KakushPoints, GamePoints}
end || {PlayerId, Winner, Robot, Paid} <- SeriesResult1].
calc_points(KakushPerWinner, KakushPerLoser, WinGamePoints, Paid, Robot, Winner) ->
if Robot -> {0, 0};
not Paid andalso Winner -> {0, WinGamePoints};
not Paid -> {0, 0};
Paid andalso Winner -> {KakushPerWinner, WinGamePoints};
Paid -> {KakushPerLoser, 0}
end.
Points = [ { , KakushPoints , GamePoints } ]
UserPrizePoints = [ { UserIdStr , KakushPoints , GamePoints } ]
prepare_users_prize_points(Points, Players) ->
[{user_id_to_string(get_user_id(PlayerId, Players)), K, G} || {PlayerId, K, G} <- Points].
is_paid(UserId) -> nsm_accounts:user_paid(UserId).
add_points_to_accounts(Points , GameId , GameType , , MulFactor ) - > ok
Types : Points = [ { UserId , KakushPoints , GamePoints } ]
add_points_to_accounts(Points, GameId, GameType, GameMode, MulFactor) ->
TI = #ti_game_event{game_name = GameType, game_mode = GameMode,
id = GameId, double_points = MulFactor,
type = game_end, tournament_type = ?TOURNAMENT_TYPE},
[begin
if KakushPoints =/= 0 ->
kvs:add(#transaction{id=kvs:next_id(transaction,1),
feed_id={kakush,UserId},amount=KakushPoints,comment=TI});
ok = nsm_accounts : , ? CURRENCY_KAKUSH , KakushPoints , TI ) ;
true -> do_nothing
end,
if GamePoints =/= 0 ->
kvs:add(#transaction{id=kvs:next_id(transaction,1),
feed_id={game_points,UserId},amount=GamePoints,comment=TI});
ok = nsm_accounts : , ? CURRENCY_GAME_POINTS , GamePoints , TI ) ;
true -> do_nothing
end
end || {UserId, KakushPoints, GamePoints} <- Points],
ok.
reg_player_with_replace(UserInfo, TableId, SeatNum, OldPlayerId, From, StateName,
#state{game_id = GameId, players = Players, tables = Tables,
game_type = GameType, seats = Seats, player_id_counter = PlayerId,
tab_requests = TabRequests, reg_requests = RegRequests,
table_module = TableModule, common_params = CommonParams,
game_mode = GameMode, mul_factor = MulFactor,
quota_per_round = Amount} = StateData) ->
#'PlayerInfo'{id = UserId, robot = IsBot} = UserInfo,
NewPlayers = del_player(OldPlayerId, Players),
NewPlayers2 = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = IsBot}, NewPlayers),
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p registered as player <~p>.", [GameId, UserId, PlayerId]),
NewSeats = set_seat(TableId, SeatNum, PlayerId, _Bot = false, _RegByTable = false,
_Connected = false, _Free = false, Seats),
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p assigned to seat <~p> of table <~p>.", [GameId, UserId, SeatNum, TableId]),
NewRegRequests = dict:store(PlayerId, From, RegRequests),
#table{pid = TablePid, state = TableStateName} = fetch_table(TableId, Tables),
NewTabRequests = table_req_replace_player(TableModule, TablePid, PlayerId, UserInfo, TableId, SeatNum, TabRequests),
case TableStateName of
?TABLE_STATE_IN_PROGRESS when not IsBot->
gas:info(?MODULE,"TRN_PAIRED <~p> User ~p is a real player <~p> and he was registered in the middle of the round."
"So deduct some quota.", [GameId, UserId, PlayerId]),
deduct_quota(GameId, GameType, GameMode, Amount, MulFactor, [UserId]);
_ -> do_nothing
end,
update_gproc(GameId, GameType, CommonParams, NewPlayers2),
{next_state, StateName, StateData#state{players = NewPlayers2,
seats = NewSeats,
player_id_counter = PlayerId + 1,
tab_requests = NewTabRequests,
reg_requests = NewRegRequests}}.
reg_new_player(UserInfo, TableId, SeatNum, From, StateName,
#state{game_id = GameId, players = Players, tables = Tables,
game_type = GameType, seats = Seats, player_id_counter = PlayerId,
tab_requests = TabRequests, reg_requests = RegRequests,
table_module = TableModule, common_params = CommonParams,
tables_num = TablesNum, seats_per_table = SeatsPerTable
} = StateData) ->
{SeatNum, NewPlayers, NewSeats} =
register_new_player(UserInfo, TableId, Players, Seats, PlayerId),
TablePid = get_table_pid(TableId, Tables),
NewTabRequests = table_req_replace_player(TableModule, TablePid, PlayerId, UserInfo,
TableId, SeatNum, TabRequests),
NewRegRequests = dict:store(PlayerId, From, RegRequests),
update_gproc(GameId, GameType, CommonParams, NewPlayers),
NewStateData = StateData#state{reg_requests = NewRegRequests, tab_requests = NewTabRequests,
players = NewPlayers, seats = NewSeats,
player_id_counter = PlayerId + 1},
EnoughPlayers = enough_players(NewSeats, TablesNum*SeatsPerTable),
if StateName == ?STATE_EMPTY_SEATS_FILLING andalso EnoughPlayers ->
gas:info(?MODULE,"TRN_PAIRED <~p> It's enough players registered to start the game. "
"Initiating the procedure.", [GameId]),
start_tour(NewStateData);
true ->
gas:info(?MODULE,"TRN_PAIRED <~p> Not enough players registered to start the game. "
"Waiting for more registrations.", [GameId]),
{next_state, StateName, NewStateData}
end.
register_new_player(UserInfo , TableId , Players , Seats , ) - > { SeatNum , NewPlayers , NewSeats }
register_new_player(UserInfo, TableId, Players, Seats, PlayerId) ->
#'PlayerInfo'{id = UserId, robot = Bot} = UserInfo,
[#seat{seat_num = SeatNum} |_] = find_free_seats(TableId, Seats),
NewSeats = set_seat(TableId, SeatNum, PlayerId, Bot, _RegByTable = false,
_Connected = false, _Free = false, Seats),
NewPlayers = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = Bot}, Players),
{SeatNum, NewPlayers, NewSeats}.
replace_by_bots(DisconnectedSeats , GameId , BotModule , Players , Seats , PlayerIdCounter ) - >
{ Replacements , NewPlayers , NewSeats , }
Replacements = [ { PlayerId , UserInfo , TableId , SeatNum } ]
replace_by_bots(DisconnectedSeats, GameId, BotModule, Players, Seats, PlayerIdCounter) ->
F = fun(#seat{player_id = PlayerId,
table = TableId,
seat_num = SeatNum}, {RAcc, PAcc, SAcc, Counter}) ->
NewPAcc1 = del_player(PlayerId, PAcc),
NewSAcc = set_seat(TableId, SeatNum, _PlayerId = Counter, _Bot = true,
_RegByTable = false, _Connected = false, _Free = false, SAcc),
#'PlayerInfo'{id = UserId} = UserInfo = spawn_bot(GameId, BotModule),
NewPAcc = store_player(#player{id = Counter, user_id = UserId,
user_info = UserInfo, is_bot = true}, NewPAcc1),
NewRAcc = [{Counter, UserInfo, TableId, SeatNum} | RAcc],
{NewRAcc, NewPAcc, NewSAcc, Counter + 1}
end,
lists:foldl(F, {[], Players, Seats, PlayerIdCounter}, DisconnectedSeats).
enough_players(Seats, Threshold) ->
NonEmptySeats = find_non_free_seats(Seats),
length(NonEmptySeats) >= Threshold.
update_gproc(GameId, GameType, CommonParams, Players) ->
Users = [if Bot -> robot; true -> UId end || #player{user_id = UId, is_bot = Bot}
<- players_to_list(Players)],
DeclRec = create_decl_rec(GameType, CommonParams, GameId, Users),
gproc:set_value({p,l,self()}, DeclRec).
prepare_players_for_new_tour(InitialPoints , Players ) - > [ { PlayerId , UserInfo , Points } ]
prepare_players_for_new_tour(InitialPoints, Players) ->
[{PlayerId, UserInfo, InitialPoints}
|| #player{id = PlayerId, user_info = UserInfo} <- players_to_list(Players)].
setup_tables(Players , TTable , TableIdCounter , GameId , TableParams ) - >
{ Tables , Seats , , CrRequests }
Types : Players = [ { PlayerId , UserInfo , Points } | empty ]
TTable = [ { Tour , [ { UserId , CommonPos , Score , Status } ] } ]
setup_tables(TableMod, Players, SeatsPerTable, TablesNum, TTable, Tour, Tours, TableIdCounter, GameId, TableParams) ->
EmptySeatsNum = SeatsPerTable*TablesNum - length(Players),
Players2 = lists:duplicate(EmptySeatsNum, empty) ++ Players,
SPlayers = shuffle(Players2),
Groups = split_by_num(SeatsPerTable, SPlayers),
F = fun(Group, {TAcc, SAcc, TableId, TCrRequestsAcc}) ->
TPlayers = prepare_table_players(Group),
TableParams2 = [{players, TPlayers}, {ttable, TTable}, {tour, Tour},
{tours, Tours}, {parent, {?MODULE, self()}} | TableParams],
{ok, TabPid} = spawn_table(TableMod, GameId, TableId, TableParams2),
MonRef = erlang:monitor(process, TabPid),
NewTAcc = reg_table(TableId, TabPid, MonRef, TAcc),
NewSAcc = reg_seats(TableId, TPlayers, SAcc),
PlayersIds = [PlId || {PlId, _, _} <- Group, PlId =/= empty],
NewTCrRequestsAcc = dict:store(TableId, PlayersIds, TCrRequestsAcc),
{NewTAcc, NewSAcc, TableId + 1, NewTCrRequestsAcc}
end,
lists:foldl(F, {tables_init(), seats_init(), TableIdCounter, dict:new()}, Groups).
reg_seats(TableId, TPlayers, Seats) ->
F = fun({{empty, _}, _PlayerInfo, SNum, _Points}, Acc) ->
set_seat(TableId, SNum, _PlId = undefined, _Bot = undefined, _Reg = false, _Conn = false, _Free = true, Acc);
({PlId, #'PlayerInfo'{robot = Bot}, SNum, _Points}, Acc) ->
set_seat(TableId, SNum, PlId, Bot, _Reg = false, _Conn = false, _Free = false, Acc)
end,
lists:foldl(F, Seats, TPlayers).
PlayersList = { PlayerId , UserInfo , Points } | empty
TPlayersList = { APlayerId , UserInfo , SeatNum , Points }
prepare_table_players(PlayersList) ->
F = fun({PlayerId, UserInfo, Points}, SeatNum) ->
{{PlayerId, UserInfo, SeatNum, Points}, SeatNum+1};
(empty, SeatNum) ->
{{_PlayerId = {empty, SeatNum}, empty_seat_userinfo(SeatNum), SeatNum, _Points=0}, SeatNum+1}
end,
{TPlayers, _} = lists:mapfoldl(F, 1, PlayersList),
TPlayers.
empty_seat_userinfo(Num) ->
#'PlayerInfo'{id = list_to_binary(["empty_", integer_to_list(Num)]),
login = <<"">>,
name = <<"empty">>,
surname = <<" ">>,
age = 0,
skill = 0,
score = 0,
avatar_url = null,
robot = true }.
setup_players(Registrants , GameId , BotModule ) - > { Players , PlayerIdCounter }
setup_players(Registrants, GameId, BotModule) ->
F = fun(robot, {Acc, PlayerId}) ->
#'PlayerInfo'{id = UserId} = UserInfo = spawn_bot(GameId, BotModule),
NewAcc = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = true}, Acc),
{NewAcc, PlayerId + 1};
(UserId, {Acc, PlayerId}) ->
UserInfo = auth_server:get_user_info_by_user_id(UserId),
NewAcc = store_player(#player{id = PlayerId, user_id = UserId,
user_info = UserInfo, is_bot = false}, Acc),
{NewAcc, PlayerId + 1}
end,
lists:foldl(F, {players_init(), 1}, Registrants).
finalize_tables_with_rejoin(TableModule, Tables) ->
F = fun(#table{mon_ref = MonRef, pid = TablePid}) ->
erlang:demonitor(MonRef, [flush]),
send_to_table(TableModule, TablePid, rejoin_players),
send_to_table(TableModule, TablePid, stop)
end,
lists:foreach(F, tables_to_list(Tables)).
finalize_tables_with_disconnect(TableModule, Tables) ->
F = fun(#table{mon_ref = MonRef, pid = TablePid}) ->
erlang:demonitor(MonRef, [flush]),
send_to_table(TableModule, TablePid, disconnect_players),
send_to_table(TableModule, TablePid, stop)
end,
lists:foreach(F, tables_to_list(Tables)).
req_replace_players(TableMod , Tables , Replacements , TabRequests ) - > NewRequests
req_replace_players(TableMod, Tables, Replacements, TabRequests) ->
F = fun({NewPlayerId, UserInfo, TableId, SeatNum}, Acc) ->
#table{pid = TablePid} = fetch_table(TableId, Tables),
table_req_replace_player(TableMod, TablePid, NewPlayerId, UserInfo, TableId, SeatNum, Acc)
end,
lists:foldl(F, TabRequests, Replacements).
table_req_replace_player(TableMod , TablePid , , UserInfo , TableId , SeatNum , TabRequests ) - > NewRequests
table_req_replace_player(TableMod, TablePid, PlayerId, UserInfo, TableId, SeatNum, TabRequests) ->
RequestId = make_ref(),
NewRequests = dict:store(RequestId, {replace_player, PlayerId, TableId, SeatNum}, TabRequests),
send_to_table(TableMod, TablePid, {replace_player, RequestId, UserInfo, PlayerId, SeatNum}),
NewRequests.
remove_table_from_next_turn_wl(TableId, StateName,
#state{game_id = GameId, cur_color = CurColor,
next_turn_wl = NextTurnWL, table_module = TableModule,
tables = Tables, tables_wl = TablesWL} = StateData) ->
gas:info(?MODULE,"TRN_PAIRED <~p> Removing table <~p> from the next turn waiting list: ~p.",
[GameId, TableId, NextTurnWL]),
NewNextTurnWL = lists:delete(TableId, NextTurnWL),
if NewNextTurnWL == [] ->
OppColor = opponent(CurColor),
{Die1, Die2} = roll(),
gas:info(?MODULE,"TRN_PAIRED <~p> The next turn waiting list is empty. Rolling dice for color ~p: ~p",
[GameId, OppColor, [Die1, Die2]]),
[send_to_table(TableModule, TablePid, {action, {rolls, OppColor, Die1, Die2}}) ||
#table{pid = TablePid} <- tables_to_list(Tables)],
gas:info(?MODULE,"TRN_PAIRED <~p> New next turn waiting list is ~p",
[GameId, TablesWL]),
{next_state, StateName, StateData#state{next_turn_wl = TablesWL,
cur_color = OppColor}};
true ->
gas:info(?MODULE,"TRN_PAIRED <~p> The next turn waiting list is not empty:~p. Waiting for the rest players.",
[GameId, NewNextTurnWL]),
{next_state, StateName, StateData#state{next_turn_wl = NewNextTurnWL}}
end.
players_init() -> midict:new().
store_player(#player { } , Players ) - > NewPlayers
store_player(#player{id =Id, user_id = UserId} = Player, Players) ->
midict:store(Id, Player, [{user_id, UserId}], Players).
get_players_ids(Players) ->
[P#player.id || P <- players_to_list(Players)].
get_player_by_user_id(UserId, Players) ->
case midict:geti(UserId, user_id, Players) of
[Player] -> {ok, Player};
[] -> error
end.
players_to_list(Players) -> midict:all_values(Players).
get_user_info(PlayerId, Players) ->
#player{user_info = UserInfo} = midict:fetch(PlayerId, Players),
UserInfo.
get_user_id(PlayerId, Players) ->
#player{user_id = UserId} = midict:fetch(PlayerId, Players),
UserId.
del_player(PlayerId , Players ) - > NewPlayers
del_player(PlayerId, Players) ->
midict:erase(PlayerId, Players).
tables_init() -> midict:new().
reg_table(TableId, Pid, MonRef, Tables) ->
reg_table(TableId, Pid, MonRef, _GlobalId = 0, _TableContext = undefined, Tables).
reg_table(TableId, Pid, MonRef, GlobalId, TableContext, Tables) ->
Table = #table{id = TableId, pid = Pid, mon_ref = MonRef, global_id = GlobalId,
state = initializing, context = TableContext},
store_table(Table, Tables).
update_created_table(TableId, Relay, Tables) ->
Table = midict:fetch(TableId, Tables),
NewTable = Table#table{relay = Relay, state = ?TABLE_STATE_READY},
store_table(NewTable, Tables).
store_table(#table{id = TableId, pid = Pid, mon_ref = MonRef, global_id = GlobalId} = Table, Tables) ->
midict:store(TableId, Table, [{pid, Pid}, {global_id, GlobalId}, {mon_ref, MonRef}], Tables).
fetch_table(TableId, Tables) -> midict:fetch(TableId, Tables).
get_table(TableId, Tables) -> midict:find(TableId, Tables).
get_table_pid(TabId, Tables) ->
#table{pid = TabPid} = midict:fetch(TabId, Tables),
TabPid.
get_table_by_mon_ref(MonRef, Tables) ->
case midict:geti(MonRef, mon_ref, Tables) of
[Table] -> Table;
[] -> not_found
end.
tables_to_list(Tables) -> midict:all_values(Tables).
seats_init() -> midict:new().
find_seats_by_player_id(PlayerId, Seats) ->
midict:geti(PlayerId, player_id, Seats).
find_seats_by_table_id(TabId, Seats) ->
midict:geti(TabId, table_id, Seats).
find_disconnected_seats(Seats) ->
midict:geti(false, connected, Seats).
find_free_seats(TableId, Seats) ->
midict:geti(true, {free_at_tab, TableId}, Seats).
find_free_seats(Seats) ->
midict:geti(true, free, Seats).
find_non_free_seats(Seats) ->
midict:geti(false, free, Seats).
find_registered_robot_seats(Seats) ->
[S || S = #seat{registered_by_table = true, is_bot = true} <- find_non_free_seats(Seats)].
fetch_seat(TableId, SeatNum, Seats) -> midict:fetch({TableId, SeatNum}, Seats).
set_seat(TabId , SeatNum , , IsBot , RegByTable , Connected , Free , Seats ) - > NewSeats
IsBot = RegByTable = Connected = undefined | boolean ( )
set_seat(TabId, SeatNum, PlayerId, IsBot, RegByTable, Connected, Free, Seats) ->
Seat = #seat{table = TabId, seat_num = SeatNum, player_id = PlayerId, is_bot = IsBot,
registered_by_table = RegByTable, connected = Connected, free = Free},
store_seat(Seat, Seats).
update_seat_connect_status(TableId, SeatNum, ConnStatus, Seats) ->
Seat = midict:fetch({TableId, SeatNum}, Seats),
NewSeat = Seat#seat{connected = ConnStatus},
store_seat(NewSeat, Seats).
store_seat(#seat{table = TabId, seat_num = SeatNum, player_id = PlayerId,
is_bot = _IsBot, registered_by_table = _RegByTable,
connected = Connected, free = Free} = Seat, Seats) ->
Indices = if Free == true ->
[{table_id, TabId}, {free, true}, {{free_at_tab, TabId}, true}];
true ->
[{table_id, TabId}, {free, false}, {{free_at_tab, TabId}, false},
{player_at_table, {PlayerId, TabId}}, {player_id, PlayerId},
{{connected, TabId}, Connected}, {connected, Connected}]
end,
midict:store({TabId, SeatNum}, Seat, Indices, Seats).
user_id_to_string(UserId) -> binary_to_list(UserId).
shuffle(List) -> deck:to_list(deck:shuffle(deck:from_list(List))).
split_by_num(Num, List) -> split_by_num(Num, List, []).
split_by_num(_, [], Acc) -> lists:reverse(Acc);
split_by_num(Num, List, Acc) ->
{Group, Rest} = lists:split(Num, List),
split_by_num(Num, Rest, [Group | Acc]).
start_timer(Timeout ) - > { TRef , Magic }
start_timer(Timeout) ->
Magic = make_ref(),
TRef = erlang:send_after(Timeout, self(), {timeout, Magic}),
{TRef, Magic}.
spawn_table(TableModule, GameId, TableId, Params) ->
TableModule:start(GameId, TableId, Params).
send_to_table(TableModule, TablePid, Message) ->
TableModule:parent_message(TablePid, Message).
get_param(ParamId, Params) ->
gas:info(?MODULE,"get_param/2 ParamId:~p", [ParamId]),
{_, Value} = lists:keyfind(ParamId, 1, Params),
Value.
get_option(OptionId, Params, DefValue) ->
proplists:get_value(OptionId, Params, DefValue).
create_decl_rec(GameType, CParams, GameId, Users) ->
#game_table{id = GameId,
name = proplists:get_value(table_name, CParams),
,
game_type = GameType,
rounds = proplists:get_value(rounds, CParams),
sets = proplists:get_value(sets, CParams),
owner = proplists:get_value(owner, CParams),
timestamp = now(),
users = Users,
users_options = proplists:get_value(users_options, CParams),
game_mode = proplists:get_value(game_mode, CParams),
game_speed = proplists:get_value(speed, CParams),
friends_only = proplists:get_value(friends_only, CParams),
private = proplists:get_value(private, CParams),
feel_lucky = false,
age_limit = proplists:get_value(age, CParams),
gender_limit = proplists:get_value(gender_limit, CParams),
paid_only = proplists:get_value(paid_only, CParams),
deny_robots = proplists:get_value(deny_robots, CParams),
slang = proplists:get_value(slang, CParams),
deny_observers = proplists:get_value(deny_observers, CParams),
gosterge_finish = proplists:get_value(gosterge_finish, CParams),
double_points = proplists:get_value(double_points, CParams),
game_state = started,
game_process = self(),
game_module = ?MODULE,
pointing_rules = proplists:get_value(pointing_rules, CParams),
pointing_rules_ex = proplists:get_value(pointing_rules, CParams),
robots_replacement_allowed = proplists:get_value(robots_replacement_allowed, CParams)
}.
spawn_bot(GameId , BotModule ) - > UserInfo
spawn_bot(GameId, BotModule) ->
{NPid, UserInfo} = create_robot(BotModule, GameId),
BotModule:join_game(NPid),
UserInfo.
create_robot(BM, GameId) ->
UserInfo = auth_server:robot_credentials(),
{ok, NPid} = BM:start(self(), UserInfo, GameId),
{NPid, UserInfo}.
competition_roll() ->
{Die1, Die2} = roll(),
if Die1 == Die2 -> competition_roll();
true -> {Die1, Die2}
end.
roll() ->
Die1 = crypto:rand_uniform(1, 7),
Die2 = crypto:rand_uniform(1, 7),
{Die1, Die2}.
opponent(?WHITE) -> ?BLACK;
opponent(?BLACK) -> ?WHITE.
ext_to_color(1) -> ?WHITE;
ext_to_color(2) -> ?BLACK. |
9cbf31607f6ff27936c5472dc5ac558f601f3c8ada0c01688f8eac1d0bc7b2f3 | lisp-mirror/clpm | build-release.lisp | Script to build CLPM releases
;;;;
This software is part of CLPM . See README.org for more information . See
;;;; LICENSE for license information.
(in-package #:cl-user)
(load (merge-pathnames "common.lisp" *load-truename*))
(in-package #:clpm-scripts)
(setup-asdf)
(defparameter *option-static*
(adopt:make-option
:static
:help "Build a static executable"
:long "static"
:reduce (constantly t)))
(defparameter *ui*
(adopt:make-interface
:name "scripts/build.lisp"
:summary "Build script for CLPM"
:help "Build script for CLPM"
:usage "[options]"
:contents (list *option-help*
*option-static*)))
(defvar *args*)
(defvar *opts*)
(multiple-value-setq (*args* *opts*) (adopt:parse-options *ui*))
(when (gethash :help *opts*)
(adopt:print-help-and-exit *ui*))
;; TODO: This is a bit hacky, but speeds up the build significantly when
;; starting from scratch (like in CI). The root problem is that
;; asdf-release-ops will occasionally cause the same code to be compiled twice:
;; once in the child process and once in the parent. This is because we use
;; asdf:monolithic-lib-op in the parent. However, moving that op to the child
;; didn't quite work as it would error out due to package variance in
;; dexador...
(asdf:load-system :clpm)
(asdf:load-system :clpm-cli)
(defparameter *op* (if (gethash :static *opts*)
'asdf-release-ops:static-release-archive-op
'asdf-release-ops:dynamic-release-archive-op))
(asdf:operate *op* :clpm)
(format uiop:*stdout*
"A ~:[dynamic~;static~] release has been built at ~A~%"
(gethash :static *opts*)
(asdf:output-file *op* :clpm))
| null | https://raw.githubusercontent.com/lisp-mirror/clpm/ad9a704fcdd0df5ce30ead106706ab6cc5fb3e5b/scripts/build-release.lisp | lisp |
LICENSE for license information.
TODO: This is a bit hacky, but speeds up the build significantly when
starting from scratch (like in CI). The root problem is that
asdf-release-ops will occasionally cause the same code to be compiled twice:
once in the child process and once in the parent. This is because we use
asdf:monolithic-lib-op in the parent. However, moving that op to the child
didn't quite work as it would error out due to package variance in
dexador... | Script to build CLPM releases
This software is part of CLPM . See README.org for more information . See
(in-package #:cl-user)
(load (merge-pathnames "common.lisp" *load-truename*))
(in-package #:clpm-scripts)
(setup-asdf)
(defparameter *option-static*
(adopt:make-option
:static
:help "Build a static executable"
:long "static"
:reduce (constantly t)))
(defparameter *ui*
(adopt:make-interface
:name "scripts/build.lisp"
:summary "Build script for CLPM"
:help "Build script for CLPM"
:usage "[options]"
:contents (list *option-help*
*option-static*)))
(defvar *args*)
(defvar *opts*)
(multiple-value-setq (*args* *opts*) (adopt:parse-options *ui*))
(when (gethash :help *opts*)
(adopt:print-help-and-exit *ui*))
(asdf:load-system :clpm)
(asdf:load-system :clpm-cli)
(defparameter *op* (if (gethash :static *opts*)
'asdf-release-ops:static-release-archive-op
'asdf-release-ops:dynamic-release-archive-op))
(asdf:operate *op* :clpm)
(format uiop:*stdout*
"A ~:[dynamic~;static~] release has been built at ~A~%"
(gethash :static *opts*)
(asdf:output-file *op* :clpm))
|
28e47e94284ff298977e6ffbbe961b56584b4bdeaea5e3226496d3c6b2684767 | takikawa/tr-pfds | implicitqueue-performance-tests.rkt | #lang racket
(require pfds/queue/implicit)
tests run with Racket 5.3.0.11 , in ,
on a Intel i7 - 920 processor machine with 12 GB memory
;;;;; test enqueue
; with bug
cpu time : 22234 real time : 22320 gc time : 11126
; bug fixed (let* moved inside delay)
cpu time : 4703 real time : 4704 gc time : 1442
(time (build-queue 1000000 add1))
| null | https://raw.githubusercontent.com/takikawa/tr-pfds/a08810bdfc760bb9ed68d08ea222a59135d9a203/pfds/tests/implicitqueue-performance-tests.rkt | racket | test enqueue
with bug
bug fixed (let* moved inside delay) | #lang racket
(require pfds/queue/implicit)
tests run with Racket 5.3.0.11 , in ,
on a Intel i7 - 920 processor machine with 12 GB memory
cpu time : 22234 real time : 22320 gc time : 11126
cpu time : 4703 real time : 4704 gc time : 1442
(time (build-queue 1000000 add1))
|
1de35685868d443041b7c09c91a8e8fe6e9b22873355701eb46bf67cc33a0375 | ghc/ghc | Types.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE GADTs #-}
# LANGUAGE StandaloneDeriving #
module GHC.Driver.Errors.Types (
GhcMessage(..)
, GhcMessageOpts(..)
, DriverMessage(..)
, DriverMessageOpts(..)
, DriverMessages, PsMessage(PsHeaderMessage)
, BuildingCabalPackage(..)
, WarningMessages
, ErrorMessages
, WarnMsg
-- * Constructors
, ghcUnknownMessage
-- * Utility functions
, hoistTcRnMessage
, hoistDsMessage
, checkBuildingCabalPackage
) where
import GHC.Prelude
import Data.Bifunctor
import Data.Typeable
import GHC.Driver.Session
import GHC.Types.Error
import GHC.Unit.Module
import GHC.Unit.State
import GHC.Parser.Errors.Types ( PsMessage(PsHeaderMessage) )
import GHC.Tc.Errors.Types ( TcRnMessage )
import GHC.HsToCore.Errors.Types ( DsMessage )
import GHC.Hs.Extension (GhcTc)
import Language.Haskell.Syntax.Decls (RuleDecl)
import GHC.Generics ( Generic )
-- | A collection of warning messages.
/INVARIANT/ : Each ' GhcMessage ' in the collection should have ' SevWarning ' severity .
type WarningMessages = Messages GhcMessage
-- | A collection of error messages.
/INVARIANT/ : Each ' GhcMessage ' in the collection should have ' SevError ' severity .
type ErrorMessages = Messages GhcMessage
-- | A single warning message.
/INVARIANT/ : It must have ' SevWarning ' severity .
type WarnMsg = MsgEnvelope GhcMessage
Note [ GhcMessage ]
~~~~~~~~~~~~~~~~~~~~
We might need to report diagnostics ( error and/or warnings ) to the users . The
' GhcMessage ' type is the root of the diagnostic hierarchy .
It 's useful to have a separate type constructor for the different stages of
the compilation pipeline . This is not just helpful for tools , as it gives a
clear indication on where the error occurred exactly . Furthermore it increases
the modularity amongst the different components of GHC ( i.e. to avoid having
" everything depend on everything else " ) and allows us to write separate
functions that renders the different kind of messages .
~~~~~~~~~~~~~~~~~~~~
We might need to report diagnostics (error and/or warnings) to the users. The
'GhcMessage' type is the root of the diagnostic hierarchy.
It's useful to have a separate type constructor for the different stages of
the compilation pipeline. This is not just helpful for tools, as it gives a
clear indication on where the error occurred exactly. Furthermore it increases
the modularity amongst the different components of GHC (i.e. to avoid having
"everything depend on everything else") and allows us to write separate
functions that renders the different kind of messages.
-}
| The umbrella type that encompasses all the different messages that GHC
-- might output during the different compilation stages. See
Note [ GhcMessage ] .
data GhcMessage where
-- | A message from the parsing phase.
GhcPsMessage :: PsMessage -> GhcMessage
| A message from / renaming phase .
GhcTcRnMessage :: TcRnMessage -> GhcMessage
-- | A message from the desugaring (HsToCore) phase.
GhcDsMessage :: DsMessage -> GhcMessage
-- | A message from the driver.
GhcDriverMessage :: DriverMessage -> GhcMessage
-- | An \"escape\" hatch which can be used when we don't know the source of
-- the message or if the message is not one of the typed ones. The
' Diagnostic ' and ' ' constraints ensure that if we /know/ , at
-- pattern-matching time, the originating type, we can attempt a cast and
access the fully - structured error . This would be the case for a GHC
-- plugin that offers a domain-specific error type but that doesn't want to
-- place the burden on IDEs/application code to \"know\" it. The
' Diagnostic ' constraint ensures that worst case scenario we can still
-- render this into something which can be eventually converted into a
-- 'DecoratedSDoc'.
GhcUnknownMessage :: UnknownDiagnostic -> GhcMessage
deriving Generic
data GhcMessageOpts = GhcMessageOpts { psMessageOpts :: DiagnosticOpts PsMessage
, tcMessageOpts :: DiagnosticOpts TcRnMessage
, dsMessageOpts :: DiagnosticOpts DsMessage
, driverMessageOpts :: DiagnosticOpts DriverMessage
}
| Creates a new ' GhcMessage ' out of any diagnostic . This function is also
-- provided to ease the integration of #18516 by allowing diagnostics to be
wrapped into the general ( but structured ) ' GhcMessage ' type , so that the
-- conversion can happen gradually. This function should not be needed within
GHC , as it would typically be used by plugin or library authors ( see
-- comment for the 'GhcUnknownMessage' type constructor)
ghcUnknownMessage :: (DiagnosticOpts a ~ NoDiagnosticOpts, Diagnostic a, Typeable a) => a -> GhcMessage
ghcUnknownMessage = GhcUnknownMessage . UnknownDiagnostic
| Abstracts away the frequent pattern where we are calling ' ioMsgMaybe ' on
the result of ' IO ( Messages TcRnMessage , a ) ' .
hoistTcRnMessage :: Monad m => m (Messages TcRnMessage, a) -> m (Messages GhcMessage, a)
hoistTcRnMessage = fmap (first (fmap GhcTcRnMessage))
| Abstracts away the frequent pattern where we are calling ' ioMsgMaybe ' on
the result of ' IO ( Messages DsMessage , a ) ' .
hoistDsMessage :: Monad m => m (Messages DsMessage, a) -> m (Messages GhcMessage, a)
hoistDsMessage = fmap (first (fmap GhcDsMessage))
-- | A collection of driver messages
type DriverMessages = Messages DriverMessage
-- | A message from the driver.
data DriverMessage where
| Simply wraps a generic ' Diagnostic ' message
DriverUnknownMessage :: UnknownDiagnostic -> DriverMessage
| A parse error in parsing a file header during dependency
-- analysis
DriverPsHeaderMessage :: !PsMessage -> DriverMessage
| DriverMissingHomeModules is a warning ( controlled with -Wmissing - home - modules ) that
arises when running GHC in --make mode when some modules needed for compilation
are not included on the command line . For example , if A imports B , ` ghc --make
A.hs ` will cause this warning , while ` ghc --make A.hs B.hs ` will not .
Useful for cabal to ensure GHC wo n't pick up modules listed neither in
' exposed - modules ' nor in ' other - modules ' .
Test case : warnings / should_compile / MissingMod
arises when running GHC in --make mode when some modules needed for compilation
are not included on the command line. For example, if A imports B, `ghc --make
A.hs` will cause this warning, while `ghc --make A.hs B.hs` will not.
Useful for cabal to ensure GHC won't pick up modules listed neither in
'exposed-modules' nor in 'other-modules'.
Test case: warnings/should_compile/MissingMod
-}
DriverMissingHomeModules :: UnitId -> [ModuleName] -> !BuildingCabalPackage -> DriverMessage
| DriverUnknown is a warning that arises when a user tries to
reexport a module which is n't part of that unit .
reexport a module which isn't part of that unit.
-}
DriverUnknownReexportedModules :: UnitId -> [ModuleName] -> DriverMessage
{-| DriverUnknownHiddenModules is a warning that arises when a user tries to
hide a module which isn't part of that unit.
-}
DriverUnknownHiddenModules :: UnitId -> [ModuleName] -> DriverMessage
{-| DriverUnusedPackages occurs when when package is requested on command line,
but was never needed during compilation. Activated by -Wunused-packages.
Test cases: warnings/should_compile/UnusedPackages
-}
DriverUnusedPackages :: [(UnitId, PackageName, Version, PackageArg)] -> DriverMessage
{-| DriverUnnecessarySourceImports (controlled with -Wunused-imports) occurs if there
are {-# SOURCE #-} imports which are not necessary. See 'warnUnnecessarySourceImports'
in 'GHC.Driver.Make'.
Test cases: warnings/should_compile/T10637
-}
DriverUnnecessarySourceImports :: !ModuleName -> DriverMessage
{-| DriverDuplicatedModuleDeclaration occurs if a module 'A' is declared in
multiple files.
Test cases: None.
-}
DriverDuplicatedModuleDeclaration :: !Module -> [FilePath] -> DriverMessage
{-| DriverModuleNotFound occurs if a module 'A' can't be found.
Test cases: None.
-}
DriverModuleNotFound :: !ModuleName -> DriverMessage
| DriverFileModuleNameMismatch occurs if a module ' A ' is defined in a file with a different name .
The first field is the name written in the source code ; the second argument is the name extracted
from the filename .
Test cases : module / , /driver / bug1677
The first field is the name written in the source code; the second argument is the name extracted
from the filename.
Test cases: module/mod178, /driver/bug1677
-}
DriverFileModuleNameMismatch :: !ModuleName -> !ModuleName -> DriverMessage
| DriverUnexpectedSignature occurs when GHC encounters a module ' A ' that imports a signature
file which is neither in the ' signatures ' section of a ' .cabal ' file nor in any package in
the home modules .
Example :
-- MyStr.hsig is defined , but not added to ' signatures ' in the ' .cabal ' file .
signature where
data
-- A.hs , which tries to import the signature .
module A where
import Test cases : driver / T12955
file which is neither in the 'signatures' section of a '.cabal' file nor in any package in
the home modules.
Example:
-- MyStr.hsig is defined, but not added to 'signatures' in the '.cabal' file.
signature MyStr where
data Str
-- A.hs, which tries to import the signature.
module A where
import MyStr
Test cases: driver/T12955
-}
DriverUnexpectedSignature :: !ModuleName -> !BuildingCabalPackage -> GenInstantiations UnitId -> DriverMessage
{-| DriverFileNotFound occurs when the input file (e.g. given on the command line) can't be found.
Test cases: None.
-}
DriverFileNotFound :: !FilePath -> DriverMessage
| DriverStaticPointersNotSupported occurs when the ' StaticPointers ' extension is used
in an interactive GHCi context .
Test cases : ghci / scripts / StaticPtr
in an interactive GHCi context.
Test cases: ghci/scripts/StaticPtr
-}
DriverStaticPointersNotSupported :: DriverMessage
{-| DriverBackpackModuleNotFound occurs when Backpack can't find a particular module
during its dependency analysis.
Test cases: -
-}
DriverBackpackModuleNotFound :: !ModuleName -> DriverMessage
| DriverUserDefinedRuleIgnored is a warning that occurs when user - defined rules
are ignored . This typically happens when Safe Haskell .
Test cases :
tests / safeHaskell / safeInfered / UnsafeWarn05
tests / safeHaskell / safeInfered / UnsafeWarn06
tests / safeHaskell / safeInfered / UnsafeWarn07
tests / safeHaskell / safeInfered / UnsafeInfered11
tests / safeHaskell / safeLanguage / SafeLang03
are ignored. This typically happens when Safe Haskell.
Test cases:
tests/safeHaskell/safeInfered/UnsafeWarn05
tests/safeHaskell/safeInfered/UnsafeWarn06
tests/safeHaskell/safeInfered/UnsafeWarn07
tests/safeHaskell/safeInfered/UnsafeInfered11
tests/safeHaskell/safeLanguage/SafeLang03
-}
DriverUserDefinedRuleIgnored :: !(RuleDecl GhcTc) -> DriverMessage
| DriverMixedSafetyImport is an error that occurs when a module is imported
both as safe and unsafe .
Test cases :
tests / safeHaskell / safeInfered / Mixed03
tests / safeHaskell / safeInfered / Mixed02
both as safe and unsafe.
Test cases:
tests/safeHaskell/safeInfered/Mixed03
tests/safeHaskell/safeInfered/Mixed02
-}
DriverMixedSafetyImport :: !ModuleName -> DriverMessage
{-| DriverCannotLoadInterfaceFile is an error that occurs when we cannot load the interface
file for a particular module. This can happen for example in the context of Safe Haskell,
when we have to load a module to check if it can be safely imported.
Test cases: None.
-}
DriverCannotLoadInterfaceFile :: !Module -> DriverMessage
{-| DriverInferredSafeImport is a warning (controlled by the Opt_WarnSafe flag)
that occurs when a module is inferred safe.
Test cases: None.
-}
DriverInferredSafeModule :: !Module -> DriverMessage
| DriverMarkedTrustworthyButInferredSafe is a warning ( controlled by the Opt_WarnTrustworthySafe flag )
that occurs when a module is marked trustworthy in SafeHaskell but it has been inferred safe .
Test cases :
tests / safeHaskell / safeInfered / TrustworthySafe02
tests / safeHaskell / safeInfered / TrustworthySafe03
that occurs when a module is marked trustworthy in SafeHaskell but it has been inferred safe.
Test cases:
tests/safeHaskell/safeInfered/TrustworthySafe02
tests/safeHaskell/safeInfered/TrustworthySafe03
-}
DriverMarkedTrustworthyButInferredSafe :: !Module -> DriverMessage
{-| DriverInferredSafeImport is a warning (controlled by the Opt_WarnInferredSafeImports flag)
that occurs when a safe-inferred module is imported from a safe module.
Test cases: None.
-}
DriverInferredSafeImport :: !Module -> DriverMessage
{-| DriverCannotImportUnsafeModule is an error that occurs when an usafe module
is being imported from a safe one.
Test cases: None.
-}
DriverCannotImportUnsafeModule :: !Module -> DriverMessage
| DriverMissingSafeHaskellMode is a warning ( controlled by the Opt_WarnMissingSafeHaskellMode flag )
that occurs when a module is using SafeHaskell features but SafeHaskell mode is not enabled .
Test cases : None .
that occurs when a module is using SafeHaskell features but SafeHaskell mode is not enabled.
Test cases: None.
-}
DriverMissingSafeHaskellMode :: !Module -> DriverMessage
| DriverPackageNotTrusted is an error that occurs when a package is required to be trusted
but it is n't .
Test cases :
tests / safeHaskell / check / Check01
tests / safeHaskell / check / Check08
tests / safeHaskell / check / Check06
tests / safeHaskell / check / pkg01 / ImpSafeOnly09
tests / safeHaskell / check / pkg01 / ImpSafe03
tests / safeHaskell / check / pkg01 / ImpSafeOnly07
tests / safeHaskell / check / pkg01 / ImpSafeOnly08
but it isn't.
Test cases:
tests/safeHaskell/check/Check01
tests/safeHaskell/check/Check08
tests/safeHaskell/check/Check06
tests/safeHaskell/check/pkg01/ImpSafeOnly09
tests/safeHaskell/check/pkg01/ImpSafe03
tests/safeHaskell/check/pkg01/ImpSafeOnly07
tests/safeHaskell/check/pkg01/ImpSafeOnly08
-}
DriverPackageNotTrusted :: !UnitState -> !UnitId -> DriverMessage
| DriverCannotImportFromUntrustedPackage is an error that occurs in the context of
Safe Haskell when trying to import a module coming from an untrusted package .
Test cases :
tests / safeHaskell / check / Check09
tests / safeHaskell / check / pkg01 / ImpSafe01
tests / safeHaskell / check / pkg01 / ImpSafe04
tests / safeHaskell / check / pkg01 / ImpSafeOnly03
tests / safeHaskell / check / pkg01 / ImpSafeOnly05
tests / safeHaskell / flags / SafeFlags17
tests / safeHaskell / flags / SafeFlags22
tests / safeHaskell / flags / SafeFlags23
tests / safeHaskell / ghci / p11
tests / safeHaskell / ghci / p12
tests / safeHaskell / ghci / p17
tests / safeHaskell / ghci / p3
tests / safeHaskell / safeInfered / UnsafeInfered01
tests / safeHaskell / safeInfered / UnsafeInfered02
tests / safeHaskell / safeInfered / UnsafeInfered02
tests / safeHaskell / safeInfered / UnsafeInfered03
tests / safeHaskell / safeInfered / UnsafeInfered05
tests / safeHaskell / safeInfered / UnsafeInfered06
tests / safeHaskell / safeInfered / UnsafeInfered09
tests / safeHaskell / safeInfered / UnsafeInfered10
tests / safeHaskell / safeInfered / UnsafeInfered11
tests / safeHaskell / safeInfered / UnsafeWarn01
tests / safeHaskell / safeInfered / UnsafeWarn03
tests / safeHaskell / safeInfered / UnsafeWarn04
tests / safeHaskell / safeInfered / UnsafeWarn05
tests / safeHaskell / unsafeLibs / BadImport01
tests / safeHaskell / unsafeLibs / BadImport06
tests / safeHaskell / unsafeLibs / BadImport07
tests / safeHaskell / unsafeLibs / BadImport08
tests / safeHaskell / unsafeLibs / BadImport09
tests / safeHaskell / unsafeLibs / Dep05
tests / safeHaskell / unsafeLibs / Dep06
tests / safeHaskell / unsafeLibs / Dep07
tests / safeHaskell / unsafeLibs / Dep08
tests / safeHaskell / unsafeLibs / Dep09
tests / safeHaskell / unsafeLibs / Dep10
Safe Haskell when trying to import a module coming from an untrusted package.
Test cases:
tests/safeHaskell/check/Check09
tests/safeHaskell/check/pkg01/ImpSafe01
tests/safeHaskell/check/pkg01/ImpSafe04
tests/safeHaskell/check/pkg01/ImpSafeOnly03
tests/safeHaskell/check/pkg01/ImpSafeOnly05
tests/safeHaskell/flags/SafeFlags17
tests/safeHaskell/flags/SafeFlags22
tests/safeHaskell/flags/SafeFlags23
tests/safeHaskell/ghci/p11
tests/safeHaskell/ghci/p12
tests/safeHaskell/ghci/p17
tests/safeHaskell/ghci/p3
tests/safeHaskell/safeInfered/UnsafeInfered01
tests/safeHaskell/safeInfered/UnsafeInfered02
tests/safeHaskell/safeInfered/UnsafeInfered02
tests/safeHaskell/safeInfered/UnsafeInfered03
tests/safeHaskell/safeInfered/UnsafeInfered05
tests/safeHaskell/safeInfered/UnsafeInfered06
tests/safeHaskell/safeInfered/UnsafeInfered09
tests/safeHaskell/safeInfered/UnsafeInfered10
tests/safeHaskell/safeInfered/UnsafeInfered11
tests/safeHaskell/safeInfered/UnsafeWarn01
tests/safeHaskell/safeInfered/UnsafeWarn03
tests/safeHaskell/safeInfered/UnsafeWarn04
tests/safeHaskell/safeInfered/UnsafeWarn05
tests/safeHaskell/unsafeLibs/BadImport01
tests/safeHaskell/unsafeLibs/BadImport06
tests/safeHaskell/unsafeLibs/BadImport07
tests/safeHaskell/unsafeLibs/BadImport08
tests/safeHaskell/unsafeLibs/BadImport09
tests/safeHaskell/unsafeLibs/Dep05
tests/safeHaskell/unsafeLibs/Dep06
tests/safeHaskell/unsafeLibs/Dep07
tests/safeHaskell/unsafeLibs/Dep08
tests/safeHaskell/unsafeLibs/Dep09
tests/safeHaskell/unsafeLibs/Dep10
-}
DriverCannotImportFromUntrustedPackage :: !UnitState -> !Module -> DriverMessage
DriverRedirectedNoMain :: !ModuleName -> DriverMessage
DriverHomePackagesNotClosed :: ![UnitId] -> DriverMessage
deriving instance Generic DriverMessage
data DriverMessageOpts =
DriverMessageOpts { psDiagnosticOpts :: DiagnosticOpts PsMessage }
| Pass to a ' DriverMessage ' the information whether or not the
-- '-fbuilding-cabal-package' flag is set.
data BuildingCabalPackage
= YesBuildingCabalPackage
| NoBuildingCabalPackage
deriving Eq
| Checks if we are building a cabal package by consulting the ' DynFlags ' .
checkBuildingCabalPackage :: DynFlags -> BuildingCabalPackage
checkBuildingCabalPackage dflags =
if gopt Opt_BuildingCabalPackage dflags
then YesBuildingCabalPackage
else NoBuildingCabalPackage
| null | https://raw.githubusercontent.com/ghc/ghc/1c050ed26f50f3a8788e650f23d6ff55badc1072/compiler/GHC/Driver/Errors/Types.hs | haskell | # LANGUAGE GADTs #
* Constructors
* Utility functions
| A collection of warning messages.
| A collection of error messages.
| A single warning message.
might output during the different compilation stages. See
| A message from the parsing phase.
| A message from the desugaring (HsToCore) phase.
| A message from the driver.
| An \"escape\" hatch which can be used when we don't know the source of
the message or if the message is not one of the typed ones. The
pattern-matching time, the originating type, we can attempt a cast and
plugin that offers a domain-specific error type but that doesn't want to
place the burden on IDEs/application code to \"know\" it. The
render this into something which can be eventually converted into a
'DecoratedSDoc'.
provided to ease the integration of #18516 by allowing diagnostics to be
conversion can happen gradually. This function should not be needed within
comment for the 'GhcUnknownMessage' type constructor)
| A collection of driver messages
| A message from the driver.
analysis
make mode when some modules needed for compilation
make
make A.hs B.hs ` will not .
make mode when some modules needed for compilation
make
make A.hs B.hs` will not.
| DriverUnknownHiddenModules is a warning that arises when a user tries to
hide a module which isn't part of that unit.
| DriverUnusedPackages occurs when when package is requested on command line,
but was never needed during compilation. Activated by -Wunused-packages.
Test cases: warnings/should_compile/UnusedPackages
| DriverUnnecessarySourceImports (controlled with -Wunused-imports) occurs if there
are {-# SOURCE #
| DriverDuplicatedModuleDeclaration occurs if a module 'A' is declared in
multiple files.
Test cases: None.
| DriverModuleNotFound occurs if a module 'A' can't be found.
Test cases: None.
MyStr.hsig is defined , but not added to ' signatures ' in the ' .cabal ' file .
A.hs , which tries to import the signature .
MyStr.hsig is defined, but not added to 'signatures' in the '.cabal' file.
A.hs, which tries to import the signature.
| DriverFileNotFound occurs when the input file (e.g. given on the command line) can't be found.
Test cases: None.
| DriverBackpackModuleNotFound occurs when Backpack can't find a particular module
during its dependency analysis.
Test cases: -
| DriverCannotLoadInterfaceFile is an error that occurs when we cannot load the interface
file for a particular module. This can happen for example in the context of Safe Haskell,
when we have to load a module to check if it can be safely imported.
Test cases: None.
| DriverInferredSafeImport is a warning (controlled by the Opt_WarnSafe flag)
that occurs when a module is inferred safe.
Test cases: None.
| DriverInferredSafeImport is a warning (controlled by the Opt_WarnInferredSafeImports flag)
that occurs when a safe-inferred module is imported from a safe module.
Test cases: None.
| DriverCannotImportUnsafeModule is an error that occurs when an usafe module
is being imported from a safe one.
Test cases: None.
'-fbuilding-cabal-package' flag is set. | # LANGUAGE DeriveGeneric #
# LANGUAGE StandaloneDeriving #
module GHC.Driver.Errors.Types (
GhcMessage(..)
, GhcMessageOpts(..)
, DriverMessage(..)
, DriverMessageOpts(..)
, DriverMessages, PsMessage(PsHeaderMessage)
, BuildingCabalPackage(..)
, WarningMessages
, ErrorMessages
, WarnMsg
, ghcUnknownMessage
, hoistTcRnMessage
, hoistDsMessage
, checkBuildingCabalPackage
) where
import GHC.Prelude
import Data.Bifunctor
import Data.Typeable
import GHC.Driver.Session
import GHC.Types.Error
import GHC.Unit.Module
import GHC.Unit.State
import GHC.Parser.Errors.Types ( PsMessage(PsHeaderMessage) )
import GHC.Tc.Errors.Types ( TcRnMessage )
import GHC.HsToCore.Errors.Types ( DsMessage )
import GHC.Hs.Extension (GhcTc)
import Language.Haskell.Syntax.Decls (RuleDecl)
import GHC.Generics ( Generic )
/INVARIANT/ : Each ' GhcMessage ' in the collection should have ' SevWarning ' severity .
type WarningMessages = Messages GhcMessage
/INVARIANT/ : Each ' GhcMessage ' in the collection should have ' SevError ' severity .
type ErrorMessages = Messages GhcMessage
/INVARIANT/ : It must have ' SevWarning ' severity .
type WarnMsg = MsgEnvelope GhcMessage
Note [ GhcMessage ]
~~~~~~~~~~~~~~~~~~~~
We might need to report diagnostics ( error and/or warnings ) to the users . The
' GhcMessage ' type is the root of the diagnostic hierarchy .
It 's useful to have a separate type constructor for the different stages of
the compilation pipeline . This is not just helpful for tools , as it gives a
clear indication on where the error occurred exactly . Furthermore it increases
the modularity amongst the different components of GHC ( i.e. to avoid having
" everything depend on everything else " ) and allows us to write separate
functions that renders the different kind of messages .
~~~~~~~~~~~~~~~~~~~~
We might need to report diagnostics (error and/or warnings) to the users. The
'GhcMessage' type is the root of the diagnostic hierarchy.
It's useful to have a separate type constructor for the different stages of
the compilation pipeline. This is not just helpful for tools, as it gives a
clear indication on where the error occurred exactly. Furthermore it increases
the modularity amongst the different components of GHC (i.e. to avoid having
"everything depend on everything else") and allows us to write separate
functions that renders the different kind of messages.
-}
| The umbrella type that encompasses all the different messages that GHC
Note [ GhcMessage ] .
data GhcMessage where
GhcPsMessage :: PsMessage -> GhcMessage
| A message from / renaming phase .
GhcTcRnMessage :: TcRnMessage -> GhcMessage
GhcDsMessage :: DsMessage -> GhcMessage
GhcDriverMessage :: DriverMessage -> GhcMessage
' Diagnostic ' and ' ' constraints ensure that if we /know/ , at
access the fully - structured error . This would be the case for a GHC
' Diagnostic ' constraint ensures that worst case scenario we can still
GhcUnknownMessage :: UnknownDiagnostic -> GhcMessage
deriving Generic
data GhcMessageOpts = GhcMessageOpts { psMessageOpts :: DiagnosticOpts PsMessage
, tcMessageOpts :: DiagnosticOpts TcRnMessage
, dsMessageOpts :: DiagnosticOpts DsMessage
, driverMessageOpts :: DiagnosticOpts DriverMessage
}
| Creates a new ' GhcMessage ' out of any diagnostic . This function is also
wrapped into the general ( but structured ) ' GhcMessage ' type , so that the
GHC , as it would typically be used by plugin or library authors ( see
ghcUnknownMessage :: (DiagnosticOpts a ~ NoDiagnosticOpts, Diagnostic a, Typeable a) => a -> GhcMessage
ghcUnknownMessage = GhcUnknownMessage . UnknownDiagnostic
| Abstracts away the frequent pattern where we are calling ' ioMsgMaybe ' on
the result of ' IO ( Messages TcRnMessage , a ) ' .
hoistTcRnMessage :: Monad m => m (Messages TcRnMessage, a) -> m (Messages GhcMessage, a)
hoistTcRnMessage = fmap (first (fmap GhcTcRnMessage))
| Abstracts away the frequent pattern where we are calling ' ioMsgMaybe ' on
the result of ' IO ( Messages DsMessage , a ) ' .
hoistDsMessage :: Monad m => m (Messages DsMessage, a) -> m (Messages GhcMessage, a)
hoistDsMessage = fmap (first (fmap GhcDsMessage))
type DriverMessages = Messages DriverMessage
data DriverMessage where
| Simply wraps a generic ' Diagnostic ' message
DriverUnknownMessage :: UnknownDiagnostic -> DriverMessage
| A parse error in parsing a file header during dependency
DriverPsHeaderMessage :: !PsMessage -> DriverMessage
| DriverMissingHomeModules is a warning ( controlled with -Wmissing - home - modules ) that
Useful for cabal to ensure GHC wo n't pick up modules listed neither in
' exposed - modules ' nor in ' other - modules ' .
Test case : warnings / should_compile / MissingMod
Useful for cabal to ensure GHC won't pick up modules listed neither in
'exposed-modules' nor in 'other-modules'.
Test case: warnings/should_compile/MissingMod
-}
DriverMissingHomeModules :: UnitId -> [ModuleName] -> !BuildingCabalPackage -> DriverMessage
| DriverUnknown is a warning that arises when a user tries to
reexport a module which is n't part of that unit .
reexport a module which isn't part of that unit.
-}
DriverUnknownReexportedModules :: UnitId -> [ModuleName] -> DriverMessage
DriverUnknownHiddenModules :: UnitId -> [ModuleName] -> DriverMessage
DriverUnusedPackages :: [(UnitId, PackageName, Version, PackageArg)] -> DriverMessage
in 'GHC.Driver.Make'.
Test cases: warnings/should_compile/T10637
-}
DriverUnnecessarySourceImports :: !ModuleName -> DriverMessage
DriverDuplicatedModuleDeclaration :: !Module -> [FilePath] -> DriverMessage
DriverModuleNotFound :: !ModuleName -> DriverMessage
| DriverFileModuleNameMismatch occurs if a module ' A ' is defined in a file with a different name .
The first field is the name written in the source code ; the second argument is the name extracted
from the filename .
Test cases : module / , /driver / bug1677
The first field is the name written in the source code; the second argument is the name extracted
from the filename.
Test cases: module/mod178, /driver/bug1677
-}
DriverFileModuleNameMismatch :: !ModuleName -> !ModuleName -> DriverMessage
| DriverUnexpectedSignature occurs when GHC encounters a module ' A ' that imports a signature
file which is neither in the ' signatures ' section of a ' .cabal ' file nor in any package in
the home modules .
Example :
signature where
data
module A where
import Test cases : driver / T12955
file which is neither in the 'signatures' section of a '.cabal' file nor in any package in
the home modules.
Example:
signature MyStr where
data Str
module A where
import MyStr
Test cases: driver/T12955
-}
DriverUnexpectedSignature :: !ModuleName -> !BuildingCabalPackage -> GenInstantiations UnitId -> DriverMessage
DriverFileNotFound :: !FilePath -> DriverMessage
| DriverStaticPointersNotSupported occurs when the ' StaticPointers ' extension is used
in an interactive GHCi context .
Test cases : ghci / scripts / StaticPtr
in an interactive GHCi context.
Test cases: ghci/scripts/StaticPtr
-}
DriverStaticPointersNotSupported :: DriverMessage
DriverBackpackModuleNotFound :: !ModuleName -> DriverMessage
| DriverUserDefinedRuleIgnored is a warning that occurs when user - defined rules
are ignored . This typically happens when Safe Haskell .
Test cases :
tests / safeHaskell / safeInfered / UnsafeWarn05
tests / safeHaskell / safeInfered / UnsafeWarn06
tests / safeHaskell / safeInfered / UnsafeWarn07
tests / safeHaskell / safeInfered / UnsafeInfered11
tests / safeHaskell / safeLanguage / SafeLang03
are ignored. This typically happens when Safe Haskell.
Test cases:
tests/safeHaskell/safeInfered/UnsafeWarn05
tests/safeHaskell/safeInfered/UnsafeWarn06
tests/safeHaskell/safeInfered/UnsafeWarn07
tests/safeHaskell/safeInfered/UnsafeInfered11
tests/safeHaskell/safeLanguage/SafeLang03
-}
DriverUserDefinedRuleIgnored :: !(RuleDecl GhcTc) -> DriverMessage
| DriverMixedSafetyImport is an error that occurs when a module is imported
both as safe and unsafe .
Test cases :
tests / safeHaskell / safeInfered / Mixed03
tests / safeHaskell / safeInfered / Mixed02
both as safe and unsafe.
Test cases:
tests/safeHaskell/safeInfered/Mixed03
tests/safeHaskell/safeInfered/Mixed02
-}
DriverMixedSafetyImport :: !ModuleName -> DriverMessage
DriverCannotLoadInterfaceFile :: !Module -> DriverMessage
DriverInferredSafeModule :: !Module -> DriverMessage
| DriverMarkedTrustworthyButInferredSafe is a warning ( controlled by the Opt_WarnTrustworthySafe flag )
that occurs when a module is marked trustworthy in SafeHaskell but it has been inferred safe .
Test cases :
tests / safeHaskell / safeInfered / TrustworthySafe02
tests / safeHaskell / safeInfered / TrustworthySafe03
that occurs when a module is marked trustworthy in SafeHaskell but it has been inferred safe.
Test cases:
tests/safeHaskell/safeInfered/TrustworthySafe02
tests/safeHaskell/safeInfered/TrustworthySafe03
-}
DriverMarkedTrustworthyButInferredSafe :: !Module -> DriverMessage
DriverInferredSafeImport :: !Module -> DriverMessage
DriverCannotImportUnsafeModule :: !Module -> DriverMessage
| DriverMissingSafeHaskellMode is a warning ( controlled by the Opt_WarnMissingSafeHaskellMode flag )
that occurs when a module is using SafeHaskell features but SafeHaskell mode is not enabled .
Test cases : None .
that occurs when a module is using SafeHaskell features but SafeHaskell mode is not enabled.
Test cases: None.
-}
DriverMissingSafeHaskellMode :: !Module -> DriverMessage
| DriverPackageNotTrusted is an error that occurs when a package is required to be trusted
but it is n't .
Test cases :
tests / safeHaskell / check / Check01
tests / safeHaskell / check / Check08
tests / safeHaskell / check / Check06
tests / safeHaskell / check / pkg01 / ImpSafeOnly09
tests / safeHaskell / check / pkg01 / ImpSafe03
tests / safeHaskell / check / pkg01 / ImpSafeOnly07
tests / safeHaskell / check / pkg01 / ImpSafeOnly08
but it isn't.
Test cases:
tests/safeHaskell/check/Check01
tests/safeHaskell/check/Check08
tests/safeHaskell/check/Check06
tests/safeHaskell/check/pkg01/ImpSafeOnly09
tests/safeHaskell/check/pkg01/ImpSafe03
tests/safeHaskell/check/pkg01/ImpSafeOnly07
tests/safeHaskell/check/pkg01/ImpSafeOnly08
-}
DriverPackageNotTrusted :: !UnitState -> !UnitId -> DriverMessage
| DriverCannotImportFromUntrustedPackage is an error that occurs in the context of
Safe Haskell when trying to import a module coming from an untrusted package .
Test cases :
tests / safeHaskell / check / Check09
tests / safeHaskell / check / pkg01 / ImpSafe01
tests / safeHaskell / check / pkg01 / ImpSafe04
tests / safeHaskell / check / pkg01 / ImpSafeOnly03
tests / safeHaskell / check / pkg01 / ImpSafeOnly05
tests / safeHaskell / flags / SafeFlags17
tests / safeHaskell / flags / SafeFlags22
tests / safeHaskell / flags / SafeFlags23
tests / safeHaskell / ghci / p11
tests / safeHaskell / ghci / p12
tests / safeHaskell / ghci / p17
tests / safeHaskell / ghci / p3
tests / safeHaskell / safeInfered / UnsafeInfered01
tests / safeHaskell / safeInfered / UnsafeInfered02
tests / safeHaskell / safeInfered / UnsafeInfered02
tests / safeHaskell / safeInfered / UnsafeInfered03
tests / safeHaskell / safeInfered / UnsafeInfered05
tests / safeHaskell / safeInfered / UnsafeInfered06
tests / safeHaskell / safeInfered / UnsafeInfered09
tests / safeHaskell / safeInfered / UnsafeInfered10
tests / safeHaskell / safeInfered / UnsafeInfered11
tests / safeHaskell / safeInfered / UnsafeWarn01
tests / safeHaskell / safeInfered / UnsafeWarn03
tests / safeHaskell / safeInfered / UnsafeWarn04
tests / safeHaskell / safeInfered / UnsafeWarn05
tests / safeHaskell / unsafeLibs / BadImport01
tests / safeHaskell / unsafeLibs / BadImport06
tests / safeHaskell / unsafeLibs / BadImport07
tests / safeHaskell / unsafeLibs / BadImport08
tests / safeHaskell / unsafeLibs / BadImport09
tests / safeHaskell / unsafeLibs / Dep05
tests / safeHaskell / unsafeLibs / Dep06
tests / safeHaskell / unsafeLibs / Dep07
tests / safeHaskell / unsafeLibs / Dep08
tests / safeHaskell / unsafeLibs / Dep09
tests / safeHaskell / unsafeLibs / Dep10
Safe Haskell when trying to import a module coming from an untrusted package.
Test cases:
tests/safeHaskell/check/Check09
tests/safeHaskell/check/pkg01/ImpSafe01
tests/safeHaskell/check/pkg01/ImpSafe04
tests/safeHaskell/check/pkg01/ImpSafeOnly03
tests/safeHaskell/check/pkg01/ImpSafeOnly05
tests/safeHaskell/flags/SafeFlags17
tests/safeHaskell/flags/SafeFlags22
tests/safeHaskell/flags/SafeFlags23
tests/safeHaskell/ghci/p11
tests/safeHaskell/ghci/p12
tests/safeHaskell/ghci/p17
tests/safeHaskell/ghci/p3
tests/safeHaskell/safeInfered/UnsafeInfered01
tests/safeHaskell/safeInfered/UnsafeInfered02
tests/safeHaskell/safeInfered/UnsafeInfered02
tests/safeHaskell/safeInfered/UnsafeInfered03
tests/safeHaskell/safeInfered/UnsafeInfered05
tests/safeHaskell/safeInfered/UnsafeInfered06
tests/safeHaskell/safeInfered/UnsafeInfered09
tests/safeHaskell/safeInfered/UnsafeInfered10
tests/safeHaskell/safeInfered/UnsafeInfered11
tests/safeHaskell/safeInfered/UnsafeWarn01
tests/safeHaskell/safeInfered/UnsafeWarn03
tests/safeHaskell/safeInfered/UnsafeWarn04
tests/safeHaskell/safeInfered/UnsafeWarn05
tests/safeHaskell/unsafeLibs/BadImport01
tests/safeHaskell/unsafeLibs/BadImport06
tests/safeHaskell/unsafeLibs/BadImport07
tests/safeHaskell/unsafeLibs/BadImport08
tests/safeHaskell/unsafeLibs/BadImport09
tests/safeHaskell/unsafeLibs/Dep05
tests/safeHaskell/unsafeLibs/Dep06
tests/safeHaskell/unsafeLibs/Dep07
tests/safeHaskell/unsafeLibs/Dep08
tests/safeHaskell/unsafeLibs/Dep09
tests/safeHaskell/unsafeLibs/Dep10
-}
DriverCannotImportFromUntrustedPackage :: !UnitState -> !Module -> DriverMessage
DriverRedirectedNoMain :: !ModuleName -> DriverMessage
DriverHomePackagesNotClosed :: ![UnitId] -> DriverMessage
deriving instance Generic DriverMessage
data DriverMessageOpts =
DriverMessageOpts { psDiagnosticOpts :: DiagnosticOpts PsMessage }
| Pass to a ' DriverMessage ' the information whether or not the
data BuildingCabalPackage
= YesBuildingCabalPackage
| NoBuildingCabalPackage
deriving Eq
| Checks if we are building a cabal package by consulting the ' DynFlags ' .
checkBuildingCabalPackage :: DynFlags -> BuildingCabalPackage
checkBuildingCabalPackage dflags =
if gopt Opt_BuildingCabalPackage dflags
then YesBuildingCabalPackage
else NoBuildingCabalPackage
|
f453b8271deed54410e7d606ab966893adf171c5aac706affa8e3c843c73f7db | Helium4Haskell/helium | ExprDoPat1.hs | module ExprDoPat1 where
main :: Int
main = unsafePerformIO (
do
(x:_) <- return [1, 2, 3]
return x
) | null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/correct/ExprDoPat1.hs | haskell | module ExprDoPat1 where
main :: Int
main = unsafePerformIO (
do
(x:_) <- return [1, 2, 3]
return x
) | |
2a71584e434ed076c27c05d8a672407cc11146825e781416d5dc178d22703e43 | logseq/logseq | core.cljs | (ns frontend.modules.file.core
(:require [clojure.string :as string]
[frontend.config :as config]
[frontend.date :as date]
[frontend.db :as db]
[frontend.db.utils :as db-utils]
[frontend.modules.file.uprint :as up]
[frontend.state :as state]
[frontend.util.property :as property]
[frontend.util.fs :as fs-util]
[frontend.handler.file :as file-handler]
[frontend.db.model :as model]))
(defn- indented-block-content
[content spaces-tabs]
(let [lines (string/split-lines content)]
(string/join (str "\n" spaces-tabs) lines)))
(defn- content-with-collapsed-state
"Only accept nake content (without any indentation)"
[format content collapsed?]
(cond
collapsed?
(property/insert-property format content :collapsed true)
;; Don't check properties. Collapsed is an internal state log as property in file, but not counted into properties
(false? collapsed?)
(property/remove-property format :collapsed content)
:else
content))
(defn transform-content
[{:block/keys [collapsed? format pre-block? unordered content left page parent properties]} level {:keys [heading-to-list?]}]
(let [heading (:heading properties)
markdown? (= :markdown format)
content (or content "")
pre-block? (or pre-block?
first block
markdown?
(string/includes? (first (string/split-lines content)) ":: ")))
content (cond
pre-block?
(let [content (string/trim content)]
(str content "\n"))
:else
(let [markdown-top-heading? (and markdown?
(= parent page)
(not unordered)
heading)
[prefix spaces-tabs]
(cond
(= format :org)
[(->>
(repeat level "*")
(apply str)) ""]
markdown-top-heading?
["" ""]
:else
(let [level (if (and heading-to-list? heading)
(if (> heading 1)
(dec heading)
heading)
level)
spaces-tabs (->>
(repeat (dec level) (state/get-export-bullet-indentation))
(apply str))]
[(str spaces-tabs "-") (str spaces-tabs " ")]))
content (if heading-to-list?
(-> (string/replace content #"^\s?#+\s+" "")
(string/replace #"^\s?#+\s?$" ""))
content)
content (content-with-collapsed-state format content collapsed?)
new-content (indented-block-content (string/trim content) spaces-tabs)
sep (if (or markdown-top-heading?
(string/blank? new-content))
""
" ")]
(str prefix sep new-content)))]
content))
(defn- tree->file-content-aux
[tree {:keys [init-level] :as opts}]
(let [block-contents (transient [])]
(loop [[f & r] tree level init-level]
(if (nil? f)
(->> block-contents persistent! flatten (remove nil?))
(let [page? (nil? (:block/page f))
content (if page? nil (transform-content f level opts))
new-content
(if-let [children (seq (:block/children f))]
(cons content (tree->file-content-aux children {:init-level (inc level)}))
[content])]
(conj! block-contents new-content)
(recur r level))))))
(defn tree->file-content
[tree opts]
(->> (tree->file-content-aux tree opts) (string/join "\n")))
(def init-level 1)
(defn- transact-file-tx-if-not-exists!
[page ok-handler]
(when-let [repo (state/get-current-repo)]
(when (:block/name page)
(let [format (name (get page :block/format
(state/get-preferred-format)))
title (string/capitalize (:block/name page))
whiteboard-page? (model/whiteboard-page? page)
format (if whiteboard-page? "edn" format)
journal-page? (date/valid-journal-title? title)
journal-title (date/normalize-journal-title title)
filename (if (and journal-page? (not (string/blank? journal-title)))
(date/date->file-name journal-title)
(-> (or (:block/original-name page) (:block/name page))
(fs-util/file-name-sanity)))
sub-dir (cond
journal-page? (config/get-journals-directory)
whiteboard-page? (config/get-whiteboards-directory)
:else (config/get-pages-directory))
ext (if (= format "markdown") "md" format)
file-path (config/get-page-file-path repo sub-dir filename ext)
file {:file/path file-path}
tx [{:file/path file-path}
{:block/name (:block/name page)
:block/file file}]]
(db/transact! tx)
(when ok-handler (ok-handler))))))
(defn- remove-transit-ids [block] (dissoc block :db/id :block/file))
(defn save-tree-aux!
[page-block tree blocks-just-deleted?]
(let [page-block (db/pull (:db/id page-block))
file-db-id (-> page-block :block/file :db/id)
file-path (-> (db-utils/entity file-db-id) :file/path)]
(if (and (string? file-path) (not-empty file-path))
(let [new-content (if (= "whiteboard" (:block/type page-block))
(->
(up/ugly-pr-str {:blocks tree
:pages (list (remove-transit-ids page-block))})
(string/triml))
(tree->file-content tree {:init-level init-level}))]
(if (and (string/blank? new-content)
(not blocks-just-deleted?))
(state/pub-event! [:capture-error {:error (js/Error. "Empty content")
:payload {:file-path file-path}}])
(let [files [[file-path new-content]]
repo (state/get-current-repo)]
(file-handler/alter-files-handler! repo files {} {}))))
;; In e2e tests, "card" page in db has no :file/path
(js/console.error "File path from page-block is not valid" page-block tree))))
(defn save-tree!
[page-block tree blocks-just-deleted?]
{:pre [(map? page-block)]}
(let [ok-handler #(save-tree-aux! page-block tree blocks-just-deleted?)
file (or (:block/file page-block)
(when-let [page (:db/id (:block/page page-block))]
(:block/file (db-utils/entity page))))]
(if file
(ok-handler)
(transact-file-tx-if-not-exists! page-block ok-handler))))
| null | https://raw.githubusercontent.com/logseq/logseq/77e63f6461fde17dfb0a6b68b9cbe9242cad10e3/src/main/frontend/modules/file/core.cljs | clojure | Don't check properties. Collapsed is an internal state log as property in file, but not counted into properties
In e2e tests, "card" page in db has no :file/path | (ns frontend.modules.file.core
(:require [clojure.string :as string]
[frontend.config :as config]
[frontend.date :as date]
[frontend.db :as db]
[frontend.db.utils :as db-utils]
[frontend.modules.file.uprint :as up]
[frontend.state :as state]
[frontend.util.property :as property]
[frontend.util.fs :as fs-util]
[frontend.handler.file :as file-handler]
[frontend.db.model :as model]))
(defn- indented-block-content
[content spaces-tabs]
(let [lines (string/split-lines content)]
(string/join (str "\n" spaces-tabs) lines)))
(defn- content-with-collapsed-state
"Only accept nake content (without any indentation)"
[format content collapsed?]
(cond
collapsed?
(property/insert-property format content :collapsed true)
(false? collapsed?)
(property/remove-property format :collapsed content)
:else
content))
(defn transform-content
[{:block/keys [collapsed? format pre-block? unordered content left page parent properties]} level {:keys [heading-to-list?]}]
(let [heading (:heading properties)
markdown? (= :markdown format)
content (or content "")
pre-block? (or pre-block?
first block
markdown?
(string/includes? (first (string/split-lines content)) ":: ")))
content (cond
pre-block?
(let [content (string/trim content)]
(str content "\n"))
:else
(let [markdown-top-heading? (and markdown?
(= parent page)
(not unordered)
heading)
[prefix spaces-tabs]
(cond
(= format :org)
[(->>
(repeat level "*")
(apply str)) ""]
markdown-top-heading?
["" ""]
:else
(let [level (if (and heading-to-list? heading)
(if (> heading 1)
(dec heading)
heading)
level)
spaces-tabs (->>
(repeat (dec level) (state/get-export-bullet-indentation))
(apply str))]
[(str spaces-tabs "-") (str spaces-tabs " ")]))
content (if heading-to-list?
(-> (string/replace content #"^\s?#+\s+" "")
(string/replace #"^\s?#+\s?$" ""))
content)
content (content-with-collapsed-state format content collapsed?)
new-content (indented-block-content (string/trim content) spaces-tabs)
sep (if (or markdown-top-heading?
(string/blank? new-content))
""
" ")]
(str prefix sep new-content)))]
content))
(defn- tree->file-content-aux
[tree {:keys [init-level] :as opts}]
(let [block-contents (transient [])]
(loop [[f & r] tree level init-level]
(if (nil? f)
(->> block-contents persistent! flatten (remove nil?))
(let [page? (nil? (:block/page f))
content (if page? nil (transform-content f level opts))
new-content
(if-let [children (seq (:block/children f))]
(cons content (tree->file-content-aux children {:init-level (inc level)}))
[content])]
(conj! block-contents new-content)
(recur r level))))))
(defn tree->file-content
[tree opts]
(->> (tree->file-content-aux tree opts) (string/join "\n")))
(def init-level 1)
(defn- transact-file-tx-if-not-exists!
[page ok-handler]
(when-let [repo (state/get-current-repo)]
(when (:block/name page)
(let [format (name (get page :block/format
(state/get-preferred-format)))
title (string/capitalize (:block/name page))
whiteboard-page? (model/whiteboard-page? page)
format (if whiteboard-page? "edn" format)
journal-page? (date/valid-journal-title? title)
journal-title (date/normalize-journal-title title)
filename (if (and journal-page? (not (string/blank? journal-title)))
(date/date->file-name journal-title)
(-> (or (:block/original-name page) (:block/name page))
(fs-util/file-name-sanity)))
sub-dir (cond
journal-page? (config/get-journals-directory)
whiteboard-page? (config/get-whiteboards-directory)
:else (config/get-pages-directory))
ext (if (= format "markdown") "md" format)
file-path (config/get-page-file-path repo sub-dir filename ext)
file {:file/path file-path}
tx [{:file/path file-path}
{:block/name (:block/name page)
:block/file file}]]
(db/transact! tx)
(when ok-handler (ok-handler))))))
(defn- remove-transit-ids [block] (dissoc block :db/id :block/file))
(defn save-tree-aux!
[page-block tree blocks-just-deleted?]
(let [page-block (db/pull (:db/id page-block))
file-db-id (-> page-block :block/file :db/id)
file-path (-> (db-utils/entity file-db-id) :file/path)]
(if (and (string? file-path) (not-empty file-path))
(let [new-content (if (= "whiteboard" (:block/type page-block))
(->
(up/ugly-pr-str {:blocks tree
:pages (list (remove-transit-ids page-block))})
(string/triml))
(tree->file-content tree {:init-level init-level}))]
(if (and (string/blank? new-content)
(not blocks-just-deleted?))
(state/pub-event! [:capture-error {:error (js/Error. "Empty content")
:payload {:file-path file-path}}])
(let [files [[file-path new-content]]
repo (state/get-current-repo)]
(file-handler/alter-files-handler! repo files {} {}))))
(js/console.error "File path from page-block is not valid" page-block tree))))
(defn save-tree!
[page-block tree blocks-just-deleted?]
{:pre [(map? page-block)]}
(let [ok-handler #(save-tree-aux! page-block tree blocks-just-deleted?)
file (or (:block/file page-block)
(when-let [page (:db/id (:block/page page-block))]
(:block/file (db-utils/entity page))))]
(if file
(ok-handler)
(transact-file-tx-if-not-exists! page-block ok-handler))))
|
5a772186501377cc571bb6dfc0d38fe208e536401ed6d3ce803ec3e0e2230f47 | Kakadu/fp2022 | ast.mli | * Copyright 2021 - 2022 , Kakadu and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
type name = string
* The main type for our AST ( дерева )
type 'name t =
| Var of 'name (** Variable [x] *)
| Abs of 'name * 'name t (** Abstraction [λx.t] *)
| App of 'name t * 'name t
(* Application [f g ] *)
* In type definition above the 3rd constructor is intentionally without documentation
to test linter
to test linter *)
| null | https://raw.githubusercontent.com/Kakadu/fp2022/0d134cc88e5db154e705c25b1d010b70df757505/Lambda/lib/ast.mli | ocaml | * Variable [x]
* Abstraction [λx.t]
Application [f g ] | * Copyright 2021 - 2022 , Kakadu and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
type name = string
* The main type for our AST ( дерева )
type 'name t =
| App of 'name t * 'name t
* In type definition above the 3rd constructor is intentionally without documentation
to test linter
to test linter *)
|
90aad590e32465cecfd284ca2746a7d1cf22515f2374c6646d74a84d14cdd063 | haskell-mafia/mafia | Install.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
module Mafia.Install
( Flavour(..)
, installDependencies
, installPackage
, transitiveOfPackages
, InstallError(..)
, renderInstallError
) where
import Control.Exception (SomeException)
import Control.Monad.Trans.Bifunctor (firstT)
import Control.Monad.Trans.Either (EitherT, pattern EitherT, left, runEitherT)
import Control.Parallel.Strategies (rpar, parMap)
import qualified Control.Retry as Retry
import Data.Bits (Bits(..))
import qualified Data.ByteString as B
import Data.Char (ord)
import qualified Data.List as List
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Read as T
import Data.Word (Word32)
import Entwine (writeQueue)
import Entwine.Parallel (RunError (..), consume_)
import GHC.Conc (getNumProcessors)
import GHC.Real (toInteger)
import Mafia.Cabal.Constraint
import Mafia.Cabal.Dependencies
import Mafia.Cabal.Package
import Mafia.Cabal.Process
import Mafia.Cabal.Sandbox
import Mafia.Cabal.Types
import Mafia.Cache
import Mafia.IO
import Mafia.P
import Mafia.Package
import Mafia.Path
import Mafia.Process
import Mafia.Tree
import Numeric (showHex)
import System.IO (IO, stderr)
import qualified System.Info as Info
------------------------------------------------------------------------
data InstallError =
InstallCacheError CacheError
| InstallCabalError CabalError
| InstallPackageError PackageId (Set Package) CabalError
| InstallLinkError Package File
| InstallEnvParseError EnvKey EnvValue Text
| InstallPlanPackageMissing PackageName
| InstallPlanPackageDuplicate PackageName [Package]
| InstallUnknownPackageType PackageId
| InstallUnpackFailed PackageId Directory (OutErrCode Text)
| InstallDisaster SomeException
deriving (Show)
renderInstallError :: InstallError -> Text
renderInstallError = \case
InstallCacheError e ->
renderCacheError e
InstallCabalError e ->
renderCabalError e
InstallPackageError pid@(PackageId name _) pkgs e ->
"Failed to install " <> renderPackageId pid <> "\n" <>
renderCabalError e <> "\n" <>
let
take n txt =
let
reasonable =
List.take (n+1) $ TL.lines txt
pname =
TL.fromStrict (unPackageName name)
presentable =
if length reasonable > n then
List.take n reasonable <>
[ "── snip ──"
, "Run 'mafia depends " <> pname <> " --tree' to see the full tree." ]
else
reasonable
in
TL.toStrict . TL.strip $ TL.unlines presentable
in
take 50 . renderTree $ filterPackages (pkgName pid) pkgs
InstallLinkError p pcfg ->
"Failed to create symlink for " <> renderHashId p <> ", package config did not exist: " <> pcfg
InstallEnvParseError key val err ->
"Failed parsing environment variable " <> key <> "=" <> val <> " (" <> err <> ")"
InstallPlanPackageMissing name ->
"Package not found in install plan: " <> unPackageName name
InstallPlanPackageDuplicate name _ ->
"Package duplicated in install plan: " <> unPackageName name
InstallUnknownPackageType pid ->
"Unknown package type for: " <> renderPackageId pid
InstallUnpackFailed pid tmp out ->
"Failed to unpack " <> renderPackageId pid <> " to " <> tmp <> "\n" <>
renderOutErrCode out
InstallDisaster ex ->
"Disaster: " <> T.pack (show ex)
------------------------------------------------------------------------
installDependencies :: Flavour -> [Flag] -> [SourcePackage] -> [Constraint] -> EitherT InstallError IO (Set Package)
installDependencies flavour flags spkgs constraints = do
pkg <- firstT InstallCabalError $ findDependenciesForCurrentDirectory flags spkgs constraints
let
tdeps = transitiveOfPackages (pkgDeps pkg)
installGlobalPackages flavour tdeps
_ <- firstT InstallCabalError initSandbox
packageDB <- firstT InstallCabalError getPackageDB
ignoreIO $ removeDirectoryRecursive packageDB
createDirectoryIfMissing True packageDB
-- create symlinks to the relevant package .conf files in the
package - db , then call recache so that ghc is aware of them .
env <- firstT InstallCacheError getCacheEnv
mapM_ (link packageDB env) tdeps
Hush <- firstT InstallCabalError $ cabal "sandbox" ["hc-pkg", "recache"]
return tdeps
installPackage :: PackageName -> [Constraint] -> EitherT InstallError IO Package
installPackage name constraints = do
pkg <- firstT InstallCabalError $ findDependenciesForPackage name constraints
installGlobalPackages Vanilla (transitiveOfPackages (Set.singleton pkg))
return pkg
installGlobalPackages :: Flavour -> Set Package -> EitherT InstallError IO ()
installGlobalPackages flavour deps = do
let producer q = mapM_ (writeQueue q) deps
mw <- getMafiaWorkers
gw <- getGhcWorkers
env <- firstT InstallCacheError getCacheEnv
firstT (squashRunError deps) $ consume_ producer (fromInteger . toInteger $ mw) (install gw env flavour)
------------------------------------------------------------------------
type NumWorkers = Int
getDefaultWorkers :: MonadIO m => m NumWorkers
getDefaultWorkers =
min 4 `liftM` liftIO getNumProcessors
getMafiaWorkers :: EitherT InstallError IO NumWorkers
getMafiaWorkers = do
def <- getDefaultWorkers
fromMaybe def <$> lookupPositive "MAFIA_WORKERS"
getGhcWorkers :: EitherT InstallError IO NumWorkers
getGhcWorkers = do
def <- getDefaultWorkers
fromMaybe def <$> lookupPositive "MAFIA_GHC_WORKERS"
lookupPositive :: Text -> EitherT InstallError IO (Maybe Int)
lookupPositive key = do
mtxt <- lookupEnv key
case mtxt of
Nothing ->
return Nothing
Just txt ->
case T.decimal txt of
Right (x, "") | x > 0 ->
return (Just x)
Right _ ->
left (InstallEnvParseError key txt "not a positive number")
Left str ->
left (InstallEnvParseError key txt (T.pack str))
------------------------------------------------------------------------
-- | Installs a package and its dependencies in to the mafia global package
cache in $ MAFIA_HOME by taking the following steps :
--
-- 1. Checks if the package.conf file already exists, this is what decides
-- whether we've already installed a package or not.
--
2 . Takes a machine wide lock on the package to make sure that two mafia 's
-- can still run at the same time.
--
-- 3. Creates a fresh a sandbox in the global cache.
--
-- 4. Adds the source if the package is a source/submodule dependency.
--
-- 5. Registers any dependencies in to the sandbox package db by creating
-- symbolic links.
--
6 . Install the package .
--
-- 7. Create a package.conf file which can be symlinked in to other package db's.
--
install :: NumWorkers -> CacheEnv -> Flavour -> Package -> EitherT InstallError IO ()
install w env flavour p@(Package (PackageRef pid _ _) deps _) = do
-- only try to install this package/flavour if we haven't done it already.
-- it's important to do this before we do the same for any dependencies
-- otherwise we end up doing an exponential number of checks.
let fmark = packageFlavourMarker env (pkgKey p) flavour
unlessM (doesFileExist fmark) $ do
-- install package dependencies
mapM_ (install w env flavour) (transitiveOfPackages deps)
-- detect and install build tools
tools <- detectBuildTools p
for_ tools $ \tool ->
liftIO . T.hPutStrLn stderr $
"Detected '" <> unPackageName (toolName tool) <> "' " <>
"was required to build " <> renderPackageId pid
paths <- installBuildTools env tools
the vanilla flavour must always be installed first :
-- + it creates and sets up the package's sandbox
-- + profiling builds need the vanilla build for template haskell to run
+ documentation builds need the vanilla build to harvest the .hi files
when (flavour /= Vanilla) $
install w env Vanilla p
-- we take this lock *after* all the package dependencies have been
-- installed, otherwise we can prevent some parallelism from occurring
unlessM (doesFileExist fmark) $
withPackageLock env (pkgKey p) flavour $
unlessM (doesFileExist fmark) $ do
-- when we create the package sandbox it determines whether the
-- package contains only executables, or is also available as a
-- library, this is the package type.
ptype <-
if (flavour == Vanilla) then
Just <$> createPackageSandbox env p
else
pure Nothing
let sbdir = packageSandboxDir env (pkgKey p)
sbcfg = packageSandboxConfig env (pkgKey p)
let sbcabal x xs =
firstT (InstallPackageError pid Set.empty) $ cabalFrom sbdir sbcfg paths x xs
liftIO . T.hPutStrLn stderr $ "Building " <> renderHashId p <> renderFlavourSuffix flavour
let platformargs =
case Info.os of
"darwin" -> [
"--ghc-options=-optl-Wl,-dead_strip_dylibs"
, "--ghc-options=-optc-Wno-unused-command-line-argument"
, "--ghc-options=-optl-Wno-unused-command-line-argument"
]
_ -> [
]
PassErr <- sbcabal "install" $
platformargs <>
[ "--ghc-options=-j" <> T.pack (show w)
, "--max-backjumps=0"
, renderPackageId pid ] <>
flavourArgs flavour <>
constraintArgs (constraintsOfPackage p)
when (flavour == Vanilla) $
case ptype of
-- only library packages can be described
Just Library -> do
Out out <- sbcabal "sandbox" ["hc-pkg", "--", "describe", renderPackageId pid]
writeUtf8 (packageConfig env $ pkgKey p) out
-- for executable only packages we just leave an empty marker
Just ExecutablesOnly ->
writeUtf8 (packageConfig env $ pkgKey p) T.empty
-- this can't really happen, we're only supposed to assign
-- 'ptype' to Nothing if we're not installing the vanilla flavour
Nothing ->
left (InstallUnknownPackageType pid)
writeBytes fmark B.empty
flavourArgs :: Flavour -> [Argument]
flavourArgs = \case
Vanilla ->
[]
Profiling ->
[ "--reinstall"
, "--ghc-options=-fprof-auto-exported"
, "--enable-library-profiling" ]
Documentation ->
[ "--reinstall"
, "--enable-documentation"
, "--haddock-hoogle"
, "--haddock-hyperlink-source" ]
-- | Creates and installs/links the dependencies for a package in to its well
-- known global sandbox.
createPackageSandbox :: CacheEnv -> Package -> EitherT InstallError IO PackageType
createPackageSandbox env p@(Package (PackageRef pid _ msrc) deps _) = do
liftIO . T.hPutStrLn stderr $ "Creating sandbox for " <> renderHashId p
let sbdir = packageSandboxDir env $ pkgKey p
sbcfg = packageSandboxConfig env $ pkgKey p
sbsrc = packageSourceDir env $ pkgKey p
let sbcabal x xs =
firstT InstallCabalError $ cabalFrom sbdir sbcfg [] x xs
ignoreIO (removeDirectoryRecursive sbdir)
createDirectoryIfMissing True sbdir
Hush <- sbcabal "sandbox" ["init", "--sandbox", sbdir]
srcdir <- case msrc of
-- hackage package
Nothing -> do
-- We install hackage packages by unpacking them in to a src/ directory
-- inside the package's location in the global cache. This allows us to
-- cheaply upgrade non-profiling builds to profiling builds as the .o
-- files are kept around in the dist/ directory. It also has the benefit
-- of not polluting the $TMPDIR on the build bot.
createDirectoryIfMissing True sbsrc
let
srcdir = sbsrc </> renderPackageId pid
retryOnLeft (unpackRetryMessage pid) . capture (InstallUnpackFailed pid sbsrc) $
sbcabal "unpack" ["--destdir=" <> sbsrc, renderPackageId pid]
Hush <- sbcabal "sandbox" ["add-source", srcdir]
-- We need to shuffle anything which was unpacked to 'dist' in to
-- 'dist-sandbox-XXX' in order to be able to install packages like
' happy ' and ' ' which have pre - baked files from their dist
-- directory in the release tarball.
--
--
--
--
let
dist = srcdir </> "dist"
distTmp = srcdir </> "dist-tmp"
distSandbox = dist </> "dist-sandbox-" <> jenkins sbdir
whenM (doesDirectoryExist dist) $ do
renameDirectory dist distTmp
createDirectoryIfMissing False dist
renameDirectory distTmp distSandbox
return srcdir
-- source package
Just src -> do
Hush <- sbcabal "sandbox" ["add-source", spDirectory src]
return (spDirectory src)
ty <- firstT InstallCabalError $ getPackageType srcdir
db <- firstT InstallCabalError $ readPackageDB sbcfg
-- create symlinks to the relevant package .conf files in the
package - db , then call recache so that ghc is aware of them .
mapM_ (link db env) (transitiveOfPackages deps)
Hush <- sbcabal "sandbox" ["hc-pkg", "recache"]
return ty
-- | Install the specified build tools and return the paths to the 'bin' directories.
installBuildTools :: CacheEnv -> Set BuildTool -> EitherT InstallError IO [Directory]
installBuildTools env tools = do
pkgs <-
for (Set.toList tools) $ \(BuildTool name constraints) ->
tryInstall name constraints
pure .
fmap (</> "bin") .
fmap (packageSandboxDir env) $
fmap pkgKey $
catMaybes pkgs
where
-- Some packages refer to build-tools that are not cabal packages.
-- For example, "zip-archive" depends on "unzip", but this is talking about a binary, not a cabal package.
-- This is unfortunate, and perhaps the package shouldn't include this as it isn't a build tool, but we should probably provide some way to continue building regardless.
tryInstall name constraints = EitherT $ do
r <- runEitherT $ installPackage name constraints
case r of
Left e -> do
T.hPutStrLn stderr $
"Error while trying to install build tool '" <> unPackageName name <> "': "
T.hPutStrLn stderr $ renderInstallError e
T.hPutStrLn stderr "Trying to continue anyway, as some packages refer to non-existent build tools."
return $ Right Nothing
Right pkg -> do
return $ Right $ Just pkg
-- | Detect the build tools required by a package.
detectBuildTools :: Package -> EitherT InstallError IO (Set BuildTool)
detectBuildTools (Package (PackageRef pid _ msrc) _ _) =
case msrc of
-- hackage package
Nothing ->
withSystemTempDirectory "mafia-detect-build-tools-" $ \tmp -> do
retryOnLeft (unpackRetryMessage pid) . capture (InstallUnpackFailed pid tmp) . firstT InstallCabalError $
cabal "unpack" ["--destdir=" <> tmp, renderPackageId pid]
firstT InstallCabalError .
getBuildTools $ tmp </> renderPackageId pid
-- source package
Just src ->
firstT InstallCabalError .
getBuildTools $ spDirectory src
unpackRetryMessage :: PackageId -> Text
unpackRetryMessage pid =
"Retrying download of " <> renderPackageId pid <> "..."
retryOnLeft :: Text -> EitherT InstallError IO a -> EitherT InstallError IO a
retryOnLeft msg io =
let
retries =
5
policy =
0.5s
Retry.limitRetries retries
check status = \case
Left e -> do
when (Retry.rsIterNumber status <= retries) $
T.hPutStrLn stderr $ renderInstallError e
pure True
Right _ ->
pure False
in
EitherT . Retry.retrying policy check $ \status -> do
when (Retry.rsIterNumber status > 0) $
T.hPutStrLn stderr msg
runEitherT io
link :: Directory -> CacheEnv -> Package -> EitherT InstallError IO ()
link db env p@(Package (PackageRef pid _ _) _ _) = do
let pcfg = packageConfig env $ pkgKey p
unlessM (doesFileExist pcfg) $
left (InstallLinkError p pcfg)
let dest = db </> renderPackageId pid <> ".conf"
createSymbolicLink pcfg dest
squashRunError :: Set Package -> RunError InstallError -> InstallError
squashRunError pkgs = \case
WorkerError (InstallPackageError pid old e) | Set.null old ->
InstallPackageError pid pkgs e
WorkerError e ->
e
BlowUpError e ->
InstallDisaster e
------------------------------------------------------------------------
constraintsOfPackage :: Package -> [Constraint]
constraintsOfPackage p =
let xs = Set.toList (transitiveOfPackages (Set.singleton p))
in concatMap (packageRefConstraints . pkgRef) xs
transitiveOfPackages :: Set Package -> Set Package
transitiveOfPackages deps =
Set.unions (deps : parMap rpar (transitiveOfPackages . pkgDeps) (Set.toList deps))
------------------------------------------------------------------------
--
This hash function is originally from Cabal :
--
-install/Distribution/Client/Sandbox.hs#L157
--
-- See
--
jenkins :: Directory -> Text
jenkins =
let
loop :: Word32 -> Char -> Word32
loop hash0 key_i' =
let
key_i = fromIntegral . ord $ key_i'
hash1 = hash0 + key_i
hash2 = hash1 + (shiftL hash1 10)
hash3 = hash2 `xor` (shiftR hash2 6)
in
hash3
loop_finish :: Word32 -> Word32
loop_finish hash0 =
let
hash1 = hash0 + (shiftL hash0 3)
hash2 = hash1 `xor` (shiftR hash1 11)
hash3 = hash2 + (shiftL hash2 15)
in
hash3
in
T.pack .
flip showHex "" .
loop_finish .
foldl' loop 0 .
T.unpack
| null | https://raw.githubusercontent.com/haskell-mafia/mafia/529440246ee571bf1473615e6218f52cd1e990ae/src/Mafia/Install.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------
----------------------------------------------------------------------
create symlinks to the relevant package .conf files in the
----------------------------------------------------------------------
----------------------------------------------------------------------
| Installs a package and its dependencies in to the mafia global package
1. Checks if the package.conf file already exists, this is what decides
whether we've already installed a package or not.
can still run at the same time.
3. Creates a fresh a sandbox in the global cache.
4. Adds the source if the package is a source/submodule dependency.
5. Registers any dependencies in to the sandbox package db by creating
symbolic links.
7. Create a package.conf file which can be symlinked in to other package db's.
only try to install this package/flavour if we haven't done it already.
it's important to do this before we do the same for any dependencies
otherwise we end up doing an exponential number of checks.
install package dependencies
detect and install build tools
+ it creates and sets up the package's sandbox
+ profiling builds need the vanilla build for template haskell to run
we take this lock *after* all the package dependencies have been
installed, otherwise we can prevent some parallelism from occurring
when we create the package sandbox it determines whether the
package contains only executables, or is also available as a
library, this is the package type.
only library packages can be described
for executable only packages we just leave an empty marker
this can't really happen, we're only supposed to assign
'ptype' to Nothing if we're not installing the vanilla flavour
| Creates and installs/links the dependencies for a package in to its well
known global sandbox.
hackage package
We install hackage packages by unpacking them in to a src/ directory
inside the package's location in the global cache. This allows us to
cheaply upgrade non-profiling builds to profiling builds as the .o
files are kept around in the dist/ directory. It also has the benefit
of not polluting the $TMPDIR on the build bot.
We need to shuffle anything which was unpacked to 'dist' in to
'dist-sandbox-XXX' in order to be able to install packages like
directory in the release tarball.
source package
create symlinks to the relevant package .conf files in the
| Install the specified build tools and return the paths to the 'bin' directories.
Some packages refer to build-tools that are not cabal packages.
For example, "zip-archive" depends on "unzip", but this is talking about a binary, not a cabal package.
This is unfortunate, and perhaps the package shouldn't include this as it isn't a build tool, but we should probably provide some way to continue building regardless.
| Detect the build tools required by a package.
hackage package
source package
----------------------------------------------------------------------
----------------------------------------------------------------------
See
| # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
module Mafia.Install
( Flavour(..)
, installDependencies
, installPackage
, transitiveOfPackages
, InstallError(..)
, renderInstallError
) where
import Control.Exception (SomeException)
import Control.Monad.Trans.Bifunctor (firstT)
import Control.Monad.Trans.Either (EitherT, pattern EitherT, left, runEitherT)
import Control.Parallel.Strategies (rpar, parMap)
import qualified Control.Retry as Retry
import Data.Bits (Bits(..))
import qualified Data.ByteString as B
import Data.Char (ord)
import qualified Data.List as List
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Read as T
import Data.Word (Word32)
import Entwine (writeQueue)
import Entwine.Parallel (RunError (..), consume_)
import GHC.Conc (getNumProcessors)
import GHC.Real (toInteger)
import Mafia.Cabal.Constraint
import Mafia.Cabal.Dependencies
import Mafia.Cabal.Package
import Mafia.Cabal.Process
import Mafia.Cabal.Sandbox
import Mafia.Cabal.Types
import Mafia.Cache
import Mafia.IO
import Mafia.P
import Mafia.Package
import Mafia.Path
import Mafia.Process
import Mafia.Tree
import Numeric (showHex)
import System.IO (IO, stderr)
import qualified System.Info as Info
data InstallError =
InstallCacheError CacheError
| InstallCabalError CabalError
| InstallPackageError PackageId (Set Package) CabalError
| InstallLinkError Package File
| InstallEnvParseError EnvKey EnvValue Text
| InstallPlanPackageMissing PackageName
| InstallPlanPackageDuplicate PackageName [Package]
| InstallUnknownPackageType PackageId
| InstallUnpackFailed PackageId Directory (OutErrCode Text)
| InstallDisaster SomeException
deriving (Show)
renderInstallError :: InstallError -> Text
renderInstallError = \case
InstallCacheError e ->
renderCacheError e
InstallCabalError e ->
renderCabalError e
InstallPackageError pid@(PackageId name _) pkgs e ->
"Failed to install " <> renderPackageId pid <> "\n" <>
renderCabalError e <> "\n" <>
let
take n txt =
let
reasonable =
List.take (n+1) $ TL.lines txt
pname =
TL.fromStrict (unPackageName name)
presentable =
if length reasonable > n then
List.take n reasonable <>
[ "── snip ──"
, "Run 'mafia depends " <> pname <> " --tree' to see the full tree." ]
else
reasonable
in
TL.toStrict . TL.strip $ TL.unlines presentable
in
take 50 . renderTree $ filterPackages (pkgName pid) pkgs
InstallLinkError p pcfg ->
"Failed to create symlink for " <> renderHashId p <> ", package config did not exist: " <> pcfg
InstallEnvParseError key val err ->
"Failed parsing environment variable " <> key <> "=" <> val <> " (" <> err <> ")"
InstallPlanPackageMissing name ->
"Package not found in install plan: " <> unPackageName name
InstallPlanPackageDuplicate name _ ->
"Package duplicated in install plan: " <> unPackageName name
InstallUnknownPackageType pid ->
"Unknown package type for: " <> renderPackageId pid
InstallUnpackFailed pid tmp out ->
"Failed to unpack " <> renderPackageId pid <> " to " <> tmp <> "\n" <>
renderOutErrCode out
InstallDisaster ex ->
"Disaster: " <> T.pack (show ex)
installDependencies :: Flavour -> [Flag] -> [SourcePackage] -> [Constraint] -> EitherT InstallError IO (Set Package)
installDependencies flavour flags spkgs constraints = do
pkg <- firstT InstallCabalError $ findDependenciesForCurrentDirectory flags spkgs constraints
let
tdeps = transitiveOfPackages (pkgDeps pkg)
installGlobalPackages flavour tdeps
_ <- firstT InstallCabalError initSandbox
packageDB <- firstT InstallCabalError getPackageDB
ignoreIO $ removeDirectoryRecursive packageDB
createDirectoryIfMissing True packageDB
package - db , then call recache so that ghc is aware of them .
env <- firstT InstallCacheError getCacheEnv
mapM_ (link packageDB env) tdeps
Hush <- firstT InstallCabalError $ cabal "sandbox" ["hc-pkg", "recache"]
return tdeps
installPackage :: PackageName -> [Constraint] -> EitherT InstallError IO Package
installPackage name constraints = do
pkg <- firstT InstallCabalError $ findDependenciesForPackage name constraints
installGlobalPackages Vanilla (transitiveOfPackages (Set.singleton pkg))
return pkg
installGlobalPackages :: Flavour -> Set Package -> EitherT InstallError IO ()
installGlobalPackages flavour deps = do
let producer q = mapM_ (writeQueue q) deps
mw <- getMafiaWorkers
gw <- getGhcWorkers
env <- firstT InstallCacheError getCacheEnv
firstT (squashRunError deps) $ consume_ producer (fromInteger . toInteger $ mw) (install gw env flavour)
type NumWorkers = Int
getDefaultWorkers :: MonadIO m => m NumWorkers
getDefaultWorkers =
min 4 `liftM` liftIO getNumProcessors
getMafiaWorkers :: EitherT InstallError IO NumWorkers
getMafiaWorkers = do
def <- getDefaultWorkers
fromMaybe def <$> lookupPositive "MAFIA_WORKERS"
getGhcWorkers :: EitherT InstallError IO NumWorkers
getGhcWorkers = do
def <- getDefaultWorkers
fromMaybe def <$> lookupPositive "MAFIA_GHC_WORKERS"
lookupPositive :: Text -> EitherT InstallError IO (Maybe Int)
lookupPositive key = do
mtxt <- lookupEnv key
case mtxt of
Nothing ->
return Nothing
Just txt ->
case T.decimal txt of
Right (x, "") | x > 0 ->
return (Just x)
Right _ ->
left (InstallEnvParseError key txt "not a positive number")
Left str ->
left (InstallEnvParseError key txt (T.pack str))
cache in $ MAFIA_HOME by taking the following steps :
2 . Takes a machine wide lock on the package to make sure that two mafia 's
6 . Install the package .
install :: NumWorkers -> CacheEnv -> Flavour -> Package -> EitherT InstallError IO ()
install w env flavour p@(Package (PackageRef pid _ _) deps _) = do
let fmark = packageFlavourMarker env (pkgKey p) flavour
unlessM (doesFileExist fmark) $ do
mapM_ (install w env flavour) (transitiveOfPackages deps)
tools <- detectBuildTools p
for_ tools $ \tool ->
liftIO . T.hPutStrLn stderr $
"Detected '" <> unPackageName (toolName tool) <> "' " <>
"was required to build " <> renderPackageId pid
paths <- installBuildTools env tools
the vanilla flavour must always be installed first :
+ documentation builds need the vanilla build to harvest the .hi files
when (flavour /= Vanilla) $
install w env Vanilla p
unlessM (doesFileExist fmark) $
withPackageLock env (pkgKey p) flavour $
unlessM (doesFileExist fmark) $ do
ptype <-
if (flavour == Vanilla) then
Just <$> createPackageSandbox env p
else
pure Nothing
let sbdir = packageSandboxDir env (pkgKey p)
sbcfg = packageSandboxConfig env (pkgKey p)
let sbcabal x xs =
firstT (InstallPackageError pid Set.empty) $ cabalFrom sbdir sbcfg paths x xs
liftIO . T.hPutStrLn stderr $ "Building " <> renderHashId p <> renderFlavourSuffix flavour
let platformargs =
case Info.os of
"darwin" -> [
"--ghc-options=-optl-Wl,-dead_strip_dylibs"
, "--ghc-options=-optc-Wno-unused-command-line-argument"
, "--ghc-options=-optl-Wno-unused-command-line-argument"
]
_ -> [
]
PassErr <- sbcabal "install" $
platformargs <>
[ "--ghc-options=-j" <> T.pack (show w)
, "--max-backjumps=0"
, renderPackageId pid ] <>
flavourArgs flavour <>
constraintArgs (constraintsOfPackage p)
when (flavour == Vanilla) $
case ptype of
Just Library -> do
Out out <- sbcabal "sandbox" ["hc-pkg", "--", "describe", renderPackageId pid]
writeUtf8 (packageConfig env $ pkgKey p) out
Just ExecutablesOnly ->
writeUtf8 (packageConfig env $ pkgKey p) T.empty
Nothing ->
left (InstallUnknownPackageType pid)
writeBytes fmark B.empty
flavourArgs :: Flavour -> [Argument]
flavourArgs = \case
Vanilla ->
[]
Profiling ->
[ "--reinstall"
, "--ghc-options=-fprof-auto-exported"
, "--enable-library-profiling" ]
Documentation ->
[ "--reinstall"
, "--enable-documentation"
, "--haddock-hoogle"
, "--haddock-hyperlink-source" ]
createPackageSandbox :: CacheEnv -> Package -> EitherT InstallError IO PackageType
createPackageSandbox env p@(Package (PackageRef pid _ msrc) deps _) = do
liftIO . T.hPutStrLn stderr $ "Creating sandbox for " <> renderHashId p
let sbdir = packageSandboxDir env $ pkgKey p
sbcfg = packageSandboxConfig env $ pkgKey p
sbsrc = packageSourceDir env $ pkgKey p
let sbcabal x xs =
firstT InstallCabalError $ cabalFrom sbdir sbcfg [] x xs
ignoreIO (removeDirectoryRecursive sbdir)
createDirectoryIfMissing True sbdir
Hush <- sbcabal "sandbox" ["init", "--sandbox", sbdir]
srcdir <- case msrc of
Nothing -> do
createDirectoryIfMissing True sbsrc
let
srcdir = sbsrc </> renderPackageId pid
retryOnLeft (unpackRetryMessage pid) . capture (InstallUnpackFailed pid sbsrc) $
sbcabal "unpack" ["--destdir=" <> sbsrc, renderPackageId pid]
Hush <- sbcabal "sandbox" ["add-source", srcdir]
' happy ' and ' ' which have pre - baked files from their dist
let
dist = srcdir </> "dist"
distTmp = srcdir </> "dist-tmp"
distSandbox = dist </> "dist-sandbox-" <> jenkins sbdir
whenM (doesDirectoryExist dist) $ do
renameDirectory dist distTmp
createDirectoryIfMissing False dist
renameDirectory distTmp distSandbox
return srcdir
Just src -> do
Hush <- sbcabal "sandbox" ["add-source", spDirectory src]
return (spDirectory src)
ty <- firstT InstallCabalError $ getPackageType srcdir
db <- firstT InstallCabalError $ readPackageDB sbcfg
package - db , then call recache so that ghc is aware of them .
mapM_ (link db env) (transitiveOfPackages deps)
Hush <- sbcabal "sandbox" ["hc-pkg", "recache"]
return ty
installBuildTools :: CacheEnv -> Set BuildTool -> EitherT InstallError IO [Directory]
installBuildTools env tools = do
pkgs <-
for (Set.toList tools) $ \(BuildTool name constraints) ->
tryInstall name constraints
pure .
fmap (</> "bin") .
fmap (packageSandboxDir env) $
fmap pkgKey $
catMaybes pkgs
where
tryInstall name constraints = EitherT $ do
r <- runEitherT $ installPackage name constraints
case r of
Left e -> do
T.hPutStrLn stderr $
"Error while trying to install build tool '" <> unPackageName name <> "': "
T.hPutStrLn stderr $ renderInstallError e
T.hPutStrLn stderr "Trying to continue anyway, as some packages refer to non-existent build tools."
return $ Right Nothing
Right pkg -> do
return $ Right $ Just pkg
detectBuildTools :: Package -> EitherT InstallError IO (Set BuildTool)
detectBuildTools (Package (PackageRef pid _ msrc) _ _) =
case msrc of
Nothing ->
withSystemTempDirectory "mafia-detect-build-tools-" $ \tmp -> do
retryOnLeft (unpackRetryMessage pid) . capture (InstallUnpackFailed pid tmp) . firstT InstallCabalError $
cabal "unpack" ["--destdir=" <> tmp, renderPackageId pid]
firstT InstallCabalError .
getBuildTools $ tmp </> renderPackageId pid
Just src ->
firstT InstallCabalError .
getBuildTools $ spDirectory src
unpackRetryMessage :: PackageId -> Text
unpackRetryMessage pid =
"Retrying download of " <> renderPackageId pid <> "..."
retryOnLeft :: Text -> EitherT InstallError IO a -> EitherT InstallError IO a
retryOnLeft msg io =
let
retries =
5
policy =
0.5s
Retry.limitRetries retries
check status = \case
Left e -> do
when (Retry.rsIterNumber status <= retries) $
T.hPutStrLn stderr $ renderInstallError e
pure True
Right _ ->
pure False
in
EitherT . Retry.retrying policy check $ \status -> do
when (Retry.rsIterNumber status > 0) $
T.hPutStrLn stderr msg
runEitherT io
link :: Directory -> CacheEnv -> Package -> EitherT InstallError IO ()
link db env p@(Package (PackageRef pid _ _) _ _) = do
let pcfg = packageConfig env $ pkgKey p
unlessM (doesFileExist pcfg) $
left (InstallLinkError p pcfg)
let dest = db </> renderPackageId pid <> ".conf"
createSymbolicLink pcfg dest
squashRunError :: Set Package -> RunError InstallError -> InstallError
squashRunError pkgs = \case
WorkerError (InstallPackageError pid old e) | Set.null old ->
InstallPackageError pid pkgs e
WorkerError e ->
e
BlowUpError e ->
InstallDisaster e
constraintsOfPackage :: Package -> [Constraint]
constraintsOfPackage p =
let xs = Set.toList (transitiveOfPackages (Set.singleton p))
in concatMap (packageRefConstraints . pkgRef) xs
transitiveOfPackages :: Set Package -> Set Package
transitiveOfPackages deps =
Set.unions (deps : parMap rpar (transitiveOfPackages . pkgDeps) (Set.toList deps))
This hash function is originally from Cabal :
-install/Distribution/Client/Sandbox.hs#L157
jenkins :: Directory -> Text
jenkins =
let
loop :: Word32 -> Char -> Word32
loop hash0 key_i' =
let
key_i = fromIntegral . ord $ key_i'
hash1 = hash0 + key_i
hash2 = hash1 + (shiftL hash1 10)
hash3 = hash2 `xor` (shiftR hash2 6)
in
hash3
loop_finish :: Word32 -> Word32
loop_finish hash0 =
let
hash1 = hash0 + (shiftL hash0 3)
hash2 = hash1 `xor` (shiftR hash1 11)
hash3 = hash2 + (shiftL hash2 15)
in
hash3
in
T.pack .
flip showHex "" .
loop_finish .
foldl' loop 0 .
T.unpack
|
c3866dae01d0bd8ae3e9622fcdd967179489187872097618b45598e9d42ee68c | neilprosser/mr-maestro | tyrant_test.clj | (ns maestro.tyrant-test
(:require [cheshire.core :as json]
[maestro
[http :as http]
[tyrant :refer :all]]
[midje.sweet :refer :all])
(:import clojure.lang.ExceptionInfo))
(fact "that getting application properties does the right thing"
(application-properties "environment" "application" "hash")
=> ..properties..
(provided
(http/simple-get
"-properties"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..properties..}))
(fact "that getting application properties which fails throws an exception"
(application-properties "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-properties"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting application properties which fails with a 500 throws an exception"
(application-properties "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-properties"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting application config does the right thing"
(application-config "environment" "application" "hash")
=> ..config..
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..config..}))
(fact "that getting application config which fails throws an exception"
(application-config "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting a non-existent application config returns nil"
(application-config "environment" "application" "hash")
=> nil
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 404}))
(fact "that getting application config which fails with a 500 throws an exception"
(application-config "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting deployment params does the right thing"
(deployment-params "environment" "application" "hash")
=> ..properties..
(provided
(http/simple-get
"-params"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..properties..}))
(fact "that getting deployment params which fails throws an exception"
(deployment-params "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-params"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting deployment params which fails with a 500 throws an exception"
(deployment-params "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-params"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting launch data does the right thing"
(launch-data "environment" "application" "hash")
=> ..properties..
(provided
(http/simple-get
"-data"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..properties..}))
(fact "that getting launch data which fails throws an exception"
(launch-data "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-data"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting launch data which fails with a 500 throws an exception"
(launch-data "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-data"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting commits does the right thing"
(commits "environment" "application")
=> ..commits..
(provided
(http/simple-get
""
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:commits ..commits..}))
(fact "that getting the last commit gives back the first item in the commits response"
(last-commit-hash "environment" "application")
=> "last-commit"
(provided
(http/simple-get
""
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:commits [{:hash "last-commit"}
{:hash "b-commit"}
{:hash "a-commit"}]}))
(fact "that verifying a hash works when the commit list contains that hash"
(verify-commit-hash "environment" "application" "hash") => true
(provided
(commits "environment" "application") => [{:hash "not the hash"} {:hash "hash"}]))
(fact "that verifying a hash works when the commit doesn't contain that hash"
(verify-commit-hash "environment" "application" "hash") => false
(provided
(commits "environment" "application") => [{:hash "not the hash"}]))
(fact "that verifying a hash and getting an error throws an exception"
(verify-commit-hash "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get "" {:socket-timeout 30000}) => {:status 500}))
(fact "that creating an application does the right thing"
(create-application "application")
=> ..application..
(provided
(json/generate-string {:name "application"})
=> ..application-body..
(http/simple-post
""
{:content-type :json
:body ..application-body..
:socket-timeout 180000})
=> {:status 201
:body ..body..}
(json/parse-string ..body.. true)
=> ..application..))
(fact "that creating an application throws an exception when given an unexpected response"
(create-application "application")
=> (throws ExceptionInfo "Unexpected response")
(provided
(json/generate-string {:name "application"})
=> ..application-body..
(http/simple-post
""
{:content-type :json
:body ..application-body..
:socket-timeout 180000})
=> {:status 500}))
(fact "that getting an application does the right thing"
(application "application")
=> ..application..
(provided
(http/simple-get ""
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:applications {:application ..application..}}))
(fact "that getting an unexpected response when getting an application is an error"
(application "application")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get ""
{:socket-timeout 30000})
=> {:status 500}))
(fact "that upserting an application creates the application if it doesn't exist"
(upsert-application "application")
=> ..application..
(provided
(application "application")
=> nil
(create-application "application")
=> ..application..))
(fact "that upserting an application does not create the application if it exists"
(upsert-application "application")
=> ..application..
(provided
(application "application")
=> ..application..))
| null | https://raw.githubusercontent.com/neilprosser/mr-maestro/469790fd712262016729c1d83d4b4e11869237a2/test/maestro/tyrant_test.clj | clojure | (ns maestro.tyrant-test
(:require [cheshire.core :as json]
[maestro
[http :as http]
[tyrant :refer :all]]
[midje.sweet :refer :all])
(:import clojure.lang.ExceptionInfo))
(fact "that getting application properties does the right thing"
(application-properties "environment" "application" "hash")
=> ..properties..
(provided
(http/simple-get
"-properties"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..properties..}))
(fact "that getting application properties which fails throws an exception"
(application-properties "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-properties"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting application properties which fails with a 500 throws an exception"
(application-properties "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-properties"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting application config does the right thing"
(application-config "environment" "application" "hash")
=> ..config..
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..config..}))
(fact "that getting application config which fails throws an exception"
(application-config "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting a non-existent application config returns nil"
(application-config "environment" "application" "hash")
=> nil
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 404}))
(fact "that getting application config which fails with a 500 throws an exception"
(application-config "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-config"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting deployment params does the right thing"
(deployment-params "environment" "application" "hash")
=> ..properties..
(provided
(http/simple-get
"-params"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..properties..}))
(fact "that getting deployment params which fails throws an exception"
(deployment-params "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-params"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting deployment params which fails with a 500 throws an exception"
(deployment-params "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-params"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting launch data does the right thing"
(launch-data "environment" "application" "hash")
=> ..properties..
(provided
(http/simple-get
"-data"
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:data ..properties..}))
(fact "that getting launch data which fails throws an exception"
(launch-data "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get
"-data"
{:socket-timeout 30000})
=> {:status 503}))
(fact "that getting launch data which fails with a 500 throws an exception"
(launch-data "environment" "application" "hash")
=> (throws ExceptionInfo "Error retrieving file content - is the JSON valid?")
(provided
(http/simple-get
"-data"
{:socket-timeout 30000})
=> {:status 500}))
(fact "that getting commits does the right thing"
(commits "environment" "application")
=> ..commits..
(provided
(http/simple-get
""
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:commits ..commits..}))
(fact "that getting the last commit gives back the first item in the commits response"
(last-commit-hash "environment" "application")
=> "last-commit"
(provided
(http/simple-get
""
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:commits [{:hash "last-commit"}
{:hash "b-commit"}
{:hash "a-commit"}]}))
(fact "that verifying a hash works when the commit list contains that hash"
(verify-commit-hash "environment" "application" "hash") => true
(provided
(commits "environment" "application") => [{:hash "not the hash"} {:hash "hash"}]))
(fact "that verifying a hash works when the commit doesn't contain that hash"
(verify-commit-hash "environment" "application" "hash") => false
(provided
(commits "environment" "application") => [{:hash "not the hash"}]))
(fact "that verifying a hash and getting an error throws an exception"
(verify-commit-hash "environment" "application" "hash")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get "" {:socket-timeout 30000}) => {:status 500}))
(fact "that creating an application does the right thing"
(create-application "application")
=> ..application..
(provided
(json/generate-string {:name "application"})
=> ..application-body..
(http/simple-post
""
{:content-type :json
:body ..application-body..
:socket-timeout 180000})
=> {:status 201
:body ..body..}
(json/parse-string ..body.. true)
=> ..application..))
(fact "that creating an application throws an exception when given an unexpected response"
(create-application "application")
=> (throws ExceptionInfo "Unexpected response")
(provided
(json/generate-string {:name "application"})
=> ..application-body..
(http/simple-post
""
{:content-type :json
:body ..application-body..
:socket-timeout 180000})
=> {:status 500}))
(fact "that getting an application does the right thing"
(application "application")
=> ..application..
(provided
(http/simple-get ""
{:socket-timeout 30000})
=> {:status 200
:body ..body..}
(json/parse-string ..body.. true)
=> {:applications {:application ..application..}}))
(fact "that getting an unexpected response when getting an application is an error"
(application "application")
=> (throws ExceptionInfo "Unexpected response")
(provided
(http/simple-get ""
{:socket-timeout 30000})
=> {:status 500}))
(fact "that upserting an application creates the application if it doesn't exist"
(upsert-application "application")
=> ..application..
(provided
(application "application")
=> nil
(create-application "application")
=> ..application..))
(fact "that upserting an application does not create the application if it exists"
(upsert-application "application")
=> ..application..
(provided
(application "application")
=> ..application..))
| |
19f03f08f47b02f585d759e00b1e2f99e962da56b604d4b4ceaee264bfc12341 | microsoft/SLAyer | HeapGraph.ml | Copyright ( c ) Microsoft Corporation . All rights reserved .
(** Graph representation of pointer structure of symbolic heaps *)
open Library
open Variable
open Expression
module E = Exp
module S = Substitution
open SymbolicHeap
module L = (val Log.std Config.vHG : Log.LOG)
(* Timing =================================================================== *)
let add_with_closure_tmr = Timer.create "HeapGraph.add_with_closure"
(*============================================================================
Heap Graphs
============================================================================*)
(** "Lifted" value expressions. *)
module LE = struct
type t = E.t option
let fv eo = Option.option Vars.empty E.fv eo
let map_exps s eo = Option.map s eo
let fold_exps fn eo z = Option.option z (fun e -> E.fold fn e z) eo
let equal = Option.equal E.equal
let compare = Option.compare E.compare
let fmtp fxt ff eo = Option.fmt "-" (E.fmtp fxt) ff eo
let fmt ff eo = fmtp (Vars.empty,Vars.empty) ff eo
let fmt_caml ff eo =
Option.fmt "None" (fun ff -> Format.fprintf ff "Some(%a)" E.fmt_caml) ff eo
end
module Edge = struct
include BiEdge.Make (LE)
let fmt ff e = Format.fprintf ff "@[(%a)@]" fmt e
let meet x y =
greatest lower bound in the lattice where Undef < Some < None
let meet_ lx ly =
match lx, ly with
| None , None -> None
| None , Some _ -> ly
| Some _, None -> lx
| Some _, Some _ when LE.equal lx ly -> lx
| Some _, Some _ -> raise Undef
in
try map2 meet_ x y
with Invalid_argument _ -> raise Undef
let drop none x = map (Option.optionk none id) x
let append_unchecked = append
let append edg edg' =
let are_adjacent =
try
(* only the common meeting point must be present *)
let btwn = drop (fun () -> raise Undef) (Args.between edg edg') in
Args.fold_links (fun (a,d) so_far -> so_far && E.equal a d) btwn true
with Undef -> false
in
if are_adjacent
then Some (append edg edg')
else None
let to_ls pat edg =
(* L.incf 0 "( to_ls: %a %a" Patn.fmt pat fmt edg ; *)
(* L.decf 0 ") to_ls: %a" SH.fmt <& *)
let none () = E.mkVar (Var.gensym "drop" Var.PointerSort) in
let ls = {Ls.
pat= pat;
len= E.mkVar (Var.gensym "len" Var.IntegerSort);
arg= drop none edg
} in
SH.LsS.star [ls] SH.emp
let fmt ff edg = Format.fprintf ff "@[(%a)@]" fmt edg
end
module EdgeSet = Set.Make(Edge)
let fmt ff pg =
Format.fprintf ff "@[<hov 1>[%a]@]"
(List.fmt ";@ " Edge.fmt) (EdgeSet.to_list pg)
let add_with_closure edg g =
Timer.start add_with_closure_tmr ;
(fun _ -> Timer.stop add_with_closure_tmr)
<&
let hds =
EdgeSet.fold (fun g_edg h ->
match Edge.append g_edg edg with
| None -> h
| Some(g_edg_edg) -> EdgeSet.add g_edg_edg h
) g EdgeSet.empty
in
let tls =
EdgeSet.fold (fun g_edg h ->
match Edge.append edg g_edg with
| None -> h
| Some(edg_g_edg) -> EdgeSet.add edg_g_edg h
) g EdgeSet.empty
in
let spn =
EdgeSet.fold_product (fun hd_edg tl_edg h ->
(* Note: It shouldn't be necessary to call append_unchecked here,
something is wrong with Args.adjacent and normalization. *)
EdgeSet.add (Edge.append_unchecked hd_edg tl_edg) h
) hds tls EdgeSet.empty
in
EdgeSet.union spn (EdgeSet.union tls (EdgeSet.union hds (EdgeSet.add edg g)))
(** [union_with_closure g g'] is the transitive closure of [g] union [g'],
assuming [g'] is closed. *)
let union_with_closure g g' = EdgeSet.fold add_with_closure g g'
let transitive_closure g = union_with_closure g EdgeSet.empty
include EdgeSet
| null | https://raw.githubusercontent.com/microsoft/SLAyer/6f46f6999c18f415bc368b43b5ba3eb54f0b1c04/src/HeapGraph.ml | ocaml | * Graph representation of pointer structure of symbolic heaps
Timing ===================================================================
============================================================================
Heap Graphs
============================================================================
* "Lifted" value expressions.
only the common meeting point must be present
L.incf 0 "( to_ls: %a %a" Patn.fmt pat fmt edg ;
L.decf 0 ") to_ls: %a" SH.fmt <&
Note: It shouldn't be necessary to call append_unchecked here,
something is wrong with Args.adjacent and normalization.
* [union_with_closure g g'] is the transitive closure of [g] union [g'],
assuming [g'] is closed. | Copyright ( c ) Microsoft Corporation . All rights reserved .
open Library
open Variable
open Expression
module E = Exp
module S = Substitution
open SymbolicHeap
module L = (val Log.std Config.vHG : Log.LOG)
let add_with_closure_tmr = Timer.create "HeapGraph.add_with_closure"
module LE = struct
type t = E.t option
let fv eo = Option.option Vars.empty E.fv eo
let map_exps s eo = Option.map s eo
let fold_exps fn eo z = Option.option z (fun e -> E.fold fn e z) eo
let equal = Option.equal E.equal
let compare = Option.compare E.compare
let fmtp fxt ff eo = Option.fmt "-" (E.fmtp fxt) ff eo
let fmt ff eo = fmtp (Vars.empty,Vars.empty) ff eo
let fmt_caml ff eo =
Option.fmt "None" (fun ff -> Format.fprintf ff "Some(%a)" E.fmt_caml) ff eo
end
module Edge = struct
include BiEdge.Make (LE)
let fmt ff e = Format.fprintf ff "@[(%a)@]" fmt e
let meet x y =
greatest lower bound in the lattice where Undef < Some < None
let meet_ lx ly =
match lx, ly with
| None , None -> None
| None , Some _ -> ly
| Some _, None -> lx
| Some _, Some _ when LE.equal lx ly -> lx
| Some _, Some _ -> raise Undef
in
try map2 meet_ x y
with Invalid_argument _ -> raise Undef
let drop none x = map (Option.optionk none id) x
let append_unchecked = append
let append edg edg' =
let are_adjacent =
try
let btwn = drop (fun () -> raise Undef) (Args.between edg edg') in
Args.fold_links (fun (a,d) so_far -> so_far && E.equal a d) btwn true
with Undef -> false
in
if are_adjacent
then Some (append edg edg')
else None
let to_ls pat edg =
let none () = E.mkVar (Var.gensym "drop" Var.PointerSort) in
let ls = {Ls.
pat= pat;
len= E.mkVar (Var.gensym "len" Var.IntegerSort);
arg= drop none edg
} in
SH.LsS.star [ls] SH.emp
let fmt ff edg = Format.fprintf ff "@[(%a)@]" fmt edg
end
module EdgeSet = Set.Make(Edge)
let fmt ff pg =
Format.fprintf ff "@[<hov 1>[%a]@]"
(List.fmt ";@ " Edge.fmt) (EdgeSet.to_list pg)
let add_with_closure edg g =
Timer.start add_with_closure_tmr ;
(fun _ -> Timer.stop add_with_closure_tmr)
<&
let hds =
EdgeSet.fold (fun g_edg h ->
match Edge.append g_edg edg with
| None -> h
| Some(g_edg_edg) -> EdgeSet.add g_edg_edg h
) g EdgeSet.empty
in
let tls =
EdgeSet.fold (fun g_edg h ->
match Edge.append edg g_edg with
| None -> h
| Some(edg_g_edg) -> EdgeSet.add edg_g_edg h
) g EdgeSet.empty
in
let spn =
EdgeSet.fold_product (fun hd_edg tl_edg h ->
EdgeSet.add (Edge.append_unchecked hd_edg tl_edg) h
) hds tls EdgeSet.empty
in
EdgeSet.union spn (EdgeSet.union tls (EdgeSet.union hds (EdgeSet.add edg g)))
let union_with_closure g g' = EdgeSet.fold add_with_closure g g'
let transitive_closure g = union_with_closure g EdgeSet.empty
include EdgeSet
|
e1df70965a99dda4fb43e571512aa7825eaef90c986c31895f22150e1664908a | greghendershott/markdown | entity.rkt | Copyright ( c ) 2013 - 2022 by .
SPDX - License - Identifier : BSD-2 - Clause
#lang racket/base
(require "parsack.rkt")
(provide $entity)
(define $char-entity/dec
(try (pdo (x <- (many1 $digit))
(char #\;)
(return (string->number (list->string x) 10)))))
(define $char-entity/hex
(try (pdo (<or> (char #\x)
(char #\X))
(x <- (many1 $hexDigit))
(char #\;)
(return (string->number (list->string x) 16)))))
(define $char-entity
(try (>> (char #\#)
(<or> $char-entity/dec
$char-entity/hex))))
(define $sym-entity
(try (pdo (x <- (many1 (<or> $letter $digit)))
(char #\;)
(return (string->symbol (list->string x))))))
(define $not-entity
not ' amp -- act like
(define $entity
(>> (char #\&)
(<or> $char-entity
$sym-entity
$not-entity)))
| null | https://raw.githubusercontent.com/greghendershott/markdown/34ada7458fad51d3a5e0516352f8bd399c517140/markdown/entity.rkt | racket | )
)
) | Copyright ( c ) 2013 - 2022 by .
SPDX - License - Identifier : BSD-2 - Clause
#lang racket/base
(require "parsack.rkt")
(provide $entity)
(define $char-entity/dec
(try (pdo (x <- (many1 $digit))
(return (string->number (list->string x) 10)))))
(define $char-entity/hex
(try (pdo (<or> (char #\x)
(char #\X))
(x <- (many1 $hexDigit))
(return (string->number (list->string x) 16)))))
(define $char-entity
(try (>> (char #\#)
(<or> $char-entity/dec
$char-entity/hex))))
(define $sym-entity
(try (pdo (x <- (many1 (<or> $letter $digit)))
(return (string->symbol (list->string x))))))
(define $not-entity
not ' amp -- act like
(define $entity
(>> (char #\&)
(<or> $char-entity
$sym-entity
$not-entity)))
|
881d33bd7ce6d69f762d55bf5b6573816d471dbaf2fb015a5c3f0a17e38f4a73 | ocaml/ocamlbuild | exit_codes.ml | (***********************************************************************)
(* *)
(* ocamlbuild *)
(* *)
, , projet Gallium , INRIA Rocquencourt
(* *)
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
let rc_ok = 0
let rc_usage = 1
let rc_failure = 2
let rc_invalid_argument = 3
let rc_system_error = 4
let rc_hygiene = 1
let rc_circularity = 5
let rc_solver_failed = 6
let rc_ocamldep_error = 7
let rc_lexing_error = 8
let rc_build_error = 9
let rc_executor_subcommand_failed = 10
let rc_executor_subcommand_got_signal = 11
let rc_executor_io_error = 12
let rc_executor_excetptional_condition = 13
| null | https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/src/exit_codes.ml | ocaml | *********************************************************************
ocamlbuild
the special exception on linking described in file ../LICENSE.
********************************************************************* | , , projet Gallium , INRIA Rocquencourt
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
let rc_ok = 0
let rc_usage = 1
let rc_failure = 2
let rc_invalid_argument = 3
let rc_system_error = 4
let rc_hygiene = 1
let rc_circularity = 5
let rc_solver_failed = 6
let rc_ocamldep_error = 7
let rc_lexing_error = 8
let rc_build_error = 9
let rc_executor_subcommand_failed = 10
let rc_executor_subcommand_got_signal = 11
let rc_executor_io_error = 12
let rc_executor_excetptional_condition = 13
|
5ec4e8059ba76561069363780b2bb164f7c3fae7d7aa7be81cac67f989dab6f4 | tokenrove/m68k-assembler | utils.lisp | (in-package :m68k-assembler)
;;;; STRINGS
(defun munge-modifier (string)
"Chops off the period-delimited extension of STRING, and returns the
new string without the extension as well as the extension, or NIL if
such an extension could not be found."
(let ((modifier nil))
(awhen (position #\. string :from-end t)
(setf modifier (subseq string (1+ it)))
(setf string (subseq string 0 it)))
(values string modifier)))
;;;; LISTS
(defun carat (x)
"If X is a cons, return the car of it. Otherwise, return X."
(if (consp x) (car x) x))
(defun tree-find-if (predicate tree)
(redirect-find-if (lambda (x) (tree-find-if predicate x))
#'consp predicate tree))
(defun redirect-find-if (redirect-fn redirect-predicate predicate tree)
(dolist (x tree)
(if (funcall redirect-predicate x)
(awhen (funcall redirect-fn x) (return it))
(when (funcall predicate x) (return x)))))
;;;; BINARY DATA, STREAMS
(defun bit-vector->int (vector)
"Converts a bit-vector to an integer, assuming that array indices
correspond to bit places in the integer. (For example, index 0 in
VECTOR corresponds to the least-significant bit of the return value.)"
(do ((value 0 (+ (ash value 1) (aref vector i)))
(i (1- (length vector)) (1- i)))
((< i 0) value)))
XXX probably totally fucked in this modern world of Unicode .
(defun string->int (string)
"Converts a string to an integer, assuming that character elements
correspond to bytes, that they are limited in range from 0 to 255, and
that they are stored from greatest value to least (big-endian)."
(do ((value 0 (+ (ash value 8) (char-code (char string i))))
(i 0 (1+ i)))
((>= i (length string)) value)))
(defun read-big-endian-data (stream length)
"Read LENGTH bits of data encoded big-endian from STREAM, returning
an integer. LENGTH must be a multiple of 8."
(assert (zerop (logand length 7)))
(do ((pos (- length 8) (- pos 8))
(value (read-byte stream) (logior (read-byte stream)
(ash value 8))))
((<= pos 0) value)))
(defun write-big-endian-data (stream data length)
"Write LENGTH bits of the integer DATA to STREAM, in big-endian
order. LENGTH must be a multiple of 8."
(assert (zerop (logand length 7)))
(do ((pos (- length 8) (- pos 8)))
((< pos 0))
(write-byte (ldb (byte 8 pos) data) stream)))
(defun copy-stream-contents (source destination
&key (element-type 'unsigned-byte))
"Copy all data from open stream SOURCE to open stream DESTINATION.
SOURCE is positioned at its beginning, and read until it reaches the
end of file."
(file-position source 0)
(let ((buffer (make-array '(4096) :element-type element-type)))
(do ((bytes #1=(read-sequence buffer source) #1#))
((= bytes 0))
(write-sequence buffer destination :end bytes))))
| null | https://raw.githubusercontent.com/tokenrove/m68k-assembler/6c3bc3e62da890bb34da856c8c72a6a7d1650eaa/utils.lisp | lisp | STRINGS
LISTS
BINARY DATA, STREAMS | (in-package :m68k-assembler)
(defun munge-modifier (string)
"Chops off the period-delimited extension of STRING, and returns the
new string without the extension as well as the extension, or NIL if
such an extension could not be found."
(let ((modifier nil))
(awhen (position #\. string :from-end t)
(setf modifier (subseq string (1+ it)))
(setf string (subseq string 0 it)))
(values string modifier)))
(defun carat (x)
"If X is a cons, return the car of it. Otherwise, return X."
(if (consp x) (car x) x))
(defun tree-find-if (predicate tree)
(redirect-find-if (lambda (x) (tree-find-if predicate x))
#'consp predicate tree))
(defun redirect-find-if (redirect-fn redirect-predicate predicate tree)
(dolist (x tree)
(if (funcall redirect-predicate x)
(awhen (funcall redirect-fn x) (return it))
(when (funcall predicate x) (return x)))))
(defun bit-vector->int (vector)
"Converts a bit-vector to an integer, assuming that array indices
correspond to bit places in the integer. (For example, index 0 in
VECTOR corresponds to the least-significant bit of the return value.)"
(do ((value 0 (+ (ash value 1) (aref vector i)))
(i (1- (length vector)) (1- i)))
((< i 0) value)))
XXX probably totally fucked in this modern world of Unicode .
(defun string->int (string)
"Converts a string to an integer, assuming that character elements
correspond to bytes, that they are limited in range from 0 to 255, and
that they are stored from greatest value to least (big-endian)."
(do ((value 0 (+ (ash value 8) (char-code (char string i))))
(i 0 (1+ i)))
((>= i (length string)) value)))
(defun read-big-endian-data (stream length)
"Read LENGTH bits of data encoded big-endian from STREAM, returning
an integer. LENGTH must be a multiple of 8."
(assert (zerop (logand length 7)))
(do ((pos (- length 8) (- pos 8))
(value (read-byte stream) (logior (read-byte stream)
(ash value 8))))
((<= pos 0) value)))
(defun write-big-endian-data (stream data length)
"Write LENGTH bits of the integer DATA to STREAM, in big-endian
order. LENGTH must be a multiple of 8."
(assert (zerop (logand length 7)))
(do ((pos (- length 8) (- pos 8)))
((< pos 0))
(write-byte (ldb (byte 8 pos) data) stream)))
(defun copy-stream-contents (source destination
&key (element-type 'unsigned-byte))
"Copy all data from open stream SOURCE to open stream DESTINATION.
SOURCE is positioned at its beginning, and read until it reaches the
end of file."
(file-position source 0)
(let ((buffer (make-array '(4096) :element-type element-type)))
(do ((bytes #1=(read-sequence buffer source) #1#))
((= bytes 0))
(write-sequence buffer destination :end bytes))))
|
12c7ee4c36a415476618dc5d2dd6b063267d7563e6a9331e1724e8abb200106c | kwantam/lviv | lviv.scm | #!/usr/bin/env gsi-script
;
Copyright ( c ) 2011 < >
;
;Permission is hereby granted, free of charge, to any person obtaining a copy
;of this software and associated documentation files (the "Software"), to deal
;in the Software without restriction, including without limitation the rights
;to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
;furnished to do so, subject to the following conditions:
;
;The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
;FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
;OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;THE SOFTWARE.
;
;
(include "lviv-misc.scm")
(include "lviv-state.scm")
(include "lviv-stack.scm")
(include "lviv-env.scm")
(include "lviv-specforms.scm")
(include "lviv-exceptions.scm")
(include "lviv-symbols.scm")
(include "lviv-funcalls.scm")
(include "lviv-repl.scm")
(include "lviv-prelude.scm")
(include "lviv-tests.scm")
; go through each arg in the arglist
; - means run a repl
;
(define (lviv-process-args arglist)
(cond ((null? arglist) #f)
((equal? "-" (car arglist))
(lviv-repl lvivState '())
(lviv-process-args (cdr arglist)))
(else
(lviv-file lvivState (car arglist))
(lviv-process-args (cdr arglist)))))
; decide how to proceed based on commandline
; if a -- is supplied, ignore all args before it
; otherwise, attempt to open and eval all args
other than the 0th
; this mimics the difference between script mode
and batch mode in gsi
(let ((c--line (member "--" (command-line)))
(c1line (cdr (command-line))))
(cond ((null? c1line) ; no arguments at all
(display "welcome to lviv\n\n")
(lviv-repl lvivState '()))
((not c--line) ; didn't find -- delimiter
(lviv-process-args c1line))
((null? (cdr c--line)) ; found --, if it's last arg just do repl
(display "welcome to lviv\n\n")
(lviv-repl lvivState '()))
; otherwise process args after --
(else
(lviv-process-args (cdr c--line)))))
; print the stack before we exit
(define (main . _) #f)
| null | https://raw.githubusercontent.com/kwantam/lviv/bbfda50a4801f92b79631f77e7fa997dc10f0516/src/lviv.scm | scheme |
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
go through each arg in the arglist
- means run a repl
decide how to proceed based on commandline
if a -- is supplied, ignore all args before it
otherwise, attempt to open and eval all args
this mimics the difference between script mode
no arguments at all
didn't find -- delimiter
found --, if it's last arg just do repl
otherwise process args after --
print the stack before we exit | #!/usr/bin/env gsi-script
Copyright ( c ) 2011 < >
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
(include "lviv-misc.scm")
(include "lviv-state.scm")
(include "lviv-stack.scm")
(include "lviv-env.scm")
(include "lviv-specforms.scm")
(include "lviv-exceptions.scm")
(include "lviv-symbols.scm")
(include "lviv-funcalls.scm")
(include "lviv-repl.scm")
(include "lviv-prelude.scm")
(include "lviv-tests.scm")
(define (lviv-process-args arglist)
(cond ((null? arglist) #f)
((equal? "-" (car arglist))
(lviv-repl lvivState '())
(lviv-process-args (cdr arglist)))
(else
(lviv-file lvivState (car arglist))
(lviv-process-args (cdr arglist)))))
other than the 0th
and batch mode in gsi
(let ((c--line (member "--" (command-line)))
(c1line (cdr (command-line))))
(display "welcome to lviv\n\n")
(lviv-repl lvivState '()))
(lviv-process-args c1line))
(display "welcome to lviv\n\n")
(lviv-repl lvivState '()))
(else
(lviv-process-args (cdr c--line)))))
(define (main . _) #f)
|
a096e76bddcd3b8e74c9fb2b6829a1f26f51548483a2378321096818ae1d869b | LPCIC/matita | renderingAttrs.ml | Copyright ( C ) 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
$ I d : renderingAttrs.ml 5881 2006 - 01 - 20 12:47:16Z asperti $
type xml_attribute = string option * string * string
type markup = [ `MathML | `BoxML ]
let color1 = "blue"
(* let color2 = "red" *)
let color2 = "blue"
let keyword_attributes = function
| `MathML -> [ None, "mathcolor", color1 ]
| `BoxML -> [ None, "color", color1 ]
let builtin_symbol_attributes = function
| `MathML -> [ None, "mathcolor", color1 ]
| `BoxML -> [ None, "color", color1 ]
let object_keyword_attributes = function
| `MathML -> [ None, "mathcolor", color2 ]
| `BoxML -> [ None, "color", color2 ]
let symbol_attributes _ = []
let ident_attributes _ = []
let number_attributes _ = []
let spacing_attributes _ = [ None, "spacing", "0.5em" ]
let indent_attributes _ = [ None, "indent", "0.5em" ]
let small_skip_attributes _ = [ None, "width", "0.5em" ]
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content_pres/renderingAttrs.ml | ocaml | let color2 = "red" | Copyright ( C ) 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
$ I d : renderingAttrs.ml 5881 2006 - 01 - 20 12:47:16Z asperti $
type xml_attribute = string option * string * string
type markup = [ `MathML | `BoxML ]
let color1 = "blue"
let color2 = "blue"
let keyword_attributes = function
| `MathML -> [ None, "mathcolor", color1 ]
| `BoxML -> [ None, "color", color1 ]
let builtin_symbol_attributes = function
| `MathML -> [ None, "mathcolor", color1 ]
| `BoxML -> [ None, "color", color1 ]
let object_keyword_attributes = function
| `MathML -> [ None, "mathcolor", color2 ]
| `BoxML -> [ None, "color", color2 ]
let symbol_attributes _ = []
let ident_attributes _ = []
let number_attributes _ = []
let spacing_attributes _ = [ None, "spacing", "0.5em" ]
let indent_attributes _ = [ None, "indent", "0.5em" ]
let small_skip_attributes _ = [ None, "width", "0.5em" ]
|
4678b008342d8066ac63857adb7bbee86adb03283c69233b88d0065ebf0f8bf5 | haskell-works/hw-dsv | Space.hs | module Main where
import Data.ByteString (ByteString)
import Data.Vector (Vector)
import HaskellWorks.Data.Dsv.Internal.Char (comma)
import Weigh
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Csv as CSV
import qualified Data.Csv.Streaming as CSS
import qualified Data.Foldable as F
import qualified Data.Vector as DV
import qualified HaskellWorks.Data.Dsv.Lazy.Cursor as SVL
import qualified HaskellWorks.Data.Dsv.Lazy.Cursor.Lazy as SVLL
import qualified HaskellWorks.Data.Dsv.Strict.Cursor as SVS
HLINT ignore " Redundant do "
repeatedly :: (a -> Maybe a) -> a -> [a]
repeatedly f a = a:case f a of
Just b -> repeatedly f b
Nothing -> []
loadCsvStrict :: FilePath -> IO (DV.Vector (DV.Vector ByteString))
loadCsvStrict filePath = do
c <- SVS.mmapCursor comma False filePath
return $ SVS.toVectorVector c
loadCsvLazy :: FilePath -> IO [DV.Vector LBS.ByteString]
loadCsvLazy filePath = do
bs <- LBS.readFile filePath
let c = SVL.makeCursor comma bs
return $ SVLL.toListVector c
main :: IO ()
main = do
let infp = "data/bench/data-0001000.csv"
mainWith $ do
setColumns [Case, Allocated, Max, Live, GCs]
sequence_
[ action "cassava strict" $ do
r <- fmap (CSV.decode CSV.HasHeader) (LBS.readFile infp) :: IO (Either String (Vector (Vector ByteString)))
case r of
Left _ -> error "Unexpected parse error"
Right v -> pure v
, action "cassava streaming" $ do
fmap (F.toList . CSS.decode CSS.HasHeader) (LBS.readFile infp) :: IO [Vector ByteString]
, action "hw-dsv strict" (loadCsvStrict infp :: IO (Vector (Vector ByteString)))
, action "hw-dsv lazy" (loadCsvLazy infp :: IO [Vector LBS.ByteString])
]
return ()
| null | https://raw.githubusercontent.com/haskell-works/hw-dsv/4f1274af383281589165232186f99219479d7898/weigh/Space.hs | haskell | module Main where
import Data.ByteString (ByteString)
import Data.Vector (Vector)
import HaskellWorks.Data.Dsv.Internal.Char (comma)
import Weigh
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Csv as CSV
import qualified Data.Csv.Streaming as CSS
import qualified Data.Foldable as F
import qualified Data.Vector as DV
import qualified HaskellWorks.Data.Dsv.Lazy.Cursor as SVL
import qualified HaskellWorks.Data.Dsv.Lazy.Cursor.Lazy as SVLL
import qualified HaskellWorks.Data.Dsv.Strict.Cursor as SVS
HLINT ignore " Redundant do "
repeatedly :: (a -> Maybe a) -> a -> [a]
repeatedly f a = a:case f a of
Just b -> repeatedly f b
Nothing -> []
loadCsvStrict :: FilePath -> IO (DV.Vector (DV.Vector ByteString))
loadCsvStrict filePath = do
c <- SVS.mmapCursor comma False filePath
return $ SVS.toVectorVector c
loadCsvLazy :: FilePath -> IO [DV.Vector LBS.ByteString]
loadCsvLazy filePath = do
bs <- LBS.readFile filePath
let c = SVL.makeCursor comma bs
return $ SVLL.toListVector c
main :: IO ()
main = do
let infp = "data/bench/data-0001000.csv"
mainWith $ do
setColumns [Case, Allocated, Max, Live, GCs]
sequence_
[ action "cassava strict" $ do
r <- fmap (CSV.decode CSV.HasHeader) (LBS.readFile infp) :: IO (Either String (Vector (Vector ByteString)))
case r of
Left _ -> error "Unexpected parse error"
Right v -> pure v
, action "cassava streaming" $ do
fmap (F.toList . CSS.decode CSS.HasHeader) (LBS.readFile infp) :: IO [Vector ByteString]
, action "hw-dsv strict" (loadCsvStrict infp :: IO (Vector (Vector ByteString)))
, action "hw-dsv lazy" (loadCsvLazy infp :: IO [Vector LBS.ByteString])
]
return ()
| |
554602944873b08eec04ffe76ab79b5d4609f75394490c124397426a9b0d3e44 | nvim-treesitter/nvim-treesitter | folds.scm | [
(element)
(style_element)
(script_element)
] @fold
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/ddc0f1b606472b6a1ab85ee9becfd4877507627d/queries/html/folds.scm | scheme | [
(element)
(style_element)
(script_element)
] @fold
| |
456e62dbb5728efff26bba8f8a7add14a772ae84d50a5ae1ec76b9aba92ab45d | footprintanalytics/footprint-web | execute.clj | (ns metabase.driver.googleanalytics.execute
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.tools.reader.edn :as edn]
[java-time :as t]
[metabase.driver.googleanalytics.metadata :as ga.metadata]
[metabase.models :refer [Database]]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.date-2.common :as u.date.common]
[metabase.util.date-2.parse :as u.date.parse]
[metabase.util.date-2.parse.builder :as u.date.builder]
[toucan.db :as db])
(:import [com.google.api.services.analytics.model Column GaData GaData$ColumnHeaders]
java.time.DayOfWeek
java.time.format.DateTimeFormatter
org.threeten.extra.YearWeek))
(defn- column-with-name ^Column [database-or-id column-name]
(some (fn [^Column column]
(when (= (.getId column) (name column-name))
column))
(ga.metadata/columns (db/select-one Database :id (u/the-id database-or-id)) {:status "PUBLIC"})))
(defn- column-metadata [database-id column-name]
(when-let [ga-column (column-with-name database-id column-name)]
(merge
{:display_name (ga.metadata/column-attribute ga-column :uiName)
:description (ga.metadata/column-attribute ga-column :description)}
(let [data-type (ga.metadata/column-attribute ga-column :dataType)]
(when-let [base-type (cond
(= column-name "ga:date") :type/Date
(= data-type "INTEGER") :type/Integer
(= data-type "STRING") :type/Text)]
{:base_type base-type})))))
memoize this because the display names and other info is n't going to change and fetching this info from GA can take
around half a second
(def ^:private ^{:arglists '([database-id column-name])} memoized-column-metadata
(memoize column-metadata))
(defn- add-col-metadata [{database-id :database} col]
(let [{:keys [base_type] :as metadata} (merge col (memoized-column-metadata (u/the-id database-id) (:name col)))]
(cond-> metadata
(and base_type (not (:effective_type metadata)))
(assoc :effective_type base_type))))
(def ^:const ga-type->base-type
"Map of Google Analytics field types to Metabase types."
{"STRING" :type/Text
"FLOAT" :type/Float
"INTEGER" :type/Integer
"PERCENT" :type/Float
"TIME" :type/Float
"CURRENCY" :type/Float
"US_CURRENCY" :type/Float})
(defn- parse-number [s]
(edn/read-string (str/replace s #"^0+(.+)$" "$1")))
(def ^:private ^DateTimeFormatter iso-year-week-formatter
(u.date.builder/formatter
(u.date.builder/value :iso/week-based-year 4)
(u.date.builder/value :iso/week-of-week-based-year 2)))
(defn- parse-iso-year-week [^String s]
(when s
(-> (YearWeek/from (.parse iso-year-week-formatter s))
(.atDay DayOfWeek/MONDAY))))
(def ^:private ^DateTimeFormatter year-week-formatter
(u.date.builder/formatter
(u.date.builder/value :week-fields/week-based-year 4)
(u.date.builder/value :week-fields/week-of-week-based-year 2)))
(defn- parse-year-week [^String s]
(when s
(let [parsed (.parse year-week-formatter s)
year (.getLong parsed (u.date.common/temporal-field :week-fields/week-based-year))
week (.getLong parsed (u.date.common/temporal-field :week-fields/week-of-week-based-year))]
(t/adjust (t/local-date year 1 1) (u.date/adjuster :week-of-year week)))))
(def ^:private ^DateTimeFormatter year-month-formatter
(u.date.builder/formatter
(u.date.builder/value :year 4)
(u.date.builder/value :month-of-year 2)
(u.date.builder/default-value :day-of-month 1)))
(def ^:private ga-dimension->formatter
{"ga:date" "yyyyMMdd"
"ga:dateHour" "yyyyMMddHH"
"ga:dateHourMinute" "yyyyMMddHHmm"
"ga:day" parse-number
"ga:dayOfWeek" (comp inc parse-number)
"ga:hour" parse-number
"ga:isoYearIsoWeek" parse-iso-year-week
"ga:minute" parse-number
"ga:month" parse-number
"ga:week" parse-number
"ga:year" parse-number
"ga:yearMonth" year-month-formatter
"ga:yearWeek" parse-year-week})
(defn- header->column [^GaData$ColumnHeaders header]
(let [formatter (ga-dimension->formatter (.getName header))]
(if formatter
{:name "ga:date"
:base_type :type/DateTime}
{:name (.getName header)
:base_type (ga-type->base-type (.getDataType header))})))
(defn- header->getter-fn [^GaData$ColumnHeaders header]
(let [formatter (ga-dimension->formatter (.getName header))
base-type (ga-type->base-type (.getDataType header))
parser (cond
formatter formatter
(isa? base-type :type/Number) edn/read-string
:else identity)]
(log/tracef "Parsing result column %s with %s" (.getName header) (pr-str parser))
(if (or (string? parser) (instance? DateTimeFormatter parser))
(partial u.date.parse/parse-with-formatter parser)
parser)))
(defn execute-reducible-query
"Execute a `query` using the provided `do-query` function, and return the results in the usual format."
[execute* query respond]
(let [^GaData response (execute* query)
headers (.getColumnHeaders response)
columns (map header->column headers)
getters (map header->getter-fn headers)]
(respond
{:cols (for [col columns]
(add-col-metadata query col))}
(for [row (.getRows response)]
(for [[data getter] (map vector row getters)]
(getter data))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/modules/drivers/googleanalytics/src/metabase/driver/googleanalytics/execute.clj | clojure | (ns metabase.driver.googleanalytics.execute
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.tools.reader.edn :as edn]
[java-time :as t]
[metabase.driver.googleanalytics.metadata :as ga.metadata]
[metabase.models :refer [Database]]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.date-2.common :as u.date.common]
[metabase.util.date-2.parse :as u.date.parse]
[metabase.util.date-2.parse.builder :as u.date.builder]
[toucan.db :as db])
(:import [com.google.api.services.analytics.model Column GaData GaData$ColumnHeaders]
java.time.DayOfWeek
java.time.format.DateTimeFormatter
org.threeten.extra.YearWeek))
(defn- column-with-name ^Column [database-or-id column-name]
(some (fn [^Column column]
(when (= (.getId column) (name column-name))
column))
(ga.metadata/columns (db/select-one Database :id (u/the-id database-or-id)) {:status "PUBLIC"})))
(defn- column-metadata [database-id column-name]
(when-let [ga-column (column-with-name database-id column-name)]
(merge
{:display_name (ga.metadata/column-attribute ga-column :uiName)
:description (ga.metadata/column-attribute ga-column :description)}
(let [data-type (ga.metadata/column-attribute ga-column :dataType)]
(when-let [base-type (cond
(= column-name "ga:date") :type/Date
(= data-type "INTEGER") :type/Integer
(= data-type "STRING") :type/Text)]
{:base_type base-type})))))
memoize this because the display names and other info is n't going to change and fetching this info from GA can take
around half a second
(def ^:private ^{:arglists '([database-id column-name])} memoized-column-metadata
(memoize column-metadata))
(defn- add-col-metadata [{database-id :database} col]
(let [{:keys [base_type] :as metadata} (merge col (memoized-column-metadata (u/the-id database-id) (:name col)))]
(cond-> metadata
(and base_type (not (:effective_type metadata)))
(assoc :effective_type base_type))))
(def ^:const ga-type->base-type
"Map of Google Analytics field types to Metabase types."
{"STRING" :type/Text
"FLOAT" :type/Float
"INTEGER" :type/Integer
"PERCENT" :type/Float
"TIME" :type/Float
"CURRENCY" :type/Float
"US_CURRENCY" :type/Float})
(defn- parse-number [s]
(edn/read-string (str/replace s #"^0+(.+)$" "$1")))
(def ^:private ^DateTimeFormatter iso-year-week-formatter
(u.date.builder/formatter
(u.date.builder/value :iso/week-based-year 4)
(u.date.builder/value :iso/week-of-week-based-year 2)))
(defn- parse-iso-year-week [^String s]
(when s
(-> (YearWeek/from (.parse iso-year-week-formatter s))
(.atDay DayOfWeek/MONDAY))))
(def ^:private ^DateTimeFormatter year-week-formatter
(u.date.builder/formatter
(u.date.builder/value :week-fields/week-based-year 4)
(u.date.builder/value :week-fields/week-of-week-based-year 2)))
(defn- parse-year-week [^String s]
(when s
(let [parsed (.parse year-week-formatter s)
year (.getLong parsed (u.date.common/temporal-field :week-fields/week-based-year))
week (.getLong parsed (u.date.common/temporal-field :week-fields/week-of-week-based-year))]
(t/adjust (t/local-date year 1 1) (u.date/adjuster :week-of-year week)))))
(def ^:private ^DateTimeFormatter year-month-formatter
(u.date.builder/formatter
(u.date.builder/value :year 4)
(u.date.builder/value :month-of-year 2)
(u.date.builder/default-value :day-of-month 1)))
(def ^:private ga-dimension->formatter
{"ga:date" "yyyyMMdd"
"ga:dateHour" "yyyyMMddHH"
"ga:dateHourMinute" "yyyyMMddHHmm"
"ga:day" parse-number
"ga:dayOfWeek" (comp inc parse-number)
"ga:hour" parse-number
"ga:isoYearIsoWeek" parse-iso-year-week
"ga:minute" parse-number
"ga:month" parse-number
"ga:week" parse-number
"ga:year" parse-number
"ga:yearMonth" year-month-formatter
"ga:yearWeek" parse-year-week})
(defn- header->column [^GaData$ColumnHeaders header]
(let [formatter (ga-dimension->formatter (.getName header))]
(if formatter
{:name "ga:date"
:base_type :type/DateTime}
{:name (.getName header)
:base_type (ga-type->base-type (.getDataType header))})))
(defn- header->getter-fn [^GaData$ColumnHeaders header]
(let [formatter (ga-dimension->formatter (.getName header))
base-type (ga-type->base-type (.getDataType header))
parser (cond
formatter formatter
(isa? base-type :type/Number) edn/read-string
:else identity)]
(log/tracef "Parsing result column %s with %s" (.getName header) (pr-str parser))
(if (or (string? parser) (instance? DateTimeFormatter parser))
(partial u.date.parse/parse-with-formatter parser)
parser)))
(defn execute-reducible-query
"Execute a `query` using the provided `do-query` function, and return the results in the usual format."
[execute* query respond]
(let [^GaData response (execute* query)
headers (.getColumnHeaders response)
columns (map header->column headers)
getters (map header->getter-fn headers)]
(respond
{:cols (for [col columns]
(add-col-metadata query col))}
(for [row (.getRows response)]
(for [[data getter] (map vector row getters)]
(getter data))))))
| |
1318a413c7575475c70097cbbd10d67cbc8fba479a24a6d928130b9d184d634c | gnarroway/mongo-driver-3 | model_test.clj | (ns mongo-driver-3.model-test
(:require [clojure.test :refer :all]
[mongo-driver-3.model :as m])
(:import (com.mongodb ReadConcern ReadPreference WriteConcern)
(java.util.concurrent TimeUnit)
(com.mongodb.client.model InsertOneOptions InsertManyOptions DeleteOptions FindOneAndUpdateOptions ReturnDocument FindOneAndReplaceOptions CountOptions UpdateOptions ReplaceOptions IndexOptions CreateCollectionOptions RenameCollectionOptions BulkWriteOptions DeleteManyModel DeleteOneModel InsertOneModel ReplaceOneModel UpdateManyModel UpdateOneModel)))
;;; Unit
(deftest test->ReadConcern
(is (nil? (m/->ReadConcern {})))
(is (thrown? IllegalArgumentException (m/->ReadConcern {:read-concern "invalid"})))
(is (instance? ReadConcern (m/->ReadConcern {:read-concern :available}))))
(deftest test->ReadPreference
(is (nil? (m/->ReadPreference {})))
(is (thrown? IllegalArgumentException (m/->ReadPreference {:read-preference "invalid"})))
(is (instance? ReadPreference (m/->ReadPreference {:read-preference :primary}))))
(deftest test->WriteConcern
(is (= (WriteConcern/W1) (m/->WriteConcern {:write-concern :w1})) "accepts kw")
(is (= (WriteConcern/W1) (m/->WriteConcern {:write-concern (WriteConcern/W1)})) "accepts WriteConcern")
(is (= (WriteConcern/ACKNOWLEDGED) (m/->WriteConcern {:write-concern "invalid"})) "defaults to acknowledged")
(is (= 1 (.getW (m/->WriteConcern {:write-concern/w 1}))) "set w")
(is (= 2 (.getW (m/->WriteConcern {:write-concern (WriteConcern/W2)}))))
(is (= 1 (.getW (m/->WriteConcern {:write-concern (WriteConcern/W2) :write-concern/w 1}))) "prefer granular option")
(is (true? (.getJournal (m/->WriteConcern {:write-concern/journal? true}))) "can set journal")
(is (= 77 (.getWTimeout (m/->WriteConcern {:write-concern/w-timeout-ms 77}) (TimeUnit/MILLISECONDS))) "can set timeout"))
(deftest test->InsertOneOptions
(is (instance? InsertOneOptions (m/->InsertOneOptions {})))
(is (true? (.getBypassDocumentValidation (m/->InsertOneOptions {:bypass-document-validation? true}))))
(is (true? (.getBypassDocumentValidation (m/->InsertOneOptions
{:insert-one-options (.bypassDocumentValidation (InsertOneOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->InsertOneOptions
{:insert-one-options (.bypassDocumentValidation (InsertOneOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->ReplaceOptions
(is (instance? ReplaceOptions (m/->ReplaceOptions {})))
(are [expected arg]
(= expected (.isUpsert (m/->ReplaceOptions {:upsert? arg})))
true true
false false
false nil)
(is (true? (.getBypassDocumentValidation (m/->ReplaceOptions {:bypass-document-validation? true}))))
(is (true? (.getBypassDocumentValidation (m/->ReplaceOptions
{:replace-options (.bypassDocumentValidation (ReplaceOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->ReplaceOptions
{:replace-options (.bypassDocumentValidation (ReplaceOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->UpdateOptions
(is (instance? UpdateOptions (m/->UpdateOptions {})))
(are [expected arg]
(= expected (.isUpsert (m/->UpdateOptions {:upsert? arg})))
true true
false false
false nil)
(is (true? (.getBypassDocumentValidation (m/->UpdateOptions {:bypass-document-validation? true}))))
(is (true? (.getBypassDocumentValidation (m/->UpdateOptions
{:update-options (.bypassDocumentValidation (UpdateOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->UpdateOptions
{:update-options (.bypassDocumentValidation (UpdateOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->InsertManyOptions
(is (instance? InsertManyOptions (m/->InsertManyOptions {})))
(are [expected arg]
(= expected (.getBypassDocumentValidation (m/->InsertManyOptions {:bypass-document-validation? arg})))
true true
false false
nil nil)
(are [expected arg]
(= expected (.isOrdered (m/->InsertManyOptions {:ordered? arg})))
true true
false false
true nil)
(is (true? (.getBypassDocumentValidation (m/->InsertManyOptions
{:insert-many-options (.bypassDocumentValidation (InsertManyOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->InsertManyOptions
{:insert-many-options (.bypassDocumentValidation (InsertManyOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->DeleteOptions
(is (instance? DeleteOptions (m/->DeleteOptions {})))
(let [opts (DeleteOptions.)]
(is (= opts (m/->DeleteOptions {:delete-options opts})) "configure directly")))
(deftest test->RenameCollectionOptions
(is (instance? RenameCollectionOptions (m/->RenameCollectionOptions {})))
(are [expected arg]
(= expected (.isDropTarget (m/->RenameCollectionOptions {:drop-target? arg})))
true true
false false
false nil)
(let [opts (RenameCollectionOptions.)]
(is (= opts (m/->RenameCollectionOptions {:rename-collection-options opts})) "configure directly")))
(deftest test->FindOneAndUpdateOptions
(is (instance? FindOneAndUpdateOptions (m/->FindOneAndUpdateOptions {})))
(let [opts (FindOneAndUpdateOptions.)]
(is (= opts (m/->FindOneAndUpdateOptions {:find-one-and-update-options opts})) "configure directly"))
(are [expected arg]
(= expected (.isUpsert (m/->FindOneAndUpdateOptions {:upsert? arg})))
true true
false false
false nil)
(are [expected arg]
(= expected (.getReturnDocument (m/->FindOneAndUpdateOptions {:return-new? arg})))
(ReturnDocument/AFTER) true
(ReturnDocument/BEFORE) false
(ReturnDocument/BEFORE) nil)
(is (= {"_id" 1} (.getSort (m/->FindOneAndUpdateOptions {:sort {:_id 1}}))))
(is (= {"_id" 1} (.getProjection (m/->FindOneAndUpdateOptions {:projection {:_id 1}})))))
(deftest test->FindOneAndReplaceOptions
(is (instance? FindOneAndReplaceOptions (m/->FindOneAndReplaceOptions {})))
(let [opts (FindOneAndReplaceOptions.)]
(is (= opts (m/->FindOneAndReplaceOptions {:find-one-and-replace-options opts})) "configure directly"))
(are [expected arg]
(= expected (.isUpsert (m/->FindOneAndReplaceOptions {:upsert? arg})))
true true
false false
false nil)
(are [expected arg]
(= expected (.getReturnDocument (m/->FindOneAndReplaceOptions {:return-new? arg})))
(ReturnDocument/AFTER) true
(ReturnDocument/BEFORE) false
(ReturnDocument/BEFORE) nil)
(is (= {"_id" 1} (.getSort (m/->FindOneAndReplaceOptions {:sort {:_id 1}}))))
(is (= {"_id" 1} (.getProjection (m/->FindOneAndReplaceOptions {:projection {:_id 1}})))))
(deftest test->CountOptions
(is (instance? CountOptions (m/->CountOptions {})))
(let [opts (CountOptions.)]
(is (= opts (m/->CountOptions {:count-options opts})) "configure directly"))
(is (= {"a" 1} (.getHint (m/->CountOptions {:hint {:a 1}}))))
(is (= 7 (.getLimit (m/->CountOptions {:limit 7}))))
(is (= 2 (.getSkip (m/->CountOptions {:skip 2}))))
(is (= 42 (.getMaxTime (m/->CountOptions {:max-time-ms 42}) (TimeUnit/MILLISECONDS)))))
(deftest test->IndexOptions
(is (instance? IndexOptions (m/->IndexOptions {})))
(are [expected arg]
(= expected (.isSparse (m/->IndexOptions {:sparse? arg})))
true true
false false
false nil)
(are [expected arg]
(= expected (.isUnique (m/->IndexOptions {:unique? arg})))
true true
false false
false nil)
(let [opts (IndexOptions.)]
(is (= opts (m/->IndexOptions {:index-options opts})) "configure directly")))
(deftest test->CreateCollectionOptions
(are [expected arg]
(= expected (.isCapped (m/->CreateCollectionOptions {:capped? arg})))
true true
false false
false nil)
(is (= 7 (.getMaxDocuments (m/->CreateCollectionOptions {:max-documents 7}))))
(is (= 42 (.getSizeInBytes (m/->CreateCollectionOptions {:max-size-bytes 42}))))
(let [opts (-> (CreateCollectionOptions.) (.maxDocuments 5))]
(is (= opts (m/->CreateCollectionOptions {:create-collection-options opts})) "configure directly")
(is (= 5 (.getMaxDocuments (m/->CreateCollectionOptions {:create-collection-options opts}))))
(is (= 7 (.getMaxDocuments (m/->CreateCollectionOptions {:create-collection-options opts :max-documents 7})))
"can override")))
(deftest test->BulkWriteOptions
(is (instance? BulkWriteOptions (m/->BulkWriteOptions {})))
(are [expected arg]
(= expected (.getBypassDocumentValidation (m/->BulkWriteOptions {:bypass-document-validation? arg})))
true true
false false
nil nil)
(are [expected arg]
(= expected (.isOrdered (m/->BulkWriteOptions {:ordered? arg})))
true true
false false
true nil)
(is (true? (.getBypassDocumentValidation (m/->BulkWriteOptions
{:bulk-write-options (.bypassDocumentValidation (BulkWriteOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->BulkWriteOptions
{:bulk-write-options (.bypassDocumentValidation (BulkWriteOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test-write-model
(testing "delete many"
(is (instance? DeleteManyModel (m/write-model [:delete-many {:filter {:a "b"}}]))))
(testing "delete one"
(is (instance? DeleteOneModel (m/write-model [:delete-one {:filter {:a "b"}}]))))
(testing "insert one"
(is (instance? InsertOneModel (m/write-model [:insert-one {:document {:a "b"}}]))))
(testing "replace one"
(is (instance? ReplaceOneModel (m/write-model [:replace-one {:filter {:a "b"} :replacement {:a "c"}}])))
(are [expected arg]
(= expected (.isUpsert (.getReplaceOptions (m/write-model [:replace-one {:filter {:a "b"} :replacement {:a "c"} :upsert? arg}]))))
true true
false false
false nil))
(testing "update many"
(is (instance? UpdateManyModel (m/write-model [:update-many {:filter {:a "b"} :update {"$set" {:a "c"}}}])))
(are [expected arg]
(= expected (.isUpsert (.getOptions ^UpdateManyModel (m/write-model [:update-many {:filter {:a "b"} :update {"$set" {:a "c"}} :upsert? arg}]))))
true true
false false
false nil))
(testing "update one"
(is (instance? UpdateOneModel (m/write-model [:update-one {:filter {:a "b"} :update {"$set" {:a "c"}}}])))
(are [expected arg]
(= expected (.isUpsert (.getOptions (m/write-model [:update-one {:filter {:a "b"} :update {"$set" {:a "c"}} :upsert? arg}]))))
true true
false false
false nil)))
| null | https://raw.githubusercontent.com/gnarroway/mongo-driver-3/c46e114f44038b9fb65e2a92b2d2062e76636e09/test/mongo_driver_3/model_test.clj | clojure | Unit | (ns mongo-driver-3.model-test
(:require [clojure.test :refer :all]
[mongo-driver-3.model :as m])
(:import (com.mongodb ReadConcern ReadPreference WriteConcern)
(java.util.concurrent TimeUnit)
(com.mongodb.client.model InsertOneOptions InsertManyOptions DeleteOptions FindOneAndUpdateOptions ReturnDocument FindOneAndReplaceOptions CountOptions UpdateOptions ReplaceOptions IndexOptions CreateCollectionOptions RenameCollectionOptions BulkWriteOptions DeleteManyModel DeleteOneModel InsertOneModel ReplaceOneModel UpdateManyModel UpdateOneModel)))
(deftest test->ReadConcern
(is (nil? (m/->ReadConcern {})))
(is (thrown? IllegalArgumentException (m/->ReadConcern {:read-concern "invalid"})))
(is (instance? ReadConcern (m/->ReadConcern {:read-concern :available}))))
(deftest test->ReadPreference
(is (nil? (m/->ReadPreference {})))
(is (thrown? IllegalArgumentException (m/->ReadPreference {:read-preference "invalid"})))
(is (instance? ReadPreference (m/->ReadPreference {:read-preference :primary}))))
(deftest test->WriteConcern
(is (= (WriteConcern/W1) (m/->WriteConcern {:write-concern :w1})) "accepts kw")
(is (= (WriteConcern/W1) (m/->WriteConcern {:write-concern (WriteConcern/W1)})) "accepts WriteConcern")
(is (= (WriteConcern/ACKNOWLEDGED) (m/->WriteConcern {:write-concern "invalid"})) "defaults to acknowledged")
(is (= 1 (.getW (m/->WriteConcern {:write-concern/w 1}))) "set w")
(is (= 2 (.getW (m/->WriteConcern {:write-concern (WriteConcern/W2)}))))
(is (= 1 (.getW (m/->WriteConcern {:write-concern (WriteConcern/W2) :write-concern/w 1}))) "prefer granular option")
(is (true? (.getJournal (m/->WriteConcern {:write-concern/journal? true}))) "can set journal")
(is (= 77 (.getWTimeout (m/->WriteConcern {:write-concern/w-timeout-ms 77}) (TimeUnit/MILLISECONDS))) "can set timeout"))
(deftest test->InsertOneOptions
(is (instance? InsertOneOptions (m/->InsertOneOptions {})))
(is (true? (.getBypassDocumentValidation (m/->InsertOneOptions {:bypass-document-validation? true}))))
(is (true? (.getBypassDocumentValidation (m/->InsertOneOptions
{:insert-one-options (.bypassDocumentValidation (InsertOneOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->InsertOneOptions
{:insert-one-options (.bypassDocumentValidation (InsertOneOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->ReplaceOptions
(is (instance? ReplaceOptions (m/->ReplaceOptions {})))
(are [expected arg]
(= expected (.isUpsert (m/->ReplaceOptions {:upsert? arg})))
true true
false false
false nil)
(is (true? (.getBypassDocumentValidation (m/->ReplaceOptions {:bypass-document-validation? true}))))
(is (true? (.getBypassDocumentValidation (m/->ReplaceOptions
{:replace-options (.bypassDocumentValidation (ReplaceOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->ReplaceOptions
{:replace-options (.bypassDocumentValidation (ReplaceOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->UpdateOptions
(is (instance? UpdateOptions (m/->UpdateOptions {})))
(are [expected arg]
(= expected (.isUpsert (m/->UpdateOptions {:upsert? arg})))
true true
false false
false nil)
(is (true? (.getBypassDocumentValidation (m/->UpdateOptions {:bypass-document-validation? true}))))
(is (true? (.getBypassDocumentValidation (m/->UpdateOptions
{:update-options (.bypassDocumentValidation (UpdateOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->UpdateOptions
{:update-options (.bypassDocumentValidation (UpdateOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->InsertManyOptions
(is (instance? InsertManyOptions (m/->InsertManyOptions {})))
(are [expected arg]
(= expected (.getBypassDocumentValidation (m/->InsertManyOptions {:bypass-document-validation? arg})))
true true
false false
nil nil)
(are [expected arg]
(= expected (.isOrdered (m/->InsertManyOptions {:ordered? arg})))
true true
false false
true nil)
(is (true? (.getBypassDocumentValidation (m/->InsertManyOptions
{:insert-many-options (.bypassDocumentValidation (InsertManyOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->InsertManyOptions
{:insert-many-options (.bypassDocumentValidation (InsertManyOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test->DeleteOptions
(is (instance? DeleteOptions (m/->DeleteOptions {})))
(let [opts (DeleteOptions.)]
(is (= opts (m/->DeleteOptions {:delete-options opts})) "configure directly")))
(deftest test->RenameCollectionOptions
(is (instance? RenameCollectionOptions (m/->RenameCollectionOptions {})))
(are [expected arg]
(= expected (.isDropTarget (m/->RenameCollectionOptions {:drop-target? arg})))
true true
false false
false nil)
(let [opts (RenameCollectionOptions.)]
(is (= opts (m/->RenameCollectionOptions {:rename-collection-options opts})) "configure directly")))
(deftest test->FindOneAndUpdateOptions
(is (instance? FindOneAndUpdateOptions (m/->FindOneAndUpdateOptions {})))
(let [opts (FindOneAndUpdateOptions.)]
(is (= opts (m/->FindOneAndUpdateOptions {:find-one-and-update-options opts})) "configure directly"))
(are [expected arg]
(= expected (.isUpsert (m/->FindOneAndUpdateOptions {:upsert? arg})))
true true
false false
false nil)
(are [expected arg]
(= expected (.getReturnDocument (m/->FindOneAndUpdateOptions {:return-new? arg})))
(ReturnDocument/AFTER) true
(ReturnDocument/BEFORE) false
(ReturnDocument/BEFORE) nil)
(is (= {"_id" 1} (.getSort (m/->FindOneAndUpdateOptions {:sort {:_id 1}}))))
(is (= {"_id" 1} (.getProjection (m/->FindOneAndUpdateOptions {:projection {:_id 1}})))))
(deftest test->FindOneAndReplaceOptions
(is (instance? FindOneAndReplaceOptions (m/->FindOneAndReplaceOptions {})))
(let [opts (FindOneAndReplaceOptions.)]
(is (= opts (m/->FindOneAndReplaceOptions {:find-one-and-replace-options opts})) "configure directly"))
(are [expected arg]
(= expected (.isUpsert (m/->FindOneAndReplaceOptions {:upsert? arg})))
true true
false false
false nil)
(are [expected arg]
(= expected (.getReturnDocument (m/->FindOneAndReplaceOptions {:return-new? arg})))
(ReturnDocument/AFTER) true
(ReturnDocument/BEFORE) false
(ReturnDocument/BEFORE) nil)
(is (= {"_id" 1} (.getSort (m/->FindOneAndReplaceOptions {:sort {:_id 1}}))))
(is (= {"_id" 1} (.getProjection (m/->FindOneAndReplaceOptions {:projection {:_id 1}})))))
(deftest test->CountOptions
(is (instance? CountOptions (m/->CountOptions {})))
(let [opts (CountOptions.)]
(is (= opts (m/->CountOptions {:count-options opts})) "configure directly"))
(is (= {"a" 1} (.getHint (m/->CountOptions {:hint {:a 1}}))))
(is (= 7 (.getLimit (m/->CountOptions {:limit 7}))))
(is (= 2 (.getSkip (m/->CountOptions {:skip 2}))))
(is (= 42 (.getMaxTime (m/->CountOptions {:max-time-ms 42}) (TimeUnit/MILLISECONDS)))))
(deftest test->IndexOptions
(is (instance? IndexOptions (m/->IndexOptions {})))
(are [expected arg]
(= expected (.isSparse (m/->IndexOptions {:sparse? arg})))
true true
false false
false nil)
(are [expected arg]
(= expected (.isUnique (m/->IndexOptions {:unique? arg})))
true true
false false
false nil)
(let [opts (IndexOptions.)]
(is (= opts (m/->IndexOptions {:index-options opts})) "configure directly")))
(deftest test->CreateCollectionOptions
(are [expected arg]
(= expected (.isCapped (m/->CreateCollectionOptions {:capped? arg})))
true true
false false
false nil)
(is (= 7 (.getMaxDocuments (m/->CreateCollectionOptions {:max-documents 7}))))
(is (= 42 (.getSizeInBytes (m/->CreateCollectionOptions {:max-size-bytes 42}))))
(let [opts (-> (CreateCollectionOptions.) (.maxDocuments 5))]
(is (= opts (m/->CreateCollectionOptions {:create-collection-options opts})) "configure directly")
(is (= 5 (.getMaxDocuments (m/->CreateCollectionOptions {:create-collection-options opts}))))
(is (= 7 (.getMaxDocuments (m/->CreateCollectionOptions {:create-collection-options opts :max-documents 7})))
"can override")))
(deftest test->BulkWriteOptions
(is (instance? BulkWriteOptions (m/->BulkWriteOptions {})))
(are [expected arg]
(= expected (.getBypassDocumentValidation (m/->BulkWriteOptions {:bypass-document-validation? arg})))
true true
false false
nil nil)
(are [expected arg]
(= expected (.isOrdered (m/->BulkWriteOptions {:ordered? arg})))
true true
false false
true nil)
(is (true? (.getBypassDocumentValidation (m/->BulkWriteOptions
{:bulk-write-options (.bypassDocumentValidation (BulkWriteOptions.) true)})))
"configure directly")
(is (false? (.getBypassDocumentValidation (m/->BulkWriteOptions
{:bulk-write-options (.bypassDocumentValidation (BulkWriteOptions.) true)
:bypass-document-validation? false})))
"can override"))
(deftest test-write-model
(testing "delete many"
(is (instance? DeleteManyModel (m/write-model [:delete-many {:filter {:a "b"}}]))))
(testing "delete one"
(is (instance? DeleteOneModel (m/write-model [:delete-one {:filter {:a "b"}}]))))
(testing "insert one"
(is (instance? InsertOneModel (m/write-model [:insert-one {:document {:a "b"}}]))))
(testing "replace one"
(is (instance? ReplaceOneModel (m/write-model [:replace-one {:filter {:a "b"} :replacement {:a "c"}}])))
(are [expected arg]
(= expected (.isUpsert (.getReplaceOptions (m/write-model [:replace-one {:filter {:a "b"} :replacement {:a "c"} :upsert? arg}]))))
true true
false false
false nil))
(testing "update many"
(is (instance? UpdateManyModel (m/write-model [:update-many {:filter {:a "b"} :update {"$set" {:a "c"}}}])))
(are [expected arg]
(= expected (.isUpsert (.getOptions ^UpdateManyModel (m/write-model [:update-many {:filter {:a "b"} :update {"$set" {:a "c"}} :upsert? arg}]))))
true true
false false
false nil))
(testing "update one"
(is (instance? UpdateOneModel (m/write-model [:update-one {:filter {:a "b"} :update {"$set" {:a "c"}}}])))
(are [expected arg]
(= expected (.isUpsert (.getOptions (m/write-model [:update-one {:filter {:a "b"} :update {"$set" {:a "c"}} :upsert? arg}]))))
true true
false false
false nil)))
|
6b511a7ca7b0e6dde937be5fa7a8a2cc8cadd3342d82d9c7486261b3cbde0412 | brendanhay/amazonka | DeleteResourcePolicy.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
Module : Amazonka . . DeleteResourcePolicy
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Deletes a resource policy from the target Amazon Web Services account .
module Amazonka.XRay.DeleteResourcePolicy
( -- * Creating a Request
DeleteResourcePolicy (..),
newDeleteResourcePolicy,
-- * Request Lenses
deleteResourcePolicy_policyRevisionId,
deleteResourcePolicy_policyName,
-- * Destructuring the Response
DeleteResourcePolicyResponse (..),
newDeleteResourcePolicyResponse,
-- * Response Lenses
deleteResourcePolicyResponse_httpStatus,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.XRay.Types
-- | /See:/ 'newDeleteResourcePolicy' smart constructor.
data DeleteResourcePolicy = DeleteResourcePolicy'
{ -- | Specifies a specific policy revision to delete. Provide a
-- @PolicyRevisionId@ to ensure an atomic delete operation. If the provided
-- revision id does not match the latest policy revision id, an
-- @InvalidPolicyRevisionIdException@ exception is returned.
policyRevisionId :: Prelude.Maybe Prelude.Text,
-- | The name of the resource policy to delete.
policyName :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
Create a value of ' DeleteResourcePolicy ' with all optional fields omitted .
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
-- 'policyRevisionId', 'deleteResourcePolicy_policyRevisionId' - Specifies a specific policy revision to delete. Provide a
-- @PolicyRevisionId@ to ensure an atomic delete operation. If the provided
-- revision id does not match the latest policy revision id, an
-- @InvalidPolicyRevisionIdException@ exception is returned.
--
-- 'policyName', 'deleteResourcePolicy_policyName' - The name of the resource policy to delete.
newDeleteResourcePolicy ::
-- | 'policyName'
Prelude.Text ->
DeleteResourcePolicy
newDeleteResourcePolicy pPolicyName_ =
DeleteResourcePolicy'
{ policyRevisionId =
Prelude.Nothing,
policyName = pPolicyName_
}
-- | Specifies a specific policy revision to delete. Provide a
-- @PolicyRevisionId@ to ensure an atomic delete operation. If the provided
-- revision id does not match the latest policy revision id, an
-- @InvalidPolicyRevisionIdException@ exception is returned.
deleteResourcePolicy_policyRevisionId :: Lens.Lens' DeleteResourcePolicy (Prelude.Maybe Prelude.Text)
deleteResourcePolicy_policyRevisionId = Lens.lens (\DeleteResourcePolicy' {policyRevisionId} -> policyRevisionId) (\s@DeleteResourcePolicy' {} a -> s {policyRevisionId = a} :: DeleteResourcePolicy)
-- | The name of the resource policy to delete.
deleteResourcePolicy_policyName :: Lens.Lens' DeleteResourcePolicy Prelude.Text
deleteResourcePolicy_policyName = Lens.lens (\DeleteResourcePolicy' {policyName} -> policyName) (\s@DeleteResourcePolicy' {} a -> s {policyName = a} :: DeleteResourcePolicy)
instance Core.AWSRequest DeleteResourcePolicy where
type
AWSResponse DeleteResourcePolicy =
DeleteResourcePolicyResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveEmpty
( \s h x ->
DeleteResourcePolicyResponse'
Prelude.<$> (Prelude.pure (Prelude.fromEnum s))
)
instance Prelude.Hashable DeleteResourcePolicy where
hashWithSalt _salt DeleteResourcePolicy' {..} =
_salt `Prelude.hashWithSalt` policyRevisionId
`Prelude.hashWithSalt` policyName
instance Prelude.NFData DeleteResourcePolicy where
rnf DeleteResourcePolicy' {..} =
Prelude.rnf policyRevisionId
`Prelude.seq` Prelude.rnf policyName
instance Data.ToHeaders DeleteResourcePolicy where
toHeaders = Prelude.const Prelude.mempty
instance Data.ToJSON DeleteResourcePolicy where
toJSON DeleteResourcePolicy' {..} =
Data.object
( Prelude.catMaybes
[ ("PolicyRevisionId" Data..=)
Prelude.<$> policyRevisionId,
Prelude.Just ("PolicyName" Data..= policyName)
]
)
instance Data.ToPath DeleteResourcePolicy where
toPath = Prelude.const "/DeleteResourcePolicy"
instance Data.ToQuery DeleteResourcePolicy where
toQuery = Prelude.const Prelude.mempty
-- | /See:/ 'newDeleteResourcePolicyResponse' smart constructor.
data DeleteResourcePolicyResponse = DeleteResourcePolicyResponse'
{ -- | The response's http status code.
httpStatus :: Prelude.Int
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'DeleteResourcePolicyResponse' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
' httpStatus ' , ' deleteResourcePolicyResponse_httpStatus ' - The response 's http status code .
newDeleteResourcePolicyResponse ::
-- | 'httpStatus'
Prelude.Int ->
DeleteResourcePolicyResponse
newDeleteResourcePolicyResponse pHttpStatus_ =
DeleteResourcePolicyResponse'
{ httpStatus =
pHttpStatus_
}
-- | The response's http status code.
deleteResourcePolicyResponse_httpStatus :: Lens.Lens' DeleteResourcePolicyResponse Prelude.Int
deleteResourcePolicyResponse_httpStatus = Lens.lens (\DeleteResourcePolicyResponse' {httpStatus} -> httpStatus) (\s@DeleteResourcePolicyResponse' {} a -> s {httpStatus = a} :: DeleteResourcePolicyResponse)
instance Prelude.NFData DeleteResourcePolicyResponse where
rnf DeleteResourcePolicyResponse' {..} =
Prelude.rnf httpStatus
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-xray/gen/Amazonka/XRay/DeleteResourcePolicy.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Creating a Request
* Request Lenses
* Destructuring the Response
* Response Lenses
| /See:/ 'newDeleteResourcePolicy' smart constructor.
| Specifies a specific policy revision to delete. Provide a
@PolicyRevisionId@ to ensure an atomic delete operation. If the provided
revision id does not match the latest policy revision id, an
@InvalidPolicyRevisionIdException@ exception is returned.
| The name of the resource policy to delete.
|
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'policyRevisionId', 'deleteResourcePolicy_policyRevisionId' - Specifies a specific policy revision to delete. Provide a
@PolicyRevisionId@ to ensure an atomic delete operation. If the provided
revision id does not match the latest policy revision id, an
@InvalidPolicyRevisionIdException@ exception is returned.
'policyName', 'deleteResourcePolicy_policyName' - The name of the resource policy to delete.
| 'policyName'
| Specifies a specific policy revision to delete. Provide a
@PolicyRevisionId@ to ensure an atomic delete operation. If the provided
revision id does not match the latest policy revision id, an
@InvalidPolicyRevisionIdException@ exception is returned.
| The name of the resource policy to delete.
| /See:/ 'newDeleteResourcePolicyResponse' smart constructor.
| The response's http status code.
|
Create a value of 'DeleteResourcePolicyResponse' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
| 'httpStatus'
| The response's http status code. | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Module : Amazonka . . DeleteResourcePolicy
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Deletes a resource policy from the target Amazon Web Services account .
module Amazonka.XRay.DeleteResourcePolicy
DeleteResourcePolicy (..),
newDeleteResourcePolicy,
deleteResourcePolicy_policyRevisionId,
deleteResourcePolicy_policyName,
DeleteResourcePolicyResponse (..),
newDeleteResourcePolicyResponse,
deleteResourcePolicyResponse_httpStatus,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.XRay.Types
data DeleteResourcePolicy = DeleteResourcePolicy'
policyRevisionId :: Prelude.Maybe Prelude.Text,
policyName :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Create a value of ' DeleteResourcePolicy ' with all optional fields omitted .
Use < -lens generic - lens > or < optics > to modify other optional fields .
newDeleteResourcePolicy ::
Prelude.Text ->
DeleteResourcePolicy
newDeleteResourcePolicy pPolicyName_ =
DeleteResourcePolicy'
{ policyRevisionId =
Prelude.Nothing,
policyName = pPolicyName_
}
deleteResourcePolicy_policyRevisionId :: Lens.Lens' DeleteResourcePolicy (Prelude.Maybe Prelude.Text)
deleteResourcePolicy_policyRevisionId = Lens.lens (\DeleteResourcePolicy' {policyRevisionId} -> policyRevisionId) (\s@DeleteResourcePolicy' {} a -> s {policyRevisionId = a} :: DeleteResourcePolicy)
deleteResourcePolicy_policyName :: Lens.Lens' DeleteResourcePolicy Prelude.Text
deleteResourcePolicy_policyName = Lens.lens (\DeleteResourcePolicy' {policyName} -> policyName) (\s@DeleteResourcePolicy' {} a -> s {policyName = a} :: DeleteResourcePolicy)
instance Core.AWSRequest DeleteResourcePolicy where
type
AWSResponse DeleteResourcePolicy =
DeleteResourcePolicyResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveEmpty
( \s h x ->
DeleteResourcePolicyResponse'
Prelude.<$> (Prelude.pure (Prelude.fromEnum s))
)
instance Prelude.Hashable DeleteResourcePolicy where
hashWithSalt _salt DeleteResourcePolicy' {..} =
_salt `Prelude.hashWithSalt` policyRevisionId
`Prelude.hashWithSalt` policyName
instance Prelude.NFData DeleteResourcePolicy where
rnf DeleteResourcePolicy' {..} =
Prelude.rnf policyRevisionId
`Prelude.seq` Prelude.rnf policyName
instance Data.ToHeaders DeleteResourcePolicy where
toHeaders = Prelude.const Prelude.mempty
instance Data.ToJSON DeleteResourcePolicy where
toJSON DeleteResourcePolicy' {..} =
Data.object
( Prelude.catMaybes
[ ("PolicyRevisionId" Data..=)
Prelude.<$> policyRevisionId,
Prelude.Just ("PolicyName" Data..= policyName)
]
)
instance Data.ToPath DeleteResourcePolicy where
toPath = Prelude.const "/DeleteResourcePolicy"
instance Data.ToQuery DeleteResourcePolicy where
toQuery = Prelude.const Prelude.mempty
data DeleteResourcePolicyResponse = DeleteResourcePolicyResponse'
httpStatus :: Prelude.Int
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' httpStatus ' , ' deleteResourcePolicyResponse_httpStatus ' - The response 's http status code .
newDeleteResourcePolicyResponse ::
Prelude.Int ->
DeleteResourcePolicyResponse
newDeleteResourcePolicyResponse pHttpStatus_ =
DeleteResourcePolicyResponse'
{ httpStatus =
pHttpStatus_
}
deleteResourcePolicyResponse_httpStatus :: Lens.Lens' DeleteResourcePolicyResponse Prelude.Int
deleteResourcePolicyResponse_httpStatus = Lens.lens (\DeleteResourcePolicyResponse' {httpStatus} -> httpStatus) (\s@DeleteResourcePolicyResponse' {} a -> s {httpStatus = a} :: DeleteResourcePolicyResponse)
instance Prelude.NFData DeleteResourcePolicyResponse where
rnf DeleteResourcePolicyResponse' {..} =
Prelude.rnf httpStatus
|
f0965be5b495bae86876b4085fe00fc40bfa7cdc730f43becb6955ff460c7709 | np/mbox-tools | mbox-list.hs | # LANGUAGE TemplateHaskell , TypeOperators , Rank2Types #
--------------------------------------------------------------------
-- |
-- Executable : mbox-list
Copyright : ( c ) 2008 , 2009 , 2011
-- License : BSD3
--
Maintainer : < >
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
import Prelude
import Control.Arrow
import Control.Lens
import Codec.Mbox (Mbox(..),Direction(..),parseMboxFiles,mboxMsgBody,opposite)
import Email (readEmail)
import EmailFmt (putEmails,ShowFormat(..),fmtOpt,defaultShowFormat,showFormatsDoc)
import System.Environment (getArgs)
import System.Console.GetOpt
data Settings = Settings { _fmt :: ShowFormat
, _dir :: Direction
, _takeOpt :: Maybe Int
, _dropOpt :: Maybe Int
, _help :: Bool
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
listMbox :: Settings -> [String] -> IO ()
listMbox opts mboxfiles =
mapM_ (putEmails (opts^.fmt) .
map ((readEmail . view mboxMsgBody) &&& id) .
maybe id take (opts^.takeOpt) .
maybe id drop (opts^.dropOpt) .
mboxMessages)
=<< parseMboxFiles (opts^.dir) mboxfiles
defaultSettings :: Settings
defaultSettings = Settings { _fmt = defaultShowFormat
, _dir = Forward
, _takeOpt = Nothing
, _dropOpt = Nothing
, _help = False
}
usage :: String -> a
usage msg = error $ unlines [msg, usageInfo header options, showFormatsDoc]
where header = "Usage: mbox-list [OPTION] <mbox-file>*"
maybeIntArg :: Lens' Settings (Maybe Int) -> ArgDescr (Settings -> Settings)
maybeIntArg l = ReqArg (set l . Just . read) "NUM"
-- Since
-- ∀ k1 k2 Positives, take k1 . drop k2 == drop k2 . take (k2 + k1)
-- one fix an ordering: drop then take.
options :: [OptDescr Flag]
options =
[ fmtOpt usage (set fmt)
, Option "r" ["reverse"] (NoArg (over dir opposite)) "Reverse the mbox order (latest firsts)"
, Option "d" ["drop"] (maybeIntArg dropOpt) "Drop the NUM firsts"
, Option "t" ["take"] (maybeIntArg takeOpt) "Take the NUM firsts (happens after --drop)"
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]
main :: IO ()
main = do
args <- getArgs
let (flags, nonopts, errs) = getOpt Permute options args
let opts = foldr ($) defaultSettings flags
if opts^.help
then usage ""
else
case (nonopts, errs) of
(mboxfiles, []) -> listMbox opts mboxfiles
(_, _) -> usage (concat errs)
| null | https://raw.githubusercontent.com/np/mbox-tools/494848aa730e445d3227b6c57d3351aa8401cf4c/mbox-list.hs | haskell | ------------------------------------------------------------------
|
Executable : mbox-list
License : BSD3
Stability : provisional
Portability:
------------------------------------------------------------------
Since
∀ k1 k2 Positives, take k1 . drop k2 == drop k2 . take (k2 + k1)
one fix an ordering: drop then take. | # LANGUAGE TemplateHaskell , TypeOperators , Rank2Types #
Copyright : ( c ) 2008 , 2009 , 2011
Maintainer : < >
import Prelude
import Control.Arrow
import Control.Lens
import Codec.Mbox (Mbox(..),Direction(..),parseMboxFiles,mboxMsgBody,opposite)
import Email (readEmail)
import EmailFmt (putEmails,ShowFormat(..),fmtOpt,defaultShowFormat,showFormatsDoc)
import System.Environment (getArgs)
import System.Console.GetOpt
data Settings = Settings { _fmt :: ShowFormat
, _dir :: Direction
, _takeOpt :: Maybe Int
, _dropOpt :: Maybe Int
, _help :: Bool
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
listMbox :: Settings -> [String] -> IO ()
listMbox opts mboxfiles =
mapM_ (putEmails (opts^.fmt) .
map ((readEmail . view mboxMsgBody) &&& id) .
maybe id take (opts^.takeOpt) .
maybe id drop (opts^.dropOpt) .
mboxMessages)
=<< parseMboxFiles (opts^.dir) mboxfiles
defaultSettings :: Settings
defaultSettings = Settings { _fmt = defaultShowFormat
, _dir = Forward
, _takeOpt = Nothing
, _dropOpt = Nothing
, _help = False
}
usage :: String -> a
usage msg = error $ unlines [msg, usageInfo header options, showFormatsDoc]
where header = "Usage: mbox-list [OPTION] <mbox-file>*"
maybeIntArg :: Lens' Settings (Maybe Int) -> ArgDescr (Settings -> Settings)
maybeIntArg l = ReqArg (set l . Just . read) "NUM"
options :: [OptDescr Flag]
options =
[ fmtOpt usage (set fmt)
, Option "r" ["reverse"] (NoArg (over dir opposite)) "Reverse the mbox order (latest firsts)"
, Option "d" ["drop"] (maybeIntArg dropOpt) "Drop the NUM firsts"
, Option "t" ["take"] (maybeIntArg takeOpt) "Take the NUM firsts (happens after --drop)"
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]
main :: IO ()
main = do
args <- getArgs
let (flags, nonopts, errs) = getOpt Permute options args
let opts = foldr ($) defaultSettings flags
if opts^.help
then usage ""
else
case (nonopts, errs) of
(mboxfiles, []) -> listMbox opts mboxfiles
(_, _) -> usage (concat errs)
|
880e229c854ffbaf18d02dc7b0c9ee0cdc59d34f2f957be8d9c395955be4f09a | timgilbert/haunting-refrain-posh | runner.cljs | (ns haunting-refrain.runner
(:require [doo.runner :refer-macros [doo-tests doo-all-tests]]
haunting-refrain.core-test
haunting-refrain.test.foursquare
haunting-refrain.test.playlist))
(doo-tests 'haunting-refrain.core-test
'haunting-refrain.test.foursquare
'haunting-refrain.test.playlist)
| null | https://raw.githubusercontent.com/timgilbert/haunting-refrain-posh/99a7daafe54c5905a3d1b0eff691b5c602ad6d8d/test/cljs/haunting_refrain/runner.cljs | clojure | (ns haunting-refrain.runner
(:require [doo.runner :refer-macros [doo-tests doo-all-tests]]
haunting-refrain.core-test
haunting-refrain.test.foursquare
haunting-refrain.test.playlist))
(doo-tests 'haunting-refrain.core-test
'haunting-refrain.test.foursquare
'haunting-refrain.test.playlist)
| |
58f69638418a3b429de783d8cc9455be571cb6af6e35ae70a77828f9aa164811 | awakesecurity/spectacle | Ref.hs | {-# OPTIONS_HADDOCK show-extensions #-}
-- |
Module : Control . . Ref
Copyright : ( c ) Arista Networks , 2022 - 2023
License : Apache License 2.0 , see LICENSE
--
-- Stability : stable
Portability : non - portable ( GHC extensions )
--
State implemented over ' IORef ' .
--
-- @since 1.0.0
module Control.Monad.Ref
( -- * RefM Transformer
RefM (RefM),
unRefM,
-- ** Lowering
runRefM,
execRefM,
)
where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State (MonadState, get, put)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
-- ---------------------------------------------------------------------------------------------------------------------
-- | 'RefM' is an impure state monad transformer built around IORef.
--
-- In situations where the state @s@ is a large structure which undergoes frequent alteration, 'RefM' can be used as a
-- more preformant alternative to state (assuming its impurity is not a concern).
--
-- @since 1.0.0
newtype RefM s m a = RefM
{ -- | Acquire the underlying @'IORef'@ for a monadic stateful computation.
unRefM :: IORef s -> m a
}
deriving (Functor)
-- | Run an impure reference-using computation, given a state, resulting in the
-- final state and return value.
--
-- @since 1.0.0
runRefM :: MonadIO m => RefM s m a -> s -> m (s, a)
runRefM (RefM k) st = do
ref <- liftIO (newIORef st)
ret <- k ref
st' <- liftIO (readIORef ref)
return (st', ret)
-- | Run an impure reference-using computation, given a state, resulting in the
-- final state.
--
-- @since 1.0.0
execRefM :: MonadIO m => RefM s m a -> s -> m s
execRefM refM st = fst <$> runRefM refM st
-- | @since 1.0.0
instance Applicative m => Applicative (RefM s m) where
pure x = RefM \_ -> pure x
# INLINE pure #
RefM f <*> RefM m = RefM \ref ->
f ref <*> m ref
{-# INLINE (<*>) #-}
-- | @since 1.0.0
instance Monad m => Monad (RefM s m) where
RefM f >>= m = RefM \ref ->
f ref >>= \x -> unRefM (m x) ref
{-# INLINE (>>=) #-}
-- | @since 1.0.0
instance MonadIO m => MonadIO (RefM s m) where
liftIO m = RefM \_ -> liftIO m
# INLINE liftIO #
-- | @since 1.0.0
instance MonadIO m => MonadState s (RefM s m) where
get = RefM (liftIO . readIORef)
{-# INLINE get #-}
put x = RefM \ref -> liftIO (writeIORef ref x)
# INLINE put #
| null | https://raw.githubusercontent.com/awakesecurity/spectacle/430680c28b26dabb50f466948180eb59ba72fc8e/src/Control/Monad/Ref.hs | haskell | # OPTIONS_HADDOCK show-extensions #
|
Stability : stable
@since 1.0.0
* RefM Transformer
** Lowering
---------------------------------------------------------------------------------------------------------------------
| 'RefM' is an impure state monad transformer built around IORef.
In situations where the state @s@ is a large structure which undergoes frequent alteration, 'RefM' can be used as a
more preformant alternative to state (assuming its impurity is not a concern).
@since 1.0.0
| Acquire the underlying @'IORef'@ for a monadic stateful computation.
| Run an impure reference-using computation, given a state, resulting in the
final state and return value.
@since 1.0.0
| Run an impure reference-using computation, given a state, resulting in the
final state.
@since 1.0.0
| @since 1.0.0
# INLINE (<*>) #
| @since 1.0.0
# INLINE (>>=) #
| @since 1.0.0
| @since 1.0.0
# INLINE get # |
Module : Control . . Ref
Copyright : ( c ) Arista Networks , 2022 - 2023
License : Apache License 2.0 , see LICENSE
Portability : non - portable ( GHC extensions )
State implemented over ' IORef ' .
module Control.Monad.Ref
RefM (RefM),
unRefM,
runRefM,
execRefM,
)
where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State (MonadState, get, put)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
newtype RefM s m a = RefM
unRefM :: IORef s -> m a
}
deriving (Functor)
runRefM :: MonadIO m => RefM s m a -> s -> m (s, a)
runRefM (RefM k) st = do
ref <- liftIO (newIORef st)
ret <- k ref
st' <- liftIO (readIORef ref)
return (st', ret)
execRefM :: MonadIO m => RefM s m a -> s -> m s
execRefM refM st = fst <$> runRefM refM st
instance Applicative m => Applicative (RefM s m) where
pure x = RefM \_ -> pure x
# INLINE pure #
RefM f <*> RefM m = RefM \ref ->
f ref <*> m ref
instance Monad m => Monad (RefM s m) where
RefM f >>= m = RefM \ref ->
f ref >>= \x -> unRefM (m x) ref
instance MonadIO m => MonadIO (RefM s m) where
liftIO m = RefM \_ -> liftIO m
# INLINE liftIO #
instance MonadIO m => MonadState s (RefM s m) where
get = RefM (liftIO . readIORef)
put x = RefM \ref -> liftIO (writeIORef ref x)
# INLINE put #
|
43b0cd2a527e30117382ab669f5c3f2b0e06ed21b3feef9a59a207cba1880e85 | ucsd-progsys/nate | help.ml | let text = "\
\032 OCamlBrowser Help\n\
\n\
USE\n\
\n\
\032 OCamlBrowser is composed of three tools, the Editor, which allows\n\
\032 one to edit/typecheck/analyse .mli and .ml files, the Viewer, to\n\
\032 walk around compiled modules, and the Shell, to run an OCaml\n\
\032 subshell. You may only have one instance of Editor and Viewer, but\n\
\032 you may use several subshells.\n\
\n\
\032 As with the compiler, you may specify a different path for the\n\
\032 standard library by setting OCAMLLIB. You may also extend the\n\
\032 initial load path (only standard library by default) by using the\n\
\032 -I command line option. The -nolabels, -rectypes and -w options are\n\
\032 also accepted, and inherited by subshells.\n\
\032 The -oldui options selects the old multi-window interface. The\n\
\032 default is now more like Smalltalk's class browser.\n\
\n\
1) Viewer\n\
\n\
\032 This is the first window you get when you start OCamlBrowser. It\n\
\032 displays a search window, and the list of modules in the load path.\n\
\032 At the top a row of menus.\n\
\n\
\032 File - Open and File - Editor give access to the editor.\n\
\n\
\032 File - Shell opens an OCaml shell.\n\
\n\
\032 View - Show all defs displays the signature of the currently\n\
\032 selected module.\n\
\n\
\032 View - Search entry shows/hides the search entry just\n\
\032 below the menu bar.\n\
\n\
\032 Modules - Path editor changes the load path.\n\
\032 Pressing [Add to path] or Insert key adds selected directories\n\
\032 to the load path.\n\
\032 Pressing [Remove from path] or Delete key removes selected\n\
\032 paths from the load path.\n\
\n\
\032 Modules - Reset cache rescans the load path and resets the module\n\
\032 cache. Do it if you recompile some interface, or change the load\n\
\032 path in a conflictual way.\n\
\n\
\032 Modules - Search symbol allows to search a symbol either by its\n\
\032 name, like the bottom line of the viewer, or, more interestingly,\n\
\032 by its type. Exact type searches for a type with exactly the same\n\
\032 information as the pattern (variables match only variables),\n\
\032 included type allows to give only partial information: the actual\n\
\032 type may take more arguments and return more results, and variables\n\
\032 in the pattern match anything. In both cases, argument and tuple\n\
\032 order is irrelevant (*), and unlabeled arguments in the pattern\n\
\032 match any label.\n\
\n\
\032 (*) To avoid combinatorial explosion of the search space, optional\n\
\032 arguments in the actual type are ignored if (1) there are to many\n\
\032 of them, and (2) they do not appear explicitly in the pattern.\n\
\n\
\032 The Search entry just below the menu bar allows one to search for\n\
\032 an identifier in all modules, either by its name (? and * patterns\n\
\032 allowed) or by its type (if there is an arrow in the input). When\n\
\032 search by type is used, it is done in inclusion mode (cf. Modules -\n\
\032 search symbol)\n\
\n\
\032 The Close all button is there to dismiss the windows created\n\
\032 by the Detach button. By double-clicking on it you will quit the\n\
\032 browser.\n\
\n\
\n\
2) Module browsing\n\
\n\
\032 You select a module in the leftmost box by either cliking on it or\n\
\032 pressing return when it is selected. Fast access is available in\n\
\032 all boxes pressing the first few letter of the desired name.\n\
\032 Double-clicking / double-return displays the whole signature for\n\
\032 the module.\n\
\n\
\032 Defined identifiers inside the module are displayed in a box to the\n\
\032 right of the previous one. If you click on one, this will either\n\
\032 display its contents in another box (if this is a sub-module) or\n\
\032 display the signature for this identifier below.\n\
\n\
\032 Signatures are clickable. Double clicking with the left mouse\n\
\032 button on an identifier in a signature brings you to its signature,\n\
\032 inside its module box.\n\
\032 A single click on the right button pops up a menu displaying the\n\
\032 type declaration for the selected identifier. Its title, when\n\
\032 selectable, also brings you to its signature.\n\
\n\
\032 At the bottom, a series of buttons, depending on the context.\n\
\032 * Detach copies the currently displayed signature in a new window,\n\
\032 to keep it.\n\
\032 * Impl and Intf bring you to the implementation or interface of\n\
\032 the currently displayed signature, if it is available.\n\
\n\
\032 C-s opens a text search dialog for the displayed signature.\n\
\n\
3) File editor\n\
\n\
\032 You can edit files with it, but there is no auto-save nor undo at\n\
\032 the moment. Otherwise you can use it as a browser, making\n\
\032 occasional corrections.\n\
\n\
\032 The Edit menu contains commands for jump (C-g), search (C-s), and\n\
\032 sending the current selection to a sub-shell (M-x). For this last\n\
\032 option, you may choose the shell via a dialog.\n\
\n\
\032 Essential function are in the Compiler menu.\n\
\n\
\032 Preferences opens a dialog to set internals of the editor and\n\
\032 type checker.\n\
\n\
\032 Lex (M-l) adds colors according to lexical categories.\n\
\n\
\032 Typecheck (M-t) verifies typing, and memorizes it to let one see an\n\
\032 expression's type by double-clicking on it. This is also valid for\n\
\032 interfaces. If an error occurs, the part of the interface preceding\n\
\032 the error is computed.\n\
\n\
\032 After typechecking, pressing the right button pops up a menu giving\n\
\032 the type of the pointed expression, and eventually allowing to\n\
\032 follow some links.\n\
\n\
\032 Clear errors dismisses type checker error messages and warnings.\n\
\n\
\032 Signature shows the signature of the current file.\n\
\n\
4) Shell\n\
\n\
\032 When you create a shell, a dialog is presented to you, letting you\n\
\032 choose which command you want to run, and the title of the shell\n\
\032 (to choose it in the Editor).\n\
\n\
\032 You may change the default command by setting the OLABL environment\n\
\032 variable.\n\
\n\
\032 The executed subshell is given the current load path.\n\
\032 File: use a source file or load a bytecode file.\n\
\032 You may also import the browser's path into the subprocess.\n\
\032 History: M-p and M-n browse up and down.\n\
\032 Signal: C-c interrupts and you can kill the subprocess.\n\
\n\
BUGS\n\
\n\
* When you quit the editor and some file was modified, a dialogue is\n\
\032 displayed asking wether you want to really quit or not. But 1) if\n\
\032 you quit directly from the viewer, there is no dialogue at all, and\n\
\032 2) if you close from the window manager, the dialogue is displayed,\n\
\032 but you cannot cancel the destruction... Beware.\n\
\n\
* When you run it through xon, the shell hangs at the first error. But\n\
\032 its ok if you start ocamlbrowser from a remote shell...\n\
\n\
TODO\n\
\n\
* Complete cross-references.\n\
\n\
* Power up editor.\n\
\n\
* Add support for the debugger.\n\
\n\
* Make this a real programming environment, both for beginners an\n\
\032 experimented users.\n\
\n\
\n\
Bug reports and comments to <>\n\
";;
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/browser/help.ml | ocaml | ), and unlabeled arguments in the pattern\n\
\032 match any label.\n\
\n\
\032 ( | let text = "\
\032 OCamlBrowser Help\n\
\n\
USE\n\
\n\
\032 OCamlBrowser is composed of three tools, the Editor, which allows\n\
\032 one to edit/typecheck/analyse .mli and .ml files, the Viewer, to\n\
\032 walk around compiled modules, and the Shell, to run an OCaml\n\
\032 subshell. You may only have one instance of Editor and Viewer, but\n\
\032 you may use several subshells.\n\
\n\
\032 As with the compiler, you may specify a different path for the\n\
\032 standard library by setting OCAMLLIB. You may also extend the\n\
\032 initial load path (only standard library by default) by using the\n\
\032 -I command line option. The -nolabels, -rectypes and -w options are\n\
\032 also accepted, and inherited by subshells.\n\
\032 The -oldui options selects the old multi-window interface. The\n\
\032 default is now more like Smalltalk's class browser.\n\
\n\
1) Viewer\n\
\n\
\032 This is the first window you get when you start OCamlBrowser. It\n\
\032 displays a search window, and the list of modules in the load path.\n\
\032 At the top a row of menus.\n\
\n\
\032 File - Open and File - Editor give access to the editor.\n\
\n\
\032 File - Shell opens an OCaml shell.\n\
\n\
\032 View - Show all defs displays the signature of the currently\n\
\032 selected module.\n\
\n\
\032 View - Search entry shows/hides the search entry just\n\
\032 below the menu bar.\n\
\n\
\032 Modules - Path editor changes the load path.\n\
\032 Pressing [Add to path] or Insert key adds selected directories\n\
\032 to the load path.\n\
\032 Pressing [Remove from path] or Delete key removes selected\n\
\032 paths from the load path.\n\
\n\
\032 Modules - Reset cache rescans the load path and resets the module\n\
\032 cache. Do it if you recompile some interface, or change the load\n\
\032 path in a conflictual way.\n\
\n\
\032 Modules - Search symbol allows to search a symbol either by its\n\
\032 name, like the bottom line of the viewer, or, more interestingly,\n\
\032 by its type. Exact type searches for a type with exactly the same\n\
\032 information as the pattern (variables match only variables),\n\
\032 included type allows to give only partial information: the actual\n\
\032 type may take more arguments and return more results, and variables\n\
\032 in the pattern match anything. In both cases, argument and tuple\n\
\032 arguments in the actual type are ignored if (1) there are to many\n\
\032 of them, and (2) they do not appear explicitly in the pattern.\n\
\n\
\032 The Search entry just below the menu bar allows one to search for\n\
\032 an identifier in all modules, either by its name (? and * patterns\n\
\032 allowed) or by its type (if there is an arrow in the input). When\n\
\032 search by type is used, it is done in inclusion mode (cf. Modules -\n\
\032 search symbol)\n\
\n\
\032 The Close all button is there to dismiss the windows created\n\
\032 by the Detach button. By double-clicking on it you will quit the\n\
\032 browser.\n\
\n\
\n\
2) Module browsing\n\
\n\
\032 You select a module in the leftmost box by either cliking on it or\n\
\032 pressing return when it is selected. Fast access is available in\n\
\032 all boxes pressing the first few letter of the desired name.\n\
\032 Double-clicking / double-return displays the whole signature for\n\
\032 the module.\n\
\n\
\032 Defined identifiers inside the module are displayed in a box to the\n\
\032 right of the previous one. If you click on one, this will either\n\
\032 display its contents in another box (if this is a sub-module) or\n\
\032 display the signature for this identifier below.\n\
\n\
\032 Signatures are clickable. Double clicking with the left mouse\n\
\032 button on an identifier in a signature brings you to its signature,\n\
\032 inside its module box.\n\
\032 A single click on the right button pops up a menu displaying the\n\
\032 type declaration for the selected identifier. Its title, when\n\
\032 selectable, also brings you to its signature.\n\
\n\
\032 At the bottom, a series of buttons, depending on the context.\n\
\032 * Detach copies the currently displayed signature in a new window,\n\
\032 to keep it.\n\
\032 * Impl and Intf bring you to the implementation or interface of\n\
\032 the currently displayed signature, if it is available.\n\
\n\
\032 C-s opens a text search dialog for the displayed signature.\n\
\n\
3) File editor\n\
\n\
\032 You can edit files with it, but there is no auto-save nor undo at\n\
\032 the moment. Otherwise you can use it as a browser, making\n\
\032 occasional corrections.\n\
\n\
\032 The Edit menu contains commands for jump (C-g), search (C-s), and\n\
\032 sending the current selection to a sub-shell (M-x). For this last\n\
\032 option, you may choose the shell via a dialog.\n\
\n\
\032 Essential function are in the Compiler menu.\n\
\n\
\032 Preferences opens a dialog to set internals of the editor and\n\
\032 type checker.\n\
\n\
\032 Lex (M-l) adds colors according to lexical categories.\n\
\n\
\032 Typecheck (M-t) verifies typing, and memorizes it to let one see an\n\
\032 expression's type by double-clicking on it. This is also valid for\n\
\032 interfaces. If an error occurs, the part of the interface preceding\n\
\032 the error is computed.\n\
\n\
\032 After typechecking, pressing the right button pops up a menu giving\n\
\032 the type of the pointed expression, and eventually allowing to\n\
\032 follow some links.\n\
\n\
\032 Clear errors dismisses type checker error messages and warnings.\n\
\n\
\032 Signature shows the signature of the current file.\n\
\n\
4) Shell\n\
\n\
\032 When you create a shell, a dialog is presented to you, letting you\n\
\032 choose which command you want to run, and the title of the shell\n\
\032 (to choose it in the Editor).\n\
\n\
\032 You may change the default command by setting the OLABL environment\n\
\032 variable.\n\
\n\
\032 The executed subshell is given the current load path.\n\
\032 File: use a source file or load a bytecode file.\n\
\032 You may also import the browser's path into the subprocess.\n\
\032 History: M-p and M-n browse up and down.\n\
\032 Signal: C-c interrupts and you can kill the subprocess.\n\
\n\
BUGS\n\
\n\
* When you quit the editor and some file was modified, a dialogue is\n\
\032 displayed asking wether you want to really quit or not. But 1) if\n\
\032 you quit directly from the viewer, there is no dialogue at all, and\n\
\032 2) if you close from the window manager, the dialogue is displayed,\n\
\032 but you cannot cancel the destruction... Beware.\n\
\n\
* When you run it through xon, the shell hangs at the first error. But\n\
\032 its ok if you start ocamlbrowser from a remote shell...\n\
\n\
TODO\n\
\n\
* Complete cross-references.\n\
\n\
* Power up editor.\n\
\n\
* Add support for the debugger.\n\
\n\
* Make this a real programming environment, both for beginners an\n\
\032 experimented users.\n\
\n\
\n\
Bug reports and comments to <>\n\
";;
|
e5a00dbfac437733a5b4e4f1b40b664ece4edeaf8b39074700a38aa23405a896 | runtimeverification/haskell-backend | DebugEvaluateCondition.hs | module Test.Kore.Log.DebugEvaluateCondition (
test_instance_Table_DebugEvaluateCondition,
) where
import Data.List (
inits,
)
import Kore.Internal.Predicate
import Kore.Internal.TermLike
import Kore.Log.DebugEvaluateCondition
import Prelude.Kore
import Test.Kore.Rewrite.MockSymbols qualified as Mock
import Test.SQL
import Test.Tasty
test_instance_Table_DebugEvaluateCondition :: TestTree
test_instance_Table_DebugEvaluateCondition =
testTable @DebugEvaluateCondition $ do
let predicates = [predicate1, predicate2]
predicate <- predicates
sideConditions <- inits predicates
[DebugEvaluateCondition (predicate :| sideConditions)]
predicate1, predicate2 :: Predicate VariableName
predicate1 = makeEqualsPredicate (Mock.f Mock.a) (Mock.g Mock.b)
predicate2 = makeEqualsPredicate (Mock.g Mock.a) (Mock.h Mock.c)
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/b06757e252ee01fdd5ab8f07de2910711997d845/kore/test/Test/Kore/Log/DebugEvaluateCondition.hs | haskell | module Test.Kore.Log.DebugEvaluateCondition (
test_instance_Table_DebugEvaluateCondition,
) where
import Data.List (
inits,
)
import Kore.Internal.Predicate
import Kore.Internal.TermLike
import Kore.Log.DebugEvaluateCondition
import Prelude.Kore
import Test.Kore.Rewrite.MockSymbols qualified as Mock
import Test.SQL
import Test.Tasty
test_instance_Table_DebugEvaluateCondition :: TestTree
test_instance_Table_DebugEvaluateCondition =
testTable @DebugEvaluateCondition $ do
let predicates = [predicate1, predicate2]
predicate <- predicates
sideConditions <- inits predicates
[DebugEvaluateCondition (predicate :| sideConditions)]
predicate1, predicate2 :: Predicate VariableName
predicate1 = makeEqualsPredicate (Mock.f Mock.a) (Mock.g Mock.b)
predicate2 = makeEqualsPredicate (Mock.g Mock.a) (Mock.h Mock.c)
| |
1204c77d821319562814119dbd9079e85f8b187f972344564da718b170b192d6 | alanz/ghc-exactprint | SlidingTypeSyn.hs | {-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
# LANGUAGE LiberalTypeSynonyms #
# LANGUAGE GADTs #
# LANGUAGE TypeFamilies #
type ( f :-> g) (r :: Type -> Type) ix = f r ix -> g r ix
) b ix = f b ix - > g b ix
type ((f :---> g)) b ix = f b ix -> g b ix
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc86/SlidingTypeSyn.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators #
# LANGUAGE KindSignatures #
-> g)) b ix = f b ix -> g b ix | # LANGUAGE LiberalTypeSynonyms #
# LANGUAGE GADTs #
# LANGUAGE TypeFamilies #
type ( f :-> g) (r :: Type -> Type) ix = f r ix -> g r ix
) b ix = f b ix - > g b ix
|
360e0937c222cc03cd4d7ffb38e33913697ea8a3d127d1d1d0ddbb45ac739b97 | toyokumo/tarayo | benchmark.clj | (ns benchmark
(:require
[criterium.core :as criterium]
[postal.core :as postal]
[tarayo.core :as tarayo]
[tarayo.test-helper :as h]))
(def ^:private message
{:from ""
:to ""
:subject "hello"
:body "world"})
(defn -main
[]
(h/with-test-smtp-server [_ port]
(println "POSTAL ----")
(criterium/bench
(postal/send-message {:host "localhost" :port port}
message)))
(println "")
(h/with-test-smtp-server [_ port]
(println "TARAYO ----")
(criterium/bench
(with-open [conn (tarayo/connect {:port port})]
(tarayo/send! conn message)))))
(comment (-main))
| null | https://raw.githubusercontent.com/toyokumo/tarayo/f9b10b85b7bc1a188d808c3955e258916cd0b38a/dev/src/benchmark.clj | clojure | (ns benchmark
(:require
[criterium.core :as criterium]
[postal.core :as postal]
[tarayo.core :as tarayo]
[tarayo.test-helper :as h]))
(def ^:private message
{:from ""
:to ""
:subject "hello"
:body "world"})
(defn -main
[]
(h/with-test-smtp-server [_ port]
(println "POSTAL ----")
(criterium/bench
(postal/send-message {:host "localhost" :port port}
message)))
(println "")
(h/with-test-smtp-server [_ port]
(println "TARAYO ----")
(criterium/bench
(with-open [conn (tarayo/connect {:port port})]
(tarayo/send! conn message)))))
(comment (-main))
| |
67e4bfabb9d1511d1256a0461ef220ef26d9dcabffcc6213fb454936359f269e | chaoxu/fancy-walks | A.hs |
get :: Integer -> Integer -> Integer
get n a = (n - 1) `div` a + 1
main = do
line <- getLine
let [n,m,a] = map read . words $ line
putStrLn $ show ((get n a) * (get m a))
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/codeforces.com/1/A.hs | haskell |
get :: Integer -> Integer -> Integer
get n a = (n - 1) `div` a + 1
main = do
line <- getLine
let [n,m,a] = map read . words $ line
putStrLn $ show ((get n a) * (get m a))
| |
204de60296be689792357499bcb82a1fd7ce03cb54b08c684f84d9748f75fd2c | incoherentsoftware/defect-process | Data.hs | module Player.Weapon.All.Sword.Data
( SwordChargeStatus(..)
, swordChargeStatusChargeSecs
, SwordAttackDescriptions(..)
, SwordData(..)
, mkSwordData
) where
import Control.Monad.IO.Class (MonadIO)
import Attack
import Configs
import Configs.All.PlayerWeapon
import Configs.All.PlayerWeapon.Sword
import FileCache
import Id
import Util
import Window.Graphics
packFilePath = "data/player/weapons/sword.pack" :: FilePath
data SwordChargeStatus
= SwordNoChargeStatus
| SwordPartialChargeStatus Secs
| SwordFullChargeStatus
deriving Eq
swordChargeStatusChargeSecs :: SwordChargeStatus -> Secs
swordChargeStatusChargeSecs = \case
SwordNoChargeStatus -> 0.0
SwordPartialChargeStatus chargeSecs -> chargeSecs
SwordFullChargeStatus -> maxSecs
data SwordAttackDescriptions = SwordAttackDescriptions
{ _slash1 :: AttackDescription
, _slash2 :: AttackDescription
, _slash2Heavy :: AttackDescription
, _slash3 :: AttackDescription
, _slash3Aoe :: AttackDescription
, _fallSlash :: AttackDescription
, _fallSlashLand :: AttackDescription
, _upSlash :: AttackDescription
, _airSlash1 :: AttackDescription
, _airSlash2 :: AttackDescription
, _airDownSlash :: AttackDescription
, _airSlash3 :: AttackDescription
, _flurryStab :: AttackDescription
, _flurryThrust :: AttackDescription
, _chargeRelease :: AttackDescription
, _airChargeRelease :: AttackDescription
, _chargeReleaseProjectile :: AttackDescription
, _summonAttackOrb :: AttackDescription
, _attackOrbActivate :: AttackDescription
}
mkSwordAttackDescriptions :: forall m. (FileCache m, GraphicsRead m, MonadIO m) => m SwordAttackDescriptions
mkSwordAttackDescriptions =
SwordAttackDescriptions <$>
loadAtkDesc "slash1-.atk" <*>
loadAtkDesc "slash2-.atk" <*>
loadAtkDesc "slash2-heavy.atk" <*>
loadAtkDesc "slash3-.atk" <*>
loadAtkDesc "slash3-aoe.atk" <*>
loadAtkDesc "fall-slash.atk" <*>
loadAtkDesc "fall-slash-land.atk" <*>
loadAtkDesc "up-slash.atk" <*>
loadAtkDesc "air-slash1-.atk" <*>
loadAtkDesc "air-slash2-.atk" <*>
loadAtkDesc "air-down-slash.atk" <*>
loadAtkDesc "air-slash3-.atk" <*>
loadAtkDesc "flurry-stab.atk" <*>
loadAtkDesc "flurry-thrust.atk" <*>
loadAtkDesc "charge-release.atk" <*>
loadAtkDesc "air-charge-release.atk" <*>
loadAtkDesc "charge-release-projectile.atk" <*>
loadAtkDesc "summon-attack-orb.atk" <*>
loadAtkDesc "attack-orb-activate.atk"
where loadAtkDesc = \f -> loadPackAttackDescription $ PackResourceFilePath packFilePath f
data SwordData = SwordData
{ _prevChargeStatus :: SwordChargeStatus
, _chargeStatus :: SwordChargeStatus
, _chargeOverlaySpr :: Sprite
, _chargeSoundHashedId :: HashedId
, _attackDescriptions :: SwordAttackDescriptions
, _config :: SwordConfig
}
mkSwordData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m SwordData
mkSwordData = do
chargeOverlaySpr <- loadPackSprite $ PackResourceFilePath packFilePath "charge-overlay.spr"
chargeSoundHashedId <- hashId <$> newId
wpnAtkDescs <- mkSwordAttackDescriptions
cfg <- readConfig _playerWeapon _sword
return $ SwordData
{ _prevChargeStatus = SwordNoChargeStatus
, _chargeStatus = SwordNoChargeStatus
, _chargeOverlaySpr = chargeOverlaySpr
, _chargeSoundHashedId = chargeSoundHashedId
, _attackDescriptions = wpnAtkDescs
, _config = cfg
}
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Player/Weapon/All/Sword/Data.hs | haskell | module Player.Weapon.All.Sword.Data
( SwordChargeStatus(..)
, swordChargeStatusChargeSecs
, SwordAttackDescriptions(..)
, SwordData(..)
, mkSwordData
) where
import Control.Monad.IO.Class (MonadIO)
import Attack
import Configs
import Configs.All.PlayerWeapon
import Configs.All.PlayerWeapon.Sword
import FileCache
import Id
import Util
import Window.Graphics
packFilePath = "data/player/weapons/sword.pack" :: FilePath
data SwordChargeStatus
= SwordNoChargeStatus
| SwordPartialChargeStatus Secs
| SwordFullChargeStatus
deriving Eq
swordChargeStatusChargeSecs :: SwordChargeStatus -> Secs
swordChargeStatusChargeSecs = \case
SwordNoChargeStatus -> 0.0
SwordPartialChargeStatus chargeSecs -> chargeSecs
SwordFullChargeStatus -> maxSecs
data SwordAttackDescriptions = SwordAttackDescriptions
{ _slash1 :: AttackDescription
, _slash2 :: AttackDescription
, _slash2Heavy :: AttackDescription
, _slash3 :: AttackDescription
, _slash3Aoe :: AttackDescription
, _fallSlash :: AttackDescription
, _fallSlashLand :: AttackDescription
, _upSlash :: AttackDescription
, _airSlash1 :: AttackDescription
, _airSlash2 :: AttackDescription
, _airDownSlash :: AttackDescription
, _airSlash3 :: AttackDescription
, _flurryStab :: AttackDescription
, _flurryThrust :: AttackDescription
, _chargeRelease :: AttackDescription
, _airChargeRelease :: AttackDescription
, _chargeReleaseProjectile :: AttackDescription
, _summonAttackOrb :: AttackDescription
, _attackOrbActivate :: AttackDescription
}
mkSwordAttackDescriptions :: forall m. (FileCache m, GraphicsRead m, MonadIO m) => m SwordAttackDescriptions
mkSwordAttackDescriptions =
SwordAttackDescriptions <$>
loadAtkDesc "slash1-.atk" <*>
loadAtkDesc "slash2-.atk" <*>
loadAtkDesc "slash2-heavy.atk" <*>
loadAtkDesc "slash3-.atk" <*>
loadAtkDesc "slash3-aoe.atk" <*>
loadAtkDesc "fall-slash.atk" <*>
loadAtkDesc "fall-slash-land.atk" <*>
loadAtkDesc "up-slash.atk" <*>
loadAtkDesc "air-slash1-.atk" <*>
loadAtkDesc "air-slash2-.atk" <*>
loadAtkDesc "air-down-slash.atk" <*>
loadAtkDesc "air-slash3-.atk" <*>
loadAtkDesc "flurry-stab.atk" <*>
loadAtkDesc "flurry-thrust.atk" <*>
loadAtkDesc "charge-release.atk" <*>
loadAtkDesc "air-charge-release.atk" <*>
loadAtkDesc "charge-release-projectile.atk" <*>
loadAtkDesc "summon-attack-orb.atk" <*>
loadAtkDesc "attack-orb-activate.atk"
where loadAtkDesc = \f -> loadPackAttackDescription $ PackResourceFilePath packFilePath f
data SwordData = SwordData
{ _prevChargeStatus :: SwordChargeStatus
, _chargeStatus :: SwordChargeStatus
, _chargeOverlaySpr :: Sprite
, _chargeSoundHashedId :: HashedId
, _attackDescriptions :: SwordAttackDescriptions
, _config :: SwordConfig
}
mkSwordData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m SwordData
mkSwordData = do
chargeOverlaySpr <- loadPackSprite $ PackResourceFilePath packFilePath "charge-overlay.spr"
chargeSoundHashedId <- hashId <$> newId
wpnAtkDescs <- mkSwordAttackDescriptions
cfg <- readConfig _playerWeapon _sword
return $ SwordData
{ _prevChargeStatus = SwordNoChargeStatus
, _chargeStatus = SwordNoChargeStatus
, _chargeOverlaySpr = chargeOverlaySpr
, _chargeSoundHashedId = chargeSoundHashedId
, _attackDescriptions = wpnAtkDescs
, _config = cfg
}
| |
6881e00316867d54d3f83a6abf65c252ea30829ddeb388b2b4306f2db437520e | pawurb/haskell-pg-extras | Mandelbrot.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
module PGExtras.Queries.Mandelbrot (mandelbrotSQL, displayMandelbrot) where
import PGExtras.Helpers (maybeText)
import Database.PostgreSQL.Simple
import Text.RawString.QQ
import qualified Data.Text as Text
import Control.Monad (forM_)
import Data.List (intercalate)
mandelbrotSQL :: Query
mandelbrotSQL = [r|WITH RECURSIVE Z(IX, IY, CX, CY, X, Y, I) AS (
SELECT IX, IY, X::float, Y::float, X::float, Y::float, 0
FROM (select -2.2 + 0.031 * i, i from generate_series(0,101) as i) as xgen(x,ix),
(select -1.5 + 0.031 * i, i from generate_series(0,101) as i) as ygen(y,iy)
UNION ALL
SELECT IX, IY, CX, CY, X * X - Y * Y + CX AS X, Y * X * 2 + CY, I + 1
FROM Z
WHERE X * X + Y * Y < 16::float
AND I < 100
)
---++++%%%%@@@@ # # # # ' , LEAST(GREATEST(I,1),27 ) , 1 ) ) , '' ) , ' t ' as t
FROM (
SELECT IX, IY, MAX(I) AS I
FROM Z
GROUP BY IY, IX
ORDER BY IY, IX
) AS ZT
GROUP BY IY
ORDER BY IY;|]
displayMandelbrot :: [(Maybe Text.Text, Maybe Text.Text)] -> IO ()
displayMandelbrot rows = do
putStrLn $ description
putStrLn $ intercalate " | " tableHeaders
forM_ rows $ \(arg1, _) ->
putStrLn $ maybeText(arg1)
description :: [Char]
description = "The mandelbrot set"
tableHeaders :: [[Char]]
tableHeaders = ["name", "ratio"]
| null | https://raw.githubusercontent.com/pawurb/haskell-pg-extras/1cddde5f784c6fa2286dd0090389237925918bd8/src/PGExtras/Queries/Mandelbrot.hs | haskell | # LANGUAGE OverloadedStrings #
-++++%%%%@@@@ # # # # ' , LEAST(GREATEST(I,1),27 ) , 1 ) ) , '' ) , ' t ' as t | # LANGUAGE QuasiQuotes #
module PGExtras.Queries.Mandelbrot (mandelbrotSQL, displayMandelbrot) where
import PGExtras.Helpers (maybeText)
import Database.PostgreSQL.Simple
import Text.RawString.QQ
import qualified Data.Text as Text
import Control.Monad (forM_)
import Data.List (intercalate)
mandelbrotSQL :: Query
mandelbrotSQL = [r|WITH RECURSIVE Z(IX, IY, CX, CY, X, Y, I) AS (
SELECT IX, IY, X::float, Y::float, X::float, Y::float, 0
FROM (select -2.2 + 0.031 * i, i from generate_series(0,101) as i) as xgen(x,ix),
(select -1.5 + 0.031 * i, i from generate_series(0,101) as i) as ygen(y,iy)
UNION ALL
SELECT IX, IY, CX, CY, X * X - Y * Y + CX AS X, Y * X * 2 + CY, I + 1
FROM Z
WHERE X * X + Y * Y < 16::float
AND I < 100
)
FROM (
SELECT IX, IY, MAX(I) AS I
FROM Z
GROUP BY IY, IX
ORDER BY IY, IX
) AS ZT
GROUP BY IY
ORDER BY IY;|]
displayMandelbrot :: [(Maybe Text.Text, Maybe Text.Text)] -> IO ()
displayMandelbrot rows = do
putStrLn $ description
putStrLn $ intercalate " | " tableHeaders
forM_ rows $ \(arg1, _) ->
putStrLn $ maybeText(arg1)
description :: [Char]
description = "The mandelbrot set"
tableHeaders :: [[Char]]
tableHeaders = ["name", "ratio"]
|
3c223da82271535a5f3ef4e587e6e58bcd3b7a8693d2ee091bd50b7c81d38cb6 | fmi/clojure-examples | 04-dynamic-returns.clj | ;;; This program illustrates how to use dynamic scoping to return arguments.
;;; The abs function can indicate whether it had to flip the sign of its
;;; argument or not. The caller can check *negative-arg* after calling abs.
;;;
;;; A caveat of this code is that it would result to an error if the caller has
;;; not bound *negative-arg*. Fixing this (with thread-bound?) is left as an
;;; exercise to the reader.
(def ^:dynamic *negative-arg*)
(defn abs [n]
(if (neg? n)
(do (set! *negative-arg* true)
(- n))
(do (set! *negative-arg* false)
n)))
(defn report-abs [n]
(binding [*negative-arg* nil]
(let [abs-n (abs n)]
(printf "The abs of %s is %s and *negative-arg* is: %s\n"
n abs-n *negative-arg*))))
(report-abs 42)
(report-abs -42)
;; Output from this program:
;;
→ clj 04-dynamic-returns.clj
The abs of 42 is 42 and * negative - arg * is : false
The abs of -42 is 42 and * negative - arg * is : true
| null | https://raw.githubusercontent.com/fmi/clojure-examples/46ec0fe7bdfdfccde1ab74a94c64dbd73ea58269/2013/03-futures-atoms-vars/04-dynamic-returns.clj | clojure | This program illustrates how to use dynamic scoping to return arguments.
The abs function can indicate whether it had to flip the sign of its
argument or not. The caller can check *negative-arg* after calling abs.
A caveat of this code is that it would result to an error if the caller has
not bound *negative-arg*. Fixing this (with thread-bound?) is left as an
exercise to the reader.
Output from this program:
| (def ^:dynamic *negative-arg*)
(defn abs [n]
(if (neg? n)
(do (set! *negative-arg* true)
(- n))
(do (set! *negative-arg* false)
n)))
(defn report-abs [n]
(binding [*negative-arg* nil]
(let [abs-n (abs n)]
(printf "The abs of %s is %s and *negative-arg* is: %s\n"
n abs-n *negative-arg*))))
(report-abs 42)
(report-abs -42)
→ clj 04-dynamic-returns.clj
The abs of 42 is 42 and * negative - arg * is : false
The abs of -42 is 42 and * negative - arg * is : true
|
3c829bcdfb48b116f197c9b85c997adde01e4c80a41558f62f422cc6c0d5423a | bendyworks/api-server | UserSpec.hs | # LANGUAGE QuasiQuotes #
module Api.Mappers.UserSpec (main, spec) where
import Control.Applicative ((<$>))
import Data.Functor.Identity (Identity (..))
import Data.Maybe (fromJust, isJust)
import Hasql (q, single)
import qualified Api.Mappers.Resource as Resource
import qualified Api.Mappers.User as User
import Api.Types.Fields
import Api.Types.Resource
import Api.Types.User
import SpecHelper hiding (shouldBe, shouldSatisfy)
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = beforeAll resetDb $ do
describe "findByLogin" $ do
it "finds a User by their UserID and UserToken" $ withRollback $ \query -> do
found <- query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
User.findByLogin login
found `shouldSatisfy` isJust
it "returns Nothing if the UserTokens don't match" $ withRollback $ \query -> do
found <- query $ do
login <- fromJust <$> User.insert
let badLogin = Login (login_userId login) (UserToken "invalid_token")
User.findByLogin badLogin
found `shouldBe` Nothing
it "returns Nothing if the UserIDs don't match" $ withRollback $ \query -> do
found <- query $ do
login <- fromJust <$> User.insert
let badLogin = Login (UserID 9999) (login_userToken login)
User.findByLogin badLogin
found `shouldBe` Nothing
describe "insert" $ do
it "creates a new User" $ withRollback $ \query -> do
count <- query $ do
login <- fromJust <$> User.insert
let (UserID uid) = login_userId login
single $ [q| SELECT COUNT(id) FROM users WHERE id = ? |] uid
fromJust count `shouldBe` Identity (1 :: Int)
it "generates unique tokens for each User" $ withRollback $ \query -> do
hasSameTokens <- query $ do
login1 <- fromJust <$> User.insert
login2 <- fromJust <$> User.insert
return $ login_userToken login1 == login_userToken login2
hasSameTokens `shouldBe` False
describe "update" $ do
it "updates a User with the same ID" $ withRollback $ \query -> do
(user, resource) <- query $ do
resource <- fromJust <$> Resource.insert mockResFields
login <- fromJust <$> User.insert
user <- fromJust <$> User.update (User (login_userId login) (Just $ res_id resource))
return (user, resource)
user_resourceId user `shouldBe` Just (res_id resource)
it "returns Nothing if no User has the same UserID" $ withRollback $ \query -> do
let notInDb = User (UserID 9999) (Just $ ResourceID 1)
found <- query $ User.update notInDb
found `shouldBe` Nothing
| null | https://raw.githubusercontent.com/bendyworks/api-server/9dd6d7c2599bd1c5a7e898a417a7aeb319415dd2/test/Api/Mappers/UserSpec.hs | haskell | # LANGUAGE QuasiQuotes #
module Api.Mappers.UserSpec (main, spec) where
import Control.Applicative ((<$>))
import Data.Functor.Identity (Identity (..))
import Data.Maybe (fromJust, isJust)
import Hasql (q, single)
import qualified Api.Mappers.Resource as Resource
import qualified Api.Mappers.User as User
import Api.Types.Fields
import Api.Types.Resource
import Api.Types.User
import SpecHelper hiding (shouldBe, shouldSatisfy)
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = beforeAll resetDb $ do
describe "findByLogin" $ do
it "finds a User by their UserID and UserToken" $ withRollback $ \query -> do
found <- query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
User.findByLogin login
found `shouldSatisfy` isJust
it "returns Nothing if the UserTokens don't match" $ withRollback $ \query -> do
found <- query $ do
login <- fromJust <$> User.insert
let badLogin = Login (login_userId login) (UserToken "invalid_token")
User.findByLogin badLogin
found `shouldBe` Nothing
it "returns Nothing if the UserIDs don't match" $ withRollback $ \query -> do
found <- query $ do
login <- fromJust <$> User.insert
let badLogin = Login (UserID 9999) (login_userToken login)
User.findByLogin badLogin
found `shouldBe` Nothing
describe "insert" $ do
it "creates a new User" $ withRollback $ \query -> do
count <- query $ do
login <- fromJust <$> User.insert
let (UserID uid) = login_userId login
single $ [q| SELECT COUNT(id) FROM users WHERE id = ? |] uid
fromJust count `shouldBe` Identity (1 :: Int)
it "generates unique tokens for each User" $ withRollback $ \query -> do
hasSameTokens <- query $ do
login1 <- fromJust <$> User.insert
login2 <- fromJust <$> User.insert
return $ login_userToken login1 == login_userToken login2
hasSameTokens `shouldBe` False
describe "update" $ do
it "updates a User with the same ID" $ withRollback $ \query -> do
(user, resource) <- query $ do
resource <- fromJust <$> Resource.insert mockResFields
login <- fromJust <$> User.insert
user <- fromJust <$> User.update (User (login_userId login) (Just $ res_id resource))
return (user, resource)
user_resourceId user `shouldBe` Just (res_id resource)
it "returns Nothing if no User has the same UserID" $ withRollback $ \query -> do
let notInDb = User (UserID 9999) (Just $ ResourceID 1)
found <- query $ User.update notInDb
found `shouldBe` Nothing
| |
339211bfbf07bba6d1cac0d6ec8a6c5e7ef66eab9692ac360f6090f16c6c996e | Phantas0s/sokoban | start_dev.cljs | (ns sokoban.start-dev
(:require [sokoban.start]
[orchestra-cljs.spec.test :as st]
[expound.alpha :as expound]
[clojure.spec.alpha :as s]))
(st/instrument)
(set! s/*explain-out* expound/printer)
| null | https://raw.githubusercontent.com/Phantas0s/sokoban/b481314b5544c30f43ecfadcb0edeb2db44669e6/src/sokoban/start_dev.cljs | clojure | (ns sokoban.start-dev
(:require [sokoban.start]
[orchestra-cljs.spec.test :as st]
[expound.alpha :as expound]
[clojure.spec.alpha :as s]))
(st/instrument)
(set! s/*explain-out* expound/printer)
| |
327763e9ed5e1cbf7bb9e330be124c3e872a93d26ac84da270f177f5304764b2 | oflatt/space-orbs | space-orbs-client.rkt | #lang racket
(require pict3d "variables.rkt" "on-draw.rkt" "key-events.rkt" "on-mouse.rkt" "stop-state.rkt" "big-crunch.rkt" "on-frame.rkt"
"frame-handling.rkt"
racket/class
racket/gui/base)
(current-material (material #:ambient 0.01
#:diffuse 0.39
#:specular 1
#:roughness 0.2))
(define gl-config (new gl-config%))
(send gl-config set-sync-swap #t)
(send gl-config set-legacy? #f)
(void;;void makes it not return the state
(big-bang3d/big-crunch
DEFAULT-STATE
#:name "Space Orbs"
#:on-draw on-draw
#:on-key on-key
#:on-release on-release
#:on-mouse on-mouse
#:stop-state? stop-state?
#:on-frame on-frame
#:display-mode 'hide-menu-bar
#:gl-config gl-config
#:cursor (make-cursor-blank))) | null | https://raw.githubusercontent.com/oflatt/space-orbs/3d6301e576f304a9994d42b49939ad2432069aac/client/space-orbs-client.rkt | racket | void makes it not return the state | #lang racket
(require pict3d "variables.rkt" "on-draw.rkt" "key-events.rkt" "on-mouse.rkt" "stop-state.rkt" "big-crunch.rkt" "on-frame.rkt"
"frame-handling.rkt"
racket/class
racket/gui/base)
(current-material (material #:ambient 0.01
#:diffuse 0.39
#:specular 1
#:roughness 0.2))
(define gl-config (new gl-config%))
(send gl-config set-sync-swap #t)
(send gl-config set-legacy? #f)
(big-bang3d/big-crunch
DEFAULT-STATE
#:name "Space Orbs"
#:on-draw on-draw
#:on-key on-key
#:on-release on-release
#:on-mouse on-mouse
#:stop-state? stop-state?
#:on-frame on-frame
#:display-mode 'hide-menu-bar
#:gl-config gl-config
#:cursor (make-cursor-blank))) |
627d34fd9b9f19580cd839d362d11650fc82981a685a01b191183720d29d7646 | jonschoning/espial | Pretty.hs | module Pretty where
import Text.Show.Pretty (ppShow)
import Language.Haskell.HsColour
import Language.Haskell.HsColour.Colourise
import ClassyPrelude
cpprint :: (MonadIO m, Show a) => a -> m ()
cpprint = putStrLn . pack . hscolour TTY defaultColourPrefs False False "" False . ppShow
cprint :: (MonadIO m, Show a) => a -> m ()
cprint = putStrLn . pack . hscolour TTY defaultColourPrefs False False "" False . show
pprint :: (MonadIO m, Show a) => a -> m ()
pprint = putStrLn . pack . ppShow
| null | https://raw.githubusercontent.com/jonschoning/espial/a0b7c3c782d1089166e7a492b4d1f48018fee2b8/src/Pretty.hs | haskell | module Pretty where
import Text.Show.Pretty (ppShow)
import Language.Haskell.HsColour
import Language.Haskell.HsColour.Colourise
import ClassyPrelude
cpprint :: (MonadIO m, Show a) => a -> m ()
cpprint = putStrLn . pack . hscolour TTY defaultColourPrefs False False "" False . ppShow
cprint :: (MonadIO m, Show a) => a -> m ()
cprint = putStrLn . pack . hscolour TTY defaultColourPrefs False False "" False . show
pprint :: (MonadIO m, Show a) => a -> m ()
pprint = putStrLn . pack . ppShow
| |
358759049e5cf53a430196cbdd6ab948268e8c123d44fd4d6e2de6c78f60534e | DSiSc/why3 | term.ml | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
open Wstdlib
open Ident
open Ty
(** Variable symbols *)
type vsymbol = {
vs_name : ident;
vs_ty : ty;
}
module Vsym = MakeMSHW (struct
type t = vsymbol
let tag vs = vs.vs_name.id_tag
end)
module Svs = Vsym.S
module Mvs = Vsym.M
module Hvs = Vsym.H
module Wvs = Vsym.W
let vs_equal : vsymbol -> vsymbol -> bool = (==)
let vs_hash vs = id_hash vs.vs_name
let vs_compare vs1 vs2 = id_compare vs1.vs_name vs2.vs_name
let create_vsymbol name ty = {
vs_name = id_register name;
vs_ty = ty;
}
(** Function and predicate symbols *)
type lsymbol = {
ls_name : ident;
ls_args : ty list;
ls_value : ty option;
ls_constr : int;
}
module Lsym = MakeMSHW (struct
type t = lsymbol
let tag ls = ls.ls_name.id_tag
end)
module Sls = Lsym.S
module Mls = Lsym.M
module Hls = Lsym.H
module Wls = Lsym.W
let ls_equal : lsymbol -> lsymbol -> bool = (==)
let ls_hash ls = id_hash ls.ls_name
let ls_compare ls1 ls2 = id_compare ls1.ls_name ls2.ls_name
let check_constr constr _args value =
if constr = 0 || (constr > 0 && value <> None)
then constr else invalid_arg "Term.create_lsymbol"
let create_lsymbol ?(constr=0) name args value = {
ls_name = id_register name;
ls_args = args;
ls_value = value;
ls_constr = check_constr constr args value;
}
let create_fsymbol ?constr nm al vl =
create_lsymbol ?constr nm al (Some vl)
let create_psymbol nm al =
create_lsymbol ~constr:0 nm al None
let ls_ty_freevars ls =
let acc = oty_freevars Stv.empty ls.ls_value in
List.fold_left ty_freevars acc ls.ls_args
(** Patterns *)
type pattern = {
pat_node : pattern_node;
pat_vars : Svs.t;
pat_ty : ty;
}
and pattern_node =
| Pwild (* _ *)
| Pvar of vsymbol (* newly introduced variables *)
| Papp of lsymbol * pattern list (* application *)
| Por of pattern * pattern (* | *)
| Pas of pattern * vsymbol
(* naming a term recognized by pattern as a variable *)
(* h-consing constructors for patterns *)
let mk_pattern n vs ty = {
pat_node = n;
pat_vars = vs;
pat_ty = ty;
}
exception UncoveredVar of vsymbol
exception DuplicateVar of vsymbol
let pat_wild ty = mk_pattern Pwild Svs.empty ty
let pat_var v = mk_pattern (Pvar v) (Svs.singleton v) v.vs_ty
let pat_as p v =
let s = Svs.add_new (DuplicateVar v) v p.pat_vars in
mk_pattern (Pas (p,v)) s v.vs_ty
let pat_or p q =
if Svs.equal p.pat_vars q.pat_vars then
mk_pattern (Por (p,q)) p.pat_vars p.pat_ty
else
let s = Mvs.union (fun _ _ _ -> None) p.pat_vars q.pat_vars in
raise (UncoveredVar (Svs.choose s))
let pat_app f pl ty =
let dup v () () = raise (DuplicateVar v) in
let merge s p = Mvs.union dup s p.pat_vars in
mk_pattern (Papp (f,pl)) (List.fold_left merge Svs.empty pl) ty
(* generic traversal functions *)
let pat_map fn pat = match pat.pat_node with
| Pwild | Pvar _ -> pat
| Papp (s, pl) -> pat_app s (List.map fn pl) pat.pat_ty
| Pas (p, v) -> pat_as (fn p) v
| Por (p, q) -> pat_or (fn p) (fn q)
let pat_map fn = pat_map (fun p ->
let res = fn p in ty_equal_check p.pat_ty res.pat_ty; res)
let pat_fold fn acc pat = match pat.pat_node with
| Pwild | Pvar _ -> acc
| Papp (_, pl) -> List.fold_left fn acc pl
| Pas (p, _) -> fn acc p
| Por (p, q) -> fn (fn acc p) q
let pat_all pr pat = Util.all pat_fold pr pat
let pat_any pr pat = Util.any pat_fold pr pat
(* smart constructors for patterns *)
exception BadArity of lsymbol * int
exception FunctionSymbolExpected of lsymbol
exception PredicateSymbolExpected of lsymbol
exception ConstructorExpected of lsymbol
let pat_app fs pl ty =
let s = match fs.ls_value with
| Some vty -> ty_match Mtv.empty vty ty
| None -> raise (FunctionSymbolExpected fs)
in
let mtch s ty p = ty_match s ty p.pat_ty in
ignore (try List.fold_left2 mtch s fs.ls_args pl with
| Invalid_argument _ -> raise (BadArity (fs, List.length pl)));
if fs.ls_constr = 0 then raise (ConstructorExpected fs);
pat_app fs pl ty
let pat_as p v =
ty_equal_check p.pat_ty v.vs_ty;
pat_as p v
let pat_or p q =
ty_equal_check p.pat_ty q.pat_ty;
pat_or p q
(* rename all variables in a pattern *)
let rec pat_rename_all m p = match p.pat_node with
| Pvar v -> pat_var (Mvs.find v m)
| Pas (p, v) -> pat_as (pat_rename_all m p) (Mvs.find v m)
| _ -> pat_map (pat_rename_all m) p
(* symbol-wise map/fold *)
let rec pat_gen_map fnT fnL m pat =
let fn = pat_gen_map fnT fnL m in
let ty = fnT pat.pat_ty in
match pat.pat_node with
| Pwild -> pat_wild ty
| Pvar v -> pat_var (Mvs.find v m)
| Papp (s, pl) -> pat_app (fnL s) (List.map fn pl) ty
| Pas (p, v) -> pat_as (fn p) (Mvs.find v m)
| Por (p, q) -> pat_or (fn p) (fn q)
let rec pat_gen_fold fnT fnL acc pat =
let fn acc p = pat_gen_fold fnT fnL acc p in
let acc = fnT acc pat.pat_ty in
match pat.pat_node with
| Pwild | Pvar _ -> acc
| Papp (s, pl) -> List.fold_left fn (fnL acc s) pl
| Por (p, q) -> fn (fn acc p) q
| Pas (p, _) -> fn acc p
(** Terms and formulas *)
type quant =
| Tforall
| Texists
type binop =
| Tand
| Tor
| Timplies
| Tiff
type term = {
t_node : term_node;
t_ty : ty option;
t_attrs : Sattr.t;
t_loc : Loc.position option;
}
and term_node =
| Tvar of vsymbol
| Tconst of Number.constant
| Tapp of lsymbol * term list
| Tif of term * term * term
| Tlet of term * term_bound
| Tcase of term * term_branch list
| Teps of term_bound
| Tquant of quant * term_quant
| Tbinop of binop * term * term
| Tnot of term
| Ttrue
| Tfalse
and term_bound = vsymbol * bind_info * term
and term_branch = pattern * bind_info * term
and term_quant = vsymbol list * bind_info * trigger * term
and trigger = term list list
and bind_info = {
bv_vars : int Mvs.t; (* free variables *)
bv_subst : term Mvs.t (* deferred substitution *)
}
(* term equality modulo alpha-equivalence and location *)
exception CompLT
exception CompGT
type frame = int Mvs.t * term Mvs.t
type term_or_bound =
| Trm of term * frame list
| Bnd of int
let rec descend vml t = match t.t_node with
| Tvar vs ->
let rec find vs = function
| (bv,vm)::vml ->
begin match Mvs.find_opt vs bv with
| Some i -> Bnd i
| None ->
begin match Mvs.find_opt vs vm with
| Some t -> descend vml t
| None -> find vs vml
end
end
| [] -> Trm (t, [])
in
find vs vml
| _ -> Trm (t, vml)
let t_compare trigger attr t1 t2 =
let comp_raise c =
if c < 0 then raise CompLT else if c > 0 then raise CompGT in
let perv_compare h1 h2 = comp_raise (Pervasives.compare h1 h2) in
let rec pat_compare (bnd,bv1,bv2 as state) p1 p2 =
match p1.pat_node, p2.pat_node with
| Pwild, Pwild ->
bnd, bv1, bv2
| Pvar v1, Pvar v2 ->
bnd + 1, Mvs.add v1 bnd bv1, Mvs.add v2 bnd bv2
| Papp (s1, l1), Papp (s2, l2) ->
comp_raise (ls_compare s1 s2);
List.fold_left2 pat_compare state l1 l2
| Por (p1, q1), Por (p2, q2) ->
let (_,bv1,bv2 as res) = pat_compare state p1 p2 in
let rec or_cmp q1 q2 = match q1.pat_node, q2.pat_node with
| Pwild, Pwild -> ()
| Pvar v1, Pvar v2 ->
perv_compare (Mvs.find v1 bv1) (Mvs.find v2 bv2)
| Papp (s1, l1), Papp (s2, l2) ->
comp_raise (ls_compare s1 s2);
List.iter2 or_cmp l1 l2
| Por (p1, q1), Por (p2, q2) ->
or_cmp p1 p2; or_cmp q1 q2
| Pas (p1, v1), Pas (p2, v2) ->
or_cmp p1 p2;
perv_compare (Mvs.find v1 bv1) (Mvs.find v2 bv2)
| Pwild, _ -> raise CompLT | _, Pwild -> raise CompGT
| Pvar _, _ -> raise CompLT | _, Pvar _ -> raise CompGT
| Papp _, _ -> raise CompLT | _, Papp _ -> raise CompGT
| Por _, _ -> raise CompLT | _, Por _ -> raise CompGT
in
or_cmp q1 q2;
res
| Pas (p1, v1), Pas (p2, v2) ->
let bnd, bv1, bv2 = pat_compare state p1 p2 in
bnd + 1, Mvs.add v1 bnd bv1, Mvs.add v2 bnd bv2
| Pwild, _ -> raise CompLT | _, Pwild -> raise CompGT
| Pvar _, _ -> raise CompLT | _, Pvar _ -> raise CompGT
| Papp _, _ -> raise CompLT | _, Papp _ -> raise CompGT
| Por _, _ -> raise CompLT | _, Por _ -> raise CompGT
in
let rec t_compare bnd vml1 vml2 t1 t2 =
if t1 != t2 || vml1 <> [] || vml2 <> [] then begin
comp_raise (oty_compare t1.t_ty t2.t_ty);
if attr then comp_raise (Sattr.compare t1.t_attrs t2.t_attrs) else ();
match descend vml1 t1, descend vml2 t2 with
| Bnd i1, Bnd i2 -> perv_compare i1 i2
| Bnd _, Trm _ -> raise CompLT
| Trm _, Bnd _ -> raise CompGT
| Trm (t1,vml1), Trm (t2,vml2) ->
begin match t1.t_node, t2.t_node with
| Tvar v1, Tvar v2 ->
comp_raise (vs_compare v1 v2)
| Tconst c1, Tconst c2 ->
let open Number in
begin match c1, c2 with
| ConstInt { ic_negative = s1; ic_abs = IConstRaw b1 },
ConstInt { ic_negative = s2; ic_abs = IConstRaw b2 } ->
perv_compare s1 s2;
comp_raise (BigInt.compare b1 b2)
| _, _ -> perv_compare c1 c2
end
| Tapp (s1,l1), Tapp (s2,l2) ->
comp_raise (ls_compare s1 s2);
List.iter2 (t_compare bnd vml1 vml2) l1 l2
| Tif (f1,t1,e1), Tif (f2,t2,e2) ->
t_compare bnd vml1 vml2 f1 f2;
t_compare bnd vml1 vml2 t1 t2;
t_compare bnd vml1 vml2 e1 e2
| Tlet (t1,(v1,b1,e1)), Tlet (t2,(v2,b2,e2)) ->
t_compare bnd vml1 vml2 t1 t2;
let vml1 = (Mvs.singleton v1 bnd, b1.bv_subst) :: vml1 in
let vml2 = (Mvs.singleton v2 bnd, b2.bv_subst) :: vml2 in
t_compare (bnd + 1) vml1 vml2 e1 e2
| Tcase (t1,bl1), Tcase (t2,bl2) ->
t_compare bnd vml1 vml2 t1 t2;
let b_compare (p1,b1,t1) (p2,b2,t2) =
let bnd,bv1,bv2 = pat_compare (bnd,Mvs.empty,Mvs.empty) p1 p2 in
let vml1 = (bv1, b1.bv_subst) :: vml1 in
let vml2 = (bv2, b2.bv_subst) :: vml2 in
t_compare bnd vml1 vml2 t1 t2; 0 in
comp_raise (Lists.compare b_compare bl1 bl2)
| Teps (v1,b1,e1), Teps (v2,b2,e2) ->
let vml1 = (Mvs.singleton v1 bnd, b1.bv_subst) :: vml1 in
let vml2 = (Mvs.singleton v2 bnd, b2.bv_subst) :: vml2 in
t_compare (bnd + 1) vml1 vml2 e1 e2
| Tquant (q1,(vl1,b1,tr1,f1)), Tquant (q2,(vl2,b2,tr2,f2)) ->
perv_compare q1 q2;
let rec add bnd bv1 bv2 vl1 vl2 = match vl1, vl2 with
| (v1::vl1), (v2::vl2) ->
let bv1 = Mvs.add v1 bnd bv1 in
let bv2 = Mvs.add v2 bnd bv2 in
add (bnd + 1) bv1 bv2 vl1 vl2
| [], (_::_) -> raise CompLT
| (_::_), [] -> raise CompGT
| [], [] -> bnd, bv1, bv2 in
let bnd, bv1, bv2 = add bnd Mvs.empty Mvs.empty vl1 vl2 in
let vml1 = (bv1, b1.bv_subst) :: vml1 in
let vml2 = (bv2, b2.bv_subst) :: vml2 in
let tr_cmp t1 t2 = t_compare bnd vml1 vml2 t1 t2; 0 in
if trigger then comp_raise (Lists.compare (Lists.compare tr_cmp) tr1 tr2) else ();
t_compare bnd vml1 vml2 f1 f2
| Tbinop (op1,f1,g1), Tbinop (op2,f2,g2) ->
perv_compare op1 op2;
t_compare bnd vml1 vml2 f1 f2;
t_compare bnd vml1 vml2 g1 g2
| Tnot f1, Tnot f2 ->
t_compare bnd vml1 vml2 f1 f2
| Ttrue, Ttrue -> ()
| Tfalse, Tfalse -> ()
| Tvar _, _ -> raise CompLT | _, Tvar _ -> raise CompGT
| Tconst _, _ -> raise CompLT | _, Tconst _ -> raise CompGT
| Tapp _, _ -> raise CompLT | _, Tapp _ -> raise CompGT
| Tif _, _ -> raise CompLT | _, Tif _ -> raise CompGT
| Tlet _, _ -> raise CompLT | _, Tlet _ -> raise CompGT
| Tcase _, _ -> raise CompLT | _, Tcase _ -> raise CompGT
| Teps _, _ -> raise CompLT | _, Teps _ -> raise CompGT
| Tquant _, _ -> raise CompLT | _, Tquant _ -> raise CompGT
| Tbinop _, _ -> raise CompLT | _, Tbinop _ -> raise CompGT
| Tnot _, _ -> raise CompLT | _, Tnot _ -> raise CompGT
| Ttrue, _ -> raise CompLT | _, Ttrue -> raise CompGT
end
end in
try t_compare 0 [] [] t1 t2; 0
with CompLT -> -1 | CompGT -> 1
let t_equal t1 t2 = (t_compare true true t1 t2 = 0)
let t_equal_nt_na t1 t2 = (t_compare false false t1 t2 = 0)
let t_compare = t_compare true true
let t_similar t1 t2 =
oty_equal t1.t_ty t2.t_ty &&
match t1.t_node, t2.t_node with
| Tvar v1, Tvar v2 -> vs_equal v1 v2
| Tconst c1, Tconst c2 -> c1 = c2
| Tapp (s1,l1), Tapp (s2,l2) -> ls_equal s1 s2 && Lists.equal (==) l1 l2
| Tif (f1,t1,e1), Tif (f2,t2,e2) -> f1 == f2 && t1 == t2 && e1 == e2
| Tlet (t1,bv1), Tlet (t2,bv2) -> t1 == t2 && bv1 == bv2
| Tcase (t1,bl1), Tcase (t2,bl2) -> t1 == t2 && Lists.equal (==) bl1 bl2
| Teps bv1, Teps bv2 -> bv1 == bv2
| Tquant (q1,bv1), Tquant (q2,bv2) -> q1 = q2 && bv1 == bv2
| Tbinop (o1,f1,g1), Tbinop (o2,f2,g2) -> o1 = o2 && f1 == f2 && g1 == g2
| Tnot f1, Tnot f2 -> f1 == f2
| Ttrue, Ttrue | Tfalse, Tfalse -> true
| _, _ -> false
let t_hash trigger attr t =
let rec pat_hash bnd bv p = match p.pat_node with
| Pwild -> bnd, bv, 0
| Pvar v -> bnd + 1, Mvs.add v bnd bv, bnd + 1
| Papp (s,l) ->
let hash (bnd,bv,h) p =
let bnd,bv,hp = pat_hash bnd bv p in
bnd, bv, Hashcons.combine h hp in
List.fold_left hash (bnd,bv,ls_hash s) l
| Por (p,q) ->
let bnd,bv,hp = pat_hash bnd bv p in
let rec or_hash q = match q.pat_node with
| Pwild -> 0
| Pvar v -> Mvs.find v bv + 1
| Papp (s,l) -> Hashcons.combine_list or_hash (ls_hash s) l
| Por (p,q) -> Hashcons.combine (or_hash p) (or_hash q)
| Pas (p,v) -> Hashcons.combine (or_hash p) (Mvs.find v bv + 1)
in
bnd, bv, Hashcons.combine hp (or_hash q)
| Pas (p,v) ->
let bnd,bv,hp = pat_hash bnd bv p in
bnd + 1, Mvs.add v bnd bv, Hashcons.combine hp (bnd + 1)
in
let rec t_hash bnd vml t =
let h = oty_hash t.t_ty in
let h =
if attr then
let comb l h = Hashcons.combine (attr_hash l) h in
Sattr.fold comb t.t_attrs h
else h
in
Hashcons.combine h
begin match descend vml t with
| Bnd i -> i + 1
| Trm (t,vml) ->
begin match t.t_node with
| Tvar v -> vs_hash v
| Tconst c -> Hashtbl.hash c
| Tapp (s,l) ->
Hashcons.combine_list (t_hash bnd vml) (ls_hash s) l
| Tif (f,t,e) ->
let hf = t_hash bnd vml f in
let ht = t_hash bnd vml t in
let he = t_hash bnd vml e in
Hashcons.combine2 hf ht he
| Tlet (t,(v,b,e)) ->
let h = t_hash bnd vml t in
let vml = (Mvs.singleton v bnd, b.bv_subst) :: vml in
Hashcons.combine h (t_hash (bnd + 1) vml e)
| Tcase (t,bl) ->
let h = t_hash bnd vml t in
let b_hash (p,b,t) =
let bnd,bv,hp = pat_hash bnd Mvs.empty p in
let vml = (bv, b.bv_subst) :: vml in
Hashcons.combine hp (t_hash bnd vml t) in
Hashcons.combine_list b_hash h bl
| Teps (v,b,e) ->
let vml = (Mvs.singleton v bnd, b.bv_subst) :: vml in
t_hash (bnd + 1) vml e
| Tquant (q,(vl,b,tr,f)) ->
let h = Hashtbl.hash q in
let rec add bnd bv vl = match vl with
| v::vl -> add (bnd + 1) (Mvs.add v bnd bv) vl
| [] -> bnd, bv in
let bnd, bv = add bnd Mvs.empty vl in
let vml = (bv, b.bv_subst) :: vml in
let h =
if trigger then
List.fold_left
(Hashcons.combine_list (t_hash bnd vml)) h tr
else h
in
Hashcons.combine h (t_hash bnd vml f)
| Tbinop (op,f,g) ->
let ho = Hashtbl.hash op in
let hf = t_hash bnd vml f in
let hg = t_hash bnd vml g in
Hashcons.combine2 ho hf hg
| Tnot f ->
Hashcons.combine 1 (t_hash bnd vml f)
| Ttrue -> 2
| Tfalse -> 3
end
end in
t_hash 0 [] t
(* type checking *)
exception TermExpected of term
exception FmlaExpected of term
let t_type t = match t.t_ty with
| Some ty -> ty
| None -> raise (TermExpected t)
let t_prop f =
if f.t_ty = None then f else raise (FmlaExpected f)
let t_ty_check t ty = match ty, t.t_ty with
| Some l, Some r -> ty_equal_check l r
| Some _, None -> raise (TermExpected t)
| None, Some _ -> raise (FmlaExpected t)
| None, None -> ()
let vs_check v t = ty_equal_check v.vs_ty (t_type t)
(* trigger equality and traversal *)
let tr_equal = Lists.equal (Lists.equal t_equal)
let tr_map fn = List.map (List.map fn)
let tr_fold fn = List.fold_left (List.fold_left fn)
let tr_map_fold fn = Lists.map_fold_left (Lists.map_fold_left fn)
(* bind_info equality, hash, and traversal *)
let bnd_map fn bv = { bv with bv_subst = Mvs.map fn bv.bv_subst }
let bnd_fold fn acc bv = Mvs.fold (fun _ t a -> fn a t) bv.bv_subst acc
let bnd_map_fold fn acc bv =
let acc,s = Mvs.mapi_fold (fun _ t a -> fn a t) bv.bv_subst acc in
acc, { bv with bv_subst = s }
(* hash-consing for terms and formulas *)
let vars_union s1 s2 = Mvs.union (fun _ m n -> Some (m + n)) s1 s2
let add_b_vars s (_,b,_) = vars_union s b.bv_vars
let rec t_vars t = match t.t_node with
| Tvar v -> Mvs.singleton v 1
| Tconst _ -> Mvs.empty
| Tapp (_,tl) -> List.fold_left add_t_vars Mvs.empty tl
| Tif (f,t,e) -> add_t_vars (add_t_vars (t_vars f) t) e
| Tlet (t,bt) -> add_b_vars (t_vars t) bt
| Tcase (t,bl) -> List.fold_left add_b_vars (t_vars t) bl
| Teps (_,b,_) -> b.bv_vars
| Tquant (_,(_,b,_,_)) -> b.bv_vars
| Tbinop (_,f1,f2) -> add_t_vars (t_vars f1) f2
| Tnot f -> t_vars f
| Ttrue | Tfalse -> Mvs.empty
and add_t_vars s t = vars_union s (t_vars t)
let add_nt_vars _ n t s = vars_union s
(if n = 1 then t_vars t else Mvs.map (( * ) n) (t_vars t))
module TermOHT = struct
type t = term
let hash = t_hash true true
let equal = t_equal
let compare = t_compare
end
module Mterm = Extmap.Make(TermOHT)
module Sterm = Extset.MakeOfMap(Mterm)
module Hterm = Exthtbl.Make(TermOHT)
module TermOHT_nt_na = struct
type t = term
let hash = t_hash false false
let equal = t_equal_nt_na
end
module Hterm_nt_na = Exthtbl.Make(TermOHT_nt_na)
let t_hash = t_hash true true
(* hash-consing constructors for terms *)
let mk_term n ty = {
t_node = n;
t_attrs = Sattr.empty;
t_loc = None;
t_ty = ty;
}
let t_var v = mk_term (Tvar v) (Some v.vs_ty)
let t_const c ty = mk_term (Tconst c) (Some ty)
let t_app f tl ty = mk_term (Tapp (f, tl)) ty
let t_if f t1 t2 = mk_term (Tif (f, t1, t2)) t2.t_ty
let t_let t1 bt ty = mk_term (Tlet (t1, bt)) ty
let t_case t1 bl ty = mk_term (Tcase (t1, bl)) ty
let t_eps bf ty = mk_term (Teps bf) ty
let t_quant q qf = mk_term (Tquant (q, qf)) None
let t_binary op f g = mk_term (Tbinop (op, f, g)) None
let t_not f = mk_term (Tnot f) None
let t_true = mk_term (Ttrue) None
let t_false = mk_term (Tfalse) None
let t_attr_set ?loc l t = { t with t_attrs = l; t_loc = loc }
let t_attr_add l t = { t with t_attrs = Sattr.add l t.t_attrs }
let t_attr_remove l t = { t with t_attrs = Sattr.remove l t.t_attrs }
let t_attr_copy s t =
if s == t then s else
if t_similar s t && Sattr.is_empty t.t_attrs && t.t_loc = None then s else
let attrs = Sattr.union s.t_attrs t.t_attrs in
let loc = if t.t_loc = None then s.t_loc else t.t_loc in
{ t with t_attrs = attrs; t_loc = loc }
(* unsafe map *)
let bound_map fn (u,b,e) = (u, bnd_map fn b, fn e)
let t_map_unsafe fn t = t_attr_copy t (match t.t_node with
| Tvar _ | Tconst _ -> t
| Tapp (f,tl) -> t_app f (List.map fn tl) t.t_ty
| Tif (f,t1,t2) -> t_if (fn f) (fn t1) (fn t2)
| Tlet (e,b) -> t_let (fn e) (bound_map fn b) t.t_ty
| Tcase (e,bl) -> t_case (fn e) (List.map (bound_map fn) bl) t.t_ty
| Teps b -> t_eps (bound_map fn b) t.t_ty
| Tquant (q,(vl,b,tl,f)) -> t_quant q (vl, bnd_map fn b, tr_map fn tl, fn f)
| Tbinop (op,f1,f2) -> t_binary op (fn f1) (fn f2)
| Tnot f1 -> t_not (fn f1)
| Ttrue | Tfalse -> t)
(* unsafe fold *)
let bound_fold fn acc (_,b,e) = fn (bnd_fold fn acc b) e
let t_fold_unsafe fn acc t = match t.t_node with
| Tvar _ | Tconst _ -> acc
| Tapp (_,tl) -> List.fold_left fn acc tl
| Tif (f,t1,t2) -> fn (fn (fn acc f) t1) t2
| Tlet (e,b) -> fn (bound_fold fn acc b) e
| Tcase (e,bl) -> List.fold_left (bound_fold fn) (fn acc e) bl
| Teps b -> bound_fold fn acc b
| Tquant (_,(_,b,tl,f1)) -> fn (tr_fold fn (bnd_fold fn acc b) tl) f1
| Tbinop (_,f1,f2) -> fn (fn acc f1) f2
| Tnot f1 -> fn acc f1
| Ttrue | Tfalse -> acc
(* unsafe map_fold *)
let bound_map_fold fn acc (u,b,e) =
let acc, b = bnd_map_fold fn acc b in
let acc, e = fn acc e in
acc, (u,b,e)
let t_map_fold_unsafe fn acc t = match t.t_node with
| Tvar _ | Tconst _ ->
acc, t
| Tapp (f,tl) ->
let acc,sl = Lists.map_fold_left fn acc tl in
acc, t_attr_copy t (t_app f sl t.t_ty)
| Tif (f,t1,t2) ->
let acc, g = fn acc f in
let acc, s1 = fn acc t1 in
let acc, s2 = fn acc t2 in
acc, t_attr_copy t (t_if g s1 s2)
| Tlet (e,b) ->
let acc, e = fn acc e in
let acc, b = bound_map_fold fn acc b in
acc, t_attr_copy t (t_let e b t.t_ty)
| Tcase (e,bl) ->
let acc, e = fn acc e in
let acc, bl = Lists.map_fold_left (bound_map_fold fn) acc bl in
acc, t_attr_copy t (t_case e bl t.t_ty)
| Teps b ->
let acc, b = bound_map_fold fn acc b in
acc, t_attr_copy t (t_eps b t.t_ty)
| Tquant (q,(vl,b,tl,f1)) ->
let acc, b = bnd_map_fold fn acc b in
let acc, tl = tr_map_fold fn acc tl in
let acc, f1 = fn acc f1 in
acc, t_attr_copy t (t_quant q (vl,b,tl,f1))
| Tbinop (op,f1,f2) ->
let acc, g1 = fn acc f1 in
let acc, g2 = fn acc f2 in
acc, t_attr_copy t (t_binary op g1 g2)
| Tnot f1 ->
let acc, g1 = fn acc f1 in
acc, t_attr_copy t (t_not g1)
| Ttrue | Tfalse ->
acc, t
(* type-unsafe term substitution *)
let rec t_subst_unsafe m t =
let t_subst t = t_subst_unsafe m t in
let b_subst (u,b,e as bv) =
if Mvs.set_disjoint m b.bv_vars then bv else
(u, bv_subst_unsafe m b, e) in
match t.t_node with
| Tvar u ->
t_attr_copy t (Mvs.find_def t u m)
| Tlet (e, bt) ->
let d = t_subst e in
t_attr_copy t (t_let d (b_subst bt) t.t_ty)
| Tcase (e, bl) ->
let d = t_subst e in
let bl = List.map b_subst bl in
t_attr_copy t (t_case d bl t.t_ty)
| Teps bf ->
t_attr_copy t (t_eps (b_subst bf) t.t_ty)
| Tquant (q, (vl,b,tl,f1 as bq)) ->
let bq =
if Mvs.set_disjoint m b.bv_vars then bq else
(vl,bv_subst_unsafe m b,tl,f1) in
t_attr_copy t (t_quant q bq)
| _ ->
t_map_unsafe t_subst t
and bv_subst_unsafe m b =
(* restrict m to the variables free in b *)
let m = Mvs.set_inter m b.bv_vars in
(* if m is empty, return early *)
if Mvs.is_empty m then b else
(* remove from b.bv_vars the variables replaced by m *)
let s = Mvs.set_diff b.bv_vars m in
(* add to b.bv_vars the free variables added by m *)
let s = Mvs.fold2_inter add_nt_vars b.bv_vars m s in
(* apply m to the terms in b.bv_subst *)
let h = Mvs.map (t_subst_unsafe m) b.bv_subst in
(* join m to b.bv_subst *)
let h = Mvs.set_union h m in
(* reconstruct b *)
{ bv_vars = s ; bv_subst = h }
let t_subst_unsafe m t =
if Mvs.is_empty m then t else t_subst_unsafe m t
(* close bindings *)
let bnd_new s = { bv_vars = s ; bv_subst = Mvs.empty }
let t_close_bound v t = (v, bnd_new (Mvs.remove v (t_vars t)), t)
let t_close_branch p t = (p, bnd_new (Mvs.set_diff (t_vars t) p.pat_vars), t)
let t_close_quant vl tl f =
let del_v s v = Mvs.remove v s in
let s = tr_fold add_t_vars (t_vars f) tl in
let s = List.fold_left del_v s vl in
(vl, bnd_new s, tl, t_prop f)
(* open bindings *)
let fresh_vsymbol v =
create_vsymbol (id_clone v.vs_name) v.vs_ty
let vs_rename h v =
let u = fresh_vsymbol v in
Mvs.add v (t_var u) h, u
let vl_rename h vl =
Lists.map_fold_left vs_rename h vl
let pat_rename h p =
let add_vs v () = fresh_vsymbol v in
let m = Mvs.mapi add_vs p.pat_vars in
let p = pat_rename_all m p in
Mvs.union (fun _ _ t -> Some t) h (Mvs.map t_var m), p
let t_open_bound (v,b,t) =
let m,v = vs_rename b.bv_subst v in
v, t_subst_unsafe m t
let t_open_bound_with e (v,b,t) =
vs_check v e;
let m = Mvs.add v e b.bv_subst in
t_subst_unsafe m t
let t_open_branch (p,b,t) =
let m,p = pat_rename b.bv_subst p in
p, t_subst_unsafe m t
let t_open_quant (vl,b,tl,f) =
let m,vl = vl_rename b.bv_subst vl in
let tl = tr_map (t_subst_unsafe m) tl in
vl, tl, t_subst_unsafe m f
let t_clone_bound_id (v,_,_) = id_clone v.vs_name
(** open bindings with optimized closing callbacks *)
let t_open_bound_cb tb =
let v, t = t_open_bound tb in
let close v' t' =
if t == t' && vs_equal v v' then tb else t_close_bound v' t'
in
v, t, close
let t_open_branch_cb tbr =
let p, t = t_open_branch tbr in
let close p' t' =
if t == t' && p == p' then tbr else t_close_branch p' t'
in
p, t, close
let t_open_quant_cb fq =
let vl, tl, f = t_open_quant fq in
let close vl' tl' f' =
if f == f' &&
Lists.equal (Lists.equal ((==) : term -> term -> bool)) tl tl' &&
Lists.equal vs_equal vl vl'
then fq else t_close_quant vl' tl' f'
in
vl, tl, f, close
(* constructors with type checking *)
let ls_arg_inst ls tl =
let mtch s ty t = ty_match s ty (t_type t) in
try List.fold_left2 mtch Mtv.empty ls.ls_args tl with
| Invalid_argument _ -> raise (BadArity (ls, List.length tl))
let ls_app_inst ls tl ty =
let s = ls_arg_inst ls tl in
match ls.ls_value, ty with
| Some _, None -> raise (PredicateSymbolExpected ls)
| None, Some _ -> raise (FunctionSymbolExpected ls)
| Some vty, Some ty -> ty_match s vty ty
| None, None -> s
let t_app_infer ls tl =
let s = ls_arg_inst ls tl in
t_app ls tl (oty_inst s ls.ls_value)
let t_app ls tl ty = ignore (ls_app_inst ls tl ty); t_app ls tl ty
let fs_app fs tl ty = t_app fs tl (Some ty)
let ps_app ps tl = t_app ps tl None
let t_nat_const n =
assert (n >= 0);
t_const (Number.const_of_int n) ty_int
let t_bigint_const n = t_const (Number.const_of_big_int n) Ty.ty_int
exception InvalidIntegerLiteralType of ty
exception InvalidRealLiteralType of ty
let check_literal c ty =
let ts = match ty.ty_node with
| Tyapp (ts,[]) -> ts
| _ -> match c with
| Number.ConstInt _ -> raise (InvalidIntegerLiteralType ty)
| Number.ConstReal _ -> raise (InvalidRealLiteralType ty)
in
match c with
| Number.ConstInt _ when ts_equal ts ts_int -> ()
| Number.ConstInt n ->
begin match ts.ts_def with
| Range ir -> Number.(check_range n ir)
| _ -> raise (InvalidIntegerLiteralType ty)
end
| Number.ConstReal _ when ts_equal ts ts_real -> ()
| Number.ConstReal x ->
begin match ts.ts_def with
| Float fp -> Number.(check_float x.Number.rc_abs fp)
| _ -> raise (InvalidRealLiteralType ty)
end
let t_const c ty = check_literal c ty; t_const c ty
let t_if f t1 t2 =
t_ty_check t2 t1.t_ty;
t_if (t_prop f) t1 t2
let t_let t1 ((v,_,t2) as bt) =
vs_check v t1;
t_let t1 bt t2.t_ty
exception EmptyCase
let t_case t bl =
let tty = t_type t in
let bty = match bl with
| (_,_,tbr) :: _ -> tbr.t_ty
| _ -> raise EmptyCase
in
let t_check_branch (p,_,tbr) =
ty_equal_check tty p.pat_ty;
t_ty_check tbr bty
in
List.iter t_check_branch bl;
t_case t bl bty
let t_eps ((v,_,f) as bf) =
ignore (t_prop f);
t_eps bf (Some v.vs_ty)
let t_quant q ((vl,_,_,f) as qf) =
if vl = [] then f else t_quant q qf
let t_binary op f1 f2 = t_binary op (t_prop f1) (t_prop f2)
let t_not f = t_not (t_prop f)
let t_forall = t_quant Tforall
let t_exists = t_quant Texists
let t_and = t_binary Tand
let t_or = t_binary Tor
let t_implies = t_binary Timplies
let t_iff = t_binary Tiff
let rec t_and_l = function
| [] -> t_true
| [f] -> f
| f::fl -> t_and f (t_and_l fl)
let rec t_or_l = function
| [] -> t_false
| [f] -> f
| f::fl -> t_or f (t_or_l fl)
let asym_split = create_attribute "asym_split"
let stop_split = create_attribute "stop_split"
let t_and_asym t1 t2 = t_and (t_attr_add asym_split t1) t2
let t_or_asym t1 t2 = t_or (t_attr_add asym_split t1) t2
let rec t_and_asym_l = function
| [] -> t_true
| [f] -> f
| f::fl -> t_and_asym f (t_and_asym_l fl)
let rec t_or_asym_l = function
| [] -> t_false
| [f] -> f
| f::fl -> t_or_asym f (t_or_asym_l fl)
(* closing constructors *)
let t_quant_close q vl tl f =
if vl = [] then t_prop f else t_quant q (t_close_quant vl tl f)
let t_forall_close = t_quant_close Tforall
let t_exists_close = t_quant_close Texists
let t_let_close v t1 t2 = t_let t1 (t_close_bound v t2)
let t_case_close t l = t_case t (List.map (fun (p,e) -> t_close_branch p e) l)
let t_eps_close v f = t_eps (t_close_bound v f)
(* built-in symbols *)
let ps_equ =
let v = ty_var (create_tvsymbol (id_fresh "a")) in
create_psymbol (id_fresh (op_infix "=")) [v; v]
let t_equ t1 t2 = ps_app ps_equ [t1; t2]
let t_neq t1 t2 = t_not (ps_app ps_equ [t1; t2])
let fs_bool_true = create_fsymbol ~constr:2 (id_fresh "True") [] ty_bool
let fs_bool_false = create_fsymbol ~constr:2 (id_fresh "False") [] ty_bool
let t_bool_true = fs_app fs_bool_true [] ty_bool
let t_bool_false = fs_app fs_bool_false [] ty_bool
let fs_tuple_ids = Hid.create 17
let fs_tuple = Hint.memo 17 (fun n ->
let ts = ts_tuple n in
let tl = List.map ty_var ts.ts_args in
let ty = ty_app ts tl in
let id = id_fresh ("Tuple" ^ string_of_int n) in
let fs = create_fsymbol ~constr:1 id tl ty in
Hid.add fs_tuple_ids fs.ls_name n;
fs)
let is_fs_tuple fs =
fs.ls_constr = 1 && Hid.mem fs_tuple_ids fs.ls_name
let is_fs_tuple_id id =
try Some (Hid.find fs_tuple_ids id) with Not_found -> None
let t_tuple tl =
let ty = ty_tuple (List.map t_type tl) in
fs_app (fs_tuple (List.length tl)) tl ty
let fs_func_app =
let ty_a = ty_var (create_tvsymbol (id_fresh "a")) in
let ty_b = ty_var (create_tvsymbol (id_fresh "b")) in
let id = id_fresh (op_infix "@") in
create_fsymbol id [ty_func ty_a ty_b; ty_a] ty_b
let t_func_app fn t = t_app_infer fs_func_app [fn; t]
let t_pred_app pr t = t_equ (t_func_app pr t) t_bool_true
let t_func_app_l fn tl = List.fold_left t_func_app fn tl
let t_pred_app_l pr tl = t_equ (t_func_app_l pr tl) t_bool_true
(** Term library *)
(* generic map over types, symbols and variables *)
let gen_fresh_vsymbol fnT v =
let ty = fnT v.vs_ty in
if ty_equal ty v.vs_ty then v else
create_vsymbol (id_clone v.vs_name) ty
let gen_vs_rename fnT h v =
let u = gen_fresh_vsymbol fnT v in
Mvs.add v u h, u
let gen_vl_rename fnT h vl =
Lists.map_fold_left (gen_vs_rename fnT) h vl
let gen_pat_rename fnT fnL h p =
let add_vs v () = gen_fresh_vsymbol fnT v in
let m = Mvs.mapi add_vs p.pat_vars in
let p = pat_gen_map fnT fnL m p in
Mvs.union (fun _ _ t -> Some t) h m, p
let gen_bnd_rename fnT fnE h b =
let add_bv v n m = Mvs.add (Mvs.find v h) n m in
let bvs = Mvs.fold add_bv b.bv_vars Mvs.empty in
let add_bs v t (nh, m) =
let nh,v = gen_vs_rename fnT nh v in
nh, Mvs.add v (fnE t) m
in
let h,bsb = Mvs.fold add_bs b.bv_subst (h,Mvs.empty) in
h, { bv_vars = bvs ; bv_subst = bsb }
let rec t_gen_map fnT fnL m t =
let fn = t_gen_map fnT fnL m in
t_attr_copy t (match t.t_node with
| Tvar v ->
let u = Mvs.find_def v v m in
ty_equal_check (fnT v.vs_ty) u.vs_ty;
t_var u
| Tconst _ ->
t
| Tapp (fs, tl) ->
t_app (fnL fs) (List.map fn tl) (Opt.map fnT t.t_ty)
| Tif (f, t1, t2) ->
t_if (fn f) (fn t1) (fn t2)
| Tlet (t1, (u,b,t2)) ->
let m,b = gen_bnd_rename fnT fn m b in
let m,u = gen_vs_rename fnT m u in
t_let (fn t1) (u, b, t_gen_map fnT fnL m t2)
| Tcase (t1, bl) ->
let fn_br (p,b,t2) =
let m,b = gen_bnd_rename fnT fn m b in
let m,p = gen_pat_rename fnT fnL m p in
(p, b, t_gen_map fnT fnL m t2)
in
t_case (fn t1) (List.map fn_br bl)
| Teps (u,b,f) ->
let m,b = gen_bnd_rename fnT fn m b in
let m,u = gen_vs_rename fnT m u in
t_eps (u, b, t_gen_map fnT fnL m f)
| Tquant (q, (vl,b,tl,f)) ->
let m,b = gen_bnd_rename fnT fn m b in
let m,vl = gen_vl_rename fnT m vl in
let fn = t_gen_map fnT fnL m in
t_quant q (vl, b, tr_map fn tl, fn f)
| Tbinop (op, f1, f2) ->
t_binary op (fn f1) (fn f2)
| Tnot f1 ->
t_not (fn f1)
| Ttrue | Tfalse ->
t)
let t_gen_map fnT fnL mapV t = t_gen_map (Wty.memoize 17 fnT) fnL mapV t
(* map over type and logic symbols *)
let gen_mapV fnT = Mvs.mapi (fun v _ -> gen_fresh_vsymbol fnT v)
let t_s_map fnT fnL t = t_gen_map fnT fnL (gen_mapV fnT (t_vars t)) t
(* simultaneous substitution into types and terms *)
let t_subst_types mapT mapV t =
let fnT = ty_inst mapT in
let m = gen_mapV fnT (t_vars t) in
let t = t_gen_map fnT (fun ls -> ls) m t in
let add _ v t m = vs_check v t; Mvs.add v t m in
let m = Mvs.fold2_inter add m mapV Mvs.empty in
(m,t)
let t_ty_subst mapT mapV t =
let m,t = t_subst_types mapT mapV t in
t_subst_unsafe m t
(* fold over symbols *)
let rec t_gen_fold fnT fnL acc t =
let fn = t_gen_fold fnT fnL in
let acc = Opt.fold fnT acc t.t_ty in
match t.t_node with
| Tconst _ | Tvar _ -> acc
| Tapp (f, tl) -> List.fold_left fn (fnL acc f) tl
| Tif (f, t1, t2) -> fn (fn (fn acc f) t1) t2
| Tlet (t1, (_,b,t2)) -> fn (bnd_fold fn (fn acc t1) b) t2
| Tcase (t1, bl) ->
let branch acc (p,b,t) =
fn (pat_gen_fold fnT fnL (bnd_fold fn acc b) p) t in
List.fold_left branch (fn acc t1) bl
| Teps (_,b,f) -> fn (bnd_fold fn acc b) f
| Tquant (_, (vl,b,tl,f1)) ->
(* these variables (and their types) may never appear below *)
let acc = List.fold_left (fun a v -> fnT a v.vs_ty) acc vl in
fn (tr_fold fn (bnd_fold fn acc b) tl) f1
| Tbinop (_, f1, f2) -> fn (fn acc f1) f2
| Tnot f1 -> fn acc f1
| Ttrue | Tfalse -> acc
let t_s_fold = t_gen_fold
let t_s_all prT prL t = Util.alld t_s_fold prT prL t
let t_s_any prT prL t = Util.anyd t_s_fold prT prL t
(* map/fold over types in terms and formulas *)
let t_ty_map fn t = t_s_map fn (fun ls -> ls) t
let t_ty_fold fn acc t = t_s_fold fn Util.const acc t
let t_ty_freevars = t_ty_fold ty_freevars
(* map/fold over applications in terms and formulas (but not in patterns!) *)
let rec t_app_map fn t =
let t = t_map_unsafe (t_app_map fn) t in
match t.t_node with
| Tapp (ls,tl) ->
let ls = fn ls (List.map t_type tl) t.t_ty in
t_attr_copy t (t_app ls tl t.t_ty)
| _ -> t
let rec t_app_fold fn acc t =
let acc = t_fold_unsafe (t_app_fold fn) acc t in
match t.t_node with
| Tapp (ls,tl) -> fn acc ls (List.map t_type tl) t.t_ty
| _ -> acc
(* Type- and binding-safe traversal *)
let t_map fn t = match t.t_node with
| Tlet (t1, b) ->
let u,t2 = t_open_bound b in
let s1 = fn t1 and s2 = fn t2 in
if s2 == t2
then if s1 == t1 then t
else t_attr_copy t (t_let s1 b)
else t_attr_copy t (t_let_close u s1 s2)
| Tcase (t1, bl) ->
let s1 = fn t1 in
let brn same b =
let p,t = t_open_branch b in
let s = fn t in
if s == t then same, b
else false, t_close_branch p s
in
let same, bl = Lists.map_fold_left brn true bl in
if s1 == t1 && same then t
else t_attr_copy t (t_case s1 bl)
| Teps b ->
let u,t1 = t_open_bound b in
let s1 = fn t1 in
if s1 == t1 then t
else t_attr_copy t (t_eps_close u s1)
| Tquant (q, b) ->
let vl,tl,f1 = t_open_quant b in
let g1 = fn f1 and sl = tr_map fn tl in
if g1 == f1 && List.for_all2 (List.for_all2 (==)) sl tl then t
else t_attr_copy t (t_quant_close q vl sl g1)
| _ ->
t_map_unsafe fn t
let t_map fn = t_map (fun t ->
let res = fn t in t_ty_check res t.t_ty; res)
(* safe opening fold *)
let t_fold fn acc t = match t.t_node with
| Tlet (t1, b) ->
let _,t2 = t_open_bound b in fn (fn acc t1) t2
| Tcase (t1, bl) ->
let brn acc b = let _,t = t_open_branch b in fn acc t in
List.fold_left brn (fn acc t1) bl
| Teps b ->
let _,f = t_open_bound b in fn acc f
| Tquant (_, b) ->
let _, tl, f1 = t_open_quant b in tr_fold fn (fn acc f1) tl
| _ -> t_fold_unsafe fn acc t
let t_iter fn t = t_fold (fun () t -> fn t) () t
let t_all pr t = Util.all t_fold pr t
let t_any pr t = Util.any t_fold pr t
(* safe opening map_fold *)
let t_map_fold fn acc t = match t.t_node with
| Tlet (t1, b) ->
let acc, s1 = fn acc t1 in
let u,t2 = t_open_bound b in
let acc, s2 = fn acc t2 in
acc, if s2 == t2
then if s1 == t1 then t
else t_attr_copy t (t_let s1 b)
else t_attr_copy t (t_let_close u s1 s2)
| Tcase (t1, bl) ->
let acc, s1 = fn acc t1 in
let brn (acc,same) b =
let p,t = t_open_branch b in
let acc, s = fn acc t in
if s == t then (acc,same), b
else (acc,false), t_close_branch p s
in
let (acc,same), bl = Lists.map_fold_left brn (acc,true) bl in
acc, if s1 == t1 && same then t
else t_attr_copy t (t_case s1 bl)
| Teps b ->
let u,t1 = t_open_bound b in
let acc, s1 = fn acc t1 in
acc, if s1 == t1 then t
else t_attr_copy t (t_eps_close u s1)
| Tquant (q, b) ->
let vl,tl,f1 = t_open_quant b in
let acc, sl = tr_map_fold fn acc tl in
let acc, g1 = fn acc f1 in
acc, if g1 == f1 && List.for_all2 (List.for_all2 (==)) sl tl
then t else t_attr_copy t (t_quant_close q vl sl g1)
| _ -> t_map_fold_unsafe fn acc t
let t_map_fold fn = t_map_fold (fun acc t ->
let res = fn acc t in t_ty_check (snd res) t.t_ty; res)
(* polarity map *)
let t_map_sign fn sign f = t_attr_copy f (match f.t_node with
| Tbinop (Timplies, f1, f2) ->
t_implies (fn (not sign) f1) (fn sign f2)
| Tbinop (Tiff, f1, f2) ->
let f1p = fn sign f1 in let f1n = fn (not sign) f1 in
let f2p = fn sign f2 in let f2n = fn (not sign) f2 in
if t_equal f1p f1n && t_equal f2p f2n then t_iff f1p f2p
else if sign
then t_and (t_implies f1n f2p) (t_implies f2n f1p)
else t_implies (t_or f1n f2n) (t_and f1p f2p)
| Tnot f1 ->
t_not (fn (not sign) f1)
| Tif (f1, f2, f3) when f.t_ty = None ->
let f1p = fn sign f1 in let f1n = fn (not sign) f1 in
let f2 = fn sign f2 in let f3 = fn sign f3 in
if t_equal f1p f1n then t_if f1p f2 f3 else if sign
then t_and (t_implies f1n f2) (t_implies (t_not f1p) f3)
else t_or (t_and f1p f2) (t_and (t_not f1n) f3)
| Tif _
| Teps _ -> failwith "t_map_sign: cannot determine polarity"
| _ -> t_map (fn sign) f)
(* continuation-passing traversal *)
let rec list_map_cont fnL contL = function
| e::el ->
let cont_l e el = contL (e::el) in
let cont_e e = list_map_cont fnL (cont_l e) el in
fnL cont_e e
| [] ->
contL []
let t_map_cont fn contT t =
let contT e = contT (t_attr_copy t e) in
match t.t_node with
| Tvar _ | Tconst _ -> contT t
| Tapp (fs, tl) ->
let cont_app tl = contT (t_app fs tl t.t_ty) in
list_map_cont fn cont_app tl
| Tif (f, t1, t2) ->
let cont_else f t1 t2 = contT (t_if f t1 t2) in
let cont_then f t1 = fn (cont_else f t1) t2 in
let cont_if f = fn (cont_then f) t1 in
fn cont_if f
| Tlet (t1, b) ->
let u,t2,close = t_open_bound_cb b in
let cont_in t1 t2 = contT (t_let t1 (close u t2)) in
let cont_let t1 = fn (cont_in t1) t2 in
fn cont_let t1
| Tcase (t1, bl) ->
let fnB contB b =
let pat,t,close = t_open_branch_cb b in
fn (fun t -> contB (close pat t)) t
in
let cont_with t1 bl = contT (t_case t1 bl) in
let cont_case t1 = list_map_cont fnB (cont_with t1) bl in
fn cont_case t1
| Teps b ->
let u,f,close = t_open_bound_cb b in
let cont_eps f = contT (t_eps (close u f)) in
fn cont_eps f
| Tquant (q, b) ->
let vl, tl, f1, close = t_open_quant_cb b in
let cont_dot tl f1 = contT (t_quant q (close vl tl f1)) in
let cont_quant tl = fn (cont_dot tl) f1 in
list_map_cont (list_map_cont fn) cont_quant tl
| Tbinop (op, f1, f2) ->
let cont_r f1 f2 = contT (t_binary op f1 f2) in
let cont_l f1 = fn (cont_r f1) f2 in
fn cont_l f1
| Tnot f1 ->
let cont_not f1 = contT (t_not f1) in
fn cont_not f1
| Ttrue | Tfalse -> contT t
let t_map_cont fn = t_map_cont (fun cont t ->
fn (fun e -> t_ty_check e t.t_ty; cont e) t)
(* map/fold over free variables *)
let t_v_map fn t =
let fn v _ = let res = fn v in vs_check v res; res in
t_subst_unsafe (Mvs.mapi fn (t_vars t)) t
let bnd_v_fold fn acc b = Mvs.fold (fun v _ acc -> fn acc v) b.bv_vars acc
let bound_v_fold fn acc (_,b,_) = bnd_v_fold fn acc b
let rec t_v_fold fn acc t = match t.t_node with
| Tvar v -> fn acc v
| Tlet (e,b) -> bound_v_fold fn (t_v_fold fn acc e) b
| Tcase (e,bl) -> List.fold_left (bound_v_fold fn) (t_v_fold fn acc e) bl
| Teps b -> bound_v_fold fn acc b
| Tquant (_,(_,b,_,_)) -> bnd_v_fold fn acc b
| _ -> t_fold_unsafe (t_v_fold fn) acc t
let t_v_all pr t = Util.all t_v_fold pr t
let t_v_any pr t = Util.any t_v_fold pr t
let t_closed t = t_v_all Util.ffalse t
let bnd_v_count fn acc b = Mvs.fold (fun v n acc -> fn acc v n) b.bv_vars acc
let bound_v_count fn acc (_,b,_) = bnd_v_count fn acc b
let rec t_v_count fn acc t = match t.t_node with
| Tvar v -> fn acc v 1
| Tlet (e,b) -> bound_v_count fn (t_v_count fn acc e) b
| Tcase (e,bl) -> List.fold_left (bound_v_count fn) (t_v_count fn acc e) bl
| Teps b -> bound_v_count fn acc b
| Tquant (_,(_,b,_,_)) -> bnd_v_count fn acc b
| _ -> t_fold_unsafe (t_v_count fn) acc t
let t_v_occurs v t =
t_v_count (fun c u n -> if vs_equal u v then c + n else c) 0 t
(* replaces variables with terms in term [t] using map [m] *)
let t_subst m t = Mvs.iter vs_check m; t_subst_unsafe m t
let t_subst_single v t1 t = t_subst (Mvs.singleton v t1) t
(* set of free variables *)
let t_freevars = add_t_vars
(* occurrence check *)
let rec t_occurs r t =
t_equal r t || t_any (t_occurs r) t
(* substitutes term [t2] for term [t1] in term [t] *)
let rec t_replace t1 t2 t =
if t_equal t t1 then t2 else t_map (t_replace t1 t2) t
let t_replace t1 t2 t =
t_ty_check t2 t1.t_ty;
t_replace t1 t2 t
(* lambdas *)
let t_lambda vl trl t =
let ty = Opt.get_def ty_bool t.t_ty in
let add_ty v ty = ty_func v.vs_ty ty in
let ty = List.fold_right add_ty vl ty in
let fc = create_vsymbol (id_fresh "fc") ty in
let copy_loc e = if t.t_loc = None then e
else t_attr_set ?loc:t.t_loc e.t_attrs e in
let mk_t_var v = if v.vs_name.id_loc = None then t_var v
else t_attr_set ?loc:v.vs_name.id_loc Sattr.empty (t_var v) in
let add_arg h v = copy_loc (t_func_app h (mk_t_var v)) in
let h = List.fold_left add_arg (mk_t_var fc) vl in
let f = match t.t_ty with
| Some _ -> t_equ h t
| None -> t_iff (copy_loc (t_equ h t_bool_true)) t in
t_eps_close fc (copy_loc (t_forall_close vl trl (copy_loc f)))
let t_lambda vl trl t =
let t = match t.t_node with
| Tapp (ps,[l;{t_node = Tapp (fs,[])}])
when ls_equal ps ps_equ && ls_equal fs fs_bool_true ->
t_attr_copy t l
| _ -> t in
if vl <> [] then t_lambda vl trl t
else if t.t_ty <> None then t
else t_if t t_bool_true t_bool_false
let t_open_lambda t = match t.t_ty, t.t_node with
| Some {ty_node = Tyapp (ts,_)}, Teps fb when ts_equal ts ts_func ->
let fc,f = t_open_bound fb in
let vl,trl,f = match f.t_node with
| Tquant (Tforall,fq) -> t_open_quant fq
| _ -> [], [], t (* fail the next check *) in
let h,e = match f.t_node with
| Tapp (ps,[h;e]) when ls_equal ps ps_equ -> h, e
| Tbinop (Tiff,{t_node = Tapp (ps,[h;{t_node = Tapp (fs,[])}])},e)
when ls_equal ps ps_equ && ls_equal fs fs_bool_true -> h, e
| _ -> t, t (* fail the next check *) in
let rec check h xl = match h.t_node, xl with
| Tapp (fs,[h;{t_node = Tvar u}]), x::xl
when ls_equal fs fs_func_app && vs_equal u x -> check h xl
| Tvar u, [] when vs_equal u fc && t_v_occurs u e = 0 -> vl, trl, e
| _ -> [], [], t in
check h (List.rev vl)
| _ -> [], [], t
(* it is rather tricky to check if a term is a lambda without properly
opening the binders. The deferred substitution in the quantifier
may obscure the closure variable or, on the contrary, introduce it
on the RHS of the definition, making it recursive. We cannot simply
reject such deferred substitutions, because the closure variable is
allowed in the triggers and it can appear there via the deferred
substitution, why not? Therefore, t_is_lambda is a mere shim around
t_open_lambda. *)
let t_is_lambda t = let vl,_,_ = t_open_lambda t in vl <> []
let t_open_lambda_cb t =
let vl, trl, e = t_open_lambda t in
let close vl' trl' e' =
if e == e' &&
Lists.equal (Lists.equal ((==) : term -> term -> bool)) trl trl' &&
Lists.equal vs_equal vl vl'
then t else t_lambda vl' trl' e' in
vl, trl, e, close
let t_closure ls tyl ty =
let mk_v i ty = create_vsymbol (id_fresh ("y" ^ string_of_int i)) ty in
let vl = Lists.mapi mk_v tyl in
let t = t_app ls (List.map t_var vl) ty in
t_lambda vl [] t
let t_app_partial ls tl tyl ty =
if tyl = [] then t_app ls tl ty else
match tl with
| [t] when ls_equal ls fs_func_app -> t
| _ ->
let cons t tyl = t_type t :: tyl in
let tyl = List.fold_right cons tl tyl in
t_func_app_l (t_closure ls tyl ty) tl
let rec t_app_beta_l lam tl =
if tl = [] then lam else
let vl, trl, e = t_open_lambda lam in
if vl = [] then t_func_app_l lam tl else
let rec add m vl tl = match vl, tl with
| [], tl ->
t_app_beta_l (t_subst_unsafe m e) tl
| vl, [] ->
let trl = List.map (List.map (t_subst_unsafe m)) trl in
t_lambda vl trl (t_subst_unsafe m e)
| v::vl, t::tl ->
vs_check v t; add (Mvs.add v t m) vl tl in
add Mvs.empty vl tl
let t_func_app_beta_l lam tl =
let e = t_app_beta_l lam tl in
if e.t_ty = None then t_if e t_bool_true t_bool_false else e
let t_pred_app_beta_l lam tl =
let e = t_app_beta_l lam tl in
if e.t_ty = None then e else t_equ e t_bool_true
let t_func_app_beta lam t = t_func_app_beta_l lam [t]
let t_pred_app_beta lam t = t_pred_app_beta_l lam [t]
(* constructors with propositional simplification *)
let t_not_simp f = match f.t_node with
| Ttrue -> t_attr_copy f t_false
| Tfalse -> t_attr_copy f t_true
| Tnot g -> t_attr_copy f g
| _ -> t_not f
let t_and_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> t_attr_remove asym_split f1
| Tfalse, _ -> t_attr_remove asym_split f1
| _, Tfalse -> f2
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_and f1 f2
let t_and_simp_l l = List.fold_right t_and_simp l t_true
let t_or_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> t_attr_remove asym_split f1
| _, Ttrue -> f2
| Tfalse, _ -> f2
| _, Tfalse -> t_attr_remove asym_split f1
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_or f1 f2
let t_or_simp_l l = List.fold_right t_or_simp l t_false
let t_and_asym_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> t_attr_remove asym_split f1
| Tfalse, _ -> t_attr_remove asym_split f1
| _, Tfalse -> f2
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_and_asym f1 f2
let t_and_asym_simp_l l = List.fold_right t_and_asym_simp l t_true
let t_or_asym_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> t_attr_remove asym_split f1
| _, Ttrue -> f2
| Tfalse, _ -> f2
| _, Tfalse -> t_attr_remove asym_split f1
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_or_asym f1 f2
let t_or_asym_simp_l l = List.fold_right t_or_asym_simp l t_false
let t_implies_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> f2
| Tfalse, _ -> t_attr_copy f1 t_true
| _, Tfalse -> t_not_simp f1
| _, _ when t_equal f1 f2 -> t_attr_copy f1 t_true
| _, _ -> t_implies f1 f2
let t_iff_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> f1
| Tfalse, _ -> t_not_simp f2
| _, Tfalse -> t_not_simp f1
| _, _ when t_equal f1 f2 -> t_attr_copy f1 t_true
| _, _ -> t_iff f1 f2
let t_binary_simp op = match op with
| Tand -> t_and_simp
| Tor -> t_or_simp
| Timplies -> t_implies_simp
| Tiff -> t_iff_simp
let t_if_simp f1 f2 f3 = match f1.t_node, f2.t_node, f3.t_node with
| Ttrue, _, _ -> f2
| Tfalse, _, _ -> f3
| _, Ttrue, _ -> t_implies_simp (t_not_simp f1) f3
| _, Tfalse, _ -> t_and_asym_simp (t_not_simp f1) f3
| _, _, Ttrue -> t_implies_simp f1 f2
| _, _, Tfalse -> t_and_asym_simp f1 f2
| _, _, _ when t_equal f2 f3 -> f2
| _, _, _ -> t_if f1 f2 f3
let small t = match t.t_node with
| Tvar _ | Tconst _ -> true
(* NOTE: shouldn't we allow this?
| Tapp (_,[]) -> true
*)
| _ -> false
let t_let_simp e ((v,b,t) as bt) =
let n = t_v_occurs v t in
if n = 0 then
t_subst_unsafe b.bv_subst t else
if n = 1 || small e then begin
vs_check v e;
t_subst_unsafe (Mvs.add v e b.bv_subst) t
end else
t_let e bt
let t_let_close_simp v e t =
let n = t_v_occurs v t in
if n = 0 then t else
if n = 1 || small e then
t_subst_single v e t
else
t_let_close v e t
let t_case_simp t bl =
let e0,tl = match bl with
| [] -> raise EmptyCase
| (_,_,e0)::tl -> e0,tl in
let e0_true = match e0.t_node with
| Ttrue -> true | _ -> false in
let e0_false = match e0.t_node with
| Tfalse -> true | _ -> false in
let is_e0 (_,_,e) = match e.t_node with
| Ttrue -> e0_true
| Tfalse -> e0_false
| _ -> t_equal e e0 in
if t_closed e0 && List.for_all is_e0 tl then e0
else t_case t bl
let t_case_close_simp t bl =
let e0,tl = match bl with
| [] -> raise EmptyCase
| (_,e0)::tl -> e0,tl in
let e0_true = match e0.t_node with
| Ttrue -> true | _ -> false in
let e0_false = match e0.t_node with
| Tfalse -> true | _ -> false in
let is_e0 (_,e) = match e.t_node with
| Ttrue -> e0_true
| Tfalse -> e0_false
| _ -> t_equal e e0 in
if t_closed e0 && List.for_all is_e0 tl then e0
else t_case_close t bl
let t_quant_simp q ((vl,_,_,f) as qf) =
let fvs = t_vars f in
let check v = Mvs.mem v fvs in
if List.for_all check vl then
t_quant q qf
else
let vl,tl,f = t_open_quant qf in
let fvs = t_vars f in
let check v = Mvs.mem v fvs in
let vl = List.filter check vl in
if vl = [] then f
else t_quant_close q vl (List.filter (List.for_all (t_v_all check)) tl) f
let t_quant_close_simp q vl tl f =
if vl = [] then f else
let fvs = t_vars f in
let check v = Mvs.mem v fvs in
if List.for_all check vl then
t_quant_close q vl tl f
else
let vl = List.filter check vl in
if vl = [] then f
else t_quant_close q vl (List.filter (List.for_all (t_v_all check)) tl) f
let t_forall_simp = t_quant_simp Tforall
let t_exists_simp = t_quant_simp Texists
let t_forall_close_simp = t_quant_close_simp Tforall
let t_exists_close_simp = t_quant_close_simp Texists
let t_equ_simp t1 t2 =
if t_equal t1 t2 then t_true else t_equ t1 t2
let t_neq_simp t1 t2 =
if t_equal t1 t2 then t_false else t_neq t1 t2
let t_forall_close_merge vs f = match f.t_node with
| Tquant (Tforall, fq) ->
let vs', trs, f = t_open_quant fq in
t_forall_close (vs@vs') trs f
| _ -> t_forall_close vs [] f
let t_exists_close_merge vs f = match f.t_node with
| Tquant (Texists, fq) ->
let vs', trs, f = t_open_quant fq in
t_exists_close (vs@vs') trs f
| _ -> t_exists_close vs [] f
let t_map_simp fn f = t_attr_copy f (match f.t_node with
| Tapp (p, [t1;t2]) when ls_equal p ps_equ ->
t_equ_simp (fn t1) (fn t2)
| Tif (f1, f2, f3) ->
t_if_simp (fn f1) (fn f2) (fn f3)
| Tlet (t, b) ->
let u,t2,close = t_open_bound_cb b in
t_let_simp (fn t) (close u (fn t2))
| Tquant (q, b) ->
let vl,tl,f1,close = t_open_quant_cb b in
t_quant_simp q (close vl (tr_map fn tl) (fn f1))
| Tbinop (op, f1, f2) ->
t_binary_simp op (fn f1) (fn f2)
| Tnot f1 ->
t_not_simp (fn f1)
| _ -> t_map fn f)
let t_map_simp fn = t_map_simp (fun t ->
let res = fn t in t_ty_check res t.t_ty; res)
(** Traversal with separate functions for value-typed and prop-typed terms *)
module TermTF = struct
let t_select fnT fnF e =
if e.t_ty = None then fnF e else fnT e
let t_selecti fnT fnF acc e =
if e.t_ty = None then fnF acc e else fnT acc e
let t_map fnT fnF = t_map (t_select fnT fnF)
let t_fold fnT fnF = t_fold (t_selecti fnT fnF)
let t_map_fold fnT fnF = t_map_fold (t_selecti fnT fnF)
let t_all prT prF = t_all (t_select prT prF)
let t_any prT prF = t_any (t_select prT prF)
let t_map_simp fnT fnF = t_map_simp (t_select fnT fnF)
let t_map_sign fnT fnF = t_map_sign (t_selecti fnT fnF)
let t_map_cont fnT fnF = t_map_cont (t_selecti fnT fnF)
let tr_map fnT fnF = tr_map (t_select fnT fnF)
let tr_fold fnT fnF = tr_fold (t_selecti fnT fnF)
let tr_map_fold fnT fnF = tr_map_fold (t_selecti fnT fnF)
end
| null | https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/core/term.ml | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
******************************************************************
* Variable symbols
* Function and predicate symbols
* Patterns
_
newly introduced variables
application
|
naming a term recognized by pattern as a variable
h-consing constructors for patterns
generic traversal functions
smart constructors for patterns
rename all variables in a pattern
symbol-wise map/fold
* Terms and formulas
free variables
deferred substitution
term equality modulo alpha-equivalence and location
type checking
trigger equality and traversal
bind_info equality, hash, and traversal
hash-consing for terms and formulas
hash-consing constructors for terms
unsafe map
unsafe fold
unsafe map_fold
type-unsafe term substitution
restrict m to the variables free in b
if m is empty, return early
remove from b.bv_vars the variables replaced by m
add to b.bv_vars the free variables added by m
apply m to the terms in b.bv_subst
join m to b.bv_subst
reconstruct b
close bindings
open bindings
* open bindings with optimized closing callbacks
constructors with type checking
closing constructors
built-in symbols
* Term library
generic map over types, symbols and variables
map over type and logic symbols
simultaneous substitution into types and terms
fold over symbols
these variables (and their types) may never appear below
map/fold over types in terms and formulas
map/fold over applications in terms and formulas (but not in patterns!)
Type- and binding-safe traversal
safe opening fold
safe opening map_fold
polarity map
continuation-passing traversal
map/fold over free variables
replaces variables with terms in term [t] using map [m]
set of free variables
occurrence check
substitutes term [t2] for term [t1] in term [t]
lambdas
fail the next check
fail the next check
it is rather tricky to check if a term is a lambda without properly
opening the binders. The deferred substitution in the quantifier
may obscure the closure variable or, on the contrary, introduce it
on the RHS of the definition, making it recursive. We cannot simply
reject such deferred substitutions, because the closure variable is
allowed in the triggers and it can appear there via the deferred
substitution, why not? Therefore, t_is_lambda is a mere shim around
t_open_lambda.
constructors with propositional simplification
NOTE: shouldn't we allow this?
| Tapp (_,[]) -> true
* Traversal with separate functions for value-typed and prop-typed terms | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
General Public License version 2.1 , with the special exception
open Wstdlib
open Ident
open Ty
type vsymbol = {
vs_name : ident;
vs_ty : ty;
}
module Vsym = MakeMSHW (struct
type t = vsymbol
let tag vs = vs.vs_name.id_tag
end)
module Svs = Vsym.S
module Mvs = Vsym.M
module Hvs = Vsym.H
module Wvs = Vsym.W
let vs_equal : vsymbol -> vsymbol -> bool = (==)
let vs_hash vs = id_hash vs.vs_name
let vs_compare vs1 vs2 = id_compare vs1.vs_name vs2.vs_name
let create_vsymbol name ty = {
vs_name = id_register name;
vs_ty = ty;
}
type lsymbol = {
ls_name : ident;
ls_args : ty list;
ls_value : ty option;
ls_constr : int;
}
module Lsym = MakeMSHW (struct
type t = lsymbol
let tag ls = ls.ls_name.id_tag
end)
module Sls = Lsym.S
module Mls = Lsym.M
module Hls = Lsym.H
module Wls = Lsym.W
let ls_equal : lsymbol -> lsymbol -> bool = (==)
let ls_hash ls = id_hash ls.ls_name
let ls_compare ls1 ls2 = id_compare ls1.ls_name ls2.ls_name
let check_constr constr _args value =
if constr = 0 || (constr > 0 && value <> None)
then constr else invalid_arg "Term.create_lsymbol"
let create_lsymbol ?(constr=0) name args value = {
ls_name = id_register name;
ls_args = args;
ls_value = value;
ls_constr = check_constr constr args value;
}
let create_fsymbol ?constr nm al vl =
create_lsymbol ?constr nm al (Some vl)
let create_psymbol nm al =
create_lsymbol ~constr:0 nm al None
let ls_ty_freevars ls =
let acc = oty_freevars Stv.empty ls.ls_value in
List.fold_left ty_freevars acc ls.ls_args
type pattern = {
pat_node : pattern_node;
pat_vars : Svs.t;
pat_ty : ty;
}
and pattern_node =
| Pas of pattern * vsymbol
let mk_pattern n vs ty = {
pat_node = n;
pat_vars = vs;
pat_ty = ty;
}
exception UncoveredVar of vsymbol
exception DuplicateVar of vsymbol
let pat_wild ty = mk_pattern Pwild Svs.empty ty
let pat_var v = mk_pattern (Pvar v) (Svs.singleton v) v.vs_ty
let pat_as p v =
let s = Svs.add_new (DuplicateVar v) v p.pat_vars in
mk_pattern (Pas (p,v)) s v.vs_ty
let pat_or p q =
if Svs.equal p.pat_vars q.pat_vars then
mk_pattern (Por (p,q)) p.pat_vars p.pat_ty
else
let s = Mvs.union (fun _ _ _ -> None) p.pat_vars q.pat_vars in
raise (UncoveredVar (Svs.choose s))
let pat_app f pl ty =
let dup v () () = raise (DuplicateVar v) in
let merge s p = Mvs.union dup s p.pat_vars in
mk_pattern (Papp (f,pl)) (List.fold_left merge Svs.empty pl) ty
let pat_map fn pat = match pat.pat_node with
| Pwild | Pvar _ -> pat
| Papp (s, pl) -> pat_app s (List.map fn pl) pat.pat_ty
| Pas (p, v) -> pat_as (fn p) v
| Por (p, q) -> pat_or (fn p) (fn q)
let pat_map fn = pat_map (fun p ->
let res = fn p in ty_equal_check p.pat_ty res.pat_ty; res)
let pat_fold fn acc pat = match pat.pat_node with
| Pwild | Pvar _ -> acc
| Papp (_, pl) -> List.fold_left fn acc pl
| Pas (p, _) -> fn acc p
| Por (p, q) -> fn (fn acc p) q
let pat_all pr pat = Util.all pat_fold pr pat
let pat_any pr pat = Util.any pat_fold pr pat
exception BadArity of lsymbol * int
exception FunctionSymbolExpected of lsymbol
exception PredicateSymbolExpected of lsymbol
exception ConstructorExpected of lsymbol
let pat_app fs pl ty =
let s = match fs.ls_value with
| Some vty -> ty_match Mtv.empty vty ty
| None -> raise (FunctionSymbolExpected fs)
in
let mtch s ty p = ty_match s ty p.pat_ty in
ignore (try List.fold_left2 mtch s fs.ls_args pl with
| Invalid_argument _ -> raise (BadArity (fs, List.length pl)));
if fs.ls_constr = 0 then raise (ConstructorExpected fs);
pat_app fs pl ty
let pat_as p v =
ty_equal_check p.pat_ty v.vs_ty;
pat_as p v
let pat_or p q =
ty_equal_check p.pat_ty q.pat_ty;
pat_or p q
let rec pat_rename_all m p = match p.pat_node with
| Pvar v -> pat_var (Mvs.find v m)
| Pas (p, v) -> pat_as (pat_rename_all m p) (Mvs.find v m)
| _ -> pat_map (pat_rename_all m) p
let rec pat_gen_map fnT fnL m pat =
let fn = pat_gen_map fnT fnL m in
let ty = fnT pat.pat_ty in
match pat.pat_node with
| Pwild -> pat_wild ty
| Pvar v -> pat_var (Mvs.find v m)
| Papp (s, pl) -> pat_app (fnL s) (List.map fn pl) ty
| Pas (p, v) -> pat_as (fn p) (Mvs.find v m)
| Por (p, q) -> pat_or (fn p) (fn q)
let rec pat_gen_fold fnT fnL acc pat =
let fn acc p = pat_gen_fold fnT fnL acc p in
let acc = fnT acc pat.pat_ty in
match pat.pat_node with
| Pwild | Pvar _ -> acc
| Papp (s, pl) -> List.fold_left fn (fnL acc s) pl
| Por (p, q) -> fn (fn acc p) q
| Pas (p, _) -> fn acc p
type quant =
| Tforall
| Texists
type binop =
| Tand
| Tor
| Timplies
| Tiff
type term = {
t_node : term_node;
t_ty : ty option;
t_attrs : Sattr.t;
t_loc : Loc.position option;
}
and term_node =
| Tvar of vsymbol
| Tconst of Number.constant
| Tapp of lsymbol * term list
| Tif of term * term * term
| Tlet of term * term_bound
| Tcase of term * term_branch list
| Teps of term_bound
| Tquant of quant * term_quant
| Tbinop of binop * term * term
| Tnot of term
| Ttrue
| Tfalse
and term_bound = vsymbol * bind_info * term
and term_branch = pattern * bind_info * term
and term_quant = vsymbol list * bind_info * trigger * term
and trigger = term list list
and bind_info = {
}
exception CompLT
exception CompGT
type frame = int Mvs.t * term Mvs.t
type term_or_bound =
| Trm of term * frame list
| Bnd of int
let rec descend vml t = match t.t_node with
| Tvar vs ->
let rec find vs = function
| (bv,vm)::vml ->
begin match Mvs.find_opt vs bv with
| Some i -> Bnd i
| None ->
begin match Mvs.find_opt vs vm with
| Some t -> descend vml t
| None -> find vs vml
end
end
| [] -> Trm (t, [])
in
find vs vml
| _ -> Trm (t, vml)
let t_compare trigger attr t1 t2 =
let comp_raise c =
if c < 0 then raise CompLT else if c > 0 then raise CompGT in
let perv_compare h1 h2 = comp_raise (Pervasives.compare h1 h2) in
let rec pat_compare (bnd,bv1,bv2 as state) p1 p2 =
match p1.pat_node, p2.pat_node with
| Pwild, Pwild ->
bnd, bv1, bv2
| Pvar v1, Pvar v2 ->
bnd + 1, Mvs.add v1 bnd bv1, Mvs.add v2 bnd bv2
| Papp (s1, l1), Papp (s2, l2) ->
comp_raise (ls_compare s1 s2);
List.fold_left2 pat_compare state l1 l2
| Por (p1, q1), Por (p2, q2) ->
let (_,bv1,bv2 as res) = pat_compare state p1 p2 in
let rec or_cmp q1 q2 = match q1.pat_node, q2.pat_node with
| Pwild, Pwild -> ()
| Pvar v1, Pvar v2 ->
perv_compare (Mvs.find v1 bv1) (Mvs.find v2 bv2)
| Papp (s1, l1), Papp (s2, l2) ->
comp_raise (ls_compare s1 s2);
List.iter2 or_cmp l1 l2
| Por (p1, q1), Por (p2, q2) ->
or_cmp p1 p2; or_cmp q1 q2
| Pas (p1, v1), Pas (p2, v2) ->
or_cmp p1 p2;
perv_compare (Mvs.find v1 bv1) (Mvs.find v2 bv2)
| Pwild, _ -> raise CompLT | _, Pwild -> raise CompGT
| Pvar _, _ -> raise CompLT | _, Pvar _ -> raise CompGT
| Papp _, _ -> raise CompLT | _, Papp _ -> raise CompGT
| Por _, _ -> raise CompLT | _, Por _ -> raise CompGT
in
or_cmp q1 q2;
res
| Pas (p1, v1), Pas (p2, v2) ->
let bnd, bv1, bv2 = pat_compare state p1 p2 in
bnd + 1, Mvs.add v1 bnd bv1, Mvs.add v2 bnd bv2
| Pwild, _ -> raise CompLT | _, Pwild -> raise CompGT
| Pvar _, _ -> raise CompLT | _, Pvar _ -> raise CompGT
| Papp _, _ -> raise CompLT | _, Papp _ -> raise CompGT
| Por _, _ -> raise CompLT | _, Por _ -> raise CompGT
in
let rec t_compare bnd vml1 vml2 t1 t2 =
if t1 != t2 || vml1 <> [] || vml2 <> [] then begin
comp_raise (oty_compare t1.t_ty t2.t_ty);
if attr then comp_raise (Sattr.compare t1.t_attrs t2.t_attrs) else ();
match descend vml1 t1, descend vml2 t2 with
| Bnd i1, Bnd i2 -> perv_compare i1 i2
| Bnd _, Trm _ -> raise CompLT
| Trm _, Bnd _ -> raise CompGT
| Trm (t1,vml1), Trm (t2,vml2) ->
begin match t1.t_node, t2.t_node with
| Tvar v1, Tvar v2 ->
comp_raise (vs_compare v1 v2)
| Tconst c1, Tconst c2 ->
let open Number in
begin match c1, c2 with
| ConstInt { ic_negative = s1; ic_abs = IConstRaw b1 },
ConstInt { ic_negative = s2; ic_abs = IConstRaw b2 } ->
perv_compare s1 s2;
comp_raise (BigInt.compare b1 b2)
| _, _ -> perv_compare c1 c2
end
| Tapp (s1,l1), Tapp (s2,l2) ->
comp_raise (ls_compare s1 s2);
List.iter2 (t_compare bnd vml1 vml2) l1 l2
| Tif (f1,t1,e1), Tif (f2,t2,e2) ->
t_compare bnd vml1 vml2 f1 f2;
t_compare bnd vml1 vml2 t1 t2;
t_compare bnd vml1 vml2 e1 e2
| Tlet (t1,(v1,b1,e1)), Tlet (t2,(v2,b2,e2)) ->
t_compare bnd vml1 vml2 t1 t2;
let vml1 = (Mvs.singleton v1 bnd, b1.bv_subst) :: vml1 in
let vml2 = (Mvs.singleton v2 bnd, b2.bv_subst) :: vml2 in
t_compare (bnd + 1) vml1 vml2 e1 e2
| Tcase (t1,bl1), Tcase (t2,bl2) ->
t_compare bnd vml1 vml2 t1 t2;
let b_compare (p1,b1,t1) (p2,b2,t2) =
let bnd,bv1,bv2 = pat_compare (bnd,Mvs.empty,Mvs.empty) p1 p2 in
let vml1 = (bv1, b1.bv_subst) :: vml1 in
let vml2 = (bv2, b2.bv_subst) :: vml2 in
t_compare bnd vml1 vml2 t1 t2; 0 in
comp_raise (Lists.compare b_compare bl1 bl2)
| Teps (v1,b1,e1), Teps (v2,b2,e2) ->
let vml1 = (Mvs.singleton v1 bnd, b1.bv_subst) :: vml1 in
let vml2 = (Mvs.singleton v2 bnd, b2.bv_subst) :: vml2 in
t_compare (bnd + 1) vml1 vml2 e1 e2
| Tquant (q1,(vl1,b1,tr1,f1)), Tquant (q2,(vl2,b2,tr2,f2)) ->
perv_compare q1 q2;
let rec add bnd bv1 bv2 vl1 vl2 = match vl1, vl2 with
| (v1::vl1), (v2::vl2) ->
let bv1 = Mvs.add v1 bnd bv1 in
let bv2 = Mvs.add v2 bnd bv2 in
add (bnd + 1) bv1 bv2 vl1 vl2
| [], (_::_) -> raise CompLT
| (_::_), [] -> raise CompGT
| [], [] -> bnd, bv1, bv2 in
let bnd, bv1, bv2 = add bnd Mvs.empty Mvs.empty vl1 vl2 in
let vml1 = (bv1, b1.bv_subst) :: vml1 in
let vml2 = (bv2, b2.bv_subst) :: vml2 in
let tr_cmp t1 t2 = t_compare bnd vml1 vml2 t1 t2; 0 in
if trigger then comp_raise (Lists.compare (Lists.compare tr_cmp) tr1 tr2) else ();
t_compare bnd vml1 vml2 f1 f2
| Tbinop (op1,f1,g1), Tbinop (op2,f2,g2) ->
perv_compare op1 op2;
t_compare bnd vml1 vml2 f1 f2;
t_compare bnd vml1 vml2 g1 g2
| Tnot f1, Tnot f2 ->
t_compare bnd vml1 vml2 f1 f2
| Ttrue, Ttrue -> ()
| Tfalse, Tfalse -> ()
| Tvar _, _ -> raise CompLT | _, Tvar _ -> raise CompGT
| Tconst _, _ -> raise CompLT | _, Tconst _ -> raise CompGT
| Tapp _, _ -> raise CompLT | _, Tapp _ -> raise CompGT
| Tif _, _ -> raise CompLT | _, Tif _ -> raise CompGT
| Tlet _, _ -> raise CompLT | _, Tlet _ -> raise CompGT
| Tcase _, _ -> raise CompLT | _, Tcase _ -> raise CompGT
| Teps _, _ -> raise CompLT | _, Teps _ -> raise CompGT
| Tquant _, _ -> raise CompLT | _, Tquant _ -> raise CompGT
| Tbinop _, _ -> raise CompLT | _, Tbinop _ -> raise CompGT
| Tnot _, _ -> raise CompLT | _, Tnot _ -> raise CompGT
| Ttrue, _ -> raise CompLT | _, Ttrue -> raise CompGT
end
end in
try t_compare 0 [] [] t1 t2; 0
with CompLT -> -1 | CompGT -> 1
let t_equal t1 t2 = (t_compare true true t1 t2 = 0)
let t_equal_nt_na t1 t2 = (t_compare false false t1 t2 = 0)
let t_compare = t_compare true true
let t_similar t1 t2 =
oty_equal t1.t_ty t2.t_ty &&
match t1.t_node, t2.t_node with
| Tvar v1, Tvar v2 -> vs_equal v1 v2
| Tconst c1, Tconst c2 -> c1 = c2
| Tapp (s1,l1), Tapp (s2,l2) -> ls_equal s1 s2 && Lists.equal (==) l1 l2
| Tif (f1,t1,e1), Tif (f2,t2,e2) -> f1 == f2 && t1 == t2 && e1 == e2
| Tlet (t1,bv1), Tlet (t2,bv2) -> t1 == t2 && bv1 == bv2
| Tcase (t1,bl1), Tcase (t2,bl2) -> t1 == t2 && Lists.equal (==) bl1 bl2
| Teps bv1, Teps bv2 -> bv1 == bv2
| Tquant (q1,bv1), Tquant (q2,bv2) -> q1 = q2 && bv1 == bv2
| Tbinop (o1,f1,g1), Tbinop (o2,f2,g2) -> o1 = o2 && f1 == f2 && g1 == g2
| Tnot f1, Tnot f2 -> f1 == f2
| Ttrue, Ttrue | Tfalse, Tfalse -> true
| _, _ -> false
let t_hash trigger attr t =
let rec pat_hash bnd bv p = match p.pat_node with
| Pwild -> bnd, bv, 0
| Pvar v -> bnd + 1, Mvs.add v bnd bv, bnd + 1
| Papp (s,l) ->
let hash (bnd,bv,h) p =
let bnd,bv,hp = pat_hash bnd bv p in
bnd, bv, Hashcons.combine h hp in
List.fold_left hash (bnd,bv,ls_hash s) l
| Por (p,q) ->
let bnd,bv,hp = pat_hash bnd bv p in
let rec or_hash q = match q.pat_node with
| Pwild -> 0
| Pvar v -> Mvs.find v bv + 1
| Papp (s,l) -> Hashcons.combine_list or_hash (ls_hash s) l
| Por (p,q) -> Hashcons.combine (or_hash p) (or_hash q)
| Pas (p,v) -> Hashcons.combine (or_hash p) (Mvs.find v bv + 1)
in
bnd, bv, Hashcons.combine hp (or_hash q)
| Pas (p,v) ->
let bnd,bv,hp = pat_hash bnd bv p in
bnd + 1, Mvs.add v bnd bv, Hashcons.combine hp (bnd + 1)
in
let rec t_hash bnd vml t =
let h = oty_hash t.t_ty in
let h =
if attr then
let comb l h = Hashcons.combine (attr_hash l) h in
Sattr.fold comb t.t_attrs h
else h
in
Hashcons.combine h
begin match descend vml t with
| Bnd i -> i + 1
| Trm (t,vml) ->
begin match t.t_node with
| Tvar v -> vs_hash v
| Tconst c -> Hashtbl.hash c
| Tapp (s,l) ->
Hashcons.combine_list (t_hash bnd vml) (ls_hash s) l
| Tif (f,t,e) ->
let hf = t_hash bnd vml f in
let ht = t_hash bnd vml t in
let he = t_hash bnd vml e in
Hashcons.combine2 hf ht he
| Tlet (t,(v,b,e)) ->
let h = t_hash bnd vml t in
let vml = (Mvs.singleton v bnd, b.bv_subst) :: vml in
Hashcons.combine h (t_hash (bnd + 1) vml e)
| Tcase (t,bl) ->
let h = t_hash bnd vml t in
let b_hash (p,b,t) =
let bnd,bv,hp = pat_hash bnd Mvs.empty p in
let vml = (bv, b.bv_subst) :: vml in
Hashcons.combine hp (t_hash bnd vml t) in
Hashcons.combine_list b_hash h bl
| Teps (v,b,e) ->
let vml = (Mvs.singleton v bnd, b.bv_subst) :: vml in
t_hash (bnd + 1) vml e
| Tquant (q,(vl,b,tr,f)) ->
let h = Hashtbl.hash q in
let rec add bnd bv vl = match vl with
| v::vl -> add (bnd + 1) (Mvs.add v bnd bv) vl
| [] -> bnd, bv in
let bnd, bv = add bnd Mvs.empty vl in
let vml = (bv, b.bv_subst) :: vml in
let h =
if trigger then
List.fold_left
(Hashcons.combine_list (t_hash bnd vml)) h tr
else h
in
Hashcons.combine h (t_hash bnd vml f)
| Tbinop (op,f,g) ->
let ho = Hashtbl.hash op in
let hf = t_hash bnd vml f in
let hg = t_hash bnd vml g in
Hashcons.combine2 ho hf hg
| Tnot f ->
Hashcons.combine 1 (t_hash bnd vml f)
| Ttrue -> 2
| Tfalse -> 3
end
end in
t_hash 0 [] t
exception TermExpected of term
exception FmlaExpected of term
let t_type t = match t.t_ty with
| Some ty -> ty
| None -> raise (TermExpected t)
let t_prop f =
if f.t_ty = None then f else raise (FmlaExpected f)
let t_ty_check t ty = match ty, t.t_ty with
| Some l, Some r -> ty_equal_check l r
| Some _, None -> raise (TermExpected t)
| None, Some _ -> raise (FmlaExpected t)
| None, None -> ()
let vs_check v t = ty_equal_check v.vs_ty (t_type t)
let tr_equal = Lists.equal (Lists.equal t_equal)
let tr_map fn = List.map (List.map fn)
let tr_fold fn = List.fold_left (List.fold_left fn)
let tr_map_fold fn = Lists.map_fold_left (Lists.map_fold_left fn)
let bnd_map fn bv = { bv with bv_subst = Mvs.map fn bv.bv_subst }
let bnd_fold fn acc bv = Mvs.fold (fun _ t a -> fn a t) bv.bv_subst acc
let bnd_map_fold fn acc bv =
let acc,s = Mvs.mapi_fold (fun _ t a -> fn a t) bv.bv_subst acc in
acc, { bv with bv_subst = s }
let vars_union s1 s2 = Mvs.union (fun _ m n -> Some (m + n)) s1 s2
let add_b_vars s (_,b,_) = vars_union s b.bv_vars
let rec t_vars t = match t.t_node with
| Tvar v -> Mvs.singleton v 1
| Tconst _ -> Mvs.empty
| Tapp (_,tl) -> List.fold_left add_t_vars Mvs.empty tl
| Tif (f,t,e) -> add_t_vars (add_t_vars (t_vars f) t) e
| Tlet (t,bt) -> add_b_vars (t_vars t) bt
| Tcase (t,bl) -> List.fold_left add_b_vars (t_vars t) bl
| Teps (_,b,_) -> b.bv_vars
| Tquant (_,(_,b,_,_)) -> b.bv_vars
| Tbinop (_,f1,f2) -> add_t_vars (t_vars f1) f2
| Tnot f -> t_vars f
| Ttrue | Tfalse -> Mvs.empty
and add_t_vars s t = vars_union s (t_vars t)
let add_nt_vars _ n t s = vars_union s
(if n = 1 then t_vars t else Mvs.map (( * ) n) (t_vars t))
module TermOHT = struct
type t = term
let hash = t_hash true true
let equal = t_equal
let compare = t_compare
end
module Mterm = Extmap.Make(TermOHT)
module Sterm = Extset.MakeOfMap(Mterm)
module Hterm = Exthtbl.Make(TermOHT)
module TermOHT_nt_na = struct
type t = term
let hash = t_hash false false
let equal = t_equal_nt_na
end
module Hterm_nt_na = Exthtbl.Make(TermOHT_nt_na)
let t_hash = t_hash true true
let mk_term n ty = {
t_node = n;
t_attrs = Sattr.empty;
t_loc = None;
t_ty = ty;
}
let t_var v = mk_term (Tvar v) (Some v.vs_ty)
let t_const c ty = mk_term (Tconst c) (Some ty)
let t_app f tl ty = mk_term (Tapp (f, tl)) ty
let t_if f t1 t2 = mk_term (Tif (f, t1, t2)) t2.t_ty
let t_let t1 bt ty = mk_term (Tlet (t1, bt)) ty
let t_case t1 bl ty = mk_term (Tcase (t1, bl)) ty
let t_eps bf ty = mk_term (Teps bf) ty
let t_quant q qf = mk_term (Tquant (q, qf)) None
let t_binary op f g = mk_term (Tbinop (op, f, g)) None
let t_not f = mk_term (Tnot f) None
let t_true = mk_term (Ttrue) None
let t_false = mk_term (Tfalse) None
let t_attr_set ?loc l t = { t with t_attrs = l; t_loc = loc }
let t_attr_add l t = { t with t_attrs = Sattr.add l t.t_attrs }
let t_attr_remove l t = { t with t_attrs = Sattr.remove l t.t_attrs }
let t_attr_copy s t =
if s == t then s else
if t_similar s t && Sattr.is_empty t.t_attrs && t.t_loc = None then s else
let attrs = Sattr.union s.t_attrs t.t_attrs in
let loc = if t.t_loc = None then s.t_loc else t.t_loc in
{ t with t_attrs = attrs; t_loc = loc }
let bound_map fn (u,b,e) = (u, bnd_map fn b, fn e)
let t_map_unsafe fn t = t_attr_copy t (match t.t_node with
| Tvar _ | Tconst _ -> t
| Tapp (f,tl) -> t_app f (List.map fn tl) t.t_ty
| Tif (f,t1,t2) -> t_if (fn f) (fn t1) (fn t2)
| Tlet (e,b) -> t_let (fn e) (bound_map fn b) t.t_ty
| Tcase (e,bl) -> t_case (fn e) (List.map (bound_map fn) bl) t.t_ty
| Teps b -> t_eps (bound_map fn b) t.t_ty
| Tquant (q,(vl,b,tl,f)) -> t_quant q (vl, bnd_map fn b, tr_map fn tl, fn f)
| Tbinop (op,f1,f2) -> t_binary op (fn f1) (fn f2)
| Tnot f1 -> t_not (fn f1)
| Ttrue | Tfalse -> t)
let bound_fold fn acc (_,b,e) = fn (bnd_fold fn acc b) e
let t_fold_unsafe fn acc t = match t.t_node with
| Tvar _ | Tconst _ -> acc
| Tapp (_,tl) -> List.fold_left fn acc tl
| Tif (f,t1,t2) -> fn (fn (fn acc f) t1) t2
| Tlet (e,b) -> fn (bound_fold fn acc b) e
| Tcase (e,bl) -> List.fold_left (bound_fold fn) (fn acc e) bl
| Teps b -> bound_fold fn acc b
| Tquant (_,(_,b,tl,f1)) -> fn (tr_fold fn (bnd_fold fn acc b) tl) f1
| Tbinop (_,f1,f2) -> fn (fn acc f1) f2
| Tnot f1 -> fn acc f1
| Ttrue | Tfalse -> acc
let bound_map_fold fn acc (u,b,e) =
let acc, b = bnd_map_fold fn acc b in
let acc, e = fn acc e in
acc, (u,b,e)
let t_map_fold_unsafe fn acc t = match t.t_node with
| Tvar _ | Tconst _ ->
acc, t
| Tapp (f,tl) ->
let acc,sl = Lists.map_fold_left fn acc tl in
acc, t_attr_copy t (t_app f sl t.t_ty)
| Tif (f,t1,t2) ->
let acc, g = fn acc f in
let acc, s1 = fn acc t1 in
let acc, s2 = fn acc t2 in
acc, t_attr_copy t (t_if g s1 s2)
| Tlet (e,b) ->
let acc, e = fn acc e in
let acc, b = bound_map_fold fn acc b in
acc, t_attr_copy t (t_let e b t.t_ty)
| Tcase (e,bl) ->
let acc, e = fn acc e in
let acc, bl = Lists.map_fold_left (bound_map_fold fn) acc bl in
acc, t_attr_copy t (t_case e bl t.t_ty)
| Teps b ->
let acc, b = bound_map_fold fn acc b in
acc, t_attr_copy t (t_eps b t.t_ty)
| Tquant (q,(vl,b,tl,f1)) ->
let acc, b = bnd_map_fold fn acc b in
let acc, tl = tr_map_fold fn acc tl in
let acc, f1 = fn acc f1 in
acc, t_attr_copy t (t_quant q (vl,b,tl,f1))
| Tbinop (op,f1,f2) ->
let acc, g1 = fn acc f1 in
let acc, g2 = fn acc f2 in
acc, t_attr_copy t (t_binary op g1 g2)
| Tnot f1 ->
let acc, g1 = fn acc f1 in
acc, t_attr_copy t (t_not g1)
| Ttrue | Tfalse ->
acc, t
let rec t_subst_unsafe m t =
let t_subst t = t_subst_unsafe m t in
let b_subst (u,b,e as bv) =
if Mvs.set_disjoint m b.bv_vars then bv else
(u, bv_subst_unsafe m b, e) in
match t.t_node with
| Tvar u ->
t_attr_copy t (Mvs.find_def t u m)
| Tlet (e, bt) ->
let d = t_subst e in
t_attr_copy t (t_let d (b_subst bt) t.t_ty)
| Tcase (e, bl) ->
let d = t_subst e in
let bl = List.map b_subst bl in
t_attr_copy t (t_case d bl t.t_ty)
| Teps bf ->
t_attr_copy t (t_eps (b_subst bf) t.t_ty)
| Tquant (q, (vl,b,tl,f1 as bq)) ->
let bq =
if Mvs.set_disjoint m b.bv_vars then bq else
(vl,bv_subst_unsafe m b,tl,f1) in
t_attr_copy t (t_quant q bq)
| _ ->
t_map_unsafe t_subst t
and bv_subst_unsafe m b =
let m = Mvs.set_inter m b.bv_vars in
if Mvs.is_empty m then b else
let s = Mvs.set_diff b.bv_vars m in
let s = Mvs.fold2_inter add_nt_vars b.bv_vars m s in
let h = Mvs.map (t_subst_unsafe m) b.bv_subst in
let h = Mvs.set_union h m in
{ bv_vars = s ; bv_subst = h }
let t_subst_unsafe m t =
if Mvs.is_empty m then t else t_subst_unsafe m t
let bnd_new s = { bv_vars = s ; bv_subst = Mvs.empty }
let t_close_bound v t = (v, bnd_new (Mvs.remove v (t_vars t)), t)
let t_close_branch p t = (p, bnd_new (Mvs.set_diff (t_vars t) p.pat_vars), t)
let t_close_quant vl tl f =
let del_v s v = Mvs.remove v s in
let s = tr_fold add_t_vars (t_vars f) tl in
let s = List.fold_left del_v s vl in
(vl, bnd_new s, tl, t_prop f)
let fresh_vsymbol v =
create_vsymbol (id_clone v.vs_name) v.vs_ty
let vs_rename h v =
let u = fresh_vsymbol v in
Mvs.add v (t_var u) h, u
let vl_rename h vl =
Lists.map_fold_left vs_rename h vl
let pat_rename h p =
let add_vs v () = fresh_vsymbol v in
let m = Mvs.mapi add_vs p.pat_vars in
let p = pat_rename_all m p in
Mvs.union (fun _ _ t -> Some t) h (Mvs.map t_var m), p
let t_open_bound (v,b,t) =
let m,v = vs_rename b.bv_subst v in
v, t_subst_unsafe m t
let t_open_bound_with e (v,b,t) =
vs_check v e;
let m = Mvs.add v e b.bv_subst in
t_subst_unsafe m t
let t_open_branch (p,b,t) =
let m,p = pat_rename b.bv_subst p in
p, t_subst_unsafe m t
let t_open_quant (vl,b,tl,f) =
let m,vl = vl_rename b.bv_subst vl in
let tl = tr_map (t_subst_unsafe m) tl in
vl, tl, t_subst_unsafe m f
let t_clone_bound_id (v,_,_) = id_clone v.vs_name
let t_open_bound_cb tb =
let v, t = t_open_bound tb in
let close v' t' =
if t == t' && vs_equal v v' then tb else t_close_bound v' t'
in
v, t, close
let t_open_branch_cb tbr =
let p, t = t_open_branch tbr in
let close p' t' =
if t == t' && p == p' then tbr else t_close_branch p' t'
in
p, t, close
let t_open_quant_cb fq =
let vl, tl, f = t_open_quant fq in
let close vl' tl' f' =
if f == f' &&
Lists.equal (Lists.equal ((==) : term -> term -> bool)) tl tl' &&
Lists.equal vs_equal vl vl'
then fq else t_close_quant vl' tl' f'
in
vl, tl, f, close
let ls_arg_inst ls tl =
let mtch s ty t = ty_match s ty (t_type t) in
try List.fold_left2 mtch Mtv.empty ls.ls_args tl with
| Invalid_argument _ -> raise (BadArity (ls, List.length tl))
let ls_app_inst ls tl ty =
let s = ls_arg_inst ls tl in
match ls.ls_value, ty with
| Some _, None -> raise (PredicateSymbolExpected ls)
| None, Some _ -> raise (FunctionSymbolExpected ls)
| Some vty, Some ty -> ty_match s vty ty
| None, None -> s
let t_app_infer ls tl =
let s = ls_arg_inst ls tl in
t_app ls tl (oty_inst s ls.ls_value)
let t_app ls tl ty = ignore (ls_app_inst ls tl ty); t_app ls tl ty
let fs_app fs tl ty = t_app fs tl (Some ty)
let ps_app ps tl = t_app ps tl None
let t_nat_const n =
assert (n >= 0);
t_const (Number.const_of_int n) ty_int
let t_bigint_const n = t_const (Number.const_of_big_int n) Ty.ty_int
exception InvalidIntegerLiteralType of ty
exception InvalidRealLiteralType of ty
let check_literal c ty =
let ts = match ty.ty_node with
| Tyapp (ts,[]) -> ts
| _ -> match c with
| Number.ConstInt _ -> raise (InvalidIntegerLiteralType ty)
| Number.ConstReal _ -> raise (InvalidRealLiteralType ty)
in
match c with
| Number.ConstInt _ when ts_equal ts ts_int -> ()
| Number.ConstInt n ->
begin match ts.ts_def with
| Range ir -> Number.(check_range n ir)
| _ -> raise (InvalidIntegerLiteralType ty)
end
| Number.ConstReal _ when ts_equal ts ts_real -> ()
| Number.ConstReal x ->
begin match ts.ts_def with
| Float fp -> Number.(check_float x.Number.rc_abs fp)
| _ -> raise (InvalidRealLiteralType ty)
end
let t_const c ty = check_literal c ty; t_const c ty
let t_if f t1 t2 =
t_ty_check t2 t1.t_ty;
t_if (t_prop f) t1 t2
let t_let t1 ((v,_,t2) as bt) =
vs_check v t1;
t_let t1 bt t2.t_ty
exception EmptyCase
let t_case t bl =
let tty = t_type t in
let bty = match bl with
| (_,_,tbr) :: _ -> tbr.t_ty
| _ -> raise EmptyCase
in
let t_check_branch (p,_,tbr) =
ty_equal_check tty p.pat_ty;
t_ty_check tbr bty
in
List.iter t_check_branch bl;
t_case t bl bty
let t_eps ((v,_,f) as bf) =
ignore (t_prop f);
t_eps bf (Some v.vs_ty)
let t_quant q ((vl,_,_,f) as qf) =
if vl = [] then f else t_quant q qf
let t_binary op f1 f2 = t_binary op (t_prop f1) (t_prop f2)
let t_not f = t_not (t_prop f)
let t_forall = t_quant Tforall
let t_exists = t_quant Texists
let t_and = t_binary Tand
let t_or = t_binary Tor
let t_implies = t_binary Timplies
let t_iff = t_binary Tiff
let rec t_and_l = function
| [] -> t_true
| [f] -> f
| f::fl -> t_and f (t_and_l fl)
let rec t_or_l = function
| [] -> t_false
| [f] -> f
| f::fl -> t_or f (t_or_l fl)
let asym_split = create_attribute "asym_split"
let stop_split = create_attribute "stop_split"
let t_and_asym t1 t2 = t_and (t_attr_add asym_split t1) t2
let t_or_asym t1 t2 = t_or (t_attr_add asym_split t1) t2
let rec t_and_asym_l = function
| [] -> t_true
| [f] -> f
| f::fl -> t_and_asym f (t_and_asym_l fl)
let rec t_or_asym_l = function
| [] -> t_false
| [f] -> f
| f::fl -> t_or_asym f (t_or_asym_l fl)
let t_quant_close q vl tl f =
if vl = [] then t_prop f else t_quant q (t_close_quant vl tl f)
let t_forall_close = t_quant_close Tforall
let t_exists_close = t_quant_close Texists
let t_let_close v t1 t2 = t_let t1 (t_close_bound v t2)
let t_case_close t l = t_case t (List.map (fun (p,e) -> t_close_branch p e) l)
let t_eps_close v f = t_eps (t_close_bound v f)
let ps_equ =
let v = ty_var (create_tvsymbol (id_fresh "a")) in
create_psymbol (id_fresh (op_infix "=")) [v; v]
let t_equ t1 t2 = ps_app ps_equ [t1; t2]
let t_neq t1 t2 = t_not (ps_app ps_equ [t1; t2])
let fs_bool_true = create_fsymbol ~constr:2 (id_fresh "True") [] ty_bool
let fs_bool_false = create_fsymbol ~constr:2 (id_fresh "False") [] ty_bool
let t_bool_true = fs_app fs_bool_true [] ty_bool
let t_bool_false = fs_app fs_bool_false [] ty_bool
let fs_tuple_ids = Hid.create 17
let fs_tuple = Hint.memo 17 (fun n ->
let ts = ts_tuple n in
let tl = List.map ty_var ts.ts_args in
let ty = ty_app ts tl in
let id = id_fresh ("Tuple" ^ string_of_int n) in
let fs = create_fsymbol ~constr:1 id tl ty in
Hid.add fs_tuple_ids fs.ls_name n;
fs)
let is_fs_tuple fs =
fs.ls_constr = 1 && Hid.mem fs_tuple_ids fs.ls_name
let is_fs_tuple_id id =
try Some (Hid.find fs_tuple_ids id) with Not_found -> None
let t_tuple tl =
let ty = ty_tuple (List.map t_type tl) in
fs_app (fs_tuple (List.length tl)) tl ty
let fs_func_app =
let ty_a = ty_var (create_tvsymbol (id_fresh "a")) in
let ty_b = ty_var (create_tvsymbol (id_fresh "b")) in
let id = id_fresh (op_infix "@") in
create_fsymbol id [ty_func ty_a ty_b; ty_a] ty_b
let t_func_app fn t = t_app_infer fs_func_app [fn; t]
let t_pred_app pr t = t_equ (t_func_app pr t) t_bool_true
let t_func_app_l fn tl = List.fold_left t_func_app fn tl
let t_pred_app_l pr tl = t_equ (t_func_app_l pr tl) t_bool_true
let gen_fresh_vsymbol fnT v =
let ty = fnT v.vs_ty in
if ty_equal ty v.vs_ty then v else
create_vsymbol (id_clone v.vs_name) ty
let gen_vs_rename fnT h v =
let u = gen_fresh_vsymbol fnT v in
Mvs.add v u h, u
let gen_vl_rename fnT h vl =
Lists.map_fold_left (gen_vs_rename fnT) h vl
let gen_pat_rename fnT fnL h p =
let add_vs v () = gen_fresh_vsymbol fnT v in
let m = Mvs.mapi add_vs p.pat_vars in
let p = pat_gen_map fnT fnL m p in
Mvs.union (fun _ _ t -> Some t) h m, p
let gen_bnd_rename fnT fnE h b =
let add_bv v n m = Mvs.add (Mvs.find v h) n m in
let bvs = Mvs.fold add_bv b.bv_vars Mvs.empty in
let add_bs v t (nh, m) =
let nh,v = gen_vs_rename fnT nh v in
nh, Mvs.add v (fnE t) m
in
let h,bsb = Mvs.fold add_bs b.bv_subst (h,Mvs.empty) in
h, { bv_vars = bvs ; bv_subst = bsb }
let rec t_gen_map fnT fnL m t =
let fn = t_gen_map fnT fnL m in
t_attr_copy t (match t.t_node with
| Tvar v ->
let u = Mvs.find_def v v m in
ty_equal_check (fnT v.vs_ty) u.vs_ty;
t_var u
| Tconst _ ->
t
| Tapp (fs, tl) ->
t_app (fnL fs) (List.map fn tl) (Opt.map fnT t.t_ty)
| Tif (f, t1, t2) ->
t_if (fn f) (fn t1) (fn t2)
| Tlet (t1, (u,b,t2)) ->
let m,b = gen_bnd_rename fnT fn m b in
let m,u = gen_vs_rename fnT m u in
t_let (fn t1) (u, b, t_gen_map fnT fnL m t2)
| Tcase (t1, bl) ->
let fn_br (p,b,t2) =
let m,b = gen_bnd_rename fnT fn m b in
let m,p = gen_pat_rename fnT fnL m p in
(p, b, t_gen_map fnT fnL m t2)
in
t_case (fn t1) (List.map fn_br bl)
| Teps (u,b,f) ->
let m,b = gen_bnd_rename fnT fn m b in
let m,u = gen_vs_rename fnT m u in
t_eps (u, b, t_gen_map fnT fnL m f)
| Tquant (q, (vl,b,tl,f)) ->
let m,b = gen_bnd_rename fnT fn m b in
let m,vl = gen_vl_rename fnT m vl in
let fn = t_gen_map fnT fnL m in
t_quant q (vl, b, tr_map fn tl, fn f)
| Tbinop (op, f1, f2) ->
t_binary op (fn f1) (fn f2)
| Tnot f1 ->
t_not (fn f1)
| Ttrue | Tfalse ->
t)
let t_gen_map fnT fnL mapV t = t_gen_map (Wty.memoize 17 fnT) fnL mapV t
let gen_mapV fnT = Mvs.mapi (fun v _ -> gen_fresh_vsymbol fnT v)
let t_s_map fnT fnL t = t_gen_map fnT fnL (gen_mapV fnT (t_vars t)) t
let t_subst_types mapT mapV t =
let fnT = ty_inst mapT in
let m = gen_mapV fnT (t_vars t) in
let t = t_gen_map fnT (fun ls -> ls) m t in
let add _ v t m = vs_check v t; Mvs.add v t m in
let m = Mvs.fold2_inter add m mapV Mvs.empty in
(m,t)
let t_ty_subst mapT mapV t =
let m,t = t_subst_types mapT mapV t in
t_subst_unsafe m t
let rec t_gen_fold fnT fnL acc t =
let fn = t_gen_fold fnT fnL in
let acc = Opt.fold fnT acc t.t_ty in
match t.t_node with
| Tconst _ | Tvar _ -> acc
| Tapp (f, tl) -> List.fold_left fn (fnL acc f) tl
| Tif (f, t1, t2) -> fn (fn (fn acc f) t1) t2
| Tlet (t1, (_,b,t2)) -> fn (bnd_fold fn (fn acc t1) b) t2
| Tcase (t1, bl) ->
let branch acc (p,b,t) =
fn (pat_gen_fold fnT fnL (bnd_fold fn acc b) p) t in
List.fold_left branch (fn acc t1) bl
| Teps (_,b,f) -> fn (bnd_fold fn acc b) f
| Tquant (_, (vl,b,tl,f1)) ->
let acc = List.fold_left (fun a v -> fnT a v.vs_ty) acc vl in
fn (tr_fold fn (bnd_fold fn acc b) tl) f1
| Tbinop (_, f1, f2) -> fn (fn acc f1) f2
| Tnot f1 -> fn acc f1
| Ttrue | Tfalse -> acc
let t_s_fold = t_gen_fold
let t_s_all prT prL t = Util.alld t_s_fold prT prL t
let t_s_any prT prL t = Util.anyd t_s_fold prT prL t
let t_ty_map fn t = t_s_map fn (fun ls -> ls) t
let t_ty_fold fn acc t = t_s_fold fn Util.const acc t
let t_ty_freevars = t_ty_fold ty_freevars
let rec t_app_map fn t =
let t = t_map_unsafe (t_app_map fn) t in
match t.t_node with
| Tapp (ls,tl) ->
let ls = fn ls (List.map t_type tl) t.t_ty in
t_attr_copy t (t_app ls tl t.t_ty)
| _ -> t
let rec t_app_fold fn acc t =
let acc = t_fold_unsafe (t_app_fold fn) acc t in
match t.t_node with
| Tapp (ls,tl) -> fn acc ls (List.map t_type tl) t.t_ty
| _ -> acc
let t_map fn t = match t.t_node with
| Tlet (t1, b) ->
let u,t2 = t_open_bound b in
let s1 = fn t1 and s2 = fn t2 in
if s2 == t2
then if s1 == t1 then t
else t_attr_copy t (t_let s1 b)
else t_attr_copy t (t_let_close u s1 s2)
| Tcase (t1, bl) ->
let s1 = fn t1 in
let brn same b =
let p,t = t_open_branch b in
let s = fn t in
if s == t then same, b
else false, t_close_branch p s
in
let same, bl = Lists.map_fold_left brn true bl in
if s1 == t1 && same then t
else t_attr_copy t (t_case s1 bl)
| Teps b ->
let u,t1 = t_open_bound b in
let s1 = fn t1 in
if s1 == t1 then t
else t_attr_copy t (t_eps_close u s1)
| Tquant (q, b) ->
let vl,tl,f1 = t_open_quant b in
let g1 = fn f1 and sl = tr_map fn tl in
if g1 == f1 && List.for_all2 (List.for_all2 (==)) sl tl then t
else t_attr_copy t (t_quant_close q vl sl g1)
| _ ->
t_map_unsafe fn t
let t_map fn = t_map (fun t ->
let res = fn t in t_ty_check res t.t_ty; res)
let t_fold fn acc t = match t.t_node with
| Tlet (t1, b) ->
let _,t2 = t_open_bound b in fn (fn acc t1) t2
| Tcase (t1, bl) ->
let brn acc b = let _,t = t_open_branch b in fn acc t in
List.fold_left brn (fn acc t1) bl
| Teps b ->
let _,f = t_open_bound b in fn acc f
| Tquant (_, b) ->
let _, tl, f1 = t_open_quant b in tr_fold fn (fn acc f1) tl
| _ -> t_fold_unsafe fn acc t
let t_iter fn t = t_fold (fun () t -> fn t) () t
let t_all pr t = Util.all t_fold pr t
let t_any pr t = Util.any t_fold pr t
let t_map_fold fn acc t = match t.t_node with
| Tlet (t1, b) ->
let acc, s1 = fn acc t1 in
let u,t2 = t_open_bound b in
let acc, s2 = fn acc t2 in
acc, if s2 == t2
then if s1 == t1 then t
else t_attr_copy t (t_let s1 b)
else t_attr_copy t (t_let_close u s1 s2)
| Tcase (t1, bl) ->
let acc, s1 = fn acc t1 in
let brn (acc,same) b =
let p,t = t_open_branch b in
let acc, s = fn acc t in
if s == t then (acc,same), b
else (acc,false), t_close_branch p s
in
let (acc,same), bl = Lists.map_fold_left brn (acc,true) bl in
acc, if s1 == t1 && same then t
else t_attr_copy t (t_case s1 bl)
| Teps b ->
let u,t1 = t_open_bound b in
let acc, s1 = fn acc t1 in
acc, if s1 == t1 then t
else t_attr_copy t (t_eps_close u s1)
| Tquant (q, b) ->
let vl,tl,f1 = t_open_quant b in
let acc, sl = tr_map_fold fn acc tl in
let acc, g1 = fn acc f1 in
acc, if g1 == f1 && List.for_all2 (List.for_all2 (==)) sl tl
then t else t_attr_copy t (t_quant_close q vl sl g1)
| _ -> t_map_fold_unsafe fn acc t
let t_map_fold fn = t_map_fold (fun acc t ->
let res = fn acc t in t_ty_check (snd res) t.t_ty; res)
let t_map_sign fn sign f = t_attr_copy f (match f.t_node with
| Tbinop (Timplies, f1, f2) ->
t_implies (fn (not sign) f1) (fn sign f2)
| Tbinop (Tiff, f1, f2) ->
let f1p = fn sign f1 in let f1n = fn (not sign) f1 in
let f2p = fn sign f2 in let f2n = fn (not sign) f2 in
if t_equal f1p f1n && t_equal f2p f2n then t_iff f1p f2p
else if sign
then t_and (t_implies f1n f2p) (t_implies f2n f1p)
else t_implies (t_or f1n f2n) (t_and f1p f2p)
| Tnot f1 ->
t_not (fn (not sign) f1)
| Tif (f1, f2, f3) when f.t_ty = None ->
let f1p = fn sign f1 in let f1n = fn (not sign) f1 in
let f2 = fn sign f2 in let f3 = fn sign f3 in
if t_equal f1p f1n then t_if f1p f2 f3 else if sign
then t_and (t_implies f1n f2) (t_implies (t_not f1p) f3)
else t_or (t_and f1p f2) (t_and (t_not f1n) f3)
| Tif _
| Teps _ -> failwith "t_map_sign: cannot determine polarity"
| _ -> t_map (fn sign) f)
let rec list_map_cont fnL contL = function
| e::el ->
let cont_l e el = contL (e::el) in
let cont_e e = list_map_cont fnL (cont_l e) el in
fnL cont_e e
| [] ->
contL []
let t_map_cont fn contT t =
let contT e = contT (t_attr_copy t e) in
match t.t_node with
| Tvar _ | Tconst _ -> contT t
| Tapp (fs, tl) ->
let cont_app tl = contT (t_app fs tl t.t_ty) in
list_map_cont fn cont_app tl
| Tif (f, t1, t2) ->
let cont_else f t1 t2 = contT (t_if f t1 t2) in
let cont_then f t1 = fn (cont_else f t1) t2 in
let cont_if f = fn (cont_then f) t1 in
fn cont_if f
| Tlet (t1, b) ->
let u,t2,close = t_open_bound_cb b in
let cont_in t1 t2 = contT (t_let t1 (close u t2)) in
let cont_let t1 = fn (cont_in t1) t2 in
fn cont_let t1
| Tcase (t1, bl) ->
let fnB contB b =
let pat,t,close = t_open_branch_cb b in
fn (fun t -> contB (close pat t)) t
in
let cont_with t1 bl = contT (t_case t1 bl) in
let cont_case t1 = list_map_cont fnB (cont_with t1) bl in
fn cont_case t1
| Teps b ->
let u,f,close = t_open_bound_cb b in
let cont_eps f = contT (t_eps (close u f)) in
fn cont_eps f
| Tquant (q, b) ->
let vl, tl, f1, close = t_open_quant_cb b in
let cont_dot tl f1 = contT (t_quant q (close vl tl f1)) in
let cont_quant tl = fn (cont_dot tl) f1 in
list_map_cont (list_map_cont fn) cont_quant tl
| Tbinop (op, f1, f2) ->
let cont_r f1 f2 = contT (t_binary op f1 f2) in
let cont_l f1 = fn (cont_r f1) f2 in
fn cont_l f1
| Tnot f1 ->
let cont_not f1 = contT (t_not f1) in
fn cont_not f1
| Ttrue | Tfalse -> contT t
let t_map_cont fn = t_map_cont (fun cont t ->
fn (fun e -> t_ty_check e t.t_ty; cont e) t)
let t_v_map fn t =
let fn v _ = let res = fn v in vs_check v res; res in
t_subst_unsafe (Mvs.mapi fn (t_vars t)) t
let bnd_v_fold fn acc b = Mvs.fold (fun v _ acc -> fn acc v) b.bv_vars acc
let bound_v_fold fn acc (_,b,_) = bnd_v_fold fn acc b
let rec t_v_fold fn acc t = match t.t_node with
| Tvar v -> fn acc v
| Tlet (e,b) -> bound_v_fold fn (t_v_fold fn acc e) b
| Tcase (e,bl) -> List.fold_left (bound_v_fold fn) (t_v_fold fn acc e) bl
| Teps b -> bound_v_fold fn acc b
| Tquant (_,(_,b,_,_)) -> bnd_v_fold fn acc b
| _ -> t_fold_unsafe (t_v_fold fn) acc t
let t_v_all pr t = Util.all t_v_fold pr t
let t_v_any pr t = Util.any t_v_fold pr t
let t_closed t = t_v_all Util.ffalse t
let bnd_v_count fn acc b = Mvs.fold (fun v n acc -> fn acc v n) b.bv_vars acc
let bound_v_count fn acc (_,b,_) = bnd_v_count fn acc b
let rec t_v_count fn acc t = match t.t_node with
| Tvar v -> fn acc v 1
| Tlet (e,b) -> bound_v_count fn (t_v_count fn acc e) b
| Tcase (e,bl) -> List.fold_left (bound_v_count fn) (t_v_count fn acc e) bl
| Teps b -> bound_v_count fn acc b
| Tquant (_,(_,b,_,_)) -> bnd_v_count fn acc b
| _ -> t_fold_unsafe (t_v_count fn) acc t
let t_v_occurs v t =
t_v_count (fun c u n -> if vs_equal u v then c + n else c) 0 t
let t_subst m t = Mvs.iter vs_check m; t_subst_unsafe m t
let t_subst_single v t1 t = t_subst (Mvs.singleton v t1) t
let t_freevars = add_t_vars
let rec t_occurs r t =
t_equal r t || t_any (t_occurs r) t
let rec t_replace t1 t2 t =
if t_equal t t1 then t2 else t_map (t_replace t1 t2) t
let t_replace t1 t2 t =
t_ty_check t2 t1.t_ty;
t_replace t1 t2 t
let t_lambda vl trl t =
let ty = Opt.get_def ty_bool t.t_ty in
let add_ty v ty = ty_func v.vs_ty ty in
let ty = List.fold_right add_ty vl ty in
let fc = create_vsymbol (id_fresh "fc") ty in
let copy_loc e = if t.t_loc = None then e
else t_attr_set ?loc:t.t_loc e.t_attrs e in
let mk_t_var v = if v.vs_name.id_loc = None then t_var v
else t_attr_set ?loc:v.vs_name.id_loc Sattr.empty (t_var v) in
let add_arg h v = copy_loc (t_func_app h (mk_t_var v)) in
let h = List.fold_left add_arg (mk_t_var fc) vl in
let f = match t.t_ty with
| Some _ -> t_equ h t
| None -> t_iff (copy_loc (t_equ h t_bool_true)) t in
t_eps_close fc (copy_loc (t_forall_close vl trl (copy_loc f)))
let t_lambda vl trl t =
let t = match t.t_node with
| Tapp (ps,[l;{t_node = Tapp (fs,[])}])
when ls_equal ps ps_equ && ls_equal fs fs_bool_true ->
t_attr_copy t l
| _ -> t in
if vl <> [] then t_lambda vl trl t
else if t.t_ty <> None then t
else t_if t t_bool_true t_bool_false
let t_open_lambda t = match t.t_ty, t.t_node with
| Some {ty_node = Tyapp (ts,_)}, Teps fb when ts_equal ts ts_func ->
let fc,f = t_open_bound fb in
let vl,trl,f = match f.t_node with
| Tquant (Tforall,fq) -> t_open_quant fq
let h,e = match f.t_node with
| Tapp (ps,[h;e]) when ls_equal ps ps_equ -> h, e
| Tbinop (Tiff,{t_node = Tapp (ps,[h;{t_node = Tapp (fs,[])}])},e)
when ls_equal ps ps_equ && ls_equal fs fs_bool_true -> h, e
let rec check h xl = match h.t_node, xl with
| Tapp (fs,[h;{t_node = Tvar u}]), x::xl
when ls_equal fs fs_func_app && vs_equal u x -> check h xl
| Tvar u, [] when vs_equal u fc && t_v_occurs u e = 0 -> vl, trl, e
| _ -> [], [], t in
check h (List.rev vl)
| _ -> [], [], t
let t_is_lambda t = let vl,_,_ = t_open_lambda t in vl <> []
let t_open_lambda_cb t =
let vl, trl, e = t_open_lambda t in
let close vl' trl' e' =
if e == e' &&
Lists.equal (Lists.equal ((==) : term -> term -> bool)) trl trl' &&
Lists.equal vs_equal vl vl'
then t else t_lambda vl' trl' e' in
vl, trl, e, close
let t_closure ls tyl ty =
let mk_v i ty = create_vsymbol (id_fresh ("y" ^ string_of_int i)) ty in
let vl = Lists.mapi mk_v tyl in
let t = t_app ls (List.map t_var vl) ty in
t_lambda vl [] t
let t_app_partial ls tl tyl ty =
if tyl = [] then t_app ls tl ty else
match tl with
| [t] when ls_equal ls fs_func_app -> t
| _ ->
let cons t tyl = t_type t :: tyl in
let tyl = List.fold_right cons tl tyl in
t_func_app_l (t_closure ls tyl ty) tl
let rec t_app_beta_l lam tl =
if tl = [] then lam else
let vl, trl, e = t_open_lambda lam in
if vl = [] then t_func_app_l lam tl else
let rec add m vl tl = match vl, tl with
| [], tl ->
t_app_beta_l (t_subst_unsafe m e) tl
| vl, [] ->
let trl = List.map (List.map (t_subst_unsafe m)) trl in
t_lambda vl trl (t_subst_unsafe m e)
| v::vl, t::tl ->
vs_check v t; add (Mvs.add v t m) vl tl in
add Mvs.empty vl tl
let t_func_app_beta_l lam tl =
let e = t_app_beta_l lam tl in
if e.t_ty = None then t_if e t_bool_true t_bool_false else e
let t_pred_app_beta_l lam tl =
let e = t_app_beta_l lam tl in
if e.t_ty = None then e else t_equ e t_bool_true
let t_func_app_beta lam t = t_func_app_beta_l lam [t]
let t_pred_app_beta lam t = t_pred_app_beta_l lam [t]
let t_not_simp f = match f.t_node with
| Ttrue -> t_attr_copy f t_false
| Tfalse -> t_attr_copy f t_true
| Tnot g -> t_attr_copy f g
| _ -> t_not f
let t_and_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> t_attr_remove asym_split f1
| Tfalse, _ -> t_attr_remove asym_split f1
| _, Tfalse -> f2
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_and f1 f2
let t_and_simp_l l = List.fold_right t_and_simp l t_true
let t_or_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> t_attr_remove asym_split f1
| _, Ttrue -> f2
| Tfalse, _ -> f2
| _, Tfalse -> t_attr_remove asym_split f1
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_or f1 f2
let t_or_simp_l l = List.fold_right t_or_simp l t_false
let t_and_asym_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> t_attr_remove asym_split f1
| Tfalse, _ -> t_attr_remove asym_split f1
| _, Tfalse -> f2
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_and_asym f1 f2
let t_and_asym_simp_l l = List.fold_right t_and_asym_simp l t_true
let t_or_asym_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> t_attr_remove asym_split f1
| _, Ttrue -> f2
| Tfalse, _ -> f2
| _, Tfalse -> t_attr_remove asym_split f1
| _, _ when t_equal f1 f2 -> f1
| _, _ -> t_or_asym f1 f2
let t_or_asym_simp_l l = List.fold_right t_or_asym_simp l t_false
let t_implies_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> f2
| Tfalse, _ -> t_attr_copy f1 t_true
| _, Tfalse -> t_not_simp f1
| _, _ when t_equal f1 f2 -> t_attr_copy f1 t_true
| _, _ -> t_implies f1 f2
let t_iff_simp f1 f2 = match f1.t_node, f2.t_node with
| Ttrue, _ -> f2
| _, Ttrue -> f1
| Tfalse, _ -> t_not_simp f2
| _, Tfalse -> t_not_simp f1
| _, _ when t_equal f1 f2 -> t_attr_copy f1 t_true
| _, _ -> t_iff f1 f2
let t_binary_simp op = match op with
| Tand -> t_and_simp
| Tor -> t_or_simp
| Timplies -> t_implies_simp
| Tiff -> t_iff_simp
let t_if_simp f1 f2 f3 = match f1.t_node, f2.t_node, f3.t_node with
| Ttrue, _, _ -> f2
| Tfalse, _, _ -> f3
| _, Ttrue, _ -> t_implies_simp (t_not_simp f1) f3
| _, Tfalse, _ -> t_and_asym_simp (t_not_simp f1) f3
| _, _, Ttrue -> t_implies_simp f1 f2
| _, _, Tfalse -> t_and_asym_simp f1 f2
| _, _, _ when t_equal f2 f3 -> f2
| _, _, _ -> t_if f1 f2 f3
let small t = match t.t_node with
| Tvar _ | Tconst _ -> true
| _ -> false
let t_let_simp e ((v,b,t) as bt) =
let n = t_v_occurs v t in
if n = 0 then
t_subst_unsafe b.bv_subst t else
if n = 1 || small e then begin
vs_check v e;
t_subst_unsafe (Mvs.add v e b.bv_subst) t
end else
t_let e bt
let t_let_close_simp v e t =
let n = t_v_occurs v t in
if n = 0 then t else
if n = 1 || small e then
t_subst_single v e t
else
t_let_close v e t
let t_case_simp t bl =
let e0,tl = match bl with
| [] -> raise EmptyCase
| (_,_,e0)::tl -> e0,tl in
let e0_true = match e0.t_node with
| Ttrue -> true | _ -> false in
let e0_false = match e0.t_node with
| Tfalse -> true | _ -> false in
let is_e0 (_,_,e) = match e.t_node with
| Ttrue -> e0_true
| Tfalse -> e0_false
| _ -> t_equal e e0 in
if t_closed e0 && List.for_all is_e0 tl then e0
else t_case t bl
let t_case_close_simp t bl =
let e0,tl = match bl with
| [] -> raise EmptyCase
| (_,e0)::tl -> e0,tl in
let e0_true = match e0.t_node with
| Ttrue -> true | _ -> false in
let e0_false = match e0.t_node with
| Tfalse -> true | _ -> false in
let is_e0 (_,e) = match e.t_node with
| Ttrue -> e0_true
| Tfalse -> e0_false
| _ -> t_equal e e0 in
if t_closed e0 && List.for_all is_e0 tl then e0
else t_case_close t bl
let t_quant_simp q ((vl,_,_,f) as qf) =
let fvs = t_vars f in
let check v = Mvs.mem v fvs in
if List.for_all check vl then
t_quant q qf
else
let vl,tl,f = t_open_quant qf in
let fvs = t_vars f in
let check v = Mvs.mem v fvs in
let vl = List.filter check vl in
if vl = [] then f
else t_quant_close q vl (List.filter (List.for_all (t_v_all check)) tl) f
let t_quant_close_simp q vl tl f =
if vl = [] then f else
let fvs = t_vars f in
let check v = Mvs.mem v fvs in
if List.for_all check vl then
t_quant_close q vl tl f
else
let vl = List.filter check vl in
if vl = [] then f
else t_quant_close q vl (List.filter (List.for_all (t_v_all check)) tl) f
let t_forall_simp = t_quant_simp Tforall
let t_exists_simp = t_quant_simp Texists
let t_forall_close_simp = t_quant_close_simp Tforall
let t_exists_close_simp = t_quant_close_simp Texists
let t_equ_simp t1 t2 =
if t_equal t1 t2 then t_true else t_equ t1 t2
let t_neq_simp t1 t2 =
if t_equal t1 t2 then t_false else t_neq t1 t2
let t_forall_close_merge vs f = match f.t_node with
| Tquant (Tforall, fq) ->
let vs', trs, f = t_open_quant fq in
t_forall_close (vs@vs') trs f
| _ -> t_forall_close vs [] f
let t_exists_close_merge vs f = match f.t_node with
| Tquant (Texists, fq) ->
let vs', trs, f = t_open_quant fq in
t_exists_close (vs@vs') trs f
| _ -> t_exists_close vs [] f
let t_map_simp fn f = t_attr_copy f (match f.t_node with
| Tapp (p, [t1;t2]) when ls_equal p ps_equ ->
t_equ_simp (fn t1) (fn t2)
| Tif (f1, f2, f3) ->
t_if_simp (fn f1) (fn f2) (fn f3)
| Tlet (t, b) ->
let u,t2,close = t_open_bound_cb b in
t_let_simp (fn t) (close u (fn t2))
| Tquant (q, b) ->
let vl,tl,f1,close = t_open_quant_cb b in
t_quant_simp q (close vl (tr_map fn tl) (fn f1))
| Tbinop (op, f1, f2) ->
t_binary_simp op (fn f1) (fn f2)
| Tnot f1 ->
t_not_simp (fn f1)
| _ -> t_map fn f)
let t_map_simp fn = t_map_simp (fun t ->
let res = fn t in t_ty_check res t.t_ty; res)
module TermTF = struct
let t_select fnT fnF e =
if e.t_ty = None then fnF e else fnT e
let t_selecti fnT fnF acc e =
if e.t_ty = None then fnF acc e else fnT acc e
let t_map fnT fnF = t_map (t_select fnT fnF)
let t_fold fnT fnF = t_fold (t_selecti fnT fnF)
let t_map_fold fnT fnF = t_map_fold (t_selecti fnT fnF)
let t_all prT prF = t_all (t_select prT prF)
let t_any prT prF = t_any (t_select prT prF)
let t_map_simp fnT fnF = t_map_simp (t_select fnT fnF)
let t_map_sign fnT fnF = t_map_sign (t_selecti fnT fnF)
let t_map_cont fnT fnF = t_map_cont (t_selecti fnT fnF)
let tr_map fnT fnF = tr_map (t_select fnT fnF)
let tr_fold fnT fnF = tr_fold (t_selecti fnT fnF)
let tr_map_fold fnT fnF = tr_map_fold (t_selecti fnT fnF)
end
|
da56080e764e3902fc08018373f11f319d7c049bf018be33698c2573e58ba13b | open-company/open-company-web | json.cljs | (ns oc.web.lib.json
(:require [clojure.walk :refer (stringify-keys)]))
(defn json->cljs [json-str]
(let [parsed-json (.parse ^js js/JSON json-str :keywordize-keys true)]
(js->clj parsed-json :keywordize-keys true)))
(defn cljs->json [coll]
(let [stringified-coll (stringify-keys coll)]
(clj->js stringified-coll))) | null | https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/lib/json.cljs | clojure | (ns oc.web.lib.json
(:require [clojure.walk :refer (stringify-keys)]))
(defn json->cljs [json-str]
(let [parsed-json (.parse ^js js/JSON json-str :keywordize-keys true)]
(js->clj parsed-json :keywordize-keys true)))
(defn cljs->json [coll]
(let [stringified-coll (stringify-keys coll)]
(clj->js stringified-coll))) | |
55970a4677261a2fe279b855325d42dc1a9c26deda66ea3aee5452a5dfba46f4 | jeromesimeon/Galax | small_stream_context.mli | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : small_stream_context.mli , v 1.6 2007/02/01 22:08:54 simeon Exp $
(* Module: Small_stream_context
Description:
This module implements the context used when building a small
stream from an element-construction expression.
*)
open Error
(****************************)
(* The small stream context *)
(****************************)
type ss_context
(**************************************)
(* Creates a new small stream context *)
(**************************************)
val build_ss_context : Small_stream_ast.sexpr list -> ss_context
(******************************************)
(* Operations on the small stream context *)
(******************************************)
val get_current_sexpr_list : ss_context -> Small_stream_ast.sexpr list
val get_remaining_sexpr_list : ss_context -> Small_stream_ast.sexpr list
val replace_current_sexpr_list : ss_context -> Small_stream_ast.sexpr list -> unit
val push_elem_to_ss_context :
ss_context -> Small_stream_ast.sexpr -> Small_stream_ast.sexpr list -> Streaming_types.sax_event * Small_stream_ast.sexpr list
val pop_elem_from_ss_context :
ss_context -> (Streaming_types.sax_event * Small_stream_ast.sexpr list) option
(******************************)
(* Simple stream constructors *)
(******************************)
val resolved_xml_stream_of_sexpr : Small_stream_ast.sexpr -> Streaming_types.xml_stream
Builds an XML stream with holes out of a fragment of AST which
contains element construction operations .
contains element construction operations. *)
val sexpr_of_rsexpr : Namespace_context.nsenv -> Small_stream_ast.sexpr -> Small_stream_ast.sexpr
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/streaming/small_stream_context.mli | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Small_stream_context
Description:
This module implements the context used when building a small
stream from an element-construction expression.
**************************
The small stream context
**************************
************************************
Creates a new small stream context
************************************
****************************************
Operations on the small stream context
****************************************
****************************
Simple stream constructors
**************************** | Copyright 2001 - 2007 .
$ I d : small_stream_context.mli , v 1.6 2007/02/01 22:08:54 simeon Exp $
open Error
type ss_context
val build_ss_context : Small_stream_ast.sexpr list -> ss_context
val get_current_sexpr_list : ss_context -> Small_stream_ast.sexpr list
val get_remaining_sexpr_list : ss_context -> Small_stream_ast.sexpr list
val replace_current_sexpr_list : ss_context -> Small_stream_ast.sexpr list -> unit
val push_elem_to_ss_context :
ss_context -> Small_stream_ast.sexpr -> Small_stream_ast.sexpr list -> Streaming_types.sax_event * Small_stream_ast.sexpr list
val pop_elem_from_ss_context :
ss_context -> (Streaming_types.sax_event * Small_stream_ast.sexpr list) option
val resolved_xml_stream_of_sexpr : Small_stream_ast.sexpr -> Streaming_types.xml_stream
Builds an XML stream with holes out of a fragment of AST which
contains element construction operations .
contains element construction operations. *)
val sexpr_of_rsexpr : Namespace_context.nsenv -> Small_stream_ast.sexpr -> Small_stream_ast.sexpr
|
c42c3bd1c1b1f784661ed93c2f85125b13bdf8f82dbfb02d9dd642bba7700370 | brendanhay/gogol | Modify.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 : . People . . Members . Modify
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Modify the members of a contact group owned by the authenticated user . The only system contact groups that can have members added are @contactGroups\/myContacts@ and @contactGroups\/starred@. Other system contact groups are deprecated and can only have contacts removed .
--
/See:/ < / People API Reference > for @people.contactGroups.members.modify@.
module Gogol.People.ContactGroups.Members.Modify
( -- * Resource
PeopleContactGroupsMembersModifyResource,
-- ** Constructing a Request
PeopleContactGroupsMembersModify (..),
newPeopleContactGroupsMembersModify,
)
where
import Gogol.People.Types
import qualified Gogol.Prelude as Core
-- | A resource alias for @people.contactGroups.members.modify@ method which the
-- 'PeopleContactGroupsMembersModify' request conforms to.
type PeopleContactGroupsMembersModifyResource =
"v1"
Core.:> Core.Capture "resourceName" Core.Text
Core.:> "members:modify"
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody
'[Core.JSON]
ModifyContactGroupMembersRequest
Core.:> Core.Post
'[Core.JSON]
ModifyContactGroupMembersResponse
| Modify the members of a contact group owned by the authenticated user . The only system contact groups that can have members added are @contactGroups\/myContacts@ and @contactGroups\/starred@. Other system contact groups are deprecated and can only have contacts removed .
--
-- /See:/ 'newPeopleContactGroupsMembersModify' smart constructor.
data PeopleContactGroupsMembersModify = PeopleContactGroupsMembersModify
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | Multipart request metadata.
payload :: ModifyContactGroupMembersRequest,
-- | Required. The resource name of the contact group to modify.
resourceName :: Core.Text,
| 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 'PeopleContactGroupsMembersModify' with the minimum fields required to make a request.
newPeopleContactGroupsMembersModify ::
-- | Multipart request metadata. See 'payload'.
ModifyContactGroupMembersRequest ->
-- | Required. The resource name of the contact group to modify. See 'resourceName'.
Core.Text ->
PeopleContactGroupsMembersModify
newPeopleContactGroupsMembersModify payload resourceName =
PeopleContactGroupsMembersModify
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
payload = payload,
resourceName = resourceName,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
PeopleContactGroupsMembersModify
where
type
Rs PeopleContactGroupsMembersModify =
ModifyContactGroupMembersResponse
type
Scopes PeopleContactGroupsMembersModify =
'[Contacts'FullControl]
requestClient PeopleContactGroupsMembersModify {..} =
go
resourceName
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
peopleService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy PeopleContactGroupsMembersModifyResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-people/gen/Gogol/People/ContactGroups/Members/Modify.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Resource
** Constructing a Request
| A resource alias for @people.contactGroups.members.modify@ method which the
'PeopleContactGroupsMembersModify' request conforms to.
/See:/ 'newPeopleContactGroupsMembersModify' smart constructor.
| V1 error format.
| OAuth access token.
| Multipart request metadata.
| Required. The resource name of the contact group to modify.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'PeopleContactGroupsMembersModify' with the minimum fields required to make a request.
| Multipart request metadata. See 'payload'.
| Required. The resource name of the contact group to modify. See 'resourceName'. | # 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 : . People . . Members . Modify
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Modify the members of a contact group owned by the authenticated user . The only system contact groups that can have members added are @contactGroups\/myContacts@ and @contactGroups\/starred@. Other system contact groups are deprecated and can only have contacts removed .
/See:/ < / People API Reference > for @people.contactGroups.members.modify@.
module Gogol.People.ContactGroups.Members.Modify
PeopleContactGroupsMembersModifyResource,
PeopleContactGroupsMembersModify (..),
newPeopleContactGroupsMembersModify,
)
where
import Gogol.People.Types
import qualified Gogol.Prelude as Core
type PeopleContactGroupsMembersModifyResource =
"v1"
Core.:> Core.Capture "resourceName" Core.Text
Core.:> "members:modify"
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody
'[Core.JSON]
ModifyContactGroupMembersRequest
Core.:> Core.Post
'[Core.JSON]
ModifyContactGroupMembersResponse
| Modify the members of a contact group owned by the authenticated user . The only system contact groups that can have members added are @contactGroups\/myContacts@ and @contactGroups\/starred@. Other system contact groups are deprecated and can only have contacts removed .
data PeopleContactGroupsMembersModify = PeopleContactGroupsMembersModify
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
payload :: ModifyContactGroupMembersRequest,
resourceName :: Core.Text,
| 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)
newPeopleContactGroupsMembersModify ::
ModifyContactGroupMembersRequest ->
Core.Text ->
PeopleContactGroupsMembersModify
newPeopleContactGroupsMembersModify payload resourceName =
PeopleContactGroupsMembersModify
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
payload = payload,
resourceName = resourceName,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
PeopleContactGroupsMembersModify
where
type
Rs PeopleContactGroupsMembersModify =
ModifyContactGroupMembersResponse
type
Scopes PeopleContactGroupsMembersModify =
'[Contacts'FullControl]
requestClient PeopleContactGroupsMembersModify {..} =
go
resourceName
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
peopleService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy PeopleContactGroupsMembersModifyResource
)
Core.mempty
|
ecea4e6faeeb046348247bdecd64c5283aa3e21c2920b2f33d9fc2366b36e395 | lthms/spatial-sway | message.ml | type subscribe_reply = { success : bool }
let subscribe_reply_decoder =
let open Json_decoder in
let open Syntax in
let+ success = field "success" bool in
{ success }
type run_command_reply = {
success : bool;
parse_error : bool option;
error : string option;
}
let run_command_reply_decoder =
let open Json_decoder in
let open Syntax in
let+ success = field "success" bool
and+ parse_error = field_opt "parse_error" bool
and+ error = field_opt "error" string in
{ success; parse_error; error }
type _ t =
| Run_command : Command.t list -> run_command_reply list t
| Get_workspaces : Workspace.t list t
| Subscribe : Event.event_type list -> subscribe_reply t
| Get_tree : Node.t t
| Get_outputs : Output.t list t
let to_raw_message : type reply. reply t -> Mltp_ipc.Raw_message.t = function
| Run_command cmds ->
( 0l,
Format.(
asprintf "%a"
(pp_print_list
~pp_sep:(fun fmt () -> pp_print_string fmt "\n")
(fun fmt x -> fprintf fmt "%a" Command.pp x))
cmds) )
| Get_workspaces -> (1l, "")
| Subscribe evs ->
( 2l,
Format.(
asprintf "[%a]"
(pp_print_list
~pp_sep:(fun fmt () -> pp_print_string fmt ", ")
(fun fmt x -> fprintf fmt "\"%s\"" (Event.event_type_string x)))
evs) )
| Get_outputs -> (3l, "")
| Get_tree -> (4l, "")
let reply_decoder : type reply. reply t -> reply Json_decoder.t = function
| Run_command _ -> Json_decoder.list run_command_reply_decoder
| Get_workspaces -> Json_decoder.list Workspace.decoder
| Subscribe _ -> subscribe_reply_decoder
| Get_outputs -> Json_decoder.list Output.decoder
| Get_tree -> Node.decoder
| null | https://raw.githubusercontent.com/lthms/spatial-sway/5e5072c75e0a1a1d58de9409e2ef09ef033cc569/lib/sway_ipc_types/message.ml | ocaml | type subscribe_reply = { success : bool }
let subscribe_reply_decoder =
let open Json_decoder in
let open Syntax in
let+ success = field "success" bool in
{ success }
type run_command_reply = {
success : bool;
parse_error : bool option;
error : string option;
}
let run_command_reply_decoder =
let open Json_decoder in
let open Syntax in
let+ success = field "success" bool
and+ parse_error = field_opt "parse_error" bool
and+ error = field_opt "error" string in
{ success; parse_error; error }
type _ t =
| Run_command : Command.t list -> run_command_reply list t
| Get_workspaces : Workspace.t list t
| Subscribe : Event.event_type list -> subscribe_reply t
| Get_tree : Node.t t
| Get_outputs : Output.t list t
let to_raw_message : type reply. reply t -> Mltp_ipc.Raw_message.t = function
| Run_command cmds ->
( 0l,
Format.(
asprintf "%a"
(pp_print_list
~pp_sep:(fun fmt () -> pp_print_string fmt "\n")
(fun fmt x -> fprintf fmt "%a" Command.pp x))
cmds) )
| Get_workspaces -> (1l, "")
| Subscribe evs ->
( 2l,
Format.(
asprintf "[%a]"
(pp_print_list
~pp_sep:(fun fmt () -> pp_print_string fmt ", ")
(fun fmt x -> fprintf fmt "\"%s\"" (Event.event_type_string x)))
evs) )
| Get_outputs -> (3l, "")
| Get_tree -> (4l, "")
let reply_decoder : type reply. reply t -> reply Json_decoder.t = function
| Run_command _ -> Json_decoder.list run_command_reply_decoder
| Get_workspaces -> Json_decoder.list Workspace.decoder
| Subscribe _ -> subscribe_reply_decoder
| Get_outputs -> Json_decoder.list Output.decoder
| Get_tree -> Node.decoder
| |
b771983026c2a8ad3781d2909457cd9e72c4b26927dd3314e7500468b08cbe6c | fccm/glMLite | movelight.ml | Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use , copy , modify , and distribute this software for
* any purpose and without fee is hereby granted , provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation , and that
* the name of Silicon Graphics , Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific ,
* written prior permission .
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS "
* AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE ,
* INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON
* GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT ,
* SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION ,
* LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF
* THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE .
*
* US Government Users Restricted Rights
* Use , duplication , or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph
* ( c)(1)(ii ) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227 - 7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement .
* Unpublished-- rights reserved under the copyright laws of the
* United States . Contractor / manufacturer is Silicon Graphics ,
* Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 .
*
* OpenGL(R ) is a registered trademark of Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(R) is a registered trademark of Silicon Graphics, Inc.
*)
movelight.ml
* This program demonstrates when to issue lighting and
* transformation commands to render a model with a light
* which is moved by a modeling transformation ( rotate or
* translate ) . The light position is reset after the modeling
* transformation is called . The eye position does not change .
*
* A sphere is drawn using a grey material characteristic .
* A single light source illuminates the object .
*
* Interaction : pressing the left mouse button alters
* the modeling transformation ( x rotation ) by 30 degrees .
* The scene is then redrawn with the light in a new position .
* This program demonstrates when to issue lighting and
* transformation commands to render a model with a light
* which is moved by a modeling transformation (rotate or
* translate). The light position is reset after the modeling
* transformation is called. The eye position does not change.
*
* A sphere is drawn using a grey material characteristic.
* A single light source illuminates the object.
*
* Interaction: pressing the left mouse button alters
* the modeling transformation (x rotation) by 30 degrees.
* The scene is then redrawn with the light in a new position.
*)
Ported from C to OCaml by
open GL
open Glu
open Glut
let spin = ref 0
Initialize material property , light source , lighting model ,
* and depth buffer .
* and depth buffer.
*)
let init() =
glClearColor 0.0 0.0 0.0 0.0;
glShadeModel GL_SMOOTH;
glEnable GL_LIGHTING;
glEnable GL_LIGHT0;
glEnable GL_DEPTH_TEST;
;;
(* Here is where the light position is reset after the modeling
* transformation (glRotated) is called. This places the
* light at a new position in world coordinates. The cube
* represents the position of the light.
*)
let display() =
let position = (0.0, 0.0, 1.5, 1.0) in
glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
glPushMatrix ();
gluLookAt 0.0 0.0 5.0 0.0 0.0 0.0 0.0 1.0 0.0;
glPushMatrix ();
glRotate (float !spin) 1.0 0.0 0.0;
glLight (GL_LIGHT 0) (Light.GL_POSITION position);
glTranslate 0.0 0.0 1.5;
glDisable GL_LIGHTING;
glColor3 0.0 1.0 1.0;
glutWireCube 0.1;
glEnable GL_LIGHTING;
glPopMatrix ();
glutSolidTorus 0.275 0.85 8 15;
glPopMatrix ();
glFlush ();
;;
let reshape ~width:w ~height:h =
glViewport 0 0 w h;
glMatrixMode GL_PROJECTION;
glLoadIdentity();
gluPerspective 40.0 (float w /. float h) 1.0 20.0;
glMatrixMode GL_MODELVIEW;
glLoadIdentity();
;;
ARGSUSED2
let mouse ~button ~state ~x ~y =
match button with
| GLUT_LEFT_BUTTON ->
if state = GLUT_DOWN then begin
spin := (!spin + 10) mod 360;
glutPostRedisplay();
end
| _ -> ()
;;
ARGSUSED1
let keyboard ~key ~x ~y =
match key with
| '\027' -> (* escape *)
exit(0);
| _ -> ()
;;
let () =
let _ = glutInit Sys.argv in
glutInitDisplayMode [GLUT_SINGLE; GLUT_RGB; GLUT_DEPTH];
glutInitWindowSize 500 500;
glutInitWindowPosition 100 100;
let _ = glutCreateWindow Sys.argv.(0) in
init ();
glutDisplayFunc ~display;
glutReshapeFunc ~reshape;
glutMouseFunc ~mouse;
glutKeyboardFunc ~keyboard;
glutMainLoop();
;;
| null | https://raw.githubusercontent.com/fccm/glMLite/c52cd806909581e49d9b660195576c8a932f6d33/RedBook-Samples/movelight.ml | ocaml | Here is where the light position is reset after the modeling
* transformation (glRotated) is called. This places the
* light at a new position in world coordinates. The cube
* represents the position of the light.
escape | Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use , copy , modify , and distribute this software for
* any purpose and without fee is hereby granted , provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation , and that
* the name of Silicon Graphics , Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific ,
* written prior permission .
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS "
* AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE ,
* INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON
* GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT ,
* SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION ,
* LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF
* THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE .
*
* US Government Users Restricted Rights
* Use , duplication , or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph
* ( c)(1)(ii ) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227 - 7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement .
* Unpublished-- rights reserved under the copyright laws of the
* United States . Contractor / manufacturer is Silicon Graphics ,
* Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 .
*
* OpenGL(R ) is a registered trademark of Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(R) is a registered trademark of Silicon Graphics, Inc.
*)
movelight.ml
* This program demonstrates when to issue lighting and
* transformation commands to render a model with a light
* which is moved by a modeling transformation ( rotate or
* translate ) . The light position is reset after the modeling
* transformation is called . The eye position does not change .
*
* A sphere is drawn using a grey material characteristic .
* A single light source illuminates the object .
*
* Interaction : pressing the left mouse button alters
* the modeling transformation ( x rotation ) by 30 degrees .
* The scene is then redrawn with the light in a new position .
* This program demonstrates when to issue lighting and
* transformation commands to render a model with a light
* which is moved by a modeling transformation (rotate or
* translate). The light position is reset after the modeling
* transformation is called. The eye position does not change.
*
* A sphere is drawn using a grey material characteristic.
* A single light source illuminates the object.
*
* Interaction: pressing the left mouse button alters
* the modeling transformation (x rotation) by 30 degrees.
* The scene is then redrawn with the light in a new position.
*)
Ported from C to OCaml by
open GL
open Glu
open Glut
let spin = ref 0
Initialize material property , light source , lighting model ,
* and depth buffer .
* and depth buffer.
*)
let init() =
glClearColor 0.0 0.0 0.0 0.0;
glShadeModel GL_SMOOTH;
glEnable GL_LIGHTING;
glEnable GL_LIGHT0;
glEnable GL_DEPTH_TEST;
;;
let display() =
let position = (0.0, 0.0, 1.5, 1.0) in
glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
glPushMatrix ();
gluLookAt 0.0 0.0 5.0 0.0 0.0 0.0 0.0 1.0 0.0;
glPushMatrix ();
glRotate (float !spin) 1.0 0.0 0.0;
glLight (GL_LIGHT 0) (Light.GL_POSITION position);
glTranslate 0.0 0.0 1.5;
glDisable GL_LIGHTING;
glColor3 0.0 1.0 1.0;
glutWireCube 0.1;
glEnable GL_LIGHTING;
glPopMatrix ();
glutSolidTorus 0.275 0.85 8 15;
glPopMatrix ();
glFlush ();
;;
let reshape ~width:w ~height:h =
glViewport 0 0 w h;
glMatrixMode GL_PROJECTION;
glLoadIdentity();
gluPerspective 40.0 (float w /. float h) 1.0 20.0;
glMatrixMode GL_MODELVIEW;
glLoadIdentity();
;;
ARGSUSED2
let mouse ~button ~state ~x ~y =
match button with
| GLUT_LEFT_BUTTON ->
if state = GLUT_DOWN then begin
spin := (!spin + 10) mod 360;
glutPostRedisplay();
end
| _ -> ()
;;
ARGSUSED1
let keyboard ~key ~x ~y =
match key with
exit(0);
| _ -> ()
;;
let () =
let _ = glutInit Sys.argv in
glutInitDisplayMode [GLUT_SINGLE; GLUT_RGB; GLUT_DEPTH];
glutInitWindowSize 500 500;
glutInitWindowPosition 100 100;
let _ = glutCreateWindow Sys.argv.(0) in
init ();
glutDisplayFunc ~display;
glutReshapeFunc ~reshape;
glutMouseFunc ~mouse;
glutKeyboardFunc ~keyboard;
glutMainLoop();
;;
|
784ada773a5e4e5e527de23ea368dd8963d1b56744b1c2d000950dbc75f1a605 | crystodev/cato | Address.hs | -- address helpers ---------------------------------------------------------------------
module Address ( createKeyPair, Address (..), AddressType(Payment, Stake), getAddressFromFile, getAddressFile, getSKeyFile, getVKeyFile, ) where
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath (takeDirectory)
import System.IO (hGetContents)
import System.Process (StdStream (CreatePipe), createProcess, proc,
std_out, waitForProcess)
import Policy (signingKeyExt, verificationKeyExt)
import Wallet (getAddressPath, Owner(..))
-- data AdressOrKey = address | signing_key | verification_key deriving (Read, Show, Eq)
newtype Address = Address { getAddress :: String } deriving (Eq)
data AddressType = Payment | Stake deriving (Read, Show, Eq)
-- create key pair based on address_name
createKeyPair :: AddressType -> FilePath -> Owner -> IO Bool
createKeyPair addressType addressesPath owner = do
let vKeyFile = getVKeyFile addressesPath addressType owner
let sKeyFile = getSKeyFile addressesPath addressType owner
bool <- doesFileExist vKeyFile
if bool then do
putStrLn $ "key pair already exists for " ++ getOwner owner
return False
else do
createDirectoryIfMissing True (takeDirectory vKeyFile)
let sAddressType = if addressType == Payment then "address" else "stake-address"
(_, Just rc, _, ph) <- createProcess (proc "cardano-cli" [sAddressType, "key-gen", "--verification-key-file", vKeyFile, "--signing-key-file", sKeyFile]){ std_out = CreatePipe }
r <- waitForProcess ph
return True
-- get address from file
getAddressFromFile :: FilePath -> IO (Maybe Address)
getAddressFromFile addressFileName = do
bool <- doesFileExist addressFileName
if not bool then do
putStrLn $ "file not found : " ++ addressFileName
return Nothing
else do
addr <- readFile addressFileName
return (Just $ Address addr)
-- give file name for name type address or key
getAddressKeyFile :: FilePath -> AddressType -> String -> Owner -> FilePath
getAddressKeyFile addressesPath addressType addressKey owner = do
let sAddressType = if addressType == Payment then "payment" else "stake"
let extMap = [ ("address", ".addr"), ("signing_key", signingKeyExt), ("verification_key", verificationKeyExt)]
let extM = lookup addressKey extMap
case extM of
Just ext -> getAddressPath addressesPath owner ++ sAddressType ++ getOwner owner ++ ext
_ -> ""
-- give file name for name type address
getAddressFile :: FilePath -> AddressType -> Owner -> FilePath
getAddressFile addressesPath addressType = getAddressKeyFile addressesPath addressType "address"
-- give file name for name type signing key
getSKeyFile :: FilePath -> AddressType -> Owner -> FilePath
getSKeyFile addressesPath addressType = getAddressKeyFile addressesPath addressType "signing_key"
-- give file name for name type verification key
getVKeyFile :: FilePath -> AddressType -> Owner -> FilePath
getVKeyFile addressesPath addressType = getAddressKeyFile addressesPath addressType "verification_key"
| null | https://raw.githubusercontent.com/crystodev/cato/ae93afe078ffb6d942a5725db07d27d3d896b8a5/src/Address.hs | haskell | address helpers ---------------------------------------------------------------------
data AdressOrKey = address | signing_key | verification_key deriving (Read, Show, Eq)
create key pair based on address_name
get address from file
give file name for name type address or key
give file name for name type address
give file name for name type signing key
give file name for name type verification key | module Address ( createKeyPair, Address (..), AddressType(Payment, Stake), getAddressFromFile, getAddressFile, getSKeyFile, getVKeyFile, ) where
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath (takeDirectory)
import System.IO (hGetContents)
import System.Process (StdStream (CreatePipe), createProcess, proc,
std_out, waitForProcess)
import Policy (signingKeyExt, verificationKeyExt)
import Wallet (getAddressPath, Owner(..))
newtype Address = Address { getAddress :: String } deriving (Eq)
data AddressType = Payment | Stake deriving (Read, Show, Eq)
createKeyPair :: AddressType -> FilePath -> Owner -> IO Bool
createKeyPair addressType addressesPath owner = do
let vKeyFile = getVKeyFile addressesPath addressType owner
let sKeyFile = getSKeyFile addressesPath addressType owner
bool <- doesFileExist vKeyFile
if bool then do
putStrLn $ "key pair already exists for " ++ getOwner owner
return False
else do
createDirectoryIfMissing True (takeDirectory vKeyFile)
let sAddressType = if addressType == Payment then "address" else "stake-address"
(_, Just rc, _, ph) <- createProcess (proc "cardano-cli" [sAddressType, "key-gen", "--verification-key-file", vKeyFile, "--signing-key-file", sKeyFile]){ std_out = CreatePipe }
r <- waitForProcess ph
return True
getAddressFromFile :: FilePath -> IO (Maybe Address)
getAddressFromFile addressFileName = do
bool <- doesFileExist addressFileName
if not bool then do
putStrLn $ "file not found : " ++ addressFileName
return Nothing
else do
addr <- readFile addressFileName
return (Just $ Address addr)
getAddressKeyFile :: FilePath -> AddressType -> String -> Owner -> FilePath
getAddressKeyFile addressesPath addressType addressKey owner = do
let sAddressType = if addressType == Payment then "payment" else "stake"
let extMap = [ ("address", ".addr"), ("signing_key", signingKeyExt), ("verification_key", verificationKeyExt)]
let extM = lookup addressKey extMap
case extM of
Just ext -> getAddressPath addressesPath owner ++ sAddressType ++ getOwner owner ++ ext
_ -> ""
getAddressFile :: FilePath -> AddressType -> Owner -> FilePath
getAddressFile addressesPath addressType = getAddressKeyFile addressesPath addressType "address"
getSKeyFile :: FilePath -> AddressType -> Owner -> FilePath
getSKeyFile addressesPath addressType = getAddressKeyFile addressesPath addressType "signing_key"
getVKeyFile :: FilePath -> AddressType -> Owner -> FilePath
getVKeyFile addressesPath addressType = getAddressKeyFile addressesPath addressType "verification_key"
|
83bc44733698e9f3a7e977fb51b3016f382d65409367d161d05c1276ecc6bfcc | diffusionkinetics/open | Logistic.hs | module Fuml.Base.Logistic where
import Numeric.LinearAlgebra
import qualified Data.Vector.Storable as VS
import Fuml.Optimisation.BFGS
import Data.List (foldl1')
-- maybe follow this: -regression-and-automated-differentiation-3/
logit :: Floating a => a -> a
logit x = 1 / (1 + exp (negate x))
logLikelihood1 :: Vector Double -> Vector Double -> Bool -> Double
logLikelihood1 theta x y = ind y * log (logit z) +
(1 - ind y) * log (1 - logit z)
where
z = VS.sum $ VS.zipWith (*) theta x
-- negative log likelihood
logLikelihood :: Double -> [(Vector Double, Bool)] -> Vector Double -> Double
logLikelihood delta theData theta = negate $ (a - delta*b)/l where
l = fromIntegral $ length theData
a = sum $ map (uncurry $ logLikelihood1 theta) theData
b = (/2) $ VS.sum $ VS.map (^2) theta
--
gradLogLikelihood1 :: Vector Double -> Vector Double -> Bool -> Vector Double
gradLogLikelihood1 theta x y = VS.map (*(ind y - lz)) x
-- (1 - ind y) * log (1 - logit z)
where
z = VS.sum $ VS.zipWith (*) theta x
lz = logit z
gradLogLikelihood :: Double -> [(Vector Double, Bool)] -> Vector Double -> Vector Double
gradLogLikelihood delta theData theta =
let vs = map (uncurry $ gradLogLikelihood1 theta) theData
vsum = foldl1' vadd vs
l = fromIntegral $ length theData
in VS.map (negate . (/l)) vsum `vadd` VS.map ((/l) . (*delta)) theta
logisticRegression :: [(Vector Double, Bool)] -> Vector Double
logisticRegression theData =
let start = VS.map (const 0) $ fst $ head theData
inisbox = VS.map (const (0.1:: Double)) $ fst $ head theData
hessInit = ident $ size start
fst $ minimizeV NMSimplex 1e-4 200 inisbox ( logLikelihood theData ) start
fst $ minimizeVD ConjugateFR 1e-10 500 0.01 0.01 ( logLikelihood theData ) ( gradLogLikelihood theData ) start -- inisbox ( logLikelihood theData ) start
case bfgsWith myBOpts (logLikelihood 0 theData) (gradLogLikelihood 0 theData) start hessInit of
Left s -> error s
Right (p, h) -> p
fst $ minimizeV NMSimplex 1e-3 100 inisbox ( logLikelihood theData ) start
myBOpts = BFGSOpts 1e-7 2e-5 200
ind :: Bool -> Double
ind True = 1
ind False = 0
vadd :: Vector Double -> Vector Double -> Vector Double
vadd = VS.zipWith (+)
| null | https://raw.githubusercontent.com/diffusionkinetics/open/673d9a4a099abd9035ccc21e37d8e614a45a1901/fuml/lib/Fuml/Base/Logistic.hs | haskell | maybe follow this: -regression-and-automated-differentiation-3/
negative log likelihood
(1 - ind y) * log (1 - logit z)
inisbox ( logLikelihood theData ) start | module Fuml.Base.Logistic where
import Numeric.LinearAlgebra
import qualified Data.Vector.Storable as VS
import Fuml.Optimisation.BFGS
import Data.List (foldl1')
logit :: Floating a => a -> a
logit x = 1 / (1 + exp (negate x))
logLikelihood1 :: Vector Double -> Vector Double -> Bool -> Double
logLikelihood1 theta x y = ind y * log (logit z) +
(1 - ind y) * log (1 - logit z)
where
z = VS.sum $ VS.zipWith (*) theta x
logLikelihood :: Double -> [(Vector Double, Bool)] -> Vector Double -> Double
logLikelihood delta theData theta = negate $ (a - delta*b)/l where
l = fromIntegral $ length theData
a = sum $ map (uncurry $ logLikelihood1 theta) theData
b = (/2) $ VS.sum $ VS.map (^2) theta
gradLogLikelihood1 :: Vector Double -> Vector Double -> Bool -> Vector Double
gradLogLikelihood1 theta x y = VS.map (*(ind y - lz)) x
where
z = VS.sum $ VS.zipWith (*) theta x
lz = logit z
gradLogLikelihood :: Double -> [(Vector Double, Bool)] -> Vector Double -> Vector Double
gradLogLikelihood delta theData theta =
let vs = map (uncurry $ gradLogLikelihood1 theta) theData
vsum = foldl1' vadd vs
l = fromIntegral $ length theData
in VS.map (negate . (/l)) vsum `vadd` VS.map ((/l) . (*delta)) theta
logisticRegression :: [(Vector Double, Bool)] -> Vector Double
logisticRegression theData =
let start = VS.map (const 0) $ fst $ head theData
inisbox = VS.map (const (0.1:: Double)) $ fst $ head theData
hessInit = ident $ size start
fst $ minimizeV NMSimplex 1e-4 200 inisbox ( logLikelihood theData ) start
case bfgsWith myBOpts (logLikelihood 0 theData) (gradLogLikelihood 0 theData) start hessInit of
Left s -> error s
Right (p, h) -> p
fst $ minimizeV NMSimplex 1e-3 100 inisbox ( logLikelihood theData ) start
myBOpts = BFGSOpts 1e-7 2e-5 200
ind :: Bool -> Double
ind True = 1
ind False = 0
vadd :: Vector Double -> Vector Double -> Vector Double
vadd = VS.zipWith (+)
|
309cd2c5d0772ddf1813d556bd6de00b6b1802086ce8768de4abec978367c32f | sergv/hkanren | IntegerLVar.hs | ----------------------------------------------------------------------------
-- |
Module : Language . . IntegerLVar
Copyright : ( c ) 2015
-- License : BSD3-style (see LICENSE)
--
-- Maintainer :
-- Stability :
-- Portability :
--
Unsafe but fast Integer - based LVars .
----------------------------------------------------------------------------
# LANGUAGE FlexibleContexts #
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE UndecidableInstances #
module Language.HKanren.IntegerLVar
(LVar)
where
import Control.DeepSeq
import Data.HOrdering
import Data.HUtils
import Data.Map (Map)
import qualified Data.Map as M
import Data.Type.Equality
import qualified Text.PrettyPrint.Leijen.Text as PP
import qualified Language.HKanren.LVar as L
import Language.HKanren.Type
import Unsafe.Coerce
type LTerm h = HFree h (LVar h)
newtype LVar (f :: (* -> *) -> (* -> *)) ix = LVar Integer
instance HEq (LVar h) where
# INLINABLE heq #
heq (LVar n) (LVar m) = n == m
instance (HEqHet (Type (h (LTerm h)))) => HEqHet (LVar h) where
# INLINABLE heqIx #
heqIx (LVar n) (LVar m) =
if n == m
then unsafeCoerce $ Just Refl
else Nothing
(==*) (LVar n) (LVar m) = n == m
instance HOrd (LVar h) where
# INLINABLE hcompare #
hcompare (LVar n) (LVar m) = compare n m
instance (HOrdHet (Type (h (LTerm h)))) => HOrdHet (LVar h) where
{-# INLINABLE hcompareIx #-}
hcompareIx (LVar n) (LVar m) =
# SCC hcompareIx_integer_lvar #
case compare n m of
LT -> HLT
EQ -> unsafeCoerce HEQ
GT -> HGT
hcompareHet (LVar n) (LVar m) = {-# SCC hcompareHet_integer_lvar #-} compare n m
instance HShow (LVar f) where
hshowsPrec n (LVar m) = \xs -> showParen (n == 11) (\ys -> "LVar " ++ show m ++ ys) xs
instance HPretty (LVar f) where
hpretty (LVar m) = PP.angles $ PP.integer m
instance HNFData (LVar f) where
hrnf (LVar m) = rnf m
instance (HOrdHet (Type (h (LTerm h)))) => L.LVar (LVar h) where
type LFunctor (LVar h) = h
type LDomain (LVar h) = Integer
newtype LMap (LVar h) = IntegerLMap { getIntegerLMap :: Map Integer (Some (LTerm h)) }
mkLVar = LVar
getDomain (LVar x) = x
empty = IntegerLMap M.empty
size = fromIntegral . M.size . getIntegerLMap
insert (LVar k) v = IntegerLMap . M.insert k (Some v) . getIntegerLMap
lookup (LVar k) m =
case M.lookup k $ getIntegerLMap m of
Nothing -> Nothing
Just (Some x) -> Just $ unsafeCoerce x
domain = M.keys . getIntegerLMap
keys = map (Some . LVar) . M.keys . getIntegerLMap
toList = map (\(k, Some v) -> (Some $ LVar k :*: v)) . M.toList . getIntegerLMap
| null | https://raw.githubusercontent.com/sergv/hkanren/94a9038f5885471c9f4d3b17a8e52af4e7747af3/src/Language/HKanren/IntegerLVar.hs | haskell | --------------------------------------------------------------------------
|
License : BSD3-style (see LICENSE)
Maintainer :
Stability :
Portability :
--------------------------------------------------------------------------
# LANGUAGE KindSignatures #
# LANGUAGE TypeFamilies #
# INLINABLE hcompareIx #
# SCC hcompareHet_integer_lvar # | Module : Language . . IntegerLVar
Copyright : ( c ) 2015
Unsafe but fast Integer - based LVars .
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
module Language.HKanren.IntegerLVar
(LVar)
where
import Control.DeepSeq
import Data.HOrdering
import Data.HUtils
import Data.Map (Map)
import qualified Data.Map as M
import Data.Type.Equality
import qualified Text.PrettyPrint.Leijen.Text as PP
import qualified Language.HKanren.LVar as L
import Language.HKanren.Type
import Unsafe.Coerce
type LTerm h = HFree h (LVar h)
newtype LVar (f :: (* -> *) -> (* -> *)) ix = LVar Integer
instance HEq (LVar h) where
# INLINABLE heq #
heq (LVar n) (LVar m) = n == m
instance (HEqHet (Type (h (LTerm h)))) => HEqHet (LVar h) where
# INLINABLE heqIx #
heqIx (LVar n) (LVar m) =
if n == m
then unsafeCoerce $ Just Refl
else Nothing
(==*) (LVar n) (LVar m) = n == m
instance HOrd (LVar h) where
# INLINABLE hcompare #
hcompare (LVar n) (LVar m) = compare n m
instance (HOrdHet (Type (h (LTerm h)))) => HOrdHet (LVar h) where
hcompareIx (LVar n) (LVar m) =
# SCC hcompareIx_integer_lvar #
case compare n m of
LT -> HLT
EQ -> unsafeCoerce HEQ
GT -> HGT
instance HShow (LVar f) where
hshowsPrec n (LVar m) = \xs -> showParen (n == 11) (\ys -> "LVar " ++ show m ++ ys) xs
instance HPretty (LVar f) where
hpretty (LVar m) = PP.angles $ PP.integer m
instance HNFData (LVar f) where
hrnf (LVar m) = rnf m
instance (HOrdHet (Type (h (LTerm h)))) => L.LVar (LVar h) where
type LFunctor (LVar h) = h
type LDomain (LVar h) = Integer
newtype LMap (LVar h) = IntegerLMap { getIntegerLMap :: Map Integer (Some (LTerm h)) }
mkLVar = LVar
getDomain (LVar x) = x
empty = IntegerLMap M.empty
size = fromIntegral . M.size . getIntegerLMap
insert (LVar k) v = IntegerLMap . M.insert k (Some v) . getIntegerLMap
lookup (LVar k) m =
case M.lookup k $ getIntegerLMap m of
Nothing -> Nothing
Just (Some x) -> Just $ unsafeCoerce x
domain = M.keys . getIntegerLMap
keys = map (Some . LVar) . M.keys . getIntegerLMap
toList = map (\(k, Some v) -> (Some $ LVar k :*: v)) . M.toList . getIntegerLMap
|
dba51cdc501678dc914364120b3467c6c159d150d9a3e4f16ddefb78c8d5bb65 | rtrusso/scp | stringset.scm | (define a (make-string 10 #\a))
(display "[")
(display a)
(display "]")
(newline)
(string-set! a 5 #\c)
(display "[")
(display a)
(display "]")
(newline)
| null | https://raw.githubusercontent.com/rtrusso/scp/2051e76df14bd36aef81aba519ffafa62b260f5c/src/tests/stringset.scm | scheme | (define a (make-string 10 #\a))
(display "[")
(display a)
(display "]")
(newline)
(string-set! a 5 #\c)
(display "[")
(display a)
(display "]")
(newline)
| |
64e672067c5f8619949969cb9dbdcf83b4edff8d3d6c0d60b50262f80d5f22b1 | strymonas/strymonas-ocaml | pk_cde.ml | (* An implementation of the Cde signature
with tracking partial knowledge
*)
module type cde_ex = module type of Cde_ex
module Make(C: cde_ex) = struct
Annotations : what is known about ' a C.cde
type 'a annot =
| Sta of 'a (* Statically known *)
| Global (* It is a cde value that does not depend
on the library code: it is some global
array or the global let-bound immutable value
*)
| Unk (* Nothing is statically known *)
type 'a cde = {sta : 'a annot; dyn : 'a C.cde}
type 'a tbase = 'a C.tbase (* Base types *)
let tbool = C.tbool
let tint = C.tint
let tfloat = C.tfloat
let tbase_zero : 'a tbase -> 'a cde = fun typ ->
{sta=Global; dyn=C.tbase_zero typ}
(* injection-projection pairs *)
let inj : 'a C.cde -> 'a cde = fun x -> {sta=Unk; dyn=x}
let dyn : 'a cde -> 'a C.cde = function {dyn=x} -> x
(* Often used for adjusting continuations *)
let injdyn : ('a cde -> 'b cde) -> 'a C.cde -> 'b C.cde =
fun k v -> v |> inj |> k |> dyn
(* Use this for code coming `outside'; for example, for arguments
of the generated function
*)
let inj_global : 'a C.cde -> 'a cde = fun x -> {sta=Global; dyn=x}
(* Injection for functions *)
One may always use inj , inj1 or : these are operations of the
last resort
last resort
*)
let inj1 : ('a C.cde -> 'b C.cde) -> ('a cde -> 'b cde) = fun f -> function
| {sta=Unk; dyn=x} -> inj @@ f x
| {dyn=x} -> {sta=Global; dyn=f x}
let inj2 : ('a C.cde -> 'b C.cde -> 'c C.cde) -> ('a cde -> 'b cde -> 'c cde) =
fun f x y ->
let v = f (dyn x) (dyn y) in
match (x,y) with
| ({sta=Unk},_) | (_,{sta=Unk}) -> inj v
| _ -> {sta=Global; dyn=v}
(* General lifting for functions, performing static computations where
possible
*)
let lift1 :
('a -> 'b) -> ('b -> 'b cde) -> ('a C.cde -> 'b C.cde) ->
('a cde -> 'b cde) = fun fs lift fd -> function
| {sta=Sta x} -> fs x |> lift
| x -> inj1 fd x
let lift2 :
('a -> 'b -> 'c) -> ('c -> 'c cde) -> ('a C.cde -> 'b C.cde -> 'c C.cde) ->
('a cde -> 'b cde -> 'c cde) = fun fs lift fd x y -> match (x,y) with
| ({sta=Sta x},{sta=Sta y}) -> fs x y |> lift
| (x,y) -> inj2 fd x y
Inquiries
let is_static : 'a cde -> bool = function {sta=Sta _} -> true | _ -> false
(* Is value dependent on something introduced by the library itself?
*)
let is_fully_dynamic : 'a cde -> bool = function {sta=Unk} -> true | _ -> false
let map_opt : ('a -> 'b) -> 'a option -> 'b option = fun f -> function
| None -> None
| Some x -> Some (f x)
(* Local let, without movement *)
let letl : 'a cde -> (('a cde -> 'w cde) -> 'w cde) = fun x k ->
match x with
| {sta=Sta _} -> k x (* constant, no need to bind *)
| {dyn=v} -> inj @@ C.letl v (injdyn k)
(* possibly let-insertion *)
let glet : 'a cde -> 'a cde = function
| {sta=Sta _} as x -> x
| {sta=Global; dyn=x} -> {sta=Global; dyn=C.glet x}
| {sta=Unk} ->
failwith "glet of Unk: let insertion with movement may be unsafe"
(* Often occuring sequential composition *)
let seq : unit cde -> 'a cde -> 'a cde = fun c1 c2 ->
match (c1,c2) with
| ({sta=Sta ()}, _) -> c2
| _ -> inj2 C.seq c1 c2
let ( @. ) : unit cde -> 'a cde -> 'a cde = seq
let unit = {sta=Sta (); dyn=C.unit}
Booleans
let bool : bool -> bool cde = fun b -> {sta=Sta b; dyn=C.bool b}
let not : bool cde -> bool cde = function
| {sta=Sta b} -> bool (Stdlib.not b)
(* XXX For a global thing, do genlet? *)
| {sta=s;dyn=y} -> {sta=s;dyn=C.not y}
let (&&) : bool cde -> bool cde -> bool cde = fun c1 c2 ->
match (c1,c2) with
| ({sta=Sta true},x) | (x,{sta=Sta true}) -> x
| ({sta=Sta false},_) | (_,{sta=Sta false}) -> bool false
| _ -> inj2 C.(&&) c1 c2
let (||) : bool cde -> bool cde -> bool cde = fun c1 c2 ->
match (c1,c2) with
| ({sta=Sta true},_) | (_,{sta=Sta true}) -> bool true
| ({sta=Sta false},x) | (x,{sta=Sta false}) -> x
| _ -> inj2 C.(||) c1 c2
let eq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( ) x y
let neq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( < > ) bool C.(neq ) x y
let lt : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( < ) bool C.(lt ) x y
let gt : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( > ) ) x y
let leq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib.(<= ) bool C.(leq ) x y
let geq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib.(>= ) bool C.(geq ) x y
let eq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.( =) bool C.(eq) x y
let neq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.(<>) bool C.(neq) x y
let lt : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.( <) bool C.(lt) x y
let gt : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.( >) bool C.(gt) x y
let leq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.(<=) bool C.(leq) x y
let geq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.(>=) bool C.(geq) x y
*)
(* Integers *)
let int : int -> int cde = fun i -> {sta=Sta i; dyn=C.int i}
let ( ~-) : int cde -> int cde = lift1 Stdlib.( ~-) int C.( ~-)
let ( + ) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| ({sta=Sta 0},x) | (x,{sta=Sta 0}) -> x
| _ -> lift2 Stdlib.( + ) int C.( + ) x y
let ( - ) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| ({sta=Sta 0},y) -> ~- y
| (x,{sta=Sta 0}) -> x
| _ -> lift2 Stdlib.( - ) int C.( - ) x y
let ( * ) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| ({sta=Sta 0},_) | (_,{sta=Sta 0}) -> int 0
| ({sta=Sta 1},x) | (x,{sta=Sta 1}) -> x
| _ -> lift2 Stdlib.( * ) int C.( * ) x y
let ( / ) : int cde -> int cde -> int cde = lift2 Stdlib.( / ) int C.( / )
let (mod) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| (_,{sta=Sta 1}) -> int 0
| _ -> lift2 Stdlib.(mod) int C.(mod) x y
let logand : int cde -> int cde -> int cde = lift2 Int.logand int C.logand
let ( =) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.( =) bool C.( =) x y
let ( <) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.( <) bool C.( <) x y
let ( >) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.( >) bool C.( >) x y
let (<=) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.(<=) bool C.(<=) x y
let (>=) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.(>=) bool C.(>=) x y
let imin : int cde -> int cde -> int cde = lift2 Stdlib.(min) int C.(imin)
let imax : int cde -> int cde -> int cde = lift2 Stdlib.(max) int C.(imax)
(* Floating points *)
let float : float -> float cde = fun x -> {sta=Sta x; dyn=C.float x}
let ( +. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( +. ) float C.( +. )
let ( -. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( -. ) float C.( -. )
let ( *. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( *. ) float C.( *. )
let ( /. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( /. ) float C.( /. )
let atan : float cde -> float cde = lift1 Stdlib.atan float C.atan
let truncate : float cde -> int cde = lift1 Stdlib.truncate int C.truncate
let float_of_int : int cde -> float cde =
lift1 Stdlib.float_of_int float C.float_of_int
(*
(* Strings *)
let string : string -> string cde = fun x ->
C.{sta=Sta x; dyn = .<x>.}
*)
(* Reference cells *)
(* We rarely want to do any static operations on them. Actually,
strymonas itself operates on them, so we make all references dynamic
*)
let newref : 'a cde -> ('a ref cde -> 'w cde) -> 'w cde = fun x k ->
inj @@ C.newref (dyn x) (injdyn k)
(* could potentially guess a constant of the right type ... *)
let newuref : 'a cde -> ('a ref cde -> 'w cde) -> 'w cde = fun x k ->
match x with
| {sta=Sta _} | {sta=Global} -> newref x k
| x -> inj @@ C.newuref (dyn x) (injdyn k)
let dref : 'a ref cde -> 'a cde = fun x -> inj @@ C.dref (dyn x)
let incr : int ref cde -> unit cde = fun x -> inj @@ C.incr (dyn x)
let decr : int ref cde -> unit cde = fun x -> inj @@ C.decr (dyn x)
let (:=) : 'a ref cde -> 'a cde -> unit cde = fun x y ->
inj @@ C.(:=) (dyn x) (dyn y)
(* Arrays *)
let array_get' : 'a array cde -> int cde -> 'a cde
= fun arr i -> inj @@ C.array_get' (dyn arr) (dyn i)
(* It makes sense to combine it with letl *)
let array_get : 'a array cde -> int cde -> ('a cde -> 'w cde) -> 'w cde
= fun arr i k ->
inj @@ C.array_get (dyn arr) (dyn i) (injdyn k)
let array_len : 'a array cde -> int cde = fun arr ->
lift1 Array.length int C.array_len arr
let array_set : 'a array cde -> int cde -> 'a cde -> unit cde = fun arr i v ->
inj @@ C.array_set (dyn arr) (dyn i) (dyn v)
let new_uarray : 'a tbase -> int -> ('a array cde -> 'w cde) -> 'w cde =
fun tb n k -> inj @@ C.new_uarray tb n (injdyn k)
let new_array : 'a tbase -> 'a cde array -> ('a array cde -> 'w cde) ->
'w cde =
fun tb arr k ->
inj @@ C.new_array tb (Array.map dyn arr) (fun darr ->
let a =
if Array.for_all (function {sta=Sta _} -> true | _ -> false) arr then
{sta =
Sta (Array.map (function {sta=Sta x} -> x | _ -> assert false) arr);
dyn = darr}
else if Array.exists (function {sta=Unk} -> true | _ -> false) arr then
inj darr
else
{sta=Global; dyn=darr}
in k a |> dyn)
(* Control operators *)
let cond : bool cde -> 'a cde -> 'a cde -> 'a cde = fun cnd bt bf ->
match cnd with
| {sta=Sta true} -> bt
| {sta=Sta false} -> bf
| _ -> inj @@ C.cond (dyn cnd) (dyn bt) (dyn bf)
let if_ : bool cde -> unit cde -> unit cde -> unit cde = cond
let if1 : bool cde -> unit cde -> unit cde = fun cnd bt ->
match cnd with
| {sta=Sta true} -> bt
| {sta=Sta false} -> unit
| _ -> inj @@ C.if1 (dyn cnd) (dyn bt)
(* Control constructs generally create Unk code
*)
let for_ : int cde -> (* exact lower bound *)
int cde -> (* exact upper bound *)
?guard:bool cde -> (* possibly a guard, terminate when false *)
?step:int cde -> (* step *)
(int cde -> unit cde) -> unit cde
= fun lwb upb ?guard ?step body ->
match (lwb,upb) with
| ({sta=Sta i},{sta=Sta j}) when Stdlib.(j < i) -> unit
| ({sta=Sta i},{sta=Sta j}) when Stdlib.(i = j) -> begin match guard with
| None -> body (int i)
| Some g -> if1 g (body (int i))
end
(* XXX: possibly unroll if upb is known and small enough *)
| _ -> inj @@ C.for_ (dyn lwb) (dyn upb)
?guard:(map_opt dyn guard)
?step:(map_opt dyn
(match step with
| Some {sta=Sta 1} -> None
| x -> x))
(injdyn body)
let while_ : bool cde -> unit cde -> unit cde = fun goon body ->
inj @@ C.while_ (dyn goon) (dyn body)
Advanced control construction
Loop with continue : execute the body , which may request to be
re - executed ( like C ` continue ' )
The loop ( as well as its body ) have two continuations : the normal
one is invoked with the produced value . The second one is implicit :
it is entered when the normal continuation is NOT invoked .
Here is how cloop is supposed to work , in the form when the second
continuation is made explicit too :
let cloop : ( ' a - > bot ) - > ( * normal continuation
re-executed (like C `continue')
The loop (as well as its body) have two continuations: the normal
one is invoked with the produced value. The second one is implicit:
it is entered when the normal continuation is NOT invoked.
Here is how cloop is supposed to work, in the form when the second
continuation is made explicit too:
let cloop : ('a -> bot) -> (* normal continuation *)
exceptional one
(unit -> bool) -> (* guard condition *)
body , in 2CPS style
bot = fun k kexc bp body ->
let rec loop () = (* create a return label *)
if not (bp ()) then kexc () (* guard failed *)
else body k loop
in loop ()
*)
let cloop :
('a -> unit cde) -> (* cloop's continuation *)
bool cde option -> (* possibly a guard *)
body , in CPS , which may exit
without calling its continuation
without calling its continuation
*)
unit cde = fun k bp body ->
inj @@ C.cloop (fun x -> k x |> dyn) (map_opt dyn bp)
(fun k -> body (fun x -> k x |> inj) |> dyn)
Accumulate all elements of a finite stream in a collection
let nil : ' a list cde = { = Sta [ ] ;
let cons : ' a cde - > ' a list cde - > ' a list cde = fun x y - > inj2 C.cons x y
let rev : ' a list cde - > ' a list cde = fun l - > inj1 C.rev l ; ;
let nil : 'a list cde = {sta=Sta []; dyn=C.nil}
let cons : 'a cde -> 'a list cde -> 'a list cde = fun x y -> inj2 C.cons x y
let rev : 'a list cde -> 'a list cde = fun l -> inj1 C.rev l;;
*)
(* Simple i/o, useful for debugging. Newline at the end *)
let print_int : int cde -> unit cde = inj1 C.print_int
let print_float : float cde -> unit cde = inj1 C.print_float
Injection of arbitrary MetaOCaml code
let of_code : ' a code - > ' a cde = fun x - > inj x
let with_cde : ( ' a code - > ' b cde ) - > ' a cde - > ' b cde = fun k x - >
k ( dyn x )
let cde_app1 : ( ' a->'b ) code - > ' a cde - > ' b cde = fun f x - >
inj1 ( fun x ' - > . < .~f .~x ' > . ) x
let time : unit cde - > float cde = fun x - > inj @@ C.time ( dyn x )
let of_code : 'a code -> 'a cde = fun x -> inj x
let with_cde : ('a code -> 'b cde) -> 'a cde -> 'b cde = fun k x ->
k (dyn x)
let cde_app1 : ('a->'b) code -> 'a cde -> 'b cde = fun f x ->
inj1 (fun x' -> .< .~f .~x' >.) x
let time : unit cde -> float cde = fun x -> inj @@ C.time (dyn x)
*)
end
| null | https://raw.githubusercontent.com/strymonas/strymonas-ocaml/b45ab87c62e5bb845ff4a989064f30ed6b468f6d/lib/pk_cde.ml | ocaml | An implementation of the Cde signature
with tracking partial knowledge
Statically known
It is a cde value that does not depend
on the library code: it is some global
array or the global let-bound immutable value
Nothing is statically known
Base types
injection-projection pairs
Often used for adjusting continuations
Use this for code coming `outside'; for example, for arguments
of the generated function
Injection for functions
General lifting for functions, performing static computations where
possible
Is value dependent on something introduced by the library itself?
Local let, without movement
constant, no need to bind
possibly let-insertion
Often occuring sequential composition
XXX For a global thing, do genlet?
Integers
Floating points
(* Strings
Reference cells
We rarely want to do any static operations on them. Actually,
strymonas itself operates on them, so we make all references dynamic
could potentially guess a constant of the right type ...
Arrays
It makes sense to combine it with letl
Control operators
Control constructs generally create Unk code
exact lower bound
exact upper bound
possibly a guard, terminate when false
step
XXX: possibly unroll if upb is known and small enough
normal continuation
guard condition
create a return label
guard failed
cloop's continuation
possibly a guard
Simple i/o, useful for debugging. Newline at the end |
module type cde_ex = module type of Cde_ex
module Make(C: cde_ex) = struct
Annotations : what is known about ' a C.cde
type 'a annot =
type 'a cde = {sta : 'a annot; dyn : 'a C.cde}
let tbool = C.tbool
let tint = C.tint
let tfloat = C.tfloat
let tbase_zero : 'a tbase -> 'a cde = fun typ ->
{sta=Global; dyn=C.tbase_zero typ}
let inj : 'a C.cde -> 'a cde = fun x -> {sta=Unk; dyn=x}
let dyn : 'a cde -> 'a C.cde = function {dyn=x} -> x
let injdyn : ('a cde -> 'b cde) -> 'a C.cde -> 'b C.cde =
fun k v -> v |> inj |> k |> dyn
let inj_global : 'a C.cde -> 'a cde = fun x -> {sta=Global; dyn=x}
One may always use inj , inj1 or : these are operations of the
last resort
last resort
*)
let inj1 : ('a C.cde -> 'b C.cde) -> ('a cde -> 'b cde) = fun f -> function
| {sta=Unk; dyn=x} -> inj @@ f x
| {dyn=x} -> {sta=Global; dyn=f x}
let inj2 : ('a C.cde -> 'b C.cde -> 'c C.cde) -> ('a cde -> 'b cde -> 'c cde) =
fun f x y ->
let v = f (dyn x) (dyn y) in
match (x,y) with
| ({sta=Unk},_) | (_,{sta=Unk}) -> inj v
| _ -> {sta=Global; dyn=v}
let lift1 :
('a -> 'b) -> ('b -> 'b cde) -> ('a C.cde -> 'b C.cde) ->
('a cde -> 'b cde) = fun fs lift fd -> function
| {sta=Sta x} -> fs x |> lift
| x -> inj1 fd x
let lift2 :
('a -> 'b -> 'c) -> ('c -> 'c cde) -> ('a C.cde -> 'b C.cde -> 'c C.cde) ->
('a cde -> 'b cde -> 'c cde) = fun fs lift fd x y -> match (x,y) with
| ({sta=Sta x},{sta=Sta y}) -> fs x y |> lift
| (x,y) -> inj2 fd x y
Inquiries
let is_static : 'a cde -> bool = function {sta=Sta _} -> true | _ -> false
let is_fully_dynamic : 'a cde -> bool = function {sta=Unk} -> true | _ -> false
let map_opt : ('a -> 'b) -> 'a option -> 'b option = fun f -> function
| None -> None
| Some x -> Some (f x)
let letl : 'a cde -> (('a cde -> 'w cde) -> 'w cde) = fun x k ->
match x with
| {dyn=v} -> inj @@ C.letl v (injdyn k)
let glet : 'a cde -> 'a cde = function
| {sta=Sta _} as x -> x
| {sta=Global; dyn=x} -> {sta=Global; dyn=C.glet x}
| {sta=Unk} ->
failwith "glet of Unk: let insertion with movement may be unsafe"
let seq : unit cde -> 'a cde -> 'a cde = fun c1 c2 ->
match (c1,c2) with
| ({sta=Sta ()}, _) -> c2
| _ -> inj2 C.seq c1 c2
let ( @. ) : unit cde -> 'a cde -> 'a cde = seq
let unit = {sta=Sta (); dyn=C.unit}
Booleans
let bool : bool -> bool cde = fun b -> {sta=Sta b; dyn=C.bool b}
let not : bool cde -> bool cde = function
| {sta=Sta b} -> bool (Stdlib.not b)
| {sta=s;dyn=y} -> {sta=s;dyn=C.not y}
let (&&) : bool cde -> bool cde -> bool cde = fun c1 c2 ->
match (c1,c2) with
| ({sta=Sta true},x) | (x,{sta=Sta true}) -> x
| ({sta=Sta false},_) | (_,{sta=Sta false}) -> bool false
| _ -> inj2 C.(&&) c1 c2
let (||) : bool cde -> bool cde -> bool cde = fun c1 c2 ->
match (c1,c2) with
| ({sta=Sta true},_) | (_,{sta=Sta true}) -> bool true
| ({sta=Sta false},x) | (x,{sta=Sta false}) -> x
| _ -> inj2 C.(||) c1 c2
let eq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( ) x y
let neq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( < > ) bool C.(neq ) x y
let lt : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( < ) bool C.(lt ) x y
let gt : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib . ( > ) ) x y
let leq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib.(<= ) bool C.(leq ) x y
let geq : ' a cde - > ' a cde - > = fun x y - > lift2 Stdlib.(>= ) bool C.(geq ) x y
let eq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.( =) bool C.(eq) x y
let neq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.(<>) bool C.(neq) x y
let lt : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.( <) bool C.(lt) x y
let gt : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.( >) bool C.(gt) x y
let leq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.(<=) bool C.(leq) x y
let geq : 'a cde -> 'a cde -> bool cde = fun x y -> lift2 Stdlib.(>=) bool C.(geq) x y
*)
let int : int -> int cde = fun i -> {sta=Sta i; dyn=C.int i}
let ( ~-) : int cde -> int cde = lift1 Stdlib.( ~-) int C.( ~-)
let ( + ) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| ({sta=Sta 0},x) | (x,{sta=Sta 0}) -> x
| _ -> lift2 Stdlib.( + ) int C.( + ) x y
let ( - ) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| ({sta=Sta 0},y) -> ~- y
| (x,{sta=Sta 0}) -> x
| _ -> lift2 Stdlib.( - ) int C.( - ) x y
let ( * ) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| ({sta=Sta 0},_) | (_,{sta=Sta 0}) -> int 0
| ({sta=Sta 1},x) | (x,{sta=Sta 1}) -> x
| _ -> lift2 Stdlib.( * ) int C.( * ) x y
let ( / ) : int cde -> int cde -> int cde = lift2 Stdlib.( / ) int C.( / )
let (mod) : int cde -> int cde -> int cde = fun x y ->
match (x,y) with
| (_,{sta=Sta 1}) -> int 0
| _ -> lift2 Stdlib.(mod) int C.(mod) x y
let logand : int cde -> int cde -> int cde = lift2 Int.logand int C.logand
let ( =) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.( =) bool C.( =) x y
let ( <) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.( <) bool C.( <) x y
let ( >) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.( >) bool C.( >) x y
let (<=) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.(<=) bool C.(<=) x y
let (>=) : int cde -> int cde -> bool cde = fun x y -> lift2 Stdlib.(>=) bool C.(>=) x y
let imin : int cde -> int cde -> int cde = lift2 Stdlib.(min) int C.(imin)
let imax : int cde -> int cde -> int cde = lift2 Stdlib.(max) int C.(imax)
let float : float -> float cde = fun x -> {sta=Sta x; dyn=C.float x}
let ( +. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( +. ) float C.( +. )
let ( -. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( -. ) float C.( -. )
let ( *. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( *. ) float C.( *. )
let ( /. ) : float cde -> float cde -> float cde =
lift2 Stdlib.( /. ) float C.( /. )
let atan : float cde -> float cde = lift1 Stdlib.atan float C.atan
let truncate : float cde -> int cde = lift1 Stdlib.truncate int C.truncate
let float_of_int : int cde -> float cde =
lift1 Stdlib.float_of_int float C.float_of_int
let string : string -> string cde = fun x ->
C.{sta=Sta x; dyn = .<x>.}
*)
let newref : 'a cde -> ('a ref cde -> 'w cde) -> 'w cde = fun x k ->
inj @@ C.newref (dyn x) (injdyn k)
let newuref : 'a cde -> ('a ref cde -> 'w cde) -> 'w cde = fun x k ->
match x with
| {sta=Sta _} | {sta=Global} -> newref x k
| x -> inj @@ C.newuref (dyn x) (injdyn k)
let dref : 'a ref cde -> 'a cde = fun x -> inj @@ C.dref (dyn x)
let incr : int ref cde -> unit cde = fun x -> inj @@ C.incr (dyn x)
let decr : int ref cde -> unit cde = fun x -> inj @@ C.decr (dyn x)
let (:=) : 'a ref cde -> 'a cde -> unit cde = fun x y ->
inj @@ C.(:=) (dyn x) (dyn y)
let array_get' : 'a array cde -> int cde -> 'a cde
= fun arr i -> inj @@ C.array_get' (dyn arr) (dyn i)
let array_get : 'a array cde -> int cde -> ('a cde -> 'w cde) -> 'w cde
= fun arr i k ->
inj @@ C.array_get (dyn arr) (dyn i) (injdyn k)
let array_len : 'a array cde -> int cde = fun arr ->
lift1 Array.length int C.array_len arr
let array_set : 'a array cde -> int cde -> 'a cde -> unit cde = fun arr i v ->
inj @@ C.array_set (dyn arr) (dyn i) (dyn v)
let new_uarray : 'a tbase -> int -> ('a array cde -> 'w cde) -> 'w cde =
fun tb n k -> inj @@ C.new_uarray tb n (injdyn k)
let new_array : 'a tbase -> 'a cde array -> ('a array cde -> 'w cde) ->
'w cde =
fun tb arr k ->
inj @@ C.new_array tb (Array.map dyn arr) (fun darr ->
let a =
if Array.for_all (function {sta=Sta _} -> true | _ -> false) arr then
{sta =
Sta (Array.map (function {sta=Sta x} -> x | _ -> assert false) arr);
dyn = darr}
else if Array.exists (function {sta=Unk} -> true | _ -> false) arr then
inj darr
else
{sta=Global; dyn=darr}
in k a |> dyn)
let cond : bool cde -> 'a cde -> 'a cde -> 'a cde = fun cnd bt bf ->
match cnd with
| {sta=Sta true} -> bt
| {sta=Sta false} -> bf
| _ -> inj @@ C.cond (dyn cnd) (dyn bt) (dyn bf)
let if_ : bool cde -> unit cde -> unit cde -> unit cde = cond
let if1 : bool cde -> unit cde -> unit cde = fun cnd bt ->
match cnd with
| {sta=Sta true} -> bt
| {sta=Sta false} -> unit
| _ -> inj @@ C.if1 (dyn cnd) (dyn bt)
(int cde -> unit cde) -> unit cde
= fun lwb upb ?guard ?step body ->
match (lwb,upb) with
| ({sta=Sta i},{sta=Sta j}) when Stdlib.(j < i) -> unit
| ({sta=Sta i},{sta=Sta j}) when Stdlib.(i = j) -> begin match guard with
| None -> body (int i)
| Some g -> if1 g (body (int i))
end
| _ -> inj @@ C.for_ (dyn lwb) (dyn upb)
?guard:(map_opt dyn guard)
?step:(map_opt dyn
(match step with
| Some {sta=Sta 1} -> None
| x -> x))
(injdyn body)
let while_ : bool cde -> unit cde -> unit cde = fun goon body ->
inj @@ C.while_ (dyn goon) (dyn body)
Advanced control construction
Loop with continue : execute the body , which may request to be
re - executed ( like C ` continue ' )
The loop ( as well as its body ) have two continuations : the normal
one is invoked with the produced value . The second one is implicit :
it is entered when the normal continuation is NOT invoked .
Here is how cloop is supposed to work , in the form when the second
continuation is made explicit too :
let cloop : ( ' a - > bot ) - > ( * normal continuation
re-executed (like C `continue')
The loop (as well as its body) have two continuations: the normal
one is invoked with the produced value. The second one is implicit:
it is entered when the normal continuation is NOT invoked.
Here is how cloop is supposed to work, in the form when the second
continuation is made explicit too:
exceptional one
body , in 2CPS style
bot = fun k kexc bp body ->
else body k loop
in loop ()
*)
let cloop :
body , in CPS , which may exit
without calling its continuation
without calling its continuation
*)
unit cde = fun k bp body ->
inj @@ C.cloop (fun x -> k x |> dyn) (map_opt dyn bp)
(fun k -> body (fun x -> k x |> inj) |> dyn)
Accumulate all elements of a finite stream in a collection
let nil : ' a list cde = { = Sta [ ] ;
let cons : ' a cde - > ' a list cde - > ' a list cde = fun x y - > inj2 C.cons x y
let rev : ' a list cde - > ' a list cde = fun l - > inj1 C.rev l ; ;
let nil : 'a list cde = {sta=Sta []; dyn=C.nil}
let cons : 'a cde -> 'a list cde -> 'a list cde = fun x y -> inj2 C.cons x y
let rev : 'a list cde -> 'a list cde = fun l -> inj1 C.rev l;;
*)
let print_int : int cde -> unit cde = inj1 C.print_int
let print_float : float cde -> unit cde = inj1 C.print_float
Injection of arbitrary MetaOCaml code
let of_code : ' a code - > ' a cde = fun x - > inj x
let with_cde : ( ' a code - > ' b cde ) - > ' a cde - > ' b cde = fun k x - >
k ( dyn x )
let cde_app1 : ( ' a->'b ) code - > ' a cde - > ' b cde = fun f x - >
inj1 ( fun x ' - > . < .~f .~x ' > . ) x
let time : unit cde - > float cde = fun x - > inj @@ C.time ( dyn x )
let of_code : 'a code -> 'a cde = fun x -> inj x
let with_cde : ('a code -> 'b cde) -> 'a cde -> 'b cde = fun k x ->
k (dyn x)
let cde_app1 : ('a->'b) code -> 'a cde -> 'b cde = fun f x ->
inj1 (fun x' -> .< .~f .~x' >.) x
let time : unit cde -> float cde = fun x -> inj @@ C.time (dyn x)
*)
end
|
59de5423a30501cf5730efd94f647436de3f6cb4b804db411840ec3ed7d7cc32 | alanz/ghc-exactprint | T365.hs | # OPTIONS_GHC -F -pgmF ./test_preprocessor.txt #
module Main where
main = print "Hello World"
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/T365.hs | haskell | # OPTIONS_GHC -F -pgmF ./test_preprocessor.txt #
module Main where
main = print "Hello World"
| |
4ac6d42831540c7f2cc897e343a27b0e32eb5a2f98da2d9fffcd201ca98f9a2f | benoitc/econfig | econfig_server.erl | %%% -*- erlang -*-
%%%
This file is part of econfig released under the Apache 2 license .
%%% See the NOTICE for more information.
%% @hidden
-module(econfig_server).
-behaviour(gen_server).
-export([register_config/2, register_config/3,
open_config/2, open_config/3,
unregister_config/1,
subscribe/1, unsubscribe/1,
reload/1, reload/2,
start_autoreload/1, stop_autoreload/1,
all/1, sections/1, prefix/2,
cfg2list/1, cfg2list/2,
get_value/2, get_value/3, get_value/4,
set_value/3, set_value/4, set_value/5,
delete_value/2, delete_value/3, delete_value/4]).
-export([start_link/0]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {confs = dict:new()}).
-record(config, {write_file=nil,
pid=nil,
change_fun,
options,
inifiles}).
-define(TAB, econfig).
start_link() ->
_ = init_tabs(),
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-spec register_config(term(), econfig:inifiles()) -> ok | {error,
any()}.
%% @doc register inifiles
register_config(ConfigName, IniFiles) ->
register_config(ConfigName, IniFiles, []).
register_config(ConfigName, IniFiles, Options) ->
gen_server:call(?MODULE, {register_conf, {ConfigName, IniFiles, Options}}, infinity).
%% @doc unregister a conf
unregister_config(ConfigName) ->
gen_server:call(?MODULE, {unregister_conf, ConfigName}).
%% @doc open or create an ini file an register it
open_config(ConfigName, IniFile) ->
open_config(ConfigName, IniFile, []).
open_config(ConfigName, IniFile, Options) ->
IniFileName = econfig_util:abs_pathname(IniFile),
case filelib:is_file(IniFileName) of
true ->
register_config(ConfigName, [IniFile], Options);
false ->
case file:open(IniFileName, [write]) of
{ok, Fd} ->
file:close(Fd),
register_config(ConfigName, [IniFile], Options);
Error ->
Error
end
end.
subscribe(ConfigName) ->
Key = {sub, ConfigName, self()},
case ets:insert_new(?TAB, {Key, self()}) of
false -> ok;
true ->
ets:insert(?TAB, {{self(), ConfigName}, Key}),
%% maybe monitor the process
case ets:insert_new(?TAB, {self(), m}) of
false -> ok;
true ->
gen_server:cast(?MODULE, {monitor_sub, self()})
end
end.
%% @doc Remove subscribtion created using `subscribe(ConfigName)'
unsubscribe(ConfigName) ->
gen_server:call(?MODULE, {unsub, ConfigName}).
%% @doc reload the configuration
reload(ConfigName) ->
reload(ConfigName, nil).
%% @doc reload the configuration
reload(ConfigName, IniFiles) ->
gen_server:call(?MODULE, {reload, {ConfigName, IniFiles}}, infinity).
start_autoreload(ConfigName) ->
gen_server:call(?MODULE, {start_autoreload, ConfigName}).
stop_autoreload(ConfigName) ->
gen_server:call(?MODULE, {stop_autoreload, ConfigName}).
%% @doc get all values of a configuration
all(ConfigName) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '$2'}, '$3'}),
[{Section, Key, Value} || [Section, Key, Value] <- Matches].
%% @doc get all sections of a configuration
sections(ConfigName) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '_'}, '_'}),
lists:umerge(Matches).
%% @doc get all sections starting by Prefix
prefix(ConfigName, Prefix) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '_'}, '_'}),
Found = lists:foldl(fun([Match], Acc) ->
case lists:prefix(Prefix, Match) of
true -> [Match | Acc];
false -> Acc
end
end, [], Matches),
lists:reverse(lists:usort(Found)).
%% @doc retrive config as a proplist
cfg2list(ConfigName) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '$2'}, '$3'}),
lists:foldl(fun([Section, Key, Value], Props) ->
case lists:keyfind(Section, 1, Props) of
false ->
[{Section, [{Key, Value}]} | Props];
{Section, KVs} ->
KVs1 = lists:keymerge(1, KVs, [{Key, Value}]),
lists:keyreplace(Section, 1, Props, {Section, KVs1})
end
end, [], Matches).
%% @doc retrieve config as a proplist
cfg2list(ConfigName, GroupKey) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '$2'}, '$3'}),
lists:foldl(fun([Section, Key, Value], Props) ->
case re:split(Section, GroupKey, [{return,list}]) of
[Section] ->
case lists:keyfind(Section, 1, Props) of
false ->
[{Section, [{Key, Value}]} | Props];
{Section, KVs} ->
KVs1 = lists:keymerge(1, KVs, [{Key, Value}]),
lists:keyreplace(Section, 1, Props, {Section, KVs1})
end;
[Section1, SSection] ->
case lists:keyfind(Section1, 1, Props) of
false ->
[{Section1, [{SSection, [{Key, Value}]}]}
| Props];
{Section1, KVs} ->
KVs1 = case lists:keyfind(SSection, 1, KVs) of
false ->
[{SSection, [{Key, Value}]} | KVs];
{SSection, SKVs} ->
SKVs1 = lists:keymerge(1, SKVs,
[{Key, Value}]),
lists:keyreplace(SSection, 1,
KVs, {SSection,
SKVs1})
end,
lists:keyreplace(Section1, 1, Props,
{Section1, KVs1})
end
end
end, [], Matches).
%% @doc get values of a section
get_value(ConfigName, Section0) ->
Section = econfig_util:to_list(Section0),
Matches = ets:match(?TAB, {{conf_key(ConfigName), Section, '$1'}, '$2'}),
[{Key, Value} || [Key, Value] <- Matches].
%% @doc get value for a key in a section
get_value(ConfigName, Section, Key) ->
get_value(ConfigName, Section, Key, undefined).
get_value(ConfigName, Section0, Key0, Default) ->
Section = econfig_util:to_list(Section0),
Key = econfig_util:to_list(Key0),
case ets:lookup(?TAB, {conf_key(ConfigName), Section, Key}) of
[] -> Default;
[{_, Match}] -> Match
end.
%% @doc set a section
set_value(ConfigName, Section, List) ->
set_value(ConfigName, Section, List, true).
set_value(ConfigName, Section0, List, Persist)
when is_boolean(Persist) ->
Section = econfig_util:to_list(Section0),
List1 = [{econfig_util:to_list(K), econfig_util:to_list(V)}
|| {K, V} <- List],
gen_server:call(?MODULE, {mset, {ConfigName, Section, List1,
Persist}}, infinity).
set_value(ConfigName, Section0, Key0, Value0, Persist) ->
Section = econfig_util:to_list(Section0),
Key = econfig_util:to_list(Key0),
Value = econfig_util:to_list(Value0),
gen_server:call(?MODULE, {set, {ConfigName, Section, Key, Value, Persist}}, infinity).
delete_value(ConfigName, Section) ->
delete_value(ConfigName, Section, true).
delete_value(ConfigName, Section0, Persist) when is_boolean(Persist) ->
Section = econfig_util:to_list(Section0),
gen_server:call(?MODULE, {mdel, {ConfigName, Section, Persist}},
infinity);
%% @doc delete a value
delete_value(ConfigName, Section, Key) ->
delete_value(ConfigName, Section, Key, true).
delete_value(ConfigName, Section0, Key0, Persist) ->
Section = econfig_util:to_list(Section0),
Key = econfig_util:to_list(Key0),
gen_server:call(?MODULE, {del, {ConfigName, Section, Key,
Persist}}, infinity).
init_tabs() ->
case ets:info(?TAB, name) of
undefined ->
ets:new(?TAB, [ordered_set, public, named_table,
{read_concurrency, true},
{write_concurrency, true}]);
_ ->
true
end.
%% -----------------------------------------------
%% gen_server callbacks
%% -----------------------------------------------
init(_) ->
process_flag(trap_exit, true),
InitialState = initialize_app_confs(),
{ok, InitialState}.
handle_call({register_conf, {ConfName, IniFiles, Options}}, _From, #state{confs=Confs}=State) ->
{Resp, NewState} =
try
WriteFile = parse_inis(ConfName, IniFiles),
{ok, Pid} = case proplists:get_value(autoreload, Options) of
true ->
Res = econfig_watcher_sup:start_watcher(ConfName, IniFiles),
Res;
Delay when is_integer(Delay) ->
econfig_watcher_sup:start_watcher(ConfName, IniFiles, Delay);
_ ->
{ok, nil}
end,
ChangeFun = proplists:get_value(change_fun, Options, fun(_Change) -> ok end),
ok = check_fun(ChangeFun),
Confs1 = dict:store(ConfName, #config{write_file=WriteFile,
pid=Pid,
change_fun=ChangeFun,
options=Options,
inifiles=IniFiles},
Confs),
State2 = State#state{confs=Confs1},
notify_change(State2, ConfName, registered),
{ok, State2#state{confs=Confs1}}
catch _Tag:Error ->
{{error, Error}, State}
end,
{reply, Resp, NewState};
handle_call({unregister_conf, ConfName}, _From, #state{confs=Confs}=State) ->
true = ets:match_delete(?TAB, {{conf_key(ConfName), '_', '_'}, '_'}),
case dict:find(ConfName, Confs) of
{ok, #config{pid=Pid}} when is_pid(Pid) ->
supervisor:terminate_child(econfig_watcher_sup, Pid),
notify_change(State, ConfName, unregistered);
_ ->
ok
end,
{reply, ok, State#state{confs=dict:erase(ConfName, Confs)}};
handle_call({reload, {ConfName, IniFiles0}}, _From,
#state{confs=Confs}=State) ->
case dict:find(ConfName, Confs) of
{ok, #config{inifiles=IniFiles1, options=Options}=Conf} ->
true = ets:match_delete(?TAB, {{conf_key(ConfName), '_', '_'}, '_'}),
IniFiles = case IniFiles0 of
nil -> IniFiles1;
_ -> IniFiles0
end,
%% do the reload
WriteFile = parse_inis(ConfName, IniFiles),
Confs1 = dict:store(ConfName, Conf#config{write_file=WriteFile,
options=Options,
inifiles=IniFiles},
Confs),
State2 = State#state{confs=Confs1},
notify_change(State2, ConfName, reload),
{reply, ok, State2};
_ ->
{reply, ok, State}
end;
handle_call({start_autoreload, ConfName}, _From, #state{confs=Confs}=State) ->
case dict:find(ConfName, Confs) of
{ok, #config{inifiles=IniFiles}=Config} ->
{ok, Pid} = econfig_watcher_sup:start_watcher(ConfName, IniFiles),
Config1 = Config#config{pid=Pid},
{reply, ok, State#state{confs=dict:store(ConfName, Config1, Confs)}};
_ ->
{reply, ok, State}
end;
handle_call({stop_autoreload, ConfName}, _From, #state{confs=Confs}=State) ->
case dict:find(ConfName, Confs) of
{ok, #config{pid=Pid}=Config} when is_pid(Pid) ->
supervisor:terminate_child(econfig_watcher_sup, Pid),
Config1 = Config#config{pid=nil},
{reply, ok, State#state{confs=dict:store(ConfName, Config1,
Confs)}};
_ ->
{reply, ok, State}
end;
handle_call({set, {ConfName, Section, Key, Value, Persist}}, _From,
#state{confs=Confs}=State) ->
Result = case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, [{Key, Value}]}, FileName)
end);
_ ->
ok
end,
case Result of
ok ->
Value1 = econfig_util:trim_whitespace(Value),
case Value1 of
[] ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key});
_ ->
true = ets:insert(?TAB, {{conf_key(ConfName), Section, Key}, Value1})
end,
notify_change(State, ConfName, {set, {Section, Key}}),
{reply, ok, State};
_Error ->
{reply, Result, State}
end;
handle_call({mset, {ConfName, Section, List, Persist}}, _From,
#state{confs=Confs}=State) ->
Result = case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, List}, FileName)
end);
_ ->
ok
end,
case Result of
ok ->
lists:foreach(fun({Key,Value}) ->
Value1 = econfig_util:trim_whitespace(Value),
if
Value1 /= [] ->
true = ets:insert(?TAB, {{conf_key(ConfName), Section, Key}, Value1}),
notify_change(State, ConfName, {set, {Section, Key}});
true ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key}),
notify_change(State, ConfName, {delete, {Section, Key}})
end
end, List),
{reply, ok, State};
_Error ->
{reply, Result, State}
end;
handle_call({del, {ConfName, Section, Key, Persist}}, _From,
#state{confs=Confs}=State) ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key}),
case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, [{Key, ""}]}, FileName)
end);
_ ->
ok
end,
notify_change(State, ConfName, {delete, {Section, Key}}),
{reply, ok, State};
handle_call({mdel, {ConfName, Section, Persist}}, _From,
#state{confs=Confs}=State) ->
Matches = ets:match(?TAB, {{conf_key(ConfName), Section, '$1'}, '$2'}),
ToDelete = lists:foldl(fun([Key, _Val], Acc) ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key}),
notify_change(State, ConfName, {delete, {Section, Key}}),
[{Key, ""} | Acc]
end, [], Matches),
case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, ToDelete}, FileName)
end);
_ ->
ok
end,
{reply, ok, State};
handle_call({unsub, ConfName}, {Pid, _}, State) ->
Key = {sub, ConfName, Pid},
case ets:lookup(?TAB, Key) of
[{Key, Pid}] ->
_ = ets:delete(?TAB, Key),
_ = ets:delete(?TAB, {Pid, ConfName});
[] -> ok
end,
{reply, ok, State};
handle_call(_Msg, _From, State) ->
{reply, ok, State}.
handle_cast({monitor_sub, Pid}, State) ->
erlang:monitor(process, Pid),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', _MRef, process, Pid, _}, State) ->
_ = process_is_down(Pid),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason , _State) ->
ok.
conf_key(Name) -> {c, Name}.
%% -----------------------------------------------
%% internal functions
%% -----------------------------------------------
%%
maybe_pause(#config{pid=Pid}, Fun) when is_pid(Pid) ->
econfig_watcher:pause(Pid),
Fun(),
econfig_watcher:restart(Pid);
maybe_pause(_, Fun) ->
Fun().
notify_change(State, ConfigName, Event) ->
Msg = {config_updated, ConfigName, Event},
run_change_fun(State, ConfigName, Msg),
send(ConfigName, Msg).
send(ConfigName, Msg) ->
Subs = ets:select(?TAB, [{{{sub, ConfigName, '_'}, '$1'}, [], ['$1']}]),
lists:foreach(fun(Pid) ->
catch Pid ! Msg
end, Subs).
run_change_fun(State, ConfigName, Msg) ->
{ok, #config{change_fun=ChangeFun}} = dict:find(ConfigName, State#state.confs),
Ret = (catch apply_change_fun(ChangeFun, Msg)),
case Ret of
{'EXIT', Reason} ->
error_logger:warning_msg("~p~n error running change hook: ~p~n", [?MODULE, Reason]),
ok;
_ ->
ok
end.
apply_change_fun(none, _Msg) -> ok;
apply_change_fun({M, F}, Msg) -> apply(M, F, [Msg]);
apply_change_fun(F, Msg) -> F(Msg).
initialize_app_confs() ->
case application:get_env(econfig, confs) of
undefined ->
#state{};
{ok, Confs} ->
initialize_app_confs1(Confs, #state{})
end.
initialize_app_confs1([], State) ->
State;
initialize_app_confs1([{ConfName, IniFiles} | Rest], State) ->
initialize_app_confs1([{ConfName, IniFiles, []} | Rest], State);
initialize_app_confs1([{ConfName, IniFiles, Options} | Rest],
#state{confs=Confs}=State) ->
WriteFile = parse_inis(ConfName, IniFiles),
{ok, Pid} = case proplists:get_value(autoreload, Options) of
true ->
econfig_watcher_sup:start_watcher(ConfName, IniFiles);
_ ->
{ok, nil}
end,
Confs1 = dict:store(ConfName, #config{write_file=WriteFile,
pid=Pid,
options=Options,
inifiles=IniFiles},
Confs),
initialize_app_confs1(Rest, State#state{confs=Confs1}).
parse_inis(ConfName, IniFiles0) ->
IniFiles = econfig_util:find_files(IniFiles0),
lists:map(fun(IniFile) ->
{ok, ParsedIniValues, DelKeys} = parse_ini_file(ConfName, IniFile),
ets:insert(?TAB, ParsedIniValues),
lists:foreach(fun(Key) -> ets:delete(?TAB, Key) end, DelKeys)
end, IniFiles),
WriteFile = lists:last(IniFiles),
WriteFile.
parse_ini_file(ConfName, IniFile) ->
IniFilename = econfig_util:abs_pathname(IniFile),
IniBin =
case file:read_file(IniFilename) of
{ok, IniBin0} ->
IniBin0;
{error, eacces} ->
throw({file_permission_error, IniFile});
{error, enoent} ->
Fmt = "Couldn't find server configuration file ~s.",
Msg = list_to_binary(io_lib:format(Fmt, [IniFilename])),
throw({startup_error, Msg})
end,
Lines = re:split(IniBin, "\r\n|\n|\r|\032", [{return, list}]),
{_, ParsedIniValues, DeleteIniKeys} =
lists:foldl(fun(Line, {AccSectionName, AccValues, AccDeletes}) ->
case string:strip(Line) of
"[" ++ Rest ->
case re:split(Rest, "\\]", [{return, list}]) of
[NewSectionName, ""] ->
{NewSectionName, AccValues, AccDeletes};
_Else -> % end bracket not at end, ignore this line
{AccSectionName, AccValues, AccDeletes}
end;
";" ++ _Comment ->
{AccSectionName, AccValues, AccDeletes};
Line2 ->
case re:split(Line2, "\s*=\s*", [{return, list}]) of
[Value] ->
MultiLineValuePart = case re:run(Line, "^ \\S", []) of
{match, _} ->
true;
_ ->
false
end,
case {MultiLineValuePart, AccValues} of
{true, [{{_, ValueName}, PrevValue} | AccValuesRest]} ->
% remove comment
case re:split(Value, "\s*;|\t;", [{return, list}]) of
[[]] ->
% empty line
{AccSectionName, AccValues, AccDeletes};
[LineValue | _Rest] ->
E = {{AccSectionName, ValueName},
PrevValue ++ " " ++
econfig_util:trim_whitespace(LineValue)},
{AccSectionName, [E | AccValuesRest], AccDeletes}
end;
_ ->
{AccSectionName, AccValues, AccDeletes}
end;
[""|_LineValues] -> % line begins with "=", ignore
{AccSectionName, AccValues, AccDeletes};
[ValueName|LineValues] -> % yeehaw, got a line!
%% replace all tabs by an empty value.
ValueName1 = econfig_util:trim_whitespace(ValueName),
RemainingLine = econfig_util:implode(LineValues, "="),
% removes comments
case re:split(RemainingLine, "\s*;|\t;", [{return, list}]) of
[[]] ->
% empty line means delete this key
AccDeletes1 = [{conf_key(ConfName), AccSectionName, ValueName1}
| AccDeletes],
{AccSectionName, AccValues, AccDeletes1};
[LineValue | _Rest] ->
{AccSectionName,
[{{conf_key(ConfName), AccSectionName, ValueName1},
econfig_util:trim_whitespace(LineValue)}
| AccValues], AccDeletes}
end
end
end
end, {"", [], []}, Lines),
{ok, ParsedIniValues, DeleteIniKeys}.
process_is_down(Pid) when is_pid(Pid) ->
case ets:member(?TAB, Pid) of
false ->
ok;
true ->
Subs = ets:select(?TAB, [{{{Pid, '$1'}, '$2'}, [], [{{'$1', '$2'}}]}]),
lists:foreach(fun({ConfName, SubKey}) ->
ets:delete(?TAB, {Pid, ConfName}),
ets:delete(?TAB, SubKey)
end, Subs),
ets:delete(?TAB, Pid),
ok
end.
check_fun(none) ->
ok;
check_fun(Fun) when is_function(Fun) ->
case erlang:fun_info(Fun, arity) of
{arity, 1} -> ok;
_ -> {error, badarity}
end;
check_fun({Mod, Fun}) ->
_ = code:ensure_loaded(Mod),
case erlang:function_exported(Mod, Fun, 1) of
true -> ok;
false -> {error, function_not_exported}
end.
| null | https://raw.githubusercontent.com/benoitc/econfig/84d7cec15f321c4ac5f5c6e08e5a9a8adea01986/src/econfig_server.erl | erlang | -*- erlang -*-
See the NOTICE for more information.
@hidden
@doc register inifiles
@doc unregister a conf
@doc open or create an ini file an register it
maybe monitor the process
@doc Remove subscribtion created using `subscribe(ConfigName)'
@doc reload the configuration
@doc reload the configuration
@doc get all values of a configuration
@doc get all sections of a configuration
@doc get all sections starting by Prefix
@doc retrive config as a proplist
@doc retrieve config as a proplist
@doc get values of a section
@doc get value for a key in a section
@doc set a section
@doc delete a value
-----------------------------------------------
gen_server callbacks
-----------------------------------------------
do the reload
-----------------------------------------------
internal functions
-----------------------------------------------
end bracket not at end, ignore this line
remove comment
empty line
line begins with "=", ignore
yeehaw, got a line!
replace all tabs by an empty value.
removes comments
empty line means delete this key | This file is part of econfig released under the Apache 2 license .
-module(econfig_server).
-behaviour(gen_server).
-export([register_config/2, register_config/3,
open_config/2, open_config/3,
unregister_config/1,
subscribe/1, unsubscribe/1,
reload/1, reload/2,
start_autoreload/1, stop_autoreload/1,
all/1, sections/1, prefix/2,
cfg2list/1, cfg2list/2,
get_value/2, get_value/3, get_value/4,
set_value/3, set_value/4, set_value/5,
delete_value/2, delete_value/3, delete_value/4]).
-export([start_link/0]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {confs = dict:new()}).
-record(config, {write_file=nil,
pid=nil,
change_fun,
options,
inifiles}).
-define(TAB, econfig).
start_link() ->
_ = init_tabs(),
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-spec register_config(term(), econfig:inifiles()) -> ok | {error,
any()}.
register_config(ConfigName, IniFiles) ->
register_config(ConfigName, IniFiles, []).
register_config(ConfigName, IniFiles, Options) ->
gen_server:call(?MODULE, {register_conf, {ConfigName, IniFiles, Options}}, infinity).
unregister_config(ConfigName) ->
gen_server:call(?MODULE, {unregister_conf, ConfigName}).
open_config(ConfigName, IniFile) ->
open_config(ConfigName, IniFile, []).
open_config(ConfigName, IniFile, Options) ->
IniFileName = econfig_util:abs_pathname(IniFile),
case filelib:is_file(IniFileName) of
true ->
register_config(ConfigName, [IniFile], Options);
false ->
case file:open(IniFileName, [write]) of
{ok, Fd} ->
file:close(Fd),
register_config(ConfigName, [IniFile], Options);
Error ->
Error
end
end.
subscribe(ConfigName) ->
Key = {sub, ConfigName, self()},
case ets:insert_new(?TAB, {Key, self()}) of
false -> ok;
true ->
ets:insert(?TAB, {{self(), ConfigName}, Key}),
case ets:insert_new(?TAB, {self(), m}) of
false -> ok;
true ->
gen_server:cast(?MODULE, {monitor_sub, self()})
end
end.
unsubscribe(ConfigName) ->
gen_server:call(?MODULE, {unsub, ConfigName}).
reload(ConfigName) ->
reload(ConfigName, nil).
reload(ConfigName, IniFiles) ->
gen_server:call(?MODULE, {reload, {ConfigName, IniFiles}}, infinity).
start_autoreload(ConfigName) ->
gen_server:call(?MODULE, {start_autoreload, ConfigName}).
stop_autoreload(ConfigName) ->
gen_server:call(?MODULE, {stop_autoreload, ConfigName}).
all(ConfigName) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '$2'}, '$3'}),
[{Section, Key, Value} || [Section, Key, Value] <- Matches].
sections(ConfigName) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '_'}, '_'}),
lists:umerge(Matches).
prefix(ConfigName, Prefix) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '_'}, '_'}),
Found = lists:foldl(fun([Match], Acc) ->
case lists:prefix(Prefix, Match) of
true -> [Match | Acc];
false -> Acc
end
end, [], Matches),
lists:reverse(lists:usort(Found)).
cfg2list(ConfigName) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '$2'}, '$3'}),
lists:foldl(fun([Section, Key, Value], Props) ->
case lists:keyfind(Section, 1, Props) of
false ->
[{Section, [{Key, Value}]} | Props];
{Section, KVs} ->
KVs1 = lists:keymerge(1, KVs, [{Key, Value}]),
lists:keyreplace(Section, 1, Props, {Section, KVs1})
end
end, [], Matches).
cfg2list(ConfigName, GroupKey) ->
Matches = ets:match(?TAB, {{conf_key(ConfigName), '$1', '$2'}, '$3'}),
lists:foldl(fun([Section, Key, Value], Props) ->
case re:split(Section, GroupKey, [{return,list}]) of
[Section] ->
case lists:keyfind(Section, 1, Props) of
false ->
[{Section, [{Key, Value}]} | Props];
{Section, KVs} ->
KVs1 = lists:keymerge(1, KVs, [{Key, Value}]),
lists:keyreplace(Section, 1, Props, {Section, KVs1})
end;
[Section1, SSection] ->
case lists:keyfind(Section1, 1, Props) of
false ->
[{Section1, [{SSection, [{Key, Value}]}]}
| Props];
{Section1, KVs} ->
KVs1 = case lists:keyfind(SSection, 1, KVs) of
false ->
[{SSection, [{Key, Value}]} | KVs];
{SSection, SKVs} ->
SKVs1 = lists:keymerge(1, SKVs,
[{Key, Value}]),
lists:keyreplace(SSection, 1,
KVs, {SSection,
SKVs1})
end,
lists:keyreplace(Section1, 1, Props,
{Section1, KVs1})
end
end
end, [], Matches).
get_value(ConfigName, Section0) ->
Section = econfig_util:to_list(Section0),
Matches = ets:match(?TAB, {{conf_key(ConfigName), Section, '$1'}, '$2'}),
[{Key, Value} || [Key, Value] <- Matches].
get_value(ConfigName, Section, Key) ->
get_value(ConfigName, Section, Key, undefined).
get_value(ConfigName, Section0, Key0, Default) ->
Section = econfig_util:to_list(Section0),
Key = econfig_util:to_list(Key0),
case ets:lookup(?TAB, {conf_key(ConfigName), Section, Key}) of
[] -> Default;
[{_, Match}] -> Match
end.
set_value(ConfigName, Section, List) ->
set_value(ConfigName, Section, List, true).
set_value(ConfigName, Section0, List, Persist)
when is_boolean(Persist) ->
Section = econfig_util:to_list(Section0),
List1 = [{econfig_util:to_list(K), econfig_util:to_list(V)}
|| {K, V} <- List],
gen_server:call(?MODULE, {mset, {ConfigName, Section, List1,
Persist}}, infinity).
set_value(ConfigName, Section0, Key0, Value0, Persist) ->
Section = econfig_util:to_list(Section0),
Key = econfig_util:to_list(Key0),
Value = econfig_util:to_list(Value0),
gen_server:call(?MODULE, {set, {ConfigName, Section, Key, Value, Persist}}, infinity).
delete_value(ConfigName, Section) ->
delete_value(ConfigName, Section, true).
delete_value(ConfigName, Section0, Persist) when is_boolean(Persist) ->
Section = econfig_util:to_list(Section0),
gen_server:call(?MODULE, {mdel, {ConfigName, Section, Persist}},
infinity);
delete_value(ConfigName, Section, Key) ->
delete_value(ConfigName, Section, Key, true).
delete_value(ConfigName, Section0, Key0, Persist) ->
Section = econfig_util:to_list(Section0),
Key = econfig_util:to_list(Key0),
gen_server:call(?MODULE, {del, {ConfigName, Section, Key,
Persist}}, infinity).
init_tabs() ->
case ets:info(?TAB, name) of
undefined ->
ets:new(?TAB, [ordered_set, public, named_table,
{read_concurrency, true},
{write_concurrency, true}]);
_ ->
true
end.
init(_) ->
process_flag(trap_exit, true),
InitialState = initialize_app_confs(),
{ok, InitialState}.
handle_call({register_conf, {ConfName, IniFiles, Options}}, _From, #state{confs=Confs}=State) ->
{Resp, NewState} =
try
WriteFile = parse_inis(ConfName, IniFiles),
{ok, Pid} = case proplists:get_value(autoreload, Options) of
true ->
Res = econfig_watcher_sup:start_watcher(ConfName, IniFiles),
Res;
Delay when is_integer(Delay) ->
econfig_watcher_sup:start_watcher(ConfName, IniFiles, Delay);
_ ->
{ok, nil}
end,
ChangeFun = proplists:get_value(change_fun, Options, fun(_Change) -> ok end),
ok = check_fun(ChangeFun),
Confs1 = dict:store(ConfName, #config{write_file=WriteFile,
pid=Pid,
change_fun=ChangeFun,
options=Options,
inifiles=IniFiles},
Confs),
State2 = State#state{confs=Confs1},
notify_change(State2, ConfName, registered),
{ok, State2#state{confs=Confs1}}
catch _Tag:Error ->
{{error, Error}, State}
end,
{reply, Resp, NewState};
handle_call({unregister_conf, ConfName}, _From, #state{confs=Confs}=State) ->
true = ets:match_delete(?TAB, {{conf_key(ConfName), '_', '_'}, '_'}),
case dict:find(ConfName, Confs) of
{ok, #config{pid=Pid}} when is_pid(Pid) ->
supervisor:terminate_child(econfig_watcher_sup, Pid),
notify_change(State, ConfName, unregistered);
_ ->
ok
end,
{reply, ok, State#state{confs=dict:erase(ConfName, Confs)}};
handle_call({reload, {ConfName, IniFiles0}}, _From,
#state{confs=Confs}=State) ->
case dict:find(ConfName, Confs) of
{ok, #config{inifiles=IniFiles1, options=Options}=Conf} ->
true = ets:match_delete(?TAB, {{conf_key(ConfName), '_', '_'}, '_'}),
IniFiles = case IniFiles0 of
nil -> IniFiles1;
_ -> IniFiles0
end,
WriteFile = parse_inis(ConfName, IniFiles),
Confs1 = dict:store(ConfName, Conf#config{write_file=WriteFile,
options=Options,
inifiles=IniFiles},
Confs),
State2 = State#state{confs=Confs1},
notify_change(State2, ConfName, reload),
{reply, ok, State2};
_ ->
{reply, ok, State}
end;
handle_call({start_autoreload, ConfName}, _From, #state{confs=Confs}=State) ->
case dict:find(ConfName, Confs) of
{ok, #config{inifiles=IniFiles}=Config} ->
{ok, Pid} = econfig_watcher_sup:start_watcher(ConfName, IniFiles),
Config1 = Config#config{pid=Pid},
{reply, ok, State#state{confs=dict:store(ConfName, Config1, Confs)}};
_ ->
{reply, ok, State}
end;
handle_call({stop_autoreload, ConfName}, _From, #state{confs=Confs}=State) ->
case dict:find(ConfName, Confs) of
{ok, #config{pid=Pid}=Config} when is_pid(Pid) ->
supervisor:terminate_child(econfig_watcher_sup, Pid),
Config1 = Config#config{pid=nil},
{reply, ok, State#state{confs=dict:store(ConfName, Config1,
Confs)}};
_ ->
{reply, ok, State}
end;
handle_call({set, {ConfName, Section, Key, Value, Persist}}, _From,
#state{confs=Confs}=State) ->
Result = case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, [{Key, Value}]}, FileName)
end);
_ ->
ok
end,
case Result of
ok ->
Value1 = econfig_util:trim_whitespace(Value),
case Value1 of
[] ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key});
_ ->
true = ets:insert(?TAB, {{conf_key(ConfName), Section, Key}, Value1})
end,
notify_change(State, ConfName, {set, {Section, Key}}),
{reply, ok, State};
_Error ->
{reply, Result, State}
end;
handle_call({mset, {ConfName, Section, List, Persist}}, _From,
#state{confs=Confs}=State) ->
Result = case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, List}, FileName)
end);
_ ->
ok
end,
case Result of
ok ->
lists:foreach(fun({Key,Value}) ->
Value1 = econfig_util:trim_whitespace(Value),
if
Value1 /= [] ->
true = ets:insert(?TAB, {{conf_key(ConfName), Section, Key}, Value1}),
notify_change(State, ConfName, {set, {Section, Key}});
true ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key}),
notify_change(State, ConfName, {delete, {Section, Key}})
end
end, List),
{reply, ok, State};
_Error ->
{reply, Result, State}
end;
handle_call({del, {ConfName, Section, Key, Persist}}, _From,
#state{confs=Confs}=State) ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key}),
case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, [{Key, ""}]}, FileName)
end);
_ ->
ok
end,
notify_change(State, ConfName, {delete, {Section, Key}}),
{reply, ok, State};
handle_call({mdel, {ConfName, Section, Persist}}, _From,
#state{confs=Confs}=State) ->
Matches = ets:match(?TAB, {{conf_key(ConfName), Section, '$1'}, '$2'}),
ToDelete = lists:foldl(fun([Key, _Val], Acc) ->
true = ets:delete(?TAB, {conf_key(ConfName), Section, Key}),
notify_change(State, ConfName, {delete, {Section, Key}}),
[{Key, ""} | Acc]
end, [], Matches),
case {Persist, dict:find(ConfName, Confs)} of
{true, {ok, #config{write_file=FileName}=Conf}} when FileName /= nil->
maybe_pause(Conf, fun() ->
econfig_file_writer:save_to_file({Section, ToDelete}, FileName)
end);
_ ->
ok
end,
{reply, ok, State};
handle_call({unsub, ConfName}, {Pid, _}, State) ->
Key = {sub, ConfName, Pid},
case ets:lookup(?TAB, Key) of
[{Key, Pid}] ->
_ = ets:delete(?TAB, Key),
_ = ets:delete(?TAB, {Pid, ConfName});
[] -> ok
end,
{reply, ok, State};
handle_call(_Msg, _From, State) ->
{reply, ok, State}.
handle_cast({monitor_sub, Pid}, State) ->
erlang:monitor(process, Pid),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', _MRef, process, Pid, _}, State) ->
_ = process_is_down(Pid),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason , _State) ->
ok.
conf_key(Name) -> {c, Name}.
maybe_pause(#config{pid=Pid}, Fun) when is_pid(Pid) ->
econfig_watcher:pause(Pid),
Fun(),
econfig_watcher:restart(Pid);
maybe_pause(_, Fun) ->
Fun().
notify_change(State, ConfigName, Event) ->
Msg = {config_updated, ConfigName, Event},
run_change_fun(State, ConfigName, Msg),
send(ConfigName, Msg).
send(ConfigName, Msg) ->
Subs = ets:select(?TAB, [{{{sub, ConfigName, '_'}, '$1'}, [], ['$1']}]),
lists:foreach(fun(Pid) ->
catch Pid ! Msg
end, Subs).
run_change_fun(State, ConfigName, Msg) ->
{ok, #config{change_fun=ChangeFun}} = dict:find(ConfigName, State#state.confs),
Ret = (catch apply_change_fun(ChangeFun, Msg)),
case Ret of
{'EXIT', Reason} ->
error_logger:warning_msg("~p~n error running change hook: ~p~n", [?MODULE, Reason]),
ok;
_ ->
ok
end.
apply_change_fun(none, _Msg) -> ok;
apply_change_fun({M, F}, Msg) -> apply(M, F, [Msg]);
apply_change_fun(F, Msg) -> F(Msg).
initialize_app_confs() ->
case application:get_env(econfig, confs) of
undefined ->
#state{};
{ok, Confs} ->
initialize_app_confs1(Confs, #state{})
end.
initialize_app_confs1([], State) ->
State;
initialize_app_confs1([{ConfName, IniFiles} | Rest], State) ->
initialize_app_confs1([{ConfName, IniFiles, []} | Rest], State);
initialize_app_confs1([{ConfName, IniFiles, Options} | Rest],
#state{confs=Confs}=State) ->
WriteFile = parse_inis(ConfName, IniFiles),
{ok, Pid} = case proplists:get_value(autoreload, Options) of
true ->
econfig_watcher_sup:start_watcher(ConfName, IniFiles);
_ ->
{ok, nil}
end,
Confs1 = dict:store(ConfName, #config{write_file=WriteFile,
pid=Pid,
options=Options,
inifiles=IniFiles},
Confs),
initialize_app_confs1(Rest, State#state{confs=Confs1}).
parse_inis(ConfName, IniFiles0) ->
IniFiles = econfig_util:find_files(IniFiles0),
lists:map(fun(IniFile) ->
{ok, ParsedIniValues, DelKeys} = parse_ini_file(ConfName, IniFile),
ets:insert(?TAB, ParsedIniValues),
lists:foreach(fun(Key) -> ets:delete(?TAB, Key) end, DelKeys)
end, IniFiles),
WriteFile = lists:last(IniFiles),
WriteFile.
parse_ini_file(ConfName, IniFile) ->
IniFilename = econfig_util:abs_pathname(IniFile),
IniBin =
case file:read_file(IniFilename) of
{ok, IniBin0} ->
IniBin0;
{error, eacces} ->
throw({file_permission_error, IniFile});
{error, enoent} ->
Fmt = "Couldn't find server configuration file ~s.",
Msg = list_to_binary(io_lib:format(Fmt, [IniFilename])),
throw({startup_error, Msg})
end,
Lines = re:split(IniBin, "\r\n|\n|\r|\032", [{return, list}]),
{_, ParsedIniValues, DeleteIniKeys} =
lists:foldl(fun(Line, {AccSectionName, AccValues, AccDeletes}) ->
case string:strip(Line) of
"[" ++ Rest ->
case re:split(Rest, "\\]", [{return, list}]) of
[NewSectionName, ""] ->
{NewSectionName, AccValues, AccDeletes};
{AccSectionName, AccValues, AccDeletes}
end;
";" ++ _Comment ->
{AccSectionName, AccValues, AccDeletes};
Line2 ->
case re:split(Line2, "\s*=\s*", [{return, list}]) of
[Value] ->
MultiLineValuePart = case re:run(Line, "^ \\S", []) of
{match, _} ->
true;
_ ->
false
end,
case {MultiLineValuePart, AccValues} of
{true, [{{_, ValueName}, PrevValue} | AccValuesRest]} ->
case re:split(Value, "\s*;|\t;", [{return, list}]) of
[[]] ->
{AccSectionName, AccValues, AccDeletes};
[LineValue | _Rest] ->
E = {{AccSectionName, ValueName},
PrevValue ++ " " ++
econfig_util:trim_whitespace(LineValue)},
{AccSectionName, [E | AccValuesRest], AccDeletes}
end;
_ ->
{AccSectionName, AccValues, AccDeletes}
end;
{AccSectionName, AccValues, AccDeletes};
ValueName1 = econfig_util:trim_whitespace(ValueName),
RemainingLine = econfig_util:implode(LineValues, "="),
case re:split(RemainingLine, "\s*;|\t;", [{return, list}]) of
[[]] ->
AccDeletes1 = [{conf_key(ConfName), AccSectionName, ValueName1}
| AccDeletes],
{AccSectionName, AccValues, AccDeletes1};
[LineValue | _Rest] ->
{AccSectionName,
[{{conf_key(ConfName), AccSectionName, ValueName1},
econfig_util:trim_whitespace(LineValue)}
| AccValues], AccDeletes}
end
end
end
end, {"", [], []}, Lines),
{ok, ParsedIniValues, DeleteIniKeys}.
process_is_down(Pid) when is_pid(Pid) ->
case ets:member(?TAB, Pid) of
false ->
ok;
true ->
Subs = ets:select(?TAB, [{{{Pid, '$1'}, '$2'}, [], [{{'$1', '$2'}}]}]),
lists:foreach(fun({ConfName, SubKey}) ->
ets:delete(?TAB, {Pid, ConfName}),
ets:delete(?TAB, SubKey)
end, Subs),
ets:delete(?TAB, Pid),
ok
end.
check_fun(none) ->
ok;
check_fun(Fun) when is_function(Fun) ->
case erlang:fun_info(Fun, arity) of
{arity, 1} -> ok;
_ -> {error, badarity}
end;
check_fun({Mod, Fun}) ->
_ = code:ensure_loaded(Mod),
case erlang:function_exported(Mod, Fun, 1) of
true -> ok;
false -> {error, function_not_exported}
end.
|
26da5a9fbac5fdb2e3ea419701e105b8cda695f42d95c91621554e7efecc6c9f | mathiasbourgoin/SPOC | gen_kir.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* , et ( 2013 )
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language .
*
* This software is governed by the CeCILL - B license under French law and
* abiding by the rules of distribution of free software . You can use ,
* modify and/ or redistribute the software under the terms of the CeCILL - B
* license as circulated by CEA , CNRS and INRIA at the following URL
* " " .
*
* As a counterpart to the access to the source code and rights to copy ,
* modify and redistribute granted by the license , users are provided only
* with a limited warranty and the software 's author , the holder of the
* economic rights , and the successive licensors have only limited
* liability .
*
* In this respect , the user 's attention is drawn to the risks associated
* with loading , using , modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software ,
* that may mean that it is complicated to manipulate , and that also
* therefore means that it is reserved for developers and experienced
* professionals having in - depth computer knowledge . Users are therefore
* encouraged to load and test the software 's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and , more generally , to use and operate it in the
* same conditions as regards security .
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL - B license and that you accept its terms .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Mathias Bourgoin, Université Pierre et Marie Curie (2013)
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language.
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*******************************************************************************)
open Camlp4.PreCast
open Syntax
open Ast
open Sarek_types
open Debug
let remove_int_var var =
match var.e with
| Id (_loc, s) ->
Hashtbl.remove !current_args (string_of_ident s);
| _ -> failwith "error new_var"
let rec parse_int2 i t=
match i.e with
| Id (_loc,s) ->
(try
let var = (Hashtbl.find !current_args (string_of_ident s)) in
if var.is_global then
<:expr<global_int_var $ExId(_loc,s)$>>
else
<:expr<var $ExInt(_loc, string_of_int var.n)$ $str:string_of_ident s$>>
with
| Not_found ->
try
let c_const = Hashtbl.find !intrinsics_const
(string_of_ident s) in
match c_const.typ with
| x when x = t ->
<:expr< intrinsics
$ExStr(_loc, c_const.cuda_val)$
$ExStr(_loc, c_const.opencl_val)$>>
| _ -> my_eprintf __LOC__;
assert (not debug); raise (TypeError (t, c_const.typ, _loc))
with Not_found ->
(my_eprintf __LOC__;
assert (not debug); raise (Unbound_value ((string_of_ident s),_loc))))
| Ref (_, {loc=_; e=Id(_loc,s); t=_}) ->
<:expr<global_int_var (fun () -> ! $ExId(_loc, s)$)>>
| Int (_loc, s) -> <:expr<spoc_int32 $(ExInt32 (_loc, s))$>>
| Int32 (_loc, s) -> <:expr<spoc_int32 $(ExInt32 (_loc, s))$>>
| Int64 (_loc, s) -> <:expr<spoc_int64 $(ExInt64 (_loc, s))$>>
| Plus32 _ | Plus64 _ | Min32 _ | Min64 _ | Mul32 _ | Mul64 _
| Mod _ | Div32 _ | Div64 _ ->
parse_body2 i false
| Bind (_loc, var, y, z, is_mutable) -> parse_body2 i false
| VecGet (_loc, vector, index) ->
<:expr<get_vec $parse_int2 vector (TVec t)$
$parse_int2 index TInt32$>>
| ArrGet (_loc, array, index) ->
<:expr<get_arr $parse_int2 array (TVec t)$
$parse_int2 index TInt32$>>
| App _ -> parse_body2 i false
| RecGet _ -> parse_body2 i false
| Nat (_loc, code) -> <:expr< spoc_native $code$>>
| _ -> (my_eprintf (Printf.sprintf "--> (*** val2 %s *)\n%!" (k_expr_to_string i.e));
assert (not debug); raise (TypeError (t, i.t, i.loc));)
and parse_float2 f t=
match f.e with
| App (_loc, e1, e2) ->
parse_body2 f false
| Id (_loc,s) ->
(try
let var = (Hashtbl.find !current_args (string_of_ident s)) in
if var.is_global then
<:expr<global_float_var $ExId(_loc,s)$>>
else
<:expr<var $ExInt(_loc, string_of_int var.n)$ $str:string_of_ident s$>>
with
| Not_found ->
try
let c_const = Hashtbl.find !intrinsics_const (string_of_ident s) in
match c_const.typ with
| x when x = t ->
<:expr< intrinsics $ExStr(_loc, c_const.cuda_val)$ $ExStr(_loc, c_const.opencl_val)$>>
| _ -> my_eprintf __LOC__;
assert (not debug); raise (TypeError (t, c_const.typ, _loc))
with Not_found ->
(my_eprintf __LOC__;
assert (not debug); raise (Unbound_value ((string_of_ident s),_loc))))
| Ref (_, {loc=_; e=Id(_loc,s); t=_}) ->
<:expr<global_float_var (fun () -> ! $ExId(_loc, s)$)>>
| Float (_loc, s) -> <:expr<spoc_float $(ExFlo(_loc, s))$>>
| Float32 (_loc, s) -> <:expr<spoc_float $(ExFlo(_loc, s))$>>
| Float64 (_loc, s) -> <:expr<spoc_double $(ExFlo(_loc, s))$>>
| PlusF32 _ | PlusF64 _ | MinF32 _ | MinF64 _
| MulF32 _ | MulF64 _ | DivF32 _ | DivF64 _
| ModuleAccess _ | RecGet _ | Acc _ ->
parse_body2 f false
| VecGet (_loc, vector, index) ->
<:expr<get_vec $parse_float2 vector (TVec t)$ $parse_int2 index TInt32$>>
| Nat (_loc, code) -> <:expr< spoc_native $code$>>
| _ -> ( my_eprintf (Printf.sprintf "(*** val2 %s *)\n%!" (k_expr_to_string f.e));
assert (not debug); raise (TypeError (t, f.t, f.loc));)
and parse_special a =
match a.e with
| (*create_array *) App (_loc,{t=typ; e= Id(_,<:ident< create_array>>); loc=_}, [b]) ->
<:expr< $parse_body2 b false$>>
| App (_loc, {e=App (_, {t=_; e= App (_,{t=_; e=Id(_,<:ident< map>>); loc=_}, [f]); loc=_}, [a]); _}, [b]) ->
<:expr< map $parse_body2 f false$ $parse_body2 a false$ $parse_body2 b false$>>;
| App (_loc, {e=App (_, {t=_; e= App (_,{t=_; e=Id(_,<:ident< reduce>>); loc=_}, [f]); loc=_}, [a]); _}, [b]) ->
<:expr< reduce $parse_body2 f false$ $parse_body2 a false$ $parse_body2 b false$>>;
|_ ->
raise Not_found
and parse_app a =
my_eprintf (Printf.sprintf "(* val2 parse_app %s *)\n%!" (k_expr_to_string a.e));
try parse_special a with
| Not_found ->
match a.e with
| App (_loc, e1, e2::[]) ->
let res = ref [] in
let constr = ref false in
let rec aux app =
my_eprintf (Printf.sprintf "(* val2 parse_app_app %s *)\n%!" (k_expr_to_string app.e));
let has_vec_lengths = ref false in
match app.e with
| Id (_loc, s) ->
(try
let intr = Hashtbl.find !intrinsics_fun (string_of_ident s) in
<:expr< intrinsics $ExStr(_loc, intr.cuda_val)$ $ExStr(_loc, intr.opencl_val)$>>
with Not_found ->
try
ignore(Hashtbl.find !global_fun (string_of_ident s));
has_vec_lengths := true;
(<:expr< global_fun $id:s$>> )
with Not_found ->
try
ignore(Hashtbl.find !local_fun (string_of_ident s));
has_vec_lengths := true;
<:expr< global_fun $id:s$>>
with Not_found ->
try
let t = Hashtbl.find !constructors (string_of_ident s) in
constr := true;
<:expr< spoc_constr $str:t.name$ $str:string_of_ident s$ [$parse_body2 e2 false$]>>
with _ ->
parse_body2 e1 false;)
| App (_loc, e3, e4::[]) ->
let e = aux e3 in
res := <:expr< ($parse_body2 e4 false$)>> :: !res;
e
| ModuleAccess (_loc, s, e3) ->
open_module s _loc;
let e = aux e3 in
close_module s;
e
| _ -> my_eprintf __LOC__; assert false;
in
let intr = aux e1 in
if !constr then
<:expr< $intr$ >>
else
(
res :=
(parse_body2 e2 false) :: !res;
(match !res with
| [] -> my_eprintf __LOC__; assert false
| t::[] ->
<:expr< app $intr$ [| ($t$) |]>>
| t::q ->
<:expr< app $intr$ [| $exSem_of_list (List.rev !res)$ |]>>)
)
| _ -> parse_body2 a false
and expr_of_app t _loc gen_var y =
match t with
| TApp (t1,((TApp (t2,t3)) as tt)) ->
expr_of_app tt _loc gen_var y
| TApp (t1,t2) ->
(match t2 with
| TInt32 -> <:expr<(new_int_var $`int:gen_var.n$)>>, (parse_body2 y false)
| TInt64 -> <:expr<(new_int_var $`int:gen_var.n$)>>, (parse_body2 y false)
| TFloat32 -> <:expr<(new_float_var $`int:gen_var.n$)>>,(parse_body2 y false)
| TFloat64 -> <:expr<(new_double_var $`int:gen_var.n$)>>, (parse_body2 y false)
| _ -> failwith "unknown var type")
| _ -> my_eprintf __LOC__; assert false
and parse_case2 mc _loc =
let aux (_loc,patt,e) =
match patt with
| Constr (_,None) ->
<:expr< spoc_case $`int:ident_of_patt _loc patt$ None $parse_body2 e false$>>
| Constr (s,Some id) ->
incr arg_idx;
Hashtbl.add !current_args (string_of_ident id)
{n = !arg_idx; var_type = ktyp_of_typ (TyId(_loc,IdLid(_loc,type_of_patt patt)));
is_mutable = false;
read_only = false;
write_only = false;
is_global = false;};
let i = !arg_idx in
let bb =
parse_body2 e false in
let e =
<:expr< spoc_case $`int:ident_of_patt _loc patt$
(Some ($str:ctype_of_sarek_type (type_of_patt patt)$,$str:s$,$`int:i$,$str:string_of_ident id$)) $bb$>> in
Hashtbl.remove !current_args (string_of_ident id);
e
in
let l = List.map aux mc
in <:expr< [| $exSem_of_list l$ |]>>
and parse_body2 body bool =
let rec aux ?return_bool:(r=false) body =
my_eprintf (Printf.sprintf "(* val2 %s : %b*)\n%!" (k_expr_to_string body.e) r);
match body.e with
| Bind (_loc, var,y, z, is_mutable) ->
(match var.e with
| Id (_loc, s) ->
(match y.e with
| Fun _ ->
parse_body2 z bool;
| _ ->
(let gen_var =
try (Hashtbl.find !current_args (string_of_ident s))
with _ ->
let s =
Printf.sprintf "Var : %s not found in [ %s ]"
(string_of_ident s)
(Hashtbl.fold
(fun a b c -> c^a^"; ")
!current_args "")
in
failwith s;
in
let rec f () =
match var.t with
| TInt32 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y)
| TInt64 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y)
| TFloat32 -> <:expr<(new_float_var $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TFloat64 -> <:expr<(new_double_var $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TBool -> <:expr< (new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y) (* use int instead of bools *)
| TApp _ -> expr_of_app var.t _loc gen_var y
| Custom (t,n) ->
<:expr<(new_custom_var $str:n$ $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TUnknown -> if gen_var.var_type <> TUnknown then
( var.t <- gen_var.var_type;
f ();)
else
(my_eprintf __LOC__;
raise (TypeError (TUnknown, gen_var.var_type , _loc));)
| TArr (t,m) ->
let elttype =
match t with
| TInt32 -> <:expr<eint32>>
| TInt64 -> <:expr<eint64>>
| TFloat32 -> <:expr<efloat32>>
| TFloat64 -> <:expr<efloat64>>
| _ -> my_eprintf __LOC__; assert false
and memspace =
match m with
| Local -> <:expr<local>>
| Shared -> <:expr<shared>>
| Global -> <:expr<global>>
| _ -> my_eprintf __LOC__; assert false
in
<:expr<(new_array $str:string_of_ident s$) ($aux y$) $elttype$ $memspace$>>,(aux y)
| _ -> ( assert (not debug);
raise (TypeError (TUnknown, gen_var.var_type , _loc));)
in
let ex1, ex2 = f () in
arg_list := <:expr<(spoc_declare $ex1$)>>:: !arg_list;
(let var_ = parse_body2 var false in
let y = aux y in
let z = aux z in
let res =
match var.t with
TArr _ -> <:expr< $z$>>
| _ -> <:expr< seq (spoc_set $var_$ $y$) $z$>>
in
remove_int_var var;
res)))
| _ -> failwith "strange binding");
| Plus32 (_loc, a,b) -> body.t <- TInt32;
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<spoc_plus $p1$ $p2$>>)
| Plus64 (_loc, a,b) -> body.t <- TInt64;
let p1 = (parse_int2 a TInt64)
and p2 = (parse_int2 b TInt64) in
if not r then
return_type := TInt64;
( <:expr<spoc_plus $p1$ $p2$>>)
| PlusF32 (_loc, a,b) ->
let p1 = (parse_float2 a TFloat32)
and p2 = (parse_float2 b TFloat32) in
if not r then
return_type := TFloat32;
( <:expr<spoc_plus_float $p1$ $p2$>>)
| PlusF64 (_loc, a,b) ->
let p1 = (parse_float2 a TFloat64)
and p2 = (parse_float2 b TFloat64) in
if not r then
return_type := TFloat64;
( <:expr<spoc_plus_float $p1$ $p2$>>)
| Min32 (_loc, a,b) -> body.t <- TInt32;
( <:expr<spoc_min $(parse_int2 a TInt32)$ $(parse_int2 b TInt32)$>>)
| Min64 (_loc, a,b) -> body.t <- TInt64;
( <:expr<spoc_min $(parse_int2 a TInt64)$ $(parse_int2 b TInt64)$>>)
| MinF32 (_loc, a,b) ->
( <:expr<spoc_min_float $(parse_float2 a TFloat32)$ $(parse_float2 b TFloat32)$>>)
| MinF64 (_loc, a,b) ->
( <:expr<spoc_min_float $(parse_float2 a TFloat64)$ $(parse_float2 b TFloat64)$>>)
| Mul32 (_loc, a,b) ->
if not r then
return_type := TInt32;
( <:expr<spoc_mul $(parse_int2 a TInt32)$ $(parse_int2 b TInt32)$>>)
| Mul64 (_loc, a,b) -> body.t <- TInt64;
( <:expr<spoc_mul $(parse_int2 a TInt64)$ $(parse_int2 b TInt64)$>>)
| MulF32 (_loc, a,b) ->
if not r then
return_type := TFloat32;
( <:expr<spoc_mul_float $(parse_float2 a TFloat32)$ $(parse_float2 b TFloat32)$>>)
| MulF64 (_loc, a,b) ->
( <:expr<spoc_mul_float $(parse_float2 a TFloat64)$ $(parse_float2 b TFloat64)$>>)
| Div32 (_loc, a,b) -> body.t <- TInt32;
( <:expr<spoc_div $(parse_int2 a TInt32)$ $(parse_int2 b TInt32)$>>)
| Div64 (_loc, a,b) -> body.t <- TInt64;
( <:expr<spoc_div $(parse_int2 a TInt64)$ $(parse_int2 b TInt64)$>>)
| DivF32 (_loc, a,b) ->
( <:expr<spoc_div_float $(parse_float2 a TFloat32)$ $(parse_float2 b TFloat32)$>>)
| DivF64 (_loc, a,b) ->
( <:expr<spoc_div_float $(parse_float2 a TFloat64)$ $(parse_float2 b TFloat64)$>>)
| Mod (_loc, a,b) -> body.t <- TInt32;
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<spoc_mod $p1$ $p2$>>)
| Id (_loc,s) ->
let id =
(try
let var =
(Hashtbl.find !current_args (string_of_ident s))
in
if not r then
return_type := var.var_type;
(match var.var_type with
| TUnit -> <:expr< Unit>>
| _ ->
body.t <- var.var_type;
if var.is_global then
match var.var_type with
| TFloat32 ->
<:expr<global_float_var (fun () -> $ExId(_loc,s)$)>>
| TInt32 -> <:expr<global_int_var (fun () -> $ExId(_loc,s)$)>>
| _ -> my_eprintf __LOC__; assert false
else
<:expr<var $ExInt(_loc, string_of_int var.n)$ $str:string_of_ident s$>>
)
with _ ->
try
let c_const = (Hashtbl.find !intrinsics_const (string_of_ident s)) in
if body.t <> c_const.typ then
if body.t = TUnknown then
body.t <- c_const.typ
else
(my_eprintf __LOC__;
raise (TypeError (c_const.typ, body.t, _loc)));
<:expr<intrinsics $ExStr(_loc, c_const.cuda_val)$ $ExStr(_loc, c_const.opencl_val)$>>
with _ ->
(try
let intr =
Hashtbl.find !intrinsics_fun (string_of_ident s) in
<:expr< intrinsics $ExStr(_loc, intr.cuda_val)$ $ExStr(_loc, intr.opencl_val)$>>
with Not_found ->
try
ignore(Hashtbl.find !global_fun (string_of_ident s));
<:expr< global_fun $id:s$>>
with Not_found ->
try
ignore(Hashtbl.find !local_fun (string_of_ident s));
<:expr< global_fun $id:s$>>
with Not_found ->
try
let t = Hashtbl.find !constructors (string_of_ident s) in
<:expr< spoc_constr $str:t.name$ $str:(string_of_ident s)$ [] >>
with
| _ ->
(my_eprintf __LOC__;
raise (Unbound_value ((string_of_ident s), _loc))))) in
if r then
(return_type := body.t;
<:expr< spoc_return $id$ >>)
else id;
| Int (_loc, i) -> <:expr<spoc_int $ExInt(_loc, i)$>>
| Int32 (_loc, i) -> <:expr<spoc_int32 $ExInt32(_loc, i)$>>
| Int64 (_loc, i) -> <:expr<spoc_int64 $ExInt64(_loc, i)$>>
| Float (_loc, f) -> <:expr<spoc_float $ExFlo(_loc, f)$>>
| Float32 (_loc, f) -> <:expr<spoc_float $ExFlo(_loc, f)$>>
| Float64 (_loc, f) -> <:expr<spoc_double $ExFlo(_loc, f)$>>
| Seq (_loc, x, y) ->
(match y.e with
| Seq _ ->
let x = parse_body2 x false in
let y = parse_body2 y bool in
<:expr<seq $x$ $y$>>
| _ ->
let e1 = parse_body2 x false in
let e2 = aux (~return_bool:true) y
in <:expr<seq $e1$ $e2$>>
)
| End (_loc, x) ->
let res = <:expr< $aux x$>>
in
<:expr<$res$>>
| VecSet (_loc, vector, value) ->
let gen_value = aux value in
let gen_value =
match vector.t, value.e with
| TInt32, (Int32 _) -> <:expr<( $gen_value$)>>
| TInt64, (Int64 _) -> <:expr<( $gen_value$)>>
| TFloat32, (Float32 _) -> <:expr<( $gen_value$)>>
| TFloat64, (Float64 _) -> <:expr<( $gen_value$)>>
| _ -> gen_value
in
let v = aux (~return_bool:true) vector in
let e = <:expr<set_vect_var $v$ $gen_value$>> in
return_type := TUnit;
e
| VecGet(_loc, vector, index) ->
let e =
<:expr<get_vec $aux vector$ $parse_int2 index TInt32$>> in
(match vector.t with
| TVec ty->
();
| _ ->
my_eprintf __LOC__; assert (not debug));
e
| ArrSet (_loc, array, value) ->
let gen_value = aux value in
let gen_value =
match array.t, value.e with
| TInt32, (Int32 _) -> <:expr<( $gen_value$)>>
| TInt64, (Int64 _) -> <:expr<( $gen_value$)>>
| TFloat32, (Float32 _) -> <:expr<( $gen_value$)>>
| TFloat64, (Float64 _) -> <:expr<( $gen_value$)>>
| _ -> gen_value
in
let v = aux (~return_bool:true) array in
let e = <:expr<set_arr_var $v$ $gen_value$>> in
return_type := TUnit;
e
| ArrGet(_loc, array, index) ->
let e =
<:expr<get_arr $aux array$ $parse_int2 index TInt32$>> in
(match array.t with
| TArr ty->
();
| _ ->
my_eprintf __LOC__; assert (not debug));
e
| True _loc ->
if not r then
return_type := TBool;
<:expr<spoc_int32 $(ExInt32 (_loc, "1"))$>>
| False _loc ->
if not r then
return_type := TBool;
<:expr<spoc_int32 $(ExInt32 (_loc, "0"))$>>
| BoolNot(_loc, a) ->
if not r then
return_type := TBool;
<:expr< b_not $aux a$>>
| BoolOr(_loc, a, b) ->
if not r then
return_type := TBool;
<:expr< b_or $aux a$ $aux b$>>
| BoolAnd(_loc, a, b) ->
if not r then
return_type := TBool;
<:expr< b_and $aux a$ $aux b$>>
| BoolEq(_loc, a, b) ->
if not r then
return_type := TBool;
(match a.t with
| Custom (_,n) ->
<:expr< equals_custom $str:"spoc_custom_compare_"^n^"_sarek"$
$aux a$ $aux b$>>
| _ -> <:expr< equals32 $aux a$ $aux b$>>
)
| BoolEq32 (_loc, a, b) ->
if not r then
return_type := TBool;
<:expr< equals32 $aux a$ $aux b$>>
| BoolEq64(_loc, a, b) ->
<:expr< equals64 $aux a$ $aux b$>>
| BoolEqF32(_loc, a, b) ->
<:expr< equalsF $aux a$ $aux b$>>
| BoolEqF64(_loc, a, b) ->
<:expr< equalsF64 $aux a$ $aux b$>>
| BoolLt(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<lt $p1$ $p2$>>)
| BoolLt32(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<lt32 $p1$ $p2$>>)
| BoolLt64(_loc, a, b) ->
<:expr< lt64 $aux a$ $aux b$>>
| BoolLtF32(_loc, a, b) ->
<:expr< ltF $aux (~return_bool:false) a$ $aux (~return_bool:false) b$>>
| BoolLtF64(_loc, a, b) ->
<:expr< ltF64 $aux a$ $aux b$>>
| BoolGt(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<gt $p1$ $p2$>>)
| BoolGt32(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<gt32 $p1$ $p2$>>)
| BoolGt64(_loc, a, b) ->
<:expr< gt64 $aux a$ $aux b$>>
| BoolGtF32(_loc, a, b) ->
<:expr< gtF $aux a$ $aux b$>>
| BoolGtF64(_loc, a, b) ->
<:expr< gtF64 $aux a$ $aux b$>>
| BoolLtE(_loc, a, b) ->
<:expr< lte $aux a$ $aux b$>>
| BoolLtE32(_loc, a, b) ->
<:expr< lte32 $aux a$ $aux b$>>
| BoolLtE64(_loc, a, b) ->
<:expr< lte64 $aux a$ $aux b$>>
| BoolLtEF32(_loc, a, b) ->
<:expr< lteF $aux a$ $aux b$>>
| BoolLtEF64(_loc, a, b) ->
<:expr< lteF64 $aux a$ $aux b$>>
| BoolGtE(_loc, a, b) ->
<:expr< gte $aux a$ $aux b$>>
| BoolGtE32(_loc, a, b) ->
<:expr< gte32 $aux a$ $aux b$>>
| BoolGtE64(_loc, a, b) ->
<:expr< gte64 $aux a$ $aux b$>>
| BoolGtEF32(_loc, a, b) ->
<:expr< gteF $aux a$ $aux b$>>
| BoolGtEF64(_loc, a, b) ->
<:expr< gteF64 $aux a$ $aux b$>>
| Ife (_loc, cond, cons1, cons2) ->
let p1 = aux (~return_bool:false) cond
and p2 = aux cons1
and p3 = aux cons2
in
if r then
return_type := cons2.t;
(<:expr< spoc_ife $p1$ $p2$ $p3$>>)
| If (_loc, cond, cons1) ->
let cons1_ = aux cons1 in
return_type := cons1.t;
(<:expr< spoc_if $aux cond$ $cons1_$>>)
| DoLoop (_loc, id, min, max, body) ->
(<:expr<spoc_do $aux id$ $aux min$ $aux max$ $aux body$>>)
| While (_loc, cond, body) ->
let cond = aux cond in
let body = aux body in
(<:expr<spoc_while $cond$ $body$>>)
| App (_loc, e1, e2) ->
let e = <:expr< $parse_app body$>> in
let rec app_return_type = function
| TApp (_,(TApp (a,b))) -> app_return_type b
| TApp (_,b) -> b
| a -> a
in
return_type := app_return_type body.t;
e
| Open (_loc, id, e) ->
let rec aux2 = function
| IdAcc (l,a,b) -> aux2 a; aux2 b
| IdUid (l,s) -> open_module s l
| _ -> my_eprintf __LOC__; assert (not debug)
in
aux2 id;
let ex = <:expr< $aux e$>> in
let rec aux2 = function
| IdAcc (l,a,b) -> aux2 a; aux2 b
| IdUid (l,s) -> close_module s
| _ -> assert (not debug)
in
aux2 id;
ex
| ModuleAccess (_loc, s, e) ->
open_module s _loc;
let ex = <:expr< $aux e$>> in
close_module s;
ex
| Noop ->
let _loc = body.loc in
<:expr< spoc_unit () >>
| Acc (_loc, e1, e2) ->
let e1 = parse_body2 e1 false
and e2 = parse_body2 e2 false
in
if not r then
return_type := TUnit;
<:expr< spoc_acc $e1$ $e2$>>
| Ref (_loc, {t=_; e=Id(_loc2, s);loc=_}) ->
let var =
Hashtbl.find !current_args (string_of_ident s) in
body.t <- var.var_type;
if not r then
return_type := body.t;
(*if var.is_global then*)
(match var.var_type with
| TFloat32 ->
<:expr<global_float_var (fun _ -> ! $ExId(_loc,s)$)>>
| TFloat64 ->
<:expr<global_float64_var (fun _ -> ! $ExId(_loc,s)$)>>
| TInt32 -> <:expr<global_int_var (fun _ -> ! $ExId(_loc,s)$)>>
| Custom _ -> <:expr<global_custom_var (fun _ -> ! $ExId(_loc,s)$)>>
| TBool -> <:expr<global_int_var (fun _ -> ! $ExId(_loc,s)$)>>
| _ -> assert false)
(*else
assert false*)
| Match(_loc,e,
((_,Constr (n,_),ec)::q as mc )) ->
let e = parse_body2 e false
and mc = parse_case2 mc _loc in
let name = (Hashtbl.find !constructors n).name in
if not r then
return_type := ec.t;
<:expr< spoc_match $str:name$ $e$ $mc$ >>
| Match _ -> assert false
| Record (_loc,fl) ->
begin
get from field list
let t,name =
let rec aux (acc:string list) (flds : field list) : string list =
match flds with
| (_loc,t,_)::q ->
let rec_fld : recrd_field =
try Hashtbl.find !rec_fields (string_of_ident t)
with
| _ ->
(assert (not debug);
raise (FieldError (string_of_ident t, List.hd acc, _loc)))
in
aux
(let rec aux2 (res:string list) (acc_:string list) (flds_:string list) =
match acc_,flds_ with
| (t1::q1),(t2::q2) ->
if t1 = t2 then
aux2 (t1::acc_) acc q2
else
aux2 (t1::acc_) q1 (t2::q2)
| _,[] -> res
| [],q ->
aux2 res acc q
in aux2 [] acc rec_fld.ctyps) q
| [] -> acc
in
let start : string list =
let (_loc,t,_) = (List.hd fl) in
try
(Hashtbl.find !rec_fields (string_of_ident t)).ctyps
with
| _ ->
(assert (not debug);
raise (FieldError (string_of_ident t, "\"\"", _loc)))
in
let r : string list =
aux start fl
in ktyp_of_typ (TyId(_loc,IdLid(_loc,List.hd r))),(List.hd r)
in
(* sort fields *)
let res =
(match t with
| Custom (KRecord (l1,l2,_),n) ->
let fl = List.map
(fun x -> List.find (fun (_,y,_) ->
(string_of_ident y) = (string_of_ident x)) fl) l2 in
let r = List.map
(fun (_,_,b) -> <:expr< $parse_body2 b false$>>)
fl
in <:expr< spoc_record $str:name$ [$Ast.exSem_of_list r$] >>
| _ -> assert false)
in
if not r then
return_type := body.t;
res;
end
| RecGet (_loc,r,fld) -> <:expr< spoc_rec_get $parse_body2 r false$ $str:string_of_ident fld$>>
| RecSet (_loc,e1,e2) -> <:expr< spoc_rec_set $parse_body2 e1 false$ $parse_body2 e2 false$>>
| TypeConstraint (_loc, e, tt) ->
if not r then return_type := tt;
parse_body2 e false
| Nat (_loc, code) -> <:expr< spoc_native $code$ >>
| Fun (_loc,stri,tt,funv,lifted) -> <:expr< global_fun $stri$ >>
| Pragma (_loc, lopt, expr) ->
let lopt = List.map
(fun opt -> <:expr< $str:opt$>>) lopt in
<:expr< pragma [$exSem_of_list lopt$] $parse_body2 expr false$ >>
| _ -> (
my_eprintf __LOC__;
failwith ((k_expr_to_string body.e)^": not implemented yet");)
in
let _loc = body.loc in
if bool then
(
my_eprintf (Printf.sprintf"(* val2 return %s *)\n%!" (k_expr_to_string body.e));
match body.e with
| Bind (_loc, var,y, z, is_mutable) ->
(
(match var.e with
| Id (_loc, s) ->
(match y.e with
| Fun _ -> <:expr< spoc_return $aux z$>>
| _ ->
(let gen_var = (
try Hashtbl.find !current_args (string_of_ident s)
with _ -> assert false) in
let ex1,ex2 =
match var.t with
| TInt32 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$) >>, (aux y)
| TInt64 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y)
| TFloat32 -> <:expr<(new_float_var $`int:gen_var.n$$str:string_of_ident s$)>>,(aux y)
| TFloat64 -> <:expr<(new_double_var $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TBool -> <:expr< (new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y) (* use int instead of bools *)
| TUnit -> <:expr<Unit>>,aux y;
| Custom (t,n) ->
<:expr<(new_custom_var $str:n$ $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| _ -> assert (not debug);
failwith "unknown var type"
in
arg_list := <:expr<(spoc_declare $ex1$)>>:: !arg_list);
(let var_ = parse_body2 var false in
let y = aux y in
let z = aux (~return_bool:true) z in
let res =
match var.t with
TArr _ -> <:expr< $z$>>
| _ -> <:expr< seq (spoc_set $var_$ $y$) $z$>>
in
remove_int_var var;
res))
| _ -> failwith "this binding is not a binding"))
| Seq (a,b,c) ->
<:expr<spoc_return $aux body$>>
| _ ->
let e = {t=body.t; e =End(_loc, body); loc = _loc} in
match body.t with
| TUnit ->
let res = aux e in
return_type := TUnit;
<:expr< $res$ >>
|_ ->
<:expr<spoc_return $aux e$>>
)
else
aux body
| null | https://raw.githubusercontent.com/mathiasbourgoin/SPOC/9014d26b6d64261d1ace97db7f3fe2256a7c459c/SpocLibs/Sarek/extension/gen_kir.ml | ocaml | create_array
use int instead of bools
if var.is_global then
else
assert false
sort fields
use int instead of bools | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* , et ( 2013 )
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language .
*
* This software is governed by the CeCILL - B license under French law and
* abiding by the rules of distribution of free software . You can use ,
* modify and/ or redistribute the software under the terms of the CeCILL - B
* license as circulated by CEA , CNRS and INRIA at the following URL
* " " .
*
* As a counterpart to the access to the source code and rights to copy ,
* modify and redistribute granted by the license , users are provided only
* with a limited warranty and the software 's author , the holder of the
* economic rights , and the successive licensors have only limited
* liability .
*
* In this respect , the user 's attention is drawn to the risks associated
* with loading , using , modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software ,
* that may mean that it is complicated to manipulate , and that also
* therefore means that it is reserved for developers and experienced
* professionals having in - depth computer knowledge . Users are therefore
* encouraged to load and test the software 's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and , more generally , to use and operate it in the
* same conditions as regards security .
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL - B license and that you accept its terms .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Mathias Bourgoin, Université Pierre et Marie Curie (2013)
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language.
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*******************************************************************************)
open Camlp4.PreCast
open Syntax
open Ast
open Sarek_types
open Debug
let remove_int_var var =
match var.e with
| Id (_loc, s) ->
Hashtbl.remove !current_args (string_of_ident s);
| _ -> failwith "error new_var"
let rec parse_int2 i t=
match i.e with
| Id (_loc,s) ->
(try
let var = (Hashtbl.find !current_args (string_of_ident s)) in
if var.is_global then
<:expr<global_int_var $ExId(_loc,s)$>>
else
<:expr<var $ExInt(_loc, string_of_int var.n)$ $str:string_of_ident s$>>
with
| Not_found ->
try
let c_const = Hashtbl.find !intrinsics_const
(string_of_ident s) in
match c_const.typ with
| x when x = t ->
<:expr< intrinsics
$ExStr(_loc, c_const.cuda_val)$
$ExStr(_loc, c_const.opencl_val)$>>
| _ -> my_eprintf __LOC__;
assert (not debug); raise (TypeError (t, c_const.typ, _loc))
with Not_found ->
(my_eprintf __LOC__;
assert (not debug); raise (Unbound_value ((string_of_ident s),_loc))))
| Ref (_, {loc=_; e=Id(_loc,s); t=_}) ->
<:expr<global_int_var (fun () -> ! $ExId(_loc, s)$)>>
| Int (_loc, s) -> <:expr<spoc_int32 $(ExInt32 (_loc, s))$>>
| Int32 (_loc, s) -> <:expr<spoc_int32 $(ExInt32 (_loc, s))$>>
| Int64 (_loc, s) -> <:expr<spoc_int64 $(ExInt64 (_loc, s))$>>
| Plus32 _ | Plus64 _ | Min32 _ | Min64 _ | Mul32 _ | Mul64 _
| Mod _ | Div32 _ | Div64 _ ->
parse_body2 i false
| Bind (_loc, var, y, z, is_mutable) -> parse_body2 i false
| VecGet (_loc, vector, index) ->
<:expr<get_vec $parse_int2 vector (TVec t)$
$parse_int2 index TInt32$>>
| ArrGet (_loc, array, index) ->
<:expr<get_arr $parse_int2 array (TVec t)$
$parse_int2 index TInt32$>>
| App _ -> parse_body2 i false
| RecGet _ -> parse_body2 i false
| Nat (_loc, code) -> <:expr< spoc_native $code$>>
| _ -> (my_eprintf (Printf.sprintf "--> (*** val2 %s *)\n%!" (k_expr_to_string i.e));
assert (not debug); raise (TypeError (t, i.t, i.loc));)
and parse_float2 f t=
match f.e with
| App (_loc, e1, e2) ->
parse_body2 f false
| Id (_loc,s) ->
(try
let var = (Hashtbl.find !current_args (string_of_ident s)) in
if var.is_global then
<:expr<global_float_var $ExId(_loc,s)$>>
else
<:expr<var $ExInt(_loc, string_of_int var.n)$ $str:string_of_ident s$>>
with
| Not_found ->
try
let c_const = Hashtbl.find !intrinsics_const (string_of_ident s) in
match c_const.typ with
| x when x = t ->
<:expr< intrinsics $ExStr(_loc, c_const.cuda_val)$ $ExStr(_loc, c_const.opencl_val)$>>
| _ -> my_eprintf __LOC__;
assert (not debug); raise (TypeError (t, c_const.typ, _loc))
with Not_found ->
(my_eprintf __LOC__;
assert (not debug); raise (Unbound_value ((string_of_ident s),_loc))))
| Ref (_, {loc=_; e=Id(_loc,s); t=_}) ->
<:expr<global_float_var (fun () -> ! $ExId(_loc, s)$)>>
| Float (_loc, s) -> <:expr<spoc_float $(ExFlo(_loc, s))$>>
| Float32 (_loc, s) -> <:expr<spoc_float $(ExFlo(_loc, s))$>>
| Float64 (_loc, s) -> <:expr<spoc_double $(ExFlo(_loc, s))$>>
| PlusF32 _ | PlusF64 _ | MinF32 _ | MinF64 _
| MulF32 _ | MulF64 _ | DivF32 _ | DivF64 _
| ModuleAccess _ | RecGet _ | Acc _ ->
parse_body2 f false
| VecGet (_loc, vector, index) ->
<:expr<get_vec $parse_float2 vector (TVec t)$ $parse_int2 index TInt32$>>
| Nat (_loc, code) -> <:expr< spoc_native $code$>>
| _ -> ( my_eprintf (Printf.sprintf "(*** val2 %s *)\n%!" (k_expr_to_string f.e));
assert (not debug); raise (TypeError (t, f.t, f.loc));)
and parse_special a =
match a.e with
<:expr< $parse_body2 b false$>>
| App (_loc, {e=App (_, {t=_; e= App (_,{t=_; e=Id(_,<:ident< map>>); loc=_}, [f]); loc=_}, [a]); _}, [b]) ->
<:expr< map $parse_body2 f false$ $parse_body2 a false$ $parse_body2 b false$>>;
| App (_loc, {e=App (_, {t=_; e= App (_,{t=_; e=Id(_,<:ident< reduce>>); loc=_}, [f]); loc=_}, [a]); _}, [b]) ->
<:expr< reduce $parse_body2 f false$ $parse_body2 a false$ $parse_body2 b false$>>;
|_ ->
raise Not_found
and parse_app a =
my_eprintf (Printf.sprintf "(* val2 parse_app %s *)\n%!" (k_expr_to_string a.e));
try parse_special a with
| Not_found ->
match a.e with
| App (_loc, e1, e2::[]) ->
let res = ref [] in
let constr = ref false in
let rec aux app =
my_eprintf (Printf.sprintf "(* val2 parse_app_app %s *)\n%!" (k_expr_to_string app.e));
let has_vec_lengths = ref false in
match app.e with
| Id (_loc, s) ->
(try
let intr = Hashtbl.find !intrinsics_fun (string_of_ident s) in
<:expr< intrinsics $ExStr(_loc, intr.cuda_val)$ $ExStr(_loc, intr.opencl_val)$>>
with Not_found ->
try
ignore(Hashtbl.find !global_fun (string_of_ident s));
has_vec_lengths := true;
(<:expr< global_fun $id:s$>> )
with Not_found ->
try
ignore(Hashtbl.find !local_fun (string_of_ident s));
has_vec_lengths := true;
<:expr< global_fun $id:s$>>
with Not_found ->
try
let t = Hashtbl.find !constructors (string_of_ident s) in
constr := true;
<:expr< spoc_constr $str:t.name$ $str:string_of_ident s$ [$parse_body2 e2 false$]>>
with _ ->
parse_body2 e1 false;)
| App (_loc, e3, e4::[]) ->
let e = aux e3 in
res := <:expr< ($parse_body2 e4 false$)>> :: !res;
e
| ModuleAccess (_loc, s, e3) ->
open_module s _loc;
let e = aux e3 in
close_module s;
e
| _ -> my_eprintf __LOC__; assert false;
in
let intr = aux e1 in
if !constr then
<:expr< $intr$ >>
else
(
res :=
(parse_body2 e2 false) :: !res;
(match !res with
| [] -> my_eprintf __LOC__; assert false
| t::[] ->
<:expr< app $intr$ [| ($t$) |]>>
| t::q ->
<:expr< app $intr$ [| $exSem_of_list (List.rev !res)$ |]>>)
)
| _ -> parse_body2 a false
and expr_of_app t _loc gen_var y =
match t with
| TApp (t1,((TApp (t2,t3)) as tt)) ->
expr_of_app tt _loc gen_var y
| TApp (t1,t2) ->
(match t2 with
| TInt32 -> <:expr<(new_int_var $`int:gen_var.n$)>>, (parse_body2 y false)
| TInt64 -> <:expr<(new_int_var $`int:gen_var.n$)>>, (parse_body2 y false)
| TFloat32 -> <:expr<(new_float_var $`int:gen_var.n$)>>,(parse_body2 y false)
| TFloat64 -> <:expr<(new_double_var $`int:gen_var.n$)>>, (parse_body2 y false)
| _ -> failwith "unknown var type")
| _ -> my_eprintf __LOC__; assert false
and parse_case2 mc _loc =
let aux (_loc,patt,e) =
match patt with
| Constr (_,None) ->
<:expr< spoc_case $`int:ident_of_patt _loc patt$ None $parse_body2 e false$>>
| Constr (s,Some id) ->
incr arg_idx;
Hashtbl.add !current_args (string_of_ident id)
{n = !arg_idx; var_type = ktyp_of_typ (TyId(_loc,IdLid(_loc,type_of_patt patt)));
is_mutable = false;
read_only = false;
write_only = false;
is_global = false;};
let i = !arg_idx in
let bb =
parse_body2 e false in
let e =
<:expr< spoc_case $`int:ident_of_patt _loc patt$
(Some ($str:ctype_of_sarek_type (type_of_patt patt)$,$str:s$,$`int:i$,$str:string_of_ident id$)) $bb$>> in
Hashtbl.remove !current_args (string_of_ident id);
e
in
let l = List.map aux mc
in <:expr< [| $exSem_of_list l$ |]>>
and parse_body2 body bool =
let rec aux ?return_bool:(r=false) body =
my_eprintf (Printf.sprintf "(* val2 %s : %b*)\n%!" (k_expr_to_string body.e) r);
match body.e with
| Bind (_loc, var,y, z, is_mutable) ->
(match var.e with
| Id (_loc, s) ->
(match y.e with
| Fun _ ->
parse_body2 z bool;
| _ ->
(let gen_var =
try (Hashtbl.find !current_args (string_of_ident s))
with _ ->
let s =
Printf.sprintf "Var : %s not found in [ %s ]"
(string_of_ident s)
(Hashtbl.fold
(fun a b c -> c^a^"; ")
!current_args "")
in
failwith s;
in
let rec f () =
match var.t with
| TInt32 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y)
| TInt64 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y)
| TFloat32 -> <:expr<(new_float_var $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TFloat64 -> <:expr<(new_double_var $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TApp _ -> expr_of_app var.t _loc gen_var y
| Custom (t,n) ->
<:expr<(new_custom_var $str:n$ $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TUnknown -> if gen_var.var_type <> TUnknown then
( var.t <- gen_var.var_type;
f ();)
else
(my_eprintf __LOC__;
raise (TypeError (TUnknown, gen_var.var_type , _loc));)
| TArr (t,m) ->
let elttype =
match t with
| TInt32 -> <:expr<eint32>>
| TInt64 -> <:expr<eint64>>
| TFloat32 -> <:expr<efloat32>>
| TFloat64 -> <:expr<efloat64>>
| _ -> my_eprintf __LOC__; assert false
and memspace =
match m with
| Local -> <:expr<local>>
| Shared -> <:expr<shared>>
| Global -> <:expr<global>>
| _ -> my_eprintf __LOC__; assert false
in
<:expr<(new_array $str:string_of_ident s$) ($aux y$) $elttype$ $memspace$>>,(aux y)
| _ -> ( assert (not debug);
raise (TypeError (TUnknown, gen_var.var_type , _loc));)
in
let ex1, ex2 = f () in
arg_list := <:expr<(spoc_declare $ex1$)>>:: !arg_list;
(let var_ = parse_body2 var false in
let y = aux y in
let z = aux z in
let res =
match var.t with
TArr _ -> <:expr< $z$>>
| _ -> <:expr< seq (spoc_set $var_$ $y$) $z$>>
in
remove_int_var var;
res)))
| _ -> failwith "strange binding");
| Plus32 (_loc, a,b) -> body.t <- TInt32;
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<spoc_plus $p1$ $p2$>>)
| Plus64 (_loc, a,b) -> body.t <- TInt64;
let p1 = (parse_int2 a TInt64)
and p2 = (parse_int2 b TInt64) in
if not r then
return_type := TInt64;
( <:expr<spoc_plus $p1$ $p2$>>)
| PlusF32 (_loc, a,b) ->
let p1 = (parse_float2 a TFloat32)
and p2 = (parse_float2 b TFloat32) in
if not r then
return_type := TFloat32;
( <:expr<spoc_plus_float $p1$ $p2$>>)
| PlusF64 (_loc, a,b) ->
let p1 = (parse_float2 a TFloat64)
and p2 = (parse_float2 b TFloat64) in
if not r then
return_type := TFloat64;
( <:expr<spoc_plus_float $p1$ $p2$>>)
| Min32 (_loc, a,b) -> body.t <- TInt32;
( <:expr<spoc_min $(parse_int2 a TInt32)$ $(parse_int2 b TInt32)$>>)
| Min64 (_loc, a,b) -> body.t <- TInt64;
( <:expr<spoc_min $(parse_int2 a TInt64)$ $(parse_int2 b TInt64)$>>)
| MinF32 (_loc, a,b) ->
( <:expr<spoc_min_float $(parse_float2 a TFloat32)$ $(parse_float2 b TFloat32)$>>)
| MinF64 (_loc, a,b) ->
( <:expr<spoc_min_float $(parse_float2 a TFloat64)$ $(parse_float2 b TFloat64)$>>)
| Mul32 (_loc, a,b) ->
if not r then
return_type := TInt32;
( <:expr<spoc_mul $(parse_int2 a TInt32)$ $(parse_int2 b TInt32)$>>)
| Mul64 (_loc, a,b) -> body.t <- TInt64;
( <:expr<spoc_mul $(parse_int2 a TInt64)$ $(parse_int2 b TInt64)$>>)
| MulF32 (_loc, a,b) ->
if not r then
return_type := TFloat32;
( <:expr<spoc_mul_float $(parse_float2 a TFloat32)$ $(parse_float2 b TFloat32)$>>)
| MulF64 (_loc, a,b) ->
( <:expr<spoc_mul_float $(parse_float2 a TFloat64)$ $(parse_float2 b TFloat64)$>>)
| Div32 (_loc, a,b) -> body.t <- TInt32;
( <:expr<spoc_div $(parse_int2 a TInt32)$ $(parse_int2 b TInt32)$>>)
| Div64 (_loc, a,b) -> body.t <- TInt64;
( <:expr<spoc_div $(parse_int2 a TInt64)$ $(parse_int2 b TInt64)$>>)
| DivF32 (_loc, a,b) ->
( <:expr<spoc_div_float $(parse_float2 a TFloat32)$ $(parse_float2 b TFloat32)$>>)
| DivF64 (_loc, a,b) ->
( <:expr<spoc_div_float $(parse_float2 a TFloat64)$ $(parse_float2 b TFloat64)$>>)
| Mod (_loc, a,b) -> body.t <- TInt32;
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<spoc_mod $p1$ $p2$>>)
| Id (_loc,s) ->
let id =
(try
let var =
(Hashtbl.find !current_args (string_of_ident s))
in
if not r then
return_type := var.var_type;
(match var.var_type with
| TUnit -> <:expr< Unit>>
| _ ->
body.t <- var.var_type;
if var.is_global then
match var.var_type with
| TFloat32 ->
<:expr<global_float_var (fun () -> $ExId(_loc,s)$)>>
| TInt32 -> <:expr<global_int_var (fun () -> $ExId(_loc,s)$)>>
| _ -> my_eprintf __LOC__; assert false
else
<:expr<var $ExInt(_loc, string_of_int var.n)$ $str:string_of_ident s$>>
)
with _ ->
try
let c_const = (Hashtbl.find !intrinsics_const (string_of_ident s)) in
if body.t <> c_const.typ then
if body.t = TUnknown then
body.t <- c_const.typ
else
(my_eprintf __LOC__;
raise (TypeError (c_const.typ, body.t, _loc)));
<:expr<intrinsics $ExStr(_loc, c_const.cuda_val)$ $ExStr(_loc, c_const.opencl_val)$>>
with _ ->
(try
let intr =
Hashtbl.find !intrinsics_fun (string_of_ident s) in
<:expr< intrinsics $ExStr(_loc, intr.cuda_val)$ $ExStr(_loc, intr.opencl_val)$>>
with Not_found ->
try
ignore(Hashtbl.find !global_fun (string_of_ident s));
<:expr< global_fun $id:s$>>
with Not_found ->
try
ignore(Hashtbl.find !local_fun (string_of_ident s));
<:expr< global_fun $id:s$>>
with Not_found ->
try
let t = Hashtbl.find !constructors (string_of_ident s) in
<:expr< spoc_constr $str:t.name$ $str:(string_of_ident s)$ [] >>
with
| _ ->
(my_eprintf __LOC__;
raise (Unbound_value ((string_of_ident s), _loc))))) in
if r then
(return_type := body.t;
<:expr< spoc_return $id$ >>)
else id;
| Int (_loc, i) -> <:expr<spoc_int $ExInt(_loc, i)$>>
| Int32 (_loc, i) -> <:expr<spoc_int32 $ExInt32(_loc, i)$>>
| Int64 (_loc, i) -> <:expr<spoc_int64 $ExInt64(_loc, i)$>>
| Float (_loc, f) -> <:expr<spoc_float $ExFlo(_loc, f)$>>
| Float32 (_loc, f) -> <:expr<spoc_float $ExFlo(_loc, f)$>>
| Float64 (_loc, f) -> <:expr<spoc_double $ExFlo(_loc, f)$>>
| Seq (_loc, x, y) ->
(match y.e with
| Seq _ ->
let x = parse_body2 x false in
let y = parse_body2 y bool in
<:expr<seq $x$ $y$>>
| _ ->
let e1 = parse_body2 x false in
let e2 = aux (~return_bool:true) y
in <:expr<seq $e1$ $e2$>>
)
| End (_loc, x) ->
let res = <:expr< $aux x$>>
in
<:expr<$res$>>
| VecSet (_loc, vector, value) ->
let gen_value = aux value in
let gen_value =
match vector.t, value.e with
| TInt32, (Int32 _) -> <:expr<( $gen_value$)>>
| TInt64, (Int64 _) -> <:expr<( $gen_value$)>>
| TFloat32, (Float32 _) -> <:expr<( $gen_value$)>>
| TFloat64, (Float64 _) -> <:expr<( $gen_value$)>>
| _ -> gen_value
in
let v = aux (~return_bool:true) vector in
let e = <:expr<set_vect_var $v$ $gen_value$>> in
return_type := TUnit;
e
| VecGet(_loc, vector, index) ->
let e =
<:expr<get_vec $aux vector$ $parse_int2 index TInt32$>> in
(match vector.t with
| TVec ty->
();
| _ ->
my_eprintf __LOC__; assert (not debug));
e
| ArrSet (_loc, array, value) ->
let gen_value = aux value in
let gen_value =
match array.t, value.e with
| TInt32, (Int32 _) -> <:expr<( $gen_value$)>>
| TInt64, (Int64 _) -> <:expr<( $gen_value$)>>
| TFloat32, (Float32 _) -> <:expr<( $gen_value$)>>
| TFloat64, (Float64 _) -> <:expr<( $gen_value$)>>
| _ -> gen_value
in
let v = aux (~return_bool:true) array in
let e = <:expr<set_arr_var $v$ $gen_value$>> in
return_type := TUnit;
e
| ArrGet(_loc, array, index) ->
let e =
<:expr<get_arr $aux array$ $parse_int2 index TInt32$>> in
(match array.t with
| TArr ty->
();
| _ ->
my_eprintf __LOC__; assert (not debug));
e
| True _loc ->
if not r then
return_type := TBool;
<:expr<spoc_int32 $(ExInt32 (_loc, "1"))$>>
| False _loc ->
if not r then
return_type := TBool;
<:expr<spoc_int32 $(ExInt32 (_loc, "0"))$>>
| BoolNot(_loc, a) ->
if not r then
return_type := TBool;
<:expr< b_not $aux a$>>
| BoolOr(_loc, a, b) ->
if not r then
return_type := TBool;
<:expr< b_or $aux a$ $aux b$>>
| BoolAnd(_loc, a, b) ->
if not r then
return_type := TBool;
<:expr< b_and $aux a$ $aux b$>>
| BoolEq(_loc, a, b) ->
if not r then
return_type := TBool;
(match a.t with
| Custom (_,n) ->
<:expr< equals_custom $str:"spoc_custom_compare_"^n^"_sarek"$
$aux a$ $aux b$>>
| _ -> <:expr< equals32 $aux a$ $aux b$>>
)
| BoolEq32 (_loc, a, b) ->
if not r then
return_type := TBool;
<:expr< equals32 $aux a$ $aux b$>>
| BoolEq64(_loc, a, b) ->
<:expr< equals64 $aux a$ $aux b$>>
| BoolEqF32(_loc, a, b) ->
<:expr< equalsF $aux a$ $aux b$>>
| BoolEqF64(_loc, a, b) ->
<:expr< equalsF64 $aux a$ $aux b$>>
| BoolLt(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<lt $p1$ $p2$>>)
| BoolLt32(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<lt32 $p1$ $p2$>>)
| BoolLt64(_loc, a, b) ->
<:expr< lt64 $aux a$ $aux b$>>
| BoolLtF32(_loc, a, b) ->
<:expr< ltF $aux (~return_bool:false) a$ $aux (~return_bool:false) b$>>
| BoolLtF64(_loc, a, b) ->
<:expr< ltF64 $aux a$ $aux b$>>
| BoolGt(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<gt $p1$ $p2$>>)
| BoolGt32(_loc, a, b) ->
let p1 = (parse_int2 a TInt32)
and p2 = (parse_int2 b TInt32) in
if not r then
return_type := TInt32;
( <:expr<gt32 $p1$ $p2$>>)
| BoolGt64(_loc, a, b) ->
<:expr< gt64 $aux a$ $aux b$>>
| BoolGtF32(_loc, a, b) ->
<:expr< gtF $aux a$ $aux b$>>
| BoolGtF64(_loc, a, b) ->
<:expr< gtF64 $aux a$ $aux b$>>
| BoolLtE(_loc, a, b) ->
<:expr< lte $aux a$ $aux b$>>
| BoolLtE32(_loc, a, b) ->
<:expr< lte32 $aux a$ $aux b$>>
| BoolLtE64(_loc, a, b) ->
<:expr< lte64 $aux a$ $aux b$>>
| BoolLtEF32(_loc, a, b) ->
<:expr< lteF $aux a$ $aux b$>>
| BoolLtEF64(_loc, a, b) ->
<:expr< lteF64 $aux a$ $aux b$>>
| BoolGtE(_loc, a, b) ->
<:expr< gte $aux a$ $aux b$>>
| BoolGtE32(_loc, a, b) ->
<:expr< gte32 $aux a$ $aux b$>>
| BoolGtE64(_loc, a, b) ->
<:expr< gte64 $aux a$ $aux b$>>
| BoolGtEF32(_loc, a, b) ->
<:expr< gteF $aux a$ $aux b$>>
| BoolGtEF64(_loc, a, b) ->
<:expr< gteF64 $aux a$ $aux b$>>
| Ife (_loc, cond, cons1, cons2) ->
let p1 = aux (~return_bool:false) cond
and p2 = aux cons1
and p3 = aux cons2
in
if r then
return_type := cons2.t;
(<:expr< spoc_ife $p1$ $p2$ $p3$>>)
| If (_loc, cond, cons1) ->
let cons1_ = aux cons1 in
return_type := cons1.t;
(<:expr< spoc_if $aux cond$ $cons1_$>>)
| DoLoop (_loc, id, min, max, body) ->
(<:expr<spoc_do $aux id$ $aux min$ $aux max$ $aux body$>>)
| While (_loc, cond, body) ->
let cond = aux cond in
let body = aux body in
(<:expr<spoc_while $cond$ $body$>>)
| App (_loc, e1, e2) ->
let e = <:expr< $parse_app body$>> in
let rec app_return_type = function
| TApp (_,(TApp (a,b))) -> app_return_type b
| TApp (_,b) -> b
| a -> a
in
return_type := app_return_type body.t;
e
| Open (_loc, id, e) ->
let rec aux2 = function
| IdAcc (l,a,b) -> aux2 a; aux2 b
| IdUid (l,s) -> open_module s l
| _ -> my_eprintf __LOC__; assert (not debug)
in
aux2 id;
let ex = <:expr< $aux e$>> in
let rec aux2 = function
| IdAcc (l,a,b) -> aux2 a; aux2 b
| IdUid (l,s) -> close_module s
| _ -> assert (not debug)
in
aux2 id;
ex
| ModuleAccess (_loc, s, e) ->
open_module s _loc;
let ex = <:expr< $aux e$>> in
close_module s;
ex
| Noop ->
let _loc = body.loc in
<:expr< spoc_unit () >>
| Acc (_loc, e1, e2) ->
let e1 = parse_body2 e1 false
and e2 = parse_body2 e2 false
in
if not r then
return_type := TUnit;
<:expr< spoc_acc $e1$ $e2$>>
| Ref (_loc, {t=_; e=Id(_loc2, s);loc=_}) ->
let var =
Hashtbl.find !current_args (string_of_ident s) in
body.t <- var.var_type;
if not r then
return_type := body.t;
(match var.var_type with
| TFloat32 ->
<:expr<global_float_var (fun _ -> ! $ExId(_loc,s)$)>>
| TFloat64 ->
<:expr<global_float64_var (fun _ -> ! $ExId(_loc,s)$)>>
| TInt32 -> <:expr<global_int_var (fun _ -> ! $ExId(_loc,s)$)>>
| Custom _ -> <:expr<global_custom_var (fun _ -> ! $ExId(_loc,s)$)>>
| TBool -> <:expr<global_int_var (fun _ -> ! $ExId(_loc,s)$)>>
| _ -> assert false)
| Match(_loc,e,
((_,Constr (n,_),ec)::q as mc )) ->
let e = parse_body2 e false
and mc = parse_case2 mc _loc in
let name = (Hashtbl.find !constructors n).name in
if not r then
return_type := ec.t;
<:expr< spoc_match $str:name$ $e$ $mc$ >>
| Match _ -> assert false
| Record (_loc,fl) ->
begin
get from field list
let t,name =
let rec aux (acc:string list) (flds : field list) : string list =
match flds with
| (_loc,t,_)::q ->
let rec_fld : recrd_field =
try Hashtbl.find !rec_fields (string_of_ident t)
with
| _ ->
(assert (not debug);
raise (FieldError (string_of_ident t, List.hd acc, _loc)))
in
aux
(let rec aux2 (res:string list) (acc_:string list) (flds_:string list) =
match acc_,flds_ with
| (t1::q1),(t2::q2) ->
if t1 = t2 then
aux2 (t1::acc_) acc q2
else
aux2 (t1::acc_) q1 (t2::q2)
| _,[] -> res
| [],q ->
aux2 res acc q
in aux2 [] acc rec_fld.ctyps) q
| [] -> acc
in
let start : string list =
let (_loc,t,_) = (List.hd fl) in
try
(Hashtbl.find !rec_fields (string_of_ident t)).ctyps
with
| _ ->
(assert (not debug);
raise (FieldError (string_of_ident t, "\"\"", _loc)))
in
let r : string list =
aux start fl
in ktyp_of_typ (TyId(_loc,IdLid(_loc,List.hd r))),(List.hd r)
in
let res =
(match t with
| Custom (KRecord (l1,l2,_),n) ->
let fl = List.map
(fun x -> List.find (fun (_,y,_) ->
(string_of_ident y) = (string_of_ident x)) fl) l2 in
let r = List.map
(fun (_,_,b) -> <:expr< $parse_body2 b false$>>)
fl
in <:expr< spoc_record $str:name$ [$Ast.exSem_of_list r$] >>
| _ -> assert false)
in
if not r then
return_type := body.t;
res;
end
| RecGet (_loc,r,fld) -> <:expr< spoc_rec_get $parse_body2 r false$ $str:string_of_ident fld$>>
| RecSet (_loc,e1,e2) -> <:expr< spoc_rec_set $parse_body2 e1 false$ $parse_body2 e2 false$>>
| TypeConstraint (_loc, e, tt) ->
if not r then return_type := tt;
parse_body2 e false
| Nat (_loc, code) -> <:expr< spoc_native $code$ >>
| Fun (_loc,stri,tt,funv,lifted) -> <:expr< global_fun $stri$ >>
| Pragma (_loc, lopt, expr) ->
let lopt = List.map
(fun opt -> <:expr< $str:opt$>>) lopt in
<:expr< pragma [$exSem_of_list lopt$] $parse_body2 expr false$ >>
| _ -> (
my_eprintf __LOC__;
failwith ((k_expr_to_string body.e)^": not implemented yet");)
in
let _loc = body.loc in
if bool then
(
my_eprintf (Printf.sprintf"(* val2 return %s *)\n%!" (k_expr_to_string body.e));
match body.e with
| Bind (_loc, var,y, z, is_mutable) ->
(
(match var.e with
| Id (_loc, s) ->
(match y.e with
| Fun _ -> <:expr< spoc_return $aux z$>>
| _ ->
(let gen_var = (
try Hashtbl.find !current_args (string_of_ident s)
with _ -> assert false) in
let ex1,ex2 =
match var.t with
| TInt32 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$) >>, (aux y)
| TInt64 -> <:expr<(new_int_var $`int:gen_var.n$ $str:string_of_ident s$)>>, (aux y)
| TFloat32 -> <:expr<(new_float_var $`int:gen_var.n$$str:string_of_ident s$)>>,(aux y)
| TFloat64 -> <:expr<(new_double_var $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| TUnit -> <:expr<Unit>>,aux y;
| Custom (t,n) ->
<:expr<(new_custom_var $str:n$ $`int:gen_var.n$ $str:string_of_ident s$)>>,(aux y)
| _ -> assert (not debug);
failwith "unknown var type"
in
arg_list := <:expr<(spoc_declare $ex1$)>>:: !arg_list);
(let var_ = parse_body2 var false in
let y = aux y in
let z = aux (~return_bool:true) z in
let res =
match var.t with
TArr _ -> <:expr< $z$>>
| _ -> <:expr< seq (spoc_set $var_$ $y$) $z$>>
in
remove_int_var var;
res))
| _ -> failwith "this binding is not a binding"))
| Seq (a,b,c) ->
<:expr<spoc_return $aux body$>>
| _ ->
let e = {t=body.t; e =End(_loc, body); loc = _loc} in
match body.t with
| TUnit ->
let res = aux e in
return_type := TUnit;
<:expr< $res$ >>
|_ ->
<:expr<spoc_return $aux e$>>
)
else
aux body
|
b03133f9641d211c3c41886e1a0b6ea4d9ed905be463efcf5d35b64cad33a8aa | wireapp/wire-server | CSV.hs | -- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Wire.API.Routes.CSV where
import Network.HTTP.Media.MediaType
import Servant.API
data CSV
instance Accept CSV where
contentType _ = "text" // "csv"
| null | https://raw.githubusercontent.com/wireapp/wire-server/e36c3562f886525e30d6ac9f16feda1a054a247f/libs/wire-api/src/Wire/API/Routes/CSV.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>. | Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Wire.API.Routes.CSV where
import Network.HTTP.Media.MediaType
import Servant.API
data CSV
instance Accept CSV where
contentType _ = "text" // "csv"
|
61203712e18cf2c1dbacc496a94281d5f4cbd9f92e23c8efb62394848a8138ea | pupeno/ninjatools | pages.cljs | Copyright © 2015 Carousel Apps , Ltd. All rights reserved .
(ns ninjatools.pages
(:require [re-frame.core :as re-frame]
[ajax.core :as ajax]
[ninjatools.layout :as layout]
[ninjatools.util :as util]))
(defmethod layout/pages :about [_]
(fn [_]
[:div "This is the About Page."]))
(re-frame/register-handler
:fail
(fn [db [_]]
(ajax/GET "/api/v1/fail" {:error-handler util/report-unexpected-error})
db))
(defmethod layout/pages :fail [_]
(fn [_]
[:div
[:h1 "Page to test error reporting"]
[:p [:a.btn.btn-default {:on-click #(throw (js/Error "Bogus error to test exception handling on the client"))} "Client Fail!"]]
[:p [:a.btn.btn-default {:href "/server-fail"} "Non-API Server Fail!"]]
[:p [:a.btn.btn-default {:on-click #(re-frame/dispatch [:fail])} "API Server Fail!"]]]))
| null | https://raw.githubusercontent.com/pupeno/ninjatools/1b73ff22174b5ec196d514062162b252899c1735/src/cljs/ninjatools/pages.cljs | clojure | Copyright © 2015 Carousel Apps , Ltd. All rights reserved .
(ns ninjatools.pages
(:require [re-frame.core :as re-frame]
[ajax.core :as ajax]
[ninjatools.layout :as layout]
[ninjatools.util :as util]))
(defmethod layout/pages :about [_]
(fn [_]
[:div "This is the About Page."]))
(re-frame/register-handler
:fail
(fn [db [_]]
(ajax/GET "/api/v1/fail" {:error-handler util/report-unexpected-error})
db))
(defmethod layout/pages :fail [_]
(fn [_]
[:div
[:h1 "Page to test error reporting"]
[:p [:a.btn.btn-default {:on-click #(throw (js/Error "Bogus error to test exception handling on the client"))} "Client Fail!"]]
[:p [:a.btn.btn-default {:href "/server-fail"} "Non-API Server Fail!"]]
[:p [:a.btn.btn-default {:on-click #(re-frame/dispatch [:fail])} "API Server Fail!"]]]))
| |
884f305072d605ecdfa39d1125fd4a1acb5994041f48b6a1e1a6a228ccca81b5 | Bogdanp/nemea | batcher.rkt | #lang racket/base
(require component
db
db/util/postgresql
gregor
gregor/period
koyo/database
racket/async-channel
racket/contract/base
racket/function
racket/match
racket/set
retry
threading
(prefix-in config: "../config.rkt")
"geolocator.rkt"
"page-visit.rkt")
(provide
(contract-out
[struct batcher ([database database?]
[geolocator geolocator?]
[events async-channel?]
[timeout exact-positive-integer?]
[listener-thread (or/c false/c thread?)])]
[make-batcher (->* ()
(#:channel-size exact-positive-integer?
#:timeout exact-positive-integer?)
(-> database? geolocator? batcher?))]
[enqueue (-> batcher? page-visit? void?)]))
(define-logger batcher)
(struct batcher (database geolocator events timeout listener-thread)
#:property prop:evt (struct-field-index listener-thread)
#:methods gen:component
[(define (component-start a-batcher)
(log-batcher-debug "starting batcher")
(struct-copy batcher a-batcher
[listener-thread (thread (make-listener a-batcher))]))
(define (component-stop a-batcher)
(log-batcher-debug "stopping batcher")
(!> a-batcher 'stop)
(thread-wait (batcher-listener-thread a-batcher))
(struct-copy batcher a-batcher
[listener-thread #f]))])
(define ((make-batcher #:channel-size [channel-size 500]
#:timeout [timeout 60]) database geolocator)
(batcher database geolocator (make-async-channel channel-size) timeout #f))
(define (!> batcher event)
(async-channel-put (batcher-events batcher) event))
(define (enqueue batcher page-visit)
(define date (today #:tz config:timezone))
(async-channel-put (batcher-events batcher) (list date page-visit)))
(define (log-exn-retryer)
(retryer #:handle (lambda (r n)
(log-batcher-error "retrying error:\n~a\nattempt: ~a" (exn-message r) n))))
(define upsert-retryer
(retryer-compose (cycle-retryer (sleep-exponential-retryer (seconds 1)) 8)
(sleep-const-retryer/random (seconds 5))
(log-exn-retryer)))
(define ((make-listener batcher))
(define timeout (* (batcher-timeout batcher) 1000))
(define geolocator (batcher-geolocator batcher))
(define events (batcher-events batcher))
(define init (list (set) (set) 0))
(let loop ([batch (hash)])
(sync
(choice-evt
(handle-evt
events
(lambda (event)
(match event
['stop
(log-batcher-debug "received 'stop")
(call/retry upsert-retryer (lambda () (upsert-batch! batcher batch)))
(void)]
['timeout
(log-batcher-debug "received 'timeout")
(call/retry upsert-retryer (lambda () (upsert-batch! batcher batch)))
(loop (hash))]
[(list d pv)
(define k (grouping d
(url->canonical-host (page-visit-location pv))
(url->canonical-path (page-visit-location pv))
(and~> (page-visit-referrer pv) (url->canonical-host))
(and~> (page-visit-referrer pv) (url->canonical-path))
(and~>> (page-visit-client-ip pv) (geolocator-country-code geolocator))))
(loop (hash-update batch k (curry aggregate pv) init))])))
(handle-evt
(alarm-evt (+ (current-inexact-milliseconds) timeout))
(lambda (e)
(async-channel-put events 'timeout)
(loop batch)))))))
(define/match (aggregate pv agg)
[(_ (list visitors sessions visits))
(list (set-add visitors (page-visit-unique-id pv))
(set-add sessions (page-visit-session-id pv))
(add1 visits))])
(define (upsert-batch! batcher batch)
(with-database-transaction [conn (batcher-database batcher)]
(for ([(grouping agg) (in-hash batch)])
(match-define (list visitors sessions visits) agg)
(query-exec conn UPSERT-BATCH-QUERY
(->sql-date (grouping-date grouping))
(grouping-host grouping)
(grouping-path grouping)
(or (grouping-referrer-host grouping) "")
(or (grouping-referrer-path grouping) "")
(or (grouping-country-code grouping) "ZZ")
visits
(list->pg-array (set->list visitors))
(list->pg-array (set->list sessions))))))
(define UPSERT-BATCH-QUERY
#<<SQL
with
visitors_agg as (select hll_add_agg(hll_hash_text(s.x)) as visitors from (select unnest($8::text[]) as x) as s),
sessions_agg as (select hll_add_agg(hll_hash_text(s.x)) as sessions from (select unnest($9::text[]) as x) as s)
insert into page_visits(date, host, path, referrer_host, referrer_path, country_code, visits, visitors, sessions)
values($1, $2, $3, $4, $5, $6, $7, (select visitors from visitors_agg), (select sessions from sessions_agg))
on conflict on constraint page_visits_partition
do update
set
visits = page_visits.visits + $7,
visitors = page_visits.visitors || (select visitors from visitors_agg),
sessions = page_visits.sessions || (select sessions from sessions_agg)
where
page_visits.date = $1 and
page_visits.host = $2 and
page_visits.path = $3 and
page_visits.referrer_host = $4 and
page_visits.referrer_path = $5 and
page_visits.country_code = $6
SQL
)
(struct grouping (date host path referrer-host referrer-path country-code)
#:transparent)
(module+ test
(require net/url
rackunit
rackunit/text-ui
"migrator.rkt")
(define-system test
[database (make-database-factory
(lambda _
(postgresql-connect
#:database "nemea_tests"
#:user "nemea"
#:password "nemea")))]
[batcher (database geolocator) (make-batcher)]
[geolocator make-geolocator]
[migrator (database) make-migrator])
(run-tests
(test-suite
"Batcher"
#:before
(lambda ()
(system-start test-system)
(with-database-connection [conn (system-get test-system 'database)]
(query-exec conn "truncate page_visits")))
#:after
(lambda ()
(system-stop test-system))
(test-case "upserts visits"
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(enqueue (system-get test-system 'batcher) (page-visit "a" "c" (string->url "") #f #f))
(!> (system-get test-system 'batcher) 'timeout)
(sync (system-idle-evt))
(check-equal?
(with-database-connection [conn (system-get test-system 'database)]
(query-row conn "select visits, hll_cardinality(visitors), hll_cardinality(sessions) from page_visits order by date desc limit 1"))
#(2 1.0 2.0))
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(!> (system-get test-system 'batcher) 'stop)
(sync (system-get test-system 'batcher))
(check-eq?
(with-database-connection [conn (system-get test-system 'database)]
(query-value conn "select visits from page_visits where path = '/a' order by date desc limit 1"))
4)
(check-eq?
(with-database-connection [conn (system-get test-system 'database)]
(query-value conn "select visits from page_visits where path = '/b' order by date desc limit 1"))
1)))))
| null | https://raw.githubusercontent.com/Bogdanp/nemea/6e6149007fb0c43d8f0fb2271b36f0ccad830703/nemea/components/batcher.rkt | racket | #lang racket/base
(require component
db
db/util/postgresql
gregor
gregor/period
koyo/database
racket/async-channel
racket/contract/base
racket/function
racket/match
racket/set
retry
threading
(prefix-in config: "../config.rkt")
"geolocator.rkt"
"page-visit.rkt")
(provide
(contract-out
[struct batcher ([database database?]
[geolocator geolocator?]
[events async-channel?]
[timeout exact-positive-integer?]
[listener-thread (or/c false/c thread?)])]
[make-batcher (->* ()
(#:channel-size exact-positive-integer?
#:timeout exact-positive-integer?)
(-> database? geolocator? batcher?))]
[enqueue (-> batcher? page-visit? void?)]))
(define-logger batcher)
(struct batcher (database geolocator events timeout listener-thread)
#:property prop:evt (struct-field-index listener-thread)
#:methods gen:component
[(define (component-start a-batcher)
(log-batcher-debug "starting batcher")
(struct-copy batcher a-batcher
[listener-thread (thread (make-listener a-batcher))]))
(define (component-stop a-batcher)
(log-batcher-debug "stopping batcher")
(!> a-batcher 'stop)
(thread-wait (batcher-listener-thread a-batcher))
(struct-copy batcher a-batcher
[listener-thread #f]))])
(define ((make-batcher #:channel-size [channel-size 500]
#:timeout [timeout 60]) database geolocator)
(batcher database geolocator (make-async-channel channel-size) timeout #f))
(define (!> batcher event)
(async-channel-put (batcher-events batcher) event))
(define (enqueue batcher page-visit)
(define date (today #:tz config:timezone))
(async-channel-put (batcher-events batcher) (list date page-visit)))
(define (log-exn-retryer)
(retryer #:handle (lambda (r n)
(log-batcher-error "retrying error:\n~a\nattempt: ~a" (exn-message r) n))))
(define upsert-retryer
(retryer-compose (cycle-retryer (sleep-exponential-retryer (seconds 1)) 8)
(sleep-const-retryer/random (seconds 5))
(log-exn-retryer)))
(define ((make-listener batcher))
(define timeout (* (batcher-timeout batcher) 1000))
(define geolocator (batcher-geolocator batcher))
(define events (batcher-events batcher))
(define init (list (set) (set) 0))
(let loop ([batch (hash)])
(sync
(choice-evt
(handle-evt
events
(lambda (event)
(match event
['stop
(log-batcher-debug "received 'stop")
(call/retry upsert-retryer (lambda () (upsert-batch! batcher batch)))
(void)]
['timeout
(log-batcher-debug "received 'timeout")
(call/retry upsert-retryer (lambda () (upsert-batch! batcher batch)))
(loop (hash))]
[(list d pv)
(define k (grouping d
(url->canonical-host (page-visit-location pv))
(url->canonical-path (page-visit-location pv))
(and~> (page-visit-referrer pv) (url->canonical-host))
(and~> (page-visit-referrer pv) (url->canonical-path))
(and~>> (page-visit-client-ip pv) (geolocator-country-code geolocator))))
(loop (hash-update batch k (curry aggregate pv) init))])))
(handle-evt
(alarm-evt (+ (current-inexact-milliseconds) timeout))
(lambda (e)
(async-channel-put events 'timeout)
(loop batch)))))))
(define/match (aggregate pv agg)
[(_ (list visitors sessions visits))
(list (set-add visitors (page-visit-unique-id pv))
(set-add sessions (page-visit-session-id pv))
(add1 visits))])
(define (upsert-batch! batcher batch)
(with-database-transaction [conn (batcher-database batcher)]
(for ([(grouping agg) (in-hash batch)])
(match-define (list visitors sessions visits) agg)
(query-exec conn UPSERT-BATCH-QUERY
(->sql-date (grouping-date grouping))
(grouping-host grouping)
(grouping-path grouping)
(or (grouping-referrer-host grouping) "")
(or (grouping-referrer-path grouping) "")
(or (grouping-country-code grouping) "ZZ")
visits
(list->pg-array (set->list visitors))
(list->pg-array (set->list sessions))))))
(define UPSERT-BATCH-QUERY
#<<SQL
with
visitors_agg as (select hll_add_agg(hll_hash_text(s.x)) as visitors from (select unnest($8::text[]) as x) as s),
sessions_agg as (select hll_add_agg(hll_hash_text(s.x)) as sessions from (select unnest($9::text[]) as x) as s)
insert into page_visits(date, host, path, referrer_host, referrer_path, country_code, visits, visitors, sessions)
values($1, $2, $3, $4, $5, $6, $7, (select visitors from visitors_agg), (select sessions from sessions_agg))
on conflict on constraint page_visits_partition
do update
set
visits = page_visits.visits + $7,
visitors = page_visits.visitors || (select visitors from visitors_agg),
sessions = page_visits.sessions || (select sessions from sessions_agg)
where
page_visits.date = $1 and
page_visits.host = $2 and
page_visits.path = $3 and
page_visits.referrer_host = $4 and
page_visits.referrer_path = $5 and
page_visits.country_code = $6
SQL
)
(struct grouping (date host path referrer-host referrer-path country-code)
#:transparent)
(module+ test
(require net/url
rackunit
rackunit/text-ui
"migrator.rkt")
(define-system test
[database (make-database-factory
(lambda _
(postgresql-connect
#:database "nemea_tests"
#:user "nemea"
#:password "nemea")))]
[batcher (database geolocator) (make-batcher)]
[geolocator make-geolocator]
[migrator (database) make-migrator])
(run-tests
(test-suite
"Batcher"
#:before
(lambda ()
(system-start test-system)
(with-database-connection [conn (system-get test-system 'database)]
(query-exec conn "truncate page_visits")))
#:after
(lambda ()
(system-stop test-system))
(test-case "upserts visits"
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(enqueue (system-get test-system 'batcher) (page-visit "a" "c" (string->url "") #f #f))
(!> (system-get test-system 'batcher) 'timeout)
(sync (system-idle-evt))
(check-equal?
(with-database-connection [conn (system-get test-system 'database)]
(query-row conn "select visits, hll_cardinality(visitors), hll_cardinality(sessions) from page_visits order by date desc limit 1"))
#(2 1.0 2.0))
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(enqueue (system-get test-system 'batcher) (page-visit "a" "b" (string->url "") #f #f))
(!> (system-get test-system 'batcher) 'stop)
(sync (system-get test-system 'batcher))
(check-eq?
(with-database-connection [conn (system-get test-system 'database)]
(query-value conn "select visits from page_visits where path = '/a' order by date desc limit 1"))
4)
(check-eq?
(with-database-connection [conn (system-get test-system 'database)]
(query-value conn "select visits from page_visits where path = '/b' order by date desc limit 1"))
1)))))
| |
1cd75077fe47a0b8815a5dc27b9c2e79adc0bc85c9328b1441771055b6ef3038 | AdaCore/why3 | bdd.ml | (**************************************************************************)
(* *)
Copyright ( C )
(* *)
(* This software is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public *)
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(**************************************************************************)
(* Binary Decision Diagrams *)
type variable = int (* 1..max_var *)
module BddVarMap =
Map.Make(struct
type t = variable
let compare (x:variable) (y:variable) = compare x y
end)
type formula =
| Ffalse
| Ftrue
| Fvar of variable
| Fand of formula * formula
| For of formula * formula
| Fimp of formula * formula
| Fiff of formula * formula
| Fnot of formula
if then f2 else f3
module type BDD = sig
val get_max_var : unit -> int
type t
type view = Zero | One | Node of variable * t * t
val view : t -> view
val var : t -> variable
val low : t -> t
val high : t -> t
val zero : t
val one : t
val make : variable -> low:t -> high:t -> t
val mk_var : variable -> t
val mk_not : t -> t
val mk_and : t -> t -> t
val mk_or : t -> t -> t
val mk_imp : t -> t -> t
val mk_iff : t -> t -> t
val mk_exist : (variable -> bool) -> t -> t
val mk_forall : (variable -> bool) -> t -> t
val extract_known_values : t -> bool BddVarMap.t
val apply : (bool -> bool -> bool) -> t -> t -> t
val constrain : t -> t -> t
val restriction : t -> t -> t
val restrict : t -> variable -> bool -> t
val build : formula -> t
val as_formula : t -> formula
val as_compact_formula : t -> formula
val is_sat : t -> bool
val tautology : t -> bool
val equivalent : t -> t -> bool
val entails : t -> t -> bool
val count_sat_int : t -> int
val count_sat : t -> Int64.t
val any_sat : t -> (variable * bool) list
val random_sat : t -> (variable * bool) list
val all_sat : t -> (variable * bool) list list
val print_var : Format.formatter -> variable -> unit
val print : Format.formatter -> t -> unit
val print_compact : Format.formatter -> t -> unit
val to_dot : t -> string
val print_to_dot : t -> file:string -> unit
val display : t -> unit
val stats : unit -> (int * int * int * int * int * int) array
end
let debug = false
(* Make a fresh module *)
module Make(X: sig
val print_var: Format.formatter -> int -> unit
val size: int
val max_var: int
end) = struct
open X
let rec power_2_above x n =
if x >= n then x
else if x * 2 > Sys.max_array_length then x
else power_2_above (x * 2) n
let size = power_2_above 16 size
let print_var = print_var
let get_max_var () = max_var
type bdd = { tag: int; node : view }
and view = Zero | One | Node of variable * bdd (*low*) * bdd (*high*)
type t = bdd (* export *)
let view b = b.node
let rec print fmt b =
match b.node with
| Zero -> Format.fprintf fmt "false"
| One -> Format.fprintf fmt "true"
| Node(v,l,h) ->
Format.fprintf fmt "@[<hv 2>if %a@ then %a@ else %a@]" print_var v print h print l
let rec print_compact fmt b =
match b.node with
| Zero -> Format.fprintf fmt "false"
| One -> Format.fprintf fmt "true"
| Node(v,{node=Zero;_},{node=One;_}) ->
if v then 1 else 0 -- > v
Format.fprintf fmt "%a" print_var v
| Node(v,{node=One;_},{node=Zero;_}) ->
if v then 0 else 1 -- > ! v
Format.fprintf fmt "!%a" print_var v
| Node(v,{node=Zero;_},h) ->
(* if v then h else 0 --> v /\ h *)
Format.fprintf fmt "@[%a /\\@ %a@]" print_var v print_compact h
| Node(v,{node=One;_},h) ->
if v then h else 1 -- > ! v \/ h
Format.fprintf fmt "@[!%a \\/@ %a@]" print_var v print_compact h
| Node(v,l,{node=Zero;_}) ->
(* if v then 0 else l --> !v /\ l *)
Format.fprintf fmt "@[!%a /\\@ %a@]" print_var v print_compact l
| Node(v,l,{node=One;_}) ->
if v then 1 else l -- > v \/ l
Format.fprintf fmt "@[%a \\/@ %a@]" print_var v print_compact l
| Node(v,l,h) ->
Format.fprintf fmt "@[<hv 2>if %a@ then %a@ else %a@]" print_var v print_compact h print_compact l
unused
let equal x y = match x , y with
| Node ( v1 , l1 , h1 ) , ( v2 , l2 , h2 ) - >
v1 = = v2 & & l1 = = l2 & & h1 = = h2
| _ - >
x = = y
let equal x y = match x, y with
| Node (v1, l1, h1), Node (v2, l2, h2) ->
v1 == v2 && l1 == l2 && h1 == h2
| _ ->
x == y
*)
* perfect hashing is actually less efficient
let pair a b = ( a + b ) * ( a + b + 1 ) / 2 + a
let triple a b c = pair c ( pair a b )
let hash_node v l h = abs ( triple l.tag h.tag v )
*
let pair a b = (a + b) * (a + b + 1) / 2 + a
let triple a b c = pair c (pair a b)
let hash_node v l h = abs (triple l.tag h.tag v)
**)
let hash_node l h = 19 * l.tag + h.tag
let hash = function
| Zero -> 0
| One -> 1
| Node (_, l, h) -> hash_node l h
let gentag = let r = ref (-1) in fun () -> incr r; !r
type table = {
mutable table : bdd Weak.t array;
mutable totsize : int; (* sum of the bucket sizes *)
mutable limit : int; (* max ratio totsize/table length *)
}
let create sz =
let emptybucket = Weak.create 0 in
{ table = Array.make sz emptybucket;
totsize = 0;
limit = 3; }
let vt = Array.init max_var (fun _ -> create size)
let fold f t init =
let rec fold_bucket i b accu =
if i >= Weak.length b then accu else
match Weak.get b i with
| Some v -> fold_bucket (i+1) b (f v accu)
| None -> fold_bucket (i+1) b accu
in
Array.fold_right (fold_bucket 0) t.table init
(* unused
let iter f t =
let rec iter_bucket i b =
if i >= Weak.length b then () else
match Weak.get b i with
| Some v -> f v; iter_bucket (i+1) b
| None -> iter_bucket (i+1) b
in
Array.iter (iter_bucket 0) t.table
*)
let count t =
let rec count_bucket i b accu =
if i >= Weak.length b then accu else
count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0))
in
Array.fold_right (count_bucket 0) t.table 0
let rec resize t =
if debug then Format.eprintf "resizing...@.";
let oldlen = Array.length t.table in
let newlen = oldlen * 2 in
if newlen > oldlen then begin
let newt = create newlen in
newt.limit <- t.limit + 100; (* prevent resizing of newt *)
fold (fun d () -> add newt d) t ();
t.table <- newt.table;
t.limit <- t.limit + 2;
end
and add t d =
add_index t d ((hash d.node) land (Array.length t.table - 1))
and add_index t d index =
let bucket = t.table.(index) in
let sz = Weak.length bucket in
let rec loop i =
if i >= sz then begin
let newsz = min (sz + 3) (Sys.max_array_length - 1) in
if newsz <= sz then
failwith "Hashcons.Make: hash bucket cannot grow more";
let newbucket = Weak.create newsz in
Weak.blit bucket 0 newbucket 0 sz;
Weak.set newbucket i (Some d);
t.table.(index) <- newbucket;
t.totsize <- t.totsize + (newsz - sz);
if t.totsize > t.limit * Array.length t.table then resize t;
end else begin
if Weak.check bucket i
then loop (i+1)
else Weak.set bucket i (Some d)
end
in
loop 0
let hashcons_node v l h =
let t = vt.(v - 1) in
let index = (hash_node l h) mod (Array.length t.table) in
let bucket = t.table.(index) in
let sz = Weak.length bucket in
let rec loop i =
if i >= sz then begin
let hnode = { tag = gentag (); node = Node (v, l, h) } in
add_index t hnode index;
hnode
end else begin
match Weak.get_copy bucket i with
| Some {node=Node(v',l',h'); _} when v==v' && l==l' && h==h' ->
begin match Weak.get bucket i with
| Some v -> v
| None -> loop (i+1)
end
| _ -> loop (i+1)
end
in
loop 0
let stat t =
let len = Array.length t.table in
let lens = Array.map Weak.length t.table in
Array.sort compare lens;
let totlen = Array.fold_left ( + ) 0 lens in
(len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1))
let stats () = Array.map stat vt
zero and one allocated once and for all
let zero = { tag = gentag (); node = Zero }
let one = { tag = gentag (); node = One }
let var b = match b.node with
| Zero | One -> max_var + 1
| Node (v, _, _) -> v
let low b = match b.node with
| Zero | One -> invalid_arg "Bdd.low"
| Node (_, l, _) -> l
let high b = match b.node with
| Zero | One -> invalid_arg "Bdd.low"
| Node (_, _, h) -> h
let mk v ~low ~high =
if low == high then low else hashcons_node v low high
let make v ~low ~high =
if v < 1 || v > max_var then invalid_arg "Bdd.make";
mk v ~low ~high
let mk_var v =
if v < 1 || v > max_var then invalid_arg "Bdd.mk_var";
mk v ~low:zero ~high:one
module Bdd = struct
type t = bdd
let equal = (==)
let hash b = b.tag
let compare b1 b2 = Stdlib.compare b1.tag b2.tag
end
module H1 = Hashtbl.Make(Bdd)
let cache_default_size = 7001
let mk_not x =
let cache = H1.create cache_default_size in
let rec mk_not_rec x =
try
H1.find cache x
with Not_found ->
let res = match x.node with
| Zero -> one
| One -> zero
| Node (v, l, h) -> mk v ~low:(mk_not_rec l) ~high:(mk_not_rec h)
in
H1.add cache x res;
res
in
mk_not_rec x
unused
let bool_of = function Zero - > false | One - > true | _ - > invalid_arg " bool_of "
let bool_of = function Zero -> false | One -> true | _ -> invalid_arg "bool_of"*)
let of_bool b = if b then one else zero
module H2 = Hashtbl.Make(
struct
type t = bdd * bdd
let equal (u1,v1) (u2,v2) = u1==u2 && v1==v2
let hash (u,v) =
abs ( 19 * u.tag + v.tag )
let s = u.tag + v.tag in abs (s * (s+1) / 2 + u.tag)
end)
type operator =
| Op_and | Op_or | Op_imp
| Op_any of (bool -> bool -> bool)
let apply_op op b1 b2 = match op with
| Op_and -> b1 && b2
| Op_or -> b1 || b2
| Op_imp -> (not b1) || b2
| Op_any f -> f b1 b2
let gapply op =
let op_z_z = of_bool (apply_op op false false) in
let op_z_o = of_bool (apply_op op false true) in
let op_o_z = of_bool (apply_op op true false) in
let op_o_o = of_bool (apply_op op true true) in
fun b1 b2 ->
let cache = H2.create cache_default_size in
let rec app ((u1,u2) as u12) =
match op with
| Op_and ->
if u1 == u2 then
u1
else if u1 == zero || u2 == zero then
zero
else if u1 == one then
u2
else if u2 == one then
u1
else
app_gen u12
| Op_or ->
if u1 == u2 then
u1
else if u1 == one || u2 == one then
one
else if u1 == zero then
u2
else if u2 == zero then
u1
else
app_gen u12
| Op_imp ->
if u1 == zero then
one
else if u1 == one then
u2
else if u2 == one then
one
else
app_gen u12
| Op_any _ ->
app_gen u12
and app_gen ((u1,u2) as u12) =
match u1.node, u2.node with
| Zero, Zero -> op_z_z
| Zero, One -> op_z_o
| One, Zero -> op_o_z
| One, One -> op_o_o
| _ ->
try
H2.find cache u12
with Not_found ->
let res =
let v1 = var u1 in
let v2 = var u2 in
if v1 == v2 then
mk v1 ~low:(app (low u1, low u2)) ~high:(app (high u1, high u2))
else if v1 < v2 then
mk v1 ~low:(app (low u1, u2)) ~high:(app (high u1, u2))
else (* v1 > v2 *)
mk v2 ~low:(app (u1, low u2)) ~high:(app (u1, high u2))
in
H2.add cache u12 res;
res
in
app (b1, b2)
let mk_and = gapply Op_and
let mk_or = gapply Op_or
let mk_imp = gapply Op_imp
let mk_iff = gapply (Op_any (fun b1 b2 -> b1 == b2))
let mk_ite f1 f2 f3 =
mk_and (mk_imp f1 f2) (mk_imp (mk_not f1) f3)
* { 2 quantifier elimination }
let rec quantifier_elim cache op filter b =
try
H1.find cache b
with Not_found ->
let res = match b.node with
| Zero | One -> b
| Node(v,l,h) ->
let low = quantifier_elim cache op filter l in
let high = quantifier_elim cache op filter h in
if filter v then
op low high
else
mk v ~low ~high
in
H1.add cache b res;
res
let mk_exist filter b =
let cache = H1.create cache_default_size in
quantifier_elim cache mk_or filter b
let mk_forall filter b =
let cache = H1.create cache_default_size in
quantifier_elim cache mk_and filter b
let rec extract_known_values cache b =
try
H1.find cache b
with Not_found ->
let res = match b.node with
| Zero | One -> BddVarMap.empty
| Node(v,{node=Zero;_},h) ->
(* if v then h else 0 --> v /\ h *)
BddVarMap.add v true (extract_known_values cache h)
| Node(v,l,{node=Zero;_}) ->
(* if v then 0 else l --> !v /\ l *)
BddVarMap.add v false (extract_known_values cache l)
| Node(_,l,h) ->
let m1 = extract_known_values cache l in
let m2 = extract_known_values cache h in
let merge_bool _ b1 b2 =
match b1, b2 with
| Some b1, Some b2 when b1=b2 -> Some b1
| _ -> None
in
BddVarMap.merge merge_bool m1 m2
in
H1.add cache b res;
res
let extract_known_values b =
let cache = H1.create cache_default_size in
extract_known_values cache b
let apply f = gapply (Op_any f)
let constrain b1 b2 =
let cache = H2.create cache_default_size in
let rec app ((u1,u2) as u12) =
match u1.node, u2.node with
| _, Zero -> failwith "constrain 0 is undefined"
| _, One -> u1
| Zero, _ -> u1
| One, _ -> u1
| _ ->
try
H2.find cache u12
with Not_found ->
let res =
let v1 = var u1 in
let v2 = var u2 in
if v1 == v2 then begin
if low u2 == zero then app (high u1, high u2)
else if high u2 == zero then app (low u1, low u2)
else mk (var u1) ~low:(app (low u1, low u2)) ~high:(app (high u1, high u2))
end
else if v1 < v2 then
mk v1 ~low:(app (low u1, u2)) ~high:(app (high u1, u2))
else (* v1 > v2 *)
mk v2 ~low:(app (u1, low u2)) ~high:(app (u1, high u2))
in
H2.add cache u12 res;
res
in
app (b1, b2)
let restriction b1 b2 =
let cache = H2.create cache_default_size in
let rec app ((u1,u2) as u12) =
match u1.node, u2.node with
| _, Zero -> failwith "constrain 0 is undefined"
| _, One -> u1
| Zero, _ -> u1
| One, _ -> u1
| _ ->
try
H2.find cache u12
with Not_found ->
let res =
let v1 = var u1 in
let v2 = var u2 in
if v1 == v2 then begin
if low u2 == zero then app (high u1, high u2)
else if high u2 == zero then app (low u1, low u2)
else mk (var u1) ~low:(app (low u1, low u2)) ~high:(app (high u1, high u2))
end
else if v1 < v2 then
mk v1 ~low:(app (low u1, u2)) ~high:(app (high u1, u2))
else (* v1 > v2 *)
app (u1, mk_or (low u2) (high u2))
in
H2.add cache u12 res;
res
in
app (b1, b2)
let restrict u x b =
let cache = H1.create cache_default_size in
let rec app u =
try
H1.find cache u
with Not_found ->
let res =
if var u > x then u
else if var u < x then mk (var u) ~low:(app (low u)) ~high:(app (high u))
else (* var u = x *) if b then app (high u)
var u = x , b = 0
in
H1.add cache u res;
res
in
app u
formula - > bdd
let rec build = function
| Ffalse -> zero
| Ftrue -> one
| Fvar v -> mk_var v
| Fand (f1, f2) -> mk_and (build f1) (build f2)
| For (f1, f2) -> mk_or (build f1) (build f2)
| Fimp (f1, f2) -> mk_imp (build f1) (build f2)
| Fiff (f1, f2) -> mk_iff (build f1) (build f2)
| Fnot f -> mk_not (build f)
| Fite (f1, f2, f3) -> mk_ite (build f1) (build f2) (build f3)
let rec as_formula b =
match b.node with
| Zero -> Ffalse
| One -> Ftrue
| Node(v,l,h) -> Fite (Fvar v, as_formula h, as_formula l)
let rec as_compact_formula b =
match b.node with
| Zero -> Ffalse
| One -> Ftrue
| Node(v,{node=Zero;_},{node=One;_}) ->
if v then 1 else 0 -- > v
Fvar v
| Node(v,{node=One;_},{node=Zero;_}) ->
if v then 0 else 1 -- > ! v
Fnot (Fvar v)
| Node(v,{node=Zero;_},h) ->
(* if v then h else 0 --> v /\ h *)
Fand (Fvar v, as_compact_formula h)
| Node(v,{node=One;_},h) ->
if v then h else 1 -- > ! v \/ h
For (Fnot (Fvar v), as_compact_formula h)
| Node(v,l,{node=Zero;_}) ->
(* if v then 0 else l --> !v /\ l *)
Fand (Fnot (Fvar v), as_compact_formula l)
| Node(v,l,{node=One;_}) ->
if v then 1 else l -- > v \/ l
For (Fvar v, as_compact_formula l)
| Node(v,l,h) ->
Fite (Fvar v, as_compact_formula h, as_compact_formula l)
let mk_Fand f1 f2 =
match f2 with
| Ftrue -> f1
| _ -> Fand(f1,f2)
let as_compact_formula b =
let m = extract_known_values b in
let reduced_bdd =
mk_exist (fun v ->
try let _ = BddVarMap.find v m in true
with Not_found -> false) b
in
let f = as_compact_formula reduced_bdd in
BddVarMap.fold
(fun v b f ->
mk_Fand (if b then Fvar v else Fnot(Fvar v)) f )
m f
(* satisfiability *)
let is_sat b = b.node != Zero
let tautology b = b.node == One
let equivalent b1 b2 = b1 == b2
let entails b1 b2 = tautology (mk_imp b1 b2)
let rec int64_two_to = function
| 0 ->
Int64.one
| n ->
let r = int64_two_to (n/2) in
let r2 = Int64.mul r r in
if n mod 2 == 0 then r2 else Int64.mul (Int64.of_int 2) r2
let count_sat_int b =
let cache = H1.create cache_default_size in
let rec count b =
try
H1.find cache b
with Not_found ->
let n = match b.node with
| Zero -> 0
| One -> 1
| Node (v, l, h) ->
let dvl = var l - v - 1 in
let dvh = var h - v - 1 in
(1 lsl dvl) * count l + (1 lsl dvh) * count h
in
H1.add cache b n;
n
in
(1 lsl (var b - 1)) * count b
let count_sat b =
let cache = H1.create cache_default_size in
let rec count b =
try
H1.find cache b
with Not_found ->
let n = match b.node with
| Zero -> Int64.zero
| One -> Int64.one
| Node (v, l, h) ->
let dvl = var l - v - 1 in
let dvh = var h - v - 1 in
Int64.add
(Int64.mul (int64_two_to dvl) (count l))
(Int64.mul (int64_two_to dvh) (count h))
in
H1.add cache b n;
n
in
Int64.mul (int64_two_to (var b - 1)) (count b)
let any_sat =
let rec mk acc b = match b.node with
| Zero -> raise Not_found
| One -> acc
| Node (v, {node=Zero; _}, h) -> mk ((v,true)::acc) h
| Node (v, l, _) -> mk ((v,false)::acc) l
in
mk []
let random_sat =
let rec mk acc b = match b.node with
| Zero -> raise Not_found
| One -> acc
| Node (v, {node=Zero; _}, h) -> mk ((v,true) :: acc) h
| Node (v, l, {node=Zero; _}) -> mk ((v,false) :: acc) l
| Node (v, l, _) when Random.bool () -> mk ((v,false) :: acc) l
| Node (v, _, h) -> mk ((v,true) :: acc) h
in
mk []
TODO : a CPS version of all_sat
let all_sat =
let cache = H1.create cache_default_size in
let rec mk b =
try
H1.find cache b
with Not_found ->
let res = match b.node with
| Zero -> []
| One -> [[]]
| Node (v, l, h) ->
(List.map (fun a -> (v,false)::a) (mk l))
@ (List.map (fun a -> (v,true)::a) (mk h))
in
H1.add cache b res;
res
in
mk
DOT pretty - printing
module S = Set.Make(Bdd)
open Format
let format_to_dot b fmt =
fprintf fmt "digraph bdd {@\n";
let ranks = Hashtbl.create 17 in (* var -> set of nodes *)
let add_rank v b =
try Hashtbl.replace ranks v (S.add b (Hashtbl.find ranks v))
with Not_found -> Hashtbl.add ranks v (S.singleton b)
in
let visited = H1.create cache_default_size in
let rec visit b =
if not (H1.mem visited b) then begin
H1.add visited b ();
match b.node with
| Zero ->
fprintf fmt "%d [shape=box label=\"0\"];" b.tag
| One ->
fprintf fmt "%d [shape=box label=\"1\"];" b.tag
| Node (v, l, h) ->
add_rank v b;
fprintf fmt "%d [label=\"%a\"];" b.tag print_var v;
fprintf fmt "%d -> %d;@\n" b.tag h.tag;
fprintf fmt "%d -> %d [style=\"dashed\"];@\n" b.tag l.tag;
visit h; visit l
end
in
Hashtbl.iter
(fun _ s ->
fprintf fmt "{rank=same; ";
S.iter (fun x -> fprintf fmt "%d " x.tag) s;
fprintf fmt ";}@\n"
)
ranks;
visit b;
fprintf fmt "}@."
let to_dot b =
Buffer.truncate Format.stdbuf 0;
format_to_dot b Format.str_formatter;
Buffer.contents Format.stdbuf
let print_to_dot b ~file =
let c = open_out file in
let fmt = formatter_of_out_channel c in
format_to_dot b fmt;
close_out c
let display b =
let file = Filename.temp_file "bdd" ".dot" in
print_to_dot b ~file;
let cmd = sprintf "dot -Tps %s | gv -" file in
begin try ignore (Sys.command cmd) with _ -> () end;
try Sys.remove file with _ -> ()
end (* module Session *)
let make ?(print_var=fun ff -> Format.fprintf ff "x%d")
?(size=7001)
max_var
= let module B = Make(struct let print_var = print_var
let size = size let max_var = max_var end) in
(module B: BDD)
| null | https://raw.githubusercontent.com/AdaCore/why3/be1023970d48869285e68f12d32858c3383958e0/src/bddinfer/bdd.ml | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
described in file LICENSE.
This software 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.
************************************************************************
Binary Decision Diagrams
1..max_var
Make a fresh module
low
high
export
if v then h else 0 --> v /\ h
if v then 0 else l --> !v /\ l
sum of the bucket sizes
max ratio totsize/table length
unused
let iter f t =
let rec iter_bucket i b =
if i >= Weak.length b then () else
match Weak.get b i with
| Some v -> f v; iter_bucket (i+1) b
| None -> iter_bucket (i+1) b
in
Array.iter (iter_bucket 0) t.table
prevent resizing of newt
v1 > v2
if v then h else 0 --> v /\ h
if v then 0 else l --> !v /\ l
v1 > v2
v1 > v2
var u = x
if v then h else 0 --> v /\ h
if v then 0 else l --> !v /\ l
satisfiability
var -> set of nodes
module Session | Copyright ( C )
License version 2.1 , with the special exception on linking
module BddVarMap =
Map.Make(struct
type t = variable
let compare (x:variable) (y:variable) = compare x y
end)
type formula =
| Ffalse
| Ftrue
| Fvar of variable
| Fand of formula * formula
| For of formula * formula
| Fimp of formula * formula
| Fiff of formula * formula
| Fnot of formula
if then f2 else f3
module type BDD = sig
val get_max_var : unit -> int
type t
type view = Zero | One | Node of variable * t * t
val view : t -> view
val var : t -> variable
val low : t -> t
val high : t -> t
val zero : t
val one : t
val make : variable -> low:t -> high:t -> t
val mk_var : variable -> t
val mk_not : t -> t
val mk_and : t -> t -> t
val mk_or : t -> t -> t
val mk_imp : t -> t -> t
val mk_iff : t -> t -> t
val mk_exist : (variable -> bool) -> t -> t
val mk_forall : (variable -> bool) -> t -> t
val extract_known_values : t -> bool BddVarMap.t
val apply : (bool -> bool -> bool) -> t -> t -> t
val constrain : t -> t -> t
val restriction : t -> t -> t
val restrict : t -> variable -> bool -> t
val build : formula -> t
val as_formula : t -> formula
val as_compact_formula : t -> formula
val is_sat : t -> bool
val tautology : t -> bool
val equivalent : t -> t -> bool
val entails : t -> t -> bool
val count_sat_int : t -> int
val count_sat : t -> Int64.t
val any_sat : t -> (variable * bool) list
val random_sat : t -> (variable * bool) list
val all_sat : t -> (variable * bool) list list
val print_var : Format.formatter -> variable -> unit
val print : Format.formatter -> t -> unit
val print_compact : Format.formatter -> t -> unit
val to_dot : t -> string
val print_to_dot : t -> file:string -> unit
val display : t -> unit
val stats : unit -> (int * int * int * int * int * int) array
end
let debug = false
module Make(X: sig
val print_var: Format.formatter -> int -> unit
val size: int
val max_var: int
end) = struct
open X
let rec power_2_above x n =
if x >= n then x
else if x * 2 > Sys.max_array_length then x
else power_2_above (x * 2) n
let size = power_2_above 16 size
let print_var = print_var
let get_max_var () = max_var
type bdd = { tag: int; node : view }
let view b = b.node
let rec print fmt b =
match b.node with
| Zero -> Format.fprintf fmt "false"
| One -> Format.fprintf fmt "true"
| Node(v,l,h) ->
Format.fprintf fmt "@[<hv 2>if %a@ then %a@ else %a@]" print_var v print h print l
let rec print_compact fmt b =
match b.node with
| Zero -> Format.fprintf fmt "false"
| One -> Format.fprintf fmt "true"
| Node(v,{node=Zero;_},{node=One;_}) ->
if v then 1 else 0 -- > v
Format.fprintf fmt "%a" print_var v
| Node(v,{node=One;_},{node=Zero;_}) ->
if v then 0 else 1 -- > ! v
Format.fprintf fmt "!%a" print_var v
| Node(v,{node=Zero;_},h) ->
Format.fprintf fmt "@[%a /\\@ %a@]" print_var v print_compact h
| Node(v,{node=One;_},h) ->
if v then h else 1 -- > ! v \/ h
Format.fprintf fmt "@[!%a \\/@ %a@]" print_var v print_compact h
| Node(v,l,{node=Zero;_}) ->
Format.fprintf fmt "@[!%a /\\@ %a@]" print_var v print_compact l
| Node(v,l,{node=One;_}) ->
if v then 1 else l -- > v \/ l
Format.fprintf fmt "@[%a \\/@ %a@]" print_var v print_compact l
| Node(v,l,h) ->
Format.fprintf fmt "@[<hv 2>if %a@ then %a@ else %a@]" print_var v print_compact h print_compact l
unused
let equal x y = match x , y with
| Node ( v1 , l1 , h1 ) , ( v2 , l2 , h2 ) - >
v1 = = v2 & & l1 = = l2 & & h1 = = h2
| _ - >
x = = y
let equal x y = match x, y with
| Node (v1, l1, h1), Node (v2, l2, h2) ->
v1 == v2 && l1 == l2 && h1 == h2
| _ ->
x == y
*)
* perfect hashing is actually less efficient
let pair a b = ( a + b ) * ( a + b + 1 ) / 2 + a
let triple a b c = pair c ( pair a b )
let hash_node v l h = abs ( triple l.tag h.tag v )
*
let pair a b = (a + b) * (a + b + 1) / 2 + a
let triple a b c = pair c (pair a b)
let hash_node v l h = abs (triple l.tag h.tag v)
**)
let hash_node l h = 19 * l.tag + h.tag
let hash = function
| Zero -> 0
| One -> 1
| Node (_, l, h) -> hash_node l h
let gentag = let r = ref (-1) in fun () -> incr r; !r
type table = {
mutable table : bdd Weak.t array;
}
let create sz =
let emptybucket = Weak.create 0 in
{ table = Array.make sz emptybucket;
totsize = 0;
limit = 3; }
let vt = Array.init max_var (fun _ -> create size)
let fold f t init =
let rec fold_bucket i b accu =
if i >= Weak.length b then accu else
match Weak.get b i with
| Some v -> fold_bucket (i+1) b (f v accu)
| None -> fold_bucket (i+1) b accu
in
Array.fold_right (fold_bucket 0) t.table init
let count t =
let rec count_bucket i b accu =
if i >= Weak.length b then accu else
count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0))
in
Array.fold_right (count_bucket 0) t.table 0
let rec resize t =
if debug then Format.eprintf "resizing...@.";
let oldlen = Array.length t.table in
let newlen = oldlen * 2 in
if newlen > oldlen then begin
let newt = create newlen in
fold (fun d () -> add newt d) t ();
t.table <- newt.table;
t.limit <- t.limit + 2;
end
and add t d =
add_index t d ((hash d.node) land (Array.length t.table - 1))
and add_index t d index =
let bucket = t.table.(index) in
let sz = Weak.length bucket in
let rec loop i =
if i >= sz then begin
let newsz = min (sz + 3) (Sys.max_array_length - 1) in
if newsz <= sz then
failwith "Hashcons.Make: hash bucket cannot grow more";
let newbucket = Weak.create newsz in
Weak.blit bucket 0 newbucket 0 sz;
Weak.set newbucket i (Some d);
t.table.(index) <- newbucket;
t.totsize <- t.totsize + (newsz - sz);
if t.totsize > t.limit * Array.length t.table then resize t;
end else begin
if Weak.check bucket i
then loop (i+1)
else Weak.set bucket i (Some d)
end
in
loop 0
let hashcons_node v l h =
let t = vt.(v - 1) in
let index = (hash_node l h) mod (Array.length t.table) in
let bucket = t.table.(index) in
let sz = Weak.length bucket in
let rec loop i =
if i >= sz then begin
let hnode = { tag = gentag (); node = Node (v, l, h) } in
add_index t hnode index;
hnode
end else begin
match Weak.get_copy bucket i with
| Some {node=Node(v',l',h'); _} when v==v' && l==l' && h==h' ->
begin match Weak.get bucket i with
| Some v -> v
| None -> loop (i+1)
end
| _ -> loop (i+1)
end
in
loop 0
let stat t =
let len = Array.length t.table in
let lens = Array.map Weak.length t.table in
Array.sort compare lens;
let totlen = Array.fold_left ( + ) 0 lens in
(len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1))
let stats () = Array.map stat vt
zero and one allocated once and for all
let zero = { tag = gentag (); node = Zero }
let one = { tag = gentag (); node = One }
let var b = match b.node with
| Zero | One -> max_var + 1
| Node (v, _, _) -> v
let low b = match b.node with
| Zero | One -> invalid_arg "Bdd.low"
| Node (_, l, _) -> l
let high b = match b.node with
| Zero | One -> invalid_arg "Bdd.low"
| Node (_, _, h) -> h
let mk v ~low ~high =
if low == high then low else hashcons_node v low high
let make v ~low ~high =
if v < 1 || v > max_var then invalid_arg "Bdd.make";
mk v ~low ~high
let mk_var v =
if v < 1 || v > max_var then invalid_arg "Bdd.mk_var";
mk v ~low:zero ~high:one
module Bdd = struct
type t = bdd
let equal = (==)
let hash b = b.tag
let compare b1 b2 = Stdlib.compare b1.tag b2.tag
end
module H1 = Hashtbl.Make(Bdd)
let cache_default_size = 7001
let mk_not x =
let cache = H1.create cache_default_size in
let rec mk_not_rec x =
try
H1.find cache x
with Not_found ->
let res = match x.node with
| Zero -> one
| One -> zero
| Node (v, l, h) -> mk v ~low:(mk_not_rec l) ~high:(mk_not_rec h)
in
H1.add cache x res;
res
in
mk_not_rec x
unused
let bool_of = function Zero - > false | One - > true | _ - > invalid_arg " bool_of "
let bool_of = function Zero -> false | One -> true | _ -> invalid_arg "bool_of"*)
let of_bool b = if b then one else zero
module H2 = Hashtbl.Make(
struct
type t = bdd * bdd
let equal (u1,v1) (u2,v2) = u1==u2 && v1==v2
let hash (u,v) =
abs ( 19 * u.tag + v.tag )
let s = u.tag + v.tag in abs (s * (s+1) / 2 + u.tag)
end)
type operator =
| Op_and | Op_or | Op_imp
| Op_any of (bool -> bool -> bool)
let apply_op op b1 b2 = match op with
| Op_and -> b1 && b2
| Op_or -> b1 || b2
| Op_imp -> (not b1) || b2
| Op_any f -> f b1 b2
let gapply op =
let op_z_z = of_bool (apply_op op false false) in
let op_z_o = of_bool (apply_op op false true) in
let op_o_z = of_bool (apply_op op true false) in
let op_o_o = of_bool (apply_op op true true) in
fun b1 b2 ->
let cache = H2.create cache_default_size in
let rec app ((u1,u2) as u12) =
match op with
| Op_and ->
if u1 == u2 then
u1
else if u1 == zero || u2 == zero then
zero
else if u1 == one then
u2
else if u2 == one then
u1
else
app_gen u12
| Op_or ->
if u1 == u2 then
u1
else if u1 == one || u2 == one then
one
else if u1 == zero then
u2
else if u2 == zero then
u1
else
app_gen u12
| Op_imp ->
if u1 == zero then
one
else if u1 == one then
u2
else if u2 == one then
one
else
app_gen u12
| Op_any _ ->
app_gen u12
and app_gen ((u1,u2) as u12) =
match u1.node, u2.node with
| Zero, Zero -> op_z_z
| Zero, One -> op_z_o
| One, Zero -> op_o_z
| One, One -> op_o_o
| _ ->
try
H2.find cache u12
with Not_found ->
let res =
let v1 = var u1 in
let v2 = var u2 in
if v1 == v2 then
mk v1 ~low:(app (low u1, low u2)) ~high:(app (high u1, high u2))
else if v1 < v2 then
mk v1 ~low:(app (low u1, u2)) ~high:(app (high u1, u2))
mk v2 ~low:(app (u1, low u2)) ~high:(app (u1, high u2))
in
H2.add cache u12 res;
res
in
app (b1, b2)
let mk_and = gapply Op_and
let mk_or = gapply Op_or
let mk_imp = gapply Op_imp
let mk_iff = gapply (Op_any (fun b1 b2 -> b1 == b2))
let mk_ite f1 f2 f3 =
mk_and (mk_imp f1 f2) (mk_imp (mk_not f1) f3)
* { 2 quantifier elimination }
let rec quantifier_elim cache op filter b =
try
H1.find cache b
with Not_found ->
let res = match b.node with
| Zero | One -> b
| Node(v,l,h) ->
let low = quantifier_elim cache op filter l in
let high = quantifier_elim cache op filter h in
if filter v then
op low high
else
mk v ~low ~high
in
H1.add cache b res;
res
let mk_exist filter b =
let cache = H1.create cache_default_size in
quantifier_elim cache mk_or filter b
let mk_forall filter b =
let cache = H1.create cache_default_size in
quantifier_elim cache mk_and filter b
let rec extract_known_values cache b =
try
H1.find cache b
with Not_found ->
let res = match b.node with
| Zero | One -> BddVarMap.empty
| Node(v,{node=Zero;_},h) ->
BddVarMap.add v true (extract_known_values cache h)
| Node(v,l,{node=Zero;_}) ->
BddVarMap.add v false (extract_known_values cache l)
| Node(_,l,h) ->
let m1 = extract_known_values cache l in
let m2 = extract_known_values cache h in
let merge_bool _ b1 b2 =
match b1, b2 with
| Some b1, Some b2 when b1=b2 -> Some b1
| _ -> None
in
BddVarMap.merge merge_bool m1 m2
in
H1.add cache b res;
res
let extract_known_values b =
let cache = H1.create cache_default_size in
extract_known_values cache b
let apply f = gapply (Op_any f)
let constrain b1 b2 =
let cache = H2.create cache_default_size in
let rec app ((u1,u2) as u12) =
match u1.node, u2.node with
| _, Zero -> failwith "constrain 0 is undefined"
| _, One -> u1
| Zero, _ -> u1
| One, _ -> u1
| _ ->
try
H2.find cache u12
with Not_found ->
let res =
let v1 = var u1 in
let v2 = var u2 in
if v1 == v2 then begin
if low u2 == zero then app (high u1, high u2)
else if high u2 == zero then app (low u1, low u2)
else mk (var u1) ~low:(app (low u1, low u2)) ~high:(app (high u1, high u2))
end
else if v1 < v2 then
mk v1 ~low:(app (low u1, u2)) ~high:(app (high u1, u2))
mk v2 ~low:(app (u1, low u2)) ~high:(app (u1, high u2))
in
H2.add cache u12 res;
res
in
app (b1, b2)
let restriction b1 b2 =
let cache = H2.create cache_default_size in
let rec app ((u1,u2) as u12) =
match u1.node, u2.node with
| _, Zero -> failwith "constrain 0 is undefined"
| _, One -> u1
| Zero, _ -> u1
| One, _ -> u1
| _ ->
try
H2.find cache u12
with Not_found ->
let res =
let v1 = var u1 in
let v2 = var u2 in
if v1 == v2 then begin
if low u2 == zero then app (high u1, high u2)
else if high u2 == zero then app (low u1, low u2)
else mk (var u1) ~low:(app (low u1, low u2)) ~high:(app (high u1, high u2))
end
else if v1 < v2 then
mk v1 ~low:(app (low u1, u2)) ~high:(app (high u1, u2))
app (u1, mk_or (low u2) (high u2))
in
H2.add cache u12 res;
res
in
app (b1, b2)
let restrict u x b =
let cache = H1.create cache_default_size in
let rec app u =
try
H1.find cache u
with Not_found ->
let res =
if var u > x then u
else if var u < x then mk (var u) ~low:(app (low u)) ~high:(app (high u))
var u = x , b = 0
in
H1.add cache u res;
res
in
app u
formula - > bdd
let rec build = function
| Ffalse -> zero
| Ftrue -> one
| Fvar v -> mk_var v
| Fand (f1, f2) -> mk_and (build f1) (build f2)
| For (f1, f2) -> mk_or (build f1) (build f2)
| Fimp (f1, f2) -> mk_imp (build f1) (build f2)
| Fiff (f1, f2) -> mk_iff (build f1) (build f2)
| Fnot f -> mk_not (build f)
| Fite (f1, f2, f3) -> mk_ite (build f1) (build f2) (build f3)
let rec as_formula b =
match b.node with
| Zero -> Ffalse
| One -> Ftrue
| Node(v,l,h) -> Fite (Fvar v, as_formula h, as_formula l)
let rec as_compact_formula b =
match b.node with
| Zero -> Ffalse
| One -> Ftrue
| Node(v,{node=Zero;_},{node=One;_}) ->
if v then 1 else 0 -- > v
Fvar v
| Node(v,{node=One;_},{node=Zero;_}) ->
if v then 0 else 1 -- > ! v
Fnot (Fvar v)
| Node(v,{node=Zero;_},h) ->
Fand (Fvar v, as_compact_formula h)
| Node(v,{node=One;_},h) ->
if v then h else 1 -- > ! v \/ h
For (Fnot (Fvar v), as_compact_formula h)
| Node(v,l,{node=Zero;_}) ->
Fand (Fnot (Fvar v), as_compact_formula l)
| Node(v,l,{node=One;_}) ->
if v then 1 else l -- > v \/ l
For (Fvar v, as_compact_formula l)
| Node(v,l,h) ->
Fite (Fvar v, as_compact_formula h, as_compact_formula l)
let mk_Fand f1 f2 =
match f2 with
| Ftrue -> f1
| _ -> Fand(f1,f2)
let as_compact_formula b =
let m = extract_known_values b in
let reduced_bdd =
mk_exist (fun v ->
try let _ = BddVarMap.find v m in true
with Not_found -> false) b
in
let f = as_compact_formula reduced_bdd in
BddVarMap.fold
(fun v b f ->
mk_Fand (if b then Fvar v else Fnot(Fvar v)) f )
m f
let is_sat b = b.node != Zero
let tautology b = b.node == One
let equivalent b1 b2 = b1 == b2
let entails b1 b2 = tautology (mk_imp b1 b2)
let rec int64_two_to = function
| 0 ->
Int64.one
| n ->
let r = int64_two_to (n/2) in
let r2 = Int64.mul r r in
if n mod 2 == 0 then r2 else Int64.mul (Int64.of_int 2) r2
let count_sat_int b =
let cache = H1.create cache_default_size in
let rec count b =
try
H1.find cache b
with Not_found ->
let n = match b.node with
| Zero -> 0
| One -> 1
| Node (v, l, h) ->
let dvl = var l - v - 1 in
let dvh = var h - v - 1 in
(1 lsl dvl) * count l + (1 lsl dvh) * count h
in
H1.add cache b n;
n
in
(1 lsl (var b - 1)) * count b
let count_sat b =
let cache = H1.create cache_default_size in
let rec count b =
try
H1.find cache b
with Not_found ->
let n = match b.node with
| Zero -> Int64.zero
| One -> Int64.one
| Node (v, l, h) ->
let dvl = var l - v - 1 in
let dvh = var h - v - 1 in
Int64.add
(Int64.mul (int64_two_to dvl) (count l))
(Int64.mul (int64_two_to dvh) (count h))
in
H1.add cache b n;
n
in
Int64.mul (int64_two_to (var b - 1)) (count b)
let any_sat =
let rec mk acc b = match b.node with
| Zero -> raise Not_found
| One -> acc
| Node (v, {node=Zero; _}, h) -> mk ((v,true)::acc) h
| Node (v, l, _) -> mk ((v,false)::acc) l
in
mk []
let random_sat =
let rec mk acc b = match b.node with
| Zero -> raise Not_found
| One -> acc
| Node (v, {node=Zero; _}, h) -> mk ((v,true) :: acc) h
| Node (v, l, {node=Zero; _}) -> mk ((v,false) :: acc) l
| Node (v, l, _) when Random.bool () -> mk ((v,false) :: acc) l
| Node (v, _, h) -> mk ((v,true) :: acc) h
in
mk []
TODO : a CPS version of all_sat
let all_sat =
let cache = H1.create cache_default_size in
let rec mk b =
try
H1.find cache b
with Not_found ->
let res = match b.node with
| Zero -> []
| One -> [[]]
| Node (v, l, h) ->
(List.map (fun a -> (v,false)::a) (mk l))
@ (List.map (fun a -> (v,true)::a) (mk h))
in
H1.add cache b res;
res
in
mk
DOT pretty - printing
module S = Set.Make(Bdd)
open Format
let format_to_dot b fmt =
fprintf fmt "digraph bdd {@\n";
let add_rank v b =
try Hashtbl.replace ranks v (S.add b (Hashtbl.find ranks v))
with Not_found -> Hashtbl.add ranks v (S.singleton b)
in
let visited = H1.create cache_default_size in
let rec visit b =
if not (H1.mem visited b) then begin
H1.add visited b ();
match b.node with
| Zero ->
fprintf fmt "%d [shape=box label=\"0\"];" b.tag
| One ->
fprintf fmt "%d [shape=box label=\"1\"];" b.tag
| Node (v, l, h) ->
add_rank v b;
fprintf fmt "%d [label=\"%a\"];" b.tag print_var v;
fprintf fmt "%d -> %d;@\n" b.tag h.tag;
fprintf fmt "%d -> %d [style=\"dashed\"];@\n" b.tag l.tag;
visit h; visit l
end
in
Hashtbl.iter
(fun _ s ->
fprintf fmt "{rank=same; ";
S.iter (fun x -> fprintf fmt "%d " x.tag) s;
fprintf fmt ";}@\n"
)
ranks;
visit b;
fprintf fmt "}@."
let to_dot b =
Buffer.truncate Format.stdbuf 0;
format_to_dot b Format.str_formatter;
Buffer.contents Format.stdbuf
let print_to_dot b ~file =
let c = open_out file in
let fmt = formatter_of_out_channel c in
format_to_dot b fmt;
close_out c
let display b =
let file = Filename.temp_file "bdd" ".dot" in
print_to_dot b ~file;
let cmd = sprintf "dot -Tps %s | gv -" file in
begin try ignore (Sys.command cmd) with _ -> () end;
try Sys.remove file with _ -> ()
let make ?(print_var=fun ff -> Format.fprintf ff "x%d")
?(size=7001)
max_var
= let module B = Make(struct let print_var = print_var
let size = size let max_var = max_var end) in
(module B: BDD)
|
e450eb25be48306a6bf7c4b485b3242dc2a70cd23d1ab31ec18b123f53dcac5b | pmundkur/flowcaml | principal.ml | (**************************************************************************)
(* *)
(* *)
, Projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 , 2003 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 .
(* *)
(* Author contact: *)
(* Software page: /~simonet/soft/flowcaml/ *)
(* *)
(**************************************************************************)
$ I d : principal.ml , v 1.4 2003/10/01 13:28:21 simonet Exp $
(* Principal: the lattice of principals *)
open Datastruct
type node =
{ mutable succ: node StringMap.t;
mutable succ_kernel: node StringMap.t;
mutable counter: int;
mutable scc: (string * node) Avl_kernel.scc
}
type lattice =
node StringHashtbl.t
(*************************************************************************)
* { 2 Graph operations on lattices }
module G = struct
type graph = lattice
type foo = node
type node = string * foo
let iter_nodes f graph =
StringHashtbl.iter (fun name node -> f (name, node)) graph
let iter_successors f (_, node) =
StringMap.iter (fun name' node' -> f (name', node')) node.succ
let get (_, node) =
node.counter
let set (_, node) i =
node.counter <- i
let get_scc (_, node) =
node.scc
let set_scc (_, node) i =
node.scc <- i
end
module Closure = Avl_closure.Make (G)
module Kernel = Avl_kernel.Make (G)
(*************************************************************************)
* { 2 Manipulating lattices }
let create () =
StringHashtbl.create 7
let dumb_scc = Avl_kernel.scc ()
(** [find lattice principal] returns the node representing the principal
[principal] in the lattice [lattice]. If [principal] is not represented
in [lattice], the exception [Not_found] is raised.
*)
let find lattice principal =
StringHashtbl.find lattice principal
(** [get lattice principal] returns the node representing the principal
[principal] in the lattice [lattice]. If [principal] is not represented
in [lattice], a new node is created, inserted in [lattice] and returned.
*)
let get lattice principal =
try
find lattice principal
with
Not_found ->
let node =
{ succ = StringMap.empty;
succ_kernel = StringMap.empty;
counter = 0;
scc = dumb_scc
}
in
StringHashtbl.add lattice principal node;
node
(*************************************************************************)
* { 2 Translating flows declarations into lattices }
* [ flow lattice principal1 principal2 ] registers the flow from
[ principal1 ] to [ principal2 ] in the lattice [ lattice ] . It does not
performs the transitive closure and reduction of the underlying graph .
[principal1] to [principal2] in the lattice [lattice]. It does not
performs the transitive closure and reduction of the underlying graph.
*)
let add_flow lattice principal1 principal2 =
let node1 = get lattice principal1 in
if not (StringMap.mem principal2 node1.succ) then begin
let node2 = get lattice principal2 in
node1.succ <- StringMap.add principal2 node2 node1.succ
end
* [ do_closure lattice ] performs the transitive closure of the lattice
[ lattice ] .
[lattice].
*)
let do_closure lattice =
let edges = Closure.list lattice in
StringHashtbl.iter (fun _ node -> node.succ <- StringMap.empty) lattice;
List.iter (function (principal1, node1), (principal2, node2) ->
node1.succ <- StringMap.add principal2 node2 node1.succ
) edges
(** [do_kernel lattice] computes the transitive reduction of the lattice
[lattice].
*)
let do_kernel lattice =
StringHashtbl.iter (fun _ node -> node.succ_kernel <- StringMap.empty) lattice;
Kernel.fold () (fun (principal1, node1) (principal2, node2) () ->
node1.succ_kernel <- StringMap.add principal2 node2 node1.succ_kernel
) lattice
(** [translate_into lattice plat] add every flow listed in [plat] in the
lattice [lattice]. At the end of insertion, [lattice] is transitively
closed.
*)
let translate_into lattice plat =
List.iter (function principals_from, principals_to ->
List.iter (function principal_from ->
List.iter (function principal_to ->
add_flow lattice principal_from principal_to
) principals_to
) principals_from
) plat;
do_closure lattice
(** [translate plat] creates a new lattice with all flows listed in [plat].
*)
let translate plat =
let lattice = create () in
translate_into lattice plat;
lattice
* [ merge_into ] inserts all the inequalities of [ ]
in [ lattice2 ] .
in [lattice2].
*)
let merge_into lattice1 lattice2 =
StringHashtbl.iter (fun principal node2 ->
let node1 = get lattice1 principal in
StringMap.iter (fun principal' _ ->
if not (StringMap.mem principal' node1.succ) then begin
let node1' = get lattice1 principal' in
node1.succ <- StringMap.add principal' node1' node1.succ
end
) node2.succ
) lattice2
(*************************************************************************)
* { 2 Inclusion test }
exception Included of string * string
let included lattice1 lattice2 =
try
StringHashtbl.iter (fun name desc1 ->
let desc2 = get lattice2 name in
StringMap.iter (fun name' _ ->
if not (StringMap.mem name' desc2.succ) then
raise (Included (name, name'))
) desc1.succ
) lattice1;
None
with
Included (name1, name2) -> Some (name1, name2)
(*************************************************************************)
* { 2 Testing inequalities }
let leq lattice principal1 principal2 =
(principal1 = principal2)
or
try
let node1 = find lattice principal1 in
StringMap.mem principal2 node1.succ
with
Not_found -> false
(*************************************************************************)
* { 2 Output functions }
let fprint ppf lattice =
do_kernel lattice;
Format.fprintf ppf "@[<v>";
StringHashtbl.iter (fun name desc ->
StringMap.iter (fun name' _ ->
Format.fprintf ppf "@[!%s < !%s@]@ " name name'
) desc.succ_kernel
) lattice;
Format.fprintf ppf "@]"
module Draw = Avl_draw.MakeGraphics (struct
open Avl_draw
let dark_blue = Avl_graphics.rgb 0 0 128
let dark_red = Avl_graphics.rgb 128 0 0
let flow_node name =
{ default_node with
nd_shape = `Box;
nd_border = `Solid (dark_blue, 0);
nd_label = `Text { default_label with
tl_text = name;
tl_color = dark_red }
}
let flow_edge =
{ default_edge with
ed_linestyle = `Solid (dark_red, 0);
ed_tailarrow = `Filled (10, 0.5 *. atan 1.0, dark_red)
}
type graph = lattice
type foo = node
type node = string * foo
type edge = node * node
let iter_nodes f graph =
StringHashtbl.iter (fun name desc -> f (name, desc)) graph
let iter_successors f (_, desc) =
StringMap.iter (fun name' desc' -> f (name', desc')) desc.succ_kernel
let get (_, desc) =
desc.counter
let set (_, desc) i =
desc.counter <- i
let iter_edges f graph =
iter_nodes (function node ->
iter_successors (function node' -> f (node, node')) node
) graph
let node_hash (name, _) =
Hashtbl.hash name
let node_equal (name1, desc1) (name2, desc2) =
name1 = name2
let node_attributes (name, _) =
flow_node ("!" ^ name)
let edge_hash ((name1, _), (name2, _)) =
Hashtbl.hash (name1, name2)
let edge_equal (node1, node2) (node1', node2') =
node_equal node1 node1' && node_equal node2 node2'
let edge_head (node, _) =
node
let edge_tail (_, node) =
node
let edge_attributes (node1, node2) =
flow_edge
end)
let draw lattice x y =
let w, h = Avl_graphics.text_size "X" in
do_kernel lattice;
Draw.draw_graph () (`Dot [`Nodesep w; `Ranksep h]) x y lattice
| null | https://raw.githubusercontent.com/pmundkur/flowcaml/ddfa8a37e1cb60f42650bed8030036ac313e048a/src-flowcaml/types/principal.ml | ocaml | ************************************************************************
et en Automatique. All rights reserved. This file is distributed
Author contact:
Software page: /~simonet/soft/flowcaml/
************************************************************************
Principal: the lattice of principals
***********************************************************************
***********************************************************************
* [find lattice principal] returns the node representing the principal
[principal] in the lattice [lattice]. If [principal] is not represented
in [lattice], the exception [Not_found] is raised.
* [get lattice principal] returns the node representing the principal
[principal] in the lattice [lattice]. If [principal] is not represented
in [lattice], a new node is created, inserted in [lattice] and returned.
***********************************************************************
* [do_kernel lattice] computes the transitive reduction of the lattice
[lattice].
* [translate_into lattice plat] add every flow listed in [plat] in the
lattice [lattice]. At the end of insertion, [lattice] is transitively
closed.
* [translate plat] creates a new lattice with all flows listed in [plat].
***********************************************************************
***********************************************************************
*********************************************************************** |
, Projet Cristal , INRIA Rocquencourt
Copyright 2002 , 2003 Institut National de Recherche en Informatique
under the terms of the Q Public License version 1.0 .
$ I d : principal.ml , v 1.4 2003/10/01 13:28:21 simonet Exp $
open Datastruct
type node =
{ mutable succ: node StringMap.t;
mutable succ_kernel: node StringMap.t;
mutable counter: int;
mutable scc: (string * node) Avl_kernel.scc
}
type lattice =
node StringHashtbl.t
* { 2 Graph operations on lattices }
module G = struct
type graph = lattice
type foo = node
type node = string * foo
let iter_nodes f graph =
StringHashtbl.iter (fun name node -> f (name, node)) graph
let iter_successors f (_, node) =
StringMap.iter (fun name' node' -> f (name', node')) node.succ
let get (_, node) =
node.counter
let set (_, node) i =
node.counter <- i
let get_scc (_, node) =
node.scc
let set_scc (_, node) i =
node.scc <- i
end
module Closure = Avl_closure.Make (G)
module Kernel = Avl_kernel.Make (G)
* { 2 Manipulating lattices }
let create () =
StringHashtbl.create 7
let dumb_scc = Avl_kernel.scc ()
let find lattice principal =
StringHashtbl.find lattice principal
let get lattice principal =
try
find lattice principal
with
Not_found ->
let node =
{ succ = StringMap.empty;
succ_kernel = StringMap.empty;
counter = 0;
scc = dumb_scc
}
in
StringHashtbl.add lattice principal node;
node
* { 2 Translating flows declarations into lattices }
* [ flow lattice principal1 principal2 ] registers the flow from
[ principal1 ] to [ principal2 ] in the lattice [ lattice ] . It does not
performs the transitive closure and reduction of the underlying graph .
[principal1] to [principal2] in the lattice [lattice]. It does not
performs the transitive closure and reduction of the underlying graph.
*)
let add_flow lattice principal1 principal2 =
let node1 = get lattice principal1 in
if not (StringMap.mem principal2 node1.succ) then begin
let node2 = get lattice principal2 in
node1.succ <- StringMap.add principal2 node2 node1.succ
end
* [ do_closure lattice ] performs the transitive closure of the lattice
[ lattice ] .
[lattice].
*)
let do_closure lattice =
let edges = Closure.list lattice in
StringHashtbl.iter (fun _ node -> node.succ <- StringMap.empty) lattice;
List.iter (function (principal1, node1), (principal2, node2) ->
node1.succ <- StringMap.add principal2 node2 node1.succ
) edges
let do_kernel lattice =
StringHashtbl.iter (fun _ node -> node.succ_kernel <- StringMap.empty) lattice;
Kernel.fold () (fun (principal1, node1) (principal2, node2) () ->
node1.succ_kernel <- StringMap.add principal2 node2 node1.succ_kernel
) lattice
let translate_into lattice plat =
List.iter (function principals_from, principals_to ->
List.iter (function principal_from ->
List.iter (function principal_to ->
add_flow lattice principal_from principal_to
) principals_to
) principals_from
) plat;
do_closure lattice
let translate plat =
let lattice = create () in
translate_into lattice plat;
lattice
* [ merge_into ] inserts all the inequalities of [ ]
in [ lattice2 ] .
in [lattice2].
*)
let merge_into lattice1 lattice2 =
StringHashtbl.iter (fun principal node2 ->
let node1 = get lattice1 principal in
StringMap.iter (fun principal' _ ->
if not (StringMap.mem principal' node1.succ) then begin
let node1' = get lattice1 principal' in
node1.succ <- StringMap.add principal' node1' node1.succ
end
) node2.succ
) lattice2
* { 2 Inclusion test }
exception Included of string * string
let included lattice1 lattice2 =
try
StringHashtbl.iter (fun name desc1 ->
let desc2 = get lattice2 name in
StringMap.iter (fun name' _ ->
if not (StringMap.mem name' desc2.succ) then
raise (Included (name, name'))
) desc1.succ
) lattice1;
None
with
Included (name1, name2) -> Some (name1, name2)
* { 2 Testing inequalities }
let leq lattice principal1 principal2 =
(principal1 = principal2)
or
try
let node1 = find lattice principal1 in
StringMap.mem principal2 node1.succ
with
Not_found -> false
* { 2 Output functions }
let fprint ppf lattice =
do_kernel lattice;
Format.fprintf ppf "@[<v>";
StringHashtbl.iter (fun name desc ->
StringMap.iter (fun name' _ ->
Format.fprintf ppf "@[!%s < !%s@]@ " name name'
) desc.succ_kernel
) lattice;
Format.fprintf ppf "@]"
module Draw = Avl_draw.MakeGraphics (struct
open Avl_draw
let dark_blue = Avl_graphics.rgb 0 0 128
let dark_red = Avl_graphics.rgb 128 0 0
let flow_node name =
{ default_node with
nd_shape = `Box;
nd_border = `Solid (dark_blue, 0);
nd_label = `Text { default_label with
tl_text = name;
tl_color = dark_red }
}
let flow_edge =
{ default_edge with
ed_linestyle = `Solid (dark_red, 0);
ed_tailarrow = `Filled (10, 0.5 *. atan 1.0, dark_red)
}
type graph = lattice
type foo = node
type node = string * foo
type edge = node * node
let iter_nodes f graph =
StringHashtbl.iter (fun name desc -> f (name, desc)) graph
let iter_successors f (_, desc) =
StringMap.iter (fun name' desc' -> f (name', desc')) desc.succ_kernel
let get (_, desc) =
desc.counter
let set (_, desc) i =
desc.counter <- i
let iter_edges f graph =
iter_nodes (function node ->
iter_successors (function node' -> f (node, node')) node
) graph
let node_hash (name, _) =
Hashtbl.hash name
let node_equal (name1, desc1) (name2, desc2) =
name1 = name2
let node_attributes (name, _) =
flow_node ("!" ^ name)
let edge_hash ((name1, _), (name2, _)) =
Hashtbl.hash (name1, name2)
let edge_equal (node1, node2) (node1', node2') =
node_equal node1 node1' && node_equal node2 node2'
let edge_head (node, _) =
node
let edge_tail (_, node) =
node
let edge_attributes (node1, node2) =
flow_edge
end)
let draw lattice x y =
let w, h = Avl_graphics.text_size "X" in
do_kernel lattice;
Draw.draw_graph () (`Dot [`Nodesep w; `Ranksep h]) x y lattice
|
4fa6810c4d80a7e7bfb8f017491b106b4bfecc53b81cec50dd8945caea0448cd | deadpendency/deadpendency | Config.hs | module RP.Model.Config
( Config (..),
)
where
import Common.Model.GitHub.GHAppId
data Config = Config
{ _redisDatabaseHost :: Text,
_githubPrivateKeySecretName :: Text,
_appId :: GHAppId
}
deriving stock (Generic)
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/run-preparer/src/RP/Model/Config.hs | haskell | module RP.Model.Config
( Config (..),
)
where
import Common.Model.GitHub.GHAppId
data Config = Config
{ _redisDatabaseHost :: Text,
_githubPrivateKeySecretName :: Text,
_appId :: GHAppId
}
deriving stock (Generic)
| |
80cf67499c5b6cf996841e6a2c36a419efa4c166b141fed151f4292fd4a75403 | johnwhitington/ocamli | exercise03.ml | let rec parts x =
if x < 0. then
let a, b = parts (-. x) in
(-. a, b)
else
(floor x, x -. floor x)
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/OCaml%20from%20the%20Very%20Beginning/Chapter%2014/exercise03.ml | ocaml | let rec parts x =
if x < 0. then
let a, b = parts (-. x) in
(-. a, b)
else
(floor x, x -. floor x)
| |
4acecee4d066b167cea53a5c8acbd8a31e1d6f82682bc5aaa2df5c964688333f | reborg/clojure-essential-reference | 5.clj | < 1 >
;; => [0 2 4 6 8]
(let [r (range 100)]
< 2 >
Execution time mean : 1.605351 µs | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Vectors/mapv/5.clj | clojure | => [0 2 4 6 8] | < 1 >
(let [r (range 100)]
< 2 >
Execution time mean : 1.605351 µs |
d355e92d80ac8d0b6b1fd160e54f3c77b477f408dd5658bae747ea2619319145 | ocaml-multicore/effects-examples | MVar.ml | module type S = sig
type 'a t
val create : 'a -> 'a t
val create_empty : unit -> 'a t
val put : 'a -> 'a t -> unit
val take : 'a t -> 'a
end
module type SCHED = sig
type 'a cont
type _ Effect.t += Suspend : ('a cont -> unit) -> 'a Effect.t
type _ Effect.t += Resume : ('a cont * 'a) -> unit Effect.t
end
module Make (S : SCHED) : S = struct
open Effect
(** The state of mvar is either [Full v q] filled with value [v] and a queue
[q] of threads waiting to fill the mvar, or [Empty q], with a queue [q] of
threads waiting to empty the mvar. *)
type 'a mv_state =
| Full of 'a * ('a * unit S.cont) Queue.t
| Empty of 'a S.cont Queue.t
type 'a t = 'a mv_state ref
let create_empty () = ref (Empty (Queue.create ()))
let create v = ref (Full (v, Queue.create ()))
let suspend f = perform @@ S.Suspend f
let resume (a,b) = perform @@ S.Resume (a,b)
let put v mv =
match !mv with
| Full (v', q) -> suspend (fun k -> Queue.push (v,k) q)
| Empty q ->
if Queue.is_empty q then
mv := Full (v, Queue.create ())
else
let t = Queue.pop q in
resume (t, v)
let take mv =
match !mv with
| Empty q -> suspend (fun k -> Queue.push k q)
| Full (v, q) ->
if Queue.is_empty q then
(mv := Empty (Queue.create ()); v)
else
let (v', t) = Queue.pop q in
(mv := Full (v', q);
resume (t, ());
v)
end
| null | https://raw.githubusercontent.com/ocaml-multicore/effects-examples/4f07e1774b726eec0f6769da0a16b402582d37b5/mvar/MVar.ml | ocaml | * The state of mvar is either [Full v q] filled with value [v] and a queue
[q] of threads waiting to fill the mvar, or [Empty q], with a queue [q] of
threads waiting to empty the mvar. | module type S = sig
type 'a t
val create : 'a -> 'a t
val create_empty : unit -> 'a t
val put : 'a -> 'a t -> unit
val take : 'a t -> 'a
end
module type SCHED = sig
type 'a cont
type _ Effect.t += Suspend : ('a cont -> unit) -> 'a Effect.t
type _ Effect.t += Resume : ('a cont * 'a) -> unit Effect.t
end
module Make (S : SCHED) : S = struct
open Effect
type 'a mv_state =
| Full of 'a * ('a * unit S.cont) Queue.t
| Empty of 'a S.cont Queue.t
type 'a t = 'a mv_state ref
let create_empty () = ref (Empty (Queue.create ()))
let create v = ref (Full (v, Queue.create ()))
let suspend f = perform @@ S.Suspend f
let resume (a,b) = perform @@ S.Resume (a,b)
let put v mv =
match !mv with
| Full (v', q) -> suspend (fun k -> Queue.push (v,k) q)
| Empty q ->
if Queue.is_empty q then
mv := Full (v, Queue.create ())
else
let t = Queue.pop q in
resume (t, v)
let take mv =
match !mv with
| Empty q -> suspend (fun k -> Queue.push k q)
| Full (v, q) ->
if Queue.is_empty q then
(mv := Empty (Queue.create ()); v)
else
let (v', t) = Queue.pop q in
(mv := Full (v', q);
resume (t, ());
v)
end
|
942570d2fa4cde9f90cf7488cb0dad1d67967dd2418a62ea8654550d573c6c92 | pedestal/pedestal | immutant_test.clj | (ns io.pedestal.http.immutant-test
(:use clojure.test
io.pedestal.http.immutant)
(:require [clj-http.client :as http]
[clojure.edn]
[io.pedestal.interceptor.helpers :refer [defhandler handler]]
[io.pedestal.http.servlet :as servlet]
[io.pedestal.http.impl.servlet-interceptor :as servlet-interceptor])
(:import (java.nio ByteBuffer)
(java.nio.channels Pipe)))
(defhandler hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defhandler hello-bytebuffer [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body (ByteBuffer/wrap (.getBytes "Hello World" "UTF-8"))})
(defhandler hello-bytechannel [request]
(let [p (Pipe/open)
b (ByteBuffer/wrap (.getBytes "Hello World" "UTF-8"))
sink (.sink p)]
(.write sink b)
(.close sink)
{:status 200
:headers {"Content-Type" "text/plain"}
:body (.source p)}))
(defn content-type-handler [content-type]
(handler
(fn [_]
{:status 200
:headers {"Content-Type" content-type}
:body ""})))
(defhandler echo-handler [request]
{:status 200
:headers {"request-map" (str (dissoc request
:body
:servlet
:servlet-request
:servlet-response
:servlet-context
:pedestal.http.impl.servlet-interceptor/protocol
:pedestal.http.impl.servlet-interceptor/async-supported?))}
:body (:body request)})
(defn immutant-server
[app options]
(server {:io.pedestal.http/servlet (servlet/servlet :service (servlet-interceptor/http-interceptor-service-fn [app]))}
(assoc options :join? false)))
(defmacro with-server [app options & body]
`(let [server# (immutant-server ~app ~options)]
(try
((:start-fn server#))
~@body
(finally ((:stop-fn server#))))))
(deftest test-run-immutant
(testing "HTTP server"
(with-server hello-world {:port 4347}
(let [response (http/get ":4347")]
(is (= (:status response) 200))
(is (.startsWith ^String (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server hello-world {:port 4347
:container-options {:ssl-port 4348
:keystore "test/io/pedestal/http/keystore.jks"
:key-password "password"}}
(let [response (http/get ":4348" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "default character encoding"
(with-server (content-type-handler "text/plain") {:port 4347}
(let [response (http/get ":4347")]
(is (.contains
^String (get-in response [:headers "content-type"])
"text/plain")))))
(testing "custom content-type"
(with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347}
(let [response (http/get ":4347")]
(is (= (into #{} (.split (get-in response [:headers "content-type"]) ";"))
#{"charset=UTF-16" "version=1" "text/plain"})))))
(testing "request translation"
(with-server echo-handler {:port 4347}
(let [response (http/get ":4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))
(let [request-map (clojure.edn/read-string
(get-in response [:headers "request-map"]))]
(is (= (:query-string request-map) "surname=jones&age=123"))
(is (= (:uri request-map) "/foo/bar/baz"))
This are no longer part of the Ring Spec , and are removed from the base request protocol
( is (= (: content - length request - map ) 5 ) )
( is (= (: character - encoding request - map ) " UTF-8 " ) )
(is (= (:request-method request-map) :get))
;(is (= (:content-type request-map) "text/plain; charset=UTF-8"))
(is (= (:remote-addr request-map) "127.0.0.1"))
(is (= (:scheme request-map) :http))
(is (= (:server-name request-map) "localhost"))
(is (= (:server-port request-map) 4347))
(is (= (:ssl-client-cert request-map) nil))))))
(testing "supports NIO Async via ByteBuffers"
(with-server hello-bytebuffer {:port 4347}
(let [response (http/get ":4347")]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "supports NIO Async via ReadableByteChannel"
(with-server hello-bytechannel {:port 4347}
(let [response (http/get ":4347")]
(is (= (:status response) 200))
(is (= (:body response) "Hello World"))))))
| null | https://raw.githubusercontent.com/pedestal/pedestal/53bfe70143a22cdfd2f0d183023334a199c9e9a2/tests/test/io/pedestal/http/immutant_test.clj | clojure | (is (= (:content-type request-map) "text/plain; charset=UTF-8")) | (ns io.pedestal.http.immutant-test
(:use clojure.test
io.pedestal.http.immutant)
(:require [clj-http.client :as http]
[clojure.edn]
[io.pedestal.interceptor.helpers :refer [defhandler handler]]
[io.pedestal.http.servlet :as servlet]
[io.pedestal.http.impl.servlet-interceptor :as servlet-interceptor])
(:import (java.nio ByteBuffer)
(java.nio.channels Pipe)))
(defhandler hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defhandler hello-bytebuffer [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body (ByteBuffer/wrap (.getBytes "Hello World" "UTF-8"))})
(defhandler hello-bytechannel [request]
(let [p (Pipe/open)
b (ByteBuffer/wrap (.getBytes "Hello World" "UTF-8"))
sink (.sink p)]
(.write sink b)
(.close sink)
{:status 200
:headers {"Content-Type" "text/plain"}
:body (.source p)}))
(defn content-type-handler [content-type]
(handler
(fn [_]
{:status 200
:headers {"Content-Type" content-type}
:body ""})))
(defhandler echo-handler [request]
{:status 200
:headers {"request-map" (str (dissoc request
:body
:servlet
:servlet-request
:servlet-response
:servlet-context
:pedestal.http.impl.servlet-interceptor/protocol
:pedestal.http.impl.servlet-interceptor/async-supported?))}
:body (:body request)})
(defn immutant-server
[app options]
(server {:io.pedestal.http/servlet (servlet/servlet :service (servlet-interceptor/http-interceptor-service-fn [app]))}
(assoc options :join? false)))
(defmacro with-server [app options & body]
`(let [server# (immutant-server ~app ~options)]
(try
((:start-fn server#))
~@body
(finally ((:stop-fn server#))))))
(deftest test-run-immutant
(testing "HTTP server"
(with-server hello-world {:port 4347}
(let [response (http/get ":4347")]
(is (= (:status response) 200))
(is (.startsWith ^String (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server hello-world {:port 4347
:container-options {:ssl-port 4348
:keystore "test/io/pedestal/http/keystore.jks"
:key-password "password"}}
(let [response (http/get ":4348" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "default character encoding"
(with-server (content-type-handler "text/plain") {:port 4347}
(let [response (http/get ":4347")]
(is (.contains
^String (get-in response [:headers "content-type"])
"text/plain")))))
(testing "custom content-type"
(with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347}
(let [response (http/get ":4347")]
(is (= (into #{} (.split (get-in response [:headers "content-type"]) ";"))
#{"charset=UTF-16" "version=1" "text/plain"})))))
(testing "request translation"
(with-server echo-handler {:port 4347}
(let [response (http/get ":4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))
(let [request-map (clojure.edn/read-string
(get-in response [:headers "request-map"]))]
(is (= (:query-string request-map) "surname=jones&age=123"))
(is (= (:uri request-map) "/foo/bar/baz"))
This are no longer part of the Ring Spec , and are removed from the base request protocol
( is (= (: content - length request - map ) 5 ) )
( is (= (: character - encoding request - map ) " UTF-8 " ) )
(is (= (:request-method request-map) :get))
(is (= (:remote-addr request-map) "127.0.0.1"))
(is (= (:scheme request-map) :http))
(is (= (:server-name request-map) "localhost"))
(is (= (:server-port request-map) 4347))
(is (= (:ssl-client-cert request-map) nil))))))
(testing "supports NIO Async via ByteBuffers"
(with-server hello-bytebuffer {:port 4347}
(let [response (http/get ":4347")]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "supports NIO Async via ReadableByteChannel"
(with-server hello-bytechannel {:port 4347}
(let [response (http/get ":4347")]
(is (= (:status response) 200))
(is (= (:body response) "Hello World"))))))
|
38289af9c795dfe945b4809f0dcd20cc05bf890d7cc64b7d422f24cc900cf726 | rbkmoney/consuela | consuela_presence_server.erl | %%%
%%% Presence server
%%%
A simple TCP server which only purpose is to service Consul .
-module(consuela_presence_server).
%%
-type ref() :: _.
-type transport_opts() :: ranch:opts().
-type opts() :: #{
transport_opts => transport_opts(),
pulse => {module(), _PulseOpts}
}.
-export([child_spec/2]).
-export([get_endpoint/1]).
-export_type([ref/0]).
-export_type([transport_opts/0]).
-export_type([opts/0]).
%%
-behaviour(ranch_protocol).
-export([start_link/4]).
-export([init/4]).
%%
-type beat() ::
{{socket, {module(), inet:socket()}}, accepted}.
-export_type([beat/0]).
-callback handle_beat(beat(), _PulseOpts) ->
_.
-export([handle_beat/2]).
%%
-spec child_spec(_Ref, opts()) ->
supervisor:child_spec().
child_spec(Ref, Opts) ->
ranch:child_spec(
{?MODULE, Ref},
ranch_tcp,
maps:get(transport_opts, Opts, #{}),
?MODULE,
mk_state(Opts)
).
-spec get_endpoint(_Ref) ->
{ok, consuela_health:endpoint()} | {error, undefined}.
get_endpoint(Ref) ->
case ranch:get_addr({?MODULE, Ref}) of
{IP, Port} when is_tuple(IP), is_integer(Port) ->
{ok, {IP, Port}};
{undefined, _} ->
{error, undefined}
end.
%%
-type st() :: #{
pulse := {module(), _PulseOpts}
}.
-spec mk_state(opts()) ->
st().
mk_state(Opts) ->
#{
pulse => maps:get(pulse, Opts, {?MODULE, []})
}.
-spec start_link(pid(), inet:socket(), module(), st()) ->
{ok, pid()}.
start_link(ListenerPid, Socket, Transport, St) ->
Pid = spawn_link(?MODULE, init, [ListenerPid, Socket, Transport, St]),
{ok, Pid}.
-spec init(pid(), inet:socket(), module(), st()) ->
_.
init(ListenerPid, Socket, Transport, St) ->
{ok, _} = ranch:handshake(ListenerPid),
_ = beat({{socket, {Transport, Socket}}, accepted}, St),
ok = Transport:close(Socket),
ok.
%%
-spec beat(beat(), st()) ->
_.
beat(Beat, #{pulse := {Module, PulseOpts}}) ->
TODO handle errors ?
Module:handle_beat(Beat, PulseOpts).
-spec handle_beat(beat(), [trace]) ->
ok.
handle_beat(Beat, [trace]) ->
logger:debug("[~p] ~p", [?MODULE, Beat]);
handle_beat(_Beat, []) ->
ok.
| null | https://raw.githubusercontent.com/rbkmoney/consuela/d11610295be5ed5c4b6c0b2ba259a35d5e00b29c/src/consuela_presence_server.erl | erlang |
Presence server
| A simple TCP server which only purpose is to service Consul .
-module(consuela_presence_server).
-type ref() :: _.
-type transport_opts() :: ranch:opts().
-type opts() :: #{
transport_opts => transport_opts(),
pulse => {module(), _PulseOpts}
}.
-export([child_spec/2]).
-export([get_endpoint/1]).
-export_type([ref/0]).
-export_type([transport_opts/0]).
-export_type([opts/0]).
-behaviour(ranch_protocol).
-export([start_link/4]).
-export([init/4]).
-type beat() ::
{{socket, {module(), inet:socket()}}, accepted}.
-export_type([beat/0]).
-callback handle_beat(beat(), _PulseOpts) ->
_.
-export([handle_beat/2]).
-spec child_spec(_Ref, opts()) ->
supervisor:child_spec().
child_spec(Ref, Opts) ->
ranch:child_spec(
{?MODULE, Ref},
ranch_tcp,
maps:get(transport_opts, Opts, #{}),
?MODULE,
mk_state(Opts)
).
-spec get_endpoint(_Ref) ->
{ok, consuela_health:endpoint()} | {error, undefined}.
get_endpoint(Ref) ->
case ranch:get_addr({?MODULE, Ref}) of
{IP, Port} when is_tuple(IP), is_integer(Port) ->
{ok, {IP, Port}};
{undefined, _} ->
{error, undefined}
end.
-type st() :: #{
pulse := {module(), _PulseOpts}
}.
-spec mk_state(opts()) ->
st().
mk_state(Opts) ->
#{
pulse => maps:get(pulse, Opts, {?MODULE, []})
}.
-spec start_link(pid(), inet:socket(), module(), st()) ->
{ok, pid()}.
start_link(ListenerPid, Socket, Transport, St) ->
Pid = spawn_link(?MODULE, init, [ListenerPid, Socket, Transport, St]),
{ok, Pid}.
-spec init(pid(), inet:socket(), module(), st()) ->
_.
init(ListenerPid, Socket, Transport, St) ->
{ok, _} = ranch:handshake(ListenerPid),
_ = beat({{socket, {Transport, Socket}}, accepted}, St),
ok = Transport:close(Socket),
ok.
-spec beat(beat(), st()) ->
_.
beat(Beat, #{pulse := {Module, PulseOpts}}) ->
TODO handle errors ?
Module:handle_beat(Beat, PulseOpts).
-spec handle_beat(beat(), [trace]) ->
ok.
handle_beat(Beat, [trace]) ->
logger:debug("[~p] ~p", [?MODULE, Beat]);
handle_beat(_Beat, []) ->
ok.
|
285b8585ce38e33af086260cd87c95fe1bc10bf80753fbc2608c1d7485923f1e | lambdaisland/souk | setup.clj | (ns lambdaisland.souk.setup
(:require [lambdaisland.webbing.config :as config]
[clojure.java.io :as io]))
(def project 'lambdaisland/souk)
(def start-keys #{:http/server})
(def schemas
{:settings [[:port int?]
[:dev/reload-routes? boolean?]]
:secrets []})
(defn proj-resource [path]
(io/resource (str project "/" path)))
(defn prod-setup []
{:schemas schemas
:keys start-keys
:sources {:config [(proj-resource "config.edn")]
:secrets [(config/cli-args)
(config/env)]
:settings [(config/cli-args)
(config/env)
(config/default-value)
(proj-resource "settings-prod.edn")
(proj-resource "settings.edn")]}})
(defn dev-setup []
(let [local-file (io/file "config.local.edn")
local-config (when (.exists local-file)
(read-string (slurp local-file)))]
{:schemas schemas
:keys (:dev/start-keys local-config start-keys)
:sources {:config [(proj-resource "config.edn")
(dissoc local-config :dev/start-keys)]
:secrets [(config/dotenv)
(config/env)
(config/default-value)]
:settings [(config/dotenv)
(config/env)
(config/default-value)
(proj-resource "settings-dev.edn")
(proj-resource "settings.edn")]}}))
| null | https://raw.githubusercontent.com/lambdaisland/souk/bf25b247d989358af9a1a00f294d4de2a9c2d59c/src/lambdaisland/souk/setup.clj | clojure | (ns lambdaisland.souk.setup
(:require [lambdaisland.webbing.config :as config]
[clojure.java.io :as io]))
(def project 'lambdaisland/souk)
(def start-keys #{:http/server})
(def schemas
{:settings [[:port int?]
[:dev/reload-routes? boolean?]]
:secrets []})
(defn proj-resource [path]
(io/resource (str project "/" path)))
(defn prod-setup []
{:schemas schemas
:keys start-keys
:sources {:config [(proj-resource "config.edn")]
:secrets [(config/cli-args)
(config/env)]
:settings [(config/cli-args)
(config/env)
(config/default-value)
(proj-resource "settings-prod.edn")
(proj-resource "settings.edn")]}})
(defn dev-setup []
(let [local-file (io/file "config.local.edn")
local-config (when (.exists local-file)
(read-string (slurp local-file)))]
{:schemas schemas
:keys (:dev/start-keys local-config start-keys)
:sources {:config [(proj-resource "config.edn")
(dissoc local-config :dev/start-keys)]
:secrets [(config/dotenv)
(config/env)
(config/default-value)]
:settings [(config/dotenv)
(config/env)
(config/default-value)
(proj-resource "settings-dev.edn")
(proj-resource "settings.edn")]}}))
| |
5d852b95cfa770365e15b5d126e0237f73babbc2a7cc657e6af8afef9ddb38d8 | dhleong/wish | overlay.cljs | (ns wish.views.overlay
(:require [garden.color :as color]
[spade.core :refer [defclass]]
[wish.style.flex :as flex]
[wish.style.media :as media]
[wish.style.shared :as shared]
[wish.util :refer [<sub click>evt]]
[wish.views.widgets :refer-macros [icon]]
[wish.views.widgets.error-boundary :refer [error-boundary]]))
(defclass overlay-class []
(merge flex/vertical-center
flex/align-center
{:position :fixed
:top 0
:left 0
:right 0
:bottom 0
:height :100%
:z-index 1
:background-color (color/transparentize "#333" 0.2)})
(at-media media/smartphones
[:& {:justify-content :flex-start}]))
(defclass overlay-inner-base []
{:position :relative
:background "#f0f0f0"
:border-radius "2px"
:max-width "80%"}
(at-media media/dark-scheme
[:& {:background "#444"}])
(at-media media/smartphones
[:& {:width "85%"
:max-width "85%"
:height [[:100% :!important]]
:max-height [[:100% :!important]]}
; Override padding and dimensions on mobile:
[:.wrapper>:first-child {:padding "16px"
:width [[:100% :!important]]}]])
[:.close-button (merge shared/clickable
{:position :absolute
:top "4px"
:right "4px"}) ]
[:.wrapper (merge flex/flex
flex/justify-center
{:height :100%
:margin-top "8px"})])
(defclass overlay-inner []
{:composes (overlay-inner-base)
:max-height :80%
:overflow-y :auto})
(defclass overlay-inner-scrollable []
{:composes (overlay-inner-base)
:height :80%}
[:.scroll-host {:height :100%
:overflow-y :auto}])
(defn overlay []
(when-let [[{:keys [scrollable?]} overlay-spec] (<sub [:showing-overlay])]
[:div
{:class (overlay-class)
:on-click (click>evt [:toggle-overlay])}
[:div
{:class (if scrollable?
(overlay-inner-scrollable)
(overlay-inner))
:on-click (fn [e]
; prevent click propagation by default
; to avoid the event leaking through and
; triggering the dismiss click on the bg
(.stopPropagation e))}
[:div.close-button
{:on-click (click>evt [:toggle-overlay])}
(icon :close)]
; finally, the overlay itself
[:div.scroll-host
[:div.wrapper
[error-boundary
overlay-spec]]]]]))
| null | https://raw.githubusercontent.com/dhleong/wish/2bfd9b0d5867f1e268733bc9eae02d24bec95020/src/cljs/wish/views/overlay.cljs | clojure | Override padding and dimensions on mobile:
prevent click propagation by default
to avoid the event leaking through and
triggering the dismiss click on the bg
finally, the overlay itself | (ns wish.views.overlay
(:require [garden.color :as color]
[spade.core :refer [defclass]]
[wish.style.flex :as flex]
[wish.style.media :as media]
[wish.style.shared :as shared]
[wish.util :refer [<sub click>evt]]
[wish.views.widgets :refer-macros [icon]]
[wish.views.widgets.error-boundary :refer [error-boundary]]))
(defclass overlay-class []
(merge flex/vertical-center
flex/align-center
{:position :fixed
:top 0
:left 0
:right 0
:bottom 0
:height :100%
:z-index 1
:background-color (color/transparentize "#333" 0.2)})
(at-media media/smartphones
[:& {:justify-content :flex-start}]))
(defclass overlay-inner-base []
{:position :relative
:background "#f0f0f0"
:border-radius "2px"
:max-width "80%"}
(at-media media/dark-scheme
[:& {:background "#444"}])
(at-media media/smartphones
[:& {:width "85%"
:max-width "85%"
:height [[:100% :!important]]
:max-height [[:100% :!important]]}
[:.wrapper>:first-child {:padding "16px"
:width [[:100% :!important]]}]])
[:.close-button (merge shared/clickable
{:position :absolute
:top "4px"
:right "4px"}) ]
[:.wrapper (merge flex/flex
flex/justify-center
{:height :100%
:margin-top "8px"})])
(defclass overlay-inner []
{:composes (overlay-inner-base)
:max-height :80%
:overflow-y :auto})
(defclass overlay-inner-scrollable []
{:composes (overlay-inner-base)
:height :80%}
[:.scroll-host {:height :100%
:overflow-y :auto}])
(defn overlay []
(when-let [[{:keys [scrollable?]} overlay-spec] (<sub [:showing-overlay])]
[:div
{:class (overlay-class)
:on-click (click>evt [:toggle-overlay])}
[:div
{:class (if scrollable?
(overlay-inner-scrollable)
(overlay-inner))
:on-click (fn [e]
(.stopPropagation e))}
[:div.close-button
{:on-click (click>evt [:toggle-overlay])}
(icon :close)]
[:div.scroll-host
[:div.wrapper
[error-boundary
overlay-spec]]]]]))
|
e9c4bccf725b8e0b308601f416997d2cb5fafd8b832ba9780bafabdf50facd7e | mput/sicp-solutions | 2_41.test.rkt | #lang racket
(require rackunit/text-ui)
(require rackunit "custom-checks.rkt")
(require rackunit "../solutions/2_41.rkt")
(define tests
(test-suite
"Test for exercise 2_41"
(test-case
"Case here"
(define sol-list (list (list 3 2 5) (list 4 1 5)))
(check-equal? (sum-pairs 4 5) sol-list))))
(run-tests tests 'verbose)
| null | https://raw.githubusercontent.com/mput/sicp-solutions/fe12ad2b6f17c99978c8fe04b2495005986b8496/tests/2_41.test.rkt | racket | #lang racket
(require rackunit/text-ui)
(require rackunit "custom-checks.rkt")
(require rackunit "../solutions/2_41.rkt")
(define tests
(test-suite
"Test for exercise 2_41"
(test-case
"Case here"
(define sol-list (list (list 3 2 5) (list 4 1 5)))
(check-equal? (sum-pairs 4 5) sol-list))))
(run-tests tests 'verbose)
| |
12af85ce6da57c8cb81c4a9950663f4f91332ff8fe8c09cdaa46f797258e24b2 | zk/clojuredocs | data.clj | (ns clojuredocs.data
(:require [somnium.congomongo :as mon]))
;; Examples
(defn find-examples-for [{:keys [ns name library-url]}]
(mon/fetch :examples
:where {:var.name name
:var.ns ns
:var.library-url library-url
:deleted-at nil}
:sort {:created-at 1}))
Notes
(defn find-notes-for [{:keys [ns name library-url]}]
(mon/fetch :notes
:where {:var.ns ns
:var.name name
:var.library-url library-url}
:sort {:created-at 1}))
;; See Alsos
(defn find-see-alsos-for [{:keys [ns name library-url]}]
(mon/fetch :see-alsos
:where {:from-var.name name
:from-var.ns ns
:from-var.library-url library-url}))
| null | https://raw.githubusercontent.com/zk/clojuredocs/28f5ee500f4349039ee81c70d7ac40acbb19e5d8/src/clj/clojuredocs/data.clj | clojure | Examples
See Alsos | (ns clojuredocs.data
(:require [somnium.congomongo :as mon]))
(defn find-examples-for [{:keys [ns name library-url]}]
(mon/fetch :examples
:where {:var.name name
:var.ns ns
:var.library-url library-url
:deleted-at nil}
:sort {:created-at 1}))
Notes
(defn find-notes-for [{:keys [ns name library-url]}]
(mon/fetch :notes
:where {:var.ns ns
:var.name name
:var.library-url library-url}
:sort {:created-at 1}))
(defn find-see-alsos-for [{:keys [ns name library-url]}]
(mon/fetch :see-alsos
:where {:from-var.name name
:from-var.ns ns
:from-var.library-url library-url}))
|
80c79eff8439418c087bace70c373e70df6179b6d96ad9af9bbfc692a7ae3ed3 | juspay/atlas | Fcm.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Types . API.Fcm
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Types.API.Fcm
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Types.API.Fcm where
import Beckn.External.FCM.Types
import Servant
type ReadFcmAPI =
"read"
:> Capture "token" FCMRecipientToken
:> Get '[JSON] ReadFcmRes
type ReadFcmRes = [FCMMessage]
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/mock-fcm/src/Types/API/Fcm.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Types . API.Fcm
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Types.API.Fcm
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Types.API.Fcm where
import Beckn.External.FCM.Types
import Servant
type ReadFcmAPI =
"read"
:> Capture "token" FCMRecipientToken
:> Get '[JSON] ReadFcmRes
type ReadFcmRes = [FCMMessage]
| |
088bf7d41da5ffaf7b00bfc416ee0a6516049890bf9df36e4b2a667440ff4b58 | michaelballantyne/syntax-spec | state-machine.rkt | #lang racket
(provide machine state on)
(require syntax-spec "state-machine-compiler.rkt")
(syntax-spec
(binding-class state-name)
(nonterminal/two-pass state-spec
(state name:state-name
((~datum on-enter) action:expr ...)
e:event-spec ...)
#:binding (export name))
(nonterminal event-spec
(on (name:id arg:id ...)
action:expr ...
((~datum ->) new-name:state-name)))
(host-interface/expression
(machine #:initial-state init:state-name
#:states s:state-spec ...
#:shared-events e:event-spec ...)
#:binding { (recursive s) init e }
#'(compile-machine (machine #:initial-state init
#:states s ...
#:shared-events e ...)))) | null | https://raw.githubusercontent.com/michaelballantyne/syntax-spec/0a9d7599afb2f90a6dcfd45e625d117191a85b3d/demos/strumienta-talk/csv-demo/state-machine.rkt | racket | #lang racket
(provide machine state on)
(require syntax-spec "state-machine-compiler.rkt")
(syntax-spec
(binding-class state-name)
(nonterminal/two-pass state-spec
(state name:state-name
((~datum on-enter) action:expr ...)
e:event-spec ...)
#:binding (export name))
(nonterminal event-spec
(on (name:id arg:id ...)
action:expr ...
((~datum ->) new-name:state-name)))
(host-interface/expression
(machine #:initial-state init:state-name
#:states s:state-spec ...
#:shared-events e:event-spec ...)
#:binding { (recursive s) init e }
#'(compile-machine (machine #:initial-state init
#:states s ...
#:shared-events e ...)))) | |
dc370bd458da024fbb21a200b0c457a4d6e0e1c84a106c8f084f3fc25c9053ba | machine-intelligence/provability | Programs.hs | module Modal.Programs where
import Modal.Formulas
import Modal.GameTools
import Modal.Programming
import Modal.Utilities
generalUDT :: Eq a => [Int] -> [u] -> [a] -> a -> ModalProgram a (U1 u a)
generalUDT levels uorder aorder dflt = completeProgram dflt mainLoop where
mainLoop = mFor (zip levels uaPairs) (uncurry checkUApair)
uaPairs = [(u, a) | u <- uorder, a <- aorder]
checkUApair n (u, a) = mIf (boxk n (Var (U1A a) %> Var (U1 u))) (mReturn a)
escalatingUDT :: (Eq a, Enum a, Enum u) => [Int] -> a -> ModalProgram a (U1 u a)
escalatingUDT levels = generalUDT levels enumerate enumerate
udtN :: (Eq a, Enum a, Enum u) => Int -> a -> ModalProgram a (U1 u a)
udtN level = generalUDT (repeat level) enumerate enumerate
udt' :: Eq a => [u] -> [a] -> a -> ModalProgram a (U1 u a)
udt' = generalUDT (repeat 0)
udt :: (Eq a, Enum a, Enum u) => a -> ModalProgram a (U1 u a)
udt = udtN 0
| null | https://raw.githubusercontent.com/machine-intelligence/provability/12d981dfe7d0420b06f5548e96afc3f39f338d26/src/Modal/Programs.hs | haskell | module Modal.Programs where
import Modal.Formulas
import Modal.GameTools
import Modal.Programming
import Modal.Utilities
generalUDT :: Eq a => [Int] -> [u] -> [a] -> a -> ModalProgram a (U1 u a)
generalUDT levels uorder aorder dflt = completeProgram dflt mainLoop where
mainLoop = mFor (zip levels uaPairs) (uncurry checkUApair)
uaPairs = [(u, a) | u <- uorder, a <- aorder]
checkUApair n (u, a) = mIf (boxk n (Var (U1A a) %> Var (U1 u))) (mReturn a)
escalatingUDT :: (Eq a, Enum a, Enum u) => [Int] -> a -> ModalProgram a (U1 u a)
escalatingUDT levels = generalUDT levels enumerate enumerate
udtN :: (Eq a, Enum a, Enum u) => Int -> a -> ModalProgram a (U1 u a)
udtN level = generalUDT (repeat level) enumerate enumerate
udt' :: Eq a => [u] -> [a] -> a -> ModalProgram a (U1 u a)
udt' = generalUDT (repeat 0)
udt :: (Eq a, Enum a, Enum u) => a -> ModalProgram a (U1 u a)
udt = udtN 0
| |
1d2409253eeaab5f3924b50f18a9d85fad56068d76b74a750d5499c61e726757 | tmattio/js-bindings | node_process.ml | [@@@js.dummy "!! This code has been generated by gen_js_api !!"]
[@@@ocaml.warning "-7-32-39"]
[@@@ocaml.warning "-7-11-32-33-39"]
open Es2020
open Node_globals
module AnonymousInterface0 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2
and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1
end
module AnonymousInterface1 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x4 : Ojs.t) -> x4
and t_to_js : t -> Ojs.t = fun (x3 : Ojs.t) -> x3
let (cflags : t -> any list) =
fun (x5 : t) ->
Ojs.list_of_js any_of_js (Ojs.get_prop_ascii (t_to_js x5) "cflags")
let (set_cflags : t -> any list -> unit) =
fun (x7 : t) ->
fun (x8 : any list) ->
Ojs.set_prop_ascii (t_to_js x7) "cflags"
(Ojs.list_to_js any_to_js x8)
let (default_configuration : t -> string) =
fun (x10 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x10) "default_configuration")
let (set_default_configuration : t -> string -> unit) =
fun (x11 : t) ->
fun (x12 : string) ->
Ojs.set_prop_ascii (t_to_js x11) "default_configuration"
(Ojs.string_to_js x12)
let (defines : t -> string list) =
fun (x13 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x13) "defines")
let (set_defines : t -> string list -> unit) =
fun (x15 : t) ->
fun (x16 : string list) ->
Ojs.set_prop_ascii (t_to_js x15) "defines"
(Ojs.list_to_js Ojs.string_to_js x16)
let (include_dirs : t -> string list) =
fun (x18 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x18) "include_dirs")
let (set_include_dirs : t -> string list -> unit) =
fun (x20 : t) ->
fun (x21 : string list) ->
Ojs.set_prop_ascii (t_to_js x20) "include_dirs"
(Ojs.list_to_js Ojs.string_to_js x21)
let (libraries : t -> string list) =
fun (x23 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x23) "libraries")
let (set_libraries : t -> string list -> unit) =
fun (x25 : t) ->
fun (x26 : string list) ->
Ojs.set_prop_ascii (t_to_js x25) "libraries"
(Ojs.list_to_js Ojs.string_to_js x26)
end
module AnonymousInterface2 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x29 : Ojs.t) -> x29
and t_to_js : t -> Ojs.t = fun (x28 : Ojs.t) -> x28
let (clang : t -> int) =
fun (x30 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x30) "clang")
let (set_clang : t -> int -> unit) =
fun (x31 : t) ->
fun (x32 : int) ->
Ojs.set_prop_ascii (t_to_js x31) "clang" (Ojs.int_to_js x32)
let (host_arch : t -> string) =
fun (x33 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x33) "host_arch")
let (set_host_arch : t -> string -> unit) =
fun (x34 : t) ->
fun (x35 : string) ->
Ojs.set_prop_ascii (t_to_js x34) "host_arch" (Ojs.string_to_js x35)
let (node_install_npm : t -> bool) =
fun (x36 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x36) "node_install_npm")
let (set_node_install_npm : t -> bool -> unit) =
fun (x37 : t) ->
fun (x38 : bool) ->
Ojs.set_prop_ascii (t_to_js x37) "node_install_npm"
(Ojs.bool_to_js x38)
let (node_install_waf : t -> bool) =
fun (x39 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x39) "node_install_waf")
let (set_node_install_waf : t -> bool -> unit) =
fun (x40 : t) ->
fun (x41 : bool) ->
Ojs.set_prop_ascii (t_to_js x40) "node_install_waf"
(Ojs.bool_to_js x41)
let (node_prefix : t -> string) =
fun (x42 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x42) "node_prefix")
let (set_node_prefix : t -> string -> unit) =
fun (x43 : t) ->
fun (x44 : string) ->
Ojs.set_prop_ascii (t_to_js x43) "node_prefix"
(Ojs.string_to_js x44)
let (node_shared_openssl : t -> bool) =
fun (x45 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x45) "node_shared_openssl")
let (set_node_shared_openssl : t -> bool -> unit) =
fun (x46 : t) ->
fun (x47 : bool) ->
Ojs.set_prop_ascii (t_to_js x46) "node_shared_openssl"
(Ojs.bool_to_js x47)
let (node_shared_v8 : t -> bool) =
fun (x48 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x48) "node_shared_v8")
let (set_node_shared_v8 : t -> bool -> unit) =
fun (x49 : t) ->
fun (x50 : bool) ->
Ojs.set_prop_ascii (t_to_js x49) "node_shared_v8"
(Ojs.bool_to_js x50)
let (node_shared_zlib : t -> bool) =
fun (x51 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x51) "node_shared_zlib")
let (set_node_shared_zlib : t -> bool -> unit) =
fun (x52 : t) ->
fun (x53 : bool) ->
Ojs.set_prop_ascii (t_to_js x52) "node_shared_zlib"
(Ojs.bool_to_js x53)
let (node_use_dtrace : t -> bool) =
fun (x54 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x54) "node_use_dtrace")
let (set_node_use_dtrace : t -> bool -> unit) =
fun (x55 : t) ->
fun (x56 : bool) ->
Ojs.set_prop_ascii (t_to_js x55) "node_use_dtrace"
(Ojs.bool_to_js x56)
let (node_use_etw : t -> bool) =
fun (x57 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x57) "node_use_etw")
let (set_node_use_etw : t -> bool -> unit) =
fun (x58 : t) ->
fun (x59 : bool) ->
Ojs.set_prop_ascii (t_to_js x58) "node_use_etw"
(Ojs.bool_to_js x59)
let (node_use_openssl : t -> bool) =
fun (x60 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x60) "node_use_openssl")
let (set_node_use_openssl : t -> bool -> unit) =
fun (x61 : t) ->
fun (x62 : bool) ->
Ojs.set_prop_ascii (t_to_js x61) "node_use_openssl"
(Ojs.bool_to_js x62)
let (tararch : t -> string) =
fun (x63 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x63) "tararch")
let (set_tararch : t -> string -> unit) =
fun (x64 : t) ->
fun (x65 : string) ->
Ojs.set_prop_ascii (t_to_js x64) "tararch" (Ojs.string_to_js x65)
let (v8_no_strict_aliasing : t -> int) =
fun (x66 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x66) "v8_no_strict_aliasing")
let (set_v8_no_strict_aliasing : t -> int -> unit) =
fun (x67 : t) ->
fun (x68 : int) ->
Ojs.set_prop_ascii (t_to_js x67) "v8_no_strict_aliasing"
(Ojs.int_to_js x68)
let (v8_use_snapshot : t -> bool) =
fun (x69 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x69) "v8_use_snapshot")
let (set_v8_use_snapshot : t -> bool -> unit) =
fun (x70 : t) ->
fun (x71 : bool) ->
Ojs.set_prop_ascii (t_to_js x70) "v8_use_snapshot"
(Ojs.bool_to_js x71)
let (visibility : t -> string) =
fun (x72 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x72) "visibility")
let (set_visibility : t -> string -> unit) =
fun (x73 : t) ->
fun (x74 : string) ->
Ojs.set_prop_ascii (t_to_js x73) "visibility"
(Ojs.string_to_js x74)
end
module AnonymousInterface3 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x76 : Ojs.t) -> x76
and t_to_js : t -> Ojs.t = fun (x75 : Ojs.t) -> x75
let (fd : t -> [ `L_n_0 ]) =
fun (x77 : t) ->
let x78 = Ojs.get_prop_ascii (t_to_js x77) "fd" in
match Ojs.int_of_js x78 with | 0 -> `L_n_0 | _ -> assert false
let (set_fd : t -> [ `L_n_0 ] -> unit) =
fun (x79 : t) ->
fun (x80 : [ `L_n_0 ]) ->
Ojs.set_prop_ascii (t_to_js x79) "fd"
(match x80 with | `L_n_0 -> Ojs.string_to_js "LN0")
end
module AnonymousInterface4 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x82 : Ojs.t) -> x82
and t_to_js : t -> Ojs.t = fun (x81 : Ojs.t) -> x81
let (fd : t -> [ `L_n_1 ]) =
fun (x83 : t) ->
let x84 = Ojs.get_prop_ascii (t_to_js x83) "fd" in
match Ojs.int_of_js x84 with | 1 -> `L_n_1 | _ -> assert false
let (set_fd : t -> [ `L_n_1 ] -> unit) =
fun (x85 : t) ->
fun (x86 : [ `L_n_1 ]) ->
Ojs.set_prop_ascii (t_to_js x85) "fd"
(match x86 with | `L_n_1 -> Ojs.string_to_js "LN1")
end
module AnonymousInterface5 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x88 : Ojs.t) -> x88
and t_to_js : t -> Ojs.t = fun (x87 : Ojs.t) -> x87
let (fd : t -> [ `L_n_2 ]) =
fun (x89 : t) ->
let x90 = Ojs.get_prop_ascii (t_to_js x89) "fd" in
match Ojs.int_of_js x90 with | 2 -> `L_n_2 | _ -> assert false
let (set_fd : t -> [ `L_n_2 ] -> unit) =
fun (x91 : t) ->
fun (x92 : [ `L_n_2 ]) ->
Ojs.set_prop_ascii (t_to_js x91) "fd"
(match x92 with | `L_n_2 -> Ojs.string_to_js "LN2")
end
module AnonymousInterface6 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x94 : Ojs.t) -> x94
and t_to_js : t -> Ojs.t = fun (x93 : Ojs.t) -> x93
let (inspector : t -> bool) =
fun (x95 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x95) "inspector")
let (set_inspector : t -> bool -> unit) =
fun (x96 : t) ->
fun (x97 : bool) ->
Ojs.set_prop_ascii (t_to_js x96) "inspector" (Ojs.bool_to_js x97)
let (debug : t -> bool) =
fun (x98 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x98) "debug")
let (set_debug : t -> bool -> unit) =
fun (x99 : t) ->
fun (x100 : bool) ->
Ojs.set_prop_ascii (t_to_js x99) "debug" (Ojs.bool_to_js x100)
let (uv : t -> bool) =
fun (x101 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x101) "uv")
let (set_uv : t -> bool -> unit) =
fun (x102 : t) ->
fun (x103 : bool) ->
Ojs.set_prop_ascii (t_to_js x102) "uv" (Ojs.bool_to_js x103)
let (ipv6 : t -> bool) =
fun (x104 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x104) "ipv6")
let (set_ipv6 : t -> bool -> unit) =
fun (x105 : t) ->
fun (x106 : bool) ->
Ojs.set_prop_ascii (t_to_js x105) "ipv6" (Ojs.bool_to_js x106)
let (tls_alpn : t -> bool) =
fun (x107 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x107) "tls_alpn")
let (set_tls_alpn : t -> bool -> unit) =
fun (x108 : t) ->
fun (x109 : bool) ->
Ojs.set_prop_ascii (t_to_js x108) "tls_alpn" (Ojs.bool_to_js x109)
let (tls_sni : t -> bool) =
fun (x110 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x110) "tls_sni")
let (set_tls_sni : t -> bool -> unit) =
fun (x111 : t) ->
fun (x112 : bool) ->
Ojs.set_prop_ascii (t_to_js x111) "tls_sni" (Ojs.bool_to_js x112)
let (tls_ocsp : t -> bool) =
fun (x113 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x113) "tls_ocsp")
let (set_tls_ocsp : t -> bool -> unit) =
fun (x114 : t) ->
fun (x115 : bool) ->
Ojs.set_prop_ascii (t_to_js x114) "tls_ocsp" (Ojs.bool_to_js x115)
let (tls : t -> bool) =
fun (x116 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x116) "tls")
let (set_tls : t -> bool -> unit) =
fun (x117 : t) ->
fun (x118 : bool) ->
Ojs.set_prop_ascii (t_to_js x117) "tls" (Ojs.bool_to_js x118)
end
module AnonymousInterface7 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x120 : Ojs.t) -> x120
and t_to_js : t -> Ojs.t = fun (x119 : Ojs.t) -> x119
let (swallow_errors : t -> bool) =
fun (x121 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x121) "swallowErrors")
let (set_swallow_errors : t -> bool -> unit) =
fun (x122 : t) ->
fun (x123 : bool) ->
Ojs.set_prop_ascii (t_to_js x122) "swallowErrors"
(Ojs.bool_to_js x123)
end
module AnonymousInterface8 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x125 : Ojs.t) -> x125
and t_to_js : t -> Ojs.t = fun (x124 : Ojs.t) -> x124
let (tardefaults : t -> AnonymousInterface1.t) =
fun (x126 : t) ->
AnonymousInterface1.t_of_js
(Ojs.get_prop_ascii (t_to_js x126) "tardefaults")
let (set_tardefaults : t -> AnonymousInterface1.t -> unit) =
fun (x127 : t) ->
fun (x128 : AnonymousInterface1.t) ->
Ojs.set_prop_ascii (t_to_js x127) "tardefaults"
(AnonymousInterface1.t_to_js x128)
let (variables : t -> AnonymousInterface2.t) =
fun (x129 : t) ->
AnonymousInterface2.t_of_js
(Ojs.get_prop_ascii (t_to_js x129) "variables")
let (set_variables : t -> AnonymousInterface2.t -> unit) =
fun (x130 : t) ->
fun (x131 : AnonymousInterface2.t) ->
Ojs.set_prop_ascii (t_to_js x130) "variables"
(AnonymousInterface2.t_to_js x131)
end
module Process =
struct
open Node_tty
module ReadStream = struct include struct include Tty.ReadStream end end
module WriteStream =
struct include struct include Tty.WriteStream end end
module MemoryUsage =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x133 : Ojs.t) -> x133
and t_to_js : t -> Ojs.t = fun (x132 : Ojs.t) -> x132
let (rss : t -> int) =
fun (x134 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x134) "rss")
let (set_rss : t -> int -> unit) =
fun (x135 : t) ->
fun (x136 : int) ->
Ojs.set_prop_ascii (t_to_js x135) "rss" (Ojs.int_to_js x136)
let (heap_total : t -> int) =
fun (x137 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x137) "heapTotal")
let (set_heap_total : t -> int -> unit) =
fun (x138 : t) ->
fun (x139 : int) ->
Ojs.set_prop_ascii (t_to_js x138) "heapTotal"
(Ojs.int_to_js x139)
let (heap_used : t -> int) =
fun (x140 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x140) "heapUsed")
let (set_heap_used : t -> int -> unit) =
fun (x141 : t) ->
fun (x142 : int) ->
Ojs.set_prop_ascii (t_to_js x141) "heapUsed"
(Ojs.int_to_js x142)
let (external_ : t -> int) =
fun (x143 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x143) "external")
let (set_external : t -> int -> unit) =
fun (x144 : t) ->
fun (x145 : int) ->
Ojs.set_prop_ascii (t_to_js x144) "external"
(Ojs.int_to_js x145)
let (array_buffers : t -> int) =
fun (x146 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x146) "arrayBuffers")
let (set_array_buffers : t -> int -> unit) =
fun (x147 : t) ->
fun (x148 : int) ->
Ojs.set_prop_ascii (t_to_js x147) "arrayBuffers"
(Ojs.int_to_js x148)
end
module CpuUsage =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x150 : Ojs.t) -> x150
and t_to_js : t -> Ojs.t = fun (x149 : Ojs.t) -> x149
let (user : t -> int) =
fun (x151 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x151) "user")
let (set_user : t -> int -> unit) =
fun (x152 : t) ->
fun (x153 : int) ->
Ojs.set_prop_ascii (t_to_js x152) "user" (Ojs.int_to_js x153)
let (system : t -> int) =
fun (x154 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x154) "system")
let (set_system : t -> int -> unit) =
fun (x155 : t) ->
fun (x156 : int) ->
Ojs.set_prop_ascii (t_to_js x155) "system" (Ojs.int_to_js x156)
end
module ProcessRelease =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x158 : Ojs.t) -> x158
and t_to_js : t -> Ojs.t = fun (x157 : Ojs.t) -> x157
let (name : t -> string) =
fun (x159 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x159) "name")
let (set_name : t -> string -> unit) =
fun (x160 : t) ->
fun (x161 : string) ->
Ojs.set_prop_ascii (t_to_js x160) "name"
(Ojs.string_to_js x161)
let (source_url : t -> string) =
fun (x162 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x162) "sourceUrl")
let (set_source_url : t -> string -> unit) =
fun (x163 : t) ->
fun (x164 : string) ->
Ojs.set_prop_ascii (t_to_js x163) "sourceUrl"
(Ojs.string_to_js x164)
let (headers_url : t -> string) =
fun (x165 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x165) "headersUrl")
let (set_headers_url : t -> string -> unit) =
fun (x166 : t) ->
fun (x167 : string) ->
Ojs.set_prop_ascii (t_to_js x166) "headersUrl"
(Ojs.string_to_js x167)
let (lib_url : t -> string) =
fun (x168 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x168) "libUrl")
let (set_lib_url : t -> string -> unit) =
fun (x169 : t) ->
fun (x170 : string) ->
Ojs.set_prop_ascii (t_to_js x169) "libUrl"
(Ojs.string_to_js x170)
let (lts : t -> string) =
fun (x171 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x171) "lts")
let (set_lts : t -> string -> unit) =
fun (x172 : t) ->
fun (x173 : string) ->
Ojs.set_prop_ascii (t_to_js x172) "lts" (Ojs.string_to_js x173)
end
module ProcessVersions =
struct
type t = string Dict.t
let rec t_of_js : Ojs.t -> t =
fun (x176 : Ojs.t) -> Dict.t_of_js Ojs.string_of_js x176
and t_to_js : t -> Ojs.t =
fun (x174 : string Dict.t) -> Dict.t_to_js Ojs.string_to_js x174
let (http_parser : t -> string) =
fun (x178 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x178) "http_parser")
let (set_http_parser : t -> string -> unit) =
fun (x179 : t) ->
fun (x180 : string) ->
Ojs.set_prop_ascii (t_to_js x179) "http_parser"
(Ojs.string_to_js x180)
let (node : t -> string) =
fun (x181 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x181) "node")
let (set_node : t -> string -> unit) =
fun (x182 : t) ->
fun (x183 : string) ->
Ojs.set_prop_ascii (t_to_js x182) "node"
(Ojs.string_to_js x183)
let (v8 : t -> string) =
fun (x184 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x184) "v8")
let (set_v8 : t -> string -> unit) =
fun (x185 : t) ->
fun (x186 : string) ->
Ojs.set_prop_ascii (t_to_js x185) "v8" (Ojs.string_to_js x186)
let (ares : t -> string) =
fun (x187 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x187) "ares")
let (set_ares : t -> string -> unit) =
fun (x188 : t) ->
fun (x189 : string) ->
Ojs.set_prop_ascii (t_to_js x188) "ares"
(Ojs.string_to_js x189)
let (uv : t -> string) =
fun (x190 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x190) "uv")
let (set_uv : t -> string -> unit) =
fun (x191 : t) ->
fun (x192 : string) ->
Ojs.set_prop_ascii (t_to_js x191) "uv" (Ojs.string_to_js x192)
let (zlib : t -> string) =
fun (x193 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x193) "zlib")
let (set_zlib : t -> string -> unit) =
fun (x194 : t) ->
fun (x195 : string) ->
Ojs.set_prop_ascii (t_to_js x194) "zlib"
(Ojs.string_to_js x195)
let (modules : t -> string) =
fun (x196 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x196) "modules")
let (set_modules : t -> string -> unit) =
fun (x197 : t) ->
fun (x198 : string) ->
Ojs.set_prop_ascii (t_to_js x197) "modules"
(Ojs.string_to_js x198)
let (openssl : t -> string) =
fun (x199 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x199) "openssl")
let (set_openssl : t -> string -> unit) =
fun (x200 : t) ->
fun (x201 : string) ->
Ojs.set_prop_ascii (t_to_js x200) "openssl"
(Ojs.string_to_js x201)
end
module Platform =
struct
type t =
[ `aix | `android | `cygwin | `darwin | `freebsd | `linux
| `netbsd | `openbsd | `sunos | `win32 ]
let rec t_of_js : Ojs.t -> t =
fun (x203 : Ojs.t) ->
let x204 = x203 in
match Ojs.string_of_js x204 with
| "aix" -> `aix
| "android" -> `android
| "cygwin" -> `cygwin
| "darwin" -> `darwin
| "freebsd" -> `freebsd
| "linux" -> `linux
| "netbsd" -> `netbsd
| "openbsd" -> `openbsd
| "sunos" -> `sunos
| "win32" -> `win32
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x202 :
[ `aix | `android | `cygwin | `darwin | `freebsd |
`linux
| `netbsd | `openbsd | `sunos | `win32 ])
->
match x202 with
| `aix -> Ojs.string_to_js "aix"
| `android -> Ojs.string_to_js "android"
| `cygwin -> Ojs.string_to_js "cygwin"
| `darwin -> Ojs.string_to_js "darwin"
| `freebsd -> Ojs.string_to_js "freebsd"
| `linux -> Ojs.string_to_js "linux"
| `netbsd -> Ojs.string_to_js "netbsd"
| `openbsd -> Ojs.string_to_js "openbsd"
| `sunos -> Ojs.string_to_js "sunos"
| `win32 -> Ojs.string_to_js "win32"
end
module Signals =
struct
type t =
[ `SIGABRT | `SIGALRM | `SIGBREAK | `SIGBUS | `SIGCHLD
| `SIGCONT | `SIGFPE | `SIGHUP | `SIGILL | `SIGINFO |
`SIGINT
| `SIGIO | `SIGIOT | `SIGKILL | `SIGLOST | `SIGPIPE
| `SIGPOLL | `SIGPROF | `SIGPWR | `SIGQUIT | `SIGSEGV
| `SIGSTKFLT | `SIGSTOP | `SIGSYS | `SIGTERM | `SIGTRAP
| `SIGTSTP | `SIGTTIN | `SIGTTOU | `SIGUNUSED | `SIGURG
| `SIGUSR1 | `SIGUSR2 | `SIGVTALRM | `SIGWINCH | `SIGXCPU
| `SIGXFSZ ]
let rec t_of_js : Ojs.t -> t =
fun (x206 : Ojs.t) ->
let x207 = x206 in
match Ojs.string_of_js x207 with
| "SIGABRT" -> `SIGABRT
| "SIGALRM" -> `SIGALRM
| "SIGBREAK" -> `SIGBREAK
| "SIGBUS" -> `SIGBUS
| "SIGCHLD" -> `SIGCHLD
| "SIGCONT" -> `SIGCONT
| "SIGFPE" -> `SIGFPE
| "SIGHUP" -> `SIGHUP
| "SIGILL" -> `SIGILL
| "SIGINFO" -> `SIGINFO
| "SIGINT" -> `SIGINT
| "SIGIO" -> `SIGIO
| "SIGIOT" -> `SIGIOT
| "SIGKILL" -> `SIGKILL
| "SIGLOST" -> `SIGLOST
| "SIGPIPE" -> `SIGPIPE
| "SIGPOLL" -> `SIGPOLL
| "SIGPROF" -> `SIGPROF
| "SIGPWR" -> `SIGPWR
| "SIGQUIT" -> `SIGQUIT
| "SIGSEGV" -> `SIGSEGV
| "SIGSTKFLT" -> `SIGSTKFLT
| "SIGSTOP" -> `SIGSTOP
| "SIGSYS" -> `SIGSYS
| "SIGTERM" -> `SIGTERM
| "SIGTRAP" -> `SIGTRAP
| "SIGTSTP" -> `SIGTSTP
| "SIGTTIN" -> `SIGTTIN
| "SIGTTOU" -> `SIGTTOU
| "SIGUNUSED" -> `SIGUNUSED
| "SIGURG" -> `SIGURG
| "SIGUSR1" -> `SIGUSR1
| "SIGUSR2" -> `SIGUSR2
| "SIGVTALRM" -> `SIGVTALRM
| "SIGWINCH" -> `SIGWINCH
| "SIGXCPU" -> `SIGXCPU
| "SIGXFSZ" -> `SIGXFSZ
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x205 :
[ `SIGABRT | `SIGALRM | `SIGBREAK | `SIGBUS | `SIGCHLD
| `SIGCONT | `SIGFPE | `SIGHUP | `SIGILL | `SIGINFO
| `SIGINT | `SIGIO | `SIGIOT | `SIGKILL | `SIGLOST
| `SIGPIPE | `SIGPOLL | `SIGPROF | `SIGPWR | `SIGQUIT
| `SIGSEGV | `SIGSTKFLT | `SIGSTOP | `SIGSYS | `SIGTERM
| `SIGTRAP | `SIGTSTP | `SIGTTIN | `SIGTTOU | `SIGUNUSED
| `SIGURG | `SIGUSR1 | `SIGUSR2 | `SIGVTALRM | `SIGWINCH
| `SIGXCPU | `SIGXFSZ ])
->
match x205 with
| `SIGABRT -> Ojs.string_to_js "SIGABRT"
| `SIGALRM -> Ojs.string_to_js "SIGALRM"
| `SIGBREAK -> Ojs.string_to_js "SIGBREAK"
| `SIGBUS -> Ojs.string_to_js "SIGBUS"
| `SIGCHLD -> Ojs.string_to_js "SIGCHLD"
| `SIGCONT -> Ojs.string_to_js "SIGCONT"
| `SIGFPE -> Ojs.string_to_js "SIGFPE"
| `SIGHUP -> Ojs.string_to_js "SIGHUP"
| `SIGILL -> Ojs.string_to_js "SIGILL"
| `SIGINFO -> Ojs.string_to_js "SIGINFO"
| `SIGINT -> Ojs.string_to_js "SIGINT"
| `SIGIO -> Ojs.string_to_js "SIGIO"
| `SIGIOT -> Ojs.string_to_js "SIGIOT"
| `SIGKILL -> Ojs.string_to_js "SIGKILL"
| `SIGLOST -> Ojs.string_to_js "SIGLOST"
| `SIGPIPE -> Ojs.string_to_js "SIGPIPE"
| `SIGPOLL -> Ojs.string_to_js "SIGPOLL"
| `SIGPROF -> Ojs.string_to_js "SIGPROF"
| `SIGPWR -> Ojs.string_to_js "SIGPWR"
| `SIGQUIT -> Ojs.string_to_js "SIGQUIT"
| `SIGSEGV -> Ojs.string_to_js "SIGSEGV"
| `SIGSTKFLT -> Ojs.string_to_js "SIGSTKFLT"
| `SIGSTOP -> Ojs.string_to_js "SIGSTOP"
| `SIGSYS -> Ojs.string_to_js "SIGSYS"
| `SIGTERM -> Ojs.string_to_js "SIGTERM"
| `SIGTRAP -> Ojs.string_to_js "SIGTRAP"
| `SIGTSTP -> Ojs.string_to_js "SIGTSTP"
| `SIGTTIN -> Ojs.string_to_js "SIGTTIN"
| `SIGTTOU -> Ojs.string_to_js "SIGTTOU"
| `SIGUNUSED -> Ojs.string_to_js "SIGUNUSED"
| `SIGURG -> Ojs.string_to_js "SIGURG"
| `SIGUSR1 -> Ojs.string_to_js "SIGUSR1"
| `SIGUSR2 -> Ojs.string_to_js "SIGUSR2"
| `SIGVTALRM -> Ojs.string_to_js "SIGVTALRM"
| `SIGWINCH -> Ojs.string_to_js "SIGWINCH"
| `SIGXCPU -> Ojs.string_to_js "SIGXCPU"
| `SIGXFSZ -> Ojs.string_to_js "SIGXFSZ"
end
module MultipleResolvesType =
struct
type t = [ `reject | `resolve ]
let rec t_of_js : Ojs.t -> t =
fun (x209 : Ojs.t) ->
let x210 = x209 in
match Ojs.string_of_js x210 with
| "reject" -> `reject
| "resolve" -> `resolve
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x208 : [ `reject | `resolve ]) ->
match x208 with
| `reject -> Ojs.string_to_js "reject"
| `resolve -> Ojs.string_to_js "resolve"
end
module BeforeExitListener =
struct
type t = code:int -> unit
let rec t_of_js : Ojs.t -> t =
fun (x213 : Ojs.t) ->
fun ~code:(x214 : int) ->
ignore (Ojs.apply x213 [|(Ojs.int_to_js x214)|])
and t_to_js : t -> Ojs.t =
fun (x211 : code:int -> unit) ->
Ojs.fun_to_js 1
(fun (x212 : Ojs.t) -> x211 ~code:(Ojs.int_of_js x212))
end
module DisconnectListener =
struct
type t = unit -> unit
let rec t_of_js : Ojs.t -> t =
fun (x216 : Ojs.t) -> fun () -> ignore (Ojs.apply x216 [||])
and t_to_js : t -> Ojs.t =
fun (x215 : unit -> unit) -> Ojs.fun_to_js 1 (fun _ -> x215 ())
end
module ExitListener =
struct
type t = code:int -> unit
let rec t_of_js : Ojs.t -> t =
fun (x219 : Ojs.t) ->
fun ~code:(x220 : int) ->
ignore (Ojs.apply x219 [|(Ojs.int_to_js x220)|])
and t_to_js : t -> Ojs.t =
fun (x217 : code:int -> unit) ->
Ojs.fun_to_js 1
(fun (x218 : Ojs.t) -> x217 ~code:(Ojs.int_of_js x218))
end
module RejectionHandledListener =
struct
type t = promise:any Promise.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x224 : Ojs.t) ->
fun ~promise:(x225 : any Promise.t) ->
ignore (Ojs.apply x224 [|(Promise.t_to_js any_to_js x225)|])
and t_to_js : t -> Ojs.t =
fun (x221 : promise:any Promise.t -> unit) ->
Ojs.fun_to_js 1
(fun (x222 : Ojs.t) ->
x221 ~promise:(Promise.t_of_js any_of_js x222))
end
module UncaughtExceptionListener =
struct
type t = error:Error.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x229 : Ojs.t) ->
fun ~error:(x230 : Error.t) ->
ignore (Ojs.apply x229 [|(Error.t_to_js x230)|])
and t_to_js : t -> Ojs.t =
fun (x227 : error:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x228 : Ojs.t) -> x227 ~error:(Error.t_of_js x228))
end
module UnhandledRejectionListener =
struct
type t =
reason:AnonymousInterface0.t or_null_or_undefined ->
promise:any Promise.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x236 : Ojs.t) ->
fun ~reason:(x237 : AnonymousInterface0.t or_null_or_undefined)
->
fun ~promise:(x239 : any Promise.t) ->
ignore
(Ojs.apply x236
[|(or_null_or_undefined_to_js
AnonymousInterface0.t_to_js x237);(Promise.t_to_js
any_to_js x239)|])
and t_to_js : t -> Ojs.t =
fun
(x231 :
reason:AnonymousInterface0.t or_null_or_undefined ->
promise:any Promise.t -> unit)
->
Ojs.fun_to_js 2
(fun (x232 : Ojs.t) ->
fun (x234 : Ojs.t) ->
x231
~reason:(or_null_or_undefined_of_js
AnonymousInterface0.t_of_js x232)
~promise:(Promise.t_of_js any_of_js x234))
end
module WarningListener =
struct
type t = warning:Error.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x243 : Ojs.t) ->
fun ~warning:(x244 : Error.t) ->
ignore (Ojs.apply x243 [|(Error.t_to_js x244)|])
and t_to_js : t -> Ojs.t =
fun (x241 : warning:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x242 : Ojs.t) -> x241 ~warning:(Error.t_of_js x242))
end
module MessageListener =
struct
type t = message:any -> send_handle:any -> unit
let rec t_of_js : Ojs.t -> t =
fun (x248 : Ojs.t) ->
fun ~message:(x249 : any) ->
fun ~send_handle:(x250 : any) ->
ignore (Ojs.apply x248 [|(any_to_js x249);(any_to_js x250)|])
and t_to_js : t -> Ojs.t =
fun (x245 : message:any -> send_handle:any -> unit) ->
Ojs.fun_to_js 2
(fun (x246 : Ojs.t) ->
fun (x247 : Ojs.t) ->
x245 ~message:(any_of_js x246)
~send_handle:(any_of_js x247))
end
module SignalsListener =
struct
type t = signal:Signals.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x253 : Ojs.t) ->
fun ~signal:(x254 : Signals.t) ->
ignore (Ojs.apply x253 [|(Signals.t_to_js x254)|])
and t_to_js : t -> Ojs.t =
fun (x251 : signal:Signals.t -> unit) ->
Ojs.fun_to_js 1
(fun (x252 : Ojs.t) -> x251 ~signal:(Signals.t_of_js x252))
end
module NewListenerListener =
struct
type t =
type_:symbol or_string -> listener:(args:any list -> unit) -> unit
let rec t_of_js : Ojs.t -> t =
fun (x262 : Ojs.t) ->
fun ~type_:(x263 : symbol or_string) ->
fun ~listener:(x265 : args:any list -> unit) ->
ignore
(Ojs.apply x262
[|(or_string_to_js symbol_to_js x263);(Ojs.fun_to_js_args
(fun (x266 : _)
->
x265
~args:(
Ojs.list_of_js_from
any_of_js
x266 0)))|])
and t_to_js : t -> Ojs.t =
fun
(x255 :
type_:symbol or_string ->
listener:(args:any list -> unit) -> unit)
->
Ojs.fun_to_js 2
(fun (x256 : Ojs.t) ->
fun (x258 : Ojs.t) ->
x255 ~type_:(or_string_of_js symbol_of_js x256)
~listener:(fun ~args:(x259 : any list) ->
ignore
(Ojs.call x258 "apply"
[|Ojs.null;((let x260 =
Ojs.new_obj
(Ojs.get_prop_ascii
Ojs.global "Array")
[||] in
List.iter
(fun (x261 : any) ->
ignore
(Ojs.call x260
"push"
[|(any_to_js
x261)|]))
x259;
x260))|])))
end
module RemoveListenerListener =
struct
type t =
type_:symbol or_string -> listener:(args:any list -> unit) -> unit
let rec t_of_js : Ojs.t -> t =
fun (x275 : Ojs.t) ->
fun ~type_:(x276 : symbol or_string) ->
fun ~listener:(x278 : args:any list -> unit) ->
ignore
(Ojs.apply x275
[|(or_string_to_js symbol_to_js x276);(Ojs.fun_to_js_args
(fun (x279 : _)
->
x278
~args:(
Ojs.list_of_js_from
any_of_js
x279 0)))|])
and t_to_js : t -> Ojs.t =
fun
(x268 :
type_:symbol or_string ->
listener:(args:any list -> unit) -> unit)
->
Ojs.fun_to_js 2
(fun (x269 : Ojs.t) ->
fun (x271 : Ojs.t) ->
x268 ~type_:(or_string_of_js symbol_of_js x269)
~listener:(fun ~args:(x272 : any list) ->
ignore
(Ojs.call x271 "apply"
[|Ojs.null;((let x273 =
Ojs.new_obj
(Ojs.get_prop_ascii
Ojs.global "Array")
[||] in
List.iter
(fun (x274 : any) ->
ignore
(Ojs.call x273
"push"
[|(any_to_js
x274)|]))
x272;
x273))|])))
end
module MultipleResolvesListener =
struct
type t =
type_:MultipleResolvesType.t ->
promise:any Promise.t -> value:any -> unit
let rec t_of_js : Ojs.t -> t =
fun (x286 : Ojs.t) ->
fun ~type_:(x287 : MultipleResolvesType.t) ->
fun ~promise:(x288 : any Promise.t) ->
fun ~value:(x290 : any) ->
ignore
(Ojs.apply x286
[|(MultipleResolvesType.t_to_js x287);(Promise.t_to_js
any_to_js
x288);(
any_to_js x290)|])
and t_to_js : t -> Ojs.t =
fun
(x281 :
type_:MultipleResolvesType.t ->
promise:any Promise.t -> value:any -> unit)
->
Ojs.fun_to_js 3
(fun (x282 : Ojs.t) ->
fun (x283 : Ojs.t) ->
fun (x285 : Ojs.t) ->
x281 ~type_:(MultipleResolvesType.t_of_js x282)
~promise:(Promise.t_of_js any_of_js x283)
~value:(any_of_js x285))
end
type listener =
[ `BeforeExit of BeforeExitListener.t
| `Disconnect of DisconnectListener.t | `Exit of ExitListener.t
| `RejectionHandled of RejectionHandledListener.t
| `UncaughtException of UncaughtExceptionListener.t
| `UnhandledRejection of UnhandledRejectionListener.t
| `Warning of WarningListener.t | `Message of MessageListener.t
| `NewListener of NewListenerListener.t
| `RemoveListener of RemoveListenerListener.t
| `MultipleResolves of MultipleResolvesListener.t ]
let rec listener_to_js : listener -> Ojs.t =
fun
(x291 :
[ `BeforeExit of BeforeExitListener.t
| `Disconnect of DisconnectListener.t | `Exit of ExitListener.t
| `RejectionHandled of RejectionHandledListener.t
| `UncaughtException of UncaughtExceptionListener.t
| `UnhandledRejection of UnhandledRejectionListener.t
| `Warning of WarningListener.t | `Message of MessageListener.t
| `NewListener of NewListenerListener.t
| `RemoveListener of RemoveListenerListener.t
| `MultipleResolves of MultipleResolvesListener.t ])
->
match x291 with
| `BeforeExit x292 -> BeforeExitListener.t_to_js x292
| `Disconnect x293 -> DisconnectListener.t_to_js x293
| `Exit x294 -> ExitListener.t_to_js x294
| `RejectionHandled x295 -> RejectionHandledListener.t_to_js x295
| `UncaughtException x296 -> UncaughtExceptionListener.t_to_js x296
| `UnhandledRejection x297 -> UnhandledRejectionListener.t_to_js x297
| `Warning x298 -> WarningListener.t_to_js x298
| `Message x299 -> MessageListener.t_to_js x299
| `NewListener x300 -> NewListenerListener.t_to_js x300
| `RemoveListener x301 -> RemoveListenerListener.t_to_js x301
| `MultipleResolves x302 -> MultipleResolvesListener.t_to_js x302
module Socket =
struct
include struct include ReadWriteStream end
let (is_tty : t -> [ `L_b_true ]) =
fun (x305 : t) ->
let x306 = Ojs.get_prop_ascii (t_to_js x305) "isTTY" in
match Ojs.bool_of_js x306 with
| true -> `L_b_true
| _ -> assert false
let (set_is_tty : t -> [ `L_b_true ] -> unit) =
fun (x307 : t) ->
fun (x308 : [ `L_b_true ]) ->
Ojs.set_prop_ascii (t_to_js x307) "isTTY"
(match x308 with | `L_b_true -> Ojs.string_to_js "LBTrue")
end
module ProcessEnv =
struct
type t = string Dict.t
let rec t_of_js : Ojs.t -> t =
fun (x311 : Ojs.t) -> Dict.t_of_js Ojs.string_of_js x311
and t_to_js : t -> Ojs.t =
fun (x309 : string Dict.t) -> Dict.t_to_js Ojs.string_to_js x309
end
module HRTime =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x314 : Ojs.t) -> x314
and t_to_js : t -> Ojs.t = fun (x313 : Ojs.t) -> x313
let (apply : t -> ?time:(int * int) -> unit -> (int * int)) =
fun (x321 : t) ->
fun ?time:(x315 : (int * int) option) ->
fun () ->
let x322 =
Ojs.call (t_to_js x321) "apply"
[|Ojs.null;((let x316 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x315 with
| Some x317 ->
ignore
(Ojs.call x316 "push"
[|((let (x318, x319) = x317 in
let x320 = Ojs.array_make 2 in
Ojs.array_set x320 0
(Ojs.int_to_js x318);
Ojs.array_set x320 1
(Ojs.int_to_js x319);
x320))|])
| None -> ());
x316))|] in
((Ojs.int_of_js (Ojs.array_get x322 0)),
(Ojs.int_of_js (Ojs.array_get x322 1)))
let (bigint : t -> bigint) =
fun (x323 : t) ->
bigint_of_js (Ojs.call (t_to_js x323) "bigint" [||])
end
module ProcessReport =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x325 : Ojs.t) -> x325
and t_to_js : t -> Ojs.t = fun (x324 : Ojs.t) -> x324
let (directory : t -> string) =
fun (x326 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x326) "directory")
let (set_directory : t -> string -> unit) =
fun (x327 : t) ->
fun (x328 : string) ->
Ojs.set_prop_ascii (t_to_js x327) "directory"
(Ojs.string_to_js x328)
let (filename : t -> string) =
fun (x329 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x329) "filename")
let (set_filename : t -> string -> unit) =
fun (x330 : t) ->
fun (x331 : string) ->
Ojs.set_prop_ascii (t_to_js x330) "filename"
(Ojs.string_to_js x331)
let (get_report : t -> ?err:Error.t -> unit -> string) =
fun (x335 : t) ->
fun ?err:(x332 : Error.t option) ->
fun () ->
Ojs.string_of_js
(let x336 = t_to_js x335 in
Ojs.call (Ojs.get_prop_ascii x336 "getReport") "apply"
[|x336;((let x333 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x332 with
| Some x334 ->
ignore
(Ojs.call x333 "push"
[|(Error.t_to_js x334)|])
| None -> ());
x333))|])
let (report_on_fatal_error : t -> bool) =
fun (x337 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x337) "reportOnFatalError")
let (set_report_on_fatal_error : t -> bool -> unit) =
fun (x338 : t) ->
fun (x339 : bool) ->
Ojs.set_prop_ascii (t_to_js x338) "reportOnFatalError"
(Ojs.bool_to_js x339)
let (report_on_signal : t -> bool) =
fun (x340 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x340) "reportOnSignal")
let (set_report_on_signal : t -> bool -> unit) =
fun (x341 : t) ->
fun (x342 : bool) ->
Ojs.set_prop_ascii (t_to_js x341) "reportOnSignal"
(Ojs.bool_to_js x342)
let (report_on_uncaught_exception : t -> bool) =
fun (x343 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x343) "reportOnUncaughtException")
let (set_report_on_uncaught_exception : t -> bool -> unit) =
fun (x344 : t) ->
fun (x345 : bool) ->
Ojs.set_prop_ascii (t_to_js x344) "reportOnUncaughtException"
(Ojs.bool_to_js x345)
let (signal : t -> Signals.t) =
fun (x346 : t) ->
Signals.t_of_js (Ojs.get_prop_ascii (t_to_js x346) "signal")
let (set_signal : t -> Signals.t -> unit) =
fun (x347 : t) ->
fun (x348 : Signals.t) ->
Ojs.set_prop_ascii (t_to_js x347) "signal"
(Signals.t_to_js x348)
let (write_report : t -> ?file_name:string -> unit -> string) =
fun (x352 : t) ->
fun ?file_name:(x349 : string option) ->
fun () ->
Ojs.string_of_js
(let x353 = t_to_js x352 in
Ojs.call (Ojs.get_prop_ascii x353 "writeReport") "apply"
[|x353;((let x350 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x349 with
| Some x351 ->
ignore
(Ojs.call x350 "push"
[|(Ojs.string_to_js x351)|])
| None -> ());
x350))|])
let (write_report' : t -> ?error:Error.t -> unit -> string) =
fun (x357 : t) ->
fun ?error:(x354 : Error.t option) ->
fun () ->
Ojs.string_of_js
(let x358 = t_to_js x357 in
Ojs.call (Ojs.get_prop_ascii x358 "writeReport") "apply"
[|x358;((let x355 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x354 with
| Some x356 ->
ignore
(Ojs.call x355 "push"
[|(Error.t_to_js x356)|])
| None -> ());
x355))|])
let (write_report'' :
t -> ?file_name:string -> ?err:Error.t -> unit -> string) =
fun (x364 : t) ->
fun ?file_name:(x359 : string option) ->
fun ?err:(x360 : Error.t option) ->
fun () ->
Ojs.string_of_js
(let x365 = t_to_js x364 in
Ojs.call (Ojs.get_prop_ascii x365 "writeReport") "apply"
[|x365;((let x361 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x359 with
| Some x363 ->
ignore
(Ojs.call x361 "push"
[|(Ojs.string_to_js x363)|])
| None -> ());
(match x360 with
| Some x362 ->
ignore
(Ojs.call x361 "push"
[|(Error.t_to_js x362)|])
| None -> ());
x361))|])
end
module ResourceUsage =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x367 : Ojs.t) -> x367
and t_to_js : t -> Ojs.t = fun (x366 : Ojs.t) -> x366
let (fs_read : t -> int) =
fun (x368 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x368) "fsRead")
let (set_fs_read : t -> int -> unit) =
fun (x369 : t) ->
fun (x370 : int) ->
Ojs.set_prop_ascii (t_to_js x369) "fsRead" (Ojs.int_to_js x370)
let (fs_write : t -> int) =
fun (x371 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x371) "fsWrite")
let (set_fs_write : t -> int -> unit) =
fun (x372 : t) ->
fun (x373 : int) ->
Ojs.set_prop_ascii (t_to_js x372) "fsWrite"
(Ojs.int_to_js x373)
let (involuntary_context_switches : t -> int) =
fun (x374 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x374) "involuntaryContextSwitches")
let (set_involuntary_context_switches : t -> int -> unit) =
fun (x375 : t) ->
fun (x376 : int) ->
Ojs.set_prop_ascii (t_to_js x375) "involuntaryContextSwitches"
(Ojs.int_to_js x376)
let (ipc_received : t -> int) =
fun (x377 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x377) "ipcReceived")
let (set_ipc_received : t -> int -> unit) =
fun (x378 : t) ->
fun (x379 : int) ->
Ojs.set_prop_ascii (t_to_js x378) "ipcReceived"
(Ojs.int_to_js x379)
let (ipc_sent : t -> int) =
fun (x380 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x380) "ipcSent")
let (set_ipc_sent : t -> int -> unit) =
fun (x381 : t) ->
fun (x382 : int) ->
Ojs.set_prop_ascii (t_to_js x381) "ipcSent"
(Ojs.int_to_js x382)
let (major_page_fault : t -> int) =
fun (x383 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x383) "majorPageFault")
let (set_major_page_fault : t -> int -> unit) =
fun (x384 : t) ->
fun (x385 : int) ->
Ojs.set_prop_ascii (t_to_js x384) "majorPageFault"
(Ojs.int_to_js x385)
let (max_rss : t -> int) =
fun (x386 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x386) "maxRSS")
let (set_max_rss : t -> int -> unit) =
fun (x387 : t) ->
fun (x388 : int) ->
Ojs.set_prop_ascii (t_to_js x387) "maxRSS" (Ojs.int_to_js x388)
let (minor_page_fault : t -> int) =
fun (x389 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x389) "minorPageFault")
let (set_minor_page_fault : t -> int -> unit) =
fun (x390 : t) ->
fun (x391 : int) ->
Ojs.set_prop_ascii (t_to_js x390) "minorPageFault"
(Ojs.int_to_js x391)
let (shared_memory_size : t -> int) =
fun (x392 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x392) "sharedMemorySize")
let (set_shared_memory_size : t -> int -> unit) =
fun (x393 : t) ->
fun (x394 : int) ->
Ojs.set_prop_ascii (t_to_js x393) "sharedMemorySize"
(Ojs.int_to_js x394)
let (signals_count : t -> int) =
fun (x395 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x395) "signalsCount")
let (set_signals_count : t -> int -> unit) =
fun (x396 : t) ->
fun (x397 : int) ->
Ojs.set_prop_ascii (t_to_js x396) "signalsCount"
(Ojs.int_to_js x397)
let (swapped_out : t -> int) =
fun (x398 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x398) "swappedOut")
let (set_swapped_out : t -> int -> unit) =
fun (x399 : t) ->
fun (x400 : int) ->
Ojs.set_prop_ascii (t_to_js x399) "swappedOut"
(Ojs.int_to_js x400)
let (system_cpu_time : t -> int) =
fun (x401 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x401) "systemCPUTime")
let (set_system_cpu_time : t -> int -> unit) =
fun (x402 : t) ->
fun (x403 : int) ->
Ojs.set_prop_ascii (t_to_js x402) "systemCPUTime"
(Ojs.int_to_js x403)
let (unshared_data_size : t -> int) =
fun (x404 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x404) "unsharedDataSize")
let (set_unshared_data_size : t -> int -> unit) =
fun (x405 : t) ->
fun (x406 : int) ->
Ojs.set_prop_ascii (t_to_js x405) "unsharedDataSize"
(Ojs.int_to_js x406)
let (unshared_stack_size : t -> int) =
fun (x407 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x407) "unsharedStackSize")
let (set_unshared_stack_size : t -> int -> unit) =
fun (x408 : t) ->
fun (x409 : int) ->
Ojs.set_prop_ascii (t_to_js x408) "unsharedStackSize"
(Ojs.int_to_js x409)
let (user_cpu_time : t -> int) =
fun (x410 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x410) "userCPUTime")
let (set_user_cpu_time : t -> int -> unit) =
fun (x411 : t) ->
fun (x412 : int) ->
Ojs.set_prop_ascii (t_to_js x411) "userCPUTime"
(Ojs.int_to_js x412)
let (voluntary_context_switches : t -> int) =
fun (x413 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x413) "voluntaryContextSwitches")
let (set_voluntary_context_switches : t -> int -> unit) =
fun (x414 : t) ->
fun (x415 : int) ->
Ojs.set_prop_ascii (t_to_js x414) "voluntaryContextSwitches"
(Ojs.int_to_js x415)
end
module Process =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x417 : Ojs.t) -> x417
and t_to_js : t -> Ojs.t = fun (x416 : Ojs.t) -> x416
let (stdout : t -> WriteStream.t) =
fun (x418 : t) ->
WriteStream.t_of_js (Ojs.get_prop_ascii (t_to_js x418) "stdout")
let (set_stdout : t -> WriteStream.t -> unit) =
fun (x419 : t) ->
fun (x420 : WriteStream.t) ->
Ojs.set_prop_ascii (t_to_js x419) "stdout"
(WriteStream.t_to_js x420)
let (stderr : t -> WriteStream.t) =
fun (x421 : t) ->
WriteStream.t_of_js (Ojs.get_prop_ascii (t_to_js x421) "stderr")
let (set_stderr : t -> WriteStream.t -> unit) =
fun (x422 : t) ->
fun (x423 : WriteStream.t) ->
Ojs.set_prop_ascii (t_to_js x422) "stderr"
(WriteStream.t_to_js x423)
let (stdin : t -> ReadStream.t) =
fun (x424 : t) ->
ReadStream.t_of_js (Ojs.get_prop_ascii (t_to_js x424) "stdin")
let (set_stdin : t -> ReadStream.t -> unit) =
fun (x425 : t) ->
fun (x426 : ReadStream.t) ->
Ojs.set_prop_ascii (t_to_js x425) "stdin"
(ReadStream.t_to_js x426)
let (open_stdin : t -> Socket.t) =
fun (x427 : t) ->
Socket.t_of_js (Ojs.call (t_to_js x427) "openStdin" [||])
let (argv : t -> string list) =
fun (x428 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x428) "argv")
let (set_argv : t -> string list -> unit) =
fun (x430 : t) ->
fun (x431 : string list) ->
Ojs.set_prop_ascii (t_to_js x430) "argv"
(Ojs.list_to_js Ojs.string_to_js x431)
let (argv0 : t -> string) =
fun (x433 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x433) "argv0")
let (set_argv0 : t -> string -> unit) =
fun (x434 : t) ->
fun (x435 : string) ->
Ojs.set_prop_ascii (t_to_js x434) "argv0"
(Ojs.string_to_js x435)
let (exec_argv : t -> string list) =
fun (x436 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x436) "execArgv")
let (set_exec_argv : t -> string list -> unit) =
fun (x438 : t) ->
fun (x439 : string list) ->
Ojs.set_prop_ascii (t_to_js x438) "execArgv"
(Ojs.list_to_js Ojs.string_to_js x439)
let (exec_path : t -> string) =
fun (x441 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x441) "execPath")
let (set_exec_path : t -> string -> unit) =
fun (x442 : t) ->
fun (x443 : string) ->
Ojs.set_prop_ascii (t_to_js x442) "execPath"
(Ojs.string_to_js x443)
let (abort : t -> never) =
fun (x444 : t) ->
never_of_js (Ojs.call (t_to_js x444) "abort" [||])
let (chdir : t -> directory:string -> unit) =
fun (x446 : t) ->
fun ~directory:(x445 : string) ->
ignore
(Ojs.call (t_to_js x446) "chdir" [|(Ojs.string_to_js x445)|])
let (cwd : t -> string) =
fun (x447 : t) ->
Ojs.string_of_js (Ojs.call (t_to_js x447) "cwd" [||])
let (debug_port : t -> int) =
fun (x448 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x448) "debugPort")
let (set_debug_port : t -> int -> unit) =
fun (x449 : t) ->
fun (x450 : int) ->
Ojs.set_prop_ascii (t_to_js x449) "debugPort"
(Ojs.int_to_js x450)
let (emit_warning :
t ->
event:[ `warning ] ->
warning:Error.t or_string ->
?name:string -> ?ctor:untyped_function -> unit -> unit)
=
fun (x459 : t) ->
fun ~event:(x451 : [ `warning ]) ->
fun ~warning:(x452 : Error.t or_string) ->
fun ?name:(x453 : string option) ->
fun ?ctor:(x454 : untyped_function option) ->
fun () ->
ignore
(let x460 = t_to_js x459 in
Ojs.call (Ojs.get_prop_ascii x460 "emitWarning")
"apply"
[|x460;((let x455 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global
"Array") [||] in
ignore
(Ojs.call x455 "push"
[|((match x451 with
| `warning ->
Ojs.string_to_js "warning"))|]);
ignore
(Ojs.call x455 "push"
[|(or_string_to_js Error.t_to_js
x452)|]);
(match x453 with
| Some x457 ->
ignore
(Ojs.call x455 "push"
[|(Ojs.string_to_js x457)|])
| None -> ());
(match x454 with
| Some x456 ->
ignore
(Ojs.call x455 "push"
[|(untyped_function_to_js x456)|])
| None -> ());
x455))|])
let (env : t -> ProcessEnv.t) =
fun (x461 : t) ->
ProcessEnv.t_of_js (Ojs.get_prop_ascii (t_to_js x461) "env")
let (set_env : t -> ProcessEnv.t -> unit) =
fun (x462 : t) ->
fun (x463 : ProcessEnv.t) ->
Ojs.set_prop_ascii (t_to_js x462) "env"
(ProcessEnv.t_to_js x463)
let (exit : t -> ?code:int -> unit -> never) =
fun (x467 : t) ->
fun ?code:(x464 : int option) ->
fun () ->
never_of_js
(let x468 = t_to_js x467 in
Ojs.call (Ojs.get_prop_ascii x468 "exit") "apply"
[|x468;((let x465 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x464 with
| Some x466 ->
ignore
(Ojs.call x465 "push"
[|(Ojs.int_to_js x466)|])
| None -> ());
x465))|])
let (exit_code : t -> int) =
fun (x469 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x469) "exitCode")
let (set_exit_code : t -> int -> unit) =
fun (x470 : t) ->
fun (x471 : int) ->
Ojs.set_prop_ascii (t_to_js x470) "exitCode"
(Ojs.int_to_js x471)
let (getgid : t -> int) =
fun (x472 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x472) "getgid" [||])
let (setgid : t -> id:string or_number -> unit) =
fun (x475 : t) ->
fun ~id:(x473 : string or_number) ->
ignore
(Ojs.call (t_to_js x475) "setgid"
[|(or_number_to_js Ojs.string_to_js x473)|])
let (getuid : t -> int) =
fun (x476 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x476) "getuid" [||])
let (setuid : t -> id:string or_number -> unit) =
fun (x479 : t) ->
fun ~id:(x477 : string or_number) ->
ignore
(Ojs.call (t_to_js x479) "setuid"
[|(or_number_to_js Ojs.string_to_js x477)|])
let (geteuid : t -> int) =
fun (x480 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x480) "geteuid" [||])
let (seteuid : t -> id:string or_number -> unit) =
fun (x483 : t) ->
fun ~id:(x481 : string or_number) ->
ignore
(Ojs.call (t_to_js x483) "seteuid"
[|(or_number_to_js Ojs.string_to_js x481)|])
let (getegid : t -> int) =
fun (x484 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x484) "getegid" [||])
let (setegid : t -> id:string or_number -> unit) =
fun (x487 : t) ->
fun ~id:(x485 : string or_number) ->
ignore
(Ojs.call (t_to_js x487) "setegid"
[|(or_number_to_js Ojs.string_to_js x485)|])
let (getgroups : t -> int list) =
fun (x488 : t) ->
Ojs.list_of_js Ojs.int_of_js
(Ojs.call (t_to_js x488) "getgroups" [||])
let (setgroups : t -> groups:string or_number list -> unit) =
fun (x493 : t) ->
fun ~groups:(x490 : string or_number list) ->
ignore
(Ojs.call (t_to_js x493) "setgroups"
[|(Ojs.list_to_js
(fun (x491 : string or_number) ->
or_number_to_js Ojs.string_to_js x491) x490)|])
let (set_uncaught_exception_capture_callback :
t -> cb:(err:Error.t -> unit) or_null -> unit) =
fun (x497 : t) ->
fun ~cb:(x494 : (err:Error.t -> unit) or_null) ->
ignore
(Ojs.call (t_to_js x497)
"setUncaughtExceptionCaptureCallback"
[|(or_null_to_js
(fun (x495 : err:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x496 : Ojs.t) ->
x495 ~err:(Error.t_of_js x496))) x494)|])
let (has_uncaught_exception_capture_callback : t -> bool) =
fun (x498 : t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x498) "hasUncaughtExceptionCaptureCallback"
[||])
let (version : t -> string) =
fun (x499 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x499) "version")
let (set_version : t -> string -> unit) =
fun (x500 : t) ->
fun (x501 : string) ->
Ojs.set_prop_ascii (t_to_js x500) "version"
(Ojs.string_to_js x501)
let (versions : t -> ProcessVersions.t) =
fun (x502 : t) ->
ProcessVersions.t_of_js
(Ojs.get_prop_ascii (t_to_js x502) "versions")
let (set_versions : t -> ProcessVersions.t -> unit) =
fun (x503 : t) ->
fun (x504 : ProcessVersions.t) ->
Ojs.set_prop_ascii (t_to_js x503) "versions"
(ProcessVersions.t_to_js x504)
let (config : t -> AnonymousInterface8.t) =
fun (x505 : t) ->
AnonymousInterface8.t_of_js
(Ojs.get_prop_ascii (t_to_js x505) "config")
let (set_config : t -> AnonymousInterface8.t -> unit) =
fun (x506 : t) ->
fun (x507 : AnonymousInterface8.t) ->
Ojs.set_prop_ascii (t_to_js x506) "config"
(AnonymousInterface8.t_to_js x507)
let (kill :
t -> pid:int -> ?signal:string or_number -> unit -> [ `L_b_true ])
=
fun (x513 : t) ->
fun ~pid:(x508 : int) ->
fun ?signal:(x509 : string or_number option) ->
fun () ->
let x515 =
let x514 = t_to_js x513 in
Ojs.call (Ojs.get_prop_ascii x514 "kill") "apply"
[|x514;((let x510 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x510 "push"
[|(Ojs.int_to_js x508)|]);
(match x509 with
| Some x511 ->
ignore
(Ojs.call x510 "push"
[|(or_number_to_js Ojs.string_to_js
x511)|])
| None -> ());
x510))|] in
match Ojs.bool_of_js x515 with
| true -> `L_b_true
| _ -> assert false
let (pid : t -> int) =
fun (x516 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x516) "pid")
let (set_pid : t -> int -> unit) =
fun (x517 : t) ->
fun (x518 : int) ->
Ojs.set_prop_ascii (t_to_js x517) "pid" (Ojs.int_to_js x518)
let (ppid : t -> int) =
fun (x519 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x519) "ppid")
let (set_ppid : t -> int -> unit) =
fun (x520 : t) ->
fun (x521 : int) ->
Ojs.set_prop_ascii (t_to_js x520) "ppid" (Ojs.int_to_js x521)
let (title : t -> string) =
fun (x522 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x522) "title")
let (set_title : t -> string -> unit) =
fun (x523 : t) ->
fun (x524 : string) ->
Ojs.set_prop_ascii (t_to_js x523) "title"
(Ojs.string_to_js x524)
let (arch : t -> string) =
fun (x525 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x525) "arch")
let (set_arch : t -> string -> unit) =
fun (x526 : t) ->
fun (x527 : string) ->
Ojs.set_prop_ascii (t_to_js x526) "arch"
(Ojs.string_to_js x527)
let (platform : t -> Platform.t) =
fun (x528 : t) ->
Platform.t_of_js (Ojs.get_prop_ascii (t_to_js x528) "platform")
let (set_platform : t -> Platform.t -> unit) =
fun (x529 : t) ->
fun (x530 : Platform.t) ->
Ojs.set_prop_ascii (t_to_js x529) "platform"
(Platform.t_to_js x530)
let (main_module : t -> Module.t) =
fun (x531 : t) ->
Module.t_of_js (Ojs.get_prop_ascii (t_to_js x531) "mainModule")
let (set_main_module : t -> Module.t -> unit) =
fun (x532 : t) ->
fun (x533 : Module.t) ->
Ojs.set_prop_ascii (t_to_js x532) "mainModule"
(Module.t_to_js x533)
let (memory_usage : t -> MemoryUsage.t) =
fun (x534 : t) ->
MemoryUsage.t_of_js (Ojs.call (t_to_js x534) "memoryUsage" [||])
let (cpu_usage :
t -> ?previous_value:CpuUsage.t -> unit -> CpuUsage.t) =
fun (x538 : t) ->
fun ?previous_value:(x535 : CpuUsage.t option) ->
fun () ->
CpuUsage.t_of_js
(let x539 = t_to_js x538 in
Ojs.call (Ojs.get_prop_ascii x539 "cpuUsage") "apply"
[|x539;((let x536 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x535 with
| Some x537 ->
ignore
(Ojs.call x536 "push"
[|(CpuUsage.t_to_js x537)|])
| None -> ());
x536))|])
let (next_tick :
t -> callback:untyped_function -> args:any list -> unit) =
fun (x544 : t) ->
fun ~callback:(x540 : untyped_function) ->
fun ~args:(x541 : any list) ->
ignore
(let x545 = t_to_js x544 in
Ojs.call (Ojs.get_prop_ascii x545 "nextTick") "apply"
[|x545;((let x542 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x542 "push"
[|(untyped_function_to_js x540)|]);
List.iter
(fun (x543 : any) ->
ignore
(Ojs.call x542 "push"
[|(any_to_js x543)|])) x541;
x542))|])
let (release : t -> ProcessRelease.t) =
fun (x546 : t) ->
ProcessRelease.t_of_js
(Ojs.get_prop_ascii (t_to_js x546) "release")
let (set_release : t -> ProcessRelease.t -> unit) =
fun (x547 : t) ->
fun (x548 : ProcessRelease.t) ->
Ojs.set_prop_ascii (t_to_js x547) "release"
(ProcessRelease.t_to_js x548)
let (features : t -> AnonymousInterface6.t) =
fun (x549 : t) ->
AnonymousInterface6.t_of_js
(Ojs.get_prop_ascii (t_to_js x549) "features")
let (set_features : t -> AnonymousInterface6.t -> unit) =
fun (x550 : t) ->
fun (x551 : AnonymousInterface6.t) ->
Ojs.set_prop_ascii (t_to_js x550) "features"
(AnonymousInterface6.t_to_js x551)
let (umask : t -> int) =
fun (x552 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x552) "umask" [||])
let (umask' : t -> mask:string or_number -> int) =
fun (x555 : t) ->
fun ~mask:(x553 : string or_number) ->
Ojs.int_of_js
(Ojs.call (t_to_js x555) "umask"
[|(or_number_to_js Ojs.string_to_js x553)|])
let (uptime : t -> int) =
fun (x556 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x556) "uptime" [||])
let (hrtime : t -> HRTime.t) =
fun (x557 : t) ->
HRTime.t_of_js (Ojs.get_prop_ascii (t_to_js x557) "hrtime")
let (set_hrtime : t -> HRTime.t -> unit) =
fun (x558 : t) ->
fun (x559 : HRTime.t) ->
Ojs.set_prop_ascii (t_to_js x558) "hrtime"
(HRTime.t_to_js x559)
let (domain : t -> Node_domain.Domain.Domain.t) =
fun (x560 : t) ->
Node_domain.Domain.Domain.t_of_js
(Ojs.get_prop_ascii (t_to_js x560) "domain")
let (set_domain : t -> Node_domain.Domain.Domain.t -> unit) =
fun (x561 : t) ->
fun (x562 : Node_domain.Domain.Domain.t) ->
Ojs.set_prop_ascii (t_to_js x561) "domain"
(Node_domain.Domain.Domain.t_to_js x562)
let (send :
t ->
message:any ->
?send_handle:any ->
?options:AnonymousInterface7.t ->
?callback:(error:Error.t or_null -> unit) -> unit -> bool)
=
fun (x573 : t) ->
fun ~message:(x563 : any) ->
fun ?send_handle:(x564 : any option) ->
fun ?options:(x565 : AnonymousInterface7.t option) ->
fun
?callback:(x566 : (error:Error.t or_null -> unit) option)
->
fun () ->
Ojs.bool_of_js
(let x574 = t_to_js x573 in
Ojs.call (Ojs.get_prop_ascii x574 "send") "apply"
[|x574;((let x567 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global
"Array") [||] in
ignore
(Ojs.call x567 "push"
[|(any_to_js x563)|]);
(match x564 with
| Some x572 ->
ignore
(Ojs.call x567 "push"
[|(any_to_js x572)|])
| None -> ());
(match x565 with
| Some x571 ->
ignore
(Ojs.call x567 "push"
[|(AnonymousInterface7.t_to_js
x571)|])
| None -> ());
(match x566 with
| Some x568 ->
ignore
(Ojs.call x567 "push"
[|(Ojs.fun_to_js 1
(fun (x569 : Ojs.t) ->
x568
~error:(or_null_of_js
Error.t_of_js
x569)))|])
| None -> ());
x567))|])
let (disconnect : t -> unit) =
fun (x575 : t) ->
ignore (Ojs.call (t_to_js x575) "disconnect" [||])
let (connected : t -> bool) =
fun (x576 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x576) "connected")
let (set_connected : t -> bool -> unit) =
fun (x577 : t) ->
fun (x578 : bool) ->
Ojs.set_prop_ascii (t_to_js x577) "connected"
(Ojs.bool_to_js x578)
let (allowed_node_environment_flags : t -> string ReadonlySet.t) =
fun (x579 : t) ->
ReadonlySet.t_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x579)
"allowedNodeEnvironmentFlags")
let (set_allowed_node_environment_flags :
t -> string ReadonlySet.t -> unit) =
fun (x581 : t) ->
fun (x582 : string ReadonlySet.t) ->
Ojs.set_prop_ascii (t_to_js x581) "allowedNodeEnvironmentFlags"
(ReadonlySet.t_to_js Ojs.string_to_js x582)
let (report : t -> ProcessReport.t) =
fun (x584 : t) ->
ProcessReport.t_of_js
(Ojs.get_prop_ascii (t_to_js x584) "report")
let (set_report : t -> ProcessReport.t -> unit) =
fun (x585 : t) ->
fun (x586 : ProcessReport.t) ->
Ojs.set_prop_ascii (t_to_js x585) "report"
(ProcessReport.t_to_js x586)
let (resource_usage : t -> ResourceUsage.t) =
fun (x587 : t) ->
ResourceUsage.t_of_js
(Ojs.call (t_to_js x587) "resourceUsage" [||])
let (trace_deprecation : t -> bool) =
fun (x588 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x588) "traceDeprecation")
let (set_trace_deprecation : t -> bool -> unit) =
fun (x589 : t) ->
fun (x590 : bool) ->
Ojs.set_prop_ascii (t_to_js x589) "traceDeprecation"
(Ojs.bool_to_js x590)
let (on : t -> string -> Ojs.t -> unit) =
fun (x593 : t) ->
fun (x591 : string) ->
fun (x592 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x593) "on"
[|(Ojs.string_to_js x591);x592|])
let (add_listener : t -> string -> Ojs.t -> unit) =
fun (x596 : t) ->
fun (x594 : string) ->
fun (x595 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x596) "addListener"
[|(Ojs.string_to_js x594);x595|])
let (once : t -> string -> Ojs.t -> unit) =
fun (x599 : t) ->
fun (x597 : string) ->
fun (x598 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x599) "once"
[|(Ojs.string_to_js x597);x598|])
let (prepend_listener : t -> string -> Ojs.t -> unit) =
fun (x602 : t) ->
fun (x600 : string) ->
fun (x601 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x602) "prependListener"
[|(Ojs.string_to_js x600);x601|])
let (prepend_once_listener : t -> string -> Ojs.t -> unit) =
fun (x605 : t) ->
fun (x603 : string) ->
fun (x604 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x605) "prependOnceListener"
[|(Ojs.string_to_js x603);x604|])
let (listeners : t -> string -> Ojs.t list) =
fun (x607 : t) ->
fun (x606 : string) ->
Ojs.list_of_js (fun (x608 : Ojs.t) -> x608)
(Ojs.call (t_to_js x607) "listeners"
[|(Ojs.string_to_js x606)|])
let with_listener_fn fn t =
function
| `BeforeExit f ->
(fn t "beforeExit") @@ (BeforeExitListener.t_to_js f)
| `Disconnect f ->
(fn t "disconnect") @@ (DisconnectListener.t_to_js f)
| `Exit f -> (fn t "exit") @@ (ExitListener.t_to_js f)
| `RejectionHandled f ->
(fn t "rejectionHandled") @@
(RejectionHandledListener.t_to_js f)
| `UncaughtException f ->
(fn t "uncaughtException") @@
(UncaughtExceptionListener.t_to_js f)
| `UnhandledRejection f ->
(fn t "unhandledRejection") @@
(UnhandledRejectionListener.t_to_js f)
| `Warning f -> (fn t "warning") @@ (WarningListener.t_to_js f)
| `Message f -> (fn t "message") @@ (MessageListener.t_to_js f)
| `NewListener f ->
(fn t "newListener") @@ (NewListenerListener.t_to_js f)
| `RemoveListener f ->
(fn t "removeListener") @@ (RemoveListenerListener.t_to_js f)
| `MultipleResolves f ->
(fn t "multipleResolves") @@
(MultipleResolvesListener.t_to_js f)
let on = with_listener_fn on
let add_listener = with_listener_fn add_listener
let once = with_listener_fn once
let prepend_listener = with_listener_fn prepend_listener
let prepend_once_listener = with_listener_fn prepend_once_listener
let listeners_before_exit t =
(listeners t "beforeExit") |> (List.map BeforeExitListener.t_of_js)
let listeners_disconnect t =
(listeners t "disconnect") |> (List.map DisconnectListener.t_of_js)
let listeners_exit t =
(listeners t "exit") |> (List.map ExitListener.t_of_js)
let listeners_rejection_handled t =
(listeners t "rejectionHandled") |>
(List.map RejectionHandledListener.t_of_js)
let listeners_uncaught_exception t =
(listeners t "uncaughtException") |>
(List.map UncaughtExceptionListener.t_of_js)
let listeners_uncaught_exception t =
(listeners t "uncaughtException") |>
(List.map UncaughtExceptionListener.t_of_js)
let listeners_unhandled_rejection t =
(listeners t "unhandledRejection") |>
(List.map UnhandledRejectionListener.t_of_js)
let listeners_warning t =
(listeners t "warning") |> (List.map WarningListener.t_of_js)
let listeners_message t =
(listeners t "message") |> (List.map MessageListener.t_of_js)
let listeners_signals t =
(listeners t "signals") |> (List.map SignalsListener.t_of_js)
let listeners_new_listener t =
(listeners t "newListener") |>
(List.map NewListenerListener.t_of_js)
let listeners_remove_listener t =
(listeners t "removeListener") |>
(List.map RemoveListenerListener.t_of_js)
let listeners_multiple_resolves t =
(listeners t "multipleResolves") |>
(List.map MultipleResolvesListener.t_of_js)
let (emit_before_exit :
t -> event:[ `beforeExit ] -> code:int -> bool) =
fun (x622 : t) ->
fun ~event:(x620 : [ `beforeExit ]) ->
fun ~code:(x621 : int) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x622) "emit"
[|((match x620 with
| `beforeExit -> Ojs.string_to_js "beforeExit"));(
Ojs.int_to_js x621)|])
let (emit_disconnect : t -> event:[ `disconnect ] -> bool) =
fun (x624 : t) ->
fun ~event:(x623 : [ `disconnect ]) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x624) "emit"
[|((match x623 with
| `disconnect -> Ojs.string_to_js "disconnect"))|])
let (emit_exit : t -> event:[ `exit ] -> code:int -> bool) =
fun (x627 : t) ->
fun ~event:(x625 : [ `exit ]) ->
fun ~code:(x626 : int) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x627) "emit"
[|((match x625 with | `exit -> Ojs.string_to_js "exit"));(
Ojs.int_to_js x626)|])
let (emit_rejection_handled :
t -> event:[ `rejectionHandled ] -> promise:any Promise.t -> bool)
=
fun (x631 : t) ->
fun ~event:(x628 : [ `rejectionHandled ]) ->
fun ~promise:(x629 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x631) "emit"
[|((match x628 with
| `rejectionHandled ->
Ojs.string_to_js "rejectionHandled"));(Promise.t_to_js
any_to_js
x629)|])
let (emit_uncaught_exception :
t -> event:[ `uncaughtException ] -> error:Error.t -> bool) =
fun (x634 : t) ->
fun ~event:(x632 : [ `uncaughtException ]) ->
fun ~error:(x633 : Error.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x634) "emit"
[|((match x632 with
| `uncaughtException ->
Ojs.string_to_js "uncaughtException"));(
Error.t_to_js x633)|])
let (emit_uncaught_exception_monitor :
t -> event:[ `uncaughtExceptionMonitor ] -> error:Error.t -> bool)
=
fun (x637 : t) ->
fun ~event:(x635 : [ `uncaughtExceptionMonitor ]) ->
fun ~error:(x636 : Error.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x637) "emit"
[|((match x635 with
| `uncaughtExceptionMonitor ->
Ojs.string_to_js "uncaughtExceptionMonitor"));(
Error.t_to_js x636)|])
let (emit_unhandled_rejection :
t ->
event:[ `unhandledRejection ] ->
reason:any -> promise:any Promise.t -> bool)
=
fun (x642 : t) ->
fun ~event:(x638 : [ `unhandledRejection ]) ->
fun ~reason:(x639 : any) ->
fun ~promise:(x640 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x642) "emit"
[|((match x638 with
| `unhandledRejection ->
Ojs.string_to_js "unhandledRejection"));(
any_to_js x639);(Promise.t_to_js any_to_js x640)|])
let (emit_warning :
t -> event:[ `warning ] -> warning:Error.t -> bool) =
fun (x645 : t) ->
fun ~event:(x643 : [ `warning ]) ->
fun ~warning:(x644 : Error.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x645) "emit"
[|((match x643 with
| `warning -> Ojs.string_to_js "warning"));(
Error.t_to_js x644)|])
let (emit_message :
t -> event:[ `message ] -> message:any -> send_handle:any -> t) =
fun (x649 : t) ->
fun ~event:(x646 : [ `message ]) ->
fun ~message:(x647 : any) ->
fun ~send_handle:(x648 : any) ->
t_of_js
(Ojs.call (t_to_js x649) "emit"
[|((match x646 with
| `message -> Ojs.string_to_js "message"));(
any_to_js x647);(any_to_js x648)|])
let (emit_new_listener :
t ->
event:[ `newListener ] ->
event_name:symbol or_string ->
listener:(args:any list -> unit) -> t)
=
fun (x656 : t) ->
fun ~event:(x650 : [ `newListener ]) ->
fun ~event_name:(x651 : symbol or_string) ->
fun ~listener:(x653 : args:any list -> unit) ->
t_of_js
(Ojs.call (t_to_js x656) "emit"
[|((match x650 with
| `newListener -> Ojs.string_to_js "newListener"));(
or_string_to_js symbol_to_js x651);(Ojs.fun_to_js_args
(fun
(x654 : _)
->
x653
~args:(
Ojs.list_of_js_from
any_of_js
x654 0)))|])
let (emit_remove_listener :
t ->
event:[ `removeListener ] ->
event_name:string -> listener:(args:any list -> unit) -> t)
=
fun (x662 : t) ->
fun ~event:(x657 : [ `removeListener ]) ->
fun ~event_name:(x658 : string) ->
fun ~listener:(x659 : args:any list -> unit) ->
t_of_js
(Ojs.call (t_to_js x662) "emit"
[|((match x657 with
| `removeListener ->
Ojs.string_to_js "removeListener"));(Ojs.string_to_js
x658);(
Ojs.fun_to_js_args
(fun (x660 : _) ->
x659
~args:(Ojs.list_of_js_from any_of_js x660 0)))|])
let (emit_multiple_resolves :
t ->
event:[ `multipleResolves ] ->
listener:MultipleResolvesListener.t -> t)
=
fun (x665 : t) ->
fun ~event:(x663 : [ `multipleResolves ]) ->
fun ~listener:(x664 : MultipleResolvesListener.t) ->
t_of_js
(Ojs.call (t_to_js x665) "emit"
[|((match x663 with
| `multipleResolves ->
Ojs.string_to_js "multipleResolves"));(MultipleResolvesListener.t_to_js
x664)|])
end
let (stdout : WriteStream.t) =
WriteStream.t_of_js (Ojs.get_prop_ascii Import.process "stdout")
let (set_stdout : WriteStream.t -> unit) =
fun (x666 : WriteStream.t) ->
ignore
(Ojs.call Import.process "stdout" [|(WriteStream.t_to_js x666)|])
let (stderr : WriteStream.t) =
WriteStream.t_of_js (Ojs.get_prop_ascii Import.process "stderr")
let (set_stderr : WriteStream.t -> unit) =
fun (x667 : WriteStream.t) ->
ignore
(Ojs.call Import.process "stderr" [|(WriteStream.t_to_js x667)|])
let (stdin : ReadStream.t) =
ReadStream.t_of_js (Ojs.get_prop_ascii Import.process "stdin")
let (set_stdin : ReadStream.t -> unit) =
fun (x668 : ReadStream.t) ->
ignore
(Ojs.call Import.process "stdin" [|(ReadStream.t_to_js x668)|])
let (open_stdin : Socket.t) =
Socket.t_of_js (Ojs.get_prop_ascii Import.process "openStdin")
let (argv : string list) =
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii Import.process "argv")
let (set_argv : string list -> unit) =
fun (x670 : string list) ->
ignore
(Ojs.call Import.process "argv"
[|(Ojs.list_to_js Ojs.string_to_js x670)|])
let (argv0 : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "argv0")
let (set_argv0 : string -> unit) =
fun (x672 : string) ->
ignore (Ojs.call Import.process "argv0" [|(Ojs.string_to_js x672)|])
let (exec_argv : string list) =
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii Import.process "execArgv")
let (set_exec_argv : string list -> unit) =
fun (x674 : string list) ->
ignore
(Ojs.call Import.process "execArgv"
[|(Ojs.list_to_js Ojs.string_to_js x674)|])
let (exec_path : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "execPath")
let (set_exec_path : string -> unit) =
fun (x676 : string) ->
ignore
(Ojs.call Import.process "execPath" [|(Ojs.string_to_js x676)|])
let (abort : never) =
never_of_js (Ojs.get_prop_ascii Import.process "abort")
let (chdir : directory:string -> unit) =
fun ~directory:(x677 : string) ->
ignore (Ojs.call Import.process "chdir" [|(Ojs.string_to_js x677)|])
let (cwd : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "cwd")
let (debug_port : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "debugPort")
let (set_debug_port : int -> unit) =
fun (x678 : int) ->
ignore (Ojs.call Import.process "debugPort" [|(Ojs.int_to_js x678)|])
let (emit_warning :
warning:Error.t or_string ->
?name:string -> ?ctor:untyped_function -> unit -> unit)
=
fun ~warning:(x679 : Error.t or_string) ->
fun ?name:(x680 : string option) ->
fun ?ctor:(x681 : untyped_function option) ->
fun () ->
ignore
(let x686 = Import.process in
Ojs.call (Ojs.get_prop_ascii x686 "emitWarning") "apply"
[|x686;((let x682 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x682 "push"
[|(or_string_to_js Error.t_to_js x679)|]);
(match x680 with
| Some x684 ->
ignore
(Ojs.call x682 "push"
[|(Ojs.string_to_js x684)|])
| None -> ());
(match x681 with
| Some x683 ->
ignore
(Ojs.call x682 "push"
[|(untyped_function_to_js x683)|])
| None -> ());
x682))|])
let (env : ProcessEnv.t) =
ProcessEnv.t_of_js (Ojs.get_prop_ascii Import.process "env")
let (set_env : ProcessEnv.t -> unit) =
fun (x687 : ProcessEnv.t) ->
ignore (Ojs.call Import.process "env" [|(ProcessEnv.t_to_js x687)|])
let (exit : ?code:int -> unit -> never) =
fun ?code:(x688 : int option) ->
fun () ->
never_of_js
(let x691 = Import.process in
Ojs.call (Ojs.get_prop_ascii x691 "exit") "apply"
[|x691;((let x689 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x688 with
| Some x690 ->
ignore
(Ojs.call x689 "push" [|(Ojs.int_to_js x690)|])
| None -> ());
x689))|])
let (exit_code : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "exitCode")
let (set_exit_code : int -> unit) =
fun (x692 : int) ->
ignore (Ojs.call Import.process "exitCode" [|(Ojs.int_to_js x692)|])
let (getgid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "getgid")
let (setgid : id:string or_number -> unit) =
fun ~id:(x693 : string or_number) ->
ignore
(Ojs.call Import.process "setgid"
[|(or_number_to_js Ojs.string_to_js x693)|])
let (getuid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "getuid")
let (setuid : id:string or_number -> unit) =
fun ~id:(x695 : string or_number) ->
ignore
(Ojs.call Import.process "setuid"
[|(or_number_to_js Ojs.string_to_js x695)|])
let (geteuid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "geteuid")
let (seteuid : id:string or_number -> unit) =
fun ~id:(x697 : string or_number) ->
ignore
(Ojs.call Import.process "seteuid"
[|(or_number_to_js Ojs.string_to_js x697)|])
let (getegid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "getegid")
let (setegid : id:string or_number -> unit) =
fun ~id:(x699 : string or_number) ->
ignore
(Ojs.call Import.process "setegid"
[|(or_number_to_js Ojs.string_to_js x699)|])
let (getgroups : int list) =
Ojs.list_of_js Ojs.int_of_js
(Ojs.get_prop_ascii Import.process "getgroups")
let (setgroups : groups:string or_number list -> unit) =
fun ~groups:(x702 : string or_number list) ->
ignore
(Ojs.call Import.process "setgroups"
[|(Ojs.list_to_js
(fun (x703 : string or_number) ->
or_number_to_js Ojs.string_to_js x703) x702)|])
let (set_uncaught_exception_capture_callback :
cb:(err:Error.t -> unit) or_null -> unit) =
fun ~cb:(x705 : (err:Error.t -> unit) or_null) ->
ignore
(Ojs.call Import.process "setUncaughtExceptionCaptureCallback"
[|(or_null_to_js
(fun (x706 : err:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x707 : Ojs.t) -> x706 ~err:(Error.t_of_js x707)))
x705)|])
let (has_uncaught_exception_capture_callback : bool) =
Ojs.bool_of_js
(Ojs.get_prop_ascii Import.process
"hasUncaughtExceptionCaptureCallback")
let (version : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "version")
let (set_version : string -> unit) =
fun (x708 : string) ->
ignore
(Ojs.call Import.process "version" [|(Ojs.string_to_js x708)|])
let (versions : ProcessVersions.t) =
ProcessVersions.t_of_js (Ojs.get_prop_ascii Import.process "versions")
let (set_versions : ProcessVersions.t -> unit) =
fun (x709 : ProcessVersions.t) ->
ignore
(Ojs.call Import.process "versions"
[|(ProcessVersions.t_to_js x709)|])
let (config : AnonymousInterface8.t) =
AnonymousInterface8.t_of_js
(Ojs.get_prop_ascii Import.process "config")
let (set_config : AnonymousInterface8.t -> unit) =
fun (x710 : AnonymousInterface8.t) ->
ignore
(Ojs.call Import.process "config"
[|(AnonymousInterface8.t_to_js x710)|])
let (kill : pid:int -> ?signal:string or_number -> unit -> [ `L_b_true ])
=
fun ~pid:(x711 : int) ->
fun ?signal:(x712 : string or_number option) ->
fun () ->
let x717 =
let x716 = Import.process in
Ojs.call (Ojs.get_prop_ascii x716 "kill") "apply"
[|x716;((let x713 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x713 "push" [|(Ojs.int_to_js x711)|]);
(match x712 with
| Some x714 ->
ignore
(Ojs.call x713 "push"
[|(or_number_to_js Ojs.string_to_js x714)|])
| None -> ());
x713))|] in
match Ojs.bool_of_js x717 with
| true -> `L_b_true
| _ -> assert false
let (pid : int) = Ojs.int_of_js (Ojs.get_prop_ascii Import.process "pid")
let (set_pid : int -> unit) =
fun (x718 : int) ->
ignore (Ojs.call Import.process "pid" [|(Ojs.int_to_js x718)|])
let (ppid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "ppid")
let (set_ppid : int -> unit) =
fun (x719 : int) ->
ignore (Ojs.call Import.process "ppid" [|(Ojs.int_to_js x719)|])
let (title : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "title")
let (set_title : string -> unit) =
fun (x720 : string) ->
ignore (Ojs.call Import.process "title" [|(Ojs.string_to_js x720)|])
let (arch : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "arch")
let (set_arch : string -> unit) =
fun (x721 : string) ->
ignore (Ojs.call Import.process "arch" [|(Ojs.string_to_js x721)|])
let (platform : Platform.t) =
Platform.t_of_js (Ojs.get_prop_ascii Import.process "platform")
let (set_platform : Platform.t -> unit) =
fun (x722 : Platform.t) ->
ignore
(Ojs.call Import.process "platform" [|(Platform.t_to_js x722)|])
let (main_module : Module.t) =
Module.t_of_js (Ojs.get_prop_ascii Import.process "mainModule")
let (set_main_module : Module.t -> unit) =
fun (x723 : Module.t) ->
ignore
(Ojs.call Import.process "mainModule" [|(Module.t_to_js x723)|])
let (memory_usage : MemoryUsage.t) =
MemoryUsage.t_of_js (Ojs.get_prop_ascii Import.process "memoryUsage")
let (cpu_usage : ?previous_value:CpuUsage.t -> unit -> CpuUsage.t) =
fun ?previous_value:(x724 : CpuUsage.t option) ->
fun () ->
CpuUsage.t_of_js
(let x727 = Import.process in
Ojs.call (Ojs.get_prop_ascii x727 "cpuUsage") "apply"
[|x727;((let x725 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x724 with
| Some x726 ->
ignore
(Ojs.call x725 "push"
[|(CpuUsage.t_to_js x726)|])
| None -> ());
x725))|])
let (next_tick : callback:untyped_function -> args:any list -> unit) =
fun ~callback:(x728 : untyped_function) ->
fun ~args:(x729 : any list) ->
ignore
(let x732 = Import.process in
Ojs.call (Ojs.get_prop_ascii x732 "nextTick") "apply"
[|x732;((let x730 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x730 "push"
[|(untyped_function_to_js x728)|]);
List.iter
(fun (x731 : any) ->
ignore
(Ojs.call x730 "push" [|(any_to_js x731)|]))
x729;
x730))|])
let (release : ProcessRelease.t) =
ProcessRelease.t_of_js (Ojs.get_prop_ascii Import.process "release")
let (set_release : ProcessRelease.t -> unit) =
fun (x733 : ProcessRelease.t) ->
ignore
(Ojs.call Import.process "release"
[|(ProcessRelease.t_to_js x733)|])
let (features : AnonymousInterface6.t) =
AnonymousInterface6.t_of_js
(Ojs.get_prop_ascii Import.process "features")
let (set_features : AnonymousInterface6.t -> unit) =
fun (x734 : AnonymousInterface6.t) ->
ignore
(Ojs.call Import.process "features"
[|(AnonymousInterface6.t_to_js x734)|])
let (umask : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "umask")
let (umask' : mask:string or_number -> int) =
fun ~mask:(x735 : string or_number) ->
Ojs.int_of_js
(Ojs.call Import.process "umask"
[|(or_number_to_js Ojs.string_to_js x735)|])
let (uptime : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "uptime")
let (hrtime : HRTime.t) =
HRTime.t_of_js (Ojs.get_prop_ascii Import.process "hrtime")
let (set_hrtime : HRTime.t -> unit) =
fun (x737 : HRTime.t) ->
ignore (Ojs.call Import.process "hrtime" [|(HRTime.t_to_js x737)|])
let (domain : Node_domain.Domain.Domain.t) =
Node_domain.Domain.Domain.t_of_js
(Ojs.get_prop_ascii Import.process "domain")
let (set_domain : Node_domain.Domain.Domain.t -> unit) =
fun (x738 : Node_domain.Domain.Domain.t) ->
ignore
(Ojs.call Import.process "domain"
[|(Node_domain.Domain.Domain.t_to_js x738)|])
let (send :
message:any ->
?send_handle:any ->
?options:AnonymousInterface7.t ->
?callback:(error:Error.t or_null -> unit) -> unit -> bool)
=
fun ~message:(x739 : any) ->
fun ?send_handle:(x740 : any option) ->
fun ?options:(x741 : AnonymousInterface7.t option) ->
fun ?callback:(x742 : (error:Error.t or_null -> unit) option) ->
fun () ->
Ojs.bool_of_js
(let x749 = Import.process in
Ojs.call (Ojs.get_prop_ascii x749 "send") "apply"
[|x749;((let x743 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x743 "push" [|(any_to_js x739)|]);
(match x740 with
| Some x748 ->
ignore
(Ojs.call x743 "push"
[|(any_to_js x748)|])
| None -> ());
(match x741 with
| Some x747 ->
ignore
(Ojs.call x743 "push"
[|(AnonymousInterface7.t_to_js x747)|])
| None -> ());
(match x742 with
| Some x744 ->
ignore
(Ojs.call x743 "push"
[|(Ojs.fun_to_js 1
(fun (x745 : Ojs.t) ->
x744
~error:(or_null_of_js
Error.t_of_js
x745)))|])
| None -> ());
x743))|])
let (disconnect : unit) =
Ojs.unit_of_js (Ojs.get_prop_ascii Import.process "disconnect")
let (connected : bool) =
Ojs.bool_of_js (Ojs.get_prop_ascii Import.process "connected")
let (set_connected : bool -> unit) =
fun (x750 : bool) ->
ignore
(Ojs.call Import.process "connected" [|(Ojs.bool_to_js x750)|])
let (allowed_node_environment_flags : string ReadonlySet.t) =
ReadonlySet.t_of_js Ojs.string_of_js
(Ojs.get_prop_ascii Import.process "allowedNodeEnvironmentFlags")
let (set_allowed_node_environment_flags : string ReadonlySet.t -> unit) =
fun (x752 : string ReadonlySet.t) ->
ignore
(Ojs.call Import.process "allowedNodeEnvironmentFlags"
[|(ReadonlySet.t_to_js Ojs.string_to_js x752)|])
let (report : ProcessReport.t) =
ProcessReport.t_of_js (Ojs.get_prop_ascii Import.process "report")
let (set_report : ProcessReport.t -> unit) =
fun (x754 : ProcessReport.t) ->
ignore
(Ojs.call Import.process "report" [|(ProcessReport.t_to_js x754)|])
let (resource_usage : ResourceUsage.t) =
ResourceUsage.t_of_js
(Ojs.get_prop_ascii Import.process "resourceUsage")
let (trace_deprecation : bool) =
Ojs.bool_of_js (Ojs.get_prop_ascii Import.process "traceDeprecation")
let (set_trace_deprecation : bool -> unit) =
fun (x755 : bool) ->
ignore
(Ojs.call Import.process "traceDeprecation"
[|(Ojs.bool_to_js x755)|])
let (on : string -> Ojs.t -> unit) =
fun (x756 : string) ->
fun (x757 : Ojs.t) ->
ignore (Ojs.call Ojs.global "on" [|(Ojs.string_to_js x756);x757|])
let (add_listener : string -> Ojs.t -> unit) =
fun (x758 : string) ->
fun (x759 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "addListener"
[|(Ojs.string_to_js x758);x759|])
let (once : string -> Ojs.t -> unit) =
fun (x760 : string) ->
fun (x761 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "once" [|(Ojs.string_to_js x760);x761|])
let (prepend_listener : string -> Ojs.t -> unit) =
fun (x762 : string) ->
fun (x763 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "prependListener"
[|(Ojs.string_to_js x762);x763|])
let (prepend_once_listener : string -> Ojs.t -> unit) =
fun (x764 : string) ->
fun (x765 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "prependOnceListener"
[|(Ojs.string_to_js x764);x765|])
let with_listener_fn fn =
function
| `BeforeExit f -> (fn "beforeExit") @@ (BeforeExitListener.t_to_js f)
| `Disconnect f -> (fn "disconnect") @@ (DisconnectListener.t_to_js f)
| `Exit f -> (fn "exit") @@ (ExitListener.t_to_js f)
| `RejectionHandled f ->
(fn "rejectionHandled") @@ (RejectionHandledListener.t_to_js f)
| `UncaughtException f ->
(fn "uncaughtException") @@ (UncaughtExceptionListener.t_to_js f)
| `UnhandledRejection f ->
(fn "unhandledRejection") @@ (UnhandledRejectionListener.t_to_js f)
| `Warning f -> (fn "warning") @@ (WarningListener.t_to_js f)
| `Message f -> (fn "message") @@ (MessageListener.t_to_js f)
| `NewListener f ->
(fn "newListener") @@ (NewListenerListener.t_to_js f)
| `RemoveListener f ->
(fn "removeListener") @@ (RemoveListenerListener.t_to_js f)
| `MultipleResolves f ->
(fn "multipleResolves") @@ (MultipleResolvesListener.t_to_js f)
let on = with_listener_fn on
let add_listener = with_listener_fn add_listener
let once = with_listener_fn once
let prepend_listener = with_listener_fn prepend_listener
let prepend_once_listener = with_listener_fn prepend_once_listener
let (emit_before_exit : event:[ `beforeExit ] -> code:int -> bool) =
fun ~event:(x777 : [ `beforeExit ]) ->
fun ~code:(x778 : int) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x777 with
| `beforeExit -> Ojs.string_to_js "beforeExit"));(
Ojs.int_to_js x778)|])
let (emit_disconnect : event:[ `disconnect ] -> bool) =
fun ~event:(x779 : [ `disconnect ]) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x779 with
| `disconnect -> Ojs.string_to_js "disconnect"))|])
let (emit_exit : event:[ `exit ] -> code:int -> bool) =
fun ~event:(x780 : [ `exit ]) ->
fun ~code:(x781 : int) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x780 with | `exit -> Ojs.string_to_js "exit"));(
Ojs.int_to_js x781)|])
let (emit_rejection_handled :
event:[ `rejectionHandled ] -> promise:any Promise.t -> bool) =
fun ~event:(x782 : [ `rejectionHandled ]) ->
fun ~promise:(x783 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x782 with
| `rejectionHandled -> Ojs.string_to_js "rejectionHandled"));(
Promise.t_to_js any_to_js x783)|])
let (emit_uncaught_exception :
event:[ `uncaughtException ] -> error:Error.t -> bool) =
fun ~event:(x785 : [ `uncaughtException ]) ->
fun ~error:(x786 : Error.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x785 with
| `uncaughtException ->
Ojs.string_to_js "uncaughtException"));(Error.t_to_js
x786)|])
let (emit_uncaught_exception_monitor :
event:[ `uncaughtExceptionMonitor ] -> error:Error.t -> bool) =
fun ~event:(x787 : [ `uncaughtExceptionMonitor ]) ->
fun ~error:(x788 : Error.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x787 with
| `uncaughtExceptionMonitor ->
Ojs.string_to_js "uncaughtExceptionMonitor"));(
Error.t_to_js x788)|])
let (emit_unhandled_rejection :
event:[ `unhandledRejection ] ->
reason:any -> promise:any Promise.t -> bool)
=
fun ~event:(x789 : [ `unhandledRejection ]) ->
fun ~reason:(x790 : any) ->
fun ~promise:(x791 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x789 with
| `unhandledRejection ->
Ojs.string_to_js "unhandledRejection"));(any_to_js
x790);(
Promise.t_to_js any_to_js x791)|])
let (emit_warning : event:[ `warning ] -> warning:Error.t -> bool) =
fun ~event:(x793 : [ `warning ]) ->
fun ~warning:(x794 : Error.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x793 with | `warning -> Ojs.string_to_js "warning"));(
Error.t_to_js x794)|])
let (emit_message :
event:[ `message ] -> message:any -> send_handle:any -> Process.t) =
fun ~event:(x795 : [ `message ]) ->
fun ~message:(x796 : any) ->
fun ~send_handle:(x797 : any) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x795 with | `message -> Ojs.string_to_js "message"));(
any_to_js x796);(any_to_js x797)|])
let (emit_new_listener :
event:[ `newListener ] ->
event_name:symbol or_string ->
listener:(args:any list -> unit) -> Process.t)
=
fun ~event:(x798 : [ `newListener ]) ->
fun ~event_name:(x799 : symbol or_string) ->
fun ~listener:(x801 : args:any list -> unit) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x798 with
| `newListener -> Ojs.string_to_js "newListener"));(
or_string_to_js symbol_to_js x799);(Ojs.fun_to_js_args
(fun (x802 : _) ->
x801
~args:(
Ojs.list_of_js_from
any_of_js
x802 0)))|])
let (emit_remove_listener :
event:[ `removeListener ] ->
event_name:string -> listener:(args:any list -> unit) -> Process.t)
=
fun ~event:(x804 : [ `removeListener ]) ->
fun ~event_name:(x805 : string) ->
fun ~listener:(x806 : args:any list -> unit) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x804 with
| `removeListener -> Ojs.string_to_js "removeListener"));(
Ojs.string_to_js x805);(Ojs.fun_to_js_args
(fun (x807 : _) ->
x806
~args:(Ojs.list_of_js_from
any_of_js x807 0)))|])
let (emit_multiple_resolves :
event:[ `multipleResolves ] ->
listener:MultipleResolvesListener.t -> Process.t)
=
fun ~event:(x809 : [ `multipleResolves ]) ->
fun ~listener:(x810 : MultipleResolvesListener.t) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x809 with
| `multipleResolves -> Ojs.string_to_js "multipleResolves"));(
MultipleResolvesListener.t_to_js x810)|])
end
let (process : Process.Process.t) =
Process.Process.t_of_js (Ojs.get_prop_ascii Ojs.global "process")
| null | https://raw.githubusercontent.com/tmattio/js-bindings/ca3bd6a12db519c8de7f41b303f14cf70cfd4c5f/lib/node/node_process.ml | ocaml | [@@@js.dummy "!! This code has been generated by gen_js_api !!"]
[@@@ocaml.warning "-7-32-39"]
[@@@ocaml.warning "-7-11-32-33-39"]
open Es2020
open Node_globals
module AnonymousInterface0 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2
and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1
end
module AnonymousInterface1 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x4 : Ojs.t) -> x4
and t_to_js : t -> Ojs.t = fun (x3 : Ojs.t) -> x3
let (cflags : t -> any list) =
fun (x5 : t) ->
Ojs.list_of_js any_of_js (Ojs.get_prop_ascii (t_to_js x5) "cflags")
let (set_cflags : t -> any list -> unit) =
fun (x7 : t) ->
fun (x8 : any list) ->
Ojs.set_prop_ascii (t_to_js x7) "cflags"
(Ojs.list_to_js any_to_js x8)
let (default_configuration : t -> string) =
fun (x10 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x10) "default_configuration")
let (set_default_configuration : t -> string -> unit) =
fun (x11 : t) ->
fun (x12 : string) ->
Ojs.set_prop_ascii (t_to_js x11) "default_configuration"
(Ojs.string_to_js x12)
let (defines : t -> string list) =
fun (x13 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x13) "defines")
let (set_defines : t -> string list -> unit) =
fun (x15 : t) ->
fun (x16 : string list) ->
Ojs.set_prop_ascii (t_to_js x15) "defines"
(Ojs.list_to_js Ojs.string_to_js x16)
let (include_dirs : t -> string list) =
fun (x18 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x18) "include_dirs")
let (set_include_dirs : t -> string list -> unit) =
fun (x20 : t) ->
fun (x21 : string list) ->
Ojs.set_prop_ascii (t_to_js x20) "include_dirs"
(Ojs.list_to_js Ojs.string_to_js x21)
let (libraries : t -> string list) =
fun (x23 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x23) "libraries")
let (set_libraries : t -> string list -> unit) =
fun (x25 : t) ->
fun (x26 : string list) ->
Ojs.set_prop_ascii (t_to_js x25) "libraries"
(Ojs.list_to_js Ojs.string_to_js x26)
end
module AnonymousInterface2 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x29 : Ojs.t) -> x29
and t_to_js : t -> Ojs.t = fun (x28 : Ojs.t) -> x28
let (clang : t -> int) =
fun (x30 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x30) "clang")
let (set_clang : t -> int -> unit) =
fun (x31 : t) ->
fun (x32 : int) ->
Ojs.set_prop_ascii (t_to_js x31) "clang" (Ojs.int_to_js x32)
let (host_arch : t -> string) =
fun (x33 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x33) "host_arch")
let (set_host_arch : t -> string -> unit) =
fun (x34 : t) ->
fun (x35 : string) ->
Ojs.set_prop_ascii (t_to_js x34) "host_arch" (Ojs.string_to_js x35)
let (node_install_npm : t -> bool) =
fun (x36 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x36) "node_install_npm")
let (set_node_install_npm : t -> bool -> unit) =
fun (x37 : t) ->
fun (x38 : bool) ->
Ojs.set_prop_ascii (t_to_js x37) "node_install_npm"
(Ojs.bool_to_js x38)
let (node_install_waf : t -> bool) =
fun (x39 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x39) "node_install_waf")
let (set_node_install_waf : t -> bool -> unit) =
fun (x40 : t) ->
fun (x41 : bool) ->
Ojs.set_prop_ascii (t_to_js x40) "node_install_waf"
(Ojs.bool_to_js x41)
let (node_prefix : t -> string) =
fun (x42 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x42) "node_prefix")
let (set_node_prefix : t -> string -> unit) =
fun (x43 : t) ->
fun (x44 : string) ->
Ojs.set_prop_ascii (t_to_js x43) "node_prefix"
(Ojs.string_to_js x44)
let (node_shared_openssl : t -> bool) =
fun (x45 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x45) "node_shared_openssl")
let (set_node_shared_openssl : t -> bool -> unit) =
fun (x46 : t) ->
fun (x47 : bool) ->
Ojs.set_prop_ascii (t_to_js x46) "node_shared_openssl"
(Ojs.bool_to_js x47)
let (node_shared_v8 : t -> bool) =
fun (x48 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x48) "node_shared_v8")
let (set_node_shared_v8 : t -> bool -> unit) =
fun (x49 : t) ->
fun (x50 : bool) ->
Ojs.set_prop_ascii (t_to_js x49) "node_shared_v8"
(Ojs.bool_to_js x50)
let (node_shared_zlib : t -> bool) =
fun (x51 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x51) "node_shared_zlib")
let (set_node_shared_zlib : t -> bool -> unit) =
fun (x52 : t) ->
fun (x53 : bool) ->
Ojs.set_prop_ascii (t_to_js x52) "node_shared_zlib"
(Ojs.bool_to_js x53)
let (node_use_dtrace : t -> bool) =
fun (x54 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x54) "node_use_dtrace")
let (set_node_use_dtrace : t -> bool -> unit) =
fun (x55 : t) ->
fun (x56 : bool) ->
Ojs.set_prop_ascii (t_to_js x55) "node_use_dtrace"
(Ojs.bool_to_js x56)
let (node_use_etw : t -> bool) =
fun (x57 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x57) "node_use_etw")
let (set_node_use_etw : t -> bool -> unit) =
fun (x58 : t) ->
fun (x59 : bool) ->
Ojs.set_prop_ascii (t_to_js x58) "node_use_etw"
(Ojs.bool_to_js x59)
let (node_use_openssl : t -> bool) =
fun (x60 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x60) "node_use_openssl")
let (set_node_use_openssl : t -> bool -> unit) =
fun (x61 : t) ->
fun (x62 : bool) ->
Ojs.set_prop_ascii (t_to_js x61) "node_use_openssl"
(Ojs.bool_to_js x62)
let (tararch : t -> string) =
fun (x63 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x63) "tararch")
let (set_tararch : t -> string -> unit) =
fun (x64 : t) ->
fun (x65 : string) ->
Ojs.set_prop_ascii (t_to_js x64) "tararch" (Ojs.string_to_js x65)
let (v8_no_strict_aliasing : t -> int) =
fun (x66 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x66) "v8_no_strict_aliasing")
let (set_v8_no_strict_aliasing : t -> int -> unit) =
fun (x67 : t) ->
fun (x68 : int) ->
Ojs.set_prop_ascii (t_to_js x67) "v8_no_strict_aliasing"
(Ojs.int_to_js x68)
let (v8_use_snapshot : t -> bool) =
fun (x69 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x69) "v8_use_snapshot")
let (set_v8_use_snapshot : t -> bool -> unit) =
fun (x70 : t) ->
fun (x71 : bool) ->
Ojs.set_prop_ascii (t_to_js x70) "v8_use_snapshot"
(Ojs.bool_to_js x71)
let (visibility : t -> string) =
fun (x72 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x72) "visibility")
let (set_visibility : t -> string -> unit) =
fun (x73 : t) ->
fun (x74 : string) ->
Ojs.set_prop_ascii (t_to_js x73) "visibility"
(Ojs.string_to_js x74)
end
module AnonymousInterface3 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x76 : Ojs.t) -> x76
and t_to_js : t -> Ojs.t = fun (x75 : Ojs.t) -> x75
let (fd : t -> [ `L_n_0 ]) =
fun (x77 : t) ->
let x78 = Ojs.get_prop_ascii (t_to_js x77) "fd" in
match Ojs.int_of_js x78 with | 0 -> `L_n_0 | _ -> assert false
let (set_fd : t -> [ `L_n_0 ] -> unit) =
fun (x79 : t) ->
fun (x80 : [ `L_n_0 ]) ->
Ojs.set_prop_ascii (t_to_js x79) "fd"
(match x80 with | `L_n_0 -> Ojs.string_to_js "LN0")
end
module AnonymousInterface4 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x82 : Ojs.t) -> x82
and t_to_js : t -> Ojs.t = fun (x81 : Ojs.t) -> x81
let (fd : t -> [ `L_n_1 ]) =
fun (x83 : t) ->
let x84 = Ojs.get_prop_ascii (t_to_js x83) "fd" in
match Ojs.int_of_js x84 with | 1 -> `L_n_1 | _ -> assert false
let (set_fd : t -> [ `L_n_1 ] -> unit) =
fun (x85 : t) ->
fun (x86 : [ `L_n_1 ]) ->
Ojs.set_prop_ascii (t_to_js x85) "fd"
(match x86 with | `L_n_1 -> Ojs.string_to_js "LN1")
end
module AnonymousInterface5 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x88 : Ojs.t) -> x88
and t_to_js : t -> Ojs.t = fun (x87 : Ojs.t) -> x87
let (fd : t -> [ `L_n_2 ]) =
fun (x89 : t) ->
let x90 = Ojs.get_prop_ascii (t_to_js x89) "fd" in
match Ojs.int_of_js x90 with | 2 -> `L_n_2 | _ -> assert false
let (set_fd : t -> [ `L_n_2 ] -> unit) =
fun (x91 : t) ->
fun (x92 : [ `L_n_2 ]) ->
Ojs.set_prop_ascii (t_to_js x91) "fd"
(match x92 with | `L_n_2 -> Ojs.string_to_js "LN2")
end
module AnonymousInterface6 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x94 : Ojs.t) -> x94
and t_to_js : t -> Ojs.t = fun (x93 : Ojs.t) -> x93
let (inspector : t -> bool) =
fun (x95 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x95) "inspector")
let (set_inspector : t -> bool -> unit) =
fun (x96 : t) ->
fun (x97 : bool) ->
Ojs.set_prop_ascii (t_to_js x96) "inspector" (Ojs.bool_to_js x97)
let (debug : t -> bool) =
fun (x98 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x98) "debug")
let (set_debug : t -> bool -> unit) =
fun (x99 : t) ->
fun (x100 : bool) ->
Ojs.set_prop_ascii (t_to_js x99) "debug" (Ojs.bool_to_js x100)
let (uv : t -> bool) =
fun (x101 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x101) "uv")
let (set_uv : t -> bool -> unit) =
fun (x102 : t) ->
fun (x103 : bool) ->
Ojs.set_prop_ascii (t_to_js x102) "uv" (Ojs.bool_to_js x103)
let (ipv6 : t -> bool) =
fun (x104 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x104) "ipv6")
let (set_ipv6 : t -> bool -> unit) =
fun (x105 : t) ->
fun (x106 : bool) ->
Ojs.set_prop_ascii (t_to_js x105) "ipv6" (Ojs.bool_to_js x106)
let (tls_alpn : t -> bool) =
fun (x107 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x107) "tls_alpn")
let (set_tls_alpn : t -> bool -> unit) =
fun (x108 : t) ->
fun (x109 : bool) ->
Ojs.set_prop_ascii (t_to_js x108) "tls_alpn" (Ojs.bool_to_js x109)
let (tls_sni : t -> bool) =
fun (x110 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x110) "tls_sni")
let (set_tls_sni : t -> bool -> unit) =
fun (x111 : t) ->
fun (x112 : bool) ->
Ojs.set_prop_ascii (t_to_js x111) "tls_sni" (Ojs.bool_to_js x112)
let (tls_ocsp : t -> bool) =
fun (x113 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x113) "tls_ocsp")
let (set_tls_ocsp : t -> bool -> unit) =
fun (x114 : t) ->
fun (x115 : bool) ->
Ojs.set_prop_ascii (t_to_js x114) "tls_ocsp" (Ojs.bool_to_js x115)
let (tls : t -> bool) =
fun (x116 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x116) "tls")
let (set_tls : t -> bool -> unit) =
fun (x117 : t) ->
fun (x118 : bool) ->
Ojs.set_prop_ascii (t_to_js x117) "tls" (Ojs.bool_to_js x118)
end
module AnonymousInterface7 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x120 : Ojs.t) -> x120
and t_to_js : t -> Ojs.t = fun (x119 : Ojs.t) -> x119
let (swallow_errors : t -> bool) =
fun (x121 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x121) "swallowErrors")
let (set_swallow_errors : t -> bool -> unit) =
fun (x122 : t) ->
fun (x123 : bool) ->
Ojs.set_prop_ascii (t_to_js x122) "swallowErrors"
(Ojs.bool_to_js x123)
end
module AnonymousInterface8 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x125 : Ojs.t) -> x125
and t_to_js : t -> Ojs.t = fun (x124 : Ojs.t) -> x124
let (tardefaults : t -> AnonymousInterface1.t) =
fun (x126 : t) ->
AnonymousInterface1.t_of_js
(Ojs.get_prop_ascii (t_to_js x126) "tardefaults")
let (set_tardefaults : t -> AnonymousInterface1.t -> unit) =
fun (x127 : t) ->
fun (x128 : AnonymousInterface1.t) ->
Ojs.set_prop_ascii (t_to_js x127) "tardefaults"
(AnonymousInterface1.t_to_js x128)
let (variables : t -> AnonymousInterface2.t) =
fun (x129 : t) ->
AnonymousInterface2.t_of_js
(Ojs.get_prop_ascii (t_to_js x129) "variables")
let (set_variables : t -> AnonymousInterface2.t -> unit) =
fun (x130 : t) ->
fun (x131 : AnonymousInterface2.t) ->
Ojs.set_prop_ascii (t_to_js x130) "variables"
(AnonymousInterface2.t_to_js x131)
end
module Process =
struct
open Node_tty
module ReadStream = struct include struct include Tty.ReadStream end end
module WriteStream =
struct include struct include Tty.WriteStream end end
module MemoryUsage =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x133 : Ojs.t) -> x133
and t_to_js : t -> Ojs.t = fun (x132 : Ojs.t) -> x132
let (rss : t -> int) =
fun (x134 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x134) "rss")
let (set_rss : t -> int -> unit) =
fun (x135 : t) ->
fun (x136 : int) ->
Ojs.set_prop_ascii (t_to_js x135) "rss" (Ojs.int_to_js x136)
let (heap_total : t -> int) =
fun (x137 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x137) "heapTotal")
let (set_heap_total : t -> int -> unit) =
fun (x138 : t) ->
fun (x139 : int) ->
Ojs.set_prop_ascii (t_to_js x138) "heapTotal"
(Ojs.int_to_js x139)
let (heap_used : t -> int) =
fun (x140 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x140) "heapUsed")
let (set_heap_used : t -> int -> unit) =
fun (x141 : t) ->
fun (x142 : int) ->
Ojs.set_prop_ascii (t_to_js x141) "heapUsed"
(Ojs.int_to_js x142)
let (external_ : t -> int) =
fun (x143 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x143) "external")
let (set_external : t -> int -> unit) =
fun (x144 : t) ->
fun (x145 : int) ->
Ojs.set_prop_ascii (t_to_js x144) "external"
(Ojs.int_to_js x145)
let (array_buffers : t -> int) =
fun (x146 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x146) "arrayBuffers")
let (set_array_buffers : t -> int -> unit) =
fun (x147 : t) ->
fun (x148 : int) ->
Ojs.set_prop_ascii (t_to_js x147) "arrayBuffers"
(Ojs.int_to_js x148)
end
module CpuUsage =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x150 : Ojs.t) -> x150
and t_to_js : t -> Ojs.t = fun (x149 : Ojs.t) -> x149
let (user : t -> int) =
fun (x151 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x151) "user")
let (set_user : t -> int -> unit) =
fun (x152 : t) ->
fun (x153 : int) ->
Ojs.set_prop_ascii (t_to_js x152) "user" (Ojs.int_to_js x153)
let (system : t -> int) =
fun (x154 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x154) "system")
let (set_system : t -> int -> unit) =
fun (x155 : t) ->
fun (x156 : int) ->
Ojs.set_prop_ascii (t_to_js x155) "system" (Ojs.int_to_js x156)
end
module ProcessRelease =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x158 : Ojs.t) -> x158
and t_to_js : t -> Ojs.t = fun (x157 : Ojs.t) -> x157
let (name : t -> string) =
fun (x159 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x159) "name")
let (set_name : t -> string -> unit) =
fun (x160 : t) ->
fun (x161 : string) ->
Ojs.set_prop_ascii (t_to_js x160) "name"
(Ojs.string_to_js x161)
let (source_url : t -> string) =
fun (x162 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x162) "sourceUrl")
let (set_source_url : t -> string -> unit) =
fun (x163 : t) ->
fun (x164 : string) ->
Ojs.set_prop_ascii (t_to_js x163) "sourceUrl"
(Ojs.string_to_js x164)
let (headers_url : t -> string) =
fun (x165 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x165) "headersUrl")
let (set_headers_url : t -> string -> unit) =
fun (x166 : t) ->
fun (x167 : string) ->
Ojs.set_prop_ascii (t_to_js x166) "headersUrl"
(Ojs.string_to_js x167)
let (lib_url : t -> string) =
fun (x168 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x168) "libUrl")
let (set_lib_url : t -> string -> unit) =
fun (x169 : t) ->
fun (x170 : string) ->
Ojs.set_prop_ascii (t_to_js x169) "libUrl"
(Ojs.string_to_js x170)
let (lts : t -> string) =
fun (x171 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x171) "lts")
let (set_lts : t -> string -> unit) =
fun (x172 : t) ->
fun (x173 : string) ->
Ojs.set_prop_ascii (t_to_js x172) "lts" (Ojs.string_to_js x173)
end
module ProcessVersions =
struct
type t = string Dict.t
let rec t_of_js : Ojs.t -> t =
fun (x176 : Ojs.t) -> Dict.t_of_js Ojs.string_of_js x176
and t_to_js : t -> Ojs.t =
fun (x174 : string Dict.t) -> Dict.t_to_js Ojs.string_to_js x174
let (http_parser : t -> string) =
fun (x178 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x178) "http_parser")
let (set_http_parser : t -> string -> unit) =
fun (x179 : t) ->
fun (x180 : string) ->
Ojs.set_prop_ascii (t_to_js x179) "http_parser"
(Ojs.string_to_js x180)
let (node : t -> string) =
fun (x181 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x181) "node")
let (set_node : t -> string -> unit) =
fun (x182 : t) ->
fun (x183 : string) ->
Ojs.set_prop_ascii (t_to_js x182) "node"
(Ojs.string_to_js x183)
let (v8 : t -> string) =
fun (x184 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x184) "v8")
let (set_v8 : t -> string -> unit) =
fun (x185 : t) ->
fun (x186 : string) ->
Ojs.set_prop_ascii (t_to_js x185) "v8" (Ojs.string_to_js x186)
let (ares : t -> string) =
fun (x187 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x187) "ares")
let (set_ares : t -> string -> unit) =
fun (x188 : t) ->
fun (x189 : string) ->
Ojs.set_prop_ascii (t_to_js x188) "ares"
(Ojs.string_to_js x189)
let (uv : t -> string) =
fun (x190 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x190) "uv")
let (set_uv : t -> string -> unit) =
fun (x191 : t) ->
fun (x192 : string) ->
Ojs.set_prop_ascii (t_to_js x191) "uv" (Ojs.string_to_js x192)
let (zlib : t -> string) =
fun (x193 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x193) "zlib")
let (set_zlib : t -> string -> unit) =
fun (x194 : t) ->
fun (x195 : string) ->
Ojs.set_prop_ascii (t_to_js x194) "zlib"
(Ojs.string_to_js x195)
let (modules : t -> string) =
fun (x196 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x196) "modules")
let (set_modules : t -> string -> unit) =
fun (x197 : t) ->
fun (x198 : string) ->
Ojs.set_prop_ascii (t_to_js x197) "modules"
(Ojs.string_to_js x198)
let (openssl : t -> string) =
fun (x199 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x199) "openssl")
let (set_openssl : t -> string -> unit) =
fun (x200 : t) ->
fun (x201 : string) ->
Ojs.set_prop_ascii (t_to_js x200) "openssl"
(Ojs.string_to_js x201)
end
module Platform =
struct
type t =
[ `aix | `android | `cygwin | `darwin | `freebsd | `linux
| `netbsd | `openbsd | `sunos | `win32 ]
let rec t_of_js : Ojs.t -> t =
fun (x203 : Ojs.t) ->
let x204 = x203 in
match Ojs.string_of_js x204 with
| "aix" -> `aix
| "android" -> `android
| "cygwin" -> `cygwin
| "darwin" -> `darwin
| "freebsd" -> `freebsd
| "linux" -> `linux
| "netbsd" -> `netbsd
| "openbsd" -> `openbsd
| "sunos" -> `sunos
| "win32" -> `win32
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x202 :
[ `aix | `android | `cygwin | `darwin | `freebsd |
`linux
| `netbsd | `openbsd | `sunos | `win32 ])
->
match x202 with
| `aix -> Ojs.string_to_js "aix"
| `android -> Ojs.string_to_js "android"
| `cygwin -> Ojs.string_to_js "cygwin"
| `darwin -> Ojs.string_to_js "darwin"
| `freebsd -> Ojs.string_to_js "freebsd"
| `linux -> Ojs.string_to_js "linux"
| `netbsd -> Ojs.string_to_js "netbsd"
| `openbsd -> Ojs.string_to_js "openbsd"
| `sunos -> Ojs.string_to_js "sunos"
| `win32 -> Ojs.string_to_js "win32"
end
module Signals =
struct
type t =
[ `SIGABRT | `SIGALRM | `SIGBREAK | `SIGBUS | `SIGCHLD
| `SIGCONT | `SIGFPE | `SIGHUP | `SIGILL | `SIGINFO |
`SIGINT
| `SIGIO | `SIGIOT | `SIGKILL | `SIGLOST | `SIGPIPE
| `SIGPOLL | `SIGPROF | `SIGPWR | `SIGQUIT | `SIGSEGV
| `SIGSTKFLT | `SIGSTOP | `SIGSYS | `SIGTERM | `SIGTRAP
| `SIGTSTP | `SIGTTIN | `SIGTTOU | `SIGUNUSED | `SIGURG
| `SIGUSR1 | `SIGUSR2 | `SIGVTALRM | `SIGWINCH | `SIGXCPU
| `SIGXFSZ ]
let rec t_of_js : Ojs.t -> t =
fun (x206 : Ojs.t) ->
let x207 = x206 in
match Ojs.string_of_js x207 with
| "SIGABRT" -> `SIGABRT
| "SIGALRM" -> `SIGALRM
| "SIGBREAK" -> `SIGBREAK
| "SIGBUS" -> `SIGBUS
| "SIGCHLD" -> `SIGCHLD
| "SIGCONT" -> `SIGCONT
| "SIGFPE" -> `SIGFPE
| "SIGHUP" -> `SIGHUP
| "SIGILL" -> `SIGILL
| "SIGINFO" -> `SIGINFO
| "SIGINT" -> `SIGINT
| "SIGIO" -> `SIGIO
| "SIGIOT" -> `SIGIOT
| "SIGKILL" -> `SIGKILL
| "SIGLOST" -> `SIGLOST
| "SIGPIPE" -> `SIGPIPE
| "SIGPOLL" -> `SIGPOLL
| "SIGPROF" -> `SIGPROF
| "SIGPWR" -> `SIGPWR
| "SIGQUIT" -> `SIGQUIT
| "SIGSEGV" -> `SIGSEGV
| "SIGSTKFLT" -> `SIGSTKFLT
| "SIGSTOP" -> `SIGSTOP
| "SIGSYS" -> `SIGSYS
| "SIGTERM" -> `SIGTERM
| "SIGTRAP" -> `SIGTRAP
| "SIGTSTP" -> `SIGTSTP
| "SIGTTIN" -> `SIGTTIN
| "SIGTTOU" -> `SIGTTOU
| "SIGUNUSED" -> `SIGUNUSED
| "SIGURG" -> `SIGURG
| "SIGUSR1" -> `SIGUSR1
| "SIGUSR2" -> `SIGUSR2
| "SIGVTALRM" -> `SIGVTALRM
| "SIGWINCH" -> `SIGWINCH
| "SIGXCPU" -> `SIGXCPU
| "SIGXFSZ" -> `SIGXFSZ
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x205 :
[ `SIGABRT | `SIGALRM | `SIGBREAK | `SIGBUS | `SIGCHLD
| `SIGCONT | `SIGFPE | `SIGHUP | `SIGILL | `SIGINFO
| `SIGINT | `SIGIO | `SIGIOT | `SIGKILL | `SIGLOST
| `SIGPIPE | `SIGPOLL | `SIGPROF | `SIGPWR | `SIGQUIT
| `SIGSEGV | `SIGSTKFLT | `SIGSTOP | `SIGSYS | `SIGTERM
| `SIGTRAP | `SIGTSTP | `SIGTTIN | `SIGTTOU | `SIGUNUSED
| `SIGURG | `SIGUSR1 | `SIGUSR2 | `SIGVTALRM | `SIGWINCH
| `SIGXCPU | `SIGXFSZ ])
->
match x205 with
| `SIGABRT -> Ojs.string_to_js "SIGABRT"
| `SIGALRM -> Ojs.string_to_js "SIGALRM"
| `SIGBREAK -> Ojs.string_to_js "SIGBREAK"
| `SIGBUS -> Ojs.string_to_js "SIGBUS"
| `SIGCHLD -> Ojs.string_to_js "SIGCHLD"
| `SIGCONT -> Ojs.string_to_js "SIGCONT"
| `SIGFPE -> Ojs.string_to_js "SIGFPE"
| `SIGHUP -> Ojs.string_to_js "SIGHUP"
| `SIGILL -> Ojs.string_to_js "SIGILL"
| `SIGINFO -> Ojs.string_to_js "SIGINFO"
| `SIGINT -> Ojs.string_to_js "SIGINT"
| `SIGIO -> Ojs.string_to_js "SIGIO"
| `SIGIOT -> Ojs.string_to_js "SIGIOT"
| `SIGKILL -> Ojs.string_to_js "SIGKILL"
| `SIGLOST -> Ojs.string_to_js "SIGLOST"
| `SIGPIPE -> Ojs.string_to_js "SIGPIPE"
| `SIGPOLL -> Ojs.string_to_js "SIGPOLL"
| `SIGPROF -> Ojs.string_to_js "SIGPROF"
| `SIGPWR -> Ojs.string_to_js "SIGPWR"
| `SIGQUIT -> Ojs.string_to_js "SIGQUIT"
| `SIGSEGV -> Ojs.string_to_js "SIGSEGV"
| `SIGSTKFLT -> Ojs.string_to_js "SIGSTKFLT"
| `SIGSTOP -> Ojs.string_to_js "SIGSTOP"
| `SIGSYS -> Ojs.string_to_js "SIGSYS"
| `SIGTERM -> Ojs.string_to_js "SIGTERM"
| `SIGTRAP -> Ojs.string_to_js "SIGTRAP"
| `SIGTSTP -> Ojs.string_to_js "SIGTSTP"
| `SIGTTIN -> Ojs.string_to_js "SIGTTIN"
| `SIGTTOU -> Ojs.string_to_js "SIGTTOU"
| `SIGUNUSED -> Ojs.string_to_js "SIGUNUSED"
| `SIGURG -> Ojs.string_to_js "SIGURG"
| `SIGUSR1 -> Ojs.string_to_js "SIGUSR1"
| `SIGUSR2 -> Ojs.string_to_js "SIGUSR2"
| `SIGVTALRM -> Ojs.string_to_js "SIGVTALRM"
| `SIGWINCH -> Ojs.string_to_js "SIGWINCH"
| `SIGXCPU -> Ojs.string_to_js "SIGXCPU"
| `SIGXFSZ -> Ojs.string_to_js "SIGXFSZ"
end
module MultipleResolvesType =
struct
type t = [ `reject | `resolve ]
let rec t_of_js : Ojs.t -> t =
fun (x209 : Ojs.t) ->
let x210 = x209 in
match Ojs.string_of_js x210 with
| "reject" -> `reject
| "resolve" -> `resolve
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x208 : [ `reject | `resolve ]) ->
match x208 with
| `reject -> Ojs.string_to_js "reject"
| `resolve -> Ojs.string_to_js "resolve"
end
module BeforeExitListener =
struct
type t = code:int -> unit
let rec t_of_js : Ojs.t -> t =
fun (x213 : Ojs.t) ->
fun ~code:(x214 : int) ->
ignore (Ojs.apply x213 [|(Ojs.int_to_js x214)|])
and t_to_js : t -> Ojs.t =
fun (x211 : code:int -> unit) ->
Ojs.fun_to_js 1
(fun (x212 : Ojs.t) -> x211 ~code:(Ojs.int_of_js x212))
end
module DisconnectListener =
struct
type t = unit -> unit
let rec t_of_js : Ojs.t -> t =
fun (x216 : Ojs.t) -> fun () -> ignore (Ojs.apply x216 [||])
and t_to_js : t -> Ojs.t =
fun (x215 : unit -> unit) -> Ojs.fun_to_js 1 (fun _ -> x215 ())
end
module ExitListener =
struct
type t = code:int -> unit
let rec t_of_js : Ojs.t -> t =
fun (x219 : Ojs.t) ->
fun ~code:(x220 : int) ->
ignore (Ojs.apply x219 [|(Ojs.int_to_js x220)|])
and t_to_js : t -> Ojs.t =
fun (x217 : code:int -> unit) ->
Ojs.fun_to_js 1
(fun (x218 : Ojs.t) -> x217 ~code:(Ojs.int_of_js x218))
end
module RejectionHandledListener =
struct
type t = promise:any Promise.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x224 : Ojs.t) ->
fun ~promise:(x225 : any Promise.t) ->
ignore (Ojs.apply x224 [|(Promise.t_to_js any_to_js x225)|])
and t_to_js : t -> Ojs.t =
fun (x221 : promise:any Promise.t -> unit) ->
Ojs.fun_to_js 1
(fun (x222 : Ojs.t) ->
x221 ~promise:(Promise.t_of_js any_of_js x222))
end
module UncaughtExceptionListener =
struct
type t = error:Error.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x229 : Ojs.t) ->
fun ~error:(x230 : Error.t) ->
ignore (Ojs.apply x229 [|(Error.t_to_js x230)|])
and t_to_js : t -> Ojs.t =
fun (x227 : error:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x228 : Ojs.t) -> x227 ~error:(Error.t_of_js x228))
end
module UnhandledRejectionListener =
struct
type t =
reason:AnonymousInterface0.t or_null_or_undefined ->
promise:any Promise.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x236 : Ojs.t) ->
fun ~reason:(x237 : AnonymousInterface0.t or_null_or_undefined)
->
fun ~promise:(x239 : any Promise.t) ->
ignore
(Ojs.apply x236
[|(or_null_or_undefined_to_js
AnonymousInterface0.t_to_js x237);(Promise.t_to_js
any_to_js x239)|])
and t_to_js : t -> Ojs.t =
fun
(x231 :
reason:AnonymousInterface0.t or_null_or_undefined ->
promise:any Promise.t -> unit)
->
Ojs.fun_to_js 2
(fun (x232 : Ojs.t) ->
fun (x234 : Ojs.t) ->
x231
~reason:(or_null_or_undefined_of_js
AnonymousInterface0.t_of_js x232)
~promise:(Promise.t_of_js any_of_js x234))
end
module WarningListener =
struct
type t = warning:Error.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x243 : Ojs.t) ->
fun ~warning:(x244 : Error.t) ->
ignore (Ojs.apply x243 [|(Error.t_to_js x244)|])
and t_to_js : t -> Ojs.t =
fun (x241 : warning:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x242 : Ojs.t) -> x241 ~warning:(Error.t_of_js x242))
end
module MessageListener =
struct
type t = message:any -> send_handle:any -> unit
let rec t_of_js : Ojs.t -> t =
fun (x248 : Ojs.t) ->
fun ~message:(x249 : any) ->
fun ~send_handle:(x250 : any) ->
ignore (Ojs.apply x248 [|(any_to_js x249);(any_to_js x250)|])
and t_to_js : t -> Ojs.t =
fun (x245 : message:any -> send_handle:any -> unit) ->
Ojs.fun_to_js 2
(fun (x246 : Ojs.t) ->
fun (x247 : Ojs.t) ->
x245 ~message:(any_of_js x246)
~send_handle:(any_of_js x247))
end
module SignalsListener =
struct
type t = signal:Signals.t -> unit
let rec t_of_js : Ojs.t -> t =
fun (x253 : Ojs.t) ->
fun ~signal:(x254 : Signals.t) ->
ignore (Ojs.apply x253 [|(Signals.t_to_js x254)|])
and t_to_js : t -> Ojs.t =
fun (x251 : signal:Signals.t -> unit) ->
Ojs.fun_to_js 1
(fun (x252 : Ojs.t) -> x251 ~signal:(Signals.t_of_js x252))
end
module NewListenerListener =
struct
type t =
type_:symbol or_string -> listener:(args:any list -> unit) -> unit
let rec t_of_js : Ojs.t -> t =
fun (x262 : Ojs.t) ->
fun ~type_:(x263 : symbol or_string) ->
fun ~listener:(x265 : args:any list -> unit) ->
ignore
(Ojs.apply x262
[|(or_string_to_js symbol_to_js x263);(Ojs.fun_to_js_args
(fun (x266 : _)
->
x265
~args:(
Ojs.list_of_js_from
any_of_js
x266 0)))|])
and t_to_js : t -> Ojs.t =
fun
(x255 :
type_:symbol or_string ->
listener:(args:any list -> unit) -> unit)
->
Ojs.fun_to_js 2
(fun (x256 : Ojs.t) ->
fun (x258 : Ojs.t) ->
x255 ~type_:(or_string_of_js symbol_of_js x256)
~listener:(fun ~args:(x259 : any list) ->
ignore
(Ojs.call x258 "apply"
[|Ojs.null;((let x260 =
Ojs.new_obj
(Ojs.get_prop_ascii
Ojs.global "Array")
[||] in
List.iter
(fun (x261 : any) ->
ignore
(Ojs.call x260
"push"
[|(any_to_js
x261)|]))
x259;
x260))|])))
end
module RemoveListenerListener =
struct
type t =
type_:symbol or_string -> listener:(args:any list -> unit) -> unit
let rec t_of_js : Ojs.t -> t =
fun (x275 : Ojs.t) ->
fun ~type_:(x276 : symbol or_string) ->
fun ~listener:(x278 : args:any list -> unit) ->
ignore
(Ojs.apply x275
[|(or_string_to_js symbol_to_js x276);(Ojs.fun_to_js_args
(fun (x279 : _)
->
x278
~args:(
Ojs.list_of_js_from
any_of_js
x279 0)))|])
and t_to_js : t -> Ojs.t =
fun
(x268 :
type_:symbol or_string ->
listener:(args:any list -> unit) -> unit)
->
Ojs.fun_to_js 2
(fun (x269 : Ojs.t) ->
fun (x271 : Ojs.t) ->
x268 ~type_:(or_string_of_js symbol_of_js x269)
~listener:(fun ~args:(x272 : any list) ->
ignore
(Ojs.call x271 "apply"
[|Ojs.null;((let x273 =
Ojs.new_obj
(Ojs.get_prop_ascii
Ojs.global "Array")
[||] in
List.iter
(fun (x274 : any) ->
ignore
(Ojs.call x273
"push"
[|(any_to_js
x274)|]))
x272;
x273))|])))
end
module MultipleResolvesListener =
struct
type t =
type_:MultipleResolvesType.t ->
promise:any Promise.t -> value:any -> unit
let rec t_of_js : Ojs.t -> t =
fun (x286 : Ojs.t) ->
fun ~type_:(x287 : MultipleResolvesType.t) ->
fun ~promise:(x288 : any Promise.t) ->
fun ~value:(x290 : any) ->
ignore
(Ojs.apply x286
[|(MultipleResolvesType.t_to_js x287);(Promise.t_to_js
any_to_js
x288);(
any_to_js x290)|])
and t_to_js : t -> Ojs.t =
fun
(x281 :
type_:MultipleResolvesType.t ->
promise:any Promise.t -> value:any -> unit)
->
Ojs.fun_to_js 3
(fun (x282 : Ojs.t) ->
fun (x283 : Ojs.t) ->
fun (x285 : Ojs.t) ->
x281 ~type_:(MultipleResolvesType.t_of_js x282)
~promise:(Promise.t_of_js any_of_js x283)
~value:(any_of_js x285))
end
type listener =
[ `BeforeExit of BeforeExitListener.t
| `Disconnect of DisconnectListener.t | `Exit of ExitListener.t
| `RejectionHandled of RejectionHandledListener.t
| `UncaughtException of UncaughtExceptionListener.t
| `UnhandledRejection of UnhandledRejectionListener.t
| `Warning of WarningListener.t | `Message of MessageListener.t
| `NewListener of NewListenerListener.t
| `RemoveListener of RemoveListenerListener.t
| `MultipleResolves of MultipleResolvesListener.t ]
let rec listener_to_js : listener -> Ojs.t =
fun
(x291 :
[ `BeforeExit of BeforeExitListener.t
| `Disconnect of DisconnectListener.t | `Exit of ExitListener.t
| `RejectionHandled of RejectionHandledListener.t
| `UncaughtException of UncaughtExceptionListener.t
| `UnhandledRejection of UnhandledRejectionListener.t
| `Warning of WarningListener.t | `Message of MessageListener.t
| `NewListener of NewListenerListener.t
| `RemoveListener of RemoveListenerListener.t
| `MultipleResolves of MultipleResolvesListener.t ])
->
match x291 with
| `BeforeExit x292 -> BeforeExitListener.t_to_js x292
| `Disconnect x293 -> DisconnectListener.t_to_js x293
| `Exit x294 -> ExitListener.t_to_js x294
| `RejectionHandled x295 -> RejectionHandledListener.t_to_js x295
| `UncaughtException x296 -> UncaughtExceptionListener.t_to_js x296
| `UnhandledRejection x297 -> UnhandledRejectionListener.t_to_js x297
| `Warning x298 -> WarningListener.t_to_js x298
| `Message x299 -> MessageListener.t_to_js x299
| `NewListener x300 -> NewListenerListener.t_to_js x300
| `RemoveListener x301 -> RemoveListenerListener.t_to_js x301
| `MultipleResolves x302 -> MultipleResolvesListener.t_to_js x302
module Socket =
struct
include struct include ReadWriteStream end
let (is_tty : t -> [ `L_b_true ]) =
fun (x305 : t) ->
let x306 = Ojs.get_prop_ascii (t_to_js x305) "isTTY" in
match Ojs.bool_of_js x306 with
| true -> `L_b_true
| _ -> assert false
let (set_is_tty : t -> [ `L_b_true ] -> unit) =
fun (x307 : t) ->
fun (x308 : [ `L_b_true ]) ->
Ojs.set_prop_ascii (t_to_js x307) "isTTY"
(match x308 with | `L_b_true -> Ojs.string_to_js "LBTrue")
end
module ProcessEnv =
struct
type t = string Dict.t
let rec t_of_js : Ojs.t -> t =
fun (x311 : Ojs.t) -> Dict.t_of_js Ojs.string_of_js x311
and t_to_js : t -> Ojs.t =
fun (x309 : string Dict.t) -> Dict.t_to_js Ojs.string_to_js x309
end
module HRTime =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x314 : Ojs.t) -> x314
and t_to_js : t -> Ojs.t = fun (x313 : Ojs.t) -> x313
let (apply : t -> ?time:(int * int) -> unit -> (int * int)) =
fun (x321 : t) ->
fun ?time:(x315 : (int * int) option) ->
fun () ->
let x322 =
Ojs.call (t_to_js x321) "apply"
[|Ojs.null;((let x316 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x315 with
| Some x317 ->
ignore
(Ojs.call x316 "push"
[|((let (x318, x319) = x317 in
let x320 = Ojs.array_make 2 in
Ojs.array_set x320 0
(Ojs.int_to_js x318);
Ojs.array_set x320 1
(Ojs.int_to_js x319);
x320))|])
| None -> ());
x316))|] in
((Ojs.int_of_js (Ojs.array_get x322 0)),
(Ojs.int_of_js (Ojs.array_get x322 1)))
let (bigint : t -> bigint) =
fun (x323 : t) ->
bigint_of_js (Ojs.call (t_to_js x323) "bigint" [||])
end
module ProcessReport =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x325 : Ojs.t) -> x325
and t_to_js : t -> Ojs.t = fun (x324 : Ojs.t) -> x324
let (directory : t -> string) =
fun (x326 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x326) "directory")
let (set_directory : t -> string -> unit) =
fun (x327 : t) ->
fun (x328 : string) ->
Ojs.set_prop_ascii (t_to_js x327) "directory"
(Ojs.string_to_js x328)
let (filename : t -> string) =
fun (x329 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x329) "filename")
let (set_filename : t -> string -> unit) =
fun (x330 : t) ->
fun (x331 : string) ->
Ojs.set_prop_ascii (t_to_js x330) "filename"
(Ojs.string_to_js x331)
let (get_report : t -> ?err:Error.t -> unit -> string) =
fun (x335 : t) ->
fun ?err:(x332 : Error.t option) ->
fun () ->
Ojs.string_of_js
(let x336 = t_to_js x335 in
Ojs.call (Ojs.get_prop_ascii x336 "getReport") "apply"
[|x336;((let x333 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x332 with
| Some x334 ->
ignore
(Ojs.call x333 "push"
[|(Error.t_to_js x334)|])
| None -> ());
x333))|])
let (report_on_fatal_error : t -> bool) =
fun (x337 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x337) "reportOnFatalError")
let (set_report_on_fatal_error : t -> bool -> unit) =
fun (x338 : t) ->
fun (x339 : bool) ->
Ojs.set_prop_ascii (t_to_js x338) "reportOnFatalError"
(Ojs.bool_to_js x339)
let (report_on_signal : t -> bool) =
fun (x340 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x340) "reportOnSignal")
let (set_report_on_signal : t -> bool -> unit) =
fun (x341 : t) ->
fun (x342 : bool) ->
Ojs.set_prop_ascii (t_to_js x341) "reportOnSignal"
(Ojs.bool_to_js x342)
let (report_on_uncaught_exception : t -> bool) =
fun (x343 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x343) "reportOnUncaughtException")
let (set_report_on_uncaught_exception : t -> bool -> unit) =
fun (x344 : t) ->
fun (x345 : bool) ->
Ojs.set_prop_ascii (t_to_js x344) "reportOnUncaughtException"
(Ojs.bool_to_js x345)
let (signal : t -> Signals.t) =
fun (x346 : t) ->
Signals.t_of_js (Ojs.get_prop_ascii (t_to_js x346) "signal")
let (set_signal : t -> Signals.t -> unit) =
fun (x347 : t) ->
fun (x348 : Signals.t) ->
Ojs.set_prop_ascii (t_to_js x347) "signal"
(Signals.t_to_js x348)
let (write_report : t -> ?file_name:string -> unit -> string) =
fun (x352 : t) ->
fun ?file_name:(x349 : string option) ->
fun () ->
Ojs.string_of_js
(let x353 = t_to_js x352 in
Ojs.call (Ojs.get_prop_ascii x353 "writeReport") "apply"
[|x353;((let x350 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x349 with
| Some x351 ->
ignore
(Ojs.call x350 "push"
[|(Ojs.string_to_js x351)|])
| None -> ());
x350))|])
let (write_report' : t -> ?error:Error.t -> unit -> string) =
fun (x357 : t) ->
fun ?error:(x354 : Error.t option) ->
fun () ->
Ojs.string_of_js
(let x358 = t_to_js x357 in
Ojs.call (Ojs.get_prop_ascii x358 "writeReport") "apply"
[|x358;((let x355 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x354 with
| Some x356 ->
ignore
(Ojs.call x355 "push"
[|(Error.t_to_js x356)|])
| None -> ());
x355))|])
let (write_report'' :
t -> ?file_name:string -> ?err:Error.t -> unit -> string) =
fun (x364 : t) ->
fun ?file_name:(x359 : string option) ->
fun ?err:(x360 : Error.t option) ->
fun () ->
Ojs.string_of_js
(let x365 = t_to_js x364 in
Ojs.call (Ojs.get_prop_ascii x365 "writeReport") "apply"
[|x365;((let x361 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x359 with
| Some x363 ->
ignore
(Ojs.call x361 "push"
[|(Ojs.string_to_js x363)|])
| None -> ());
(match x360 with
| Some x362 ->
ignore
(Ojs.call x361 "push"
[|(Error.t_to_js x362)|])
| None -> ());
x361))|])
end
module ResourceUsage =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x367 : Ojs.t) -> x367
and t_to_js : t -> Ojs.t = fun (x366 : Ojs.t) -> x366
let (fs_read : t -> int) =
fun (x368 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x368) "fsRead")
let (set_fs_read : t -> int -> unit) =
fun (x369 : t) ->
fun (x370 : int) ->
Ojs.set_prop_ascii (t_to_js x369) "fsRead" (Ojs.int_to_js x370)
let (fs_write : t -> int) =
fun (x371 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x371) "fsWrite")
let (set_fs_write : t -> int -> unit) =
fun (x372 : t) ->
fun (x373 : int) ->
Ojs.set_prop_ascii (t_to_js x372) "fsWrite"
(Ojs.int_to_js x373)
let (involuntary_context_switches : t -> int) =
fun (x374 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x374) "involuntaryContextSwitches")
let (set_involuntary_context_switches : t -> int -> unit) =
fun (x375 : t) ->
fun (x376 : int) ->
Ojs.set_prop_ascii (t_to_js x375) "involuntaryContextSwitches"
(Ojs.int_to_js x376)
let (ipc_received : t -> int) =
fun (x377 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x377) "ipcReceived")
let (set_ipc_received : t -> int -> unit) =
fun (x378 : t) ->
fun (x379 : int) ->
Ojs.set_prop_ascii (t_to_js x378) "ipcReceived"
(Ojs.int_to_js x379)
let (ipc_sent : t -> int) =
fun (x380 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x380) "ipcSent")
let (set_ipc_sent : t -> int -> unit) =
fun (x381 : t) ->
fun (x382 : int) ->
Ojs.set_prop_ascii (t_to_js x381) "ipcSent"
(Ojs.int_to_js x382)
let (major_page_fault : t -> int) =
fun (x383 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x383) "majorPageFault")
let (set_major_page_fault : t -> int -> unit) =
fun (x384 : t) ->
fun (x385 : int) ->
Ojs.set_prop_ascii (t_to_js x384) "majorPageFault"
(Ojs.int_to_js x385)
let (max_rss : t -> int) =
fun (x386 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x386) "maxRSS")
let (set_max_rss : t -> int -> unit) =
fun (x387 : t) ->
fun (x388 : int) ->
Ojs.set_prop_ascii (t_to_js x387) "maxRSS" (Ojs.int_to_js x388)
let (minor_page_fault : t -> int) =
fun (x389 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x389) "minorPageFault")
let (set_minor_page_fault : t -> int -> unit) =
fun (x390 : t) ->
fun (x391 : int) ->
Ojs.set_prop_ascii (t_to_js x390) "minorPageFault"
(Ojs.int_to_js x391)
let (shared_memory_size : t -> int) =
fun (x392 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x392) "sharedMemorySize")
let (set_shared_memory_size : t -> int -> unit) =
fun (x393 : t) ->
fun (x394 : int) ->
Ojs.set_prop_ascii (t_to_js x393) "sharedMemorySize"
(Ojs.int_to_js x394)
let (signals_count : t -> int) =
fun (x395 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x395) "signalsCount")
let (set_signals_count : t -> int -> unit) =
fun (x396 : t) ->
fun (x397 : int) ->
Ojs.set_prop_ascii (t_to_js x396) "signalsCount"
(Ojs.int_to_js x397)
let (swapped_out : t -> int) =
fun (x398 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x398) "swappedOut")
let (set_swapped_out : t -> int -> unit) =
fun (x399 : t) ->
fun (x400 : int) ->
Ojs.set_prop_ascii (t_to_js x399) "swappedOut"
(Ojs.int_to_js x400)
let (system_cpu_time : t -> int) =
fun (x401 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x401) "systemCPUTime")
let (set_system_cpu_time : t -> int -> unit) =
fun (x402 : t) ->
fun (x403 : int) ->
Ojs.set_prop_ascii (t_to_js x402) "systemCPUTime"
(Ojs.int_to_js x403)
let (unshared_data_size : t -> int) =
fun (x404 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x404) "unsharedDataSize")
let (set_unshared_data_size : t -> int -> unit) =
fun (x405 : t) ->
fun (x406 : int) ->
Ojs.set_prop_ascii (t_to_js x405) "unsharedDataSize"
(Ojs.int_to_js x406)
let (unshared_stack_size : t -> int) =
fun (x407 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x407) "unsharedStackSize")
let (set_unshared_stack_size : t -> int -> unit) =
fun (x408 : t) ->
fun (x409 : int) ->
Ojs.set_prop_ascii (t_to_js x408) "unsharedStackSize"
(Ojs.int_to_js x409)
let (user_cpu_time : t -> int) =
fun (x410 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x410) "userCPUTime")
let (set_user_cpu_time : t -> int -> unit) =
fun (x411 : t) ->
fun (x412 : int) ->
Ojs.set_prop_ascii (t_to_js x411) "userCPUTime"
(Ojs.int_to_js x412)
let (voluntary_context_switches : t -> int) =
fun (x413 : t) ->
Ojs.int_of_js
(Ojs.get_prop_ascii (t_to_js x413) "voluntaryContextSwitches")
let (set_voluntary_context_switches : t -> int -> unit) =
fun (x414 : t) ->
fun (x415 : int) ->
Ojs.set_prop_ascii (t_to_js x414) "voluntaryContextSwitches"
(Ojs.int_to_js x415)
end
module Process =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x417 : Ojs.t) -> x417
and t_to_js : t -> Ojs.t = fun (x416 : Ojs.t) -> x416
let (stdout : t -> WriteStream.t) =
fun (x418 : t) ->
WriteStream.t_of_js (Ojs.get_prop_ascii (t_to_js x418) "stdout")
let (set_stdout : t -> WriteStream.t -> unit) =
fun (x419 : t) ->
fun (x420 : WriteStream.t) ->
Ojs.set_prop_ascii (t_to_js x419) "stdout"
(WriteStream.t_to_js x420)
let (stderr : t -> WriteStream.t) =
fun (x421 : t) ->
WriteStream.t_of_js (Ojs.get_prop_ascii (t_to_js x421) "stderr")
let (set_stderr : t -> WriteStream.t -> unit) =
fun (x422 : t) ->
fun (x423 : WriteStream.t) ->
Ojs.set_prop_ascii (t_to_js x422) "stderr"
(WriteStream.t_to_js x423)
let (stdin : t -> ReadStream.t) =
fun (x424 : t) ->
ReadStream.t_of_js (Ojs.get_prop_ascii (t_to_js x424) "stdin")
let (set_stdin : t -> ReadStream.t -> unit) =
fun (x425 : t) ->
fun (x426 : ReadStream.t) ->
Ojs.set_prop_ascii (t_to_js x425) "stdin"
(ReadStream.t_to_js x426)
let (open_stdin : t -> Socket.t) =
fun (x427 : t) ->
Socket.t_of_js (Ojs.call (t_to_js x427) "openStdin" [||])
let (argv : t -> string list) =
fun (x428 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x428) "argv")
let (set_argv : t -> string list -> unit) =
fun (x430 : t) ->
fun (x431 : string list) ->
Ojs.set_prop_ascii (t_to_js x430) "argv"
(Ojs.list_to_js Ojs.string_to_js x431)
let (argv0 : t -> string) =
fun (x433 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x433) "argv0")
let (set_argv0 : t -> string -> unit) =
fun (x434 : t) ->
fun (x435 : string) ->
Ojs.set_prop_ascii (t_to_js x434) "argv0"
(Ojs.string_to_js x435)
let (exec_argv : t -> string list) =
fun (x436 : t) ->
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x436) "execArgv")
let (set_exec_argv : t -> string list -> unit) =
fun (x438 : t) ->
fun (x439 : string list) ->
Ojs.set_prop_ascii (t_to_js x438) "execArgv"
(Ojs.list_to_js Ojs.string_to_js x439)
let (exec_path : t -> string) =
fun (x441 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x441) "execPath")
let (set_exec_path : t -> string -> unit) =
fun (x442 : t) ->
fun (x443 : string) ->
Ojs.set_prop_ascii (t_to_js x442) "execPath"
(Ojs.string_to_js x443)
let (abort : t -> never) =
fun (x444 : t) ->
never_of_js (Ojs.call (t_to_js x444) "abort" [||])
let (chdir : t -> directory:string -> unit) =
fun (x446 : t) ->
fun ~directory:(x445 : string) ->
ignore
(Ojs.call (t_to_js x446) "chdir" [|(Ojs.string_to_js x445)|])
let (cwd : t -> string) =
fun (x447 : t) ->
Ojs.string_of_js (Ojs.call (t_to_js x447) "cwd" [||])
let (debug_port : t -> int) =
fun (x448 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x448) "debugPort")
let (set_debug_port : t -> int -> unit) =
fun (x449 : t) ->
fun (x450 : int) ->
Ojs.set_prop_ascii (t_to_js x449) "debugPort"
(Ojs.int_to_js x450)
let (emit_warning :
t ->
event:[ `warning ] ->
warning:Error.t or_string ->
?name:string -> ?ctor:untyped_function -> unit -> unit)
=
fun (x459 : t) ->
fun ~event:(x451 : [ `warning ]) ->
fun ~warning:(x452 : Error.t or_string) ->
fun ?name:(x453 : string option) ->
fun ?ctor:(x454 : untyped_function option) ->
fun () ->
ignore
(let x460 = t_to_js x459 in
Ojs.call (Ojs.get_prop_ascii x460 "emitWarning")
"apply"
[|x460;((let x455 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global
"Array") [||] in
ignore
(Ojs.call x455 "push"
[|((match x451 with
| `warning ->
Ojs.string_to_js "warning"))|]);
ignore
(Ojs.call x455 "push"
[|(or_string_to_js Error.t_to_js
x452)|]);
(match x453 with
| Some x457 ->
ignore
(Ojs.call x455 "push"
[|(Ojs.string_to_js x457)|])
| None -> ());
(match x454 with
| Some x456 ->
ignore
(Ojs.call x455 "push"
[|(untyped_function_to_js x456)|])
| None -> ());
x455))|])
let (env : t -> ProcessEnv.t) =
fun (x461 : t) ->
ProcessEnv.t_of_js (Ojs.get_prop_ascii (t_to_js x461) "env")
let (set_env : t -> ProcessEnv.t -> unit) =
fun (x462 : t) ->
fun (x463 : ProcessEnv.t) ->
Ojs.set_prop_ascii (t_to_js x462) "env"
(ProcessEnv.t_to_js x463)
let (exit : t -> ?code:int -> unit -> never) =
fun (x467 : t) ->
fun ?code:(x464 : int option) ->
fun () ->
never_of_js
(let x468 = t_to_js x467 in
Ojs.call (Ojs.get_prop_ascii x468 "exit") "apply"
[|x468;((let x465 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x464 with
| Some x466 ->
ignore
(Ojs.call x465 "push"
[|(Ojs.int_to_js x466)|])
| None -> ());
x465))|])
let (exit_code : t -> int) =
fun (x469 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x469) "exitCode")
let (set_exit_code : t -> int -> unit) =
fun (x470 : t) ->
fun (x471 : int) ->
Ojs.set_prop_ascii (t_to_js x470) "exitCode"
(Ojs.int_to_js x471)
let (getgid : t -> int) =
fun (x472 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x472) "getgid" [||])
let (setgid : t -> id:string or_number -> unit) =
fun (x475 : t) ->
fun ~id:(x473 : string or_number) ->
ignore
(Ojs.call (t_to_js x475) "setgid"
[|(or_number_to_js Ojs.string_to_js x473)|])
let (getuid : t -> int) =
fun (x476 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x476) "getuid" [||])
let (setuid : t -> id:string or_number -> unit) =
fun (x479 : t) ->
fun ~id:(x477 : string or_number) ->
ignore
(Ojs.call (t_to_js x479) "setuid"
[|(or_number_to_js Ojs.string_to_js x477)|])
let (geteuid : t -> int) =
fun (x480 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x480) "geteuid" [||])
let (seteuid : t -> id:string or_number -> unit) =
fun (x483 : t) ->
fun ~id:(x481 : string or_number) ->
ignore
(Ojs.call (t_to_js x483) "seteuid"
[|(or_number_to_js Ojs.string_to_js x481)|])
let (getegid : t -> int) =
fun (x484 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x484) "getegid" [||])
let (setegid : t -> id:string or_number -> unit) =
fun (x487 : t) ->
fun ~id:(x485 : string or_number) ->
ignore
(Ojs.call (t_to_js x487) "setegid"
[|(or_number_to_js Ojs.string_to_js x485)|])
let (getgroups : t -> int list) =
fun (x488 : t) ->
Ojs.list_of_js Ojs.int_of_js
(Ojs.call (t_to_js x488) "getgroups" [||])
let (setgroups : t -> groups:string or_number list -> unit) =
fun (x493 : t) ->
fun ~groups:(x490 : string or_number list) ->
ignore
(Ojs.call (t_to_js x493) "setgroups"
[|(Ojs.list_to_js
(fun (x491 : string or_number) ->
or_number_to_js Ojs.string_to_js x491) x490)|])
let (set_uncaught_exception_capture_callback :
t -> cb:(err:Error.t -> unit) or_null -> unit) =
fun (x497 : t) ->
fun ~cb:(x494 : (err:Error.t -> unit) or_null) ->
ignore
(Ojs.call (t_to_js x497)
"setUncaughtExceptionCaptureCallback"
[|(or_null_to_js
(fun (x495 : err:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x496 : Ojs.t) ->
x495 ~err:(Error.t_of_js x496))) x494)|])
let (has_uncaught_exception_capture_callback : t -> bool) =
fun (x498 : t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x498) "hasUncaughtExceptionCaptureCallback"
[||])
let (version : t -> string) =
fun (x499 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x499) "version")
let (set_version : t -> string -> unit) =
fun (x500 : t) ->
fun (x501 : string) ->
Ojs.set_prop_ascii (t_to_js x500) "version"
(Ojs.string_to_js x501)
let (versions : t -> ProcessVersions.t) =
fun (x502 : t) ->
ProcessVersions.t_of_js
(Ojs.get_prop_ascii (t_to_js x502) "versions")
let (set_versions : t -> ProcessVersions.t -> unit) =
fun (x503 : t) ->
fun (x504 : ProcessVersions.t) ->
Ojs.set_prop_ascii (t_to_js x503) "versions"
(ProcessVersions.t_to_js x504)
let (config : t -> AnonymousInterface8.t) =
fun (x505 : t) ->
AnonymousInterface8.t_of_js
(Ojs.get_prop_ascii (t_to_js x505) "config")
let (set_config : t -> AnonymousInterface8.t -> unit) =
fun (x506 : t) ->
fun (x507 : AnonymousInterface8.t) ->
Ojs.set_prop_ascii (t_to_js x506) "config"
(AnonymousInterface8.t_to_js x507)
let (kill :
t -> pid:int -> ?signal:string or_number -> unit -> [ `L_b_true ])
=
fun (x513 : t) ->
fun ~pid:(x508 : int) ->
fun ?signal:(x509 : string or_number option) ->
fun () ->
let x515 =
let x514 = t_to_js x513 in
Ojs.call (Ojs.get_prop_ascii x514 "kill") "apply"
[|x514;((let x510 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x510 "push"
[|(Ojs.int_to_js x508)|]);
(match x509 with
| Some x511 ->
ignore
(Ojs.call x510 "push"
[|(or_number_to_js Ojs.string_to_js
x511)|])
| None -> ());
x510))|] in
match Ojs.bool_of_js x515 with
| true -> `L_b_true
| _ -> assert false
let (pid : t -> int) =
fun (x516 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x516) "pid")
let (set_pid : t -> int -> unit) =
fun (x517 : t) ->
fun (x518 : int) ->
Ojs.set_prop_ascii (t_to_js x517) "pid" (Ojs.int_to_js x518)
let (ppid : t -> int) =
fun (x519 : t) ->
Ojs.int_of_js (Ojs.get_prop_ascii (t_to_js x519) "ppid")
let (set_ppid : t -> int -> unit) =
fun (x520 : t) ->
fun (x521 : int) ->
Ojs.set_prop_ascii (t_to_js x520) "ppid" (Ojs.int_to_js x521)
let (title : t -> string) =
fun (x522 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x522) "title")
let (set_title : t -> string -> unit) =
fun (x523 : t) ->
fun (x524 : string) ->
Ojs.set_prop_ascii (t_to_js x523) "title"
(Ojs.string_to_js x524)
let (arch : t -> string) =
fun (x525 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x525) "arch")
let (set_arch : t -> string -> unit) =
fun (x526 : t) ->
fun (x527 : string) ->
Ojs.set_prop_ascii (t_to_js x526) "arch"
(Ojs.string_to_js x527)
let (platform : t -> Platform.t) =
fun (x528 : t) ->
Platform.t_of_js (Ojs.get_prop_ascii (t_to_js x528) "platform")
let (set_platform : t -> Platform.t -> unit) =
fun (x529 : t) ->
fun (x530 : Platform.t) ->
Ojs.set_prop_ascii (t_to_js x529) "platform"
(Platform.t_to_js x530)
let (main_module : t -> Module.t) =
fun (x531 : t) ->
Module.t_of_js (Ojs.get_prop_ascii (t_to_js x531) "mainModule")
let (set_main_module : t -> Module.t -> unit) =
fun (x532 : t) ->
fun (x533 : Module.t) ->
Ojs.set_prop_ascii (t_to_js x532) "mainModule"
(Module.t_to_js x533)
let (memory_usage : t -> MemoryUsage.t) =
fun (x534 : t) ->
MemoryUsage.t_of_js (Ojs.call (t_to_js x534) "memoryUsage" [||])
let (cpu_usage :
t -> ?previous_value:CpuUsage.t -> unit -> CpuUsage.t) =
fun (x538 : t) ->
fun ?previous_value:(x535 : CpuUsage.t option) ->
fun () ->
CpuUsage.t_of_js
(let x539 = t_to_js x538 in
Ojs.call (Ojs.get_prop_ascii x539 "cpuUsage") "apply"
[|x539;((let x536 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x535 with
| Some x537 ->
ignore
(Ojs.call x536 "push"
[|(CpuUsage.t_to_js x537)|])
| None -> ());
x536))|])
let (next_tick :
t -> callback:untyped_function -> args:any list -> unit) =
fun (x544 : t) ->
fun ~callback:(x540 : untyped_function) ->
fun ~args:(x541 : any list) ->
ignore
(let x545 = t_to_js x544 in
Ojs.call (Ojs.get_prop_ascii x545 "nextTick") "apply"
[|x545;((let x542 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x542 "push"
[|(untyped_function_to_js x540)|]);
List.iter
(fun (x543 : any) ->
ignore
(Ojs.call x542 "push"
[|(any_to_js x543)|])) x541;
x542))|])
let (release : t -> ProcessRelease.t) =
fun (x546 : t) ->
ProcessRelease.t_of_js
(Ojs.get_prop_ascii (t_to_js x546) "release")
let (set_release : t -> ProcessRelease.t -> unit) =
fun (x547 : t) ->
fun (x548 : ProcessRelease.t) ->
Ojs.set_prop_ascii (t_to_js x547) "release"
(ProcessRelease.t_to_js x548)
let (features : t -> AnonymousInterface6.t) =
fun (x549 : t) ->
AnonymousInterface6.t_of_js
(Ojs.get_prop_ascii (t_to_js x549) "features")
let (set_features : t -> AnonymousInterface6.t -> unit) =
fun (x550 : t) ->
fun (x551 : AnonymousInterface6.t) ->
Ojs.set_prop_ascii (t_to_js x550) "features"
(AnonymousInterface6.t_to_js x551)
let (umask : t -> int) =
fun (x552 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x552) "umask" [||])
let (umask' : t -> mask:string or_number -> int) =
fun (x555 : t) ->
fun ~mask:(x553 : string or_number) ->
Ojs.int_of_js
(Ojs.call (t_to_js x555) "umask"
[|(or_number_to_js Ojs.string_to_js x553)|])
let (uptime : t -> int) =
fun (x556 : t) ->
Ojs.int_of_js (Ojs.call (t_to_js x556) "uptime" [||])
let (hrtime : t -> HRTime.t) =
fun (x557 : t) ->
HRTime.t_of_js (Ojs.get_prop_ascii (t_to_js x557) "hrtime")
let (set_hrtime : t -> HRTime.t -> unit) =
fun (x558 : t) ->
fun (x559 : HRTime.t) ->
Ojs.set_prop_ascii (t_to_js x558) "hrtime"
(HRTime.t_to_js x559)
let (domain : t -> Node_domain.Domain.Domain.t) =
fun (x560 : t) ->
Node_domain.Domain.Domain.t_of_js
(Ojs.get_prop_ascii (t_to_js x560) "domain")
let (set_domain : t -> Node_domain.Domain.Domain.t -> unit) =
fun (x561 : t) ->
fun (x562 : Node_domain.Domain.Domain.t) ->
Ojs.set_prop_ascii (t_to_js x561) "domain"
(Node_domain.Domain.Domain.t_to_js x562)
let (send :
t ->
message:any ->
?send_handle:any ->
?options:AnonymousInterface7.t ->
?callback:(error:Error.t or_null -> unit) -> unit -> bool)
=
fun (x573 : t) ->
fun ~message:(x563 : any) ->
fun ?send_handle:(x564 : any option) ->
fun ?options:(x565 : AnonymousInterface7.t option) ->
fun
?callback:(x566 : (error:Error.t or_null -> unit) option)
->
fun () ->
Ojs.bool_of_js
(let x574 = t_to_js x573 in
Ojs.call (Ojs.get_prop_ascii x574 "send") "apply"
[|x574;((let x567 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global
"Array") [||] in
ignore
(Ojs.call x567 "push"
[|(any_to_js x563)|]);
(match x564 with
| Some x572 ->
ignore
(Ojs.call x567 "push"
[|(any_to_js x572)|])
| None -> ());
(match x565 with
| Some x571 ->
ignore
(Ojs.call x567 "push"
[|(AnonymousInterface7.t_to_js
x571)|])
| None -> ());
(match x566 with
| Some x568 ->
ignore
(Ojs.call x567 "push"
[|(Ojs.fun_to_js 1
(fun (x569 : Ojs.t) ->
x568
~error:(or_null_of_js
Error.t_of_js
x569)))|])
| None -> ());
x567))|])
let (disconnect : t -> unit) =
fun (x575 : t) ->
ignore (Ojs.call (t_to_js x575) "disconnect" [||])
let (connected : t -> bool) =
fun (x576 : t) ->
Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x576) "connected")
let (set_connected : t -> bool -> unit) =
fun (x577 : t) ->
fun (x578 : bool) ->
Ojs.set_prop_ascii (t_to_js x577) "connected"
(Ojs.bool_to_js x578)
let (allowed_node_environment_flags : t -> string ReadonlySet.t) =
fun (x579 : t) ->
ReadonlySet.t_of_js Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x579)
"allowedNodeEnvironmentFlags")
let (set_allowed_node_environment_flags :
t -> string ReadonlySet.t -> unit) =
fun (x581 : t) ->
fun (x582 : string ReadonlySet.t) ->
Ojs.set_prop_ascii (t_to_js x581) "allowedNodeEnvironmentFlags"
(ReadonlySet.t_to_js Ojs.string_to_js x582)
let (report : t -> ProcessReport.t) =
fun (x584 : t) ->
ProcessReport.t_of_js
(Ojs.get_prop_ascii (t_to_js x584) "report")
let (set_report : t -> ProcessReport.t -> unit) =
fun (x585 : t) ->
fun (x586 : ProcessReport.t) ->
Ojs.set_prop_ascii (t_to_js x585) "report"
(ProcessReport.t_to_js x586)
let (resource_usage : t -> ResourceUsage.t) =
fun (x587 : t) ->
ResourceUsage.t_of_js
(Ojs.call (t_to_js x587) "resourceUsage" [||])
let (trace_deprecation : t -> bool) =
fun (x588 : t) ->
Ojs.bool_of_js
(Ojs.get_prop_ascii (t_to_js x588) "traceDeprecation")
let (set_trace_deprecation : t -> bool -> unit) =
fun (x589 : t) ->
fun (x590 : bool) ->
Ojs.set_prop_ascii (t_to_js x589) "traceDeprecation"
(Ojs.bool_to_js x590)
let (on : t -> string -> Ojs.t -> unit) =
fun (x593 : t) ->
fun (x591 : string) ->
fun (x592 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x593) "on"
[|(Ojs.string_to_js x591);x592|])
let (add_listener : t -> string -> Ojs.t -> unit) =
fun (x596 : t) ->
fun (x594 : string) ->
fun (x595 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x596) "addListener"
[|(Ojs.string_to_js x594);x595|])
let (once : t -> string -> Ojs.t -> unit) =
fun (x599 : t) ->
fun (x597 : string) ->
fun (x598 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x599) "once"
[|(Ojs.string_to_js x597);x598|])
let (prepend_listener : t -> string -> Ojs.t -> unit) =
fun (x602 : t) ->
fun (x600 : string) ->
fun (x601 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x602) "prependListener"
[|(Ojs.string_to_js x600);x601|])
let (prepend_once_listener : t -> string -> Ojs.t -> unit) =
fun (x605 : t) ->
fun (x603 : string) ->
fun (x604 : Ojs.t) ->
ignore
(Ojs.call (t_to_js x605) "prependOnceListener"
[|(Ojs.string_to_js x603);x604|])
let (listeners : t -> string -> Ojs.t list) =
fun (x607 : t) ->
fun (x606 : string) ->
Ojs.list_of_js (fun (x608 : Ojs.t) -> x608)
(Ojs.call (t_to_js x607) "listeners"
[|(Ojs.string_to_js x606)|])
let with_listener_fn fn t =
function
| `BeforeExit f ->
(fn t "beforeExit") @@ (BeforeExitListener.t_to_js f)
| `Disconnect f ->
(fn t "disconnect") @@ (DisconnectListener.t_to_js f)
| `Exit f -> (fn t "exit") @@ (ExitListener.t_to_js f)
| `RejectionHandled f ->
(fn t "rejectionHandled") @@
(RejectionHandledListener.t_to_js f)
| `UncaughtException f ->
(fn t "uncaughtException") @@
(UncaughtExceptionListener.t_to_js f)
| `UnhandledRejection f ->
(fn t "unhandledRejection") @@
(UnhandledRejectionListener.t_to_js f)
| `Warning f -> (fn t "warning") @@ (WarningListener.t_to_js f)
| `Message f -> (fn t "message") @@ (MessageListener.t_to_js f)
| `NewListener f ->
(fn t "newListener") @@ (NewListenerListener.t_to_js f)
| `RemoveListener f ->
(fn t "removeListener") @@ (RemoveListenerListener.t_to_js f)
| `MultipleResolves f ->
(fn t "multipleResolves") @@
(MultipleResolvesListener.t_to_js f)
let on = with_listener_fn on
let add_listener = with_listener_fn add_listener
let once = with_listener_fn once
let prepend_listener = with_listener_fn prepend_listener
let prepend_once_listener = with_listener_fn prepend_once_listener
let listeners_before_exit t =
(listeners t "beforeExit") |> (List.map BeforeExitListener.t_of_js)
let listeners_disconnect t =
(listeners t "disconnect") |> (List.map DisconnectListener.t_of_js)
let listeners_exit t =
(listeners t "exit") |> (List.map ExitListener.t_of_js)
let listeners_rejection_handled t =
(listeners t "rejectionHandled") |>
(List.map RejectionHandledListener.t_of_js)
let listeners_uncaught_exception t =
(listeners t "uncaughtException") |>
(List.map UncaughtExceptionListener.t_of_js)
let listeners_uncaught_exception t =
(listeners t "uncaughtException") |>
(List.map UncaughtExceptionListener.t_of_js)
let listeners_unhandled_rejection t =
(listeners t "unhandledRejection") |>
(List.map UnhandledRejectionListener.t_of_js)
let listeners_warning t =
(listeners t "warning") |> (List.map WarningListener.t_of_js)
let listeners_message t =
(listeners t "message") |> (List.map MessageListener.t_of_js)
let listeners_signals t =
(listeners t "signals") |> (List.map SignalsListener.t_of_js)
let listeners_new_listener t =
(listeners t "newListener") |>
(List.map NewListenerListener.t_of_js)
let listeners_remove_listener t =
(listeners t "removeListener") |>
(List.map RemoveListenerListener.t_of_js)
let listeners_multiple_resolves t =
(listeners t "multipleResolves") |>
(List.map MultipleResolvesListener.t_of_js)
let (emit_before_exit :
t -> event:[ `beforeExit ] -> code:int -> bool) =
fun (x622 : t) ->
fun ~event:(x620 : [ `beforeExit ]) ->
fun ~code:(x621 : int) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x622) "emit"
[|((match x620 with
| `beforeExit -> Ojs.string_to_js "beforeExit"));(
Ojs.int_to_js x621)|])
let (emit_disconnect : t -> event:[ `disconnect ] -> bool) =
fun (x624 : t) ->
fun ~event:(x623 : [ `disconnect ]) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x624) "emit"
[|((match x623 with
| `disconnect -> Ojs.string_to_js "disconnect"))|])
let (emit_exit : t -> event:[ `exit ] -> code:int -> bool) =
fun (x627 : t) ->
fun ~event:(x625 : [ `exit ]) ->
fun ~code:(x626 : int) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x627) "emit"
[|((match x625 with | `exit -> Ojs.string_to_js "exit"));(
Ojs.int_to_js x626)|])
let (emit_rejection_handled :
t -> event:[ `rejectionHandled ] -> promise:any Promise.t -> bool)
=
fun (x631 : t) ->
fun ~event:(x628 : [ `rejectionHandled ]) ->
fun ~promise:(x629 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x631) "emit"
[|((match x628 with
| `rejectionHandled ->
Ojs.string_to_js "rejectionHandled"));(Promise.t_to_js
any_to_js
x629)|])
let (emit_uncaught_exception :
t -> event:[ `uncaughtException ] -> error:Error.t -> bool) =
fun (x634 : t) ->
fun ~event:(x632 : [ `uncaughtException ]) ->
fun ~error:(x633 : Error.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x634) "emit"
[|((match x632 with
| `uncaughtException ->
Ojs.string_to_js "uncaughtException"));(
Error.t_to_js x633)|])
let (emit_uncaught_exception_monitor :
t -> event:[ `uncaughtExceptionMonitor ] -> error:Error.t -> bool)
=
fun (x637 : t) ->
fun ~event:(x635 : [ `uncaughtExceptionMonitor ]) ->
fun ~error:(x636 : Error.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x637) "emit"
[|((match x635 with
| `uncaughtExceptionMonitor ->
Ojs.string_to_js "uncaughtExceptionMonitor"));(
Error.t_to_js x636)|])
let (emit_unhandled_rejection :
t ->
event:[ `unhandledRejection ] ->
reason:any -> promise:any Promise.t -> bool)
=
fun (x642 : t) ->
fun ~event:(x638 : [ `unhandledRejection ]) ->
fun ~reason:(x639 : any) ->
fun ~promise:(x640 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x642) "emit"
[|((match x638 with
| `unhandledRejection ->
Ojs.string_to_js "unhandledRejection"));(
any_to_js x639);(Promise.t_to_js any_to_js x640)|])
let (emit_warning :
t -> event:[ `warning ] -> warning:Error.t -> bool) =
fun (x645 : t) ->
fun ~event:(x643 : [ `warning ]) ->
fun ~warning:(x644 : Error.t) ->
Ojs.bool_of_js
(Ojs.call (t_to_js x645) "emit"
[|((match x643 with
| `warning -> Ojs.string_to_js "warning"));(
Error.t_to_js x644)|])
let (emit_message :
t -> event:[ `message ] -> message:any -> send_handle:any -> t) =
fun (x649 : t) ->
fun ~event:(x646 : [ `message ]) ->
fun ~message:(x647 : any) ->
fun ~send_handle:(x648 : any) ->
t_of_js
(Ojs.call (t_to_js x649) "emit"
[|((match x646 with
| `message -> Ojs.string_to_js "message"));(
any_to_js x647);(any_to_js x648)|])
let (emit_new_listener :
t ->
event:[ `newListener ] ->
event_name:symbol or_string ->
listener:(args:any list -> unit) -> t)
=
fun (x656 : t) ->
fun ~event:(x650 : [ `newListener ]) ->
fun ~event_name:(x651 : symbol or_string) ->
fun ~listener:(x653 : args:any list -> unit) ->
t_of_js
(Ojs.call (t_to_js x656) "emit"
[|((match x650 with
| `newListener -> Ojs.string_to_js "newListener"));(
or_string_to_js symbol_to_js x651);(Ojs.fun_to_js_args
(fun
(x654 : _)
->
x653
~args:(
Ojs.list_of_js_from
any_of_js
x654 0)))|])
let (emit_remove_listener :
t ->
event:[ `removeListener ] ->
event_name:string -> listener:(args:any list -> unit) -> t)
=
fun (x662 : t) ->
fun ~event:(x657 : [ `removeListener ]) ->
fun ~event_name:(x658 : string) ->
fun ~listener:(x659 : args:any list -> unit) ->
t_of_js
(Ojs.call (t_to_js x662) "emit"
[|((match x657 with
| `removeListener ->
Ojs.string_to_js "removeListener"));(Ojs.string_to_js
x658);(
Ojs.fun_to_js_args
(fun (x660 : _) ->
x659
~args:(Ojs.list_of_js_from any_of_js x660 0)))|])
let (emit_multiple_resolves :
t ->
event:[ `multipleResolves ] ->
listener:MultipleResolvesListener.t -> t)
=
fun (x665 : t) ->
fun ~event:(x663 : [ `multipleResolves ]) ->
fun ~listener:(x664 : MultipleResolvesListener.t) ->
t_of_js
(Ojs.call (t_to_js x665) "emit"
[|((match x663 with
| `multipleResolves ->
Ojs.string_to_js "multipleResolves"));(MultipleResolvesListener.t_to_js
x664)|])
end
let (stdout : WriteStream.t) =
WriteStream.t_of_js (Ojs.get_prop_ascii Import.process "stdout")
let (set_stdout : WriteStream.t -> unit) =
fun (x666 : WriteStream.t) ->
ignore
(Ojs.call Import.process "stdout" [|(WriteStream.t_to_js x666)|])
let (stderr : WriteStream.t) =
WriteStream.t_of_js (Ojs.get_prop_ascii Import.process "stderr")
let (set_stderr : WriteStream.t -> unit) =
fun (x667 : WriteStream.t) ->
ignore
(Ojs.call Import.process "stderr" [|(WriteStream.t_to_js x667)|])
let (stdin : ReadStream.t) =
ReadStream.t_of_js (Ojs.get_prop_ascii Import.process "stdin")
let (set_stdin : ReadStream.t -> unit) =
fun (x668 : ReadStream.t) ->
ignore
(Ojs.call Import.process "stdin" [|(ReadStream.t_to_js x668)|])
let (open_stdin : Socket.t) =
Socket.t_of_js (Ojs.get_prop_ascii Import.process "openStdin")
let (argv : string list) =
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii Import.process "argv")
let (set_argv : string list -> unit) =
fun (x670 : string list) ->
ignore
(Ojs.call Import.process "argv"
[|(Ojs.list_to_js Ojs.string_to_js x670)|])
let (argv0 : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "argv0")
let (set_argv0 : string -> unit) =
fun (x672 : string) ->
ignore (Ojs.call Import.process "argv0" [|(Ojs.string_to_js x672)|])
let (exec_argv : string list) =
Ojs.list_of_js Ojs.string_of_js
(Ojs.get_prop_ascii Import.process "execArgv")
let (set_exec_argv : string list -> unit) =
fun (x674 : string list) ->
ignore
(Ojs.call Import.process "execArgv"
[|(Ojs.list_to_js Ojs.string_to_js x674)|])
let (exec_path : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "execPath")
let (set_exec_path : string -> unit) =
fun (x676 : string) ->
ignore
(Ojs.call Import.process "execPath" [|(Ojs.string_to_js x676)|])
let (abort : never) =
never_of_js (Ojs.get_prop_ascii Import.process "abort")
let (chdir : directory:string -> unit) =
fun ~directory:(x677 : string) ->
ignore (Ojs.call Import.process "chdir" [|(Ojs.string_to_js x677)|])
let (cwd : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "cwd")
let (debug_port : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "debugPort")
let (set_debug_port : int -> unit) =
fun (x678 : int) ->
ignore (Ojs.call Import.process "debugPort" [|(Ojs.int_to_js x678)|])
let (emit_warning :
warning:Error.t or_string ->
?name:string -> ?ctor:untyped_function -> unit -> unit)
=
fun ~warning:(x679 : Error.t or_string) ->
fun ?name:(x680 : string option) ->
fun ?ctor:(x681 : untyped_function option) ->
fun () ->
ignore
(let x686 = Import.process in
Ojs.call (Ojs.get_prop_ascii x686 "emitWarning") "apply"
[|x686;((let x682 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x682 "push"
[|(or_string_to_js Error.t_to_js x679)|]);
(match x680 with
| Some x684 ->
ignore
(Ojs.call x682 "push"
[|(Ojs.string_to_js x684)|])
| None -> ());
(match x681 with
| Some x683 ->
ignore
(Ojs.call x682 "push"
[|(untyped_function_to_js x683)|])
| None -> ());
x682))|])
let (env : ProcessEnv.t) =
ProcessEnv.t_of_js (Ojs.get_prop_ascii Import.process "env")
let (set_env : ProcessEnv.t -> unit) =
fun (x687 : ProcessEnv.t) ->
ignore (Ojs.call Import.process "env" [|(ProcessEnv.t_to_js x687)|])
let (exit : ?code:int -> unit -> never) =
fun ?code:(x688 : int option) ->
fun () ->
never_of_js
(let x691 = Import.process in
Ojs.call (Ojs.get_prop_ascii x691 "exit") "apply"
[|x691;((let x689 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x688 with
| Some x690 ->
ignore
(Ojs.call x689 "push" [|(Ojs.int_to_js x690)|])
| None -> ());
x689))|])
let (exit_code : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "exitCode")
let (set_exit_code : int -> unit) =
fun (x692 : int) ->
ignore (Ojs.call Import.process "exitCode" [|(Ojs.int_to_js x692)|])
let (getgid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "getgid")
let (setgid : id:string or_number -> unit) =
fun ~id:(x693 : string or_number) ->
ignore
(Ojs.call Import.process "setgid"
[|(or_number_to_js Ojs.string_to_js x693)|])
let (getuid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "getuid")
let (setuid : id:string or_number -> unit) =
fun ~id:(x695 : string or_number) ->
ignore
(Ojs.call Import.process "setuid"
[|(or_number_to_js Ojs.string_to_js x695)|])
let (geteuid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "geteuid")
let (seteuid : id:string or_number -> unit) =
fun ~id:(x697 : string or_number) ->
ignore
(Ojs.call Import.process "seteuid"
[|(or_number_to_js Ojs.string_to_js x697)|])
let (getegid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "getegid")
let (setegid : id:string or_number -> unit) =
fun ~id:(x699 : string or_number) ->
ignore
(Ojs.call Import.process "setegid"
[|(or_number_to_js Ojs.string_to_js x699)|])
let (getgroups : int list) =
Ojs.list_of_js Ojs.int_of_js
(Ojs.get_prop_ascii Import.process "getgroups")
let (setgroups : groups:string or_number list -> unit) =
fun ~groups:(x702 : string or_number list) ->
ignore
(Ojs.call Import.process "setgroups"
[|(Ojs.list_to_js
(fun (x703 : string or_number) ->
or_number_to_js Ojs.string_to_js x703) x702)|])
let (set_uncaught_exception_capture_callback :
cb:(err:Error.t -> unit) or_null -> unit) =
fun ~cb:(x705 : (err:Error.t -> unit) or_null) ->
ignore
(Ojs.call Import.process "setUncaughtExceptionCaptureCallback"
[|(or_null_to_js
(fun (x706 : err:Error.t -> unit) ->
Ojs.fun_to_js 1
(fun (x707 : Ojs.t) -> x706 ~err:(Error.t_of_js x707)))
x705)|])
let (has_uncaught_exception_capture_callback : bool) =
Ojs.bool_of_js
(Ojs.get_prop_ascii Import.process
"hasUncaughtExceptionCaptureCallback")
let (version : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "version")
let (set_version : string -> unit) =
fun (x708 : string) ->
ignore
(Ojs.call Import.process "version" [|(Ojs.string_to_js x708)|])
let (versions : ProcessVersions.t) =
ProcessVersions.t_of_js (Ojs.get_prop_ascii Import.process "versions")
let (set_versions : ProcessVersions.t -> unit) =
fun (x709 : ProcessVersions.t) ->
ignore
(Ojs.call Import.process "versions"
[|(ProcessVersions.t_to_js x709)|])
let (config : AnonymousInterface8.t) =
AnonymousInterface8.t_of_js
(Ojs.get_prop_ascii Import.process "config")
let (set_config : AnonymousInterface8.t -> unit) =
fun (x710 : AnonymousInterface8.t) ->
ignore
(Ojs.call Import.process "config"
[|(AnonymousInterface8.t_to_js x710)|])
let (kill : pid:int -> ?signal:string or_number -> unit -> [ `L_b_true ])
=
fun ~pid:(x711 : int) ->
fun ?signal:(x712 : string or_number option) ->
fun () ->
let x717 =
let x716 = Import.process in
Ojs.call (Ojs.get_prop_ascii x716 "kill") "apply"
[|x716;((let x713 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x713 "push" [|(Ojs.int_to_js x711)|]);
(match x712 with
| Some x714 ->
ignore
(Ojs.call x713 "push"
[|(or_number_to_js Ojs.string_to_js x714)|])
| None -> ());
x713))|] in
match Ojs.bool_of_js x717 with
| true -> `L_b_true
| _ -> assert false
let (pid : int) = Ojs.int_of_js (Ojs.get_prop_ascii Import.process "pid")
let (set_pid : int -> unit) =
fun (x718 : int) ->
ignore (Ojs.call Import.process "pid" [|(Ojs.int_to_js x718)|])
let (ppid : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "ppid")
let (set_ppid : int -> unit) =
fun (x719 : int) ->
ignore (Ojs.call Import.process "ppid" [|(Ojs.int_to_js x719)|])
let (title : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "title")
let (set_title : string -> unit) =
fun (x720 : string) ->
ignore (Ojs.call Import.process "title" [|(Ojs.string_to_js x720)|])
let (arch : string) =
Ojs.string_of_js (Ojs.get_prop_ascii Import.process "arch")
let (set_arch : string -> unit) =
fun (x721 : string) ->
ignore (Ojs.call Import.process "arch" [|(Ojs.string_to_js x721)|])
let (platform : Platform.t) =
Platform.t_of_js (Ojs.get_prop_ascii Import.process "platform")
let (set_platform : Platform.t -> unit) =
fun (x722 : Platform.t) ->
ignore
(Ojs.call Import.process "platform" [|(Platform.t_to_js x722)|])
let (main_module : Module.t) =
Module.t_of_js (Ojs.get_prop_ascii Import.process "mainModule")
let (set_main_module : Module.t -> unit) =
fun (x723 : Module.t) ->
ignore
(Ojs.call Import.process "mainModule" [|(Module.t_to_js x723)|])
let (memory_usage : MemoryUsage.t) =
MemoryUsage.t_of_js (Ojs.get_prop_ascii Import.process "memoryUsage")
let (cpu_usage : ?previous_value:CpuUsage.t -> unit -> CpuUsage.t) =
fun ?previous_value:(x724 : CpuUsage.t option) ->
fun () ->
CpuUsage.t_of_js
(let x727 = Import.process in
Ojs.call (Ojs.get_prop_ascii x727 "cpuUsage") "apply"
[|x727;((let x725 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x724 with
| Some x726 ->
ignore
(Ojs.call x725 "push"
[|(CpuUsage.t_to_js x726)|])
| None -> ());
x725))|])
let (next_tick : callback:untyped_function -> args:any list -> unit) =
fun ~callback:(x728 : untyped_function) ->
fun ~args:(x729 : any list) ->
ignore
(let x732 = Import.process in
Ojs.call (Ojs.get_prop_ascii x732 "nextTick") "apply"
[|x732;((let x730 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x730 "push"
[|(untyped_function_to_js x728)|]);
List.iter
(fun (x731 : any) ->
ignore
(Ojs.call x730 "push" [|(any_to_js x731)|]))
x729;
x730))|])
let (release : ProcessRelease.t) =
ProcessRelease.t_of_js (Ojs.get_prop_ascii Import.process "release")
let (set_release : ProcessRelease.t -> unit) =
fun (x733 : ProcessRelease.t) ->
ignore
(Ojs.call Import.process "release"
[|(ProcessRelease.t_to_js x733)|])
let (features : AnonymousInterface6.t) =
AnonymousInterface6.t_of_js
(Ojs.get_prop_ascii Import.process "features")
let (set_features : AnonymousInterface6.t -> unit) =
fun (x734 : AnonymousInterface6.t) ->
ignore
(Ojs.call Import.process "features"
[|(AnonymousInterface6.t_to_js x734)|])
let (umask : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "umask")
let (umask' : mask:string or_number -> int) =
fun ~mask:(x735 : string or_number) ->
Ojs.int_of_js
(Ojs.call Import.process "umask"
[|(or_number_to_js Ojs.string_to_js x735)|])
let (uptime : int) =
Ojs.int_of_js (Ojs.get_prop_ascii Import.process "uptime")
let (hrtime : HRTime.t) =
HRTime.t_of_js (Ojs.get_prop_ascii Import.process "hrtime")
let (set_hrtime : HRTime.t -> unit) =
fun (x737 : HRTime.t) ->
ignore (Ojs.call Import.process "hrtime" [|(HRTime.t_to_js x737)|])
let (domain : Node_domain.Domain.Domain.t) =
Node_domain.Domain.Domain.t_of_js
(Ojs.get_prop_ascii Import.process "domain")
let (set_domain : Node_domain.Domain.Domain.t -> unit) =
fun (x738 : Node_domain.Domain.Domain.t) ->
ignore
(Ojs.call Import.process "domain"
[|(Node_domain.Domain.Domain.t_to_js x738)|])
let (send :
message:any ->
?send_handle:any ->
?options:AnonymousInterface7.t ->
?callback:(error:Error.t or_null -> unit) -> unit -> bool)
=
fun ~message:(x739 : any) ->
fun ?send_handle:(x740 : any option) ->
fun ?options:(x741 : AnonymousInterface7.t option) ->
fun ?callback:(x742 : (error:Error.t or_null -> unit) option) ->
fun () ->
Ojs.bool_of_js
(let x749 = Import.process in
Ojs.call (Ojs.get_prop_ascii x749 "send") "apply"
[|x749;((let x743 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x743 "push" [|(any_to_js x739)|]);
(match x740 with
| Some x748 ->
ignore
(Ojs.call x743 "push"
[|(any_to_js x748)|])
| None -> ());
(match x741 with
| Some x747 ->
ignore
(Ojs.call x743 "push"
[|(AnonymousInterface7.t_to_js x747)|])
| None -> ());
(match x742 with
| Some x744 ->
ignore
(Ojs.call x743 "push"
[|(Ojs.fun_to_js 1
(fun (x745 : Ojs.t) ->
x744
~error:(or_null_of_js
Error.t_of_js
x745)))|])
| None -> ());
x743))|])
let (disconnect : unit) =
Ojs.unit_of_js (Ojs.get_prop_ascii Import.process "disconnect")
let (connected : bool) =
Ojs.bool_of_js (Ojs.get_prop_ascii Import.process "connected")
let (set_connected : bool -> unit) =
fun (x750 : bool) ->
ignore
(Ojs.call Import.process "connected" [|(Ojs.bool_to_js x750)|])
let (allowed_node_environment_flags : string ReadonlySet.t) =
ReadonlySet.t_of_js Ojs.string_of_js
(Ojs.get_prop_ascii Import.process "allowedNodeEnvironmentFlags")
let (set_allowed_node_environment_flags : string ReadonlySet.t -> unit) =
fun (x752 : string ReadonlySet.t) ->
ignore
(Ojs.call Import.process "allowedNodeEnvironmentFlags"
[|(ReadonlySet.t_to_js Ojs.string_to_js x752)|])
let (report : ProcessReport.t) =
ProcessReport.t_of_js (Ojs.get_prop_ascii Import.process "report")
let (set_report : ProcessReport.t -> unit) =
fun (x754 : ProcessReport.t) ->
ignore
(Ojs.call Import.process "report" [|(ProcessReport.t_to_js x754)|])
let (resource_usage : ResourceUsage.t) =
ResourceUsage.t_of_js
(Ojs.get_prop_ascii Import.process "resourceUsage")
let (trace_deprecation : bool) =
Ojs.bool_of_js (Ojs.get_prop_ascii Import.process "traceDeprecation")
let (set_trace_deprecation : bool -> unit) =
fun (x755 : bool) ->
ignore
(Ojs.call Import.process "traceDeprecation"
[|(Ojs.bool_to_js x755)|])
let (on : string -> Ojs.t -> unit) =
fun (x756 : string) ->
fun (x757 : Ojs.t) ->
ignore (Ojs.call Ojs.global "on" [|(Ojs.string_to_js x756);x757|])
let (add_listener : string -> Ojs.t -> unit) =
fun (x758 : string) ->
fun (x759 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "addListener"
[|(Ojs.string_to_js x758);x759|])
let (once : string -> Ojs.t -> unit) =
fun (x760 : string) ->
fun (x761 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "once" [|(Ojs.string_to_js x760);x761|])
let (prepend_listener : string -> Ojs.t -> unit) =
fun (x762 : string) ->
fun (x763 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "prependListener"
[|(Ojs.string_to_js x762);x763|])
let (prepend_once_listener : string -> Ojs.t -> unit) =
fun (x764 : string) ->
fun (x765 : Ojs.t) ->
ignore
(Ojs.call Ojs.global "prependOnceListener"
[|(Ojs.string_to_js x764);x765|])
let with_listener_fn fn =
function
| `BeforeExit f -> (fn "beforeExit") @@ (BeforeExitListener.t_to_js f)
| `Disconnect f -> (fn "disconnect") @@ (DisconnectListener.t_to_js f)
| `Exit f -> (fn "exit") @@ (ExitListener.t_to_js f)
| `RejectionHandled f ->
(fn "rejectionHandled") @@ (RejectionHandledListener.t_to_js f)
| `UncaughtException f ->
(fn "uncaughtException") @@ (UncaughtExceptionListener.t_to_js f)
| `UnhandledRejection f ->
(fn "unhandledRejection") @@ (UnhandledRejectionListener.t_to_js f)
| `Warning f -> (fn "warning") @@ (WarningListener.t_to_js f)
| `Message f -> (fn "message") @@ (MessageListener.t_to_js f)
| `NewListener f ->
(fn "newListener") @@ (NewListenerListener.t_to_js f)
| `RemoveListener f ->
(fn "removeListener") @@ (RemoveListenerListener.t_to_js f)
| `MultipleResolves f ->
(fn "multipleResolves") @@ (MultipleResolvesListener.t_to_js f)
let on = with_listener_fn on
let add_listener = with_listener_fn add_listener
let once = with_listener_fn once
let prepend_listener = with_listener_fn prepend_listener
let prepend_once_listener = with_listener_fn prepend_once_listener
let (emit_before_exit : event:[ `beforeExit ] -> code:int -> bool) =
fun ~event:(x777 : [ `beforeExit ]) ->
fun ~code:(x778 : int) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x777 with
| `beforeExit -> Ojs.string_to_js "beforeExit"));(
Ojs.int_to_js x778)|])
let (emit_disconnect : event:[ `disconnect ] -> bool) =
fun ~event:(x779 : [ `disconnect ]) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x779 with
| `disconnect -> Ojs.string_to_js "disconnect"))|])
let (emit_exit : event:[ `exit ] -> code:int -> bool) =
fun ~event:(x780 : [ `exit ]) ->
fun ~code:(x781 : int) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x780 with | `exit -> Ojs.string_to_js "exit"));(
Ojs.int_to_js x781)|])
let (emit_rejection_handled :
event:[ `rejectionHandled ] -> promise:any Promise.t -> bool) =
fun ~event:(x782 : [ `rejectionHandled ]) ->
fun ~promise:(x783 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x782 with
| `rejectionHandled -> Ojs.string_to_js "rejectionHandled"));(
Promise.t_to_js any_to_js x783)|])
let (emit_uncaught_exception :
event:[ `uncaughtException ] -> error:Error.t -> bool) =
fun ~event:(x785 : [ `uncaughtException ]) ->
fun ~error:(x786 : Error.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x785 with
| `uncaughtException ->
Ojs.string_to_js "uncaughtException"));(Error.t_to_js
x786)|])
let (emit_uncaught_exception_monitor :
event:[ `uncaughtExceptionMonitor ] -> error:Error.t -> bool) =
fun ~event:(x787 : [ `uncaughtExceptionMonitor ]) ->
fun ~error:(x788 : Error.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x787 with
| `uncaughtExceptionMonitor ->
Ojs.string_to_js "uncaughtExceptionMonitor"));(
Error.t_to_js x788)|])
let (emit_unhandled_rejection :
event:[ `unhandledRejection ] ->
reason:any -> promise:any Promise.t -> bool)
=
fun ~event:(x789 : [ `unhandledRejection ]) ->
fun ~reason:(x790 : any) ->
fun ~promise:(x791 : any Promise.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x789 with
| `unhandledRejection ->
Ojs.string_to_js "unhandledRejection"));(any_to_js
x790);(
Promise.t_to_js any_to_js x791)|])
let (emit_warning : event:[ `warning ] -> warning:Error.t -> bool) =
fun ~event:(x793 : [ `warning ]) ->
fun ~warning:(x794 : Error.t) ->
Ojs.bool_of_js
(Ojs.call Import.process "emit"
[|((match x793 with | `warning -> Ojs.string_to_js "warning"));(
Error.t_to_js x794)|])
let (emit_message :
event:[ `message ] -> message:any -> send_handle:any -> Process.t) =
fun ~event:(x795 : [ `message ]) ->
fun ~message:(x796 : any) ->
fun ~send_handle:(x797 : any) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x795 with | `message -> Ojs.string_to_js "message"));(
any_to_js x796);(any_to_js x797)|])
let (emit_new_listener :
event:[ `newListener ] ->
event_name:symbol or_string ->
listener:(args:any list -> unit) -> Process.t)
=
fun ~event:(x798 : [ `newListener ]) ->
fun ~event_name:(x799 : symbol or_string) ->
fun ~listener:(x801 : args:any list -> unit) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x798 with
| `newListener -> Ojs.string_to_js "newListener"));(
or_string_to_js symbol_to_js x799);(Ojs.fun_to_js_args
(fun (x802 : _) ->
x801
~args:(
Ojs.list_of_js_from
any_of_js
x802 0)))|])
let (emit_remove_listener :
event:[ `removeListener ] ->
event_name:string -> listener:(args:any list -> unit) -> Process.t)
=
fun ~event:(x804 : [ `removeListener ]) ->
fun ~event_name:(x805 : string) ->
fun ~listener:(x806 : args:any list -> unit) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x804 with
| `removeListener -> Ojs.string_to_js "removeListener"));(
Ojs.string_to_js x805);(Ojs.fun_to_js_args
(fun (x807 : _) ->
x806
~args:(Ojs.list_of_js_from
any_of_js x807 0)))|])
let (emit_multiple_resolves :
event:[ `multipleResolves ] ->
listener:MultipleResolvesListener.t -> Process.t)
=
fun ~event:(x809 : [ `multipleResolves ]) ->
fun ~listener:(x810 : MultipleResolvesListener.t) ->
Process.t_of_js
(Ojs.call Import.process "emit"
[|((match x809 with
| `multipleResolves -> Ojs.string_to_js "multipleResolves"));(
MultipleResolvesListener.t_to_js x810)|])
end
let (process : Process.Process.t) =
Process.Process.t_of_js (Ojs.get_prop_ascii Ojs.global "process")
| |
6e7f79eb04f349b55023f2f6601f8d9182d953cc7f3515cd78a3608ca94fd88f | haskell-opengl/OpenGLRaw | PixelBufferObject.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
Module : Graphics .
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.PixelBufferObject (
-- * Extension Support
glGetARBPixelBufferObject,
gl_ARB_pixel_buffer_object,
-- * Enums
pattern GL_PIXEL_PACK_BUFFER_ARB,
pattern GL_PIXEL_PACK_BUFFER_BINDING_ARB,
pattern GL_PIXEL_UNPACK_BUFFER_ARB,
pattern GL_PIXEL_UNPACK_BUFFER_BINDING_ARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/ARB/PixelBufferObject.hs | haskell | ------------------------------------------------------------------------------
|
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums | # LANGUAGE PatternSynonyms #
Module : Graphics .
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.ARB.PixelBufferObject (
glGetARBPixelBufferObject,
gl_ARB_pixel_buffer_object,
pattern GL_PIXEL_PACK_BUFFER_ARB,
pattern GL_PIXEL_PACK_BUFFER_BINDING_ARB,
pattern GL_PIXEL_UNPACK_BUFFER_ARB,
pattern GL_PIXEL_UNPACK_BUFFER_BINDING_ARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.