_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 |
|---|---|---|---|---|---|---|---|---|
f7fae31f9ea3b35bcd9774ebd74e6bf2ed5e399c8fffbee14094fbfe0a47e79c | haskell-webgear/webgear | JWT.hs | # OPTIONS_GHC -Wno - orphans #
| OpenApi implementation of ' JWTAuth '' trait .
module WebGear.OpenApi.Trait.Auth.JWT where
import Data.OpenApi
import Data.String (fromString)
import Data.Typeable (Proxy (..))
import GHC.TypeLits (KnownSymbol, symbolVal)
import WebGear.Core.Request (Request)
import WebGear.Core.Trait (Attribute, Get (..), Linked, TraitAbsence (..))
import WebGear.Core.Trait.Auth.JWT (JWTAuth' (..))
import WebGear.OpenApi.Handler (DocNode (DocSecurityScheme), OpenApiHandler (..), singletonNode)
instance
(TraitAbsence (JWTAuth' x scheme m e a) Request, KnownSymbol scheme) =>
Get (OpenApiHandler m) (JWTAuth' x scheme m e a) Request
where
# INLINE getTrait #
getTrait ::
JWTAuth' x scheme m e a ->
OpenApiHandler m (Linked ts Request) (Either (Absence (JWTAuth' x scheme m e a) Request) (Attribute (JWTAuth' x scheme m e a) Request))
getTrait _ =
let schemeName = "http" <> fromString (symbolVal (Proxy @scheme))
securityScheme =
SecurityScheme
{ _securitySchemeType = SecuritySchemeHttp (HttpSchemeBearer (Just "JWT"))
, _securitySchemeDescription = Nothing
}
in OpenApiHandler $ singletonNode (DocSecurityScheme schemeName securityScheme)
| null | https://raw.githubusercontent.com/haskell-webgear/webgear/52e90e28d81e4ce6d7c8e63b3f9769f6629b031f/webgear-openapi/src/WebGear/OpenApi/Trait/Auth/JWT.hs | haskell | # OPTIONS_GHC -Wno - orphans #
| OpenApi implementation of ' JWTAuth '' trait .
module WebGear.OpenApi.Trait.Auth.JWT where
import Data.OpenApi
import Data.String (fromString)
import Data.Typeable (Proxy (..))
import GHC.TypeLits (KnownSymbol, symbolVal)
import WebGear.Core.Request (Request)
import WebGear.Core.Trait (Attribute, Get (..), Linked, TraitAbsence (..))
import WebGear.Core.Trait.Auth.JWT (JWTAuth' (..))
import WebGear.OpenApi.Handler (DocNode (DocSecurityScheme), OpenApiHandler (..), singletonNode)
instance
(TraitAbsence (JWTAuth' x scheme m e a) Request, KnownSymbol scheme) =>
Get (OpenApiHandler m) (JWTAuth' x scheme m e a) Request
where
# INLINE getTrait #
getTrait ::
JWTAuth' x scheme m e a ->
OpenApiHandler m (Linked ts Request) (Either (Absence (JWTAuth' x scheme m e a) Request) (Attribute (JWTAuth' x scheme m e a) Request))
getTrait _ =
let schemeName = "http" <> fromString (symbolVal (Proxy @scheme))
securityScheme =
SecurityScheme
{ _securitySchemeType = SecuritySchemeHttp (HttpSchemeBearer (Just "JWT"))
, _securitySchemeDescription = Nothing
}
in OpenApiHandler $ singletonNode (DocSecurityScheme schemeName securityScheme)
| |
706cb48608d1b4e17e8d034890ac812e732d07d1b0ef7095ebb9eccd2a529d32 | codeflows/rebass | ListUtil.hs | module Rebass.ListUtil where
import Data.List
split :: Eq a => a -> [a] -> [[a]]
split s xs = foldr collect [[]] xs
where collect x (current : splitted) | x == s = [] : (current : splitted)
| otherwise = (x : current) : splitted
endsWith :: Eq a => [a] -> [a] -> Bool
endsWith hayStack needle = any (== needle) $ tails hayStack
startsWith :: Eq a => [a] -> [a] -> Bool
startsWith hayStack needle = any (== needle) $ inits hayStack
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace _ _ [] = []
replace old new hayStack | hayStack `startsWith` old = new ++ replace old new (drop (length old) hayStack)
| otherwise = head hayStack : replace old new (tail hayStack)
| null | https://raw.githubusercontent.com/codeflows/rebass/8c8411ee51c5d9588ddd263d311ef7b5939e3e9a/src/Rebass/ListUtil.hs | haskell | module Rebass.ListUtil where
import Data.List
split :: Eq a => a -> [a] -> [[a]]
split s xs = foldr collect [[]] xs
where collect x (current : splitted) | x == s = [] : (current : splitted)
| otherwise = (x : current) : splitted
endsWith :: Eq a => [a] -> [a] -> Bool
endsWith hayStack needle = any (== needle) $ tails hayStack
startsWith :: Eq a => [a] -> [a] -> Bool
startsWith hayStack needle = any (== needle) $ inits hayStack
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace _ _ [] = []
replace old new hayStack | hayStack `startsWith` old = new ++ replace old new (drop (length old) hayStack)
| otherwise = head hayStack : replace old new (tail hayStack)
| |
dbf2a5f0aedf0312e27ca0c0998c3bcecea6a9899e8d96fa017ba7726f5c9f8c | inaka/elvis_core | fail_no_block_expressions.erl | -module(fail_no_block_expressions).
-export([no_block_expression/0, block_expression/0]).
no_block_expression() ->
ok.
block_expression() ->
begin
ok
end.
| null | https://raw.githubusercontent.com/inaka/elvis_core/9ff0c1115fcb3cf3737e701f1307ee02e6272c1b/test/examples/fail_no_block_expressions.erl | erlang | -module(fail_no_block_expressions).
-export([no_block_expression/0, block_expression/0]).
no_block_expression() ->
ok.
block_expression() ->
begin
ok
end.
| |
59c63ebc167e4abc7aaa28ff5e6a84fa65a11d0d63c60594d22a7d9b522cb0ab | pierric/neural-network | LSTM.hs | ------------------------------------------------------------
-- |
Module : Data . NeuralNetwork . Backend . BLASHS.LSTM
Description : A backend for neuralnetwork with .
Copyright : ( c ) 2016
-- License : BSD-style (see the file LICENSE)
Maintainer : < >
-- Stability : experimental
-- Portability : portable
--
--
This module supplies a LSTM component .
------------------------------------------------------------
# LANGUAGE UndecidableInstances #
module Data.NeuralNetwork.Backend.BLASHS.LSTM(
LSTM(..), LSTM_Env_Transformer, newLSTM, Stream(..),
) where
import Blas.Generic.Unsafe (Numeric)
import Control.Monad.State.Strict
import Data.Foldable (foldrM)
import qualified Data.Vector as V
import qualified Data.Map as M
import Data.Data
import Data.Generics
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (tanh)
import Data.NeuralNetwork
import Data.NeuralNetwork.Adapter
import Data.NeuralNetwork.Backend.BLASHS.Utils
import Data.NeuralNetwork.Backend.BLASHS.SIMD
import System.Random.MWC
import System.Random.MWC.Distributions
-- import GHC.Float (double2Float)
import Data.Vector.Storable (Storable)
import qualified Text.PrettyPrint.Free as P
type VecR p = DenseVector p
type MatR p = DenseMatrix p
type LSTMident = Int
data LSTM p = LLSTM { parm_w_f :: MatR p, parm_w_i :: MatR p, parm_w_o :: MatR p, parm_w_c :: MatR p
, parm_u_f :: MatR p, parm_u_i :: MatR p, parm_u_o :: MatR p
, parm_b_f :: VecR p, parm_b_i :: VecR p, parm_b_o :: VecR p, parm_b_c :: VecR p
, lstm_id :: LSTMident, lstm_isize, lstm_osize :: Int
}
deriving Typeable
instance Data p => Data (LSTM p) where
toConstr a = lstmConstr
gfoldl f z a = z (\i->a{lstm_id=i}) `f` (lstm_id a)
gunfold k z c = errorWithoutStackTrace "Data.Data.gunfold(LSTM)"
dataTypeOf _ = lstmDataType
lstmConstr = mkConstr lstmDataType "LSTM" ["identifier"] Prefix
lstmDataType = mkDataType "Data.NeuralNetwork.Backend.BLASHS.LSTM.LSTM" [lstmConstr]
global_LSTM_id_counter :: IORef Int
global_LSTM_id_counter = unsafePerformIO (newIORef 0)
| create a new LSTM component
newLSTM :: (Numeric p, RealType p, SIMDable p)
=> Int -- ^ input size
-> Int -- ^ output size
-> IO (LSTM p)-- ^ the new layer
newLSTM m n =
withSystemRandom . asGenIO $ \gen -> do
let newW v = do raw <- newDenseVectorByGen (fromDouble <$> normal 0 v gen) (m*n)
return $ v2m m n raw
newU v = do raw <- newDenseVectorByGen (fromDouble <$> normal 0 v gen) (n*n)
return $ v2m n n raw
newB v = newDenseVectorConst n v
parm_w_f <- newW 0.01
parm_w_i <- newW 0.01
parm_w_o <- newW 0.01
parm_w_c <- newW 0.01
parm_u_f <- newU 0.01
parm_u_i <- newU 0.01
parm_u_o <- newU 0.01
parm_b_f <- newB 1.0
parm_b_i <- newB 0
parm_b_o <- newB 0
parm_b_c <- newB 0
lstm_id <- readIORef global_LSTM_id_counter
modifyIORef' global_LSTM_id_counter (+1)
return $ LLSTM {
parm_w_f = parm_w_f,
parm_w_i = parm_w_i,
parm_w_o = parm_w_o,
parm_w_c = parm_w_c,
parm_u_f = parm_u_f,
parm_u_i = parm_u_i,
parm_u_o = parm_u_o,
parm_b_f = parm_b_f,
parm_b_i = parm_b_i,
parm_b_o = parm_b_o,
parm_b_c = parm_b_c,
lstm_id = lstm_id,
lstm_isize = m,
lstm_osize = n
}
-- state passed forward
type LSTMstreamPrev p = VecR p
-- state passed backward
data LSTMstreamNext p = NextNothing
| NextJust { nx_mf, nx_mi, nx_mo, nx_f,
nx_delta_c, nx_delta_f, nx_delta_i, nx_delta_o :: VecR p,
nx_ori_uf, nx_ori_ui, nx_ori_uo :: MatR p }
-- sum-type of the forward and backward state
type LSTMstreamInfo p = Either (LSTMstreamPrev p) (LSTMstreamNext p)
type LSTM_Env_Transformer p = StateT (M.Map LSTMident (LSTMstreamInfo p))
instance (Numeric p, RealType p, SIMDable p) => Component (LSTM p) where
The state is mapping from LSTM identifier to Info .
So when mutiple compoents are stacked , each can
-- access its own state.
type Dty (LSTM p) = p
type Run (LSTM p) = LSTM_Env_Transformer p IO
type Inp (LSTM p) = VecR p
type Out (LSTM p) = VecR p
data Trace (LSTM p) = LTrace { tr_mf, tr_mi, tr_mo, tr_n, tr_f, tr_i, tr_o, tr_c', tr_c, tr_inp, tr_out :: VecR p }
forwardT lstm x_t = do
Just (Left c_tm1) <- gets (M.lookup $ lstm_id lstm)
let osize = lstm_osize lstm
mf_t <- newDenseVector osize
mf_t <<= x_t :<# parm_w_f lstm
mf_t <<+ c_tm1 :<# parm_u_f lstm
mf_t <<= mf_t :.+ parm_b_f lstm
f_t <- newDenseVectorCopy mf_t
f_t <<= Apply sigma
mi_t <- newDenseVector osize
mi_t <<= x_t :<# parm_w_i lstm
mi_t <<+ c_tm1 :<# parm_u_i lstm
mi_t <<= mi_t :.+ parm_b_i lstm
i_t <- newDenseVectorCopy mi_t
i_t <<= Apply sigma
mo_t <- newDenseVector osize
mo_t <<= x_t :<# parm_w_o lstm
mo_t <<+ c_tm1 :<# parm_u_o lstm
mo_t <<= mo_t :.+ parm_b_o lstm
o_t <- newDenseVectorCopy mo_t
o_t <<= Apply sigma
n_t <- newDenseVector osize
n_t <<= x_t :<# parm_w_c lstm
n_t <<= n_t :.+ parm_b_c lstm
c_t <- newDenseVector osize
c_t <<= c_tm1 :.* f_t
tmp <- newDenseVectorCopy n_t
tmp <<= Apply sigma
tmp <<= i_t :.* tmp
c_t <<= c_t :.+ tmp
denseVectorCopy tmp c_t
tmp <<= Apply sigma
tmp <<= tmp :.* o_t
modify $ M.insert (lstm_id lstm) (Left c_t)
let trace = LTrace { tr_mf = mf_t, tr_mi = mi_t, tr_mo = mo_t
, tr_n = n_t
, tr_f = f_t, tr_i = i_t, tr_o = o_t
, tr_c' = c_tm1, tr_c = c_t
, tr_inp = x_t, tr_out = tmp }
return $ trace
output = tr_out
backward lstm trace !delta_out rate = do
Just (Right upward) <- gets (M.lookup $ lstm_id lstm)
(delta_ct, ori_uf, ori_ui, ori_uo) <- case upward of
NextNothing -> do
tmp <- newDenseVectorCopy (tr_c trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* tr_o trace
tmp <<= tmp :.* delta_out
the original Ui , Uf , Uo are used in calc delta_ct ,
-- so save a copy in state.
ori_uf <- newDenseMatrixCopy (parm_u_f lstm)
ori_ui <- newDenseMatrixCopy (parm_u_i lstm)
ori_uo <- newDenseMatrixCopy (parm_u_o lstm)
return (tmp, ori_uf, ori_ui, ori_uo)
nx -> do
tmp <- newDenseVectorCopy (tr_c trace)
tmp <<= nx_f nx :.* nx_delta_c nx
NOTE : c_t , mf_(t+1 ) , mi_(t+1 ) , mo_(t+1 ) shall not used any more
c_t <- newDenseVectorCopy (tr_c trace)
c_t <<= Apply sigma'
c_t <<= c_t :.* tr_o trace
c_t <<= c_t :.* delta_out
tmp <<= tmp :.+ c_t
mf_tp1 <- newDenseVectorCopy (nx_mf nx)
mf_tp1 <<= Apply sigma'
mf_tp1 <<= nx_ori_uf nx :#> mf_tp1
mf_tp1 <<= mf_tp1 :.* nx_delta_f nx
tmp <<= tmp :.+ mf_tp1
mi_tp1 <- newDenseVectorCopy (nx_mi nx)
mi_tp1 <<= Apply sigma'
mi_tp1 <<= nx_ori_ui nx :#> mi_tp1
mi_tp1 <<= mi_tp1 :.* nx_delta_i nx
tmp <<= tmp :.+ mi_tp1
mo_tp1 <- newDenseVectorCopy (nx_mo nx)
mo_tp1 <<= Apply sigma'
mo_tp1 <<= nx_ori_uo nx :#> mo_tp1
mo_tp1 <<= mo_tp1 :.* nx_delta_o nx
tmp <<= tmp :.+ mo_tp1
return (tmp, nx_ori_uf nx, nx_ori_ui nx, nx_ori_uo nx)
delta_ft <- newDenseVector (lstm_osize lstm)
delta_ft <<= tr_c' trace :.* delta_ct
delta_it <- newDenseVectorCopy (tr_n trace)
delta_it <<= Apply sigma
delta_it <<= delta_it :.* delta_ct
delta_ot <- newDenseVectorCopy (tr_c trace)
delta_ot <<= Apply sigma
delta_ot <<= delta_ot :.* delta_out
delta_bc <- newDenseVectorCopy (tr_n trace)
delta_bc <<= Apply sigma'
delta_bc <<= delta_bc :.* tr_i trace
delta_bc <<= delta_bc :.* delta_ct
delta_bf <- newDenseVectorCopy (tr_mf trace)
delta_bf <<= Apply sigma'
delta_bf <<= delta_bf :.* delta_ft
delta_bi <- newDenseVectorCopy (tr_mi trace)
delta_bi <<= Apply sigma'
delta_bi <<= delta_bi :.* delta_it
delta_bo <- newDenseVectorCopy (tr_mo trace)
delta_bo <<= Apply sigma'
delta_bo <<= delta_bo :.* delta_ot
delta_wc <- uncurry newDenseMatrix (size (parm_w_c lstm))
tmp <- newDenseVectorCopy (tr_n trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* tr_i trace
tmp <<= tmp :.* delta_ct
delta_wc <<+ tr_inp trace :## tmp
delta_wf <- uncurry newDenseMatrix (size (parm_w_f lstm))
denseVectorCopy tmp (tr_mf trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ft
delta_wf <<+ tr_inp trace :## tmp
delta_wi <- uncurry newDenseMatrix (size (parm_w_i lstm))
denseVectorCopy tmp (tr_mi trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_it
delta_wi <<+ tr_inp trace :## tmp
delta_wo <- uncurry newDenseMatrix (size (parm_w_o lstm))
denseVectorCopy tmp (tr_mo trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ot
delta_wo <<+ tr_inp trace :## tmp
delta_uf <- uncurry newDenseMatrix (size (parm_u_f lstm))
denseVectorCopy tmp (tr_mf trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ft
delta_uf <<+ tr_c' trace :## tmp
delta_ui <- uncurry newDenseMatrix (size (parm_u_i lstm))
denseVectorCopy tmp (tr_mi trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_it
delta_ui <<+ tr_c' trace :## tmp
delta_uo <- uncurry newDenseMatrix (size (parm_u_o lstm))
denseVectorCopy tmp (tr_mo trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ot
delta_uo <<+ tr_c' trace :## tmp
delta_inp <- newDenseVector (lstm_isize lstm)
tmp <- newDenseVectorCopy (tr_mf trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ft
delta_inp <<= parm_w_f lstm :#> tmp
denseVectorCopy tmp (tr_mi trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_it
delta_inp <<+ parm_w_i lstm :#> tmp
denseVectorCopy tmp (tr_mo trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ot
delta_inp <<+ parm_w_o lstm :#> tmp
denseVectorCopy tmp (tr_n trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* tr_i trace
tmp <<= tmp :.* delta_ct
delta_inp <<+ parm_w_c lstm :#> tmp
let rate' = fromFloat rate
delta_bc <<= Scale rate'
parm_b_c lstm <<= parm_b_c lstm :.+ delta_bc
delta_bf <<= Scale rate'
parm_b_f lstm <<= parm_b_f lstm :.+ delta_bf
delta_bi <<= Scale rate'
parm_b_i lstm <<= parm_b_i lstm :.+ delta_bi
delta_bo <<= Scale rate'
parm_b_o lstm <<= parm_b_o lstm :.+ delta_bo
delta_wc <<= Scale rate'
parm_w_c lstm <<= parm_w_c lstm :.+ delta_wc
delta_wf <<= Scale rate'
parm_w_f lstm <<= parm_w_f lstm :.+ delta_wf
delta_wi <<= Scale rate'
parm_w_i lstm <<= parm_w_i lstm :.+ delta_wi
delta_wo <<= Scale rate'
parm_w_o lstm <<= parm_w_o lstm :.+ delta_wo
delta_uf <<= Scale rate'
parm_u_f lstm <<= parm_u_f lstm :.+ delta_uf
delta_ui <<= Scale rate'
parm_u_i lstm <<= parm_u_i lstm :.+ delta_ui
delta_uo <<= Scale rate'
parm_u_o lstm <<= parm_u_o lstm :.+ delta_uo
modify $ M.insert (lstm_id lstm)
(Right $ NextJust {
nx_mf = tr_mf trace,
nx_mi = tr_mi trace,
nx_mo = tr_mo trace,
nx_f = tr_f trace,
nx_delta_c = delta_ct,
nx_delta_f = delta_ft,
nx_delta_i = delta_it,
nx_delta_o = delta_ot,
nx_ori_uf = ori_uf,
nx_ori_ui = ori_ui,
nx_ori_uo = ori_uo
})
return (lstm, delta_inp)
newtype Stream a = Stream a
deriving (Typeable, Data)
instance (Data a, Component a,
Inp a ~ VecR (Dty a),
Typeable (Dty a), Numeric (Dty a), RealType (Dty a), SIMDable (Dty a),
Run a ~ Run (LSTM (Dty a))) => Component (Stream a) where
type Dty (Stream a) = Dty a
type Run (Stream a) = IO
type Inp (Stream a) = [Inp a]
type Out (Stream a) = [Out a]
newtype Trace (Stream a) = StreamTrace [Trace a]
forwardT (Stream c) xs = do
set initial state for all LSTMs
st <- forM (collectLSTMs c) (\lstm -> do
vec <- newDenseVector (lstm_osize lstm)
return (lstm_id lstm, Left vec))
forward each input one by one , where the state is implicitly propagated .
trs <- flip evalStateT (M.fromList st) (mapM (forwardT c) xs)
return $ StreamTrace trs
output (StreamTrace trace) = map output trace
backward (Stream c) (StreamTrace trace) delta_out rate = do
set initial state for all LSTMs
st <- forM (collectLSTMs c) (\lstm ->
return (lstm_id lstm, Right NextNothing))
backward for each input one by one , and accumulate all updates
(c, delta_inp) <- flip evalStateT (M.fromList st) $ foldrM step (c, []) (zip trace delta_out)
return (Stream c, delta_inp)
where
step (tr,dout) (c,ds) = do
(c', di) <- backward c tr dout rate
return (c', di:ds)
collectLSTMs :: (Data a, Component a, Typeable (Dty a)) => a -> [LSTM (Dty a)]
collectLSTMs = everything (++) ([] `mkQ` isLSTM)
where
isLSTM a@(LLSTM{}) = [a]
sigma, sigma' :: SIMDable a => SIMDPACK a -> SIMDPACK a
sigma = tanh
sigma' = tanh'
| null | https://raw.githubusercontent.com/pierric/neural-network/406ecaf334cde9b10c9324e1f6c4b8663eae58d7/Backend-blashs/Data/NeuralNetwork/Backend/BLASHS/LSTM.hs | haskell | ----------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : portable
----------------------------------------------------------
import GHC.Float (double2Float)
^ input size
^ output size
^ the new layer
state passed forward
state passed backward
sum-type of the forward and backward state
access its own state.
so save a copy in state. | Module : Data . NeuralNetwork . Backend . BLASHS.LSTM
Description : A backend for neuralnetwork with .
Copyright : ( c ) 2016
Maintainer : < >
This module supplies a LSTM component .
# LANGUAGE UndecidableInstances #
module Data.NeuralNetwork.Backend.BLASHS.LSTM(
LSTM(..), LSTM_Env_Transformer, newLSTM, Stream(..),
) where
import Blas.Generic.Unsafe (Numeric)
import Control.Monad.State.Strict
import Data.Foldable (foldrM)
import qualified Data.Vector as V
import qualified Data.Map as M
import Data.Data
import Data.Generics
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (tanh)
import Data.NeuralNetwork
import Data.NeuralNetwork.Adapter
import Data.NeuralNetwork.Backend.BLASHS.Utils
import Data.NeuralNetwork.Backend.BLASHS.SIMD
import System.Random.MWC
import System.Random.MWC.Distributions
import Data.Vector.Storable (Storable)
import qualified Text.PrettyPrint.Free as P
type VecR p = DenseVector p
type MatR p = DenseMatrix p
type LSTMident = Int
data LSTM p = LLSTM { parm_w_f :: MatR p, parm_w_i :: MatR p, parm_w_o :: MatR p, parm_w_c :: MatR p
, parm_u_f :: MatR p, parm_u_i :: MatR p, parm_u_o :: MatR p
, parm_b_f :: VecR p, parm_b_i :: VecR p, parm_b_o :: VecR p, parm_b_c :: VecR p
, lstm_id :: LSTMident, lstm_isize, lstm_osize :: Int
}
deriving Typeable
instance Data p => Data (LSTM p) where
toConstr a = lstmConstr
gfoldl f z a = z (\i->a{lstm_id=i}) `f` (lstm_id a)
gunfold k z c = errorWithoutStackTrace "Data.Data.gunfold(LSTM)"
dataTypeOf _ = lstmDataType
lstmConstr = mkConstr lstmDataType "LSTM" ["identifier"] Prefix
lstmDataType = mkDataType "Data.NeuralNetwork.Backend.BLASHS.LSTM.LSTM" [lstmConstr]
global_LSTM_id_counter :: IORef Int
global_LSTM_id_counter = unsafePerformIO (newIORef 0)
| create a new LSTM component
newLSTM :: (Numeric p, RealType p, SIMDable p)
newLSTM m n =
withSystemRandom . asGenIO $ \gen -> do
let newW v = do raw <- newDenseVectorByGen (fromDouble <$> normal 0 v gen) (m*n)
return $ v2m m n raw
newU v = do raw <- newDenseVectorByGen (fromDouble <$> normal 0 v gen) (n*n)
return $ v2m n n raw
newB v = newDenseVectorConst n v
parm_w_f <- newW 0.01
parm_w_i <- newW 0.01
parm_w_o <- newW 0.01
parm_w_c <- newW 0.01
parm_u_f <- newU 0.01
parm_u_i <- newU 0.01
parm_u_o <- newU 0.01
parm_b_f <- newB 1.0
parm_b_i <- newB 0
parm_b_o <- newB 0
parm_b_c <- newB 0
lstm_id <- readIORef global_LSTM_id_counter
modifyIORef' global_LSTM_id_counter (+1)
return $ LLSTM {
parm_w_f = parm_w_f,
parm_w_i = parm_w_i,
parm_w_o = parm_w_o,
parm_w_c = parm_w_c,
parm_u_f = parm_u_f,
parm_u_i = parm_u_i,
parm_u_o = parm_u_o,
parm_b_f = parm_b_f,
parm_b_i = parm_b_i,
parm_b_o = parm_b_o,
parm_b_c = parm_b_c,
lstm_id = lstm_id,
lstm_isize = m,
lstm_osize = n
}
type LSTMstreamPrev p = VecR p
data LSTMstreamNext p = NextNothing
| NextJust { nx_mf, nx_mi, nx_mo, nx_f,
nx_delta_c, nx_delta_f, nx_delta_i, nx_delta_o :: VecR p,
nx_ori_uf, nx_ori_ui, nx_ori_uo :: MatR p }
type LSTMstreamInfo p = Either (LSTMstreamPrev p) (LSTMstreamNext p)
type LSTM_Env_Transformer p = StateT (M.Map LSTMident (LSTMstreamInfo p))
instance (Numeric p, RealType p, SIMDable p) => Component (LSTM p) where
The state is mapping from LSTM identifier to Info .
So when mutiple compoents are stacked , each can
type Dty (LSTM p) = p
type Run (LSTM p) = LSTM_Env_Transformer p IO
type Inp (LSTM p) = VecR p
type Out (LSTM p) = VecR p
data Trace (LSTM p) = LTrace { tr_mf, tr_mi, tr_mo, tr_n, tr_f, tr_i, tr_o, tr_c', tr_c, tr_inp, tr_out :: VecR p }
forwardT lstm x_t = do
Just (Left c_tm1) <- gets (M.lookup $ lstm_id lstm)
let osize = lstm_osize lstm
mf_t <- newDenseVector osize
mf_t <<= x_t :<# parm_w_f lstm
mf_t <<+ c_tm1 :<# parm_u_f lstm
mf_t <<= mf_t :.+ parm_b_f lstm
f_t <- newDenseVectorCopy mf_t
f_t <<= Apply sigma
mi_t <- newDenseVector osize
mi_t <<= x_t :<# parm_w_i lstm
mi_t <<+ c_tm1 :<# parm_u_i lstm
mi_t <<= mi_t :.+ parm_b_i lstm
i_t <- newDenseVectorCopy mi_t
i_t <<= Apply sigma
mo_t <- newDenseVector osize
mo_t <<= x_t :<# parm_w_o lstm
mo_t <<+ c_tm1 :<# parm_u_o lstm
mo_t <<= mo_t :.+ parm_b_o lstm
o_t <- newDenseVectorCopy mo_t
o_t <<= Apply sigma
n_t <- newDenseVector osize
n_t <<= x_t :<# parm_w_c lstm
n_t <<= n_t :.+ parm_b_c lstm
c_t <- newDenseVector osize
c_t <<= c_tm1 :.* f_t
tmp <- newDenseVectorCopy n_t
tmp <<= Apply sigma
tmp <<= i_t :.* tmp
c_t <<= c_t :.+ tmp
denseVectorCopy tmp c_t
tmp <<= Apply sigma
tmp <<= tmp :.* o_t
modify $ M.insert (lstm_id lstm) (Left c_t)
let trace = LTrace { tr_mf = mf_t, tr_mi = mi_t, tr_mo = mo_t
, tr_n = n_t
, tr_f = f_t, tr_i = i_t, tr_o = o_t
, tr_c' = c_tm1, tr_c = c_t
, tr_inp = x_t, tr_out = tmp }
return $ trace
output = tr_out
backward lstm trace !delta_out rate = do
Just (Right upward) <- gets (M.lookup $ lstm_id lstm)
(delta_ct, ori_uf, ori_ui, ori_uo) <- case upward of
NextNothing -> do
tmp <- newDenseVectorCopy (tr_c trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* tr_o trace
tmp <<= tmp :.* delta_out
the original Ui , Uf , Uo are used in calc delta_ct ,
ori_uf <- newDenseMatrixCopy (parm_u_f lstm)
ori_ui <- newDenseMatrixCopy (parm_u_i lstm)
ori_uo <- newDenseMatrixCopy (parm_u_o lstm)
return (tmp, ori_uf, ori_ui, ori_uo)
nx -> do
tmp <- newDenseVectorCopy (tr_c trace)
tmp <<= nx_f nx :.* nx_delta_c nx
NOTE : c_t , mf_(t+1 ) , mi_(t+1 ) , mo_(t+1 ) shall not used any more
c_t <- newDenseVectorCopy (tr_c trace)
c_t <<= Apply sigma'
c_t <<= c_t :.* tr_o trace
c_t <<= c_t :.* delta_out
tmp <<= tmp :.+ c_t
mf_tp1 <- newDenseVectorCopy (nx_mf nx)
mf_tp1 <<= Apply sigma'
mf_tp1 <<= nx_ori_uf nx :#> mf_tp1
mf_tp1 <<= mf_tp1 :.* nx_delta_f nx
tmp <<= tmp :.+ mf_tp1
mi_tp1 <- newDenseVectorCopy (nx_mi nx)
mi_tp1 <<= Apply sigma'
mi_tp1 <<= nx_ori_ui nx :#> mi_tp1
mi_tp1 <<= mi_tp1 :.* nx_delta_i nx
tmp <<= tmp :.+ mi_tp1
mo_tp1 <- newDenseVectorCopy (nx_mo nx)
mo_tp1 <<= Apply sigma'
mo_tp1 <<= nx_ori_uo nx :#> mo_tp1
mo_tp1 <<= mo_tp1 :.* nx_delta_o nx
tmp <<= tmp :.+ mo_tp1
return (tmp, nx_ori_uf nx, nx_ori_ui nx, nx_ori_uo nx)
delta_ft <- newDenseVector (lstm_osize lstm)
delta_ft <<= tr_c' trace :.* delta_ct
delta_it <- newDenseVectorCopy (tr_n trace)
delta_it <<= Apply sigma
delta_it <<= delta_it :.* delta_ct
delta_ot <- newDenseVectorCopy (tr_c trace)
delta_ot <<= Apply sigma
delta_ot <<= delta_ot :.* delta_out
delta_bc <- newDenseVectorCopy (tr_n trace)
delta_bc <<= Apply sigma'
delta_bc <<= delta_bc :.* tr_i trace
delta_bc <<= delta_bc :.* delta_ct
delta_bf <- newDenseVectorCopy (tr_mf trace)
delta_bf <<= Apply sigma'
delta_bf <<= delta_bf :.* delta_ft
delta_bi <- newDenseVectorCopy (tr_mi trace)
delta_bi <<= Apply sigma'
delta_bi <<= delta_bi :.* delta_it
delta_bo <- newDenseVectorCopy (tr_mo trace)
delta_bo <<= Apply sigma'
delta_bo <<= delta_bo :.* delta_ot
delta_wc <- uncurry newDenseMatrix (size (parm_w_c lstm))
tmp <- newDenseVectorCopy (tr_n trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* tr_i trace
tmp <<= tmp :.* delta_ct
delta_wc <<+ tr_inp trace :## tmp
delta_wf <- uncurry newDenseMatrix (size (parm_w_f lstm))
denseVectorCopy tmp (tr_mf trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ft
delta_wf <<+ tr_inp trace :## tmp
delta_wi <- uncurry newDenseMatrix (size (parm_w_i lstm))
denseVectorCopy tmp (tr_mi trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_it
delta_wi <<+ tr_inp trace :## tmp
delta_wo <- uncurry newDenseMatrix (size (parm_w_o lstm))
denseVectorCopy tmp (tr_mo trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ot
delta_wo <<+ tr_inp trace :## tmp
delta_uf <- uncurry newDenseMatrix (size (parm_u_f lstm))
denseVectorCopy tmp (tr_mf trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ft
delta_uf <<+ tr_c' trace :## tmp
delta_ui <- uncurry newDenseMatrix (size (parm_u_i lstm))
denseVectorCopy tmp (tr_mi trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_it
delta_ui <<+ tr_c' trace :## tmp
delta_uo <- uncurry newDenseMatrix (size (parm_u_o lstm))
denseVectorCopy tmp (tr_mo trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ot
delta_uo <<+ tr_c' trace :## tmp
delta_inp <- newDenseVector (lstm_isize lstm)
tmp <- newDenseVectorCopy (tr_mf trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ft
delta_inp <<= parm_w_f lstm :#> tmp
denseVectorCopy tmp (tr_mi trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_it
delta_inp <<+ parm_w_i lstm :#> tmp
denseVectorCopy tmp (tr_mo trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* delta_ot
delta_inp <<+ parm_w_o lstm :#> tmp
denseVectorCopy tmp (tr_n trace)
tmp <<= Apply sigma'
tmp <<= tmp :.* tr_i trace
tmp <<= tmp :.* delta_ct
delta_inp <<+ parm_w_c lstm :#> tmp
let rate' = fromFloat rate
delta_bc <<= Scale rate'
parm_b_c lstm <<= parm_b_c lstm :.+ delta_bc
delta_bf <<= Scale rate'
parm_b_f lstm <<= parm_b_f lstm :.+ delta_bf
delta_bi <<= Scale rate'
parm_b_i lstm <<= parm_b_i lstm :.+ delta_bi
delta_bo <<= Scale rate'
parm_b_o lstm <<= parm_b_o lstm :.+ delta_bo
delta_wc <<= Scale rate'
parm_w_c lstm <<= parm_w_c lstm :.+ delta_wc
delta_wf <<= Scale rate'
parm_w_f lstm <<= parm_w_f lstm :.+ delta_wf
delta_wi <<= Scale rate'
parm_w_i lstm <<= parm_w_i lstm :.+ delta_wi
delta_wo <<= Scale rate'
parm_w_o lstm <<= parm_w_o lstm :.+ delta_wo
delta_uf <<= Scale rate'
parm_u_f lstm <<= parm_u_f lstm :.+ delta_uf
delta_ui <<= Scale rate'
parm_u_i lstm <<= parm_u_i lstm :.+ delta_ui
delta_uo <<= Scale rate'
parm_u_o lstm <<= parm_u_o lstm :.+ delta_uo
modify $ M.insert (lstm_id lstm)
(Right $ NextJust {
nx_mf = tr_mf trace,
nx_mi = tr_mi trace,
nx_mo = tr_mo trace,
nx_f = tr_f trace,
nx_delta_c = delta_ct,
nx_delta_f = delta_ft,
nx_delta_i = delta_it,
nx_delta_o = delta_ot,
nx_ori_uf = ori_uf,
nx_ori_ui = ori_ui,
nx_ori_uo = ori_uo
})
return (lstm, delta_inp)
newtype Stream a = Stream a
deriving (Typeable, Data)
instance (Data a, Component a,
Inp a ~ VecR (Dty a),
Typeable (Dty a), Numeric (Dty a), RealType (Dty a), SIMDable (Dty a),
Run a ~ Run (LSTM (Dty a))) => Component (Stream a) where
type Dty (Stream a) = Dty a
type Run (Stream a) = IO
type Inp (Stream a) = [Inp a]
type Out (Stream a) = [Out a]
newtype Trace (Stream a) = StreamTrace [Trace a]
forwardT (Stream c) xs = do
set initial state for all LSTMs
st <- forM (collectLSTMs c) (\lstm -> do
vec <- newDenseVector (lstm_osize lstm)
return (lstm_id lstm, Left vec))
forward each input one by one , where the state is implicitly propagated .
trs <- flip evalStateT (M.fromList st) (mapM (forwardT c) xs)
return $ StreamTrace trs
output (StreamTrace trace) = map output trace
backward (Stream c) (StreamTrace trace) delta_out rate = do
set initial state for all LSTMs
st <- forM (collectLSTMs c) (\lstm ->
return (lstm_id lstm, Right NextNothing))
backward for each input one by one , and accumulate all updates
(c, delta_inp) <- flip evalStateT (M.fromList st) $ foldrM step (c, []) (zip trace delta_out)
return (Stream c, delta_inp)
where
step (tr,dout) (c,ds) = do
(c', di) <- backward c tr dout rate
return (c', di:ds)
collectLSTMs :: (Data a, Component a, Typeable (Dty a)) => a -> [LSTM (Dty a)]
collectLSTMs = everything (++) ([] `mkQ` isLSTM)
where
isLSTM a@(LLSTM{}) = [a]
sigma, sigma' :: SIMDable a => SIMDPACK a -> SIMDPACK a
sigma = tanh
sigma' = tanh'
|
ce2dda45d44c03516ec1c783a63df0aa00efe967058737b7d712223458ab5a22 | huangjs/cl | zhemm.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(let* ((one (f2cl-lib:cmplx 1.0 0.0)) (zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) one)
(type (f2cl-lib:complex16) zero)
(ignorable one zero))
(defun zhemm (side uplo m n alpha a lda b ldb$ beta c ldc)
(declare (type (array f2cl-lib:complex16 (*)) c b a)
(type (f2cl-lib:complex16) beta alpha)
(type (f2cl-lib:integer4) ldc ldb$ lda n m)
(type (simple-array character (*)) uplo side))
(f2cl-lib:with-multi-array-data
((side character side-%data% side-%offset%)
(uplo character uplo-%data% uplo-%offset%)
(a f2cl-lib:complex16 a-%data% a-%offset%)
(b f2cl-lib:complex16 b-%data% b-%offset%)
(c f2cl-lib:complex16 c-%data% c-%offset%))
(prog ((temp1 #C(0.0 0.0)) (temp2 #C(0.0 0.0)) (i 0) (info 0) (j 0) (k 0)
(nrowa 0) (upper nil))
(declare (type (f2cl-lib:complex16) temp1 temp2)
(type (f2cl-lib:integer4) i info j k nrowa)
(type f2cl-lib:logical upper))
(cond
((lsame side "L")
(setf nrowa m))
(t
(setf nrowa n)))
(setf upper (lsame uplo "U"))
(setf info 0)
(cond
((and (not (lsame side "L")) (not (lsame side "R")))
(setf info 1))
((and (not upper) (not (lsame uplo "L")))
(setf info 2))
((< m 0)
(setf info 3))
((< n 0)
(setf info 4))
((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 nrowa)))
(setf info 7))
((< ldb$ (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info 9))
((< ldc (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info 12)))
(cond
((/= info 0)
(xerbla "ZHEMM " info)
(go end_label)))
(if (or (= m 0) (= n 0) (and (= alpha zero) (= beta one)))
(go end_label))
(cond
((= alpha zero)
(cond
((= beta zero)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
zero)
label10))
label20)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)))
label30))
label40))))
(go end_label)))
(cond
((lsame side "L")
(cond
(upper
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%)))
(setf temp2 zero)
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add i
(f2cl-lib:int-sub
1)))
nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref b-%data%
(k j)
((1 ldb$) (1 *))
b-%offset%)
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%)))))
label50))
(cond
((= beta zero)
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2))))
(t
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%))
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))))
label60))
label70)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i m (f2cl-lib:int-add i (f2cl-lib:int-sub 1)))
((> i 1) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%)))
(setf temp2 zero)
(f2cl-lib:fdo (k (f2cl-lib:int-add i 1)
(f2cl-lib:int-add k 1))
((> k m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref b-%data%
(k j)
((1 ldb$) (1 *))
b-%offset%)
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%)))))
label80))
(cond
((= beta zero)
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2))))
(t
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%))
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))))
label90))
label100)))))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(j j)
((1 lda) (1 *))
a-%offset%))))
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%)))
label110)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%))
(* temp1
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%))))
label120))))
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(cond
(upper
(setf temp1
(* alpha
(f2cl-lib:fref a-%data%
(k j)
((1 lda) (1 *))
a-%offset%))))
(t
(setf temp1
(* alpha
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(j k)
((1 lda) (1 *))
a-%offset%))))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref b-%data%
(i k)
((1 ldb$) (1 *))
b-%offset%))))
label130))
label140))
(f2cl-lib:fdo (k (f2cl-lib:int-add j 1) (f2cl-lib:int-add k 1))
((> k n) nil)
(tagbody
(cond
(upper
(setf temp1
(* alpha
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(j k)
((1 lda) (1 *))
a-%offset%)))))
(t
(setf temp1
(* alpha
(f2cl-lib:fref a-%data%
(k j)
((1 lda) (1 *))
a-%offset%)))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref b-%data%
(i k)
((1 ldb$) (1 *))
b-%offset%))))
label150))
label160))
label170))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zhemm fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-array character (1))
(simple-array character (1))
(fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/share/lapack/blas/zhemm.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
(in-package :blas)
(let* ((one (f2cl-lib:cmplx 1.0 0.0)) (zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) one)
(type (f2cl-lib:complex16) zero)
(ignorable one zero))
(defun zhemm (side uplo m n alpha a lda b ldb$ beta c ldc)
(declare (type (array f2cl-lib:complex16 (*)) c b a)
(type (f2cl-lib:complex16) beta alpha)
(type (f2cl-lib:integer4) ldc ldb$ lda n m)
(type (simple-array character (*)) uplo side))
(f2cl-lib:with-multi-array-data
((side character side-%data% side-%offset%)
(uplo character uplo-%data% uplo-%offset%)
(a f2cl-lib:complex16 a-%data% a-%offset%)
(b f2cl-lib:complex16 b-%data% b-%offset%)
(c f2cl-lib:complex16 c-%data% c-%offset%))
(prog ((temp1 #C(0.0 0.0)) (temp2 #C(0.0 0.0)) (i 0) (info 0) (j 0) (k 0)
(nrowa 0) (upper nil))
(declare (type (f2cl-lib:complex16) temp1 temp2)
(type (f2cl-lib:integer4) i info j k nrowa)
(type f2cl-lib:logical upper))
(cond
((lsame side "L")
(setf nrowa m))
(t
(setf nrowa n)))
(setf upper (lsame uplo "U"))
(setf info 0)
(cond
((and (not (lsame side "L")) (not (lsame side "R")))
(setf info 1))
((and (not upper) (not (lsame uplo "L")))
(setf info 2))
((< m 0)
(setf info 3))
((< n 0)
(setf info 4))
((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 nrowa)))
(setf info 7))
((< ldb$ (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info 9))
((< ldc (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info 12)))
(cond
((/= info 0)
(xerbla "ZHEMM " info)
(go end_label)))
(if (or (= m 0) (= n 0) (and (= alpha zero) (= beta one)))
(go end_label))
(cond
((= alpha zero)
(cond
((= beta zero)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
zero)
label10))
label20)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)))
label30))
label40))))
(go end_label)))
(cond
((lsame side "L")
(cond
(upper
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%)))
(setf temp2 zero)
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add i
(f2cl-lib:int-sub
1)))
nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref b-%data%
(k j)
((1 ldb$) (1 *))
b-%offset%)
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%)))))
label50))
(cond
((= beta zero)
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2))))
(t
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%))
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))))
label60))
label70)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i m (f2cl-lib:int-add i (f2cl-lib:int-sub 1)))
((> i 1) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%)))
(setf temp2 zero)
(f2cl-lib:fdo (k (f2cl-lib:int-add i 1)
(f2cl-lib:int-add k 1))
((> k m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(k j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:fref b-%data%
(k j)
((1 ldb$) (1 *))
b-%offset%)
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(k i)
((1 lda) (1 *))
a-%offset%)))))
label80))
(cond
((= beta zero)
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2))))
(t
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%))
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(i i)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))))
label90))
label100)))))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(j j)
((1 lda) (1 *))
a-%offset%))))
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%)))
label110)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(* beta
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%))
(* temp1
(f2cl-lib:fref b-%data%
(i j)
((1 ldb$) (1 *))
b-%offset%))))
label120))))
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(cond
(upper
(setf temp1
(* alpha
(f2cl-lib:fref a-%data%
(k j)
((1 lda) (1 *))
a-%offset%))))
(t
(setf temp1
(* alpha
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(j k)
((1 lda) (1 *))
a-%offset%))))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref b-%data%
(i k)
((1 ldb$) (1 *))
b-%offset%))))
label130))
label140))
(f2cl-lib:fdo (k (f2cl-lib:int-add j 1) (f2cl-lib:int-add k 1))
((> k n) nil)
(tagbody
(cond
(upper
(setf temp1
(* alpha
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(j k)
((1 lda) (1 *))
a-%offset%)))))
(t
(setf temp1
(* alpha
(f2cl-lib:fref a-%data%
(k j)
((1 lda) (1 *))
a-%offset%)))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(+
(f2cl-lib:fref c-%data%
(i j)
((1 ldc) (1 *))
c-%offset%)
(* temp1
(f2cl-lib:fref b-%data%
(i k)
((1 ldb$) (1 *))
b-%offset%))))
label150))
label160))
label170))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zhemm fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-array character (1))
(simple-array character (1))
(fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
|
a8314748ccbd01d5cbac6dcd3fe273df9bb02844599ba7dde5a05a304b84d64a | na4zagin3/satyrographos | command_satysfi__with_project_env.ml | module StdList = List
open Satyrographos_testlib
open Core
open Shexp_process
let satyristes =
{|
(version "0.0.2")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf")
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
(file "doc/grcnum.md" "README.md")
(fontDir "font")
(packageDir "src")
))
(opam "satysfi-grcnum.opam")
(dependencies ((fonts-theano ())))
(compatibility ((satyrographos 0.0.1))))
(libraryDoc
(name "grcnum-doc")
(version "0.2")
(build
((satysfi "doc-grcnum.saty" "-o" "doc-grcnum-ja.pdf")))
(sources
((doc "doc-grcnum-ja.pdf" "./doc-grcnum-ja.pdf")))
(opam "satysfi-grcnum-doc.opam")
(dependencies ((grcnum ())
(fonts-theano ()))))
|}
let () =
let main ~outf ~temp_dir =
let open Shexp_process.Infix in
let log_file = FilePath.concat temp_dir "exec.log" in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "doc-example.saty") (echo "@@doc-example.saty@@")
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let bin_dir = FilePath.concat temp_dir "bin" in
let system_font_prefix = None in
let autogen_libraries = [] in
let libraries = Some [] in
let verbose = true in
let project_env = Some Satyrographos.Environment.{
buildscript_path = FilePath.concat pkg_dir "Satyristes";
satysfi_runtime_dir = FilePath.concat pkg_dir "_build/satysfi";
}
in
let cmd =
PrepareBin.prepare_bin bin_dir log_file
>> prepare_pkg
>> prepare_dist
>>| TestLib.read_env ~opam_reg ~dist_library_dir:empty_dist
>>= fun env ->
Satyrographos_command.RunSatysfi.satysfi_command
~outf
~system_font_prefix
~autogen_libraries
~libraries
~verbose
~project_env
~env
[FilePath.concat pkg_dir "doc-example.saty"; "-o"; FilePath.concat pkg_dir "doc-example.pdf";]
>>= (fun exit_code ->
if exit_code <> 0
then sprintf "Non zero exit code: %d" exit_code |> echo
else return ())
>> TestLib.echo_line
>> stdin_from log_file (iter_lines echo)
>> TestLib.echo_line
in
TestLib.with_bin_dir bin_dir cmd
in
let open Shexp_process.Infix in
eval (
Shexp_process.with_temp_dir ~prefix:"Satyrographos" ~suffix:"satysfi" (fun temp_dir ->
TestLib.with_formatter_map (fun outf ->
main ~outf ~temp_dir
)
)
|- TestLib.censor_tempdirs
)
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/9dbccf05138510c977a67c859bbbb48755470c7f/test/testcases/command_satysfi__with_project_env.ml | ocaml | module StdList = List
open Satyrographos_testlib
open Core
open Shexp_process
let satyristes =
{|
(version "0.0.2")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf")
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
(file "doc/grcnum.md" "README.md")
(fontDir "font")
(packageDir "src")
))
(opam "satysfi-grcnum.opam")
(dependencies ((fonts-theano ())))
(compatibility ((satyrographos 0.0.1))))
(libraryDoc
(name "grcnum-doc")
(version "0.2")
(build
((satysfi "doc-grcnum.saty" "-o" "doc-grcnum-ja.pdf")))
(sources
((doc "doc-grcnum-ja.pdf" "./doc-grcnum-ja.pdf")))
(opam "satysfi-grcnum-doc.opam")
(dependencies ((grcnum ())
(fonts-theano ()))))
|}
let () =
let main ~outf ~temp_dir =
let open Shexp_process.Infix in
let log_file = FilePath.concat temp_dir "exec.log" in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "doc-example.saty") (echo "@@doc-example.saty@@")
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let bin_dir = FilePath.concat temp_dir "bin" in
let system_font_prefix = None in
let autogen_libraries = [] in
let libraries = Some [] in
let verbose = true in
let project_env = Some Satyrographos.Environment.{
buildscript_path = FilePath.concat pkg_dir "Satyristes";
satysfi_runtime_dir = FilePath.concat pkg_dir "_build/satysfi";
}
in
let cmd =
PrepareBin.prepare_bin bin_dir log_file
>> prepare_pkg
>> prepare_dist
>>| TestLib.read_env ~opam_reg ~dist_library_dir:empty_dist
>>= fun env ->
Satyrographos_command.RunSatysfi.satysfi_command
~outf
~system_font_prefix
~autogen_libraries
~libraries
~verbose
~project_env
~env
[FilePath.concat pkg_dir "doc-example.saty"; "-o"; FilePath.concat pkg_dir "doc-example.pdf";]
>>= (fun exit_code ->
if exit_code <> 0
then sprintf "Non zero exit code: %d" exit_code |> echo
else return ())
>> TestLib.echo_line
>> stdin_from log_file (iter_lines echo)
>> TestLib.echo_line
in
TestLib.with_bin_dir bin_dir cmd
in
let open Shexp_process.Infix in
eval (
Shexp_process.with_temp_dir ~prefix:"Satyrographos" ~suffix:"satysfi" (fun temp_dir ->
TestLib.with_formatter_map (fun outf ->
main ~outf ~temp_dir
)
)
|- TestLib.censor_tempdirs
)
| |
a4434dc5f9134c533eafd5868bffa28e57491cefb3c816828bbf0be8bce859aa | ParaPhrase/skel | sk_map_combiner.erl | %%%----------------------------------------------------------------------------
@author < >
2012 University of St Andrews ( See LICENCE )
@headerfile " skel.hrl "
%%%
%%% @doc This module contains the Map skeleton combiner logic.
%%%
%%% The Map skeleton is a parallel map. The skeleton applies a given function
%%% to the elements within one or more lists.
%%%
%%% The combiner receives each partite element of each input following the
%%% original element's application to the given workflow. This module collects
%%% each resulting partite element of all inputs and restores the structure of
%%% the original inputs.
%%%
Similar to { @link } , this module supports both the
%%% automatic creation of workers, and the ability to define the number used.
%%%
%%% @end
%%%----------------------------------------------------------------------------
-module(sk_map_combiner).
-export([start/1, start/2]).
-include("skel.hrl").
-spec start(pid()) -> 'eos'.
%% @doc Initialises the recomposition process for when the number of workers
%% is <em>not</em> set by the developer.
%%
%% Recomposition consists of rebuilding
%% a list from its elements, in the correct order. For each set of elements, a
{ @link data_message ( ) } is produced and sent to the process given by
` NextPid ' .
start(NextPid) ->
sk_tracer:t(75, self(), {?MODULE, start}, [{next_pid, NextPid}]),
loop(auto, 0, 0, dict:new(), recomp_with(), NextPid).
-spec start(pid(), pos_integer()) -> 'eos'.
%% @doc Initialises the recomposition process for when the number of workers
%% <em>is</em> set by the developer.
%%
%% Recomposition similarly consists of rebuilding a list from its elements, in
the correct order . For each set of elements a { @link data_message ( ) } is
produced and sent to the process given by ` NextPid ' .
start(NextPid, NWorkers) ->
sk_tracer:t(75, self(), {?MODULE, start}, [{next_pid, NextPid}]),
loop(man, NWorkers, 0, dict:new(), recomp_with(), NextPid).
-spec loop(atom(), non_neg_integer(), non_neg_integer(), dict:dict(), data_recomp_fun(), pid()) -> 'eos'.
%% @doc Recursively receives and stores messages until groups of said messages
%% may be recomposed and sent. Serves to stop all processes once all inputs
%% have been processed.
%%
The first clause is used when the number of workers is left unspecified by
the developer . The second , where it is specified .
loop(auto, TotWorkers, DeadWorkers, Dict, DataCombinerFun, NextPid) ->
receive
{data, _, _} = PartitionMessage ->
{{decomp, Ref, Idx, NPartitions}, PartitionMessage1} = sk_data:pop(PartitionMessage),
Dict1 = store(Ref, Idx, NPartitions, PartitionMessage1, Dict),
Dict2 = combine_and_forward(Ref, Dict1, DataCombinerFun, NextPid),
TotWorkers1 = new_total_workers(TotWorkers, NPartitions),
loop(auto, TotWorkers1, DeadWorkers, Dict2, DataCombinerFun, NextPid);
{system, eos} when DeadWorkers+1 >= TotWorkers ->
sk_tracer:t(75, self(), NextPid, {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
NextPid ! {system, eos},
eos;
{system, eos} ->
sk_tracer:t(85, self(), {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
loop(auto, TotWorkers, DeadWorkers+1, Dict, DataCombinerFun, NextPid)
end;
loop(man, TotWorkers, DeadWorkers, Dict, DataCombinerFun, NextPid) ->
receive
{data, _, _} = PartitionMessage ->
{{decomp, Ref, Idx, NPartitions}, PartitionMessage1} = sk_data:pop(PartitionMessage),
Dict1 = store(Ref, Idx, NPartitions, PartitionMessage1, Dict),
Dict2 = combine_and_forward(Ref, Dict1, DataCombinerFun, NextPid),
loop(man, TotWorkers, DeadWorkers, Dict2, DataCombinerFun, NextPid);
{system, eos} when DeadWorkers+1 >= TotWorkers ->
sk_tracer:t(75, self(), NextPid, {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
NextPid ! {system, eos},
eos;
{system, eos} ->
sk_tracer:t(85, self(), {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
loop(man, TotWorkers, DeadWorkers+1, Dict, DataCombinerFun, NextPid)
end.
-spec recomp_with() -> data_recomp_fun().
%% @doc Provides the recomposition function and means to merge many inputs
%% into one. This appends each individual `DataMessage', in order, to a list.
This list is wrapped in a single { @link data_message ( ) } .
recomp_with() ->
fun([{data, _, Ids}|_] = DataMessages) ->
{data, [Value || {_, Value, _} <- DataMessages], Ids}
end.
-spec new_total_workers(non_neg_integer(), non_neg_integer()) -> non_neg_integer().
%% @doc Returns the total number of workers used by the skeleton. Employed
%% when the number of workers is automatically determined.
new_total_workers(TotWorkers, NPartitions) when NPartitions > TotWorkers ->
NPartitions;
new_total_workers(TotWorkers, _NPartitions) ->
TotWorkers.
-spec store(reference(), pos_integer(), pos_integer(), data_message(), dict:dict()) -> dict:dict().
%% @doc Stores in a dictionary the total number of partitions, `NPartitions',
%% expected; all messages heretofore received; and the number said received
%% messages, for the original input under the reference given by `Ref'. The
%% updated dictionary, using `Dict' as a base, is returned.
store(Ref, Idx, NPartitions, PartitionMessage, Dict) ->
Dict1 = dict:store({Ref, expecting}, NPartitions, Dict),
Dict2 = dict:store({Ref, Idx}, PartitionMessage, Dict1),
dict:update_counter({Ref, received}, 1, Dict2).
-spec combine_and_forward(reference(), dict:dict(), data_recomp_fun(), pid()) -> dict:dict().
%% @doc Attempts to find the reference as given by `Ref' in the specified
%% dictionary.
%%
%% If said reference is found, {@link combine_and_forward/5} is used to
%% attempt a recomposition of the partite elements stored as messages in
%% `Dict'.
combine_and_forward(Ref, Dict, DataCombinerFun, NextPid) ->
case dict:find({Ref, expecting}, Dict) of
error -> Dict;
{ok, NPartitions} -> combine_and_forward(Ref, Dict, NPartitions, DataCombinerFun, NextPid)
end.
-spec combine_and_forward(reference(), dict:dict(), pos_integer(), data_recomp_fun(), pid()) -> dict:dict().
%% @doc Inner-function for {@link combine_and_forward/4} that attempts to
%% restore a decomposed list from parts in a dictionary `Dict', whose
%% reference is given by `Ref'.
%%
%% If all decomposed elements can be found, `combine_and_forward/5' retrieves
%% them and applies the recomposition function under `DataCombinerFun'. The
resulting data message is sent to the process represented by ` NextPid ' ,
%% those messages deleted from the dictionary, and the dictionary returned.
combine_and_forward(Ref, Dict, NPartitions, DataCombinerFun, NextPid) ->
RcvdPartitions = dict:fetch({Ref, received}, Dict),
if
RcvdPartitions == NPartitions ->
PartitionMessages = fetch_partitions(Ref, NPartitions, Dict, []),
DataMessage = apply(DataCombinerFun, [PartitionMessages]),
sk_tracer:t(50, self(), NextPid, {?MODULE, data}, [{ref, Ref}, {output, DataMessage}, {partitions, PartitionMessages}]),
NextPid ! DataMessage,
purge_partitions(Ref, NPartitions, Dict);
true ->
Dict
end.
-spec fetch_partitions(reference(), non_neg_integer(), dict:dict(), [any()]) -> [any()].
%% @doc Returns a list of all data messages in the given dictionary, whose
%% reference is `Ref'.
fetch_partitions(_Ref, 0, _Dict, Acc) ->
Acc;
fetch_partitions(Ref, NPartitions, Dict, Acc) ->
{ok, Piece} = dict:find({Ref, NPartitions}, Dict),
fetch_partitions(Ref, NPartitions-1, Dict, [Piece|Acc]).
-spec purge_partitions(reference(), non_neg_integer(), dict:dict()) -> dict:dict().
%% @doc Recursively removes all entries with `Ref' as their reference in the
%% given dictionary.
purge_partitions(Ref, 0, Dict) ->
Dict1 = dict:erase({Ref, expecting}, Dict),
Dict2 = dict:erase({Ref, received}, Dict1),
Dict2;
purge_partitions(Ref, NPartitions, Dict) ->
Dict1 = dict:erase({Ref, NPartitions}, Dict),
purge_partitions(Ref, NPartitions-1, Dict1).
| null | https://raw.githubusercontent.com/ParaPhrase/skel/bf55de94e64354592ea335f4375f4b40607baf43/src/sk_map_combiner.erl | erlang | ----------------------------------------------------------------------------
@doc This module contains the Map skeleton combiner logic.
The Map skeleton is a parallel map. The skeleton applies a given function
to the elements within one or more lists.
The combiner receives each partite element of each input following the
original element's application to the given workflow. This module collects
each resulting partite element of all inputs and restores the structure of
the original inputs.
automatic creation of workers, and the ability to define the number used.
@end
----------------------------------------------------------------------------
@doc Initialises the recomposition process for when the number of workers
is <em>not</em> set by the developer.
Recomposition consists of rebuilding
a list from its elements, in the correct order. For each set of elements, a
@doc Initialises the recomposition process for when the number of workers
<em>is</em> set by the developer.
Recomposition similarly consists of rebuilding a list from its elements, in
@doc Recursively receives and stores messages until groups of said messages
may be recomposed and sent. Serves to stop all processes once all inputs
have been processed.
@doc Provides the recomposition function and means to merge many inputs
into one. This appends each individual `DataMessage', in order, to a list.
@doc Returns the total number of workers used by the skeleton. Employed
when the number of workers is automatically determined.
@doc Stores in a dictionary the total number of partitions, `NPartitions',
expected; all messages heretofore received; and the number said received
messages, for the original input under the reference given by `Ref'. The
updated dictionary, using `Dict' as a base, is returned.
@doc Attempts to find the reference as given by `Ref' in the specified
dictionary.
If said reference is found, {@link combine_and_forward/5} is used to
attempt a recomposition of the partite elements stored as messages in
`Dict'.
@doc Inner-function for {@link combine_and_forward/4} that attempts to
restore a decomposed list from parts in a dictionary `Dict', whose
reference is given by `Ref'.
If all decomposed elements can be found, `combine_and_forward/5' retrieves
them and applies the recomposition function under `DataCombinerFun'. The
those messages deleted from the dictionary, and the dictionary returned.
@doc Returns a list of all data messages in the given dictionary, whose
reference is `Ref'.
@doc Recursively removes all entries with `Ref' as their reference in the
given dictionary. | @author < >
2012 University of St Andrews ( See LICENCE )
@headerfile " skel.hrl "
Similar to { @link } , this module supports both the
-module(sk_map_combiner).
-export([start/1, start/2]).
-include("skel.hrl").
-spec start(pid()) -> 'eos'.
{ @link data_message ( ) } is produced and sent to the process given by
` NextPid ' .
start(NextPid) ->
sk_tracer:t(75, self(), {?MODULE, start}, [{next_pid, NextPid}]),
loop(auto, 0, 0, dict:new(), recomp_with(), NextPid).
-spec start(pid(), pos_integer()) -> 'eos'.
the correct order . For each set of elements a { @link data_message ( ) } is
produced and sent to the process given by ` NextPid ' .
start(NextPid, NWorkers) ->
sk_tracer:t(75, self(), {?MODULE, start}, [{next_pid, NextPid}]),
loop(man, NWorkers, 0, dict:new(), recomp_with(), NextPid).
-spec loop(atom(), non_neg_integer(), non_neg_integer(), dict:dict(), data_recomp_fun(), pid()) -> 'eos'.
The first clause is used when the number of workers is left unspecified by
the developer . The second , where it is specified .
loop(auto, TotWorkers, DeadWorkers, Dict, DataCombinerFun, NextPid) ->
receive
{data, _, _} = PartitionMessage ->
{{decomp, Ref, Idx, NPartitions}, PartitionMessage1} = sk_data:pop(PartitionMessage),
Dict1 = store(Ref, Idx, NPartitions, PartitionMessage1, Dict),
Dict2 = combine_and_forward(Ref, Dict1, DataCombinerFun, NextPid),
TotWorkers1 = new_total_workers(TotWorkers, NPartitions),
loop(auto, TotWorkers1, DeadWorkers, Dict2, DataCombinerFun, NextPid);
{system, eos} when DeadWorkers+1 >= TotWorkers ->
sk_tracer:t(75, self(), NextPid, {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
NextPid ! {system, eos},
eos;
{system, eos} ->
sk_tracer:t(85, self(), {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
loop(auto, TotWorkers, DeadWorkers+1, Dict, DataCombinerFun, NextPid)
end;
loop(man, TotWorkers, DeadWorkers, Dict, DataCombinerFun, NextPid) ->
receive
{data, _, _} = PartitionMessage ->
{{decomp, Ref, Idx, NPartitions}, PartitionMessage1} = sk_data:pop(PartitionMessage),
Dict1 = store(Ref, Idx, NPartitions, PartitionMessage1, Dict),
Dict2 = combine_and_forward(Ref, Dict1, DataCombinerFun, NextPid),
loop(man, TotWorkers, DeadWorkers, Dict2, DataCombinerFun, NextPid);
{system, eos} when DeadWorkers+1 >= TotWorkers ->
sk_tracer:t(75, self(), NextPid, {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
NextPid ! {system, eos},
eos;
{system, eos} ->
sk_tracer:t(85, self(), {?MODULE, system}, [{msg, eos}, {total, TotWorkers}, {dead, DeadWorkers+1}]),
loop(man, TotWorkers, DeadWorkers+1, Dict, DataCombinerFun, NextPid)
end.
-spec recomp_with() -> data_recomp_fun().
This list is wrapped in a single { @link data_message ( ) } .
recomp_with() ->
fun([{data, _, Ids}|_] = DataMessages) ->
{data, [Value || {_, Value, _} <- DataMessages], Ids}
end.
-spec new_total_workers(non_neg_integer(), non_neg_integer()) -> non_neg_integer().
new_total_workers(TotWorkers, NPartitions) when NPartitions > TotWorkers ->
NPartitions;
new_total_workers(TotWorkers, _NPartitions) ->
TotWorkers.
-spec store(reference(), pos_integer(), pos_integer(), data_message(), dict:dict()) -> dict:dict().
store(Ref, Idx, NPartitions, PartitionMessage, Dict) ->
Dict1 = dict:store({Ref, expecting}, NPartitions, Dict),
Dict2 = dict:store({Ref, Idx}, PartitionMessage, Dict1),
dict:update_counter({Ref, received}, 1, Dict2).
-spec combine_and_forward(reference(), dict:dict(), data_recomp_fun(), pid()) -> dict:dict().
combine_and_forward(Ref, Dict, DataCombinerFun, NextPid) ->
case dict:find({Ref, expecting}, Dict) of
error -> Dict;
{ok, NPartitions} -> combine_and_forward(Ref, Dict, NPartitions, DataCombinerFun, NextPid)
end.
-spec combine_and_forward(reference(), dict:dict(), pos_integer(), data_recomp_fun(), pid()) -> dict:dict().
resulting data message is sent to the process represented by ` NextPid ' ,
combine_and_forward(Ref, Dict, NPartitions, DataCombinerFun, NextPid) ->
RcvdPartitions = dict:fetch({Ref, received}, Dict),
if
RcvdPartitions == NPartitions ->
PartitionMessages = fetch_partitions(Ref, NPartitions, Dict, []),
DataMessage = apply(DataCombinerFun, [PartitionMessages]),
sk_tracer:t(50, self(), NextPid, {?MODULE, data}, [{ref, Ref}, {output, DataMessage}, {partitions, PartitionMessages}]),
NextPid ! DataMessage,
purge_partitions(Ref, NPartitions, Dict);
true ->
Dict
end.
-spec fetch_partitions(reference(), non_neg_integer(), dict:dict(), [any()]) -> [any()].
fetch_partitions(_Ref, 0, _Dict, Acc) ->
Acc;
fetch_partitions(Ref, NPartitions, Dict, Acc) ->
{ok, Piece} = dict:find({Ref, NPartitions}, Dict),
fetch_partitions(Ref, NPartitions-1, Dict, [Piece|Acc]).
-spec purge_partitions(reference(), non_neg_integer(), dict:dict()) -> dict:dict().
purge_partitions(Ref, 0, Dict) ->
Dict1 = dict:erase({Ref, expecting}, Dict),
Dict2 = dict:erase({Ref, received}, Dict1),
Dict2;
purge_partitions(Ref, NPartitions, Dict) ->
Dict1 = dict:erase({Ref, NPartitions}, Dict),
purge_partitions(Ref, NPartitions-1, Dict1).
|
124671ca036bcc712fe5ea60a6179fceee7469119227f87d3b19b3404f5e97b3 | coingaming/lnd-client | ChannelBackup.hs | module LndClient.Data.ChannelBackup
( ChannelBackup (..),
SingleChanBackupBlob (..),
)
where
import Data.ProtoLens
import qualified LndClient.Data.ChannelPoint as Ch
import LndClient.Import
import qualified Proto.Lnrpc.Ln1 as Ln1
import qualified Proto.Lnrpc.Ln1_Fields as Ln1
data ChannelBackup = ChannelBackup
{ chanPoint :: Ch.ChannelPoint,
chanBackup :: SingleChanBackupBlob
}
deriving stock
( Eq,
Ord,
Show,
Generic
)
instance Out ChannelBackup
newtype SingleChanBackupBlob = SingleChanBackupBlob
{ unSingleChanBackupBlob :: ByteString
}
deriving newtype
( Eq,
Ord,
Show,
PersistField,
PersistFieldSql
)
deriving stock
( Generic
)
instance Out SingleChanBackupBlob
instance FromGrpc [ChannelBackup] Ln1.ChanBackupSnapshot where
fromGrpc x =
fromGrpc $
x ^. Ln1.singleChanBackups . Ln1.chanBackups
instance FromGrpc ChannelBackup Ln1.ChannelBackup where
fromGrpc x =
ChannelBackup
<$> fromGrpc (x ^. Ln1.chanPoint)
<*> fromGrpc (x ^. Ln1.chanBackup)
instance ToGrpc ChannelBackup Ln1.ChannelBackup where
toGrpc x =
msg
<$> toGrpc (chanPoint x)
<*> toGrpc (chanBackup x)
where
msg cp bak =
defMessage
& Ln1.chanPoint .~ cp
& Ln1.chanBackup .~ bak
instance FromGrpc SingleChanBackupBlob ByteString where
fromGrpc x =
if null x
then
Left
. FromGrpcError
$ "Cannot parse SingleChanBackupBlob from " <> inspectPlain x
else
Right $
SingleChanBackupBlob x
instance ToGrpc SingleChanBackupBlob ByteString where
toGrpc =
Right . unSingleChanBackupBlob
instance ToGrpc [ChannelBackup] Ln1.RestoreChanBackupRequest where
toGrpc xs0 = do
xs <- mapM toGrpc xs0
pure $
defMessage
& Ln1.chanBackups
.~ ( defMessage
& Ln1.chanBackups .~ xs
)
| null | https://raw.githubusercontent.com/coingaming/lnd-client/caf08bab7d0ce57e344841646692fd193313a437/src/LndClient/Data/ChannelBackup.hs | haskell | module LndClient.Data.ChannelBackup
( ChannelBackup (..),
SingleChanBackupBlob (..),
)
where
import Data.ProtoLens
import qualified LndClient.Data.ChannelPoint as Ch
import LndClient.Import
import qualified Proto.Lnrpc.Ln1 as Ln1
import qualified Proto.Lnrpc.Ln1_Fields as Ln1
data ChannelBackup = ChannelBackup
{ chanPoint :: Ch.ChannelPoint,
chanBackup :: SingleChanBackupBlob
}
deriving stock
( Eq,
Ord,
Show,
Generic
)
instance Out ChannelBackup
newtype SingleChanBackupBlob = SingleChanBackupBlob
{ unSingleChanBackupBlob :: ByteString
}
deriving newtype
( Eq,
Ord,
Show,
PersistField,
PersistFieldSql
)
deriving stock
( Generic
)
instance Out SingleChanBackupBlob
instance FromGrpc [ChannelBackup] Ln1.ChanBackupSnapshot where
fromGrpc x =
fromGrpc $
x ^. Ln1.singleChanBackups . Ln1.chanBackups
instance FromGrpc ChannelBackup Ln1.ChannelBackup where
fromGrpc x =
ChannelBackup
<$> fromGrpc (x ^. Ln1.chanPoint)
<*> fromGrpc (x ^. Ln1.chanBackup)
instance ToGrpc ChannelBackup Ln1.ChannelBackup where
toGrpc x =
msg
<$> toGrpc (chanPoint x)
<*> toGrpc (chanBackup x)
where
msg cp bak =
defMessage
& Ln1.chanPoint .~ cp
& Ln1.chanBackup .~ bak
instance FromGrpc SingleChanBackupBlob ByteString where
fromGrpc x =
if null x
then
Left
. FromGrpcError
$ "Cannot parse SingleChanBackupBlob from " <> inspectPlain x
else
Right $
SingleChanBackupBlob x
instance ToGrpc SingleChanBackupBlob ByteString where
toGrpc =
Right . unSingleChanBackupBlob
instance ToGrpc [ChannelBackup] Ln1.RestoreChanBackupRequest where
toGrpc xs0 = do
xs <- mapM toGrpc xs0
pure $
defMessage
& Ln1.chanBackups
.~ ( defMessage
& Ln1.chanBackups .~ xs
)
| |
f1a82d5b6d3622d17248925dead7cc5460c05b98786f19b82c4bb367c8cbee2d | janestreet/ecaml | function_id.mli | * A unique i d for each OCaml function that can be called from Emacs .
open! Core
open! Import
include Unique_id.Id
| null | https://raw.githubusercontent.com/janestreet/ecaml/7c16e5720ee1da04e0757cf185a074debf9088df/src/function_id.mli | ocaml | * A unique i d for each OCaml function that can be called from Emacs .
open! Core
open! Import
include Unique_id.Id
| |
b76199bd6bab9f9bb6ac0c028a47d5b1da8c68605e0a174e52ab4c50a0e0a4d3 | coco33920/boulangerie | initializer.ml | let exists () =
try
open_in "_boulangerie.json" |> ignore;
true
with _ -> false
(*
Creates a new croissant project
*)
let init git =
Filemanager.init_list_file ();
if exists () then print_endline "there already is a croissant project here"
else (
print_endline "Downloading file from github...";
Sys.command
"wget -q \
"
|> ignore;
print_endline "file downloaded";
if git then (
Sys.command "git init" |> ignore;
print_endline "git repository created");
let oc = open_out "lib.baguette" in
Printf.fprintf oc "%s\n"
"CROISSANT CHOUQUETTE PARISBREST Hello World PARISBREST CLAFOUTIS \
BAGUETTE";
close_out oc;
print_endline "Boulangerie project initialized")
| null | https://raw.githubusercontent.com/coco33920/boulangerie/24213bbefee1f8b9a2891f5b0ebee346cfa5104c/lib/initializer.ml | ocaml |
Creates a new croissant project
| let exists () =
try
open_in "_boulangerie.json" |> ignore;
true
with _ -> false
let init git =
Filemanager.init_list_file ();
if exists () then print_endline "there already is a croissant project here"
else (
print_endline "Downloading file from github...";
Sys.command
"wget -q \
"
|> ignore;
print_endline "file downloaded";
if git then (
Sys.command "git init" |> ignore;
print_endline "git repository created");
let oc = open_out "lib.baguette" in
Printf.fprintf oc "%s\n"
"CROISSANT CHOUQUETTE PARISBREST Hello World PARISBREST CLAFOUTIS \
BAGUETTE";
close_out oc;
print_endline "Boulangerie project initialized")
|
398625b9c901fbabb4d6d87810db5eedcb1ab888a71f254c43237059adabf29e | may-liu/qtalk | http_add_muc_user.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(http_add_muc_user).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-export([add_muc_users/1]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("http_req.hrl").
-include("jlib.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{Method, _ } = cowboy_req:method(Req),
case Method of
<<"GET">> ->
{ok, Req1} = echo(<<"No Get Method!">>,Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req1} = post_echo(Method, HasBody, Req),
{ok, Req1, State};
_ ->
{ok,Req3} = echo(undefined, Req),
{ok, Req3, State}
end.
post_echo(<<"POST">>,true,Req) ->
{ok, PBody, _} = cowboy_req:body(Req),
Header = cowboy_req:get(headers,Req),
Body =
case catch proplists:get_value(<<"content-encoding">>,Header) of
<<"gzip">> ->
zlib:gunzip(PBody);
_ ->
PBody
end,
case rfc4627:decode(Body) of
{ok,{obj,Args},[]} ->
Res = add_muc_users(Args),
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}], Res, Req);
_ ->
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>,<<"Json format error.">>,<<"">>), Req)
end;
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], http_utils:gen_result(true, <<"0">>,Echo,<<"">>), Req).
terminate(_Reason, _Req, _State) ->
ok.
add_muc_users(Args) ->
Servers = ejabberd_config:get_myhosts(),
LServer = lists:nth(1,Servers),
add_muc_users(LServer,Args).
add_muc_users(Server,Args) ->
Muc_id = http_muc_session:get_value("muc_id",Args,<<"">>),
Muc_owner = http_muc_session:get_value("muc_owner",Args,<<"">>),
Muc_member = http_muc_session:get_value("muc_member",Args,<<"">>),
Domain = http_muc_session:get_value("muc_domain",Args,<<"">>),
case http_muc_session:check_muc_exist(Server,Muc_id) of
true ->
Packet = http_muc_session:make_muc_presence(),
Muc_jid = jlib:make_jid(Muc_id,Domain,<<"">>),
Invite_Jid = jlib:make_jid(Muc_owner,Server,<<"">>),
%lists:foreach(fun(U) ->
% Jid = jlib:make_jid(U,Server,<<"">>),
% case ejabberd_sm:get_user_resources(U, Server) of
% [] ->
% http_muc_session:handle_add_muc_users(Server,Muc_id,Domain,Jid);
% Rs ->
lists : ) - >
% case jlib:make_jid(U,Server,<<"">>) of
% error ->
% ok;
% Muc_user ->
% N = ejabberd_public:get_user_nick(U),
catch ejabberd_router : route(Muc_user , jlib : make_jid(Muc_id , Domain , N ) , Packet ) ,
case Muc_member of
<<"">> ->
ok;
_ ->
IQ_Packet = http_muc_session:make_invite_iq(Muc_member,<<"ejabhost1">>),
?DEBUG("From ~p ,To ~p,Packet ~p ~n",[Invite_Jid,Muc_jid,IQ_Packet]),
catch ejabberd_router:route(Invite_Jid,Muc_jid,IQ_Packet)
end,
catch http_muc_session : update_user_presence_a(Server , U , R , Muc_id , Domain )
% end
catch ejabberd_router : route(Invite_Jid , Muc_jid , http_muc_session : : ) ) )
% http_muc_session:handle_add_muc_users(Server,Muc_id,Domain,Jid)
end , ) ,
http_utils:gen_result(true, <<"0">>,<<"">>,<<"sucess">>);
_ ->
http_utils:gen_result(true, <<"1">>,<<"">>,<<"failed">>)
end.
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/http_add_muc_user.erl | erlang | Feel free to use, reuse and abuse the code in this file.
lists:foreach(fun(U) ->
Jid = jlib:make_jid(U,Server,<<"">>),
case ejabberd_sm:get_user_resources(U, Server) of
[] ->
http_muc_session:handle_add_muc_users(Server,Muc_id,Domain,Jid);
Rs ->
case jlib:make_jid(U,Server,<<"">>) of
error ->
ok;
Muc_user ->
N = ejabberd_public:get_user_nick(U),
end
http_muc_session:handle_add_muc_users(Server,Muc_id,Domain,Jid) |
-module(http_add_muc_user).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-export([add_muc_users/1]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("http_req.hrl").
-include("jlib.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{Method, _ } = cowboy_req:method(Req),
case Method of
<<"GET">> ->
{ok, Req1} = echo(<<"No Get Method!">>,Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req1} = post_echo(Method, HasBody, Req),
{ok, Req1, State};
_ ->
{ok,Req3} = echo(undefined, Req),
{ok, Req3, State}
end.
post_echo(<<"POST">>,true,Req) ->
{ok, PBody, _} = cowboy_req:body(Req),
Header = cowboy_req:get(headers,Req),
Body =
case catch proplists:get_value(<<"content-encoding">>,Header) of
<<"gzip">> ->
zlib:gunzip(PBody);
_ ->
PBody
end,
case rfc4627:decode(Body) of
{ok,{obj,Args},[]} ->
Res = add_muc_users(Args),
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}], Res, Req);
_ ->
cowboy_req:reply(200, [{<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>,<<"Json format error.">>,<<"">>), Req)
end;
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], http_utils:gen_result(false, <<"-1">>,<<"Missing Post body.">>,<<"">>), Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], http_utils:gen_result(true, <<"0">>,Echo,<<"">>), Req).
terminate(_Reason, _Req, _State) ->
ok.
add_muc_users(Args) ->
Servers = ejabberd_config:get_myhosts(),
LServer = lists:nth(1,Servers),
add_muc_users(LServer,Args).
add_muc_users(Server,Args) ->
Muc_id = http_muc_session:get_value("muc_id",Args,<<"">>),
Muc_owner = http_muc_session:get_value("muc_owner",Args,<<"">>),
Muc_member = http_muc_session:get_value("muc_member",Args,<<"">>),
Domain = http_muc_session:get_value("muc_domain",Args,<<"">>),
case http_muc_session:check_muc_exist(Server,Muc_id) of
true ->
Packet = http_muc_session:make_muc_presence(),
Muc_jid = jlib:make_jid(Muc_id,Domain,<<"">>),
Invite_Jid = jlib:make_jid(Muc_owner,Server,<<"">>),
lists : ) - >
catch ejabberd_router : route(Muc_user , jlib : make_jid(Muc_id , Domain , N ) , Packet ) ,
case Muc_member of
<<"">> ->
ok;
_ ->
IQ_Packet = http_muc_session:make_invite_iq(Muc_member,<<"ejabhost1">>),
?DEBUG("From ~p ,To ~p,Packet ~p ~n",[Invite_Jid,Muc_jid,IQ_Packet]),
catch ejabberd_router:route(Invite_Jid,Muc_jid,IQ_Packet)
end,
catch http_muc_session : update_user_presence_a(Server , U , R , Muc_id , Domain )
catch ejabberd_router : route(Invite_Jid , Muc_jid , http_muc_session : : ) ) )
end , ) ,
http_utils:gen_result(true, <<"0">>,<<"">>,<<"sucess">>);
_ ->
http_utils:gen_result(true, <<"1">>,<<"">>,<<"failed">>)
end.
|
3b409b8c9ce8d5d72460b3ead3de8492b2bdcdc8f95416745f3d113cf18a0c04 | BenjaminVanRyseghem/great-things-done | name_editor.cljs | Copyright ( c ) 2015 , . All rights reserved .
; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php )
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ui.widgets.name-editor
(:use [jayq.core :only [$]])
(:require [reagent.core :as reagent :refer [atom]]
[utils.core :as utils]))
(defn- plain-name-editor
[entity auto-focus]
[:div.entity-name
{:id (str "entity-name-" (:id entity))
:placeholder "Add a name"
:tab-index 0}
(:name entity)])
(defn- enter-pressed
[callback input]
(when-not (empty? (.val input))
(.blur input))
(callback input)
(when (empty? (.val input))
(.focus input)))
(defn- make-editable
[entity callback on-enter]
(.editable ($ (str "#entity-name-" (:id entity)))
"focus"
(clj->js {:onInputCreation (fn [input _]
(when on-enter
(utils/on input
"keydown"
[:escape :prevent] #(.blur input)
[:enter :prevent] #(enter-pressed (fn [i]
(callback entity
(.val i))
(on-enter i))
input))))
:callback (fn [event]
(if (empty? (.-value event))
(do
(.html (.-target event)
(.-old_value event))
false)
(when-not (= (.-old_value event)
(.-value event))
(callback entity
(.-value event)))))})))
(defn- build
[entity callback on-enter auto-focus]
(with-meta plain-name-editor
{:component-did-mount (fn []
(make-editable entity
callback
on-enter)
(when auto-focus
(.focus ($ (str "#entity-name-" (:id entity))))))}))
(defn render
[entity callback & {:keys [on-enter auto-focus]}]
[(build entity
callback
on-enter
auto-focus) entity])
| null | https://raw.githubusercontent.com/BenjaminVanRyseghem/great-things-done/1db9adc871556a347426df842a4f5ea6b3a1b7e0/src/front/ui/widgets/name_editor.cljs | clojure | The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) 2015 , . All rights reserved .
Eclipse Public License 1.0 ( -1.0.php )
(ns ui.widgets.name-editor
(:use [jayq.core :only [$]])
(:require [reagent.core :as reagent :refer [atom]]
[utils.core :as utils]))
(defn- plain-name-editor
[entity auto-focus]
[:div.entity-name
{:id (str "entity-name-" (:id entity))
:placeholder "Add a name"
:tab-index 0}
(:name entity)])
(defn- enter-pressed
[callback input]
(when-not (empty? (.val input))
(.blur input))
(callback input)
(when (empty? (.val input))
(.focus input)))
(defn- make-editable
[entity callback on-enter]
(.editable ($ (str "#entity-name-" (:id entity)))
"focus"
(clj->js {:onInputCreation (fn [input _]
(when on-enter
(utils/on input
"keydown"
[:escape :prevent] #(.blur input)
[:enter :prevent] #(enter-pressed (fn [i]
(callback entity
(.val i))
(on-enter i))
input))))
:callback (fn [event]
(if (empty? (.-value event))
(do
(.html (.-target event)
(.-old_value event))
false)
(when-not (= (.-old_value event)
(.-value event))
(callback entity
(.-value event)))))})))
(defn- build
[entity callback on-enter auto-focus]
(with-meta plain-name-editor
{:component-did-mount (fn []
(make-editable entity
callback
on-enter)
(when auto-focus
(.focus ($ (str "#entity-name-" (:id entity))))))}))
(defn render
[entity callback & {:keys [on-enter auto-focus]}]
[(build entity
callback
on-enter
auto-focus) entity])
|
1cbf51194f3a789827321d1899499bd783cb836942b48e5275d0f7245c0c6a49 | leksah/leksah-server | PackageCollector.hs | # LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE LambdaCase #
-----------------------------------------------------------------------------
--
-- Module : IDE.Metainfo.PackageCollector
Copyright : 2007 - 2009 ,
-- License : GPL Nothing
--
-- Maintainer :
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Metainfo.PackageCollector (
collectPackage
, collectPackageOnly
) where
import Prelude ()
import Prelude.Compat
import IDE.StrippedPrefs
(getUnpackDirectory, RetrieveStrategy(..), Prefs(..))
import PackageConfig (PackageConfig)
import IDE.Metainfo.SourceCollectorH
(findSourceForPackage, packageFromSource, PackageCollectStats(..))
import System.Log.Logger (errorM, debugM, infoM)
import IDE.Metainfo.InterfaceCollector (collectPackageFromHI)
import IDE.Core.CTypes
(dscTypeHint, descrType, dscName, modu, sdExported, sdComment,
sdLocation, sdType, sdName, SimpleDescr(..), TypeDescr(..),
dsrDescr, dsrMbModu, ReexportedDescr(..), Descr(..), dscExported',
dscTypeHint', dscMbComment', dscMbLocation', dscMbModu',
dscMbTypeStr', dscName', RealDescr(..), Descr, metadataVersion,
PackageDescr(..), leksahVersion, packageIdentifierToString,
getThisPackage, packId, ModuleDescr(..), PackageDBs(..))
import IDE.Utils.FileUtils (runProjectTool, getCollectorPath, getSysLibDir)
import System.Directory
(createDirectoryIfMissing, doesDirectoryExist, doesFileExist,
setCurrentDirectory)
import IDE.Utils.Utils
(leksahMetadataPathFileExtension,
leksahMetadataSystemFileExtension)
import System.FilePath
(dropFileName, takeBaseName, (<.>), (</>))
import Data.Binary.Shared (encodeFileSer)
import Distribution.Text (display)
import Control.Monad.IO.Class (MonadIO, MonadIO(..))
import qualified Control.Exception as E (SomeException, catch)
import IDE.Utils.Tool (ToolOutput(..), runTool')
import qualified Data.Text as T
(stripSuffix, stripPrefix, unpack, pack)
import Data.Text (Text)
import Network.HTTP.Proxy (Proxy(..), fetchProxy)
import Network.Browser
(request, setAuthorityGen, setOutHandler, setErrHandler, setProxy,
browse)
import Data.Char (isSpace)
import Network.URI (parseURI)
import Network.HTTP (rspBody, rspCode, Header(..), Request(..))
import Network.HTTP.Base (RequestMethod(..))
import Network.HTTP.Headers (HeaderName(..))
import qualified Data.ByteString as BS (readFile, writeFile, empty)
import qualified Paths_leksah_server (version)
import Distribution.System (buildArch, buildOS)
import qualified Data.Map as Map
(fromListWith, fromList, keys, lookup)
import Data.List (delete, nub)
import GHC.IO.Exception (ExitCode(..))
import Distribution.Package (pkgName)
import Distribution.Simple.Utils (installDirectoryContents)
import Distribution.Verbosity (normal)
import Data.Maybe (fromMaybe, maybeToList)
import Paths_leksah_server (getDataDir)
import IDE.Utils.Project (ProjectKey, pjDir)
import Data.Version (showVersion)
collectPackage :: Bool -> Prefs -> Int -> ((PackageConfig, PackageDBs), Int) -> IO PackageCollectStats
collectPackage writeAscii prefs numPackages ((packageConfig, PackageDBs{..}), packageIndex) =
collectPackageNix prefs packageConfig pDBsProject >>= \case
Just s -> return s
Nothing -> do
infoM "leksah-server" ("update_toolbar " ++ show
((fromIntegral packageIndex / fromIntegral numPackages) :: Double))
debugM "leksah-server" $ "collectPackage (pDBsProjectFile, pDBsPaths) " <> show (pDBsProject, pDBsPaths)
eitherStrFp <- findSourceForPackage prefs pid pDBsProject
case eitherStrFp of
Left message -> do
debugM "leksah-server" . T.unpack $ message <> " : " <> packageName
collectPackageFromHI pDBsProject packageConfig pDBsPaths >>= \case
Just packageDescrHi -> do
writeExtractedPackage False packageDescrHi
return stat {packageString = message, modulesTotal = Just (length (pdModules packageDescrHi))}
Nothing -> return stat
Right fpSource ->
case retrieveStrategy prefs of
RetrieveThenBuild ->
retrieve fpSource >>= \case
Just stats -> return stats
Nothing -> buildOnly fpSource
BuildThenRetrieve -> do
debugM "leksah-server" $ "Build (then retrieve) " <> T.unpack packageName <> " in " <> fpSource
build fpSource >>= \case
(Nothing, bstat) -> return bstat
(Just packageDescrHi, bstat) ->
retrieve fpSource >>= \case
Just stats -> return stats
Nothing -> do
writeExtractedPackage False packageDescrHi
return bstat{modulesTotal = Just (length (pdModules packageDescrHi))}
NeverRetrieve -> do
debugM "leksah-server" $ "Build " <> T.unpack packageName <> " in " <> fpSource
buildOnly fpSource
where
pid = packId $ getThisPackage packageConfig
packageName = packageIdentifierToString pid
stat = PackageCollectStats packageName Nothing False False Nothing
retrieve :: FilePath -> IO (Maybe PackageCollectStats)
retrieve fpSource = do
collectorPath <- liftIO getCollectorPath
setCurrentDirectory collectorPath
let fullUrl = T.unpack (retrieveURL prefs) <> "/metadata-" <> leksahVersion <> "/" <> T.unpack packageName <> leksahMetadataSystemFileExtension
filePath = collectorPath </> T.unpack packageName <.> leksahMetadataSystemFileExtension
case parseURI fullUrl of
Nothing -> do
errorM "leksah-server" $ "collectPackage: invalid URI = " <> fullUrl
return Nothing
Just uri -> do
debugM "leksah-server" $ "collectPackage: before retreiving = " <> fullUrl
proxy <- filterEmptyProxy . trimProxyUri <$> fetchProxy True
(_, rsp) <- browse $ do
setProxy proxy
setErrHandler (errorM "leksah-server")
setOutHandler (debugM "leksah-server")
setAuthorityGen (\_ _ -> return Nothing)
request Request{ rqURI = uri
, rqMethod = GET
, rqHeaders = [Header HdrUserAgent userAgent]
, rqBody = BS.empty }
if rspCode rsp == (2,0,0)
then do
BS.writeFile filePath $ rspBody rsp
debugM "leksah-server" . T.unpack $ "collectPackage: retreived = " <> packageName
liftIO $ writePackagePath (dropFileName fpSource) packageName
return (Just stat {withSource=True, retrieved= True, mbError=Nothing})
else do
debugM "leksah-server" . T.unpack $ "collectPackage: Can't retreive = " <> packageName
return Nothing
build :: FilePath -> IO (Maybe PackageDescr, PackageCollectStats)
build fpSource =
collectPackageFromHI pDBsProject packageConfig pDBsPaths >>= \case
Nothing -> return (Nothing, stat)
Just packageDescrHi -> do
runCabalConfigure fpSource
mbPackageDescrPair <- packageFromSource pDBsProject pDBsPaths fpSource packageConfig
case mbPackageDescrPair of
(Just packageDescrS, bstat) -> do
writeMerged packageDescrS packageDescrHi fpSource
return (Nothing, bstat{modulesTotal = Just (length (pdModules packageDescrS))})
(Nothing, bstat) -> return (Just packageDescrHi, bstat)
buildOnly :: FilePath -> IO PackageCollectStats
buildOnly fpSource =
build fpSource >>= \case
(Nothing, bstat) -> return bstat
(Just packageDescrHi, bstat) -> do
writeExtractedPackage False packageDescrHi
return bstat{modulesTotal = Just (length (pdModules packageDescrHi))}
trimProxyUri (Proxy uri auth) = Proxy (trim uri) auth
trimProxyUri p = p
filterEmptyProxy (Proxy "" _) = NoProxy
filterEmptyProxy p = p
trim = f . f where f = reverse . dropWhile isSpace
userAgent = concat [ "leksah-server/", showVersion Paths_leksah_server.version
, " (", display buildOS, "; ", display buildArch, ")"
]
writeMerged packageDescrS packageDescrHi fpSource = do
let mergedPackageDescr = mergePackageDescrs packageDescrHi packageDescrS
liftIO $ writeExtractedPackage writeAscii mergedPackageDescr
liftIO $ writePackagePath (dropFileName fpSource) packageName
runCabalConfigure fpSource = do
let dirPath = dropFileName fpSource
packageName' = takeBaseName fpSource
flagsFor "base" = do
libDir <- getSysLibDir pDBsProject Nothing
return $ ["-finteger-gmp", "-finteger-gmp2"] ++ maybeToList ((\l -> T.pack $ "--configure-option=CFLAGS=-I" <> l </> "include") <$> libDir)
flagsFor ('g':'i':'-':_) = return ["-f-enable-overloading", "-f-overloaded-methods", "-f-overloaded-properties", "-f-overloaded-signals"]
flagsFor _ = return []
setCurrentDirectory dirPath
E.catch (do _ <- runTool' "cabal" ["clean"] Nothing Nothing
debugM "leksah" $ "fpSource = " <> show fpSource
flags <- flagsFor packageName'
_ <- runProjectTool pDBsProject "cabal" ("v1-configure":flags ++ map (("--package-db="<>) .T.pack) pDBsPaths) Nothing Nothing
return ())
(\ (_e :: E.SomeException) -> do
debugM "leksah-server" "Can't configure"
return ())
collectPackageNix :: Prefs -> PackageConfig -> Maybe ProjectKey -> IO (Maybe PackageCollectStats)
collectPackageNix _ _ Nothing = return Nothing
collectPackageNix prefs packageConfig (Just project) = do
debugM "leksah-server" "collectPackageNix"
let nixFile = pjDir project </> "default.nix"
doesFileExist nixFile >>= \case
True -> do
collectorPath <- getCollectorPath
leksahMetadataNix <- (</> "data/leksah-metadata.nix") <$> getDataDir
(nixOuput, _) <- runTool' "nix-build" ["--no-out-link", "-E", T.pack $
"let ghc=(let fn = import ./.; in if builtins.isFunction fn then fn {} else fn).ghc; "
<> "in import " <> leksahMetadataNix <> " { inherit ghc; "
<> "pkg=ghc." <> display (pkgName pid) <> ";}"
] (Just $ pjDir project) Nothing
case reverse nixOuput of
(ToolExit ExitSuccess:ToolOutput lineMaybeQuoted:_) -> do
let line = T.unpack $ removeQuotes lineMaybeQuoted
metadataFile = line </> "share/leksah/metadata"
</> packageName' <.> leksahMetadataSystemFileExtension
pkgSource = line </> "share/leksah/packageSource"
doesFileExist metadataFile >>= \case
True -> do
BS.readFile metadataFile >>= BS.writeFile (
collectorPath </> packageName' <.> leksahMetadataSystemFileExtension)
doesDirectoryExist pkgSource >>= \case
True -> do
unpackDir <- getUnpackDirectory prefs
case unpackDir of
Nothing -> return $ Just stat {packageString = "metadata from nix (no unpack dir)"}
Just fpUnpack -> do
createDirectoryIfMissing True fpUnpack
installDirectoryContents normal pkgSource (fpUnpack </> packageName')
writePackagePath (fpUnpack </> packageName' <> "/") packageName
return $ Just stat {packageString = "metadata and source from nix"}
False -> return $ Just stat {packageString = "metadata from nix"}
False -> return Nothing
_ -> return Nothing
False -> return Nothing
where
pid = packId $ getThisPackage packageConfig
packageName = packageIdentifierToString pid
packageName' = T.unpack packageName
stat = PackageCollectStats packageName Nothing False False Nothing
removeQuotes s = fromMaybe s $ T.stripPrefix "\"" s >>= T.stripSuffix "\""
collectPackageOnly :: PackageConfig -> [FilePath] -> FilePath -> FilePath -> IO ()
collectPackageOnly packageConfig dbs fpSource outputFile = do
debugM "leksah-server" $ "Build " <> T.unpack packageName <> " in " <> fpSource <> " out " <> outputFile
build
where
pid = packId $ getThisPackage packageConfig
packageName = packageIdentifierToString pid
build :: IO ()
build =
collectPackageFromHI Nothing packageConfig dbs >>= \case
Nothing -> return ()
Just packageDescrHi -> do
mbPackageDescrPair <- packageFromSource Nothing dbs fpSource packageConfig
case mbPackageDescrPair of
(Just packageDescrS, _) ->
encodeFileSer outputFile (metadataVersion, mergePackageDescrs packageDescrHi packageDescrS)
(Nothing, _) ->
encodeFileSer outputFile (metadataVersion, packageDescrHi)
writeExtractedPackage :: MonadIO m => Bool -> PackageDescr -> m ()
writeExtractedPackage writeAscii pd = do
collectorPath <- liftIO getCollectorPath
let filePath = collectorPath </> T.unpack (packageIdentifierToString $ pdPackage pd) <.>
leksahMetadataSystemFileExtension
if writeAscii
then liftIO $ writeFile (filePath ++ "dpg") (show pd)
else liftIO $ encodeFileSer filePath (metadataVersion, pd)
writePackagePath :: MonadIO m => FilePath -> Text -> m ()
writePackagePath fp packageName = do
collectorPath <- liftIO getCollectorPath
let filePath = collectorPath </> T.unpack packageName <.> leksahMetadataPathFileExtension
liftIO $ writeFile filePath fp
------------Merging of .hi and .hs parsing / parsing and typechecking results
mergePackageDescrs :: PackageDescr -> PackageDescr -> PackageDescr
mergePackageDescrs packageDescrHI packageDescrS = PackageDescr {
pdPackage = pdPackage packageDescrHI
, pdMbSourcePath = pdMbSourcePath packageDescrS
, pdModules = mergeModuleDescrs (pdModules packageDescrHI) (pdModules packageDescrS)
, pdBuildDepends = pdBuildDepends packageDescrHI}
mergeModuleDescrs :: [ModuleDescr] -> [ModuleDescr] -> [ModuleDescr]
mergeModuleDescrs hiList srcList = map mergeIt allNames
where
mergeIt :: String -> ModuleDescr
mergeIt str = case (Map.lookup str hiDict, Map.lookup str srcDict) of
(Just mdhi, Nothing) -> mdhi
(Nothing, Just mdsrc) -> mdsrc
(Just mdhi, Just mdsrc) -> mergeModuleDescr mdhi mdsrc
(Nothing, Nothing) -> error "Collector>>mergeModuleDescrs: impossible"
allNames = nub $ Map.keys hiDict ++ Map.keys srcDict
hiDict = Map.fromList $ zip (map (display . modu . mdModuleId) hiList) hiList
srcDict = Map.fromList $ zip (map (display . modu . mdModuleId) srcList) srcList
mergeModuleDescr :: ModuleDescr -> ModuleDescr -> ModuleDescr
mergeModuleDescr hiDescr srcDescr = ModuleDescr {
mdModuleId = mdModuleId hiDescr
, mdMbSourcePath = mdMbSourcePath srcDescr
, mdReferences = mdReferences hiDescr
, mdIdDescriptions = mergeDescrs (mdIdDescriptions hiDescr) (mdIdDescriptions srcDescr)}
mergeDescrs :: [Descr] -> [Descr] -> [Descr]
mergeDescrs hiList srcList = concatMap mergeIt allNames
where
mergeIt :: Text -> [Descr]
mergeIt pm = case (Map.lookup pm hiDict, Map.lookup pm srcDict) of
(Just mdhi, Nothing) -> mdhi
(Nothing, Just mdsrc) -> mdsrc
(Just mdhi, Just mdsrc) -> map (uncurry mergeDescr) $ makePairs mdhi mdsrc
(Nothing, Nothing) -> error "Collector>>mergeModuleDescrs: impossible"
allNames = nub $ Map.keys hiDict ++ Map.keys srcDict
hiDict = Map.fromListWith (++) $ zip (map dscName hiList) (map (: []) hiList)
srcDict = Map.fromListWith (++) $ zip (map dscName srcList)(map (: []) srcList)
makePairs :: [Descr] -> [Descr] -> [(Maybe Descr,Maybe Descr)]
makePairs (hd:tl) srcList = (Just hd, theMatching)
: makePairs tl (case theMatching of
Just tm -> delete tm srcList
Nothing -> srcList)
where
theMatching = findMatching hd srcList
findMatching ele (hd':tail')
| matches ele hd' = Just hd'
| otherwise = findMatching ele tail'
findMatching _ele [] = Nothing
matches :: Descr -> Descr -> Bool
matches d1 d2 = (descrType . dscTypeHint) d1 == (descrType . dscTypeHint) d2
makePairs [] rest = map (\ a -> (Nothing, Just a)) rest
mergeDescr :: Maybe Descr -> Maybe Descr -> Descr
mergeDescr (Just descr) Nothing = descr
mergeDescr Nothing (Just descr) = descr
mergeDescr (Just (Real rdhi)) (Just (Real rdsrc)) =
Real RealDescr {
dscName' = dscName' rdhi
, dscMbTypeStr' = dscMbTypeStr' rdsrc
, dscMbModu' = dscMbModu' rdsrc
, dscMbLocation' = dscMbLocation' rdsrc
, dscMbComment' = dscMbComment' rdsrc
, dscTypeHint' = mergeTypeDescr (dscTypeHint' rdhi) (dscTypeHint' rdsrc)
, dscExported' = True
}
mergeDescr (Just (Reexported rdhi)) (Just rdsrc) =
Reexported $ ReexportedDescr {
dsrMbModu = dsrMbModu rdhi
, dsrDescr = mergeDescr (Just (dsrDescr rdhi)) (Just rdsrc)
}
mergeDescr _ _ = error "Collector>>mergeDescr: impossible"
mergeTypeHint : : Maybe TypeDescr - > Maybe TypeDescr - > Maybe TypeDescr
--mergeTypeHint Nothing Nothing = Nothing
--mergeTypeHint Nothing jtd = jtd
--mergeTypeHint jtd Nothing = jtd
mergeTypeHint ( Just tdhi ) ( Just tdhs ) = Just ( mergeTypeDescr )
mergeTypeDescr :: TypeDescr -> TypeDescr -> TypeDescr
mergeTypeDescr (DataDescr constrListHi fieldListHi) (DataDescr constrListSrc fieldListSrc) =
DataDescr (mergeSimpleDescrs constrListHi constrListSrc) (mergeSimpleDescrs fieldListHi fieldListSrc)
mergeTypeDescr (NewtypeDescr constrHi mbFieldHi) (NewtypeDescr constrSrc mbFieldSrc) =
NewtypeDescr (mergeSimpleDescr constrHi constrSrc) (mergeMbDescr mbFieldHi mbFieldSrc)
mergeTypeDescr (ClassDescr superHi methodsHi) (ClassDescr _superSrc methodsSrc) =
ClassDescr superHi (mergeSimpleDescrs methodsHi methodsSrc)
mergeTypeDescr (InstanceDescr _bindsHi) (InstanceDescr bindsSrc) =
InstanceDescr bindsSrc
mergeTypeDescr descrHi _ =
descrHi
mergeSimpleDescrs :: [SimpleDescr] -> [SimpleDescr] -> [SimpleDescr]
mergeSimpleDescrs hiList srcList = map mergeIt allNames
where
mergeIt :: Text -> SimpleDescr
mergeIt pm = fromMaybe (error "Collector>>mergeSimpleDescrs: impossible")
(mergeMbDescr (Map.lookup pm hiDict) (Map.lookup pm srcDict))
allNames = nub $ Map.keys hiDict ++ Map.keys srcDict
hiDict = Map.fromList $ zip (map sdName hiList) hiList
srcDict = Map.fromList $ zip (map sdName srcList) srcList
mergeSimpleDescr :: SimpleDescr -> SimpleDescr -> SimpleDescr
mergeSimpleDescr sdHi sdSrc = SimpleDescr {
sdName = sdName sdHi,
sdType = sdType sdHi,
sdLocation = sdLocation sdSrc,
sdComment = sdComment sdSrc,
sdExported = sdExported sdSrc}
mergeMbDescr :: Maybe SimpleDescr -> Maybe SimpleDescr -> Maybe SimpleDescr
mergeMbDescr (Just mdhi) Nothing = Just mdhi
mergeMbDescr Nothing (Just mdsrc) = Just mdsrc
mergeMbDescr (Just mdhi) (Just mdsrc) = Just (mergeSimpleDescr mdhi mdsrc)
mergeMbDescr Nothing Nothing = Nothing
| null | https://raw.githubusercontent.com/leksah/leksah-server/d4b735c17a36123dc97f79fabf1e9310d74984a6/src/IDE/Metainfo/PackageCollector.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
Module : IDE.Metainfo.PackageCollector
License : GPL Nothing
Maintainer :
Stability : provisional
Portability :
|
---------------------------------------------------------------------------
----------Merging of .hi and .hs parsing / parsing and typechecking results
mergeTypeHint Nothing Nothing = Nothing
mergeTypeHint Nothing jtd = jtd
mergeTypeHint jtd Nothing = jtd | # LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
Copyright : 2007 - 2009 ,
module IDE.Metainfo.PackageCollector (
collectPackage
, collectPackageOnly
) where
import Prelude ()
import Prelude.Compat
import IDE.StrippedPrefs
(getUnpackDirectory, RetrieveStrategy(..), Prefs(..))
import PackageConfig (PackageConfig)
import IDE.Metainfo.SourceCollectorH
(findSourceForPackage, packageFromSource, PackageCollectStats(..))
import System.Log.Logger (errorM, debugM, infoM)
import IDE.Metainfo.InterfaceCollector (collectPackageFromHI)
import IDE.Core.CTypes
(dscTypeHint, descrType, dscName, modu, sdExported, sdComment,
sdLocation, sdType, sdName, SimpleDescr(..), TypeDescr(..),
dsrDescr, dsrMbModu, ReexportedDescr(..), Descr(..), dscExported',
dscTypeHint', dscMbComment', dscMbLocation', dscMbModu',
dscMbTypeStr', dscName', RealDescr(..), Descr, metadataVersion,
PackageDescr(..), leksahVersion, packageIdentifierToString,
getThisPackage, packId, ModuleDescr(..), PackageDBs(..))
import IDE.Utils.FileUtils (runProjectTool, getCollectorPath, getSysLibDir)
import System.Directory
(createDirectoryIfMissing, doesDirectoryExist, doesFileExist,
setCurrentDirectory)
import IDE.Utils.Utils
(leksahMetadataPathFileExtension,
leksahMetadataSystemFileExtension)
import System.FilePath
(dropFileName, takeBaseName, (<.>), (</>))
import Data.Binary.Shared (encodeFileSer)
import Distribution.Text (display)
import Control.Monad.IO.Class (MonadIO, MonadIO(..))
import qualified Control.Exception as E (SomeException, catch)
import IDE.Utils.Tool (ToolOutput(..), runTool')
import qualified Data.Text as T
(stripSuffix, stripPrefix, unpack, pack)
import Data.Text (Text)
import Network.HTTP.Proxy (Proxy(..), fetchProxy)
import Network.Browser
(request, setAuthorityGen, setOutHandler, setErrHandler, setProxy,
browse)
import Data.Char (isSpace)
import Network.URI (parseURI)
import Network.HTTP (rspBody, rspCode, Header(..), Request(..))
import Network.HTTP.Base (RequestMethod(..))
import Network.HTTP.Headers (HeaderName(..))
import qualified Data.ByteString as BS (readFile, writeFile, empty)
import qualified Paths_leksah_server (version)
import Distribution.System (buildArch, buildOS)
import qualified Data.Map as Map
(fromListWith, fromList, keys, lookup)
import Data.List (delete, nub)
import GHC.IO.Exception (ExitCode(..))
import Distribution.Package (pkgName)
import Distribution.Simple.Utils (installDirectoryContents)
import Distribution.Verbosity (normal)
import Data.Maybe (fromMaybe, maybeToList)
import Paths_leksah_server (getDataDir)
import IDE.Utils.Project (ProjectKey, pjDir)
import Data.Version (showVersion)
collectPackage :: Bool -> Prefs -> Int -> ((PackageConfig, PackageDBs), Int) -> IO PackageCollectStats
collectPackage writeAscii prefs numPackages ((packageConfig, PackageDBs{..}), packageIndex) =
collectPackageNix prefs packageConfig pDBsProject >>= \case
Just s -> return s
Nothing -> do
infoM "leksah-server" ("update_toolbar " ++ show
((fromIntegral packageIndex / fromIntegral numPackages) :: Double))
debugM "leksah-server" $ "collectPackage (pDBsProjectFile, pDBsPaths) " <> show (pDBsProject, pDBsPaths)
eitherStrFp <- findSourceForPackage prefs pid pDBsProject
case eitherStrFp of
Left message -> do
debugM "leksah-server" . T.unpack $ message <> " : " <> packageName
collectPackageFromHI pDBsProject packageConfig pDBsPaths >>= \case
Just packageDescrHi -> do
writeExtractedPackage False packageDescrHi
return stat {packageString = message, modulesTotal = Just (length (pdModules packageDescrHi))}
Nothing -> return stat
Right fpSource ->
case retrieveStrategy prefs of
RetrieveThenBuild ->
retrieve fpSource >>= \case
Just stats -> return stats
Nothing -> buildOnly fpSource
BuildThenRetrieve -> do
debugM "leksah-server" $ "Build (then retrieve) " <> T.unpack packageName <> " in " <> fpSource
build fpSource >>= \case
(Nothing, bstat) -> return bstat
(Just packageDescrHi, bstat) ->
retrieve fpSource >>= \case
Just stats -> return stats
Nothing -> do
writeExtractedPackage False packageDescrHi
return bstat{modulesTotal = Just (length (pdModules packageDescrHi))}
NeverRetrieve -> do
debugM "leksah-server" $ "Build " <> T.unpack packageName <> " in " <> fpSource
buildOnly fpSource
where
pid = packId $ getThisPackage packageConfig
packageName = packageIdentifierToString pid
stat = PackageCollectStats packageName Nothing False False Nothing
retrieve :: FilePath -> IO (Maybe PackageCollectStats)
retrieve fpSource = do
collectorPath <- liftIO getCollectorPath
setCurrentDirectory collectorPath
let fullUrl = T.unpack (retrieveURL prefs) <> "/metadata-" <> leksahVersion <> "/" <> T.unpack packageName <> leksahMetadataSystemFileExtension
filePath = collectorPath </> T.unpack packageName <.> leksahMetadataSystemFileExtension
case parseURI fullUrl of
Nothing -> do
errorM "leksah-server" $ "collectPackage: invalid URI = " <> fullUrl
return Nothing
Just uri -> do
debugM "leksah-server" $ "collectPackage: before retreiving = " <> fullUrl
proxy <- filterEmptyProxy . trimProxyUri <$> fetchProxy True
(_, rsp) <- browse $ do
setProxy proxy
setErrHandler (errorM "leksah-server")
setOutHandler (debugM "leksah-server")
setAuthorityGen (\_ _ -> return Nothing)
request Request{ rqURI = uri
, rqMethod = GET
, rqHeaders = [Header HdrUserAgent userAgent]
, rqBody = BS.empty }
if rspCode rsp == (2,0,0)
then do
BS.writeFile filePath $ rspBody rsp
debugM "leksah-server" . T.unpack $ "collectPackage: retreived = " <> packageName
liftIO $ writePackagePath (dropFileName fpSource) packageName
return (Just stat {withSource=True, retrieved= True, mbError=Nothing})
else do
debugM "leksah-server" . T.unpack $ "collectPackage: Can't retreive = " <> packageName
return Nothing
build :: FilePath -> IO (Maybe PackageDescr, PackageCollectStats)
build fpSource =
collectPackageFromHI pDBsProject packageConfig pDBsPaths >>= \case
Nothing -> return (Nothing, stat)
Just packageDescrHi -> do
runCabalConfigure fpSource
mbPackageDescrPair <- packageFromSource pDBsProject pDBsPaths fpSource packageConfig
case mbPackageDescrPair of
(Just packageDescrS, bstat) -> do
writeMerged packageDescrS packageDescrHi fpSource
return (Nothing, bstat{modulesTotal = Just (length (pdModules packageDescrS))})
(Nothing, bstat) -> return (Just packageDescrHi, bstat)
buildOnly :: FilePath -> IO PackageCollectStats
buildOnly fpSource =
build fpSource >>= \case
(Nothing, bstat) -> return bstat
(Just packageDescrHi, bstat) -> do
writeExtractedPackage False packageDescrHi
return bstat{modulesTotal = Just (length (pdModules packageDescrHi))}
trimProxyUri (Proxy uri auth) = Proxy (trim uri) auth
trimProxyUri p = p
filterEmptyProxy (Proxy "" _) = NoProxy
filterEmptyProxy p = p
trim = f . f where f = reverse . dropWhile isSpace
userAgent = concat [ "leksah-server/", showVersion Paths_leksah_server.version
, " (", display buildOS, "; ", display buildArch, ")"
]
writeMerged packageDescrS packageDescrHi fpSource = do
let mergedPackageDescr = mergePackageDescrs packageDescrHi packageDescrS
liftIO $ writeExtractedPackage writeAscii mergedPackageDescr
liftIO $ writePackagePath (dropFileName fpSource) packageName
runCabalConfigure fpSource = do
let dirPath = dropFileName fpSource
packageName' = takeBaseName fpSource
flagsFor "base" = do
libDir <- getSysLibDir pDBsProject Nothing
return $ ["-finteger-gmp", "-finteger-gmp2"] ++ maybeToList ((\l -> T.pack $ "--configure-option=CFLAGS=-I" <> l </> "include") <$> libDir)
flagsFor ('g':'i':'-':_) = return ["-f-enable-overloading", "-f-overloaded-methods", "-f-overloaded-properties", "-f-overloaded-signals"]
flagsFor _ = return []
setCurrentDirectory dirPath
E.catch (do _ <- runTool' "cabal" ["clean"] Nothing Nothing
debugM "leksah" $ "fpSource = " <> show fpSource
flags <- flagsFor packageName'
_ <- runProjectTool pDBsProject "cabal" ("v1-configure":flags ++ map (("--package-db="<>) .T.pack) pDBsPaths) Nothing Nothing
return ())
(\ (_e :: E.SomeException) -> do
debugM "leksah-server" "Can't configure"
return ())
collectPackageNix :: Prefs -> PackageConfig -> Maybe ProjectKey -> IO (Maybe PackageCollectStats)
collectPackageNix _ _ Nothing = return Nothing
collectPackageNix prefs packageConfig (Just project) = do
debugM "leksah-server" "collectPackageNix"
let nixFile = pjDir project </> "default.nix"
doesFileExist nixFile >>= \case
True -> do
collectorPath <- getCollectorPath
leksahMetadataNix <- (</> "data/leksah-metadata.nix") <$> getDataDir
(nixOuput, _) <- runTool' "nix-build" ["--no-out-link", "-E", T.pack $
"let ghc=(let fn = import ./.; in if builtins.isFunction fn then fn {} else fn).ghc; "
<> "in import " <> leksahMetadataNix <> " { inherit ghc; "
<> "pkg=ghc." <> display (pkgName pid) <> ";}"
] (Just $ pjDir project) Nothing
case reverse nixOuput of
(ToolExit ExitSuccess:ToolOutput lineMaybeQuoted:_) -> do
let line = T.unpack $ removeQuotes lineMaybeQuoted
metadataFile = line </> "share/leksah/metadata"
</> packageName' <.> leksahMetadataSystemFileExtension
pkgSource = line </> "share/leksah/packageSource"
doesFileExist metadataFile >>= \case
True -> do
BS.readFile metadataFile >>= BS.writeFile (
collectorPath </> packageName' <.> leksahMetadataSystemFileExtension)
doesDirectoryExist pkgSource >>= \case
True -> do
unpackDir <- getUnpackDirectory prefs
case unpackDir of
Nothing -> return $ Just stat {packageString = "metadata from nix (no unpack dir)"}
Just fpUnpack -> do
createDirectoryIfMissing True fpUnpack
installDirectoryContents normal pkgSource (fpUnpack </> packageName')
writePackagePath (fpUnpack </> packageName' <> "/") packageName
return $ Just stat {packageString = "metadata and source from nix"}
False -> return $ Just stat {packageString = "metadata from nix"}
False -> return Nothing
_ -> return Nothing
False -> return Nothing
where
pid = packId $ getThisPackage packageConfig
packageName = packageIdentifierToString pid
packageName' = T.unpack packageName
stat = PackageCollectStats packageName Nothing False False Nothing
removeQuotes s = fromMaybe s $ T.stripPrefix "\"" s >>= T.stripSuffix "\""
collectPackageOnly :: PackageConfig -> [FilePath] -> FilePath -> FilePath -> IO ()
collectPackageOnly packageConfig dbs fpSource outputFile = do
debugM "leksah-server" $ "Build " <> T.unpack packageName <> " in " <> fpSource <> " out " <> outputFile
build
where
pid = packId $ getThisPackage packageConfig
packageName = packageIdentifierToString pid
build :: IO ()
build =
collectPackageFromHI Nothing packageConfig dbs >>= \case
Nothing -> return ()
Just packageDescrHi -> do
mbPackageDescrPair <- packageFromSource Nothing dbs fpSource packageConfig
case mbPackageDescrPair of
(Just packageDescrS, _) ->
encodeFileSer outputFile (metadataVersion, mergePackageDescrs packageDescrHi packageDescrS)
(Nothing, _) ->
encodeFileSer outputFile (metadataVersion, packageDescrHi)
writeExtractedPackage :: MonadIO m => Bool -> PackageDescr -> m ()
writeExtractedPackage writeAscii pd = do
collectorPath <- liftIO getCollectorPath
let filePath = collectorPath </> T.unpack (packageIdentifierToString $ pdPackage pd) <.>
leksahMetadataSystemFileExtension
if writeAscii
then liftIO $ writeFile (filePath ++ "dpg") (show pd)
else liftIO $ encodeFileSer filePath (metadataVersion, pd)
writePackagePath :: MonadIO m => FilePath -> Text -> m ()
writePackagePath fp packageName = do
collectorPath <- liftIO getCollectorPath
let filePath = collectorPath </> T.unpack packageName <.> leksahMetadataPathFileExtension
liftIO $ writeFile filePath fp
mergePackageDescrs :: PackageDescr -> PackageDescr -> PackageDescr
mergePackageDescrs packageDescrHI packageDescrS = PackageDescr {
pdPackage = pdPackage packageDescrHI
, pdMbSourcePath = pdMbSourcePath packageDescrS
, pdModules = mergeModuleDescrs (pdModules packageDescrHI) (pdModules packageDescrS)
, pdBuildDepends = pdBuildDepends packageDescrHI}
mergeModuleDescrs :: [ModuleDescr] -> [ModuleDescr] -> [ModuleDescr]
mergeModuleDescrs hiList srcList = map mergeIt allNames
where
mergeIt :: String -> ModuleDescr
mergeIt str = case (Map.lookup str hiDict, Map.lookup str srcDict) of
(Just mdhi, Nothing) -> mdhi
(Nothing, Just mdsrc) -> mdsrc
(Just mdhi, Just mdsrc) -> mergeModuleDescr mdhi mdsrc
(Nothing, Nothing) -> error "Collector>>mergeModuleDescrs: impossible"
allNames = nub $ Map.keys hiDict ++ Map.keys srcDict
hiDict = Map.fromList $ zip (map (display . modu . mdModuleId) hiList) hiList
srcDict = Map.fromList $ zip (map (display . modu . mdModuleId) srcList) srcList
mergeModuleDescr :: ModuleDescr -> ModuleDescr -> ModuleDescr
mergeModuleDescr hiDescr srcDescr = ModuleDescr {
mdModuleId = mdModuleId hiDescr
, mdMbSourcePath = mdMbSourcePath srcDescr
, mdReferences = mdReferences hiDescr
, mdIdDescriptions = mergeDescrs (mdIdDescriptions hiDescr) (mdIdDescriptions srcDescr)}
mergeDescrs :: [Descr] -> [Descr] -> [Descr]
mergeDescrs hiList srcList = concatMap mergeIt allNames
where
mergeIt :: Text -> [Descr]
mergeIt pm = case (Map.lookup pm hiDict, Map.lookup pm srcDict) of
(Just mdhi, Nothing) -> mdhi
(Nothing, Just mdsrc) -> mdsrc
(Just mdhi, Just mdsrc) -> map (uncurry mergeDescr) $ makePairs mdhi mdsrc
(Nothing, Nothing) -> error "Collector>>mergeModuleDescrs: impossible"
allNames = nub $ Map.keys hiDict ++ Map.keys srcDict
hiDict = Map.fromListWith (++) $ zip (map dscName hiList) (map (: []) hiList)
srcDict = Map.fromListWith (++) $ zip (map dscName srcList)(map (: []) srcList)
makePairs :: [Descr] -> [Descr] -> [(Maybe Descr,Maybe Descr)]
makePairs (hd:tl) srcList = (Just hd, theMatching)
: makePairs tl (case theMatching of
Just tm -> delete tm srcList
Nothing -> srcList)
where
theMatching = findMatching hd srcList
findMatching ele (hd':tail')
| matches ele hd' = Just hd'
| otherwise = findMatching ele tail'
findMatching _ele [] = Nothing
matches :: Descr -> Descr -> Bool
matches d1 d2 = (descrType . dscTypeHint) d1 == (descrType . dscTypeHint) d2
makePairs [] rest = map (\ a -> (Nothing, Just a)) rest
mergeDescr :: Maybe Descr -> Maybe Descr -> Descr
mergeDescr (Just descr) Nothing = descr
mergeDescr Nothing (Just descr) = descr
mergeDescr (Just (Real rdhi)) (Just (Real rdsrc)) =
Real RealDescr {
dscName' = dscName' rdhi
, dscMbTypeStr' = dscMbTypeStr' rdsrc
, dscMbModu' = dscMbModu' rdsrc
, dscMbLocation' = dscMbLocation' rdsrc
, dscMbComment' = dscMbComment' rdsrc
, dscTypeHint' = mergeTypeDescr (dscTypeHint' rdhi) (dscTypeHint' rdsrc)
, dscExported' = True
}
mergeDescr (Just (Reexported rdhi)) (Just rdsrc) =
Reexported $ ReexportedDescr {
dsrMbModu = dsrMbModu rdhi
, dsrDescr = mergeDescr (Just (dsrDescr rdhi)) (Just rdsrc)
}
mergeDescr _ _ = error "Collector>>mergeDescr: impossible"
mergeTypeHint : : Maybe TypeDescr - > Maybe TypeDescr - > Maybe TypeDescr
mergeTypeHint ( Just tdhi ) ( Just tdhs ) = Just ( mergeTypeDescr )
mergeTypeDescr :: TypeDescr -> TypeDescr -> TypeDescr
mergeTypeDescr (DataDescr constrListHi fieldListHi) (DataDescr constrListSrc fieldListSrc) =
DataDescr (mergeSimpleDescrs constrListHi constrListSrc) (mergeSimpleDescrs fieldListHi fieldListSrc)
mergeTypeDescr (NewtypeDescr constrHi mbFieldHi) (NewtypeDescr constrSrc mbFieldSrc) =
NewtypeDescr (mergeSimpleDescr constrHi constrSrc) (mergeMbDescr mbFieldHi mbFieldSrc)
mergeTypeDescr (ClassDescr superHi methodsHi) (ClassDescr _superSrc methodsSrc) =
ClassDescr superHi (mergeSimpleDescrs methodsHi methodsSrc)
mergeTypeDescr (InstanceDescr _bindsHi) (InstanceDescr bindsSrc) =
InstanceDescr bindsSrc
mergeTypeDescr descrHi _ =
descrHi
mergeSimpleDescrs :: [SimpleDescr] -> [SimpleDescr] -> [SimpleDescr]
mergeSimpleDescrs hiList srcList = map mergeIt allNames
where
mergeIt :: Text -> SimpleDescr
mergeIt pm = fromMaybe (error "Collector>>mergeSimpleDescrs: impossible")
(mergeMbDescr (Map.lookup pm hiDict) (Map.lookup pm srcDict))
allNames = nub $ Map.keys hiDict ++ Map.keys srcDict
hiDict = Map.fromList $ zip (map sdName hiList) hiList
srcDict = Map.fromList $ zip (map sdName srcList) srcList
mergeSimpleDescr :: SimpleDescr -> SimpleDescr -> SimpleDescr
mergeSimpleDescr sdHi sdSrc = SimpleDescr {
sdName = sdName sdHi,
sdType = sdType sdHi,
sdLocation = sdLocation sdSrc,
sdComment = sdComment sdSrc,
sdExported = sdExported sdSrc}
mergeMbDescr :: Maybe SimpleDescr -> Maybe SimpleDescr -> Maybe SimpleDescr
mergeMbDescr (Just mdhi) Nothing = Just mdhi
mergeMbDescr Nothing (Just mdsrc) = Just mdsrc
mergeMbDescr (Just mdhi) (Just mdsrc) = Just (mergeSimpleDescr mdhi mdsrc)
mergeMbDescr Nothing Nothing = Nothing
|
59a3164c1a88bded3b60f77c6d300152f097f4c701b84042e7b3cdb5b2def3b7 | tweag/asterius | ThreadDelay.hs | import Asterius.Types
import Control.Concurrent
import Data.Coerce
foreign import javascript "console.log($1)" js_print :: JSVal -> IO ()
printString :: String -> IO ()
printString s = js_print (coerce (toJSString s))
main :: IO ()
main = do
printString "Hello"
threadDelay 2000000
printString "world"
threadDelay 2000000
printString "of delays!"
| null | https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/rts/ThreadDelay.hs | haskell | import Asterius.Types
import Control.Concurrent
import Data.Coerce
foreign import javascript "console.log($1)" js_print :: JSVal -> IO ()
printString :: String -> IO ()
printString s = js_print (coerce (toJSString s))
main :: IO ()
main = do
printString "Hello"
threadDelay 2000000
printString "world"
threadDelay 2000000
printString "of delays!"
| |
76067849b1cfcfcab6d939cafeee8eddaa12e32b7d5192434d6d78329edf3094 | dimitri/ql-to-deb | build-cl-unicode.lisp | ;;;
;;; Load the cl-unicode system so that files generated by its
;;; build-dependency :build[cl-unicode system are available when packaging.
;;;
(require :asdf)
;(asdf:load-system :asdf) ; upgrade
(setf asdf:*central-registry*
(list* '*default-pathname-defaults* asdf:*central-registry*))
(asdf:load-system :cl-unicode)
(quit)
| null | https://raw.githubusercontent.com/dimitri/ql-to-deb/f89e91804ebbb1912001c1b1d45c157cf162608f/packages/cl-unicode/debian/build-cl-unicode.lisp | lisp |
Load the cl-unicode system so that files generated by its
build-dependency :build[cl-unicode system are available when packaging.
(asdf:load-system :asdf) ; upgrade |
(require :asdf)
(setf asdf:*central-registry*
(list* '*default-pathname-defaults* asdf:*central-registry*))
(asdf:load-system :cl-unicode)
(quit)
|
1656ef409443fd7bdcbe001fa9c9e3e50c3c5fca23c25f973b37f4c07eea4fcc | tatut/clj-chrome-devtools | browser.clj | (ns clj-chrome-devtools.commands.browser
"The Browser domain defines methods and events for browser managing."
(:require [clojure.spec.alpha :as s]
[clj-chrome-devtools.impl.command :as cmd]
[clj-chrome-devtools.impl.connection :as c]))
(s/def
::browser-context-id
string?)
(s/def
::window-id
integer?)
(s/def
::window-state
#{"normal" "fullscreen" "maximized" "minimized"})
(s/def
::bounds
(s/keys
:opt-un
[::left
::top
::width
::height
::window-state]))
(s/def
::permission-type
#{"clipboardReadWrite" "paymentHandler" "notifications" "audioCapture"
"idleDetection" "nfc" "geolocation" "wakeLockScreen" "sensors"
"videoCapture" "accessibilityEvents" "wakeLockSystem"
"backgroundSync" "displayCapture" "durableStorage" "midi"
"videoCapturePanTiltZoom" "flash" "periodicBackgroundSync"
"clipboardSanitizedWrite" "backgroundFetch" "midiSysex"
"protectedMediaIdentifier"})
(s/def
::permission-setting
#{"granted" "prompt" "denied"})
(s/def
::permission-descriptor
(s/keys
:req-un
[::name]
:opt-un
[::sysex
::user-visible-only
::allow-without-sanitization
::pan-tilt-zoom]))
(s/def
::browser-command-id
#{"closeTabSearch" "openTabSearch"})
(s/def
::bucket
(s/keys
:req-un
[::low
::high
::count]))
(s/def
::histogram
(s/keys
:req-un
[::name
::sum
::count
::buckets]))
(defn
set-permission
"Set permission settings for given origin.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :permission | Descriptor of permission to override.\n :setting | Setting of the permission.\n :origin | Origin the permission applies to, all origins if not specified. (optional)\n :browser-context-id | Context to override. When omitted, default browser context is used. (optional)"
([]
(set-permission
(c/get-current-connection)
{}))
([{:as params, :keys [permission setting origin browser-context-id]}]
(set-permission
(c/get-current-connection)
params))
([connection
{:as params, :keys [permission setting origin browser-context-id]}]
(cmd/command
connection
"Browser"
"setPermission"
params
{:permission "permission",
:setting "setting",
:origin "origin",
:browser-context-id "browserContextId"})))
(s/fdef
set-permission
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::permission
::setting]
:opt-un
[::origin
::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::permission
::setting]
:opt-un
[::origin
::browser-context-id])))
:ret
(s/keys))
(defn
grant-permissions
"Grant specific permissions to the given origin and reject all others.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :permissions | null\n :origin | Origin the permission applies to, all origins if not specified. (optional)\n :browser-context-id | BrowserContext to override permissions. When omitted, default browser context is used. (optional)"
([]
(grant-permissions
(c/get-current-connection)
{}))
([{:as params, :keys [permissions origin browser-context-id]}]
(grant-permissions
(c/get-current-connection)
params))
([connection
{:as params, :keys [permissions origin browser-context-id]}]
(cmd/command
connection
"Browser"
"grantPermissions"
params
{:permissions "permissions",
:origin "origin",
:browser-context-id "browserContextId"})))
(s/fdef
grant-permissions
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::permissions]
:opt-un
[::origin
::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::permissions]
:opt-un
[::origin
::browser-context-id])))
:ret
(s/keys))
(defn
reset-permissions
"Reset all permission management for all origins.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :browser-context-id | BrowserContext to reset permissions. When omitted, default browser context is used. (optional)"
([]
(reset-permissions
(c/get-current-connection)
{}))
([{:as params, :keys [browser-context-id]}]
(reset-permissions
(c/get-current-connection)
params))
([connection {:as params, :keys [browser-context-id]}]
(cmd/command
connection
"Browser"
"resetPermissions"
params
{:browser-context-id "browserContextId"})))
(s/fdef
reset-permissions
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::browser-context-id])))
:ret
(s/keys))
(defn
set-download-behavior
"Set the behavior when downloading a file.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :behavior | Whether to allow all or deny all download requests, or use default Chrome behavior if\navailable (otherwise deny). |allowAndName| allows download and names files according to\ntheir dowmload guids.\n :browser-context-id | BrowserContext to set download behavior. When omitted, default browser context is used. (optional)\n :download-path | The default path to save downloaded files to. This is required if behavior is set to 'allow'\nor 'allowAndName'. (optional)\n :events-enabled | Whether to emit download events (defaults to false). (optional)"
([]
(set-download-behavior
(c/get-current-connection)
{}))
([{:as params,
:keys [behavior browser-context-id download-path events-enabled]}]
(set-download-behavior
(c/get-current-connection)
params))
([connection
{:as params,
:keys [behavior browser-context-id download-path events-enabled]}]
(cmd/command
connection
"Browser"
"setDownloadBehavior"
params
{:behavior "behavior",
:browser-context-id "browserContextId",
:download-path "downloadPath",
:events-enabled "eventsEnabled"})))
(s/fdef
set-download-behavior
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::behavior]
:opt-un
[::browser-context-id
::download-path
::events-enabled]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::behavior]
:opt-un
[::browser-context-id
::download-path
::events-enabled])))
:ret
(s/keys))
(defn
cancel-download
"Cancel a download if in progress\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :guid | Global unique identifier of the download.\n :browser-context-id | BrowserContext to perform the action in. When omitted, default browser context is used. (optional)"
([]
(cancel-download
(c/get-current-connection)
{}))
([{:as params, :keys [guid browser-context-id]}]
(cancel-download
(c/get-current-connection)
params))
([connection {:as params, :keys [guid browser-context-id]}]
(cmd/command
connection
"Browser"
"cancelDownload"
params
{:guid "guid", :browser-context-id "browserContextId"})))
(s/fdef
cancel-download
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::guid]
:opt-un
[::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::guid]
:opt-un
[::browser-context-id])))
:ret
(s/keys))
(defn
close
"Close browser gracefully."
([]
(close
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(close
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"close"
params
{})))
(s/fdef
close
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys))
(defn
crash
"Crashes browser on the main thread."
([]
(crash
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(crash
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"crash"
params
{})))
(s/fdef
crash
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys))
(defn
crash-gpu-process
"Crashes GPU process."
([]
(crash-gpu-process
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(crash-gpu-process
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"crashGpuProcess"
params
{})))
(s/fdef
crash-gpu-process
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys))
(defn
get-version
"Returns version information.\n\nReturn map keys:\n\n\n Key | Description \n ------------------|------------ \n :protocol-version | Protocol version.\n :product | Product name.\n :revision | Product revision.\n :user-agent | User-Agent.\n :js-version | V8 version."
([]
(get-version
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(get-version
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"getVersion"
params
{})))
(s/fdef
get-version
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys
:req-un
[::protocol-version
::product
::revision
::user-agent
::js-version]))
(defn
get-browser-command-line
"Returns the command line switches for the browser process if, and only if\n--enable-automation is on the commandline.\n\nReturn map keys:\n\n\n Key | Description \n -----------|------------ \n :arguments | Commandline parameters"
([]
(get-browser-command-line
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(get-browser-command-line
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"getBrowserCommandLine"
params
{})))
(s/fdef
get-browser-command-line
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys
:req-un
[::arguments]))
(defn
get-histograms
"Get Chrome histograms.\n\nParameters map keys:\n\n\n Key | Description \n -------|------------ \n :query | Requested substring in name. Only histograms which have query as a\nsubstring in their name are extracted. An empty or absent query returns\nall histograms. (optional)\n :delta | If true, retrieve delta since last call. (optional)\n\nReturn map keys:\n\n\n Key | Description \n ------------|------------ \n :histograms | Histograms."
([]
(get-histograms
(c/get-current-connection)
{}))
([{:as params, :keys [query delta]}]
(get-histograms
(c/get-current-connection)
params))
([connection {:as params, :keys [query delta]}]
(cmd/command
connection
"Browser"
"getHistograms"
params
{:query "query", :delta "delta"})))
(s/fdef
get-histograms
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::query
::delta]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::query
::delta])))
:ret
(s/keys
:req-un
[::histograms]))
(defn
get-histogram
"Get a Chrome histogram by name.\n\nParameters map keys:\n\n\n Key | Description \n -------|------------ \n :name | Requested histogram name.\n :delta | If true, retrieve delta since last call. (optional)\n\nReturn map keys:\n\n\n Key | Description \n -----------|------------ \n :histogram | Histogram."
([]
(get-histogram
(c/get-current-connection)
{}))
([{:as params, :keys [name delta]}]
(get-histogram
(c/get-current-connection)
params))
([connection {:as params, :keys [name delta]}]
(cmd/command
connection
"Browser"
"getHistogram"
params
{:name "name", :delta "delta"})))
(s/fdef
get-histogram
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::name]
:opt-un
[::delta]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::name]
:opt-un
[::delta])))
:ret
(s/keys
:req-un
[::histogram]))
(defn
get-window-bounds
"Get position and size of the browser window.\n\nParameters map keys:\n\n\n Key | Description \n -----------|------------ \n :window-id | Browser window id.\n\nReturn map keys:\n\n\n Key | Description \n --------|------------ \n :bounds | Bounds information of the window. When window state is 'minimized', the restored window\nposition and size are returned."
([]
(get-window-bounds
(c/get-current-connection)
{}))
([{:as params, :keys [window-id]}]
(get-window-bounds
(c/get-current-connection)
params))
([connection {:as params, :keys [window-id]}]
(cmd/command
connection
"Browser"
"getWindowBounds"
params
{:window-id "windowId"})))
(s/fdef
get-window-bounds
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::window-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::window-id])))
:ret
(s/keys
:req-un
[::bounds]))
(defn
get-window-for-target
"Get the browser window that contains the devtools target.\n\nParameters map keys:\n\n\n Key | Description \n -----------|------------ \n :target-id | Devtools agent host id. If called as a part of the session, associated targetId is used. (optional)\n\nReturn map keys:\n\n\n Key | Description \n -----------|------------ \n :window-id | Browser window id.\n :bounds | Bounds information of the window. When window state is 'minimized', the restored window\nposition and size are returned."
([]
(get-window-for-target
(c/get-current-connection)
{}))
([{:as params, :keys [target-id]}]
(get-window-for-target
(c/get-current-connection)
params))
([connection {:as params, :keys [target-id]}]
(cmd/command
connection
"Browser"
"getWindowForTarget"
params
{:target-id "targetId"})))
(s/fdef
get-window-for-target
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::target-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::target-id])))
:ret
(s/keys
:req-un
[::window-id
::bounds]))
(defn
set-window-bounds
"Set position and/or size of the browser window.\n\nParameters map keys:\n\n\n Key | Description \n -----------|------------ \n :window-id | Browser window id.\n :bounds | New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined\nwith 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged."
([]
(set-window-bounds
(c/get-current-connection)
{}))
([{:as params, :keys [window-id bounds]}]
(set-window-bounds
(c/get-current-connection)
params))
([connection {:as params, :keys [window-id bounds]}]
(cmd/command
connection
"Browser"
"setWindowBounds"
params
{:window-id "windowId", :bounds "bounds"})))
(s/fdef
set-window-bounds
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::window-id
::bounds]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::window-id
::bounds])))
:ret
(s/keys))
(defn
set-dock-tile
"Set dock tile details, platform-specific.\n\nParameters map keys:\n\n\n Key | Description \n -------------|------------ \n :badge-label | null (optional)\n :image | Png encoded image. (Encoded as a base64 string when passed over JSON) (optional)"
([]
(set-dock-tile
(c/get-current-connection)
{}))
([{:as params, :keys [badge-label image]}]
(set-dock-tile
(c/get-current-connection)
params))
([connection {:as params, :keys [badge-label image]}]
(cmd/command
connection
"Browser"
"setDockTile"
params
{:badge-label "badgeLabel", :image "image"})))
(s/fdef
set-dock-tile
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::badge-label
::image]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::badge-label
::image])))
:ret
(s/keys))
(defn
execute-browser-command
"Invoke custom browser commands used by telemetry.\n\nParameters map keys:\n\n\n Key | Description \n ------------|------------ \n :command-id | null"
([]
(execute-browser-command
(c/get-current-connection)
{}))
([{:as params, :keys [command-id]}]
(execute-browser-command
(c/get-current-connection)
params))
([connection {:as params, :keys [command-id]}]
(cmd/command
connection
"Browser"
"executeBrowserCommand"
params
{:command-id "commandId"})))
(s/fdef
execute-browser-command
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::command-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::command-id])))
:ret
(s/keys))
| null | https://raw.githubusercontent.com/tatut/clj-chrome-devtools/48a77f8cd64dae88acc271b46c48a647e41a7580/src/clj_chrome_devtools/commands/browser.clj | clojure | (ns clj-chrome-devtools.commands.browser
"The Browser domain defines methods and events for browser managing."
(:require [clojure.spec.alpha :as s]
[clj-chrome-devtools.impl.command :as cmd]
[clj-chrome-devtools.impl.connection :as c]))
(s/def
::browser-context-id
string?)
(s/def
::window-id
integer?)
(s/def
::window-state
#{"normal" "fullscreen" "maximized" "minimized"})
(s/def
::bounds
(s/keys
:opt-un
[::left
::top
::width
::height
::window-state]))
(s/def
::permission-type
#{"clipboardReadWrite" "paymentHandler" "notifications" "audioCapture"
"idleDetection" "nfc" "geolocation" "wakeLockScreen" "sensors"
"videoCapture" "accessibilityEvents" "wakeLockSystem"
"backgroundSync" "displayCapture" "durableStorage" "midi"
"videoCapturePanTiltZoom" "flash" "periodicBackgroundSync"
"clipboardSanitizedWrite" "backgroundFetch" "midiSysex"
"protectedMediaIdentifier"})
(s/def
::permission-setting
#{"granted" "prompt" "denied"})
(s/def
::permission-descriptor
(s/keys
:req-un
[::name]
:opt-un
[::sysex
::user-visible-only
::allow-without-sanitization
::pan-tilt-zoom]))
(s/def
::browser-command-id
#{"closeTabSearch" "openTabSearch"})
(s/def
::bucket
(s/keys
:req-un
[::low
::high
::count]))
(s/def
::histogram
(s/keys
:req-un
[::name
::sum
::count
::buckets]))
(defn
set-permission
"Set permission settings for given origin.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :permission | Descriptor of permission to override.\n :setting | Setting of the permission.\n :origin | Origin the permission applies to, all origins if not specified. (optional)\n :browser-context-id | Context to override. When omitted, default browser context is used. (optional)"
([]
(set-permission
(c/get-current-connection)
{}))
([{:as params, :keys [permission setting origin browser-context-id]}]
(set-permission
(c/get-current-connection)
params))
([connection
{:as params, :keys [permission setting origin browser-context-id]}]
(cmd/command
connection
"Browser"
"setPermission"
params
{:permission "permission",
:setting "setting",
:origin "origin",
:browser-context-id "browserContextId"})))
(s/fdef
set-permission
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::permission
::setting]
:opt-un
[::origin
::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::permission
::setting]
:opt-un
[::origin
::browser-context-id])))
:ret
(s/keys))
(defn
grant-permissions
"Grant specific permissions to the given origin and reject all others.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :permissions | null\n :origin | Origin the permission applies to, all origins if not specified. (optional)\n :browser-context-id | BrowserContext to override permissions. When omitted, default browser context is used. (optional)"
([]
(grant-permissions
(c/get-current-connection)
{}))
([{:as params, :keys [permissions origin browser-context-id]}]
(grant-permissions
(c/get-current-connection)
params))
([connection
{:as params, :keys [permissions origin browser-context-id]}]
(cmd/command
connection
"Browser"
"grantPermissions"
params
{:permissions "permissions",
:origin "origin",
:browser-context-id "browserContextId"})))
(s/fdef
grant-permissions
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::permissions]
:opt-un
[::origin
::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::permissions]
:opt-un
[::origin
::browser-context-id])))
:ret
(s/keys))
(defn
reset-permissions
"Reset all permission management for all origins.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :browser-context-id | BrowserContext to reset permissions. When omitted, default browser context is used. (optional)"
([]
(reset-permissions
(c/get-current-connection)
{}))
([{:as params, :keys [browser-context-id]}]
(reset-permissions
(c/get-current-connection)
params))
([connection {:as params, :keys [browser-context-id]}]
(cmd/command
connection
"Browser"
"resetPermissions"
params
{:browser-context-id "browserContextId"})))
(s/fdef
reset-permissions
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::browser-context-id])))
:ret
(s/keys))
(defn
set-download-behavior
"Set the behavior when downloading a file.\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :behavior | Whether to allow all or deny all download requests, or use default Chrome behavior if\navailable (otherwise deny). |allowAndName| allows download and names files according to\ntheir dowmload guids.\n :browser-context-id | BrowserContext to set download behavior. When omitted, default browser context is used. (optional)\n :download-path | The default path to save downloaded files to. This is required if behavior is set to 'allow'\nor 'allowAndName'. (optional)\n :events-enabled | Whether to emit download events (defaults to false). (optional)"
([]
(set-download-behavior
(c/get-current-connection)
{}))
([{:as params,
:keys [behavior browser-context-id download-path events-enabled]}]
(set-download-behavior
(c/get-current-connection)
params))
([connection
{:as params,
:keys [behavior browser-context-id download-path events-enabled]}]
(cmd/command
connection
"Browser"
"setDownloadBehavior"
params
{:behavior "behavior",
:browser-context-id "browserContextId",
:download-path "downloadPath",
:events-enabled "eventsEnabled"})))
(s/fdef
set-download-behavior
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::behavior]
:opt-un
[::browser-context-id
::download-path
::events-enabled]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::behavior]
:opt-un
[::browser-context-id
::download-path
::events-enabled])))
:ret
(s/keys))
(defn
cancel-download
"Cancel a download if in progress\n\nParameters map keys:\n\n\n Key | Description \n --------------------|------------ \n :guid | Global unique identifier of the download.\n :browser-context-id | BrowserContext to perform the action in. When omitted, default browser context is used. (optional)"
([]
(cancel-download
(c/get-current-connection)
{}))
([{:as params, :keys [guid browser-context-id]}]
(cancel-download
(c/get-current-connection)
params))
([connection {:as params, :keys [guid browser-context-id]}]
(cmd/command
connection
"Browser"
"cancelDownload"
params
{:guid "guid", :browser-context-id "browserContextId"})))
(s/fdef
cancel-download
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::guid]
:opt-un
[::browser-context-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::guid]
:opt-un
[::browser-context-id])))
:ret
(s/keys))
(defn
close
"Close browser gracefully."
([]
(close
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(close
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"close"
params
{})))
(s/fdef
close
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys))
(defn
crash
"Crashes browser on the main thread."
([]
(crash
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(crash
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"crash"
params
{})))
(s/fdef
crash
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys))
(defn
crash-gpu-process
"Crashes GPU process."
([]
(crash-gpu-process
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(crash-gpu-process
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"crashGpuProcess"
params
{})))
(s/fdef
crash-gpu-process
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys))
(defn
get-version
"Returns version information.\n\nReturn map keys:\n\n\n Key | Description \n ------------------|------------ \n :protocol-version | Protocol version.\n :product | Product name.\n :revision | Product revision.\n :user-agent | User-Agent.\n :js-version | V8 version."
([]
(get-version
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(get-version
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"getVersion"
params
{})))
(s/fdef
get-version
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys
:req-un
[::protocol-version
::product
::revision
::user-agent
::js-version]))
(defn
get-browser-command-line
"Returns the command line switches for the browser process if, and only if\n--enable-automation is on the commandline.\n\nReturn map keys:\n\n\n Key | Description \n -----------|------------ \n :arguments | Commandline parameters"
([]
(get-browser-command-line
(c/get-current-connection)
{}))
([{:as params, :keys []}]
(get-browser-command-line
(c/get-current-connection)
params))
([connection {:as params, :keys []}]
(cmd/command
connection
"Browser"
"getBrowserCommandLine"
params
{})))
(s/fdef
get-browser-command-line
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat :params (s/keys))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys)))
:ret
(s/keys
:req-un
[::arguments]))
(defn
get-histograms
"Get Chrome histograms.\n\nParameters map keys:\n\n\n Key | Description \n -------|------------ \n :query | Requested substring in name. Only histograms which have query as a\nsubstring in their name are extracted. An empty or absent query returns\nall histograms. (optional)\n :delta | If true, retrieve delta since last call. (optional)\n\nReturn map keys:\n\n\n Key | Description \n ------------|------------ \n :histograms | Histograms."
([]
(get-histograms
(c/get-current-connection)
{}))
([{:as params, :keys [query delta]}]
(get-histograms
(c/get-current-connection)
params))
([connection {:as params, :keys [query delta]}]
(cmd/command
connection
"Browser"
"getHistograms"
params
{:query "query", :delta "delta"})))
(s/fdef
get-histograms
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::query
::delta]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::query
::delta])))
:ret
(s/keys
:req-un
[::histograms]))
(defn
get-histogram
"Get a Chrome histogram by name.\n\nParameters map keys:\n\n\n Key | Description \n -------|------------ \n :name | Requested histogram name.\n :delta | If true, retrieve delta since last call. (optional)\n\nReturn map keys:\n\n\n Key | Description \n -----------|------------ \n :histogram | Histogram."
([]
(get-histogram
(c/get-current-connection)
{}))
([{:as params, :keys [name delta]}]
(get-histogram
(c/get-current-connection)
params))
([connection {:as params, :keys [name delta]}]
(cmd/command
connection
"Browser"
"getHistogram"
params
{:name "name", :delta "delta"})))
(s/fdef
get-histogram
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::name]
:opt-un
[::delta]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::name]
:opt-un
[::delta])))
:ret
(s/keys
:req-un
[::histogram]))
(defn
get-window-bounds
"Get position and size of the browser window.\n\nParameters map keys:\n\n\n Key | Description \n -----------|------------ \n :window-id | Browser window id.\n\nReturn map keys:\n\n\n Key | Description \n --------|------------ \n :bounds | Bounds information of the window. When window state is 'minimized', the restored window\nposition and size are returned."
([]
(get-window-bounds
(c/get-current-connection)
{}))
([{:as params, :keys [window-id]}]
(get-window-bounds
(c/get-current-connection)
params))
([connection {:as params, :keys [window-id]}]
(cmd/command
connection
"Browser"
"getWindowBounds"
params
{:window-id "windowId"})))
(s/fdef
get-window-bounds
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::window-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::window-id])))
:ret
(s/keys
:req-un
[::bounds]))
(defn
get-window-for-target
"Get the browser window that contains the devtools target.\n\nParameters map keys:\n\n\n Key | Description \n -----------|------------ \n :target-id | Devtools agent host id. If called as a part of the session, associated targetId is used. (optional)\n\nReturn map keys:\n\n\n Key | Description \n -----------|------------ \n :window-id | Browser window id.\n :bounds | Bounds information of the window. When window state is 'minimized', the restored window\nposition and size are returned."
([]
(get-window-for-target
(c/get-current-connection)
{}))
([{:as params, :keys [target-id]}]
(get-window-for-target
(c/get-current-connection)
params))
([connection {:as params, :keys [target-id]}]
(cmd/command
connection
"Browser"
"getWindowForTarget"
params
{:target-id "targetId"})))
(s/fdef
get-window-for-target
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::target-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::target-id])))
:ret
(s/keys
:req-un
[::window-id
::bounds]))
(defn
set-window-bounds
"Set position and/or size of the browser window.\n\nParameters map keys:\n\n\n Key | Description \n -----------|------------ \n :window-id | Browser window id.\n :bounds | New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined\nwith 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged."
([]
(set-window-bounds
(c/get-current-connection)
{}))
([{:as params, :keys [window-id bounds]}]
(set-window-bounds
(c/get-current-connection)
params))
([connection {:as params, :keys [window-id bounds]}]
(cmd/command
connection
"Browser"
"setWindowBounds"
params
{:window-id "windowId", :bounds "bounds"})))
(s/fdef
set-window-bounds
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::window-id
::bounds]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::window-id
::bounds])))
:ret
(s/keys))
(defn
set-dock-tile
"Set dock tile details, platform-specific.\n\nParameters map keys:\n\n\n Key | Description \n -------------|------------ \n :badge-label | null (optional)\n :image | Png encoded image. (Encoded as a base64 string when passed over JSON) (optional)"
([]
(set-dock-tile
(c/get-current-connection)
{}))
([{:as params, :keys [badge-label image]}]
(set-dock-tile
(c/get-current-connection)
params))
([connection {:as params, :keys [badge-label image]}]
(cmd/command
connection
"Browser"
"setDockTile"
params
{:badge-label "badgeLabel", :image "image"})))
(s/fdef
set-dock-tile
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:opt-un
[::badge-label
::image]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:opt-un
[::badge-label
::image])))
:ret
(s/keys))
(defn
execute-browser-command
"Invoke custom browser commands used by telemetry.\n\nParameters map keys:\n\n\n Key | Description \n ------------|------------ \n :command-id | null"
([]
(execute-browser-command
(c/get-current-connection)
{}))
([{:as params, :keys [command-id]}]
(execute-browser-command
(c/get-current-connection)
params))
([connection {:as params, :keys [command-id]}]
(cmd/command
connection
"Browser"
"executeBrowserCommand"
params
{:command-id "commandId"})))
(s/fdef
execute-browser-command
:args
(s/or
:no-args
(s/cat)
:just-params
(s/cat
:params
(s/keys
:req-un
[::command-id]))
:connection-and-params
(s/cat
:connection
(s/?
c/connection?)
:params
(s/keys
:req-un
[::command-id])))
:ret
(s/keys))
| |
f201d3b1f47d1a6c7e645fc1c62815feb67acc3efd5ce8d839403c369b47a4c5 | donaldsonjw/bigloo | license.scm | ;; Automatically generated file (don't edit)
(module tools_license (export (bigloo-license)))
(define (bigloo-license)
" ---------------------------------------------------------------------
A practical implementation for the Scheme programming language
,--^,
_ ___/ /|/
,;'( )__, ) '
;; // L__.
' \\ / '
^ ^
Copyright (c) 1992 - 2013 Manuel Serrano
Bug descriptions, user reports, comments or suggestions are
welcome. Send them to
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
either version 2 of the License , or
(at your option) any later version. More precisely,
- The compiler and the tools are distributed under the terms of the
GNU General Public License.
- The Bigloo run-time system and the libraries are distributed under
the terms of the GNU Library General Public License. The source code
of the Bigloo runtime system is located in the ./runtime directory.
The source code of the FairThreads library is located in the
./fthread directory.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
--------------------------------------------------------------------- ")
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/comptime/Tools/license.scm | scheme | Automatically generated file (don't edit)
'( )__, ) '
// L__.
you can redistribute it and/or modify
without even the implied warranty of
if not, write to the Free | (module tools_license (export (bigloo-license)))
(define (bigloo-license)
" ---------------------------------------------------------------------
A practical implementation for the Scheme programming language
,--^,
_ ___/ /|/
' \\ / '
^ ^
Copyright (c) 1992 - 2013 Manuel Serrano
Bug descriptions, user reports, comments or suggestions are
welcome. Send them to
it under the terms of the GNU General Public License as published by
either version 2 of the License , or
(at your option) any later version. More precisely,
- The compiler and the tools are distributed under the terms of the
GNU General Public License.
- The Bigloo run-time system and the libraries are distributed under
the terms of the GNU Library General Public License. The source code
of the Bigloo runtime system is located in the ./runtime directory.
The source code of the FairThreads library is located in the
./fthread directory.
This program is distributed in the hope that it will be useful,
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
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
--------------------------------------------------------------------- ")
|
b78d5d90cca243bd16c1f820b635a926d1453a24448db1bb0e06ecefb920fe9d | Beyamor/ruin | array2d.cljs | (ns ruin.array2d
(:refer-clojure :exclude [get set!]))
(defn width
[arr]
(alength arr))
(defn height
[arr]
(alength (aget width 0)))
(defn set!
[arr x y value]
(aset (aget arr x) y value)
arr)
(defn get
[arr x y]
(aget (aget arr x) y))
(defn create
[width height]
(let [arr (array)]
(dotimes [x width]
(.push arr (array))
(dotimes [y height]
(.push (aget arr x) nil)))
arr))
| null | https://raw.githubusercontent.com/Beyamor/ruin/50a6977430dcbbceecccadbf732298462165b049/src/ruin/array2d.cljs | clojure | (ns ruin.array2d
(:refer-clojure :exclude [get set!]))
(defn width
[arr]
(alength arr))
(defn height
[arr]
(alength (aget width 0)))
(defn set!
[arr x y value]
(aset (aget arr x) y value)
arr)
(defn get
[arr x y]
(aget (aget arr x) y))
(defn create
[width height]
(let [arr (array)]
(dotimes [x width]
(.push arr (array))
(dotimes [y height]
(.push (aget arr x) nil)))
arr))
| |
9c61c0acc43f8051a7d68c4e376996d95aa903d12d06d14b1bfcd3c9a050d00f | roman/Haskell-capataz | Core.hs | # LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE RankNTypes #-}
{-| This module contains:
* Functions exported on the public API
* High level message handlers of the supervisor thread loop
-}
module Control.Concurrent.Capataz.Internal.Core
(
HasSupervisor(..)
, forkWorker
, forkSupervisor
, forkCapataz
, terminateProcess
, terminateCapataz
, terminateCapataz_
, joinCapatazThread
, getSupervisorProcessId
, getSupervisorAsync
, getCapatazTeardown
)
where
import RIO
import Control.Teardown (Teardown, TeardownResult, newTeardown, runTeardown, runTeardown_)
import RIO.Time (getCurrentTime)
import qualified Data.UUID.V4 as UUID (nextRandom)
import qualified Control.Concurrent.Capataz.Internal.Supervisor as Supervisor
import Control.Concurrent.Capataz.Internal.Types
import qualified Control.Concurrent.Capataz.Internal.Util as Util
--------------------------------------------------------------------------------
-- | Utility typeclass to call public supervision API with types
that contain a supervisor ( e.g. record ) .
class HasSupervisor a where
-- | Fetches a supervisor from a record internals.
getSupervisor :: a m -> Supervisor m
instance HasSupervisor Capataz where
getSupervisor Capataz {capatazSupervisor} = capatazSupervisor
instance HasSupervisor Supervisor where
getSupervisor = id
| Creates a record , which holds both a root supervisor and a
' Teardown ' to shut down the system . The root supervisor monitors failures on
-- process threads defined with 'supervisorProcessSpecList' or created
dynamically using ' forkWorker ' or ' ' .
forkCapataz
:: (MonadUnliftIO m, MonadIO m)
=> Text
-> (CapatazOptions m -> CapatazOptions m)
-> m (Capataz m)
forkCapataz capatazName modOptionsFn = do
capatazId <- liftIO UUID.nextRandom
supervisorId <- liftIO UUID.nextRandom
let
capatazOptions@CapatazOptions { notifyEvent } =
defCapatazOptions capatazName modOptionsFn
supervisorOptions@SupervisorOptions { supervisorName } =
Util.capatazOptionsToSupervisorOptions capatazOptions
parentSupervisorEnv = ParentSupervisorEnv
{ supervisorId = capatazId
, supervisorName = "capataz-root"
, supervisorNotify = \supervisorEvent -> do
eventTime <- getCurrentTime
case supervisorEvent of
MonitorEvent ProcessFailed' { processError } -> notifyEvent
CapatazFailed
{ supervisorId
, supervisorName
, eventTime
, supervisorError = processError
}
MonitorEvent ProcessTerminated'{} -> notifyEvent CapatazTerminated
{ supervisorId
, supervisorName
, eventTime
}
MonitorEvent ProcessCompleted'{} ->
error "Capataz completed; this should never happen"
MonitorEvent ProcessForcedRestart{} ->
error
"Capataz was restarted from a OneForAll strategy; this should never happen"
ControlAction{} ->
error "Capataz received a ControlAction message; bad implementation"
, notifyEvent
}
capatazSupervisor@Supervisor { supervisorEnv } <- Supervisor.supervisorMain
parentSupervisorEnv
supervisorOptions
supervisorId
0 -- initial restart count
capatazTeardown <- withRunInIO $ \run -> newTeardown
"capataz"
(run $ do
Supervisor.haltSupervisor "capataz system shutdown" supervisorEnv
eventTime <- getCurrentTime
notifyEvent CapatazTerminated {supervisorId , supervisorName , eventTime }
)
return Capataz {capatazSupervisor , capatazTeardown }
-- | Creates a green thread from an @IO ()@ sub-routine. Depending in options
defined in the ' WorkerOptions ' record , it will automatically restart this
-- sub-routine in case of failures.
--
-- See documentation of related functions:
--
-- * 'buildWorkerOptionsWithDefaults'
-- * 'buildWorkerOptions'
--
forkWorker
:: (MonadIO m, HasSupervisor supervisor)
=> WorkerOptions m -- ^ Worker options (restart, name, callbacks, etc)
-> supervisor m -- ^ 'Supervisor' that supervises the worker
-> m WorkerId -- ^ An identifier that can be used to terminate the 'Worker'
forkWorker workerOptions sup = do
let Supervisor { supervisorNotify } = getSupervisor sup
workerIdVar <- newEmptyMVar
supervisorNotify
(ControlAction ForkWorker
{ workerOptions
, returnWorkerId = putMVar workerIdVar
}
)
takeMVar workerIdVar
-- | Creates a green thread which monitors other green threads for failures and
-- restarts them using settings defined on 'SupervisorOptions'.
--
-- See documentation of related functions:
--
-- * 'buildSupervisorOptionsWithDefault'
-- * 'buildSupervisorOptions'
--
forkSupervisor
:: (MonadIO m, HasSupervisor parentSupervisor)
=> SupervisorOptions m -- ^ Supervisor options
-> parentSupervisor m -- ^ Parent supervisor instance that supervises new supervisor
-> m (Supervisor m) -- ^ A record used to dynamically create and supervise
-- other processes
forkSupervisor supervisorOptions parentSup = do
let Supervisor { supervisorNotify } = getSupervisor parentSup
supervisorVar <- newEmptyMVar
supervisorNotify
(ControlAction ForkSupervisor
{ supervisorOptions
, returnSupervisor = putMVar supervisorVar
}
)
takeMVar supervisorVar
-- | Stops the execution of a green thread being supervised by the given
-- supervisor.
--
-- __IMPORTANT__ If 'ProcessId' maps to a worker that is configured with a
-- 'Permanent' worker restart strategy, the worker green thread __will be
-- restarted again__.
--
terminateProcess
:: (MonadIO m, HasSupervisor supervisor)
=> Text
-> ProcessId
-> supervisor m
-> m Bool
terminateProcess processTerminationReason processId supervisor = do
let Supervisor { supervisorNotify } = getSupervisor supervisor
result <- newEmptyMVar
supervisorNotify
(ControlAction TerminateProcess
{ processId
, processTerminationReason
, notifyProcessTermination = putMVar result
}
)
takeMVar result
-- | Joins the thread of the root supervisor of the given capataz system to the
-- current thread.
joinCapatazThread :: MonadIO m => Capataz m -> m ()
joinCapatazThread Capataz { capatazSupervisor } =
let Supervisor { supervisorAsync } = capatazSupervisor
in wait supervisorAsync
| Terminates a ' ' system ( all supervised threads ) and returns a ' TeardownResult '
--
@since 0.2.0.0
terminateCapataz :: MonadIO m => Capataz m -> m TeardownResult
terminateCapataz = liftIO . runTeardown
| Terminates a ' ' system ( all supervised threads )
--
@since 0.2.0.0
terminateCapataz_ :: MonadIO m => Capataz m -> m ()
terminateCapataz_ = liftIO . runTeardown_
-- | Gets 'Teardown' record of this capataz system.
getCapatazTeardown :: Capataz m -> Teardown
getCapatazTeardown Capataz { capatazTeardown } = capatazTeardown
-- | Gets the 'Async' of a Supervisor thread.
--
-- NOTE: There is no way to get the 'Async' value of the root supervisor; this
-- is done on-purpose to avoid error scenarios.
getSupervisorAsync :: Supervisor m -> Async ()
getSupervisorAsync Supervisor { supervisorAsync } = supervisorAsync
-- | Gets the process identifier of a 'Supervisor'; normally used for termination.
getSupervisorProcessId :: Supervisor m -> ProcessId
getSupervisorProcessId Supervisor { supervisorId } = supervisorId
| null | https://raw.githubusercontent.com/roman/Haskell-capataz/0952178a8afdc41e86f3d3ff22fbb731bd21519e/src/Control/Concurrent/Capataz/Internal/Core.hs | haskell | # LANGUAGE RankNTypes #
| This module contains:
* Functions exported on the public API
* High level message handlers of the supervisor thread loop
------------------------------------------------------------------------------
| Utility typeclass to call public supervision API with types
| Fetches a supervisor from a record internals.
process threads defined with 'supervisorProcessSpecList' or created
initial restart count
| Creates a green thread from an @IO ()@ sub-routine. Depending in options
sub-routine in case of failures.
See documentation of related functions:
* 'buildWorkerOptionsWithDefaults'
* 'buildWorkerOptions'
^ Worker options (restart, name, callbacks, etc)
^ 'Supervisor' that supervises the worker
^ An identifier that can be used to terminate the 'Worker'
| Creates a green thread which monitors other green threads for failures and
restarts them using settings defined on 'SupervisorOptions'.
See documentation of related functions:
* 'buildSupervisorOptionsWithDefault'
* 'buildSupervisorOptions'
^ Supervisor options
^ Parent supervisor instance that supervises new supervisor
^ A record used to dynamically create and supervise
other processes
| Stops the execution of a green thread being supervised by the given
supervisor.
__IMPORTANT__ If 'ProcessId' maps to a worker that is configured with a
'Permanent' worker restart strategy, the worker green thread __will be
restarted again__.
| Joins the thread of the root supervisor of the given capataz system to the
current thread.
| Gets 'Teardown' record of this capataz system.
| Gets the 'Async' of a Supervisor thread.
NOTE: There is no way to get the 'Async' value of the root supervisor; this
is done on-purpose to avoid error scenarios.
| Gets the process identifier of a 'Supervisor'; normally used for termination. | # LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
module Control.Concurrent.Capataz.Internal.Core
(
HasSupervisor(..)
, forkWorker
, forkSupervisor
, forkCapataz
, terminateProcess
, terminateCapataz
, terminateCapataz_
, joinCapatazThread
, getSupervisorProcessId
, getSupervisorAsync
, getCapatazTeardown
)
where
import RIO
import Control.Teardown (Teardown, TeardownResult, newTeardown, runTeardown, runTeardown_)
import RIO.Time (getCurrentTime)
import qualified Data.UUID.V4 as UUID (nextRandom)
import qualified Control.Concurrent.Capataz.Internal.Supervisor as Supervisor
import Control.Concurrent.Capataz.Internal.Types
import qualified Control.Concurrent.Capataz.Internal.Util as Util
that contain a supervisor ( e.g. record ) .
class HasSupervisor a where
getSupervisor :: a m -> Supervisor m
instance HasSupervisor Capataz where
getSupervisor Capataz {capatazSupervisor} = capatazSupervisor
instance HasSupervisor Supervisor where
getSupervisor = id
| Creates a record , which holds both a root supervisor and a
' Teardown ' to shut down the system . The root supervisor monitors failures on
dynamically using ' forkWorker ' or ' ' .
forkCapataz
:: (MonadUnliftIO m, MonadIO m)
=> Text
-> (CapatazOptions m -> CapatazOptions m)
-> m (Capataz m)
forkCapataz capatazName modOptionsFn = do
capatazId <- liftIO UUID.nextRandom
supervisorId <- liftIO UUID.nextRandom
let
capatazOptions@CapatazOptions { notifyEvent } =
defCapatazOptions capatazName modOptionsFn
supervisorOptions@SupervisorOptions { supervisorName } =
Util.capatazOptionsToSupervisorOptions capatazOptions
parentSupervisorEnv = ParentSupervisorEnv
{ supervisorId = capatazId
, supervisorName = "capataz-root"
, supervisorNotify = \supervisorEvent -> do
eventTime <- getCurrentTime
case supervisorEvent of
MonitorEvent ProcessFailed' { processError } -> notifyEvent
CapatazFailed
{ supervisorId
, supervisorName
, eventTime
, supervisorError = processError
}
MonitorEvent ProcessTerminated'{} -> notifyEvent CapatazTerminated
{ supervisorId
, supervisorName
, eventTime
}
MonitorEvent ProcessCompleted'{} ->
error "Capataz completed; this should never happen"
MonitorEvent ProcessForcedRestart{} ->
error
"Capataz was restarted from a OneForAll strategy; this should never happen"
ControlAction{} ->
error "Capataz received a ControlAction message; bad implementation"
, notifyEvent
}
capatazSupervisor@Supervisor { supervisorEnv } <- Supervisor.supervisorMain
parentSupervisorEnv
supervisorOptions
supervisorId
capatazTeardown <- withRunInIO $ \run -> newTeardown
"capataz"
(run $ do
Supervisor.haltSupervisor "capataz system shutdown" supervisorEnv
eventTime <- getCurrentTime
notifyEvent CapatazTerminated {supervisorId , supervisorName , eventTime }
)
return Capataz {capatazSupervisor , capatazTeardown }
defined in the ' WorkerOptions ' record , it will automatically restart this
forkWorker
:: (MonadIO m, HasSupervisor supervisor)
forkWorker workerOptions sup = do
let Supervisor { supervisorNotify } = getSupervisor sup
workerIdVar <- newEmptyMVar
supervisorNotify
(ControlAction ForkWorker
{ workerOptions
, returnWorkerId = putMVar workerIdVar
}
)
takeMVar workerIdVar
forkSupervisor
:: (MonadIO m, HasSupervisor parentSupervisor)
forkSupervisor supervisorOptions parentSup = do
let Supervisor { supervisorNotify } = getSupervisor parentSup
supervisorVar <- newEmptyMVar
supervisorNotify
(ControlAction ForkSupervisor
{ supervisorOptions
, returnSupervisor = putMVar supervisorVar
}
)
takeMVar supervisorVar
terminateProcess
:: (MonadIO m, HasSupervisor supervisor)
=> Text
-> ProcessId
-> supervisor m
-> m Bool
terminateProcess processTerminationReason processId supervisor = do
let Supervisor { supervisorNotify } = getSupervisor supervisor
result <- newEmptyMVar
supervisorNotify
(ControlAction TerminateProcess
{ processId
, processTerminationReason
, notifyProcessTermination = putMVar result
}
)
takeMVar result
joinCapatazThread :: MonadIO m => Capataz m -> m ()
joinCapatazThread Capataz { capatazSupervisor } =
let Supervisor { supervisorAsync } = capatazSupervisor
in wait supervisorAsync
| Terminates a ' ' system ( all supervised threads ) and returns a ' TeardownResult '
@since 0.2.0.0
terminateCapataz :: MonadIO m => Capataz m -> m TeardownResult
terminateCapataz = liftIO . runTeardown
| Terminates a ' ' system ( all supervised threads )
@since 0.2.0.0
terminateCapataz_ :: MonadIO m => Capataz m -> m ()
terminateCapataz_ = liftIO . runTeardown_
getCapatazTeardown :: Capataz m -> Teardown
getCapatazTeardown Capataz { capatazTeardown } = capatazTeardown
getSupervisorAsync :: Supervisor m -> Async ()
getSupervisorAsync Supervisor { supervisorAsync } = supervisorAsync
getSupervisorProcessId :: Supervisor m -> ProcessId
getSupervisorProcessId Supervisor { supervisorId } = supervisorId
|
fc095efe2223dbb2070c864b341d57dbf87ba82ba1883b1ee2beb7a90fd16ab6 | vnarek/jude | matcher.ml | type message = string * bytes
type match_result = Matched | Next
type t = message -> match_result
let case (type a) (m : a Binable.m) fn (digest, msg) =
match Binable.from_bytes m ~digest msg with
| Error str ->
Log.debug (fun m -> m "case error: %s" str);
Next
| Ok a ->
fn a;
Matched
let rec react (matchers : t list) messages =
match matchers with
| [] -> Next
| m :: rest -> (
match m messages with Next -> react rest messages | Matched -> Matched )
let any fn message =
fn message;
Matched
let sink = any ignore
let block _ = Next
| null | https://raw.githubusercontent.com/vnarek/jude/b1e9387d0242cd83b3b72695bce267c970de1857/lib/matcher.ml | ocaml | type message = string * bytes
type match_result = Matched | Next
type t = message -> match_result
let case (type a) (m : a Binable.m) fn (digest, msg) =
match Binable.from_bytes m ~digest msg with
| Error str ->
Log.debug (fun m -> m "case error: %s" str);
Next
| Ok a ->
fn a;
Matched
let rec react (matchers : t list) messages =
match matchers with
| [] -> Next
| m :: rest -> (
match m messages with Next -> react rest messages | Matched -> Matched )
let any fn message =
fn message;
Matched
let sink = any ignore
let block _ = Next
| |
717b02cdb563478472e8d0567482b37e98c647146f10c150ec414cd2c3d31a8d | vehicle-lang/vehicle | Core.hs | module Vehicle.Verify.Core where
import Vehicle.Prelude
data VerifierIdentifier
= Marabou
deriving (Eq, Ord, Show, Read, Bounded, Enum)
instance Pretty VerifierIdentifier where
pretty = pretty . show
-- | Location of a verifier query file.
type QueryFile = FilePath
-- | Location of the verifier executable file
type VerifierExecutable = FilePath
| null | https://raw.githubusercontent.com/vehicle-lang/vehicle/b8a5bb89a84def465d8ac74f73719f54ae02f562/vehicle/src/Vehicle/Verify/Core.hs | haskell | | Location of a verifier query file.
| Location of the verifier executable file | module Vehicle.Verify.Core where
import Vehicle.Prelude
data VerifierIdentifier
= Marabou
deriving (Eq, Ord, Show, Read, Bounded, Enum)
instance Pretty VerifierIdentifier where
pretty = pretty . show
type QueryFile = FilePath
type VerifierExecutable = FilePath
|
88f3a09cf1630a01aa0851663588fe6640b9175e9af7b92a267047e8b885ecf5 | nixeagle/cl-irc | protocol.lisp | $ Id$
;;;; $Source$
;;;; See LICENSE for licensing information.
(in-package :irc)
;;
;; Condition
;;
(define-condition no-such-reply ()
((reply-number
:reader reply-number
:initarg :reply-number))
(:report (lambda (condition stream)
(format stream "No such reply ~A." (reply-number condition)))))
;;
Connection
;;
(defclass connection ()
((user
:initarg :user
:accessor user)
(server-name
:initarg :server-name
:accessor server-name
:initform "Unknown server")
(server-stream
:initarg :server-stream
:accessor server-stream
:documentation "Stream used to talk to the IRC server.")
(server-capabilities
:initform *default-isupport-values*
:accessor server-capabilities
:documentation "Assoc array for rpl_isupport message;
see -brocklesby-irc-isupport-03.txt")
(client-stream
:initarg :client-stream
:accessor client-stream
:initform t
:documentation "Messages coming back from the server is sent to
this stream.")
(channels
:initarg :channels
:accessor channels
:initform (make-hash-table :test #'equal))
(hooks
:initarg :hooks
:accessor hooks
:initform (make-hash-table :test #'equal))
(users
:initarg :users
:accessor users
:initform (make-hash-table :test #'equal))))
(defmethod print-object ((object connection) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(princ (server-name object) stream)))
(defgeneric add-default-hooks (connection))
(defgeneric client-raw-log (connection message))
(defgeneric connectedp (connection))
(defgeneric read-message (connection))
(defgeneric start-process (function name))
(defgeneric start-background-message-handler (connection))
(defgeneric read-message-loop (connection))
(defgeneric read-irc-message (connection))
(defgeneric send-irc-message (connection command
&optional trailing-argument &rest arguments))
(defgeneric get-hooks (connection class))
(defgeneric add-hook (connection class hook))
(defgeneric remove-hook (connection class hook))
(defgeneric remove-hooks (connection class))
(defgeneric remove-all-hooks (connection))
(defgeneric case-map-name (connection))
(defgeneric re-apply-case-mapping (connection))
(defun make-connection (&key (user nil)
(server-name "")
(server-stream nil)
(client-stream t)
(hooks nil))
(let ((connection (make-instance 'connection
:user user
:server-name server-name
:server-stream server-stream
:client-stream client-stream)))
(dolist (hook hooks)
(add-hook connection (car hook) (cadr hook)))
connection))
(defmethod add-default-hooks ((connection connection))
(dolist (message '(irc-rpl_isupport-message
irc-rpl_whoisuser-message
irc-rpl_list-message
irc-rpl_topic-message
irc-rpl_namreply-message
irc-ping-message
irc-join-message
irc-topic-message
irc-part-message
irc-quit-message
irc-kick-message
irc-nick-message
ctcp-time-message
ctcp-source-message
ctcp-finger-message
ctcp-version-message
ctcp-ping-message))
(add-hook connection message #'default-hook)))
(defmethod client-raw-log ((connection connection) message)
(let ((stream (client-stream connection)))
(format stream (format nil "RAW LOG: ~A~%" message))
(force-output stream)))
(defmethod connectedp ((connection connection))
"Returns t if `connection' is connected to a server and is ready for
input."
(let ((stream (server-stream connection)))
(and (streamp stream)
(open-stream-p stream))))
(define-condition invalidate-me (condition)
((stream :initarg :stream
:reader invalidate-me-stream)
(condition :initarg :condition
:reader invalidate-me-condition)))
(defmethod read-message ((connection connection))
(let ((read-more-p t))
(handler-case
(progn
(when (and (connectedp connection) read-more-p)
(let ((message (read-irc-message connection)))
(when *debug-p*
(format *debug-stream* "~A" (describe message)))
(irc-message-event message)
message))) ; needed because of the "loop while" in read-message-loop
(stream-error (c) (setf read-more-p nil)
(signal 'invalidate-me :stream
(server-stream connection)
:condition c)))))
(defvar *process-count* 0)
(defmethod start-process (function name)
#+allegro (mp:process-run-function name function)
#+cmu (mp:make-process function :name name)
#+lispworks (mp:process-run-function name nil function)
#+sb-thread (sb-thread:make-thread function)
#+openmcl (ccl:process-run-function name function)
#+armedbear (ext:make-thread function))
(defmethod start-background-message-handler ((connection connection))
"Read messages from the `connection', parse them and dispatch
irc-message-event on them. Returns background process ID if available."
(flet ((do-loop () (read-message-loop connection)))
(let ((name (format nil "irc-hander-~D" (incf *process-count*))))
#+(or allegro cmu lispworks sb-thread openmcl armedbear)
(start-process #'do-loop name)
#+(and sbcl (not sb-thread))
(sb-sys:add-fd-handler (sb-sys:fd-stream-fd
(server-stream connection))
:input (lambda (fd)
(declare (ignore fd))
(handler-case
(read-message connection)
(invalidate-me (c)
(sb-sys:invalidate-descriptor
(sb-sys:fd-stream-fd
(invalidate-me-stream c)))
(format t "Socket closed: ~A~%"
(invalidate-me-condition c)))))))))
(defun stop-background-message-handler (process)
"Stops a background message handler process returned by the start function."
#+cmu (mp:destroy-process process)
#+allegro (mp:process-kill process)
#+sb-thread (sb-thread:destroy-thread process)
#+lispworks (mp:process-kill process)
#+openmcl (ccl:process-kill process)
#+armedbear (ext:destroy-thread process))
(defmethod read-message-loop ((connection connection))
(loop while (read-message connection)))
(defmethod read-irc-message ((connection connection))
"Read and parse an IRC-message from the `connection'."
(let ((message (create-irc-message
(read-line (server-stream connection) t))))
(setf (connection message) connection)
message))
(defmethod send-irc-message ((connection connection) command
&optional trailing-argument &rest arguments)
"Turn the arguments into a valid IRC message and send it to the
server, via the `connection'."
(let ((raw-message (make-irc-message command
:arguments arguments
:trailing-argument trailing-argument)))
(write-sequence raw-message (server-stream connection))
(force-output (server-stream connection))
raw-message))
(defmethod get-hooks ((connection connection) (class symbol))
"Return a list of all hooks for `class'."
(gethash class (hooks connection)))
(defmethod add-hook ((connection connection) class hook)
"Add `hook' to `class'."
(setf (gethash class (hooks connection))
(pushnew hook (gethash class (hooks connection)))))
(defmethod remove-hook ((connection connection) class hook)
"Remove `hook' from `class'."
(setf (gethash class (hooks connection))
(delete hook (gethash class (hooks connection)))))
(defmethod remove-hooks ((connection connection) class)
"Remove all hooks for `class'."
(setf (gethash class (hooks connection)) nil))
(defmethod remove-all-hooks ((connection connection))
(clrhash (hooks connection)))
(defmethod case-map-name ((connection connection))
(let ((case-mapping (assoc "CASEMAPPING" (server-capabilities connection)
:test #'equal)))
(intern (string-upcase (second case-mapping)) (find-package "KEYWORD"))))
(defmethod re-apply-case-mapping ((connection connection))
(setf (normalized-nickname (user connection))
(normalize-nickname connection (nickname (user connection))))
(flet ((set-new-users-hash (object)
(let ((new-users (make-hash-table :test #'equal)))
(maphash
#'(lambda (norm-nick user)
(declare (ignore norm-nick))
(setf (gethash
(setf (normalized-nickname user)
(normalize-nickname connection
(nickname user)))
new-users) user))
(users object))
(setf (users object) new-users))))
(set-new-users-hash connection)
(let ((new-channels (make-hash-table :test #'equal)))
(maphash #'(lambda (norm-name channel)
(declare (ignore norm-name))
(setf (gethash
(setf (normalized-channel-name channel)
(normalize-channel-name connection
(name channel)))
new-channels) channel)
(set-new-users-hash channel))
(channels connection))
(setf (channels connection) new-channels))))
;;
DCC Connection
;;
(defclass dcc-connection ()
((user
:initarg :user
:accessor user
:documentation "The user at the other end of this connection. The
user at this end can be reached via your normal connection object.")
(stream
:initarg :stream
:accessor dcc-stream)
(output-stream
:initarg :output-stream
:accessor output-stream
:initform t)
(socket
:initarg :socket
:accessor socket
:documentation "The actual socket object for the connection
between the two users.")))
(defmethod print-object ((object dcc-connection) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(if (user object)
(format stream "with ~A@~A"
(nickname (user object))
(hostname (user object)))
"")))
(defun make-dcc-connection (&key (user nil)
(remote-address nil)
(remote-port nil)
(output-stream t))
#+sbcl
(let ((socket (sb-bsd-sockets:make-inet-socket :stream :tcp)))
(sb-bsd-sockets:socket-connect socket remote-address remote-port)
(make-instance 'dcc-connection
:user user
:stream (sb-bsd-sockets:socket-make-stream socket :input t :output t :buffering :none)
:socket socket
:output-stream t))
#+openmcl
(let ((socket-stream (ccl:make-socket :remote-host remote-address
:remote-port remote-port)))
(make-instance 'dcc-connection
:user user
:stream socket-stream
:output-stream output-stream))
#-(or openmcl sbcl)
(warn "make-dcc-connection not supported for this implementation."))
(defgeneric dcc-close (connection))
(defgeneric send-dcc-message (connection message))
(defmethod read-message ((connection dcc-connection))
(let ((message (read-line (dcc-stream connection))))
(format (output-stream connection) "~A~%" message)
(force-output (output-stream connection))
message))
(defmethod read-message-loop ((connection dcc-connection))
(loop while (read-message connection)))
(defmethod send-dcc-message ((connection dcc-connection) message)
(format (dcc-stream connection) "~A~%" message))
;; argh. I want to name this quit but that gives me issues with
;; generic functions. need to resolve.
(defmethod dcc-close ((connection dcc-connection))
(close (dcc-stream connection))
(setf (user connection) nil)
(setf *dcc-connections* (remove connection *dcc-connections*))
#+sbcl (sb-bsd-sockets:socket-close (socket connection))
)
(defmethod connectedp ((connection dcc-connection))
(let ((stream (dcc-stream connection)))
(and (streamp stream)
(open-stream-p stream))))
;;
;; Channel
;;
(defclass channel ()
((name
:initarg :name
:accessor name)
(normalized-name
:initarg :normalized-name
:accessor normalized-name)
(topic
:initarg :topic
:accessor topic)
(modes
:initarg :modes
:accessor modes
:initform nil)
(users
:initarg :users
:accessor users
:initform (make-hash-table :test #'equal))
(user-count
:initarg :user-count
:accessor user-count
:initform nil
:documentation "May not represent the real number of users in the
channel. Rather, the number returned from the LIST command gets stuck
in there so the user of this library can use it for searching
channels, for instance. If the value is NIL then the slot has not
been populated by a LIST command.")))
(defmethod print-object ((object channel) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(princ (name object) stream)))
(defun normalize-channel-name (connection string)
"Normalize `string' so that it represents an all-downcased channel
name."
(irc-string-downcase (case-map-name connection) string))
(defun make-channel (connection
&key (name "")
(topic "")
(modes nil)
(users nil)
(user-count nil))
(let ((channel
(make-instance 'channel
:name name
:normalized-name
(normalize-channel-name connection name)
:topic topic
:modes modes
:user-count user-count)))
(dolist (user users)
(add-user channel user))
channel))
(defgeneric find-channel (connection channel))
(defgeneric remove-all-channels (connection))
(defgeneric add-channel (connection channel))
(defgeneric remove-channel (connection channel))
(defgeneric remove-users (channel))
(defmethod find-channel ((connection connection) (channel string))
"Return channel as designated by `channel'. If no such channel can
be found, return nil."
(let ((channel-name (normalize-channel-name connection channel)))
(gethash channel-name (channels connection))))
(defmethod remove-all-channels ((connection connection))
"Remove all channels known to `connection'."
(clrhash (channels connection)))
(defmethod add-channel ((connection connection) (channel channel))
"Add `channel' to `connection'."
(setf (gethash (normalized-name channel) (channels connection)) channel))
(defmethod remove-channel ((connection connection) (channel channel))
"Remove `channel' from `connection'."
(remhash (normalized-name channel) (channels connection)))
(defmethod remove-users ((channel channel))
"Remove all users on `channel'."
(clrhash (users channel)))
;;
;; User
;;
(defclass user ()
((nickname
:initarg :nickname
:accessor nickname
:initform "")
(normalized-nickname
:initarg :normalized-nickname
:accessor normalized-nickname
:initform "")
(username
:initarg :username
:accessor username
:initform "")
(hostname
:initarg :hostname
:accessor hostname
:initform "")
(realname
:initarg :realname
:accessor realname
:initform "")
(channels
:initarg :channels
:accessor channels
:initform nil)))
(defmethod print-object ((object user) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A!~A@~A \"~A\""
(nickname object)
(username object)
(hostname object)
(realname object))))
(defun make-user (connection
&key (nickname "")
(username "")
(hostname "")
(realname ""))
(make-instance 'user
:nickname nickname
:normalized-nickname (normalize-nickname connection nickname)
:username username
:hostname hostname
:realname realname))
(defun canonicalize-nickname (connection nickname)
(if (find (char nickname 0)
(parse-isupport-prefix-argument
(second (assoc "PREFIX"
(server-capabilities connection)
:test #'string=))))
(subseq nickname 1)
nickname))
(defun normalize-nickname (connection string)
"Normalize `string' so that represents an all-downcased IRC
nickname."
(irc-string-downcase (case-map-name connection) string))
(defgeneric find-user (connection nickname))
(defgeneric add-user (object user))
(defgeneric remove-all-users (connection))
(defgeneric remove-user (object user))
(defgeneric remove-user-everywhere (connection user))
(defgeneric find-or-make-user (connection nickname
&key username hostname realname))
(defgeneric change-nickname (connection user new-nickname))
(defmethod find-user ((connection connection) (nickname string))
"Return user as designated by `nickname' or nil if no such user is
known."
(let ((nickname (normalize-nickname connection nickname)))
(or (gethash nickname (users connection))
(when (string= nickname (nickname (user connection)))
(user connection)))))
; what if the user is not on any channels?
(defmethod add-user ((connection connection) (user user))
"Add `user' to `connection'."
(setf (gethash (normalized-nickname user) (users connection)) user))
(defmethod add-user ((channel channel) (user user))
(setf (gethash (normalized-nickname user) (users channel)) user)
(pushnew channel (channels user)))
(defmethod remove-all-users ((connection connection))
"Remove all users known to `connection'."
(clrhash (users connection)))
(defmethod remove-user ((channel channel) (user user))
"Remove `user' from `channel' and `channel' from `user'."
(remhash (normalized-nickname user) (users channel))
(setf (channels user) (remove channel (channels user))))
(defmethod remove-channel ((channel channel) (user user))
"Remove `channel' from `user'."
(warn
(concatenate 'string
"use of depricated API (remove-channel channel user): "
"(remove-channel user channel) is now preferred"))
(remove-channel user channel))
(defmethod remove-channel ((user user) (channel channel))
"Remove `channel' from `user'."
(setf (channels user) (remove channel (channels user))))
(defmethod remove-user ((connection connection) (user user))
"Remove `user' from `connection' but leave user in any channels he
may be already be on."
(remhash (normalized-nickname user) (users connection)))
(defmethod remove-user-everywhere ((connection connection) (user user))
"Remove `user' anywhere present in the `connection'."
(dolist (channel (channels user))
(remove-user channel user))
(remove-user connection user))
(defmethod find-or-make-user ((connection connection) nickname &key (username "")
(hostname "") (realname ""))
(or (find-user connection nickname)
(make-user connection
:nickname nickname
:username username
:hostname hostname
:realname realname)))
(defmethod change-nickname ((connection connection) (user user) new-nickname)
(let ((new-user user)
(channels (channels user)))
(remove-user connection user)
(setf (nickname new-user) new-nickname)
(setf (normalized-nickname new-user)
(normalize-nickname connection new-nickname))
(dolist (channel channels)
(remove-user channel user)
(add-user channel new-user))
(add-user connection user)
new-user))
;; IRC Message
;;
(defclass irc-message ()
((source
:accessor source
:initarg :source
:type string)
(user
:accessor user
:initarg :user)
(host
:accessor host
:initarg :host
:type string)
(command
:accessor command
:initarg :command
:type string)
(arguments
:accessor arguments
:initarg :arguments
:type list)
(trailing-argument
:accessor trailing-argument
:initarg :trailing-argument
:type string)
(connection
:accessor connection
:initarg :connection)
(received-time
:accessor received-time
:initarg :received-time)
(raw-message-string
:accessor raw-message-string
:initarg :raw-message-string
:type string)))
(defmethod print-object ((object irc-message) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A ~A" (source object) (command object))))
(defgeneric self-message-p (message))
(defgeneric find-irc-message-class (type))
(defgeneric client-log (connection message &optional prefix))
(defgeneric apply-to-hooks (message))
(defmethod self-message-p ((message irc-message))
"Did we send this message?"
(string-equal (source message)
(nickname (user (connection message)))))
(defclass irc-error-reply (irc-message) ())
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun intern-message-symbol (prefix name)
"Intern based on symbol-name to support case-sensitive mlisp"
(intern
(concatenate 'string
(symbol-name prefix)
"-"
(symbol-name name)
"-"
(symbol-name '#:message))))
(defun define-irc-message (command)
(let ((name (intern-message-symbol :irc command)))
`(progn
(defmethod find-irc-message-class ((type (eql ,command)))
(find-class ',name))
(export ',name)
(defclass ,name (irc-message) ())))))
(defmacro create-irc-message-classes (class-list)
`(progn ,@(mapcar #'define-irc-message class-list)))
;; should perhaps wrap this in an eval-when?
(create-irc-message-classes #.(remove-duplicates (mapcar #'second *reply-names*)))
(create-irc-message-classes (:privmsg :notice :kick :topic :error :mode :ping
:nick :join :part :quit :kill :pong :invite))
(defmethod find-irc-message-class (type)
(declare (ignore type))
(find-class 'irc-message))
(defmethod client-log ((connection connection) (message irc-message) &optional (prefix ""))
(let ((stream (client-stream connection)))
(format stream "~A~A: ~A: ~A~{ ~A~} \"~A\"~%"
prefix
(received-time message)
(command message)
(source message)
(arguments message)
(trailing-argument message))
(force-output stream)))
(defmethod apply-to-hooks ((message irc-message))
(let ((connection (connection message)))
(dolist (hook (get-hooks connection (class-name (class-of message))))
(funcall hook message))))
;;
;; CTCP Message
;;
(defclass ctcp-mixin ()
((ctcp-command
:initarg :ctcp-command
:accessor ctcp-command)))
(defclass standard-ctcp-message (ctcp-mixin irc-message) ())
(defgeneric find-ctcp-message-class (type))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun define-ctcp-message (ctcp-command)
(let ((name (intern-message-symbol :ctcp ctcp-command)))
`(progn
(defmethod find-ctcp-message-class ((type (eql ,ctcp-command)))
(find-class ',name))
(export ',name)
(defclass ,name (ctcp-mixin irc-message) ())))))
(defmacro create-ctcp-message-classes (class-list)
`(progn ,@(mapcar #'define-ctcp-message class-list)))
;; should perhaps wrap this in an eval-when?
(create-ctcp-message-classes (:action :source :finger :ping
:version :userinfo :time :dcc-chat-request
:dcc-send-request))
(defmethod find-ctcp-message-class (type)
(declare (ignore type))
(find-class 'standard-ctcp-message))
(defmethod client-log ((connection connection) (message ctcp-mixin) &optional (prefix ""))
(let ((stream (client-stream connection)))
(format stream "~A~A: ~A (~A): ~A~{ ~A~} \"~A\"~%"
prefix
(received-time message)
(command message)
(ctcp-command message)
(source message)
(arguments message)
(trailing-argument message))
(force-output stream)))
| null | https://raw.githubusercontent.com/nixeagle/cl-irc/efaea15f2962107ea9b1a2fad5cd9db492b4247b/tags/debian_version_0_6_3/protocol.lisp | lisp | $Source$
See LICENSE for licensing information.
Condition
needed because of the "loop while" in read-message-loop
argh. I want to name this quit but that gives me issues with
generic functions. need to resolve.
Channel
User
what if the user is not on any channels?
IRC Message
should perhaps wrap this in an eval-when?
CTCP Message
should perhaps wrap this in an eval-when? | $ Id$
(in-package :irc)
(define-condition no-such-reply ()
((reply-number
:reader reply-number
:initarg :reply-number))
(:report (lambda (condition stream)
(format stream "No such reply ~A." (reply-number condition)))))
Connection
(defclass connection ()
((user
:initarg :user
:accessor user)
(server-name
:initarg :server-name
:accessor server-name
:initform "Unknown server")
(server-stream
:initarg :server-stream
:accessor server-stream
:documentation "Stream used to talk to the IRC server.")
(server-capabilities
:initform *default-isupport-values*
:accessor server-capabilities
see -brocklesby-irc-isupport-03.txt")
(client-stream
:initarg :client-stream
:accessor client-stream
:initform t
:documentation "Messages coming back from the server is sent to
this stream.")
(channels
:initarg :channels
:accessor channels
:initform (make-hash-table :test #'equal))
(hooks
:initarg :hooks
:accessor hooks
:initform (make-hash-table :test #'equal))
(users
:initarg :users
:accessor users
:initform (make-hash-table :test #'equal))))
(defmethod print-object ((object connection) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(princ (server-name object) stream)))
(defgeneric add-default-hooks (connection))
(defgeneric client-raw-log (connection message))
(defgeneric connectedp (connection))
(defgeneric read-message (connection))
(defgeneric start-process (function name))
(defgeneric start-background-message-handler (connection))
(defgeneric read-message-loop (connection))
(defgeneric read-irc-message (connection))
(defgeneric send-irc-message (connection command
&optional trailing-argument &rest arguments))
(defgeneric get-hooks (connection class))
(defgeneric add-hook (connection class hook))
(defgeneric remove-hook (connection class hook))
(defgeneric remove-hooks (connection class))
(defgeneric remove-all-hooks (connection))
(defgeneric case-map-name (connection))
(defgeneric re-apply-case-mapping (connection))
(defun make-connection (&key (user nil)
(server-name "")
(server-stream nil)
(client-stream t)
(hooks nil))
(let ((connection (make-instance 'connection
:user user
:server-name server-name
:server-stream server-stream
:client-stream client-stream)))
(dolist (hook hooks)
(add-hook connection (car hook) (cadr hook)))
connection))
(defmethod add-default-hooks ((connection connection))
(dolist (message '(irc-rpl_isupport-message
irc-rpl_whoisuser-message
irc-rpl_list-message
irc-rpl_topic-message
irc-rpl_namreply-message
irc-ping-message
irc-join-message
irc-topic-message
irc-part-message
irc-quit-message
irc-kick-message
irc-nick-message
ctcp-time-message
ctcp-source-message
ctcp-finger-message
ctcp-version-message
ctcp-ping-message))
(add-hook connection message #'default-hook)))
(defmethod client-raw-log ((connection connection) message)
(let ((stream (client-stream connection)))
(format stream (format nil "RAW LOG: ~A~%" message))
(force-output stream)))
(defmethod connectedp ((connection connection))
"Returns t if `connection' is connected to a server and is ready for
input."
(let ((stream (server-stream connection)))
(and (streamp stream)
(open-stream-p stream))))
(define-condition invalidate-me (condition)
((stream :initarg :stream
:reader invalidate-me-stream)
(condition :initarg :condition
:reader invalidate-me-condition)))
(defmethod read-message ((connection connection))
(let ((read-more-p t))
(handler-case
(progn
(when (and (connectedp connection) read-more-p)
(let ((message (read-irc-message connection)))
(when *debug-p*
(format *debug-stream* "~A" (describe message)))
(irc-message-event message)
(stream-error (c) (setf read-more-p nil)
(signal 'invalidate-me :stream
(server-stream connection)
:condition c)))))
(defvar *process-count* 0)
(defmethod start-process (function name)
#+allegro (mp:process-run-function name function)
#+cmu (mp:make-process function :name name)
#+lispworks (mp:process-run-function name nil function)
#+sb-thread (sb-thread:make-thread function)
#+openmcl (ccl:process-run-function name function)
#+armedbear (ext:make-thread function))
(defmethod start-background-message-handler ((connection connection))
"Read messages from the `connection', parse them and dispatch
irc-message-event on them. Returns background process ID if available."
(flet ((do-loop () (read-message-loop connection)))
(let ((name (format nil "irc-hander-~D" (incf *process-count*))))
#+(or allegro cmu lispworks sb-thread openmcl armedbear)
(start-process #'do-loop name)
#+(and sbcl (not sb-thread))
(sb-sys:add-fd-handler (sb-sys:fd-stream-fd
(server-stream connection))
:input (lambda (fd)
(declare (ignore fd))
(handler-case
(read-message connection)
(invalidate-me (c)
(sb-sys:invalidate-descriptor
(sb-sys:fd-stream-fd
(invalidate-me-stream c)))
(format t "Socket closed: ~A~%"
(invalidate-me-condition c)))))))))
(defun stop-background-message-handler (process)
"Stops a background message handler process returned by the start function."
#+cmu (mp:destroy-process process)
#+allegro (mp:process-kill process)
#+sb-thread (sb-thread:destroy-thread process)
#+lispworks (mp:process-kill process)
#+openmcl (ccl:process-kill process)
#+armedbear (ext:destroy-thread process))
(defmethod read-message-loop ((connection connection))
(loop while (read-message connection)))
(defmethod read-irc-message ((connection connection))
"Read and parse an IRC-message from the `connection'."
(let ((message (create-irc-message
(read-line (server-stream connection) t))))
(setf (connection message) connection)
message))
(defmethod send-irc-message ((connection connection) command
&optional trailing-argument &rest arguments)
"Turn the arguments into a valid IRC message and send it to the
server, via the `connection'."
(let ((raw-message (make-irc-message command
:arguments arguments
:trailing-argument trailing-argument)))
(write-sequence raw-message (server-stream connection))
(force-output (server-stream connection))
raw-message))
(defmethod get-hooks ((connection connection) (class symbol))
"Return a list of all hooks for `class'."
(gethash class (hooks connection)))
(defmethod add-hook ((connection connection) class hook)
"Add `hook' to `class'."
(setf (gethash class (hooks connection))
(pushnew hook (gethash class (hooks connection)))))
(defmethod remove-hook ((connection connection) class hook)
"Remove `hook' from `class'."
(setf (gethash class (hooks connection))
(delete hook (gethash class (hooks connection)))))
(defmethod remove-hooks ((connection connection) class)
"Remove all hooks for `class'."
(setf (gethash class (hooks connection)) nil))
(defmethod remove-all-hooks ((connection connection))
(clrhash (hooks connection)))
(defmethod case-map-name ((connection connection))
(let ((case-mapping (assoc "CASEMAPPING" (server-capabilities connection)
:test #'equal)))
(intern (string-upcase (second case-mapping)) (find-package "KEYWORD"))))
(defmethod re-apply-case-mapping ((connection connection))
(setf (normalized-nickname (user connection))
(normalize-nickname connection (nickname (user connection))))
(flet ((set-new-users-hash (object)
(let ((new-users (make-hash-table :test #'equal)))
(maphash
#'(lambda (norm-nick user)
(declare (ignore norm-nick))
(setf (gethash
(setf (normalized-nickname user)
(normalize-nickname connection
(nickname user)))
new-users) user))
(users object))
(setf (users object) new-users))))
(set-new-users-hash connection)
(let ((new-channels (make-hash-table :test #'equal)))
(maphash #'(lambda (norm-name channel)
(declare (ignore norm-name))
(setf (gethash
(setf (normalized-channel-name channel)
(normalize-channel-name connection
(name channel)))
new-channels) channel)
(set-new-users-hash channel))
(channels connection))
(setf (channels connection) new-channels))))
DCC Connection
(defclass dcc-connection ()
((user
:initarg :user
:accessor user
:documentation "The user at the other end of this connection. The
user at this end can be reached via your normal connection object.")
(stream
:initarg :stream
:accessor dcc-stream)
(output-stream
:initarg :output-stream
:accessor output-stream
:initform t)
(socket
:initarg :socket
:accessor socket
:documentation "The actual socket object for the connection
between the two users.")))
(defmethod print-object ((object dcc-connection) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(if (user object)
(format stream "with ~A@~A"
(nickname (user object))
(hostname (user object)))
"")))
(defun make-dcc-connection (&key (user nil)
(remote-address nil)
(remote-port nil)
(output-stream t))
#+sbcl
(let ((socket (sb-bsd-sockets:make-inet-socket :stream :tcp)))
(sb-bsd-sockets:socket-connect socket remote-address remote-port)
(make-instance 'dcc-connection
:user user
:stream (sb-bsd-sockets:socket-make-stream socket :input t :output t :buffering :none)
:socket socket
:output-stream t))
#+openmcl
(let ((socket-stream (ccl:make-socket :remote-host remote-address
:remote-port remote-port)))
(make-instance 'dcc-connection
:user user
:stream socket-stream
:output-stream output-stream))
#-(or openmcl sbcl)
(warn "make-dcc-connection not supported for this implementation."))
(defgeneric dcc-close (connection))
(defgeneric send-dcc-message (connection message))
(defmethod read-message ((connection dcc-connection))
(let ((message (read-line (dcc-stream connection))))
(format (output-stream connection) "~A~%" message)
(force-output (output-stream connection))
message))
(defmethod read-message-loop ((connection dcc-connection))
(loop while (read-message connection)))
(defmethod send-dcc-message ((connection dcc-connection) message)
(format (dcc-stream connection) "~A~%" message))
(defmethod dcc-close ((connection dcc-connection))
(close (dcc-stream connection))
(setf (user connection) nil)
(setf *dcc-connections* (remove connection *dcc-connections*))
#+sbcl (sb-bsd-sockets:socket-close (socket connection))
)
(defmethod connectedp ((connection dcc-connection))
(let ((stream (dcc-stream connection)))
(and (streamp stream)
(open-stream-p stream))))
(defclass channel ()
((name
:initarg :name
:accessor name)
(normalized-name
:initarg :normalized-name
:accessor normalized-name)
(topic
:initarg :topic
:accessor topic)
(modes
:initarg :modes
:accessor modes
:initform nil)
(users
:initarg :users
:accessor users
:initform (make-hash-table :test #'equal))
(user-count
:initarg :user-count
:accessor user-count
:initform nil
:documentation "May not represent the real number of users in the
channel. Rather, the number returned from the LIST command gets stuck
in there so the user of this library can use it for searching
channels, for instance. If the value is NIL then the slot has not
been populated by a LIST command.")))
(defmethod print-object ((object channel) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(princ (name object) stream)))
(defun normalize-channel-name (connection string)
"Normalize `string' so that it represents an all-downcased channel
name."
(irc-string-downcase (case-map-name connection) string))
(defun make-channel (connection
&key (name "")
(topic "")
(modes nil)
(users nil)
(user-count nil))
(let ((channel
(make-instance 'channel
:name name
:normalized-name
(normalize-channel-name connection name)
:topic topic
:modes modes
:user-count user-count)))
(dolist (user users)
(add-user channel user))
channel))
(defgeneric find-channel (connection channel))
(defgeneric remove-all-channels (connection))
(defgeneric add-channel (connection channel))
(defgeneric remove-channel (connection channel))
(defgeneric remove-users (channel))
(defmethod find-channel ((connection connection) (channel string))
"Return channel as designated by `channel'. If no such channel can
be found, return nil."
(let ((channel-name (normalize-channel-name connection channel)))
(gethash channel-name (channels connection))))
(defmethod remove-all-channels ((connection connection))
"Remove all channels known to `connection'."
(clrhash (channels connection)))
(defmethod add-channel ((connection connection) (channel channel))
"Add `channel' to `connection'."
(setf (gethash (normalized-name channel) (channels connection)) channel))
(defmethod remove-channel ((connection connection) (channel channel))
"Remove `channel' from `connection'."
(remhash (normalized-name channel) (channels connection)))
(defmethod remove-users ((channel channel))
"Remove all users on `channel'."
(clrhash (users channel)))
(defclass user ()
((nickname
:initarg :nickname
:accessor nickname
:initform "")
(normalized-nickname
:initarg :normalized-nickname
:accessor normalized-nickname
:initform "")
(username
:initarg :username
:accessor username
:initform "")
(hostname
:initarg :hostname
:accessor hostname
:initform "")
(realname
:initarg :realname
:accessor realname
:initform "")
(channels
:initarg :channels
:accessor channels
:initform nil)))
(defmethod print-object ((object user) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A!~A@~A \"~A\""
(nickname object)
(username object)
(hostname object)
(realname object))))
(defun make-user (connection
&key (nickname "")
(username "")
(hostname "")
(realname ""))
(make-instance 'user
:nickname nickname
:normalized-nickname (normalize-nickname connection nickname)
:username username
:hostname hostname
:realname realname))
(defun canonicalize-nickname (connection nickname)
(if (find (char nickname 0)
(parse-isupport-prefix-argument
(second (assoc "PREFIX"
(server-capabilities connection)
:test #'string=))))
(subseq nickname 1)
nickname))
(defun normalize-nickname (connection string)
"Normalize `string' so that represents an all-downcased IRC
nickname."
(irc-string-downcase (case-map-name connection) string))
(defgeneric find-user (connection nickname))
(defgeneric add-user (object user))
(defgeneric remove-all-users (connection))
(defgeneric remove-user (object user))
(defgeneric remove-user-everywhere (connection user))
(defgeneric find-or-make-user (connection nickname
&key username hostname realname))
(defgeneric change-nickname (connection user new-nickname))
(defmethod find-user ((connection connection) (nickname string))
"Return user as designated by `nickname' or nil if no such user is
known."
(let ((nickname (normalize-nickname connection nickname)))
(or (gethash nickname (users connection))
(when (string= nickname (nickname (user connection)))
(user connection)))))
(defmethod add-user ((connection connection) (user user))
"Add `user' to `connection'."
(setf (gethash (normalized-nickname user) (users connection)) user))
(defmethod add-user ((channel channel) (user user))
(setf (gethash (normalized-nickname user) (users channel)) user)
(pushnew channel (channels user)))
(defmethod remove-all-users ((connection connection))
"Remove all users known to `connection'."
(clrhash (users connection)))
(defmethod remove-user ((channel channel) (user user))
"Remove `user' from `channel' and `channel' from `user'."
(remhash (normalized-nickname user) (users channel))
(setf (channels user) (remove channel (channels user))))
(defmethod remove-channel ((channel channel) (user user))
"Remove `channel' from `user'."
(warn
(concatenate 'string
"use of depricated API (remove-channel channel user): "
"(remove-channel user channel) is now preferred"))
(remove-channel user channel))
(defmethod remove-channel ((user user) (channel channel))
"Remove `channel' from `user'."
(setf (channels user) (remove channel (channels user))))
(defmethod remove-user ((connection connection) (user user))
"Remove `user' from `connection' but leave user in any channels he
may be already be on."
(remhash (normalized-nickname user) (users connection)))
(defmethod remove-user-everywhere ((connection connection) (user user))
"Remove `user' anywhere present in the `connection'."
(dolist (channel (channels user))
(remove-user channel user))
(remove-user connection user))
(defmethod find-or-make-user ((connection connection) nickname &key (username "")
(hostname "") (realname ""))
(or (find-user connection nickname)
(make-user connection
:nickname nickname
:username username
:hostname hostname
:realname realname)))
(defmethod change-nickname ((connection connection) (user user) new-nickname)
(let ((new-user user)
(channels (channels user)))
(remove-user connection user)
(setf (nickname new-user) new-nickname)
(setf (normalized-nickname new-user)
(normalize-nickname connection new-nickname))
(dolist (channel channels)
(remove-user channel user)
(add-user channel new-user))
(add-user connection user)
new-user))
(defclass irc-message ()
((source
:accessor source
:initarg :source
:type string)
(user
:accessor user
:initarg :user)
(host
:accessor host
:initarg :host
:type string)
(command
:accessor command
:initarg :command
:type string)
(arguments
:accessor arguments
:initarg :arguments
:type list)
(trailing-argument
:accessor trailing-argument
:initarg :trailing-argument
:type string)
(connection
:accessor connection
:initarg :connection)
(received-time
:accessor received-time
:initarg :received-time)
(raw-message-string
:accessor raw-message-string
:initarg :raw-message-string
:type string)))
(defmethod print-object ((object irc-message) stream)
"Print the object for the Lisp reader."
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A ~A" (source object) (command object))))
(defgeneric self-message-p (message))
(defgeneric find-irc-message-class (type))
(defgeneric client-log (connection message &optional prefix))
(defgeneric apply-to-hooks (message))
(defmethod self-message-p ((message irc-message))
"Did we send this message?"
(string-equal (source message)
(nickname (user (connection message)))))
(defclass irc-error-reply (irc-message) ())
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun intern-message-symbol (prefix name)
"Intern based on symbol-name to support case-sensitive mlisp"
(intern
(concatenate 'string
(symbol-name prefix)
"-"
(symbol-name name)
"-"
(symbol-name '#:message))))
(defun define-irc-message (command)
(let ((name (intern-message-symbol :irc command)))
`(progn
(defmethod find-irc-message-class ((type (eql ,command)))
(find-class ',name))
(export ',name)
(defclass ,name (irc-message) ())))))
(defmacro create-irc-message-classes (class-list)
`(progn ,@(mapcar #'define-irc-message class-list)))
(create-irc-message-classes #.(remove-duplicates (mapcar #'second *reply-names*)))
(create-irc-message-classes (:privmsg :notice :kick :topic :error :mode :ping
:nick :join :part :quit :kill :pong :invite))
(defmethod find-irc-message-class (type)
(declare (ignore type))
(find-class 'irc-message))
(defmethod client-log ((connection connection) (message irc-message) &optional (prefix ""))
(let ((stream (client-stream connection)))
(format stream "~A~A: ~A: ~A~{ ~A~} \"~A\"~%"
prefix
(received-time message)
(command message)
(source message)
(arguments message)
(trailing-argument message))
(force-output stream)))
(defmethod apply-to-hooks ((message irc-message))
(let ((connection (connection message)))
(dolist (hook (get-hooks connection (class-name (class-of message))))
(funcall hook message))))
(defclass ctcp-mixin ()
((ctcp-command
:initarg :ctcp-command
:accessor ctcp-command)))
(defclass standard-ctcp-message (ctcp-mixin irc-message) ())
(defgeneric find-ctcp-message-class (type))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun define-ctcp-message (ctcp-command)
(let ((name (intern-message-symbol :ctcp ctcp-command)))
`(progn
(defmethod find-ctcp-message-class ((type (eql ,ctcp-command)))
(find-class ',name))
(export ',name)
(defclass ,name (ctcp-mixin irc-message) ())))))
(defmacro create-ctcp-message-classes (class-list)
`(progn ,@(mapcar #'define-ctcp-message class-list)))
(create-ctcp-message-classes (:action :source :finger :ping
:version :userinfo :time :dcc-chat-request
:dcc-send-request))
(defmethod find-ctcp-message-class (type)
(declare (ignore type))
(find-class 'standard-ctcp-message))
(defmethod client-log ((connection connection) (message ctcp-mixin) &optional (prefix ""))
(let ((stream (client-stream connection)))
(format stream "~A~A: ~A (~A): ~A~{ ~A~} \"~A\"~%"
prefix
(received-time message)
(command message)
(ctcp-command message)
(source message)
(arguments message)
(trailing-argument message))
(force-output stream)))
|
2d05cc2a14cd6248766ec338ac285b89510b784aac64d3912353d6f9fecbfcda | borgeby/jarl | api.clj | (ns jarl.api
(:require [jarl.parser :as parser]
[jarl.eval :as eval])
(:import (java.util Map List Set)))
(gen-class
:name "by.borge.jarl.internal.InternalPlanImpl"
:implements [by.borge.jarl.internal.InternalPlan]
:main false
:prefix "-plan-"
:constructors {[Object Object String] []}
:state "state"
:init "init"
)
(defn -plan-init [info plan entry-point]
[[info] [info plan entry-point]])
(defn- sanitize [data]
(cond
(instance? Map data) (reduce-kv (fn [d k v] (assoc d k (sanitize v))) {} data)
(instance? List data) (reduce (fn [d v] (conj d (sanitize v))) [] data)
(instance? Set data) (reduce (fn [d v] (conj d (sanitize v))) #{} data)
:else data))
(defn -plan-eval [^by.borge.jarl.internal.InternalPlanImpl this input data]
(let [[info plan entry-point] (.state this)]
(if (nil? plan)
(throw (Exception. (format "plan with entry-point '%s' doesn't exist" entry-point)))
(plan info (sanitize input) (sanitize data)))))
(defn -plans-toString [^by.borge.jarl.internal.InternalPlanImpl this]
(let [[_ _ entry-point] (.state this)]
entry-point))
(gen-class
:name "by.borge.jarl.internal.IrImpl"
:implements [by.borge.jarl.internal.IntermediateRepresentation]
:prefix "-jarl-ir-"
:main false
:state "state"
:init "init"
:constructors {[Object] []}
)
(defn -jarl-ir-init [info]
[[info] info])
(defn -jarl-ir-withStrictBuiltinErrors [^by.borge.jarl.internal.IrImpl this strict]
(let [info (.state this)]
(new by.borge.jarl.internal.IrImpl (assoc info :strict-builtin-errors strict))))
(defn -jarl-ir-getPlans [^by.borge.jarl.internal.IrImpl this]
(let [info (.state this)
plans (:plans info)
plans (into (sorted-map) plans)
plans (reduce-kv (fn [m name plan] (assoc m name (new by.borge.jarl.internal.InternalPlanImpl info plan name))) {} plans)]
plans))
(defn -jarl-ir-getPlan [^by.borge.jarl.internal.IrImpl this entry-point]
(let [info (.state this)
plan (eval/find-plan info entry-point)]
(new by.borge.jarl.internal.InternalPlanImpl info plan entry-point)))
(gen-class
:name "by.borge.jarl.internal.Parser"
:prefix "-jarl-parser-"
:main false
:methods [^{:static true} [parse [String] by.borge.jarl.internal.IntermediateRepresentation]]
)
(defn -jarl-parser-parse [ir]
(new by.borge.jarl.internal.IrImpl (parser/parse-json ir))) | null | https://raw.githubusercontent.com/borgeby/jarl/3783e3a383aadb74a123a6accc72d290451c9be5/core/src/main/clj/jarl/api.clj | clojure | (ns jarl.api
(:require [jarl.parser :as parser]
[jarl.eval :as eval])
(:import (java.util Map List Set)))
(gen-class
:name "by.borge.jarl.internal.InternalPlanImpl"
:implements [by.borge.jarl.internal.InternalPlan]
:main false
:prefix "-plan-"
:constructors {[Object Object String] []}
:state "state"
:init "init"
)
(defn -plan-init [info plan entry-point]
[[info] [info plan entry-point]])
(defn- sanitize [data]
(cond
(instance? Map data) (reduce-kv (fn [d k v] (assoc d k (sanitize v))) {} data)
(instance? List data) (reduce (fn [d v] (conj d (sanitize v))) [] data)
(instance? Set data) (reduce (fn [d v] (conj d (sanitize v))) #{} data)
:else data))
(defn -plan-eval [^by.borge.jarl.internal.InternalPlanImpl this input data]
(let [[info plan entry-point] (.state this)]
(if (nil? plan)
(throw (Exception. (format "plan with entry-point '%s' doesn't exist" entry-point)))
(plan info (sanitize input) (sanitize data)))))
(defn -plans-toString [^by.borge.jarl.internal.InternalPlanImpl this]
(let [[_ _ entry-point] (.state this)]
entry-point))
(gen-class
:name "by.borge.jarl.internal.IrImpl"
:implements [by.borge.jarl.internal.IntermediateRepresentation]
:prefix "-jarl-ir-"
:main false
:state "state"
:init "init"
:constructors {[Object] []}
)
(defn -jarl-ir-init [info]
[[info] info])
(defn -jarl-ir-withStrictBuiltinErrors [^by.borge.jarl.internal.IrImpl this strict]
(let [info (.state this)]
(new by.borge.jarl.internal.IrImpl (assoc info :strict-builtin-errors strict))))
(defn -jarl-ir-getPlans [^by.borge.jarl.internal.IrImpl this]
(let [info (.state this)
plans (:plans info)
plans (into (sorted-map) plans)
plans (reduce-kv (fn [m name plan] (assoc m name (new by.borge.jarl.internal.InternalPlanImpl info plan name))) {} plans)]
plans))
(defn -jarl-ir-getPlan [^by.borge.jarl.internal.IrImpl this entry-point]
(let [info (.state this)
plan (eval/find-plan info entry-point)]
(new by.borge.jarl.internal.InternalPlanImpl info plan entry-point)))
(gen-class
:name "by.borge.jarl.internal.Parser"
:prefix "-jarl-parser-"
:main false
:methods [^{:static true} [parse [String] by.borge.jarl.internal.IntermediateRepresentation]]
)
(defn -jarl-parser-parse [ir]
(new by.borge.jarl.internal.IrImpl (parser/parse-json ir))) | |
9785423210849f8005f21660ac481f2983d73835d452f6bc1198077db6bfc3ab | ocaml/ocamlfind | fl_package_base.ml | (* $Id$
* ----------------------------------------------------------------------
*
*)
open Fl_metascanner
exception No_such_package of string * string
(* (name, reason) *)
type package =
{ package_name : string;
package_dir : string;
package_meta : string;
package_defs : Fl_metascanner.pkg_definition list;
package_priv : package_priv
}
and package_priv =
{ mutable missing_reqs : (string * string) list;
If non - empty the package is broken . This may be set by
add_all_relations , and should be checked before using the
package later . Each element corresponds to No_such_package .
add_all_relations, and should be checked before using the
package later. Each element corresponds to No_such_package.
*)
}
;;
module Fl_metaentry =
struct
type t = package
type id_t = string
let id m = m.package_name
end
;;
module Fl_metastore =
Fl_topo.Make(Fl_metaentry)
;;
module StringSet = Set.Make(String);;
let has_prefix s pref =
String.length s >= String.length pref &&
String.sub s 0 (String.length pref) = pref
;;
let ocamlpath = ref [];;
let ocamlstdlib = ref "";;
let conf_ignore_dups_in = ref ([] : string list)
let store = Fl_metastore.create();;
We collect here only nodes , but no relations . First copy [ store ]
* and put relations into the copy .
* and put relations into the copy.
*)
let init path stdlib ignore_dups_in =
ocamlpath := path;
ocamlstdlib := stdlib;
conf_ignore_dups_in := ignore_dups_in
;;
let packages_in_meta_file ?(directory_required = false)
~name:package_name ~dir:package_dir ~meta_file () =
Parses the META file whose name is [ meta_file ] . In [ package_name ] , the
* name of the main package must be passed . [ package_dir ] is the
* directory associated with the package by default ( i.e. before
* it is overriden by the " directory " directive ) .
*
* directory_required : If true , a " directory " directive is necessary .
*
* Returns the [ package ] records found in this file . The " directory "
* directive is already applied .
* name of the main package must be passed. [package_dir] is the
* directory associated with the package by default (i.e. before
* it is overriden by the "directory" directive).
*
* directory_required: If true, a "directory" directive is necessary.
*
* Returns the [package] records found in this file. The "directory"
* directive is already applied.
*)
let rec flatten_meta pkg_name_prefix pkg_dir (pkg_name_component,pkg_expr) =
Turns the recursive [ pkg_expr ] into a flat list of [ package]s .
* [ pkg_dir ] is the default package directory . [ pkg_name_prefix ] is
* the name prefix to prepend to the fully qualified package name , or
* " " . [ pkg_name_component ] is the local package name .
* [pkg_dir] is the default package directory. [pkg_name_prefix] is
* the name prefix to prepend to the fully qualified package name, or
* "". [pkg_name_component] is the local package name.
*)
(* Determine the final package directory: *)
let d =
(* The value of "directory", or "" if not applicable *)
try
lookup "directory" [] pkg_expr.pkg_defs
with
Not_found ->
if pkg_name_prefix="" && directory_required then
failwith ("The `directory' directive is required in this META definition");
""
in
let d' =
if d = "" then
pkg_dir
else
match d.[0] with
| '^'
| '+' ->
let rest = String.sub d 1 (String.length d - 1) in
if rest = "" then
!ocamlstdlib
else
Filename.concat !ocamlstdlib rest
| _ ->
if Filename.is_relative d then
Filename.concat pkg_dir d
else
d
in
let p_name =
if pkg_name_prefix = "" then
pkg_name_component
else
pkg_name_prefix ^ "." ^ pkg_name_component in
let p =
{ package_name = p_name;
package_dir = d';
package_meta = meta_file;
package_defs = pkg_expr.pkg_defs;
package_priv = { missing_reqs = [] }
} in
(* Check for exists_if: *)
let p_exists =
try
let def =
List.find (fun def -> def.def_var = "exists_if") p.package_defs in
let files = Fl_split.in_words def.def_value in
List.exists
(fun file -> Sys.file_exists (Filename.concat d' file))
files
with Not_found -> true in
if p_exists then
p :: (List.flatten
(List.map (flatten_meta p_name d') pkg_expr.pkg_children))
else
[]
in
let ch = open_in meta_file in
try
let pkg_expr = Fl_metascanner.parse ch in
let packages = flatten_meta "" package_dir (package_name, pkg_expr) in
close_in ch;
packages
with
Failure s ->
close_in ch;
failwith ("While parsing '" ^ meta_file ^ "': " ^ s)
| Fl_metascanner.Error s ->
close_in ch;
failwith ("While parsing '" ^ meta_file ^ "': " ^ s)
| any ->
close_in ch;
raise any
;;
let query package_name =
let package_name_comps = Fl_split.package_name package_name in
if package_name_comps = [] then invalid_arg "Fl_package_base.query";
let main_name = List.hd package_name_comps in
let process_file_and_lookup ?directory_required package_dir meta_file =
let packages =
packages_in_meta_file
?directory_required ~name:main_name ~dir:package_dir ~meta_file () in
let p =
( try
List.find
(fun p -> p.package_name = package_name)
packages
with
Not_found ->
raise (No_such_package (package_name, ""))
) in
List.iter (Fl_metastore.add store) packages;
p
in
let rec run_ocamlpath path =
match path with
[] -> raise(No_such_package(package_name, ""))
| dir :: path' ->
let package_dir = Filename.concat dir main_name in
let meta_file_1 = Filename.concat package_dir "META" in
let meta_file_2 = Filename.concat dir ("META." ^ main_name) in
if Sys.file_exists meta_file_1 then
process_file_and_lookup package_dir meta_file_1
else
if Sys.file_exists meta_file_2 then
process_file_and_lookup ~directory_required:true dir meta_file_2
(* Note: It is allowed to have relative "directory" directives.
* The base directory is [dir] in this case.
*)
else
run_ocamlpath path'
in
try
Fl_metastore.find store package_name
with
Not_found ->
run_ocamlpath !ocamlpath
;;
exception Package_loop of string
(* A package is required by itself. The arg is the name of the
* package
*)
let fixup_thread_needed_1 predlist =
When the thread fixup is required to apply , 1st criterion
List.mem "mt" predlist
;;
let fixup_thread_needed_2 pkg =
When the thread fixup is required to apply , 2nd criterion
(pkg <> "unix" && pkg <> "threads" && not (has_prefix pkg "threads."))
;;
let fixup_thread_base predlist pkg =
(* Add the package "threads" if required *)
if fixup_thread_needed_1 predlist && fixup_thread_needed_2 pkg then
[ "threads" ]
else
[]
;;
let query_requirements ~preds:predlist package_name =
(* Part of [requires] implementation: Load all required packages, but
* do not add relations
*)
let m = query package_name in
(* may raise No_such_package *)
let r =
try Fl_metascanner.lookup "requires" predlist m.package_defs
with Not_found -> ""
in
let ancestors = Fl_split.in_words r @
fixup_thread_base predlist package_name in
List.iter
(fun p ->
try
let _ = query p in (* may raise No_such_package *)
()
with
No_such_package(pname,_) ->
raise(No_such_package(pname, "required by `" ^ package_name ^ "'"))
)
ancestors;
ancestors
;;
let add_relations s ancestors package_name =
Part of [ requires ] implementation : Adds the relations from [ package_name ]
* to [ ancestors ] . Target store is [ s ] .
* to [ancestors]. Target store is [s].
*)
List.iter
(fun p ->
try
Fl_metastore.let_le s p package_name (* add relation *)
with
| Fl_topo.Inconsistent_ordering ->
raise(Package_loop p)
| Not_found ->
(* A relation to a package not part of [s]. We ignore it here. *)
()
)
ancestors
;;
let add_all_relations predlist s =
(* Adds all relations for the packages currently defined in [s].
Note that missing requirements are not reported immediately (we do
not know here which part of the graph [s] is really accessed), and
instead the error is added to the missing_reqs field, where
it should be checked before used.
*)
let pkgs = ref [] in
Fl_metastore.iter_up
(fun p -> pkgs := p :: !pkgs)
s;
List.iter
(fun p ->
let pkg = p.package_name in
try
let pkg_ancestors = query_requirements predlist pkg in
add_relations s pkg_ancestors pkg
with
| No_such_package(n,reason) ->
p.package_priv.missing_reqs <-
(n,reason) :: p.package_priv.missing_reqs
)
!pkgs
;;
let fixup_thread_deps s =
(* All packages (except "threads", "threads.*", and "unix") are made
* dependent on "threads"
*)
let pkgs = ref [] in
Fl_metastore.iter_up
(fun p -> pkgs := p.package_name :: !pkgs)
s;
List.iter
(fun pkg ->
if fixup_thread_needed_2 pkg then (
try
Fl_metastore.let_le s "threads" pkg (* add relation *)
with
Not_found ->
(* Because "threads" does not exist! Normally this is an
* error, because "threads" is also magically added by
* query_requirements. However, there are situations
* where it cannot be expected that required packages
* are loaded, so ignore this case.
*)
()
)
)
!pkgs
;;
let requires ~preds:predlist package_name =
returns names of packages required by [ package_name ] , the fully qualified
* name of the package . It is checked that the packages really exist .
* [ predlist ] : list of true predicates
* May raise [ No_such_package ] or [ Package_loop ] .
* name of the package. It is checked that the packages really exist.
* [predlist]: list of true predicates
* May raise [No_such_package] or [Package_loop].
*)
let ancestors = query_requirements predlist package_name in
let store' = Fl_metastore.copy store in (* work with a copy *)
add_relations store' ancestors package_name;
if List.mem "mt" predlist then fixup_thread_deps store';
ancestors
;;
let requires_deeply ~preds:predlist package_list =
returns names of packages required by the packages in [ package_list ] ,
* either directly or indirectly .
* It is checked that the packages really exist .
* The list of names is sorted topologically ; first comes the deepest
* ancestor .
* [ predlist ] : list of true predicates
* - raises [ Not_found ] if there is no ' package '
* - raises [ Failure ] if some of the ancestors do not exist
* either directly or indirectly.
* It is checked that the packages really exist.
* The list of names is sorted topologically; first comes the deepest
* ancestor.
* [predlist]: list of true predicates
* - raises [Not_found] if there is no 'package'
* - raises [Failure] if some of the ancestors do not exist
*)
let pkgset = ref StringSet.empty in
let rec query_packages pkglist =
match pkglist with
pkg :: pkglist' ->
if not(StringSet.mem pkg !pkgset) then begin
let pkg_ancestors = query_requirements predlist pkg in
pkgset := StringSet.add pkg !pkgset;
query_packages pkg_ancestors
end;
query_packages pkglist'
| [] ->
()
in
First query for all packages , such that they are loaded :
query_packages package_list;
(* Now make a copy of the store, and add the relations: *)
let store' = Fl_metastore.copy store in
add_all_relations predlist store';
if List.mem "mt" predlist then fixup_thread_deps store';
(* Finally, iterate through the graph. Note that the graph may
* contain more members than required, so we have to test explicitly
* whether the packages are contained in pkgset.
*)
let l = ref [] in
Fl_metastore.iter_up_at
(fun m ->
if StringSet.mem m.package_name !pkgset then (
if m.package_priv.missing_reqs <> [] then (
let (n,reason) = List.hd m.package_priv.missing_reqs in
raise(No_such_package(n,reason))
);
l := m.package_name :: !l
)
)
store'
package_list;
List.rev !l
;;
(**********************************************************************)
The following two functions do not use ! ocamlpath , because there may
* be duplicates in it .
* be duplicates in it.
*)
let package_definitions ~search_path package_name =
Return all META files defining this [ package_name ] that occur in the
* directories mentioned in [ search_path ]
* directories mentioned in [search_path]
*)
let package_name_comps = Fl_split.package_name package_name in
if package_name_comps = [] then invalid_arg "Fl_package_base.package_definitions";
let main_name = List.hd package_name_comps in
let rec run_ocamlpath path =
match path with
[] -> []
| dir :: path' ->
let package_dir = Filename.concat dir main_name in
let meta_file_1 = Filename.concat package_dir "META" in
let meta_file_2 = Filename.concat dir ("META." ^ main_name) in
if Sys.file_exists meta_file_1 then
meta_file_1 :: run_ocamlpath path'
else
if Sys.file_exists meta_file_2 then
meta_file_2 :: run_ocamlpath path'
else
run_ocamlpath path'
in
run_ocamlpath search_path
;;
let in_report_search_path identify_dir d =
Whether package dir d is to be considered for generating reports .
d is sorted out when the ignore_dups_in option is set
d is sorted out when the ignore_dups_in option is set
*)
List.for_all
(fun id ->
try identify_dir d <> identify_dir id
with _ -> Fl_split.norm_dir d <> Fl_split.norm_dir id
)
!conf_ignore_dups_in
;;
let package_conflict_report_1 identify_dir () =
let remove_dups_from_path p =
(* Removes directories which are physically the same from the path [p],
* and returns the shortened path
*)
let dir_identity = Hashtbl.create 20 in
let rec remove p =
match p with
d :: p' ->
begin try
let id = identify_dir d in (* may raise exceptions *)
if Hashtbl.mem dir_identity id then
remove p'
else begin
Hashtbl.add dir_identity id ();
d :: (remove p')
end
with error ->
(* Don't know anything, so the "directory" remains in the path *)
d :: (remove p')
end
| [] ->
[]
in
remove p
in
If we have ignore_dups_in this directory is removed from our search
path first
path first
*)
let search_path0 =
List.filter (in_report_search_path identify_dir) !ocamlpath in
(* Now eliminate all duplicates *)
let search_path =
remove_dups_from_path search_path0 in
Fl_metastore.iter_up
(fun pkg ->
(* Check only main packages: *)
let package_name_comps = Fl_split.package_name pkg.package_name in
match package_name_comps with
[_] ->
(* pkg is a main package *)
( let c = package_definitions search_path pkg.package_name in
match c with
[]
| [_] ->
()
| _ ->
Printf.eprintf "findlib: [WARNING] Package %s has multiple definitions in %s\n"
pkg.package_name
(String.concat ", " c)
)
| _ ->
()
)
store;
flush stderr
;;
let package_conflict_report ?identify_dir () =
match identify_dir with
None -> package_conflict_report_1 (fun s -> s) ()
| Some f -> package_conflict_report_1 f ()
;;
let check_prefix ?prefix f =
match prefix with
| None -> true
| Some prefix ->
let len = String.length prefix in
String.length f >= len && String.sub f 0 len = prefix
let load_base ?prefix () =
(* Ensures that the cache is completely filled with every package
* of the system that match prefix
*)
let list_directory d =
try
Array.to_list(Sys.readdir d)
with
Sys_error msg ->
prerr_endline ("findlib: [WARNING] cannot read directory " ^ msg);
[]
in
let process_file ?directory_required main_name package_dir meta_file =
try
let _ = Fl_metastore.find store main_name in
(* Note: If the main package is already loaded into the graph, we
* do not even look at the subpackages!
*)
()
with
Not_found ->
let packages =
try
packages_in_meta_file
?directory_required ~name:main_name ~dir:package_dir ~meta_file ()
with
Failure s ->
prerr_endline ("findlib: [WARNING] " ^ s); []
in
List.iter (Fl_metastore.add store) packages;
(* Nothing evil can happen! *)
in
let rec run_ocamlpath path =
match path with
[] -> ()
| dir :: path' ->
let files = list_directory dir in
List.iter
(fun f ->
if check_prefix ?prefix f
then
If f / META exists : Add package f
let package_dir = Filename.concat dir f in
let meta_file_1 = Filename.concat package_dir "META" in
if Sys.file_exists meta_file_1 then
process_file f package_dir meta_file_1
else
If f is : Add package pkgname
(* We skip over filenames ending in '~' *)
if String.length f >= 6 && String.sub f 0 5 = "META." &&
String.sub f (String.length f - 1) 1 <> "~" then begin
let name = String.sub f 5 (String.length f - 5) in
let meta_file_2 = Filename.concat dir f in
process_file ~directory_required:true name dir meta_file_2
end;
)
files;
run_ocamlpath path'
in
run_ocamlpath !ocamlpath
;;
let list_packages ?prefix () =
load_base ?prefix ();
let l = ref [] in
Fl_metastore.iter_up
(fun m ->
if check_prefix ?prefix m.package_name then
l := m.package_name :: !l
)
store;
!l
;;
let package_users ~preds pl =
(* Check that all packages in [pl] really exist, or raise No_such_package: *)
List.iter
(fun p -> let _ = query p in ())
pl;
load_base();
let store' = Fl_metastore.copy store in
add_all_relations preds store';
if List.mem "mt" preds then fixup_thread_deps store';
let l = ref [] in
Fl_metastore.iter_down_at
(fun m ->
if m.package_priv.missing_reqs <> [] then (
let (n,reason) = List.hd m.package_priv.missing_reqs in
raise(No_such_package(n,reason))
);
l := m.package_name :: !l
)
store'
pl;
!l
;;
let module_conflict_report_1 identify_dir incpath =
(* Find any *.cmi files occurring twice in incpath.
*)
let dir_of_module = Hashtbl.create 100 in
let dirs = ref [] in
let examine_dir d =
try
let d = Fl_split.norm_dir d in
let d_id = identify_dir d in
(* Is d new? *)
if not (List.mem d_id !dirs) then begin
dirs := d_id :: !dirs;
Yes : Get all files ending in .cmi
try
or Sys_error
let d_cmi =
List.filter
(fun n -> Filename.check_suffix n ".cmi")
d_all in
(* Add the modules to dir_of_module: *)
List.iter
(fun m ->
try
let entry = Hashtbl.find dir_of_module m in (* or Not_found *)
entry := d :: !entry
with
Not_found ->
Hashtbl.add dir_of_module m (ref [d])
)
d_cmi
with
Sys_error msg ->
prerr_endline ("findlib: [WARNING] cannot read directory " ^ msg)
end
with
| _ -> () (* identify_dir fails *)
in
let print_report() =
Hashtbl.iter
(fun m dlist ->
match !dlist with
[]
| [_] ->
()
| _ ->
Printf.eprintf "findlib: [WARNING] Interface %s occurs in several directories: %s\n"
m
(String.concat ", " !dlist)
)
dir_of_module
in
If we have ignore_dups_in this directory is removed from our search
path first
path first
*)
let incpath1 =
List.filter (in_report_search_path identify_dir) incpath in
List.iter examine_dir incpath1;
print_report();
flush stderr
;;
let module_conflict_report ?identify_dir incpath =
match identify_dir with
None -> module_conflict_report_1 (fun s -> s) incpath
| Some f -> module_conflict_report_1 f incpath
;;
| null | https://raw.githubusercontent.com/ocaml/ocamlfind/00b1b75b4f0c75387d38530cbc6eeb3148a08b3b/src/findlib/fl_package_base.ml | ocaml | $Id$
* ----------------------------------------------------------------------
*
(name, reason)
Determine the final package directory:
The value of "directory", or "" if not applicable
Check for exists_if:
Note: It is allowed to have relative "directory" directives.
* The base directory is [dir] in this case.
A package is required by itself. The arg is the name of the
* package
Add the package "threads" if required
Part of [requires] implementation: Load all required packages, but
* do not add relations
may raise No_such_package
may raise No_such_package
add relation
A relation to a package not part of [s]. We ignore it here.
Adds all relations for the packages currently defined in [s].
Note that missing requirements are not reported immediately (we do
not know here which part of the graph [s] is really accessed), and
instead the error is added to the missing_reqs field, where
it should be checked before used.
All packages (except "threads", "threads.*", and "unix") are made
* dependent on "threads"
add relation
Because "threads" does not exist! Normally this is an
* error, because "threads" is also magically added by
* query_requirements. However, there are situations
* where it cannot be expected that required packages
* are loaded, so ignore this case.
work with a copy
Now make a copy of the store, and add the relations:
Finally, iterate through the graph. Note that the graph may
* contain more members than required, so we have to test explicitly
* whether the packages are contained in pkgset.
********************************************************************
Removes directories which are physically the same from the path [p],
* and returns the shortened path
may raise exceptions
Don't know anything, so the "directory" remains in the path
Now eliminate all duplicates
Check only main packages:
pkg is a main package
Ensures that the cache is completely filled with every package
* of the system that match prefix
Note: If the main package is already loaded into the graph, we
* do not even look at the subpackages!
Nothing evil can happen!
We skip over filenames ending in '~'
Check that all packages in [pl] really exist, or raise No_such_package:
Find any *.cmi files occurring twice in incpath.
Is d new?
Add the modules to dir_of_module:
or Not_found
identify_dir fails |
open Fl_metascanner
exception No_such_package of string * string
type package =
{ package_name : string;
package_dir : string;
package_meta : string;
package_defs : Fl_metascanner.pkg_definition list;
package_priv : package_priv
}
and package_priv =
{ mutable missing_reqs : (string * string) list;
If non - empty the package is broken . This may be set by
add_all_relations , and should be checked before using the
package later . Each element corresponds to No_such_package .
add_all_relations, and should be checked before using the
package later. Each element corresponds to No_such_package.
*)
}
;;
module Fl_metaentry =
struct
type t = package
type id_t = string
let id m = m.package_name
end
;;
module Fl_metastore =
Fl_topo.Make(Fl_metaentry)
;;
module StringSet = Set.Make(String);;
let has_prefix s pref =
String.length s >= String.length pref &&
String.sub s 0 (String.length pref) = pref
;;
let ocamlpath = ref [];;
let ocamlstdlib = ref "";;
let conf_ignore_dups_in = ref ([] : string list)
let store = Fl_metastore.create();;
We collect here only nodes , but no relations . First copy [ store ]
* and put relations into the copy .
* and put relations into the copy.
*)
let init path stdlib ignore_dups_in =
ocamlpath := path;
ocamlstdlib := stdlib;
conf_ignore_dups_in := ignore_dups_in
;;
let packages_in_meta_file ?(directory_required = false)
~name:package_name ~dir:package_dir ~meta_file () =
Parses the META file whose name is [ meta_file ] . In [ package_name ] , the
* name of the main package must be passed . [ package_dir ] is the
* directory associated with the package by default ( i.e. before
* it is overriden by the " directory " directive ) .
*
* directory_required : If true , a " directory " directive is necessary .
*
* Returns the [ package ] records found in this file . The " directory "
* directive is already applied .
* name of the main package must be passed. [package_dir] is the
* directory associated with the package by default (i.e. before
* it is overriden by the "directory" directive).
*
* directory_required: If true, a "directory" directive is necessary.
*
* Returns the [package] records found in this file. The "directory"
* directive is already applied.
*)
let rec flatten_meta pkg_name_prefix pkg_dir (pkg_name_component,pkg_expr) =
Turns the recursive [ pkg_expr ] into a flat list of [ package]s .
* [ pkg_dir ] is the default package directory . [ pkg_name_prefix ] is
* the name prefix to prepend to the fully qualified package name , or
* " " . [ pkg_name_component ] is the local package name .
* [pkg_dir] is the default package directory. [pkg_name_prefix] is
* the name prefix to prepend to the fully qualified package name, or
* "". [pkg_name_component] is the local package name.
*)
let d =
try
lookup "directory" [] pkg_expr.pkg_defs
with
Not_found ->
if pkg_name_prefix="" && directory_required then
failwith ("The `directory' directive is required in this META definition");
""
in
let d' =
if d = "" then
pkg_dir
else
match d.[0] with
| '^'
| '+' ->
let rest = String.sub d 1 (String.length d - 1) in
if rest = "" then
!ocamlstdlib
else
Filename.concat !ocamlstdlib rest
| _ ->
if Filename.is_relative d then
Filename.concat pkg_dir d
else
d
in
let p_name =
if pkg_name_prefix = "" then
pkg_name_component
else
pkg_name_prefix ^ "." ^ pkg_name_component in
let p =
{ package_name = p_name;
package_dir = d';
package_meta = meta_file;
package_defs = pkg_expr.pkg_defs;
package_priv = { missing_reqs = [] }
} in
let p_exists =
try
let def =
List.find (fun def -> def.def_var = "exists_if") p.package_defs in
let files = Fl_split.in_words def.def_value in
List.exists
(fun file -> Sys.file_exists (Filename.concat d' file))
files
with Not_found -> true in
if p_exists then
p :: (List.flatten
(List.map (flatten_meta p_name d') pkg_expr.pkg_children))
else
[]
in
let ch = open_in meta_file in
try
let pkg_expr = Fl_metascanner.parse ch in
let packages = flatten_meta "" package_dir (package_name, pkg_expr) in
close_in ch;
packages
with
Failure s ->
close_in ch;
failwith ("While parsing '" ^ meta_file ^ "': " ^ s)
| Fl_metascanner.Error s ->
close_in ch;
failwith ("While parsing '" ^ meta_file ^ "': " ^ s)
| any ->
close_in ch;
raise any
;;
let query package_name =
let package_name_comps = Fl_split.package_name package_name in
if package_name_comps = [] then invalid_arg "Fl_package_base.query";
let main_name = List.hd package_name_comps in
let process_file_and_lookup ?directory_required package_dir meta_file =
let packages =
packages_in_meta_file
?directory_required ~name:main_name ~dir:package_dir ~meta_file () in
let p =
( try
List.find
(fun p -> p.package_name = package_name)
packages
with
Not_found ->
raise (No_such_package (package_name, ""))
) in
List.iter (Fl_metastore.add store) packages;
p
in
let rec run_ocamlpath path =
match path with
[] -> raise(No_such_package(package_name, ""))
| dir :: path' ->
let package_dir = Filename.concat dir main_name in
let meta_file_1 = Filename.concat package_dir "META" in
let meta_file_2 = Filename.concat dir ("META." ^ main_name) in
if Sys.file_exists meta_file_1 then
process_file_and_lookup package_dir meta_file_1
else
if Sys.file_exists meta_file_2 then
process_file_and_lookup ~directory_required:true dir meta_file_2
else
run_ocamlpath path'
in
try
Fl_metastore.find store package_name
with
Not_found ->
run_ocamlpath !ocamlpath
;;
exception Package_loop of string
let fixup_thread_needed_1 predlist =
When the thread fixup is required to apply , 1st criterion
List.mem "mt" predlist
;;
let fixup_thread_needed_2 pkg =
When the thread fixup is required to apply , 2nd criterion
(pkg <> "unix" && pkg <> "threads" && not (has_prefix pkg "threads."))
;;
let fixup_thread_base predlist pkg =
if fixup_thread_needed_1 predlist && fixup_thread_needed_2 pkg then
[ "threads" ]
else
[]
;;
let query_requirements ~preds:predlist package_name =
let m = query package_name in
let r =
try Fl_metascanner.lookup "requires" predlist m.package_defs
with Not_found -> ""
in
let ancestors = Fl_split.in_words r @
fixup_thread_base predlist package_name in
List.iter
(fun p ->
try
()
with
No_such_package(pname,_) ->
raise(No_such_package(pname, "required by `" ^ package_name ^ "'"))
)
ancestors;
ancestors
;;
let add_relations s ancestors package_name =
Part of [ requires ] implementation : Adds the relations from [ package_name ]
* to [ ancestors ] . Target store is [ s ] .
* to [ancestors]. Target store is [s].
*)
List.iter
(fun p ->
try
with
| Fl_topo.Inconsistent_ordering ->
raise(Package_loop p)
| Not_found ->
()
)
ancestors
;;
let add_all_relations predlist s =
let pkgs = ref [] in
Fl_metastore.iter_up
(fun p -> pkgs := p :: !pkgs)
s;
List.iter
(fun p ->
let pkg = p.package_name in
try
let pkg_ancestors = query_requirements predlist pkg in
add_relations s pkg_ancestors pkg
with
| No_such_package(n,reason) ->
p.package_priv.missing_reqs <-
(n,reason) :: p.package_priv.missing_reqs
)
!pkgs
;;
let fixup_thread_deps s =
let pkgs = ref [] in
Fl_metastore.iter_up
(fun p -> pkgs := p.package_name :: !pkgs)
s;
List.iter
(fun pkg ->
if fixup_thread_needed_2 pkg then (
try
with
Not_found ->
()
)
)
!pkgs
;;
let requires ~preds:predlist package_name =
returns names of packages required by [ package_name ] , the fully qualified
* name of the package . It is checked that the packages really exist .
* [ predlist ] : list of true predicates
* May raise [ No_such_package ] or [ Package_loop ] .
* name of the package. It is checked that the packages really exist.
* [predlist]: list of true predicates
* May raise [No_such_package] or [Package_loop].
*)
let ancestors = query_requirements predlist package_name in
add_relations store' ancestors package_name;
if List.mem "mt" predlist then fixup_thread_deps store';
ancestors
;;
let requires_deeply ~preds:predlist package_list =
returns names of packages required by the packages in [ package_list ] ,
* either directly or indirectly .
* It is checked that the packages really exist .
* The list of names is sorted topologically ; first comes the deepest
* ancestor .
* [ predlist ] : list of true predicates
* - raises [ Not_found ] if there is no ' package '
* - raises [ Failure ] if some of the ancestors do not exist
* either directly or indirectly.
* It is checked that the packages really exist.
* The list of names is sorted topologically; first comes the deepest
* ancestor.
* [predlist]: list of true predicates
* - raises [Not_found] if there is no 'package'
* - raises [Failure] if some of the ancestors do not exist
*)
let pkgset = ref StringSet.empty in
let rec query_packages pkglist =
match pkglist with
pkg :: pkglist' ->
if not(StringSet.mem pkg !pkgset) then begin
let pkg_ancestors = query_requirements predlist pkg in
pkgset := StringSet.add pkg !pkgset;
query_packages pkg_ancestors
end;
query_packages pkglist'
| [] ->
()
in
First query for all packages , such that they are loaded :
query_packages package_list;
let store' = Fl_metastore.copy store in
add_all_relations predlist store';
if List.mem "mt" predlist then fixup_thread_deps store';
let l = ref [] in
Fl_metastore.iter_up_at
(fun m ->
if StringSet.mem m.package_name !pkgset then (
if m.package_priv.missing_reqs <> [] then (
let (n,reason) = List.hd m.package_priv.missing_reqs in
raise(No_such_package(n,reason))
);
l := m.package_name :: !l
)
)
store'
package_list;
List.rev !l
;;
The following two functions do not use ! ocamlpath , because there may
* be duplicates in it .
* be duplicates in it.
*)
let package_definitions ~search_path package_name =
Return all META files defining this [ package_name ] that occur in the
* directories mentioned in [ search_path ]
* directories mentioned in [search_path]
*)
let package_name_comps = Fl_split.package_name package_name in
if package_name_comps = [] then invalid_arg "Fl_package_base.package_definitions";
let main_name = List.hd package_name_comps in
let rec run_ocamlpath path =
match path with
[] -> []
| dir :: path' ->
let package_dir = Filename.concat dir main_name in
let meta_file_1 = Filename.concat package_dir "META" in
let meta_file_2 = Filename.concat dir ("META." ^ main_name) in
if Sys.file_exists meta_file_1 then
meta_file_1 :: run_ocamlpath path'
else
if Sys.file_exists meta_file_2 then
meta_file_2 :: run_ocamlpath path'
else
run_ocamlpath path'
in
run_ocamlpath search_path
;;
let in_report_search_path identify_dir d =
Whether package dir d is to be considered for generating reports .
d is sorted out when the ignore_dups_in option is set
d is sorted out when the ignore_dups_in option is set
*)
List.for_all
(fun id ->
try identify_dir d <> identify_dir id
with _ -> Fl_split.norm_dir d <> Fl_split.norm_dir id
)
!conf_ignore_dups_in
;;
let package_conflict_report_1 identify_dir () =
let remove_dups_from_path p =
let dir_identity = Hashtbl.create 20 in
let rec remove p =
match p with
d :: p' ->
begin try
if Hashtbl.mem dir_identity id then
remove p'
else begin
Hashtbl.add dir_identity id ();
d :: (remove p')
end
with error ->
d :: (remove p')
end
| [] ->
[]
in
remove p
in
If we have ignore_dups_in this directory is removed from our search
path first
path first
*)
let search_path0 =
List.filter (in_report_search_path identify_dir) !ocamlpath in
let search_path =
remove_dups_from_path search_path0 in
Fl_metastore.iter_up
(fun pkg ->
let package_name_comps = Fl_split.package_name pkg.package_name in
match package_name_comps with
[_] ->
( let c = package_definitions search_path pkg.package_name in
match c with
[]
| [_] ->
()
| _ ->
Printf.eprintf "findlib: [WARNING] Package %s has multiple definitions in %s\n"
pkg.package_name
(String.concat ", " c)
)
| _ ->
()
)
store;
flush stderr
;;
let package_conflict_report ?identify_dir () =
match identify_dir with
None -> package_conflict_report_1 (fun s -> s) ()
| Some f -> package_conflict_report_1 f ()
;;
let check_prefix ?prefix f =
match prefix with
| None -> true
| Some prefix ->
let len = String.length prefix in
String.length f >= len && String.sub f 0 len = prefix
let load_base ?prefix () =
let list_directory d =
try
Array.to_list(Sys.readdir d)
with
Sys_error msg ->
prerr_endline ("findlib: [WARNING] cannot read directory " ^ msg);
[]
in
let process_file ?directory_required main_name package_dir meta_file =
try
let _ = Fl_metastore.find store main_name in
()
with
Not_found ->
let packages =
try
packages_in_meta_file
?directory_required ~name:main_name ~dir:package_dir ~meta_file ()
with
Failure s ->
prerr_endline ("findlib: [WARNING] " ^ s); []
in
List.iter (Fl_metastore.add store) packages;
in
let rec run_ocamlpath path =
match path with
[] -> ()
| dir :: path' ->
let files = list_directory dir in
List.iter
(fun f ->
if check_prefix ?prefix f
then
If f / META exists : Add package f
let package_dir = Filename.concat dir f in
let meta_file_1 = Filename.concat package_dir "META" in
if Sys.file_exists meta_file_1 then
process_file f package_dir meta_file_1
else
If f is : Add package pkgname
if String.length f >= 6 && String.sub f 0 5 = "META." &&
String.sub f (String.length f - 1) 1 <> "~" then begin
let name = String.sub f 5 (String.length f - 5) in
let meta_file_2 = Filename.concat dir f in
process_file ~directory_required:true name dir meta_file_2
end;
)
files;
run_ocamlpath path'
in
run_ocamlpath !ocamlpath
;;
let list_packages ?prefix () =
load_base ?prefix ();
let l = ref [] in
Fl_metastore.iter_up
(fun m ->
if check_prefix ?prefix m.package_name then
l := m.package_name :: !l
)
store;
!l
;;
let package_users ~preds pl =
List.iter
(fun p -> let _ = query p in ())
pl;
load_base();
let store' = Fl_metastore.copy store in
add_all_relations preds store';
if List.mem "mt" preds then fixup_thread_deps store';
let l = ref [] in
Fl_metastore.iter_down_at
(fun m ->
if m.package_priv.missing_reqs <> [] then (
let (n,reason) = List.hd m.package_priv.missing_reqs in
raise(No_such_package(n,reason))
);
l := m.package_name :: !l
)
store'
pl;
!l
;;
let module_conflict_report_1 identify_dir incpath =
let dir_of_module = Hashtbl.create 100 in
let dirs = ref [] in
let examine_dir d =
try
let d = Fl_split.norm_dir d in
let d_id = identify_dir d in
if not (List.mem d_id !dirs) then begin
dirs := d_id :: !dirs;
Yes : Get all files ending in .cmi
try
or Sys_error
let d_cmi =
List.filter
(fun n -> Filename.check_suffix n ".cmi")
d_all in
List.iter
(fun m ->
try
entry := d :: !entry
with
Not_found ->
Hashtbl.add dir_of_module m (ref [d])
)
d_cmi
with
Sys_error msg ->
prerr_endline ("findlib: [WARNING] cannot read directory " ^ msg)
end
with
in
let print_report() =
Hashtbl.iter
(fun m dlist ->
match !dlist with
[]
| [_] ->
()
| _ ->
Printf.eprintf "findlib: [WARNING] Interface %s occurs in several directories: %s\n"
m
(String.concat ", " !dlist)
)
dir_of_module
in
If we have ignore_dups_in this directory is removed from our search
path first
path first
*)
let incpath1 =
List.filter (in_report_search_path identify_dir) incpath in
List.iter examine_dir incpath1;
print_report();
flush stderr
;;
let module_conflict_report ?identify_dir incpath =
match identify_dir with
None -> module_conflict_report_1 (fun s -> s) incpath
| Some f -> module_conflict_report_1 f incpath
;;
|
c147de00ce9305b5510a8690e81b6e8058f6f92d8d105e96d980180684d98887 | LexiFi/menhir | patricia.mli | (******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
(* file LICENSE. *)
(* *)
(******************************************************************************)
This is an implementation of , following 's paper at the 1998 ML Workshop in Baltimore .
Both big - endian and little - endian trees are provided . Both sets and maps are implemented on top of trees .
Both big-endian and little-endian trees are provided. Both sets and maps are implemented on top of Patricia
trees. *)
module Little : GMap.S with type key = int
module Big : GMap.S with type key = int
| null | https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/src/patricia.mli | ocaml | ****************************************************************************
file LICENSE.
**************************************************************************** |
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
This is an implementation of , following 's paper at the 1998 ML Workshop in Baltimore .
Both big - endian and little - endian trees are provided . Both sets and maps are implemented on top of trees .
Both big-endian and little-endian trees are provided. Both sets and maps are implemented on top of Patricia
trees. *)
module Little : GMap.S with type key = int
module Big : GMap.S with type key = int
|
a603b397ae5d8f9961538eebf582dc00a44964649d4f0baddcdca4b00325b990 | cardmagic/lucash | posixstr.scm | Regexp - ADT - > Posix - string translator .
January 1997 , May 1998 .
- If the regexp value contains nul character constants , or character sets
that contain the nul character , they will show up in the string
we produce . 's C regexp engine can handle regexp strings that
contain nul bytes , but this might blow up other implementations -- that
is , the nul byte might prematurely terminate the C string passed to the
;;; regexp engine.
;;;
- The code is ASCII - specific in only one place : the expression for
a regexp that matches nothing is the 6 - char pattern " [ ^\000-\177 ] " ,
which assumes a 7 - bit character code . Note that the static simplifier
;;; can remove *all* occurences of this "empty regexp" except for the
un - simplifiable case of a single , top - level empty regexp , e.g.
;;; (rx (in))
;;; We can handle this one special case specially, so we shouldn't *ever*
;;; have to produce this ASCII-specific pattern.
;;; Exports: regexp->posix-string
;;; Todo: A dumb, simple char-set renderer.
These functions translate static regular expressions into regexp
strings . They generally return four values :
;;; - string (regexp)
;;;
- syntax level : 0 parenthesized exp , 1 piece , 2 branch , 3 top
( " piece " , " branch " and " top " are 's terms ):
;;; + A parenthesized exp is syntactically equivalent to a piece.
;;; (But it's useful to know when an exp is parenthesized for
eliminating redundant submatch - generated parens . )
;;; + A piece is something that would bind to a following *
;;; ("a" but not "aa").
;;; + A branch is a sequence of pieces -- something that would bind to a |
;;; ("ab*d" but not "ab*|d"). That is, a branch is not allowed to contain
;;; top-level |'s.
;;; + Top is for a sequence of branches -- "a|b*c|d".
;;;
;;; - paren count in the returned string.
;;;
;;; [This is a newer description; is it correct?]
- A vector mapping submatches ( vector index 0 is submatch 1 )
to the paren for that submatch ( the first paren is paren # 1 ) .
;;;
;;; [This is my original description.]
- Vector of parens numbers used for submatching . The first paren is
numbered 1 . # F means a dead submatch -- one we can tell statically
;;; will never match anything.
Non - R4RS imports :
;;; ? = COND
;;; Multiple-value return: VALUES RECEIVE CALL-WITH-VALUES
;;; SORT-LIST
;;; Useful little utility -- pad vector V with
;;; PRE initial and POST following #f's.
(define (pad-vector pre post v)
(if (= pre post 0) v
(let* ((vlen (vector-length v))
(alen (+ pre post vlen))
(ans (make-vector alen #f)))
(do ((from (- vlen 1) (- from 1))
(to (+ pre vlen -1) (- to 1)))
((< from 0))
(vector-set! ans to (vector-ref v from)))
ans)))
(define (n-falses n) (make-vector n #f))
;;; There's no representation for regexps that never match anything (e.g.,
( | ) ) in strict notation . When we get one of these , we treat it
specially , producing [ # f # f # f # f ] .
;;;
;;; We can always detect these empty regexps, because they always simplify
to one of these two values :
;;; - (make-re-char-set char-set:empty)
;;; - (dsm m n (make-re-char-set char-set:empty))
(define (simple-empty-re? re)
(or (and (re-char-set? re)
(char-set-empty? (re-char-set:cset re)))
(and (re-dsm? re)
(simple-empty-re? (re-dsm:body re)))))
;;; Top-level
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (regexp->posix-string re)
;; We *must* simplify, to guarantee correct translation.
(let ((re (simplify-regexp re)))
(if (simple-empty-re? re) (values #f #f #f '#())
(translate-regexp re))))
(define (translate-regexp re)
(cond
((re-string? re) (translate-string (re-string:chars re)))
((re-repeat? re) (translate-repeat re))
((re-choice? re) (translate-choice re))
((re-seq? re) (translate-seq re))
((re-char-set? re) (translate-char-set (re-char-set:cset re)))
((re-submatch? re) (translate-submatch re))
((re-bos? re) (values "^" 1 0 '#()))
((re-eos? re) (values "$" 1 0 '#()))
((re-bol? re) (error "Beginning-of-line regexp not supported in this implementation."))
((re-eol? re) (error "End-of-line regexp not supported in this implementation."))
((re-dsm? re) (let ((pre-dsm (re-dsm:pre-dsm re))
(body (re-dsm:body re)))
(translate-dsm body pre-dsm
(- (re-dsm:tsm re)
(+ pre-dsm (re-tsm body))))))
(else (error "Illegal regular expression" re))))
;;; Translate reloc-elt ELT = (N . RE) from a sequence or choice
into a string .
- Relocate the submatch indices by PREV - PCOUNT .
;;; (That is, assume rendering preceding elts used PREV-PCOUNT parens.)
;;; - Assume preceding elements allocated PREV-SMCOUNT submatches
;;; (we may have to pad our returned submatches string with some
;;; initial #F's to account for dead submatches PREV-SMCOUNT through N.)
- If SUB - LEV3 ? is true , the result string is guaranteed to be < level 3 .
;;; This is used by the & and | translators.
- Returns the usual 4 values plus the final submatch count including
;;; this regexp.
(define (translate-elt elt prev-pcount prev-smcount sub-lev3?)
(let ((offset (car elt))
(re (cdr elt)))
(receive (s level pcount submatches) (translate-regexp re)
Relocate submatch indices by OFFSET and force level <3 , if needed :
(receive (s level pcount submatches)
(if (and sub-lev3? (= level 3))
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv (lambda (sm) (and sm (+ prev-pcount 1 sm)))
submatches))
(values s level pcount
(mapv (lambda (sm) (and sm (+ prev-pcount sm)))
submatches)))
;; Tack onto submatches as many initial #F's as needed to bump
the previous submatches count from PREV - SMCOUNT to OFFSET .
(values s level pcount
(pad-vector (- offset prev-smcount) 0 submatches)
(+ offset (re-tsm re)))))))
Force the string to be level < 3 by parenthesizing it if necessary .
(define (paren-if-necessary s lev pcount submatches)
(if (< lev 3)
(values s lev pcount submatches)
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv (lambda (sm) (and sm (+ 1 sm)))
submatches))))
;;; (: re1 ... ren)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (translate-seq re)
(let ((elts (re-seq:elts re))
(tsm (re-seq:tsm re)))
(let recur ((elts elts) (prev-pcount 0) (prev-smcount 0))
Render a sequence tail ELTS , assuming the previous elements translated
;; to a string with PREV-PCOUNT parens, and allocated PREV-SMCOUNT
;; submatches.
(if (pair? elts)
(let* ((elt (car elts))
(elts (cdr elts)))
(receive (s1 level1 pcount1 submatches1)
(translate-regexp elt)
(receive (s1 level1 pcount1 submatches1)
(paren-if-necessary s1 level1 pcount1 submatches1)
(receive (s level pcount submatches)
(recur elts
(+ pcount1 prev-pcount)
(+ prev-smcount (re-tsm elt)))
(values (string-append s1 s)
2
(+ pcount1 pcount)
(vector-append (mapv (lambda (p) (and p (+ p prev-pcount)))
submatches1)
submatches))))))
(values "" 2 0 '#()))))) ; Empty seq
;;; (| re1 ... ren)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (translate-choice re)
(let ((elts (re-choice:elts re))
(tsm (re-choice:tsm re)))
(if (pair? elts)
(let recur ((elts elts) (prev-pcount 0) (prev-smcount 0))
ELTS is a non - empty choice tail . Render it , assuming the
;; previous elements translated to a string with PREV-PCOUNT parens,
;; and allocated PREV-SMCOUNT submatches.
(let ((elt (car elts)) (tail (cdr elts)))
(receive (s1 level1 pcount1 submatches1) (translate-regexp elt)
(let ((submatches1 (mapv (lambda (sm) (and sm (+ sm prev-pcount)))
submatches1)))
(if (pair? tail)
(receive (s level pcount submatches)
(recur tail
(+ pcount1 prev-pcount)
(+ prev-smcount (re-tsm elt)))
(values (string-append s1 "|" s) 3
(+ pcount1 pcount)
(vector-append submatches1 submatches)))
(values s1 level1 pcount1 submatches1))))))
(values "[^\000-\377]" 1 0 (n-falses tsm))))) ; Empty choice.
;;; Repeated cases: * + ? and {n,m} ranges.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (translate-repeat re)
(let ((from (re-repeat:from re))
(to (re-repeat:to re))
(body (re-repeat:body re))
(tsm (re-repeat:tsm re)))
(cond
((and to (> from to)) ; Unsatisfiable
(values "[^\000-\377]" 1 0 (n-falses tsm)))
((and to (= from to 1)) (translate-seq body)) ; RE{1,1} => RE
((and to (= to 0)) ; RE{0,0} => ""
(values "" 2 0 (n-falses tsm)))
(else ; General case
(receive (s level pcount submatches) (translate-regexp body)
Coerce S to level < 2 .
(if (> level 1)
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv (lambda (i) (and i (+ i 1))) submatches))
(values s level pcount submatches))
(values (if to
(cond ((and (= from 0) (= to 1)) (string-append s "?"))
((= from to)
(string-append s "{" (number->string to) "}"))
(else
(string-append s "{" (number->string from)
"," (number->string to) "}")))
(cond ((= from 0) (string-append s "*"))
((= from 1) (string-append s "+"))
(else (string-append s "{" (number->string from) ",}"))))
1 pcount submatches)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (translate-submatch re)
(let ((body (re-submatch:body re))
(pre-dsm (re-submatch:pre-dsm re)))
;; Translate the body, along with any leading or trailing dead submatches.
(receive (s level pcount submatches)
(translate-dsm body
pre-dsm
(- (re-submatch:tsm re)
(+ 1 pre-dsm (re-tsm body))))
If the whole expression is n't already wrapped in a paren , wrap it .
This outer paren becomes the new submatch -- add to submatches list .
(if (= level 0)
(values s 0 pcount (vector-append '#(1) submatches))
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv! (lambda (i) (and i (+ i 1))) ; Excuse me.
(vector-append '#(0) submatches)))))))
;;; Translating DSM
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Translate the body, and paste enough #F's before and after the submatches
;;; list to account for extra dead submatches.
(define (translate-dsm body pre-dsm post-dsm)
(receive (s level pcount submatches) (translate-regexp body)
(values s level pcount (pad-vector pre-dsm post-dsm submatches))))
;;; Constant regexps
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Convert a string into a regexp pattern that matches that string exactly --
;;; quote the special chars with backslashes.
(define translate-string
(let ((specials (string->char-set "{}[.*?()|\\$^+")))
(lambda (s)
(let ((len (string-length s)))
(if (zero? len)
(values "()" 0 1 '#()) ; Special case ""
(let* ((len2 (string-fold (lambda (c len) ; Length of answer str
(+ len (if (char-set-contains? specials c) 2 1)))
0 s))
(s2 (make-string len2))) ; Answer string
;; Copy the chars over to S2.
(string-fold (lambda (c i)
;; Write char C at index I, return the next index.
(let ((i (cond ((char-set-contains? specials c)
(string-set! s2 i #\\)
(+ i 1))
(else i))))
(string-set! s2 i c)
(+ i 1)))
0 s)
(values s2 (if (= len 1) 1 2)
0 '#())))))))
;;; Translating char-sets to [...] strings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This is the nastiest code in the system. We make an effort to return
;;; succinct encodings of the char-sets, in the event these encodings are
;;; being shown to humans.
;;; - A singleton set is rendered as that char.
;;; - A full set is rendered as "."
;;; - An empty set is rendered as [^\000-\177].
;;; - Otherwise, render it both as a [...] and as a [^...] spec, and
;;; take whichever is shortest.
;;; Take a char set, and return the standard
[ regexp - string , level , pcount , ]
;;; quadruple.
;;;
(define *nul* (ascii->char 0))
(define (translate-char-set cset)
(if (char-set-full? cset)
(values "." 1 0 '#()) ; Full set
(let* ((cset (char-set-delete cset *nul*))
(nchars (char-set-size cset))
(->bracket-string (lambda (cset in?)
(receive (loose ranges) (char-set->in-pair cset)
(hack-bracket-spec loose ranges in?)))))
(cond
((= 0 nchars) (values "[^\000-\177]" 1 0 '#())) ; Empty set
Singleton set
(translate-string (string (car (char-set->list cset)))))
;; General case. Try both [...] and [^...].
(else (let ((s- (->bracket-string cset #t))
(s+ (->bracket-string
(char-set-delete (char-set-complement cset) *nul*)
#f)))
(values (if (< (string-length s-) (string-length s+))
s- s+)
1 0 '#())))))))
;;; Commentary
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Hacking special chars in character-class strings:
;;; ] - ^ ]...^-
;;; ] - ]...-
;;; ] ^ ]...^
;;; ] ]...
;;; - ^ ...^- (or doubleton screw-case)
;;; - ...-
;;; ^ ...^ (or singleton screw-case)
;;;
Two screw cases :
;;; "^-" must be converted to "-^" for IN.
;;; "^" must be converted to non-class "^" for IN.
Rendering a general char - set into a correct [ ... ] bracket expression
;;; is a complete mess.
;;;
;;; The rules on bracket expressions:
- ] terminates the exp unless it is the first char
;;; (after an optional leading ^).
;;; - .*[\ are not special in bracket expressions.
;;; - However, [. [= and [: *are* special, so you can't follow an
open bracket by one of .= : . See below .
- ^ is n't special unless it 's the first char .
- - is special unless it 's first ( after an optional ^ ) , last ,
;;; or as the ending char in a range (e.g., a--).
;;; This means:
;;; - You must ensure that ] doesn't begin or terminate a range.
;;; - You must ensure that .=: don't follow [
;;; + This can happen in the loose char list;
;;; + This can happen in the range list -- consider the pair of
;;; ranges "x-[.-%" Handle this by prohibiting [ as a range-terminator.
;;; + It can happen at the loose/range boundary: %[:-?
First , run - length encode the set into loose and range - pairs .
;;; If the set is a singleton set, then punt the whole [...] effort,
;;; and do it as a simple char.
;;; Repeat until stable:
;;; - Sort the ranges in this order:
1 . other ranges ;
2 . ranges that begin with ^ ( not priority )
3 . ranges that begin with .= : ( priority )
4 . ranges that end with [ ( priority )
;;; This eliminates [. [= [: problems in the ranges, and
;;; minimises the chances of the problem at the loose/range boundary.
;;; and problems with initial ^ chars.
- Sort the loose chars so that ] is first , then - , then .= : , then [ ,
;;; then others, then ^. This eliminates [. [= [: problems in the loose
;;; chars, and minimises the chances of the problem at the loose/range
;;; boundary.
;;; - Shrink ranges by moving an opening or closing range char into the
;;; loose-char set:
;;; + If ] opens or closes a range, shrink it out.
;;; + If any range opens with -, shrink it out.
+ If the first range opens with .= : , and the last loose char is [ ,
;;; shrink it out.
+ If there are no loose chars , the first range begins with ^ , and
;;; we're doing an IN range, shrink out the ^.
+ Shrinking a range down to means move it 's elts into the
;;; loose char set.
;;; - If both [ and - are in the loose char set,
;;; pull - out as special end-hypen.
;;; Finally, we have to hack things so that ^ doesn't begin an IN sequence.
;;; - If it's a NOT-IN sequence, no worries.
;;; - If ^ is the opening loose char, then it's the only loose char.
;;; If there are ranges, move it to the end of the string.
;;; If there are no ranges, then just punt the char-class and convert
;;; it to a singleton ^. In fact, do this up-front, for any singleton
;;; set.
;;;
;;; If the special end-hyphen flag is set, add - to the end of the string.
;;; This general approach -- starting out with maximal ranges, and then
;;; shrinking them to avoid other syntax violations -- has the advantage
;;; of not relying on the details of the ASCII encodings.
;;; Ordering ranges:
1 . other ranges ( ordered by start char )
2 . ranges that begin with ^ ( not priority )
3 . ranges that begin with .= :
4 . ranges that end with [ ( priority over # 2 & # 3 )
(define (range< r1 r2)
(let ((r1-start (car r1)) (r1-end (cdr r1))
(r2-start (car r2)) (r2-end (cdr r2)))
(or (char=? r2-end #\[) ; Range ending with [ comes last.
(and (not (char=? r1-end #\[))
Range begin with one of .= : comes next - to - last
(or (char=? r2-start #\.) (char=? r2-start #\=) (char=? r2-start #\:)
(and (not (char=? r1-start #\.))
(not (char=? r1-start #\=))
(not (char=? r1-start #\:))
;; Range beginning with ^ comes before that.
(or (char=? r1-start #\^)
(and (not (char=? r2-start #\^))
;; Other ranges are ordered by start char.
(< (char->ascii r1-start)
(char->ascii r2-start))))))))))
;;; Order loose chars:
] is first ,
;;; - is next,
;;; .=: are next,
;;; [ is next,
then others ( ordered by )
;;; ^ is last.
(define (loose<= c1 c2)
] is first ,
(and (not (char=? c2 #\]))
(or (char=? c1 #\-) ; - is next,
(and (not (char=? c2 #\-))
;; .=: are next,
(or (char=? c1 #\.) (char=? c1 #\=) (char=? c1 #\:)
(and (not (char=? c2 #\.))
(not (char=? c2 #\=))
(not (char=? c2 #\:))
(or (char=? c1 #\[) ; [ is next,
(and (not (char=? c2 #\[))
(or (char=? c2 #\^) ; ^ is last,
(and (not (char=? c1 #\^))
;; other chars by ASCII.
(<= (char->ascii c1)
(char->ascii c2)))))))))))))
Returns ( 1 ) a list of 0 - 3 loose chars , ( 2 ) a list of 0 or 1 ranges .
(define (shrink-range-start r)
(let ((start (char->ascii (car r)))
(end (char->ascii (cdr r))))
(shrink-range-finish-up start (+ start 1) end)))
(define (shrink-range-end r)
(let ((start (char->ascii (car r)))
(end (char->ascii (cdr r))))
(shrink-range-finish-up end start (- end 1))))
(define (shrink-range-finish-up c start end)
(cond
((> start end) (values (list (ascii->char c)) '())) ; Empty range
((= start end) ; Collapse singleton range.
(values (list (ascii->char c) (ascii->char start))
'()))
((= (+ start 1) end) ; Collapse doubleton range.
(values (list (ascii->char c) (ascii->char start) (ascii->char end))
'()))
(else (values (list (ascii->char c))
(list (cons (ascii->char start) (ascii->char end)))))))
;;; We assume the bracket-spec is not a singleton, not empty, and not complete.
;;; (These cases get rendered as the letter, [^\000-\177], and ".",
;;; respectively.) We assume the loose chars and the ranges are all disjoint.
(define (hack-bracket-spec loose ranges in?)
(let lp ((loose0 loose) (ranges0 ranges) (end-hyphen? #f))
;; Repeat until stable:
(let ((loose (sort-list loose0 loose<=)) ; Sort loose chars and ranges.
(ranges (sort-list ranges0 range<)))
;; If ] opens or closes a range, shrink it out.
;; If - opens a range, shrink it out.
(receive (loose ranges)
(let recur ((ranges ranges))
(if (pair? ranges)
(let* ((range (car ranges))
(start (car range))
(end (cdr range))
(ranges (cdr ranges)))
(receive (new-loose new-ranges) (recur ranges)
(receive (new-loose0 new-ranges0)
(cond ((char=? #\] start)
(shrink-range-start range))
((char=? #\] end)
(shrink-range-end range))
((char=? #\- start)
(shrink-range-start range))
(else (values '() (list range))))
(values (append new-loose0 new-loose)
(append new-ranges0 new-ranges)))))
(values loose '())))
(let ((loose (sort-list loose loose<=)) ; Sort loose chars and ranges.
(ranges (sort-list ranges range<)))
(cond
((or (not (equal? loose0 loose)) ; Loop if anything changed.
(not (equal? ranges0 ranges)))
(lp loose ranges end-hyphen?))
If the first range opens with .= : , and the last loose char is [ ,
;; shrink it out & loop.
((and (pair? ranges)
(memv (caar ranges) '(#\. #\= #\:))
(pair? loose)
(char=? #\[ (car (reverse loose))))
(receive (new-loose new-ranges)
(shrink-range-start (car ranges))
(lp (append new-loose loose) (append new-ranges (cdr ranges)) end-hyphen?)))
If there are no loose chars , the first range begins with ^ , and
;; we're doing an IN range, shrink out the ^.
((and in? (null? loose) (pair? ranges) (char=? #\^ (caar ranges)))
(receive (new-loose new-ranges) (shrink-range-start (car ranges))
(lp (append new-loose loose) (append new-ranges ranges) end-hyphen?)))
;; If both ] and - are in the loose char set,
;; pull - out as special end-hypen.
((and (pair? loose)
(pair? (cdr loose))
(char=? (car loose) #\])
(char=? (cadr loose) #\-))
(lp (cons (car loose) (cddr loose)) ranges #t))
;; No change! Build the answer...
(else (string-append (if in? "[" "[^")
(list->string loose)
(apply string-append
(map (lambda (r) (string (car r) #\- (cdr r)))
ranges))
(if end-hyphen? "-" "")
"]"))))))))
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/rx/posixstr.scm | scheme | regexp engine.
can remove *all* occurences of this "empty regexp" except for the
(rx (in))
We can handle this one special case specially, so we shouldn't *ever*
have to produce this ASCII-specific pattern.
Exports: regexp->posix-string
Todo: A dumb, simple char-set renderer.
- string (regexp)
+ A parenthesized exp is syntactically equivalent to a piece.
(But it's useful to know when an exp is parenthesized for
+ A piece is something that would bind to a following *
("a" but not "aa").
+ A branch is a sequence of pieces -- something that would bind to a |
("ab*d" but not "ab*|d"). That is, a branch is not allowed to contain
top-level |'s.
+ Top is for a sequence of branches -- "a|b*c|d".
- paren count in the returned string.
[This is a newer description; is it correct?]
[This is my original description.]
will never match anything.
? = COND
Multiple-value return: VALUES RECEIVE CALL-WITH-VALUES
SORT-LIST
Useful little utility -- pad vector V with
PRE initial and POST following #f's.
There's no representation for regexps that never match anything (e.g.,
We can always detect these empty regexps, because they always simplify
- (make-re-char-set char-set:empty)
- (dsm m n (make-re-char-set char-set:empty))
Top-level
We *must* simplify, to guarantee correct translation.
Translate reloc-elt ELT = (N . RE) from a sequence or choice
(That is, assume rendering preceding elts used PREV-PCOUNT parens.)
- Assume preceding elements allocated PREV-SMCOUNT submatches
(we may have to pad our returned submatches string with some
initial #F's to account for dead submatches PREV-SMCOUNT through N.)
This is used by the & and | translators.
this regexp.
Tack onto submatches as many initial #F's as needed to bump
(: re1 ... ren)
to a string with PREV-PCOUNT parens, and allocated PREV-SMCOUNT
submatches.
Empty seq
(| re1 ... ren)
previous elements translated to a string with PREV-PCOUNT parens,
and allocated PREV-SMCOUNT submatches.
Empty choice.
Repeated cases: * + ? and {n,m} ranges.
Unsatisfiable
RE{1,1} => RE
RE{0,0} => ""
General case
Translate the body, along with any leading or trailing dead submatches.
Excuse me.
Translating DSM
Translate the body, and paste enough #F's before and after the submatches
list to account for extra dead submatches.
Constant regexps
Convert a string into a regexp pattern that matches that string exactly --
quote the special chars with backslashes.
Special case ""
Length of answer str
Answer string
Copy the chars over to S2.
Write char C at index I, return the next index.
Translating char-sets to [...] strings
This is the nastiest code in the system. We make an effort to return
succinct encodings of the char-sets, in the event these encodings are
being shown to humans.
- A singleton set is rendered as that char.
- A full set is rendered as "."
- An empty set is rendered as [^\000-\177].
- Otherwise, render it both as a [...] and as a [^...] spec, and
take whichever is shortest.
Take a char set, and return the standard
quadruple.
Full set
Empty set
General case. Try both [...] and [^...].
Commentary
Hacking special chars in character-class strings:
] - ^ ]...^-
] - ]...-
] ^ ]...^
] ]...
- ^ ...^- (or doubleton screw-case)
- ...-
^ ...^ (or singleton screw-case)
"^-" must be converted to "-^" for IN.
"^" must be converted to non-class "^" for IN.
is a complete mess.
The rules on bracket expressions:
(after an optional leading ^).
- .*[\ are not special in bracket expressions.
- However, [. [= and [: *are* special, so you can't follow an
or as the ending char in a range (e.g., a--).
This means:
- You must ensure that ] doesn't begin or terminate a range.
- You must ensure that .=: don't follow [
+ This can happen in the loose char list;
+ This can happen in the range list -- consider the pair of
ranges "x-[.-%" Handle this by prohibiting [ as a range-terminator.
+ It can happen at the loose/range boundary: %[:-?
If the set is a singleton set, then punt the whole [...] effort,
and do it as a simple char.
Repeat until stable:
- Sort the ranges in this order:
This eliminates [. [= [: problems in the ranges, and
minimises the chances of the problem at the loose/range boundary.
and problems with initial ^ chars.
then others, then ^. This eliminates [. [= [: problems in the loose
chars, and minimises the chances of the problem at the loose/range
boundary.
- Shrink ranges by moving an opening or closing range char into the
loose-char set:
+ If ] opens or closes a range, shrink it out.
+ If any range opens with -, shrink it out.
shrink it out.
we're doing an IN range, shrink out the ^.
loose char set.
- If both [ and - are in the loose char set,
pull - out as special end-hypen.
Finally, we have to hack things so that ^ doesn't begin an IN sequence.
- If it's a NOT-IN sequence, no worries.
- If ^ is the opening loose char, then it's the only loose char.
If there are ranges, move it to the end of the string.
If there are no ranges, then just punt the char-class and convert
it to a singleton ^. In fact, do this up-front, for any singleton
set.
If the special end-hyphen flag is set, add - to the end of the string.
This general approach -- starting out with maximal ranges, and then
shrinking them to avoid other syntax violations -- has the advantage
of not relying on the details of the ASCII encodings.
Ordering ranges:
Range ending with [ comes last.
Range beginning with ^ comes before that.
Other ranges are ordered by start char.
Order loose chars:
- is next,
.=: are next,
[ is next,
^ is last.
- is next,
.=: are next,
[ is next,
^ is last,
other chars by ASCII.
Empty range
Collapse singleton range.
Collapse doubleton range.
We assume the bracket-spec is not a singleton, not empty, and not complete.
(These cases get rendered as the letter, [^\000-\177], and ".",
respectively.) We assume the loose chars and the ranges are all disjoint.
Repeat until stable:
Sort loose chars and ranges.
If ] opens or closes a range, shrink it out.
If - opens a range, shrink it out.
Sort loose chars and ranges.
Loop if anything changed.
shrink it out & loop.
we're doing an IN range, shrink out the ^.
If both ] and - are in the loose char set,
pull - out as special end-hypen.
No change! Build the answer... | Regexp - ADT - > Posix - string translator .
January 1997 , May 1998 .
- If the regexp value contains nul character constants , or character sets
that contain the nul character , they will show up in the string
we produce . 's C regexp engine can handle regexp strings that
contain nul bytes , but this might blow up other implementations -- that
is , the nul byte might prematurely terminate the C string passed to the
- The code is ASCII - specific in only one place : the expression for
a regexp that matches nothing is the 6 - char pattern " [ ^\000-\177 ] " ,
which assumes a 7 - bit character code . Note that the static simplifier
un - simplifiable case of a single , top - level empty regexp , e.g.
These functions translate static regular expressions into regexp
strings . They generally return four values :
- syntax level : 0 parenthesized exp , 1 piece , 2 branch , 3 top
( " piece " , " branch " and " top " are 's terms ):
eliminating redundant submatch - generated parens . )
- A vector mapping submatches ( vector index 0 is submatch 1 )
to the paren for that submatch ( the first paren is paren # 1 ) .
- Vector of parens numbers used for submatching . The first paren is
numbered 1 . # F means a dead submatch -- one we can tell statically
Non - R4RS imports :
(define (pad-vector pre post v)
(if (= pre post 0) v
(let* ((vlen (vector-length v))
(alen (+ pre post vlen))
(ans (make-vector alen #f)))
(do ((from (- vlen 1) (- from 1))
(to (+ pre vlen -1) (- to 1)))
((< from 0))
(vector-set! ans to (vector-ref v from)))
ans)))
(define (n-falses n) (make-vector n #f))
( | ) ) in strict notation . When we get one of these , we treat it
specially , producing [ # f # f # f # f ] .
to one of these two values :
(define (simple-empty-re? re)
(or (and (re-char-set? re)
(char-set-empty? (re-char-set:cset re)))
(and (re-dsm? re)
(simple-empty-re? (re-dsm:body re)))))
(define (regexp->posix-string re)
(let ((re (simplify-regexp re)))
(if (simple-empty-re? re) (values #f #f #f '#())
(translate-regexp re))))
(define (translate-regexp re)
(cond
((re-string? re) (translate-string (re-string:chars re)))
((re-repeat? re) (translate-repeat re))
((re-choice? re) (translate-choice re))
((re-seq? re) (translate-seq re))
((re-char-set? re) (translate-char-set (re-char-set:cset re)))
((re-submatch? re) (translate-submatch re))
((re-bos? re) (values "^" 1 0 '#()))
((re-eos? re) (values "$" 1 0 '#()))
((re-bol? re) (error "Beginning-of-line regexp not supported in this implementation."))
((re-eol? re) (error "End-of-line regexp not supported in this implementation."))
((re-dsm? re) (let ((pre-dsm (re-dsm:pre-dsm re))
(body (re-dsm:body re)))
(translate-dsm body pre-dsm
(- (re-dsm:tsm re)
(+ pre-dsm (re-tsm body))))))
(else (error "Illegal regular expression" re))))
into a string .
- Relocate the submatch indices by PREV - PCOUNT .
- If SUB - LEV3 ? is true , the result string is guaranteed to be < level 3 .
- Returns the usual 4 values plus the final submatch count including
(define (translate-elt elt prev-pcount prev-smcount sub-lev3?)
(let ((offset (car elt))
(re (cdr elt)))
(receive (s level pcount submatches) (translate-regexp re)
Relocate submatch indices by OFFSET and force level <3 , if needed :
(receive (s level pcount submatches)
(if (and sub-lev3? (= level 3))
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv (lambda (sm) (and sm (+ prev-pcount 1 sm)))
submatches))
(values s level pcount
(mapv (lambda (sm) (and sm (+ prev-pcount sm)))
submatches)))
the previous submatches count from PREV - SMCOUNT to OFFSET .
(values s level pcount
(pad-vector (- offset prev-smcount) 0 submatches)
(+ offset (re-tsm re)))))))
Force the string to be level < 3 by parenthesizing it if necessary .
(define (paren-if-necessary s lev pcount submatches)
(if (< lev 3)
(values s lev pcount submatches)
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv (lambda (sm) (and sm (+ 1 sm)))
submatches))))
(define (translate-seq re)
(let ((elts (re-seq:elts re))
(tsm (re-seq:tsm re)))
(let recur ((elts elts) (prev-pcount 0) (prev-smcount 0))
Render a sequence tail ELTS , assuming the previous elements translated
(if (pair? elts)
(let* ((elt (car elts))
(elts (cdr elts)))
(receive (s1 level1 pcount1 submatches1)
(translate-regexp elt)
(receive (s1 level1 pcount1 submatches1)
(paren-if-necessary s1 level1 pcount1 submatches1)
(receive (s level pcount submatches)
(recur elts
(+ pcount1 prev-pcount)
(+ prev-smcount (re-tsm elt)))
(values (string-append s1 s)
2
(+ pcount1 pcount)
(vector-append (mapv (lambda (p) (and p (+ p prev-pcount)))
submatches1)
submatches))))))
(define (translate-choice re)
(let ((elts (re-choice:elts re))
(tsm (re-choice:tsm re)))
(if (pair? elts)
(let recur ((elts elts) (prev-pcount 0) (prev-smcount 0))
ELTS is a non - empty choice tail . Render it , assuming the
(let ((elt (car elts)) (tail (cdr elts)))
(receive (s1 level1 pcount1 submatches1) (translate-regexp elt)
(let ((submatches1 (mapv (lambda (sm) (and sm (+ sm prev-pcount)))
submatches1)))
(if (pair? tail)
(receive (s level pcount submatches)
(recur tail
(+ pcount1 prev-pcount)
(+ prev-smcount (re-tsm elt)))
(values (string-append s1 "|" s) 3
(+ pcount1 pcount)
(vector-append submatches1 submatches)))
(values s1 level1 pcount1 submatches1))))))
(define (translate-repeat re)
(let ((from (re-repeat:from re))
(to (re-repeat:to re))
(body (re-repeat:body re))
(tsm (re-repeat:tsm re)))
(cond
(values "[^\000-\377]" 1 0 (n-falses tsm)))
(values "" 2 0 (n-falses tsm)))
(receive (s level pcount submatches) (translate-regexp body)
Coerce S to level < 2 .
(if (> level 1)
(values (string-append "(" s ")")
0
(+ pcount 1)
(mapv (lambda (i) (and i (+ i 1))) submatches))
(values s level pcount submatches))
(values (if to
(cond ((and (= from 0) (= to 1)) (string-append s "?"))
((= from to)
(string-append s "{" (number->string to) "}"))
(else
(string-append s "{" (number->string from)
"," (number->string to) "}")))
(cond ((= from 0) (string-append s "*"))
((= from 1) (string-append s "+"))
(else (string-append s "{" (number->string from) ",}"))))
1 pcount submatches)))))))
(define (translate-submatch re)
(let ((body (re-submatch:body re))
(pre-dsm (re-submatch:pre-dsm re)))
(receive (s level pcount submatches)
(translate-dsm body
pre-dsm
(- (re-submatch:tsm re)
(+ 1 pre-dsm (re-tsm body))))
If the whole expression is n't already wrapped in a paren , wrap it .
This outer paren becomes the new submatch -- add to submatches list .
(if (= level 0)
(values s 0 pcount (vector-append '#(1) submatches))
(values (string-append "(" s ")")
0
(+ pcount 1)
(vector-append '#(0) submatches)))))))
(define (translate-dsm body pre-dsm post-dsm)
(receive (s level pcount submatches) (translate-regexp body)
(values s level pcount (pad-vector pre-dsm post-dsm submatches))))
(define translate-string
(let ((specials (string->char-set "{}[.*?()|\\$^+")))
(lambda (s)
(let ((len (string-length s)))
(if (zero? len)
(+ len (if (char-set-contains? specials c) 2 1)))
0 s))
(string-fold (lambda (c i)
(let ((i (cond ((char-set-contains? specials c)
(string-set! s2 i #\\)
(+ i 1))
(else i))))
(string-set! s2 i c)
(+ i 1)))
0 s)
(values s2 (if (= len 1) 1 2)
0 '#())))))))
[ regexp - string , level , pcount , ]
(define *nul* (ascii->char 0))
(define (translate-char-set cset)
(if (char-set-full? cset)
(let* ((cset (char-set-delete cset *nul*))
(nchars (char-set-size cset))
(->bracket-string (lambda (cset in?)
(receive (loose ranges) (char-set->in-pair cset)
(hack-bracket-spec loose ranges in?)))))
(cond
Singleton set
(translate-string (string (car (char-set->list cset)))))
(else (let ((s- (->bracket-string cset #t))
(s+ (->bracket-string
(char-set-delete (char-set-complement cset) *nul*)
#f)))
(values (if (< (string-length s-) (string-length s+))
s- s+)
1 0 '#())))))))
Two screw cases :
Rendering a general char - set into a correct [ ... ] bracket expression
- ] terminates the exp unless it is the first char
open bracket by one of .= : . See below .
- ^ is n't special unless it 's the first char .
- - is special unless it 's first ( after an optional ^ ) , last ,
First , run - length encode the set into loose and range - pairs .
2 . ranges that begin with ^ ( not priority )
3 . ranges that begin with .= : ( priority )
4 . ranges that end with [ ( priority )
- Sort the loose chars so that ] is first , then - , then .= : , then [ ,
+ If the first range opens with .= : , and the last loose char is [ ,
+ If there are no loose chars , the first range begins with ^ , and
+ Shrinking a range down to means move it 's elts into the
1 . other ranges ( ordered by start char )
2 . ranges that begin with ^ ( not priority )
3 . ranges that begin with .= :
4 . ranges that end with [ ( priority over # 2 & # 3 )
(define (range< r1 r2)
(let ((r1-start (car r1)) (r1-end (cdr r1))
(r2-start (car r2)) (r2-end (cdr r2)))
(and (not (char=? r1-end #\[))
Range begin with one of .= : comes next - to - last
(or (char=? r2-start #\.) (char=? r2-start #\=) (char=? r2-start #\:)
(and (not (char=? r1-start #\.))
(not (char=? r1-start #\=))
(not (char=? r1-start #\:))
(or (char=? r1-start #\^)
(and (not (char=? r2-start #\^))
(< (char->ascii r1-start)
(char->ascii r2-start))))))))))
] is first ,
then others ( ordered by )
(define (loose<= c1 c2)
] is first ,
(and (not (char=? c2 #\]))
(and (not (char=? c2 #\-))
(or (char=? c1 #\.) (char=? c1 #\=) (char=? c1 #\:)
(and (not (char=? c2 #\.))
(not (char=? c2 #\=))
(not (char=? c2 #\:))
(and (not (char=? c2 #\[))
(and (not (char=? c1 #\^))
(<= (char->ascii c1)
(char->ascii c2)))))))))))))
Returns ( 1 ) a list of 0 - 3 loose chars , ( 2 ) a list of 0 or 1 ranges .
(define (shrink-range-start r)
(let ((start (char->ascii (car r)))
(end (char->ascii (cdr r))))
(shrink-range-finish-up start (+ start 1) end)))
(define (shrink-range-end r)
(let ((start (char->ascii (car r)))
(end (char->ascii (cdr r))))
(shrink-range-finish-up end start (- end 1))))
(define (shrink-range-finish-up c start end)
(cond
(values (list (ascii->char c) (ascii->char start))
'()))
(values (list (ascii->char c) (ascii->char start) (ascii->char end))
'()))
(else (values (list (ascii->char c))
(list (cons (ascii->char start) (ascii->char end)))))))
(define (hack-bracket-spec loose ranges in?)
(let lp ((loose0 loose) (ranges0 ranges) (end-hyphen? #f))
(ranges (sort-list ranges0 range<)))
(receive (loose ranges)
(let recur ((ranges ranges))
(if (pair? ranges)
(let* ((range (car ranges))
(start (car range))
(end (cdr range))
(ranges (cdr ranges)))
(receive (new-loose new-ranges) (recur ranges)
(receive (new-loose0 new-ranges0)
(cond ((char=? #\] start)
(shrink-range-start range))
((char=? #\] end)
(shrink-range-end range))
((char=? #\- start)
(shrink-range-start range))
(else (values '() (list range))))
(values (append new-loose0 new-loose)
(append new-ranges0 new-ranges)))))
(values loose '())))
(ranges (sort-list ranges range<)))
(cond
(not (equal? ranges0 ranges)))
(lp loose ranges end-hyphen?))
If the first range opens with .= : , and the last loose char is [ ,
((and (pair? ranges)
(memv (caar ranges) '(#\. #\= #\:))
(pair? loose)
(char=? #\[ (car (reverse loose))))
(receive (new-loose new-ranges)
(shrink-range-start (car ranges))
(lp (append new-loose loose) (append new-ranges (cdr ranges)) end-hyphen?)))
If there are no loose chars , the first range begins with ^ , and
((and in? (null? loose) (pair? ranges) (char=? #\^ (caar ranges)))
(receive (new-loose new-ranges) (shrink-range-start (car ranges))
(lp (append new-loose loose) (append new-ranges ranges) end-hyphen?)))
((and (pair? loose)
(pair? (cdr loose))
(char=? (car loose) #\])
(char=? (cadr loose) #\-))
(lp (cons (car loose) (cddr loose)) ranges #t))
(else (string-append (if in? "[" "[^")
(list->string loose)
(apply string-append
(map (lambda (r) (string (car r) #\- (cdr r)))
ranges))
(if end-hyphen? "-" "")
"]"))))))))
|
a2c81d280755e8c270c2d508b4f8ee9426f9891858c7957d29ef7f2c1659f1dd | AmpersandTarski/Ampersand | Runners.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
-- | Utilities for running stack commands.
--
-- Instead of using Has-style classes below, the type signatures use
-- concrete environments to try and avoid accidentally rerunning
-- configuration parsing. For example, we want @withConfig $
-- withConfig $ ...@ to fail.
module Ampersand.Runners
( -- withBuildConfig
-- , withEnvConfig
-- , withDefaultEnvConfig
withConfig,
, withGlobalProject
withRunnerGlobal,
logLevel,
, ShouldReexec ( .. )
)
where
import Ampersand.Basics
--import RIO.Time (addUTCTime, getCurrentTime)
import Stack . Build . Target(NeedTargets ( .. ) )
import Ampersand.Types.Config
import RIO.Process (mkDefaultProcessContext)
import Stack . Constants
import Stack . DefaultColorWhen ( defaultColorWhen )
import qualified Stack . as
import qualified Stack . Nix as Nix
import Stack . Setup
import Stack . Storage . User ( upgradeChecksSince , logUpgradeCheck )
import Stack . Types . Config
import Stack . Types . ( dockerEnable )
import Stack . Types . Nix ( nixEnable )
import Stack . Types . Version ( stackMinorVersion , stackVersion , minorVersion )
import System.Console.ANSI (hSupportsANSIWithoutEmulation)
import System.Console.Terminal.Size (size, width)
-- -- | Ensure that no project settings are used when running 'withConfig'.
-- withGlobalProject :: RIO Runner a -> RIO Runner a
-- withGlobalProject inner = do
-- oldSYL <- view stackYamlLocL
-- case oldSYL of
-- SYLDefault -> local (set stackYamlLocL SYLGlobalProject) inner
-- _ -> throwString "Cannot use this command with options which override the stack.yaml location"
-- -- | Helper for 'withEnvConfig' which passes in some default arguments:
-- --
-- -- * No targets are requested
-- --
-- -- * Default command line build options are assumed
-- withDefaultEnvConfig
: : RIO EnvConfig a
-- -> RIO Config a
withDefaultEnvConfig = withEnvConfig AllowNoTargets defaultBuildOptsCLI
-- | Upgrade a ' Config ' environment to an ' EnvConfig ' environment by
-- -- performing further parsing of project-specific configuration (like
-- -- 'withBuildConfig') and then setting up a build environment
-- -- toolchain. This is intended to be run inside a call to
-- -- 'withConfig'.
-- withEnvConfig
: : NeedTargets
-- -> BuildOptsCLI
-- -> RIO EnvConfig a
-- ^ Action that uses the build config . If is enabled for builds ,
-- this will be run in a container .
-- -> RIO Config a
withEnvConfig needTargets boptsCLI inner =
-- withBuildConfig $ do
-- envConfig <- setupEnv needTargets boptsCLI Nothing
" Starting to execute command inside EnvConfig "
runRIO envConfig inner
-- | If the settings justify it , should we reexec inside or ?
data ShouldReexec = YesReexec | NoReexec
-- | Load the configuration. Convenience function used
-- throughout this module.
withConfig ::
RIO Config a ->
RIO Runner a
withConfig inner =
loadConfig $ \config -> do
runRIO config $ do
-- -- Catching all exceptions here, since we don't want this
-- check to ever cause to stop working
shouldUpgradeCheck ` catchAny ` \e - >
-- logError ("Error when running shouldUpgradeCheck: " <> displayShow e)
inner
-- | Perform a or , if warranted . Otherwise run the
-- -- inner action.
-- reexec :: RIO Config a -> RIO Config a
-- reexec inner = do
nixEnable ' < - asks $ nixEnable . configNix
dockerEnable ' < - asks $ dockerEnable . configDocker
case ( nixEnable ' , dockerEnable ' ) of
( True , True ) - > throwString " Can not use both and at the same time "
-- (False, False) -> inner
-- Want to use
-- (True, False) -> do
whenM getInContainer $ throwString " Can not use from within a container "
-- inShell <- getInNixShell
-- if inShell
-- then do
-- isReexec <- view reExecL
-- if isReexec
-- then inner
else throwString " In shell but reExecL is False "
-- else Nix.runShellAndExit
-- Want to use
-- (False, True) -> do
whenM getInNixShell $ throwString " Can not use from within a Nix shell "
-- inContainer <- getInContainer
-- if inContainer
-- then do
-- isReexec <- view reExecL
-- if isReexec
-- then inner
else throwIO . OnlyOnHostException
-- else Docker.runContainerAndExit
-- | Use the 'GlobalOpts' to create a 'Runner' and run the provided
-- action.
withRunnerGlobal :: GlobalOpts -> RIO Runner a -> IO a
withRunnerGlobal go inner = do
useColor <-
fromMaybe True
<$> hSupportsANSIWithoutEmulation stderr
let defaultTerminalWidth = 100
termWidth <-
clipWidth
<$> maybe
( fromMaybe defaultTerminalWidth
<$> (fmap width <$> size)
)
pure
(globalTermWidth go)
menv <- mkDefaultProcessContext
logOptions0 <- logOptionsHandle stderr False
let logOptions =
setLogUseColor useColor
. setLogUseTime (globalTimeInLog go)
. setLogMinLevel (globalLogLevel go)
. setLogVerboseFormat (globalLogLevel go <= LevelDebug)
. setLogTerminal (globalTerminal go)
$ logOptions0
withLogFunc logOptions $ \logFunc ->
runRIO
Runner
{ runnerGlobalOpts = go,
runnerUseColor = useColor,
runnerLogFunc = logFunc,
runnerTermWidth = termWidth,
runnerProcessContext = menv
}
inner
where
minTerminalWidth = 40
maxTerminalWidth = 200
clipWidth w
| w < minTerminalWidth = minTerminalWidth
| w > maxTerminalWidth = maxTerminalWidth
| otherwise = w
-- | Check if we should recommend upgrading Stack and , if so , recommend it .
-- shouldUpgradeCheck :: RIO Config ()
-- shouldUpgradeCheck = do
-- config <- ask
-- when (configRecommendUpgrade config) $ do
-- now <- getCurrentTime
let yesterday = addUTCTime ( -24 * 60 * 60 ) now
checks < - upgradeChecksSince yesterday
-- when (checks == 0) $ do
-- mversion <- getLatestHackageVersion NoRequireHackageIndex "stack" UsePreferredVersions
-- case mversion of
-- -- Compare the minor version so we avoid patch-level, Hackage-only releases.
-- -- See: #pullrequestreview-227176315
-- Just (PackageIdentifierRevision _ version _) | minorVersion version > stackMinorVersion -> do
-- logWarn "<<<<<<<<<<<<<<<<<<"
-- logWarn $
" You are currently using Stack version " < >
-- fromString (versionString stackVersion) <>
-- ", but version " <>
-- fromString (versionString version) <>
-- " is available"
-- logWarn "You can try to upgrade by running 'stack upgrade'"
-- logWarn $
-- "Tired of seeing this? Add 'recommend-stack-upgrade: false' to " <>
-- fromString (toFilePath (configUserConfigPath config))
-- logWarn ">>>>>>>>>>>>>>>>>>"
-- logWarn ""
-- logWarn ""
-- _ -> pure ()
-- logUpgradeCheck now
logLevel :: Runner -> LogLevel
logLevel = globalLogLevel . runnerGlobalOpts
| null | https://raw.githubusercontent.com/AmpersandTarski/Ampersand/cb2306a09ce79d5609ccf8d3e28c0a1eb45feafe/src/Ampersand/Runners.hs | haskell | | Utilities for running stack commands.
Instead of using Has-style classes below, the type signatures use
concrete environments to try and avoid accidentally rerunning
configuration parsing. For example, we want @withConfig $
withConfig $ ...@ to fail.
withBuildConfig
, withEnvConfig
, withDefaultEnvConfig
import RIO.Time (addUTCTime, getCurrentTime)
-- | Ensure that no project settings are used when running 'withConfig'.
withGlobalProject :: RIO Runner a -> RIO Runner a
withGlobalProject inner = do
oldSYL <- view stackYamlLocL
case oldSYL of
SYLDefault -> local (set stackYamlLocL SYLGlobalProject) inner
_ -> throwString "Cannot use this command with options which override the stack.yaml location"
-- | Helper for 'withEnvConfig' which passes in some default arguments:
--
-- * No targets are requested
--
-- * Default command line build options are assumed
withDefaultEnvConfig
-> RIO Config a
| Upgrade a ' Config ' environment to an ' EnvConfig ' environment by
-- performing further parsing of project-specific configuration (like
-- 'withBuildConfig') and then setting up a build environment
-- toolchain. This is intended to be run inside a call to
-- 'withConfig'.
withEnvConfig
-> BuildOptsCLI
-> RIO EnvConfig a
^ Action that uses the build config . If is enabled for builds ,
this will be run in a container .
-> RIO Config a
withBuildConfig $ do
envConfig <- setupEnv needTargets boptsCLI Nothing
| If the settings justify it , should we reexec inside or ?
| Load the configuration. Convenience function used
throughout this module.
-- Catching all exceptions here, since we don't want this
check to ever cause to stop working
logError ("Error when running shouldUpgradeCheck: " <> displayShow e)
| Perform a or , if warranted . Otherwise run the
-- inner action.
reexec :: RIO Config a -> RIO Config a
reexec inner = do
(False, False) -> inner
Want to use
(True, False) -> do
inShell <- getInNixShell
if inShell
then do
isReexec <- view reExecL
if isReexec
then inner
else Nix.runShellAndExit
Want to use
(False, True) -> do
inContainer <- getInContainer
if inContainer
then do
isReexec <- view reExecL
if isReexec
then inner
else Docker.runContainerAndExit
| Use the 'GlobalOpts' to create a 'Runner' and run the provided
action.
| Check if we should recommend upgrading Stack and , if so , recommend it .
shouldUpgradeCheck :: RIO Config ()
shouldUpgradeCheck = do
config <- ask
when (configRecommendUpgrade config) $ do
now <- getCurrentTime
when (checks == 0) $ do
mversion <- getLatestHackageVersion NoRequireHackageIndex "stack" UsePreferredVersions
case mversion of
-- Compare the minor version so we avoid patch-level, Hackage-only releases.
-- See: #pullrequestreview-227176315
Just (PackageIdentifierRevision _ version _) | minorVersion version > stackMinorVersion -> do
logWarn "<<<<<<<<<<<<<<<<<<"
logWarn $
fromString (versionString stackVersion) <>
", but version " <>
fromString (versionString version) <>
" is available"
logWarn "You can try to upgrade by running 'stack upgrade'"
logWarn $
"Tired of seeing this? Add 'recommend-stack-upgrade: false' to " <>
fromString (toFilePath (configUserConfigPath config))
logWarn ">>>>>>>>>>>>>>>>>>"
logWarn ""
logWarn ""
_ -> pure ()
logUpgradeCheck now | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
module Ampersand.Runners
withConfig,
, withGlobalProject
withRunnerGlobal,
logLevel,
, ShouldReexec ( .. )
)
where
import Ampersand.Basics
import Stack . Build . Target(NeedTargets ( .. ) )
import Ampersand.Types.Config
import RIO.Process (mkDefaultProcessContext)
import Stack . Constants
import Stack . DefaultColorWhen ( defaultColorWhen )
import qualified Stack . as
import qualified Stack . Nix as Nix
import Stack . Setup
import Stack . Storage . User ( upgradeChecksSince , logUpgradeCheck )
import Stack . Types . Config
import Stack . Types . ( dockerEnable )
import Stack . Types . Nix ( nixEnable )
import Stack . Types . Version ( stackMinorVersion , stackVersion , minorVersion )
import System.Console.ANSI (hSupportsANSIWithoutEmulation)
import System.Console.Terminal.Size (size, width)
: : RIO EnvConfig a
withDefaultEnvConfig = withEnvConfig AllowNoTargets defaultBuildOptsCLI
: : NeedTargets
withEnvConfig needTargets boptsCLI inner =
" Starting to execute command inside EnvConfig "
runRIO envConfig inner
data ShouldReexec = YesReexec | NoReexec
withConfig ::
RIO Config a ->
RIO Runner a
withConfig inner =
loadConfig $ \config -> do
runRIO config $ do
shouldUpgradeCheck ` catchAny ` \e - >
inner
nixEnable ' < - asks $ nixEnable . configNix
dockerEnable ' < - asks $ dockerEnable . configDocker
case ( nixEnable ' , dockerEnable ' ) of
( True , True ) - > throwString " Can not use both and at the same time "
whenM getInContainer $ throwString " Can not use from within a container "
else throwString " In shell but reExecL is False "
whenM getInNixShell $ throwString " Can not use from within a Nix shell "
else throwIO . OnlyOnHostException
withRunnerGlobal :: GlobalOpts -> RIO Runner a -> IO a
withRunnerGlobal go inner = do
useColor <-
fromMaybe True
<$> hSupportsANSIWithoutEmulation stderr
let defaultTerminalWidth = 100
termWidth <-
clipWidth
<$> maybe
( fromMaybe defaultTerminalWidth
<$> (fmap width <$> size)
)
pure
(globalTermWidth go)
menv <- mkDefaultProcessContext
logOptions0 <- logOptionsHandle stderr False
let logOptions =
setLogUseColor useColor
. setLogUseTime (globalTimeInLog go)
. setLogMinLevel (globalLogLevel go)
. setLogVerboseFormat (globalLogLevel go <= LevelDebug)
. setLogTerminal (globalTerminal go)
$ logOptions0
withLogFunc logOptions $ \logFunc ->
runRIO
Runner
{ runnerGlobalOpts = go,
runnerUseColor = useColor,
runnerLogFunc = logFunc,
runnerTermWidth = termWidth,
runnerProcessContext = menv
}
inner
where
minTerminalWidth = 40
maxTerminalWidth = 200
clipWidth w
| w < minTerminalWidth = minTerminalWidth
| w > maxTerminalWidth = maxTerminalWidth
| otherwise = w
let yesterday = addUTCTime ( -24 * 60 * 60 ) now
checks < - upgradeChecksSince yesterday
" You are currently using Stack version " < >
logLevel :: Runner -> LogLevel
logLevel = globalLogLevel . runnerGlobalOpts
|
f6f7e24555c804cab40e1e47cbe6f2f24bce9b18a83d343099a8a62fa74a38f3 | ericthorsen/enclojure-repl | repl_history.clj | (comment
;*
* Copyright ( c ) ThorTech , L.L.C .. All rights reserved .
;* The use and distribution terms for this software are covered by the
;* Eclipse Public License 1.0 (-1.0.php)
;* which can be found in the file epl-v10.html at the root of this distribution.
;* By using this software in any fashion, you are agreeing to be bound by
;* the terms of this license.
;* You must not remove this notice, or any other, from this software.
;*
* Author :
)
(ns #^{ :author "Eric Thorsen",
:doc "Support code for managing history for a REPL instance.
There is a log which stores only unique commands (uses a hash of the expression)
and there is a list used for history at the command line of the REPL. Here
dups are allowed but it won't repeat the last command. Assume the following
commands are typed in and executed in the REPL:
(+ 1 1)
(/ 23 1)
(+ 1 1)
(+ 1 1)
The command line history list will contain:
(+ 1 1)
(/ 23 1)
(+ 1 1)
The history log will contain:
(+ 1 1)
(/ 23 1)
There are 2 functions that need to be implemented in the IReplWindow
interface that are used by this module for displaying the log.
[showHistory [] java.awt.Component]
[getHistoryLogFile [] java.lang.String]
See the org.enclojure.ide.repl.interface-factory for definitions of these
classes.
"}
org.enclojure.ide.repl.repl-history
(:require [org.enclojure.commons.c-slf4j :as logger])
(:import (java.util.logging Level Logger)
(java.awt.event KeyEvent)))
; setup logging
(logger/ensure-logger)
(defn- new-history
"A blank history data item or you can pass in a list of items.
These functions just help out with the management
of navigating and keeping track of where you are in a list."
([]
{:index nil
:history-list []
:forms-set #{}})
([history-list]
(let [hlist (if (and history-list
(pos? (count history-list)))
history-list [])
has-elements? (pos? (count hlist))]
{:history-list hlist
:index (when has-elements? (count hlist))
:forms-set (if has-elements?
(reduce conj #{} hlist)
#{})
})))
(defn new-history-ref
"A blank history data item or you can pass in a list of items.
These functions just help out with the management
of navigating and keeping track of where you are in a list."
[& args]
(ref
(apply new-history args)
:validator #(= 3 (count (select-keys %1 [:index :history-list :forms-set])))))
(defn check-bounds
[{:keys [index history-list] } inx]
(let [c (count history-list)]
(when (and inx index history-list
(>= inx 0) (< inx c)))))
(defn nav-index
"Move the index of the history item based on the key-event"
[history key-code]
(let [{:keys [index history-list] } history]
(if index
(let [c (dec (count history-list))]
(merge history
{:index
({KeyEvent/VK_DOWN (min (inc index) c)
KeyEvent/VK_UP (max 0 (dec index))}
key-code)}))
history)))
(defn nav-history
"Based on the key-event, return the next history item"
[history key-event]
(let [{:keys [index history-list] } history]
(if (and (pos? (count history-list))
(.isControlDown key-event)
(#{KeyEvent/VK_UP KeyEvent/VK_DOWN} (.getKeyCode key-event)))
(do
(.consume key-event)
(nav-index history (.getKeyCode key-event)))
history)))
(defn get-current-item [history]
(let [{:keys [index history-list]} history]
(when (and index history-list)
((:history-list history) index))))
(defn add-history-item
"Add the form to history unless it is a duplicate of the tail of the list.
The index of the list is always set to the last item after this function is called."
[{:keys [index history-list forms-set] :as history} form]
(if (or (nil? index)
(not= form (last history-list)))
(assoc history
:history-list (conj history-list form)
:index (inc (count history-list)))
(assoc history :index (count history-list))))
| null | https://raw.githubusercontent.com/ericthorsen/enclojure-repl/eeae31ba5ddccde5a1aa11a122db6e8d8a49cd8f/org-enclojure-repl-client/src/main/clojure/org/enclojure/ide/repl/repl_history.clj | clojure | *
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
*
setup logging | (comment
* Copyright ( c ) ThorTech , L.L.C .. All rights reserved .
* Author :
)
(ns #^{ :author "Eric Thorsen",
:doc "Support code for managing history for a REPL instance.
There is a log which stores only unique commands (uses a hash of the expression)
and there is a list used for history at the command line of the REPL. Here
dups are allowed but it won't repeat the last command. Assume the following
commands are typed in and executed in the REPL:
(+ 1 1)
(/ 23 1)
(+ 1 1)
(+ 1 1)
The command line history list will contain:
(+ 1 1)
(/ 23 1)
(+ 1 1)
The history log will contain:
(+ 1 1)
(/ 23 1)
There are 2 functions that need to be implemented in the IReplWindow
interface that are used by this module for displaying the log.
[showHistory [] java.awt.Component]
[getHistoryLogFile [] java.lang.String]
See the org.enclojure.ide.repl.interface-factory for definitions of these
classes.
"}
org.enclojure.ide.repl.repl-history
(:require [org.enclojure.commons.c-slf4j :as logger])
(:import (java.util.logging Level Logger)
(java.awt.event KeyEvent)))
(logger/ensure-logger)
(defn- new-history
"A blank history data item or you can pass in a list of items.
These functions just help out with the management
of navigating and keeping track of where you are in a list."
([]
{:index nil
:history-list []
:forms-set #{}})
([history-list]
(let [hlist (if (and history-list
(pos? (count history-list)))
history-list [])
has-elements? (pos? (count hlist))]
{:history-list hlist
:index (when has-elements? (count hlist))
:forms-set (if has-elements?
(reduce conj #{} hlist)
#{})
})))
(defn new-history-ref
"A blank history data item or you can pass in a list of items.
These functions just help out with the management
of navigating and keeping track of where you are in a list."
[& args]
(ref
(apply new-history args)
:validator #(= 3 (count (select-keys %1 [:index :history-list :forms-set])))))
(defn check-bounds
[{:keys [index history-list] } inx]
(let [c (count history-list)]
(when (and inx index history-list
(>= inx 0) (< inx c)))))
(defn nav-index
"Move the index of the history item based on the key-event"
[history key-code]
(let [{:keys [index history-list] } history]
(if index
(let [c (dec (count history-list))]
(merge history
{:index
({KeyEvent/VK_DOWN (min (inc index) c)
KeyEvent/VK_UP (max 0 (dec index))}
key-code)}))
history)))
(defn nav-history
"Based on the key-event, return the next history item"
[history key-event]
(let [{:keys [index history-list] } history]
(if (and (pos? (count history-list))
(.isControlDown key-event)
(#{KeyEvent/VK_UP KeyEvent/VK_DOWN} (.getKeyCode key-event)))
(do
(.consume key-event)
(nav-index history (.getKeyCode key-event)))
history)))
(defn get-current-item [history]
(let [{:keys [index history-list]} history]
(when (and index history-list)
((:history-list history) index))))
(defn add-history-item
"Add the form to history unless it is a duplicate of the tail of the list.
The index of the list is always set to the last item after this function is called."
[{:keys [index history-list forms-set] :as history} form]
(if (or (nil? index)
(not= form (last history-list)))
(assoc history
:history-list (conj history-list form)
:index (inc (count history-list)))
(assoc history :index (count history-list))))
|
b1181c1cb90b27ef8a0c8745b702e97601a1f90d94cc6dc5a2323626d2127b7c | vbmithr/ocaml-libbitcoin | error.mli | open Ctypes
type t = private Error of unit ptr
val of_ptr : unit ptr -> t
val message : t -> string option
| null | https://raw.githubusercontent.com/vbmithr/ocaml-libbitcoin/b93a5cca1d430c38dd822b45e47fc5132fb28ab9/src/error.mli | ocaml | open Ctypes
type t = private Error of unit ptr
val of_ptr : unit ptr -> t
val message : t -> string option
| |
a9ff9b336906ba64943de80038fa1a1ddad9aecedb518c16525c5838473ec90f | nasser/magic | pprint.clj | pprint.clj -- Pretty printer and Common Lisp compatible format function ( cl - format ) for Clojure
Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
Author :
April 3 , 2009
(ns
^{:author "Tom Faulhaber",
:doc "A Pretty Printer for Clojure
clojure.pprint implements a flexible system for printing structured data
in a pleasing, easy-to-understand format. Basic use of the pretty printer is
simple, just call pprint instead of println. More advanced users can use
the building blocks provided to create custom output formats.
Out of the box, pprint supports a simple structured format for basic data
and a specialized format for Clojure source code. More advanced formats,
including formats that don't look like Clojure data at all like XML and
JSON, can be rendered by creating custom dispatch functions.
In addition to the pprint function, this module contains cl-format, a text
formatting function which is fully compatible with the format function in
Common Lisp. Because pretty printing directives are directly integrated with
cl-format, it supports very concise custom dispatch. It also provides
a more powerful alternative to Clojure's standard format function.
See documentation for pprint and cl-format for more information or
complete documentation on the Clojure web site on GitHub.",
:added "1.2"}
clojure.pprint
(:refer-clojure :exclude (deftype))
(:use [clojure.walk :only [walk]]))
(set! *warn-on-reflection* true)
(load "pprint/utilities")
(load "pprint/column_writer")
(load "pprint/pretty_writer")
(load "pprint/pprint_base")
(load "pprint/cl_format")
(load "pprint/dispatch")
(load "pprint/print_table")
nil
| null | https://raw.githubusercontent.com/nasser/magic/7a46f773bc7785c82d9527d52c1a8c28ac16e195/src/stdlib/clojure/pprint.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | pprint.clj -- Pretty printer and Common Lisp compatible format function ( cl - format ) for Clojure
Copyright ( c ) . All rights reserved .
Author :
April 3 , 2009
(ns
^{:author "Tom Faulhaber",
:doc "A Pretty Printer for Clojure
clojure.pprint implements a flexible system for printing structured data
in a pleasing, easy-to-understand format. Basic use of the pretty printer is
simple, just call pprint instead of println. More advanced users can use
the building blocks provided to create custom output formats.
Out of the box, pprint supports a simple structured format for basic data
and a specialized format for Clojure source code. More advanced formats,
including formats that don't look like Clojure data at all like XML and
JSON, can be rendered by creating custom dispatch functions.
In addition to the pprint function, this module contains cl-format, a text
formatting function which is fully compatible with the format function in
Common Lisp. Because pretty printing directives are directly integrated with
cl-format, it supports very concise custom dispatch. It also provides
a more powerful alternative to Clojure's standard format function.
See documentation for pprint and cl-format for more information or
complete documentation on the Clojure web site on GitHub.",
:added "1.2"}
clojure.pprint
(:refer-clojure :exclude (deftype))
(:use [clojure.walk :only [walk]]))
(set! *warn-on-reflection* true)
(load "pprint/utilities")
(load "pprint/column_writer")
(load "pprint/pretty_writer")
(load "pprint/pprint_base")
(load "pprint/cl_format")
(load "pprint/dispatch")
(load "pprint/print_table")
nil
|
845c83a8fa2b17badcb2041c75b682c8a851fe2030fa9f61f83c48acfc4909f6 | 0zat/gen-bs | js_args.ml | open Js
open Js_type
open Bs_external
let to_js_arg_type necessity type_ =
match necessity with
| `Fixed -> type_
| `Optional -> (`Undef type_)
| `Variadic -> (`Array type_)
let to_bs_arg (js_arg : js_arg) =
let js_arg_type = to_js_arg_type js_arg.necessity js_arg.type_ in
let type_ = to_arg_type js_arg_type in
match js_arg.necessity with
| `Fixed -> to_label_arg js_arg.name type_
| `Optional -> to_optional_arg js_arg.name type_
| `Variadic -> to_label_arg js_arg.name type_
let to_bs_args args =
List.map to_bs_arg args
let to_owner_arg name =
let obj = to_owner_type name in
to_label_arg name obj
| null | https://raw.githubusercontent.com/0zat/gen-bs/20348991775d9ef3974c3b824968a0ab219502a8/src/intermediate/js_to_bs/js_obj_to_module/from_js/js_args.ml | ocaml | open Js
open Js_type
open Bs_external
let to_js_arg_type necessity type_ =
match necessity with
| `Fixed -> type_
| `Optional -> (`Undef type_)
| `Variadic -> (`Array type_)
let to_bs_arg (js_arg : js_arg) =
let js_arg_type = to_js_arg_type js_arg.necessity js_arg.type_ in
let type_ = to_arg_type js_arg_type in
match js_arg.necessity with
| `Fixed -> to_label_arg js_arg.name type_
| `Optional -> to_optional_arg js_arg.name type_
| `Variadic -> to_label_arg js_arg.name type_
let to_bs_args args =
List.map to_bs_arg args
let to_owner_arg name =
let obj = to_owner_type name in
to_label_arg name obj
| |
22c9c8855ddfd7a531dc0c9cebc1c8921c6e4db481945e225d66d8f9027c3bbb | marcoheisig/adventofcode | day-04.lisp | (defpackage :adventofcode-2018-day-4
(:use :cl))
(in-package :adventofcode-2018-day-4)
(defclass record ()
((%who :initarg :who :accessor record-who)
(%what :initarg :what :reader record-what)
(%when :initarg :when :reader record-when)))
(defclass guard ()
((%id :initarg :id :reader guard-id)
(%sleep-vector :reader sleep-vector
:initform (make-array 60 :initial-element 0))))
(defmethod print-object ((record record) stream)
(print-unreadable-object (record stream :type t)
(format stream "~A ~A ~A"
(record-when record)
(record-who record)
(record-what record))))
(defmethod print-object ((guard guard) stream)
(print-unreadable-object (guard stream :type t)
(format stream "~A" (guard-id guard))))
(defvar *guards* nil
"A hash table, mapping from guards ids to guards.")
(defun guard (id)
(multiple-value-bind (guard present-p)
(gethash id *guards*)
(if present-p
guard
(let ((guard (make-instance 'guard :id id)))
(setf (gethash id *guards*) guard)
guard))))
(defun parse-record (string)
(multiple-value-bind (match substrings)
(cl-ppcre:scan-to-strings
"\\[([0-9]+)-([0-9]+)-([0-9]+) +([0-9]+):([0-9]+)\\] (.*)"
string)
(assert match)
(let ((action (aref substrings 5)))
(multiple-value-bind (who what)
(ecase (schar action 0)
(#\w (values '? :wakes-up))
(#\f (values '? :falls-asleep))
(#\G (values
(guard
(parse-integer action :start (1+ (position #\# action))
:junk-allowed t))
:begins-shift)))
(make-instance 'record
:who who
:what what
:when (local-time:encode-timestamp
0
0
(parse-integer (aref substrings 4))
(parse-integer (aref substrings 3))
(parse-integer (aref substrings 2))
(parse-integer (aref substrings 1))
(parse-integer (aref substrings 0))))))))
(defun read-records (file)
(with-open-file (stream file :direction :input)
(loop for line = (read-line stream nil nil)
while line
collect (parse-record line))))
(defun fixup-records (records)
(let ((who '?)
(records (sort (copy-list records) #'local-time:timestamp<=
:key #'record-when)))
(loop for record in records do
(if (eq (record-what record) :begins-shift)
(setf who (record-who record))
(setf (record-who record) who)))
records))
(defun process-records (records)
(let ((records (fixup-records records))
(sleep-start nil))
(labels ((call-with-next-record (fn)
(unless (null records)
(with-accessors ((who record-who)
(when record-when)
(what record-what))
(pop records)
(funcall fn who what when))))
(initial-state (who what when)
(declare (ignore who when))
(unless (eq what :begins-shift)
(error "Cannot ~A before any shift has begun." what))
(call-with-next-record #'awake-state))
(awake-state (who what when)
(ecase what
(:begins-shift
(call-with-next-record #'awake-state))
(:wakes-up
(error "Guard ~D cannot wake up twice." who))
(:falls-asleep
(setf sleep-start when)
(call-with-next-record #'sleeping-state))))
(sleeping-state (who what when)
(ecase what
((:begins-shift :wakes-up)
(let ((start (local-time:timestamp-minute sleep-start))
(end (local-time:timestamp-minute when))
(sleep-vector (sleep-vector who)))
(loop for index from start below end do
(incf (svref sleep-vector index))))
(call-with-next-record #'awake-state))
(:falls-asleep
(error "Guard ~D cannot fall asleep twice." who)))))
(call-with-next-record #'initial-state))))
(defun read-guards (input)
(let ((*guards* (make-hash-table)))
(process-records (read-records "input"))
(loop for guard being the hash-values of *guards*
collect guard)))
(defun total-sleep (guard)
(reduce #'+ (sleep-vector guard)))
(defun max-sleep (guard)
(reduce #'max (sleep-vector guard)))
(defun solve-problem-1 ()
(let ((sleepy (first (sort (read-guards "input") #'> :key #'total-sleep))))
(* (guard-id sleepy)
(position (max-sleep sleepy) (sleep-vector sleepy)))))
(defun solve-problem-2 ()
(let ((sleepy (first (sort (read-guards "input") #'> :key #'max-sleep))))
(* (guard-id sleepy)
(position (max-sleep sleepy) (sleep-vector sleepy)))))
| null | https://raw.githubusercontent.com/marcoheisig/adventofcode/e96a0da17cd79f424af984ed2648b49ffdacb893/2018/day-04/day-04.lisp | lisp | (defpackage :adventofcode-2018-day-4
(:use :cl))
(in-package :adventofcode-2018-day-4)
(defclass record ()
((%who :initarg :who :accessor record-who)
(%what :initarg :what :reader record-what)
(%when :initarg :when :reader record-when)))
(defclass guard ()
((%id :initarg :id :reader guard-id)
(%sleep-vector :reader sleep-vector
:initform (make-array 60 :initial-element 0))))
(defmethod print-object ((record record) stream)
(print-unreadable-object (record stream :type t)
(format stream "~A ~A ~A"
(record-when record)
(record-who record)
(record-what record))))
(defmethod print-object ((guard guard) stream)
(print-unreadable-object (guard stream :type t)
(format stream "~A" (guard-id guard))))
(defvar *guards* nil
"A hash table, mapping from guards ids to guards.")
(defun guard (id)
(multiple-value-bind (guard present-p)
(gethash id *guards*)
(if present-p
guard
(let ((guard (make-instance 'guard :id id)))
(setf (gethash id *guards*) guard)
guard))))
(defun parse-record (string)
(multiple-value-bind (match substrings)
(cl-ppcre:scan-to-strings
"\\[([0-9]+)-([0-9]+)-([0-9]+) +([0-9]+):([0-9]+)\\] (.*)"
string)
(assert match)
(let ((action (aref substrings 5)))
(multiple-value-bind (who what)
(ecase (schar action 0)
(#\w (values '? :wakes-up))
(#\f (values '? :falls-asleep))
(#\G (values
(guard
(parse-integer action :start (1+ (position #\# action))
:junk-allowed t))
:begins-shift)))
(make-instance 'record
:who who
:what what
:when (local-time:encode-timestamp
0
0
(parse-integer (aref substrings 4))
(parse-integer (aref substrings 3))
(parse-integer (aref substrings 2))
(parse-integer (aref substrings 1))
(parse-integer (aref substrings 0))))))))
(defun read-records (file)
(with-open-file (stream file :direction :input)
(loop for line = (read-line stream nil nil)
while line
collect (parse-record line))))
(defun fixup-records (records)
(let ((who '?)
(records (sort (copy-list records) #'local-time:timestamp<=
:key #'record-when)))
(loop for record in records do
(if (eq (record-what record) :begins-shift)
(setf who (record-who record))
(setf (record-who record) who)))
records))
(defun process-records (records)
(let ((records (fixup-records records))
(sleep-start nil))
(labels ((call-with-next-record (fn)
(unless (null records)
(with-accessors ((who record-who)
(when record-when)
(what record-what))
(pop records)
(funcall fn who what when))))
(initial-state (who what when)
(declare (ignore who when))
(unless (eq what :begins-shift)
(error "Cannot ~A before any shift has begun." what))
(call-with-next-record #'awake-state))
(awake-state (who what when)
(ecase what
(:begins-shift
(call-with-next-record #'awake-state))
(:wakes-up
(error "Guard ~D cannot wake up twice." who))
(:falls-asleep
(setf sleep-start when)
(call-with-next-record #'sleeping-state))))
(sleeping-state (who what when)
(ecase what
((:begins-shift :wakes-up)
(let ((start (local-time:timestamp-minute sleep-start))
(end (local-time:timestamp-minute when))
(sleep-vector (sleep-vector who)))
(loop for index from start below end do
(incf (svref sleep-vector index))))
(call-with-next-record #'awake-state))
(:falls-asleep
(error "Guard ~D cannot fall asleep twice." who)))))
(call-with-next-record #'initial-state))))
(defun read-guards (input)
(let ((*guards* (make-hash-table)))
(process-records (read-records "input"))
(loop for guard being the hash-values of *guards*
collect guard)))
(defun total-sleep (guard)
(reduce #'+ (sleep-vector guard)))
(defun max-sleep (guard)
(reduce #'max (sleep-vector guard)))
(defun solve-problem-1 ()
(let ((sleepy (first (sort (read-guards "input") #'> :key #'total-sleep))))
(* (guard-id sleepy)
(position (max-sleep sleepy) (sleep-vector sleepy)))))
(defun solve-problem-2 ()
(let ((sleepy (first (sort (read-guards "input") #'> :key #'max-sleep))))
(* (guard-id sleepy)
(position (max-sleep sleepy) (sleep-vector sleepy)))))
| |
855d4ed63d1d071458d62fb5b6cdd97fff2144276e11d778e26887893ee5557f | lexi-lambda/racket-curly-fn | info.rkt | #lang info
(define collection 'multi)
(define deps
'())
(define build-deps
'("base"
"curly-fn-lib"
"rackunit-lib"))
| null | https://raw.githubusercontent.com/lexi-lambda/racket-curly-fn/d64cd71d5b386be85f5979edae6f6b6469a4df86/curly-fn-test/info.rkt | racket | #lang info
(define collection 'multi)
(define deps
'())
(define build-deps
'("base"
"curly-fn-lib"
"rackunit-lib"))
| |
ab18eb8d2632f8a43b5d5a72bca231f30cb0858b2ba25aab5b856c0cd1fee38a | drlivingston/kabob | taxon.clj |
iao / ncbi_taxon / NCBI_TAXON_215158_ICE
iao / ncbi_taxon / NCBI_TAXON_215158_ICE
` { : name " ncbitaxon - ice - gen "
;; :head ((?/ice obo/IAO_0000219 ?/subclass))
;; :body ((?/subclass [rdfs/subClassOf *] obo/NCBITaxon_1))
;; :reify ([?/ice {:ln (:localname ?/subclass)
: ns " iaoncbitaxon " : prefix " " : suffix " _ ICE " } ] ) }
`{:name "ncbitaxon-ice-gen"
:head ((?/ice obo/IAO_0000219 ?/subclass))
:body ((?/subclass [rdfs/subClassOf *] obo/NCBITaxon_1))
:reify ([?/ice {:ln (:regex "obo/NCBITaxon" "NCBI_TAXON" ?/subclass)
:ns "iaoncbitaxon" :prefix "" :suffix "_ICE"}])}
| null | https://raw.githubusercontent.com/drlivingston/kabob/7038076849744c959da9c8507e8a8ab7215410aa/kabob-build/src/main/resources/edu/ucdenver/ccp/kabob/build/rules/temp/bio_to_ice/taxon.clj | clojure | :head ((?/ice obo/IAO_0000219 ?/subclass))
:body ((?/subclass [rdfs/subClassOf *] obo/NCBITaxon_1))
:reify ([?/ice {:ln (:localname ?/subclass) |
iao / ncbi_taxon / NCBI_TAXON_215158_ICE
iao / ncbi_taxon / NCBI_TAXON_215158_ICE
` { : name " ncbitaxon - ice - gen "
: ns " iaoncbitaxon " : prefix " " : suffix " _ ICE " } ] ) }
`{:name "ncbitaxon-ice-gen"
:head ((?/ice obo/IAO_0000219 ?/subclass))
:body ((?/subclass [rdfs/subClassOf *] obo/NCBITaxon_1))
:reify ([?/ice {:ln (:regex "obo/NCBITaxon" "NCBI_TAXON" ?/subclass)
:ns "iaoncbitaxon" :prefix "" :suffix "_ICE"}])}
|
f1a047f6ae70fe017fcdf1852aa665be51a1c62183d2badc4bfb7f018ed9dbc3 | johnlawrenceaspden/hobby-code | memoize.clj | ;;I noticed the other day that clojure has built in support for memoization,
;;which is a technique for remembering the return values of functions which
;;take a while to calculate
;;The classic example of when this can be useful is
;;the naive fibonnacci calculation.
;;When expressed as the obvious recursion, this is a very bad algorithm indeed.
;;Memoization turns it into a much better algorithm
;;I'll let the code speak for itself. You get a not inconsiderable speedup.
;;Note the nasty technique of mutating the value of the variable fib.
(defmacro time-it [expr]
`(let [start# (. System (nanoTime))
result# ~expr
finish# (. System (nanoTime))]
(/ (double (- finish# start#)) 1000000.0)))
(defn fib [n]
(if (< n 2) n
( + (fib (- n 1)) (fib (- n 2)))))
(doall (map #(time-it (fib %)) (range 1 30)))
(def fib (memoize fib))
(doall (map #(time-it (fib %)) (range 1 30))) | null | https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/memoize.clj | clojure | I noticed the other day that clojure has built in support for memoization,
which is a technique for remembering the return values of functions which
take a while to calculate
The classic example of when this can be useful is
the naive fibonnacci calculation.
When expressed as the obvious recursion, this is a very bad algorithm indeed.
Memoization turns it into a much better algorithm
I'll let the code speak for itself. You get a not inconsiderable speedup.
Note the nasty technique of mutating the value of the variable fib. |
(defmacro time-it [expr]
`(let [start# (. System (nanoTime))
result# ~expr
finish# (. System (nanoTime))]
(/ (double (- finish# start#)) 1000000.0)))
(defn fib [n]
(if (< n 2) n
( + (fib (- n 1)) (fib (- n 2)))))
(doall (map #(time-it (fib %)) (range 1 30)))
(def fib (memoize fib))
(doall (map #(time-it (fib %)) (range 1 30))) |
5fdb5f15954295ca43c1721760bd0df210980255224b35aaa9e087f76ea61a63 | janestreet/hardcaml | circuit.mli | (** Creation and manipulation of hardware circuits *)
open Base
(** circuit data structure *)
type t [@@deriving sexp_of]
(** Check if the ports specified in the interface match those defined in the circuit. *)
module Port_checks : sig
type t =
| Relaxed (** No checks *)
| Port_sets (** Input and output port sets agree *)
| Port_sets_and_widths
(** Input and output port sets agree, and their widths are the same. *)
end
module Config : sig
type t =
{ detect_combinational_loops : bool
(** Check circuit for combinational loops (cyclic paths that do not pass through a
register or memory). *)
; normalize_uids : bool
* Renumber the [ Uid]s of all signals in the circuit starting at one .
Uid normalization ensures that circuits will print the same ( as sexps or rtl )
regardless of the environment in which they are constructed ( in particular with
regard to the global uid generator ) .
Uid normalization ensures that circuits will print the same (as sexps or rtl)
regardless of the environment in which they are constructed (in particular with
regard to the global uid generator). *)
; assertions : Assertion_manager.t option
; port_checks : Port_checks.t
(** Perform validation checks on inputs and outputs ([With_interface] only) *)
; add_phantom_inputs : bool
(** Add inputs defined in an [Interface] but not used within the [Circuit]
([With_interface] only). *)
; modify_outputs : Signal.t list -> Signal.t list
(** Map over circuit outputs just before constructing the circuit. *)
}
(** Perform combination loop checking, normalize uids, [Relaxed] port checks, and add
phantom inputs. *)
val default : t
end
(** create circuit data structure *)
val create_exn : ?config:Config.t -> name:string -> Signal.t list -> t
(** return circuit inputs *)
val inputs : t -> Signal.t list
(** return circuit outputs *)
val outputs : t -> Signal.t list
val signal_graph : t -> Signal_graph.t
(** return circuit name *)
val name : t -> string
(** Return identical circuit except for the name. *)
val with_name : t -> name:string -> t
(** is the signal an input to the circuit *)
val is_input : t -> Signal.t -> bool
(** is the signal an output of the circuit *)
val is_output : t -> Signal.t -> bool
val find_signal_exn : t -> Signal.Uid.t -> Signal.t
* For internal use . Add phantom input ports to the circuit when writing RTL . This
can be necessary to ensure [ Interface ] based input specifications match those
discovered when traversing the hardware design from its outputs . It is especially
important when working with hierarchical designs .
can be necessary to ensure [Interface] based input specifications match those
discovered when traversing the hardware design from its outputs. It is especially
important when working with hierarchical designs. *)
val set_phantom_inputs : t -> (string * int) list -> t
val phantom_inputs : t -> (string * int) list
* Map of [ uid]s to [ Signal.t]s .
module Signal_map : sig
type t = Signal.t Signal.Uid_map.t [@@deriving sexp_of]
end
val assertions : t -> Signal.t Map.M(String).t
* Get map of [ uid]s to [ Signal.t]s .
val signal_map : t -> Signal_map.t
* Compute and return a [ Fan_out_map.t ] . The computation is lazy and only performed the
first time [ fan_out_map ] is called .
first time [fan_out_map] is called. *)
val fan_out_map : t -> Signal.Uid_set.t Signal.Uid_map.t
* Compute and return a [ Fan_in_map.t ] . The computation is lazy and only performed the
first time [ fan_in_map ] is called .
first time [fan_in_map] is called. *)
val fan_in_map : t -> Signal.Uid_set.t Signal.Uid_map.t
* compare 2 circuits to see if they are the same
val structural_compare : ?check_names:bool -> t -> t -> bool
(** returns the list of instantiations in this circuit *)
val instantiations : t -> Signal.instantiation list
val create_with_interface
: (module Interface.S_Of_signal with type Of_signal.t = 'i)
-> (module Interface.S_Of_signal with type Of_signal.t = 'o)
-> ?config:Config.t
-> name:string
-> ('i -> 'o)
-> t
module With_interface (I : Interface.S) (O : Interface.S) : sig
type create = Signal.t Interface.Create_fn(I)(O).t
(** Create a circuit with [inputs] and [outputs] automatically defined and labelled
according to the input ([I]) and output ([O]) interfaces. *)
val create_exn : ?config:Config.t -> name:string -> create -> t
end
| null | https://raw.githubusercontent.com/janestreet/hardcaml/1cdb35da263479bb4149c0f5550462163b7439d1/src/circuit.mli | ocaml | * Creation and manipulation of hardware circuits
* circuit data structure
* Check if the ports specified in the interface match those defined in the circuit.
* No checks
* Input and output port sets agree
* Input and output port sets agree, and their widths are the same.
* Check circuit for combinational loops (cyclic paths that do not pass through a
register or memory).
* Perform validation checks on inputs and outputs ([With_interface] only)
* Add inputs defined in an [Interface] but not used within the [Circuit]
([With_interface] only).
* Map over circuit outputs just before constructing the circuit.
* Perform combination loop checking, normalize uids, [Relaxed] port checks, and add
phantom inputs.
* create circuit data structure
* return circuit inputs
* return circuit outputs
* return circuit name
* Return identical circuit except for the name.
* is the signal an input to the circuit
* is the signal an output of the circuit
* returns the list of instantiations in this circuit
* Create a circuit with [inputs] and [outputs] automatically defined and labelled
according to the input ([I]) and output ([O]) interfaces. |
open Base
type t [@@deriving sexp_of]
module Port_checks : sig
type t =
| Port_sets_and_widths
end
module Config : sig
type t =
{ detect_combinational_loops : bool
; normalize_uids : bool
* Renumber the [ Uid]s of all signals in the circuit starting at one .
Uid normalization ensures that circuits will print the same ( as sexps or rtl )
regardless of the environment in which they are constructed ( in particular with
regard to the global uid generator ) .
Uid normalization ensures that circuits will print the same (as sexps or rtl)
regardless of the environment in which they are constructed (in particular with
regard to the global uid generator). *)
; assertions : Assertion_manager.t option
; port_checks : Port_checks.t
; add_phantom_inputs : bool
; modify_outputs : Signal.t list -> Signal.t list
}
val default : t
end
val create_exn : ?config:Config.t -> name:string -> Signal.t list -> t
val inputs : t -> Signal.t list
val outputs : t -> Signal.t list
val signal_graph : t -> Signal_graph.t
val name : t -> string
val with_name : t -> name:string -> t
val is_input : t -> Signal.t -> bool
val is_output : t -> Signal.t -> bool
val find_signal_exn : t -> Signal.Uid.t -> Signal.t
* For internal use . Add phantom input ports to the circuit when writing RTL . This
can be necessary to ensure [ Interface ] based input specifications match those
discovered when traversing the hardware design from its outputs . It is especially
important when working with hierarchical designs .
can be necessary to ensure [Interface] based input specifications match those
discovered when traversing the hardware design from its outputs. It is especially
important when working with hierarchical designs. *)
val set_phantom_inputs : t -> (string * int) list -> t
val phantom_inputs : t -> (string * int) list
* Map of [ uid]s to [ Signal.t]s .
module Signal_map : sig
type t = Signal.t Signal.Uid_map.t [@@deriving sexp_of]
end
val assertions : t -> Signal.t Map.M(String).t
* Get map of [ uid]s to [ Signal.t]s .
val signal_map : t -> Signal_map.t
* Compute and return a [ Fan_out_map.t ] . The computation is lazy and only performed the
first time [ fan_out_map ] is called .
first time [fan_out_map] is called. *)
val fan_out_map : t -> Signal.Uid_set.t Signal.Uid_map.t
* Compute and return a [ Fan_in_map.t ] . The computation is lazy and only performed the
first time [ fan_in_map ] is called .
first time [fan_in_map] is called. *)
val fan_in_map : t -> Signal.Uid_set.t Signal.Uid_map.t
* compare 2 circuits to see if they are the same
val structural_compare : ?check_names:bool -> t -> t -> bool
val instantiations : t -> Signal.instantiation list
val create_with_interface
: (module Interface.S_Of_signal with type Of_signal.t = 'i)
-> (module Interface.S_Of_signal with type Of_signal.t = 'o)
-> ?config:Config.t
-> name:string
-> ('i -> 'o)
-> t
module With_interface (I : Interface.S) (O : Interface.S) : sig
type create = Signal.t Interface.Create_fn(I)(O).t
val create_exn : ?config:Config.t -> name:string -> create -> t
end
|
a7275db760f77d9684def0a6ba740ddf75657dc7ddaebca69f5165681bef046f | zyrolasting/racket-koans | vectors.rkt | #lang racket/base
(require rackunit)
; Vectors resemble lists, but work differently. You can express them
; using the #(value value ...) notation, or by calling `vector`.
(define letters/literal #("a" "b" "c"))
(define letters/runtime (vector "a" "b" "c"))
(check-equal? letters/literal letters/runtime)
(check-equal? '? (vector? letters/literal))
(check-equal? '? (vector? letters/runtime))
; The way you make a vector affects whether you can mutate (change)
; the vector later.
(check-equal? '? (immutable? letters/literal))
(check-equal? '? (immutable? letters/runtime))
; Vectors have constant time access and update, meaning the size of
; the vector does not slow down how quickly you can access or change
; an individual element. Why do you think these operations are fast?
(check-equal? "?" (vector-ref letters/literal 1))
(vector-set! letters/runtime 2 (string-upcase (vector-ref letters/literal 0)))
(check-equal? "?" (vector-ref letters/runtime 2))
; Vector literals may specify their own length.
; What happens if you write #3(a b c d)?
(check-equal? "?" #3())
(check-equal? "?" #3(a))
(check-equal? "?" #3(a b))
(check-equal? "?" #3(a b c))
| null | https://raw.githubusercontent.com/zyrolasting/racket-koans/4a1057728b848493be8874a364b657b2398d0f7f/koans/vectors.rkt | racket | Vectors resemble lists, but work differently. You can express them
using the #(value value ...) notation, or by calling `vector`.
The way you make a vector affects whether you can mutate (change)
the vector later.
Vectors have constant time access and update, meaning the size of
the vector does not slow down how quickly you can access or change
an individual element. Why do you think these operations are fast?
Vector literals may specify their own length.
What happens if you write #3(a b c d)? | #lang racket/base
(require rackunit)
(define letters/literal #("a" "b" "c"))
(define letters/runtime (vector "a" "b" "c"))
(check-equal? letters/literal letters/runtime)
(check-equal? '? (vector? letters/literal))
(check-equal? '? (vector? letters/runtime))
(check-equal? '? (immutable? letters/literal))
(check-equal? '? (immutable? letters/runtime))
(check-equal? "?" (vector-ref letters/literal 1))
(vector-set! letters/runtime 2 (string-upcase (vector-ref letters/literal 0)))
(check-equal? "?" (vector-ref letters/runtime 2))
(check-equal? "?" #3())
(check-equal? "?" #3(a))
(check-equal? "?" #3(a b))
(check-equal? "?" #3(a b c))
|
b9a2d45e615f9477e209ddb916b96d6bcae471ca8a58c3962398869c4d957ca1 | javazquez/arnoldclj_interpreter | method_test.clj | (ns arnoldclj_s.method-test
(:use midje.sweet)
(:use arnoldclj_s.lexr))
(fact "evalute method other than main"
(lights-camera-action "LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY\n"
"IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED\n")=> [:Program
[:method-declaration [:variable "mymethod"] ]
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]])
;getOutput(code) should equal("Hello\n")
(fact "evalute method other than main2"
(lights-camera-action "LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY\n"
"IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED") => [:Program
[:method-declaration [:variable "mymethod"] ]
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]])
;getOutput(code) should equal("Hello\n")
(fact "evalute method other than main3"
(lights-camera-action "IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY\n")=> [:Program
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]
[:method-declaration [:variable "mymethod"] ]])
;getOutput(code) should equal("Hello\n")
FIXME check that method name is in symbol table
(fact"evalute method other than main4"
(lights-camera-action "IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]
[:method-declaration [:variable "mymethod"] ]])
;getOutput(code) should equal("Hello\n")
(fact "evalute a plain method call"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printHello\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main
[:statement [:call-method [:method-name "printHello"]]]]
[:method-declaration
[:variable "printHello"]
[:statement [:printing [:quotedstring "Hello"]]] ]])
;getOutput(code) should equal("Hello\n")
(fact "evalute a method call that takes an argument"
(lights-camera-action "IT'S SHOWTIME\n"
"HEY CHRISTMAS TREE argument\n"
"YOU SET US UP 123\n"
"DO IT NOW printInteger argument\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printInteger\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"TALK TO THE HAND value\n"
"HASTA LA VISTA, BABY") =>
[:Program
[:begin-main
[:statement [:decvar [:variable "argument"] [:init-val [:number "123"]]]]
[:statement
[:call-method
[:method-name "printInteger"]
[:variable "argument"]]]]
[:method-declaration [:variable "printInteger"]
[:method-arg [:variable "value"]]
[:statement [:printing [:variable "value"]]] ]])
;getOutput(code) should equal("123\n")
(fact "evalute multiple method calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printHello\n"
"DO IT NOW printCheers\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n"
"HASTA LA VISTA, BABY\n"
"LISTEN TO ME VERY CAREFULLY printCheers\n"
"TALK TO THE HAND \"Cheers\"\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main
[:statement [:call-method [:method-name "printHello"]]]
[:statement [:call-method [:method-name "printCheers"]]]]
[:method-declaration [:variable "printHello"]
[:statement [:printing [:quotedstring "Hello"]]] ]
[:method-declaration [:variable "printCheers"]
[:statement [:printing [:quotedstring "Cheers"]]] ]])
;getOutput(code) should equal("Hello\nCheers\n")
(fact "evalute method calls inside method calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printHello\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n"
"DO IT NOW printCheers\n"
"DO IT NOW printHejsan\n"
"HASTA LA VISTA, BABY\n"
"LISTEN TO ME VERY CAREFULLY printCheers\n"
"TALK TO THE HAND \"Cheers\"\n"
"HASTA LA VISTA, BABY\n"
"LISTEN TO ME VERY CAREFULLY printHejsan\n"
"TALK TO THE HAND \"Hejsan\"\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main [:statement [:call-method [:method-name "printHello"]]]]
[:method-declaration [:variable "printHello"]
[:statement [:printing [:quotedstring "Hello"]]]
[:statement [:call-method [:method-name "printCheers"]]]
[:statement [:call-method [:method-name "printHejsan"]]] ]
[:method-declaration [:variable "printCheers"]
[:statement [:printing [:quotedstring "Cheers"]]] ]
[:method-declaration [:variable "printHejsan"]
[:statement [:printing [:quotedstring "Hejsan"]]] ]])
;getOutput(code) should equal("Hello\nCheers\nHejsan\n")
(fact"evalute a return statement in void calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "method"]]]]
[:method-declaration [:variable "method"]
[:statement [:return]] ]])
;getOutput(code) should equal("")
(fact "evalute multiple return statemenents in void calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printboolean @NO PROBLEMO\n"
"DO IT NOW printboolean @I LIED\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printboolean\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"true\"\n"
"I'LL BE BACK\n"
"BULLSHIT\n"
"TALK TO THE HAND \"false\"\n"
"I'LL BE BACK\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "printboolean"] [:true 1]]]
[:statement [:call-method [:method-name "printboolean"] [:false 0]]]]
[:method-declaration [:variable "printboolean"]
[:method-arg [:variable "value"]]
[:statement [:if [:variable "value"]
[:statement [:printing [:quotedstring "true"]]]
[:statement [:return]]
[:else-if
[:statement [:printing [:quotedstring "false"]]]
[:statement [:return]]]
]] ]])
;getOutput(code) should equal("true\nfalse\n")
(fact "evalute multiple return statemenents in void calls permutation2"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printboolean @NO PROBLEMO\n"
"DO IT NOW printboolean @I LIED\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printboolean\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"true\"\n"
"BULLSHIT\n"
"TALK TO THE HAND \"false\"\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "printboolean"] [:true 1]]]
[:statement [:call-method [:method-name "printboolean"] [:false 0]]]]
[:method-declaration [:variable "printboolean"]
[:method-arg [:variable "value"]]
[:statement [:if [:variable "value"]
[:statement [:printing [:quotedstring "true"]]]
[:else-if [:statement [:printing [:quotedstring "false"]]]] ]] ]])
;getOutput(code) should equal("true\nfalse\n")
(fact"evalute multiple return statemenents in void calls permutation3"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printboolean @NO PROBLEMO\n"
"DO IT NOW printboolean @I LIED\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printboolean\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"true\"\n"
"BULLSHIT\n"
"TALK TO THE HAND \"false\"\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"I'LL BE BACK\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "printboolean"] [:true 1]]]
[:statement [:call-method [:method-name "printboolean"] [:false 0]]]]
[:method-declaration [:variable "printboolean"]
[:method-arg [:variable "value"]]
[:statement [:if
[:variable "value"]
[:statement [:printing [:quotedstring "true"]]]
[:else-if
[:statement [:printing [:quotedstring "false"]]]]
]]
[:statement [:return]]
[:statement [:return]] ]])
;getOutput(code) should equal("true\nfalse\n")
(fact "evalute multiple return statemenents in void calls with unreachable code"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"TALK TO THE HAND \"reached codeblock\"\n"
"I'LL BE BACK\n"
"TALK TO THE HAND \"unreached codeblock\"\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "method"]]]]
[:method-declaration [:variable "method"]
[:statement [:printing [:quotedstring "reached codeblock"]]]
[:statement [:return]]
[:statement [:printing [:quotedstring "unreached codeblock"]]] ]]
)
;getOutput(code) should equal("reached codeblock\n")
(fact "evalute void method calls returning from branched statements"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW reverse @NO PROBLEMO\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY reverse\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"evaluated\"\n"
"I'LL BE BACK\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"TALK TO THE HAND \"not evaluated\"\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement
[:call-method
[:method-name "reverse"]
[:true 1]]]]
[:method-declaration
[:variable "reverse"]
[:method-arg
[:variable "value"]]
[:statement
[:if
[:variable "value"]
[:statement [:printing [:quotedstring "evaluated"]]]
[:statement [:return]]]]
[:statement [:printing [:quotedstring "not evaluated"]]]
[:statement [:return]] ]])
;getOutput(code) should equal("evaluated\n")
(fact "evalute non void method calls returning from branched statements"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW reverse @NO PROBLEMO\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY reverse\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"GIVE THESE PEOPLE AIR\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"evaluated\"\n"
"I'LL BE BACK 0\n"
"TALK TO THE HAND \"evaluated\"\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"TALK TO THE HAND \"not evaluated\"\n"
"I'LL BE BACK 0\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "reverse"] [:true 1]]]]
[:method-declaration
[:variable "reverse"]
[:method-arg [:variable "value"]]
[:non-void-method
[:method-statement
[:if
[:variable "value"]
[:statement [:printing [:quotedstring "evaluated"]]]
[:statement [:return [:number "0"]]]
[:statement [:printing [:quotedstring "evaluated"]]] ]]
[:method-statement
[:printing [:quotedstring "not evaluated"]]]
[:method-return [:number "0"]] ]
]])
;getOutput(code) should equal("evaluated\n")
(fact "evalute assignments to variables from method calls "
(lights-camera-action "IT'S SHOWTIME\n"
"HEY CHRISTMAS TREE result\n"
"YOU SET US UP 0\n"
"GET YOUR ASS TO MARS result\n"
"DO IT NOW square 7\n"
"TALK TO THE HAND result\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY square\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"GIVE THESE PEOPLE AIR\n"
"GET TO THE CHOPPER value\n"
"HERE IS MY INVITATION value\n"
"YOU'RE FIRED value\n"
"ENOUGH TALK\n"
"I'LL BE BACK value\n"
"HASTA LA VISTA, BABY\n") =>
[:Program [:begin-main [:statement [:decvar [:variable "result"] [:init-val [:number "0"]]]] [:statement [:assign-var-from-method-call [:variable "result"] [:call-method [:method-name "square"] [:number "7"]]]] [:statement [:printing [:variable "result"]]]] [:method-declaration [:variable "square"] [:method-arg [:variable "value"]] [:non-void-method [:method-statement [:assignment [:variable "value"] [:set-val [:variable "value"] [:arithmetic-op [:mult [:variable "value"]]]]]] [:method-return [:variable "value"]]]]]
)
;getOutput(code) should equal("49\n")
(fact "detect unclosed main method"
(lights-camera-action "IT'S SHOWTIME\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n") => (throws Exception "WHAT THE FUCK DID I DO WRONG? \nParse error at line 2, column 1:\nLISTEN TO ME VERY CAREFULLY printHello\n^\nExpected one of:\n\"I'LL BE BACK\"\n\"STICK AROUND\"\n\"BECAUSE I'M GOING TO SAY PLEASE\"\n\"DO IT NOW\"\n\"GET YOUR ASS TO MARS\"\n\"HEY CHRISTMAS TREE\"\n\"TALK TO THE HAND\"\n\"GET TO THE CHOPPER\"\n"))
;intercept[ParsingException] {
;getOutput(code)
(fact "detect unclosed methods"
(lights-camera-action "IT'S SHOWTIME\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n") => (throws Exception "WHAT THE FUCK DID I DO WRONG? \nParse error at line 2, column 1:\nYOU HAVE BEEN TERMINATED\n^\nExpected one of:\n\"I'LL BE BACK\"\n\"STICK AROUND\"\n\"BECAUSE I'M GOING TO SAY PLEASE\"\n\"DO IT NOW\"\n\"GET YOUR ASS TO MARS\"\n\"HEY CHRISTMAS TREE\"\n\"TALK TO THE HAND\"\n\"GET TO THE CHOPPER\"\n"))
;intercept[ParsingException] {
;getOutput(code)
fixme , this is a runtime error
(fact "detect calls to methods that are not declared"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW noSuchMethod\n"
"YOU HAVE BEEN TERMINATED\n"))
;intercept[ParsingException] {
;getOutput(code)
! !
(fact "detect if void method tries to return a parameter"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"I'LL BE BACK 0\n"
"HASTA LA VISTA, BABY\n"))
;intercept[ParsingException] ;
;getOutput(code)
fixme
(fact "detect if a non-void method tries to return a without a parameter"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method 0\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"GIVE THESE PEOPLE AIR\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") => (throws Exception
#_"Exception WHAT THE FUCK DID I DO WRONG? \nParse error at line 8, column 15:\n
HASTA LA VISTA, BABY\n ^\nExpected one of:\n\"HASTA LA VISTA, BABY\"\n\"I'LL BE BACK\"\n\"STICK AROUND\"\n\"BECAUSE I'M GOING TO SAY PLEASE\"\n\"DO IT NOW\"\n\"GET YOUR ASS TO MARS\"\n\"HEY CHRISTMAS TREE\"\n\"TALK TO THE HAND\"\n\"GET TO THE CHOPPER\"\n#\"\\\".*\\\"\"\n\"@NO PROBLEMO\"\n\"@I LIED\"\n#\"[a-zA-Z][a-zA-Z0-9]*\"\n#\"-?[0-9]+\"" ))
; ;intercept[ParsingException]
;getOutput(code)
| null | https://raw.githubusercontent.com/javazquez/arnoldclj_interpreter/d6860d7063a121103293b10dca65b113ad843d26/test/arnoldclj_s/method_test.clj | clojure | getOutput(code) should equal("Hello\n")
getOutput(code) should equal("Hello\n")
getOutput(code) should equal("Hello\n")
getOutput(code) should equal("Hello\n")
getOutput(code) should equal("Hello\n")
getOutput(code) should equal("123\n")
getOutput(code) should equal("Hello\nCheers\n")
getOutput(code) should equal("Hello\nCheers\nHejsan\n")
getOutput(code) should equal("")
getOutput(code) should equal("true\nfalse\n")
getOutput(code) should equal("true\nfalse\n")
getOutput(code) should equal("true\nfalse\n")
getOutput(code) should equal("reached codeblock\n")
getOutput(code) should equal("evaluated\n")
getOutput(code) should equal("evaluated\n")
getOutput(code) should equal("49\n")
intercept[ParsingException] {
getOutput(code)
intercept[ParsingException] {
getOutput(code)
intercept[ParsingException] {
getOutput(code)
intercept[ParsingException] ;
getOutput(code)
;intercept[ParsingException]
getOutput(code) | (ns arnoldclj_s.method-test
(:use midje.sweet)
(:use arnoldclj_s.lexr))
(fact "evalute method other than main"
(lights-camera-action "LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY\n"
"IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED\n")=> [:Program
[:method-declaration [:variable "mymethod"] ]
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]])
(fact "evalute method other than main2"
(lights-camera-action "LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY\n"
"IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED") => [:Program
[:method-declaration [:variable "mymethod"] ]
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]])
(fact "evalute method other than main3"
(lights-camera-action "IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY\n")=> [:Program
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]
[:method-declaration [:variable "mymethod"] ]])
FIXME check that method name is in symbol table
(fact"evalute method other than main4"
(lights-camera-action "IT'S SHOWTIME\n"
"TALK TO THE HAND \"Hello\"\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY mymethod\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main
[:statement [:printing [:quotedstring "Hello"]]]]
[:method-declaration [:variable "mymethod"] ]])
(fact "evalute a plain method call"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printHello\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main
[:statement [:call-method [:method-name "printHello"]]]]
[:method-declaration
[:variable "printHello"]
[:statement [:printing [:quotedstring "Hello"]]] ]])
(fact "evalute a method call that takes an argument"
(lights-camera-action "IT'S SHOWTIME\n"
"HEY CHRISTMAS TREE argument\n"
"YOU SET US UP 123\n"
"DO IT NOW printInteger argument\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printInteger\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"TALK TO THE HAND value\n"
"HASTA LA VISTA, BABY") =>
[:Program
[:begin-main
[:statement [:decvar [:variable "argument"] [:init-val [:number "123"]]]]
[:statement
[:call-method
[:method-name "printInteger"]
[:variable "argument"]]]]
[:method-declaration [:variable "printInteger"]
[:method-arg [:variable "value"]]
[:statement [:printing [:variable "value"]]] ]])
(fact "evalute multiple method calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printHello\n"
"DO IT NOW printCheers\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n"
"HASTA LA VISTA, BABY\n"
"LISTEN TO ME VERY CAREFULLY printCheers\n"
"TALK TO THE HAND \"Cheers\"\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main
[:statement [:call-method [:method-name "printHello"]]]
[:statement [:call-method [:method-name "printCheers"]]]]
[:method-declaration [:variable "printHello"]
[:statement [:printing [:quotedstring "Hello"]]] ]
[:method-declaration [:variable "printCheers"]
[:statement [:printing [:quotedstring "Cheers"]]] ]])
(fact "evalute method calls inside method calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printHello\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n"
"DO IT NOW printCheers\n"
"DO IT NOW printHejsan\n"
"HASTA LA VISTA, BABY\n"
"LISTEN TO ME VERY CAREFULLY printCheers\n"
"TALK TO THE HAND \"Cheers\"\n"
"HASTA LA VISTA, BABY\n"
"LISTEN TO ME VERY CAREFULLY printHejsan\n"
"TALK TO THE HAND \"Hejsan\"\n"
"HASTA LA VISTA, BABY") => [:Program
[:begin-main [:statement [:call-method [:method-name "printHello"]]]]
[:method-declaration [:variable "printHello"]
[:statement [:printing [:quotedstring "Hello"]]]
[:statement [:call-method [:method-name "printCheers"]]]
[:statement [:call-method [:method-name "printHejsan"]]] ]
[:method-declaration [:variable "printCheers"]
[:statement [:printing [:quotedstring "Cheers"]]] ]
[:method-declaration [:variable "printHejsan"]
[:statement [:printing [:quotedstring "Hejsan"]]] ]])
(fact"evalute a return statement in void calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "method"]]]]
[:method-declaration [:variable "method"]
[:statement [:return]] ]])
(fact "evalute multiple return statemenents in void calls"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printboolean @NO PROBLEMO\n"
"DO IT NOW printboolean @I LIED\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printboolean\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"true\"\n"
"I'LL BE BACK\n"
"BULLSHIT\n"
"TALK TO THE HAND \"false\"\n"
"I'LL BE BACK\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "printboolean"] [:true 1]]]
[:statement [:call-method [:method-name "printboolean"] [:false 0]]]]
[:method-declaration [:variable "printboolean"]
[:method-arg [:variable "value"]]
[:statement [:if [:variable "value"]
[:statement [:printing [:quotedstring "true"]]]
[:statement [:return]]
[:else-if
[:statement [:printing [:quotedstring "false"]]]
[:statement [:return]]]
]] ]])
(fact "evalute multiple return statemenents in void calls permutation2"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printboolean @NO PROBLEMO\n"
"DO IT NOW printboolean @I LIED\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printboolean\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"true\"\n"
"BULLSHIT\n"
"TALK TO THE HAND \"false\"\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "printboolean"] [:true 1]]]
[:statement [:call-method [:method-name "printboolean"] [:false 0]]]]
[:method-declaration [:variable "printboolean"]
[:method-arg [:variable "value"]]
[:statement [:if [:variable "value"]
[:statement [:printing [:quotedstring "true"]]]
[:else-if [:statement [:printing [:quotedstring "false"]]]] ]] ]])
(fact"evalute multiple return statemenents in void calls permutation3"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW printboolean @NO PROBLEMO\n"
"DO IT NOW printboolean @I LIED\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printboolean\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"true\"\n"
"BULLSHIT\n"
"TALK TO THE HAND \"false\"\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"I'LL BE BACK\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "printboolean"] [:true 1]]]
[:statement [:call-method [:method-name "printboolean"] [:false 0]]]]
[:method-declaration [:variable "printboolean"]
[:method-arg [:variable "value"]]
[:statement [:if
[:variable "value"]
[:statement [:printing [:quotedstring "true"]]]
[:else-if
[:statement [:printing [:quotedstring "false"]]]]
]]
[:statement [:return]]
[:statement [:return]] ]])
(fact "evalute multiple return statemenents in void calls with unreachable code"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"TALK TO THE HAND \"reached codeblock\"\n"
"I'LL BE BACK\n"
"TALK TO THE HAND \"unreached codeblock\"\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "method"]]]]
[:method-declaration [:variable "method"]
[:statement [:printing [:quotedstring "reached codeblock"]]]
[:statement [:return]]
[:statement [:printing [:quotedstring "unreached codeblock"]]] ]]
)
(fact "evalute void method calls returning from branched statements"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW reverse @NO PROBLEMO\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY reverse\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"evaluated\"\n"
"I'LL BE BACK\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"TALK TO THE HAND \"not evaluated\"\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement
[:call-method
[:method-name "reverse"]
[:true 1]]]]
[:method-declaration
[:variable "reverse"]
[:method-arg
[:variable "value"]]
[:statement
[:if
[:variable "value"]
[:statement [:printing [:quotedstring "evaluated"]]]
[:statement [:return]]]]
[:statement [:printing [:quotedstring "not evaluated"]]]
[:statement [:return]] ]])
(fact "evalute non void method calls returning from branched statements"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW reverse @NO PROBLEMO\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY reverse\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"GIVE THESE PEOPLE AIR\n"
"BECAUSE I'M GOING TO SAY PLEASE value\n"
"TALK TO THE HAND \"evaluated\"\n"
"I'LL BE BACK 0\n"
"TALK TO THE HAND \"evaluated\"\n"
"YOU HAVE NO RESPECT FOR LOGIC\n"
"TALK TO THE HAND \"not evaluated\"\n"
"I'LL BE BACK 0\n"
"HASTA LA VISTA, BABY\n") =>
[:Program
[:begin-main
[:statement [:call-method [:method-name "reverse"] [:true 1]]]]
[:method-declaration
[:variable "reverse"]
[:method-arg [:variable "value"]]
[:non-void-method
[:method-statement
[:if
[:variable "value"]
[:statement [:printing [:quotedstring "evaluated"]]]
[:statement [:return [:number "0"]]]
[:statement [:printing [:quotedstring "evaluated"]]] ]]
[:method-statement
[:printing [:quotedstring "not evaluated"]]]
[:method-return [:number "0"]] ]
]])
(fact "evalute assignments to variables from method calls "
(lights-camera-action "IT'S SHOWTIME\n"
"HEY CHRISTMAS TREE result\n"
"YOU SET US UP 0\n"
"GET YOUR ASS TO MARS result\n"
"DO IT NOW square 7\n"
"TALK TO THE HAND result\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY square\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"GIVE THESE PEOPLE AIR\n"
"GET TO THE CHOPPER value\n"
"HERE IS MY INVITATION value\n"
"YOU'RE FIRED value\n"
"ENOUGH TALK\n"
"I'LL BE BACK value\n"
"HASTA LA VISTA, BABY\n") =>
[:Program [:begin-main [:statement [:decvar [:variable "result"] [:init-val [:number "0"]]]] [:statement [:assign-var-from-method-call [:variable "result"] [:call-method [:method-name "square"] [:number "7"]]]] [:statement [:printing [:variable "result"]]]] [:method-declaration [:variable "square"] [:method-arg [:variable "value"]] [:non-void-method [:method-statement [:assignment [:variable "value"] [:set-val [:variable "value"] [:arithmetic-op [:mult [:variable "value"]]]]]] [:method-return [:variable "value"]]]]]
)
(fact "detect unclosed main method"
(lights-camera-action "IT'S SHOWTIME\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n") => (throws Exception "WHAT THE FUCK DID I DO WRONG? \nParse error at line 2, column 1:\nLISTEN TO ME VERY CAREFULLY printHello\n^\nExpected one of:\n\"I'LL BE BACK\"\n\"STICK AROUND\"\n\"BECAUSE I'M GOING TO SAY PLEASE\"\n\"DO IT NOW\"\n\"GET YOUR ASS TO MARS\"\n\"HEY CHRISTMAS TREE\"\n\"TALK TO THE HAND\"\n\"GET TO THE CHOPPER\"\n"))
(fact "detect unclosed methods"
(lights-camera-action "IT'S SHOWTIME\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY printHello\n"
"TALK TO THE HAND \"Hello\"\n") => (throws Exception "WHAT THE FUCK DID I DO WRONG? \nParse error at line 2, column 1:\nYOU HAVE BEEN TERMINATED\n^\nExpected one of:\n\"I'LL BE BACK\"\n\"STICK AROUND\"\n\"BECAUSE I'M GOING TO SAY PLEASE\"\n\"DO IT NOW\"\n\"GET YOUR ASS TO MARS\"\n\"HEY CHRISTMAS TREE\"\n\"TALK TO THE HAND\"\n\"GET TO THE CHOPPER\"\n"))
fixme , this is a runtime error
(fact "detect calls to methods that are not declared"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW noSuchMethod\n"
"YOU HAVE BEEN TERMINATED\n"))
! !
(fact "detect if void method tries to return a parameter"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"I'LL BE BACK 0\n"
"HASTA LA VISTA, BABY\n"))
fixme
(fact "detect if a non-void method tries to return a without a parameter"
(lights-camera-action "IT'S SHOWTIME\n"
"DO IT NOW method 0\n"
"YOU HAVE BEEN TERMINATED\n"
"LISTEN TO ME VERY CAREFULLY method\n"
"I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE value\n"
"GIVE THESE PEOPLE AIR\n"
"I'LL BE BACK\n"
"HASTA LA VISTA, BABY\n") => (throws Exception
#_"Exception WHAT THE FUCK DID I DO WRONG? \nParse error at line 8, column 15:\n
HASTA LA VISTA, BABY\n ^\nExpected one of:\n\"HASTA LA VISTA, BABY\"\n\"I'LL BE BACK\"\n\"STICK AROUND\"\n\"BECAUSE I'M GOING TO SAY PLEASE\"\n\"DO IT NOW\"\n\"GET YOUR ASS TO MARS\"\n\"HEY CHRISTMAS TREE\"\n\"TALK TO THE HAND\"\n\"GET TO THE CHOPPER\"\n#\"\\\".*\\\"\"\n\"@NO PROBLEMO\"\n\"@I LIED\"\n#\"[a-zA-Z][a-zA-Z0-9]*\"\n#\"-?[0-9]+\"" ))
|
976a6656cd73c0d25e71a0f64e615380d88302badc0bbedaaf657bb5daeddb6c | reanimate/reanimate | TernaryPlot.hs | |
Module : Reanimate . Builtin . TernaryPlot
Copyright : Written by
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
Implementation of ternary plots : < >
Module : Reanimate.Builtin.TernaryPlot
Copyright : Written by David Himmelstrup
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
Implementation of ternary plots: <>
-}
module Reanimate.Builtin.TernaryPlot
( ACoord
, BCoord
, CCoord
, ternaryPlot
-- , atCenter
-- , radius
, toCartesianCoords
, toOffsetCartesianCoords
, fromCartesianCoords
) where
import Codec.Picture (PixelRGBA8 (..), generateImage)
import Graphics.SvgTree (Tree)
import Reanimate.Raster (embedImage)
import Reanimate.Svg (flipYAxis, scaleToWidth, translate)
-- a+b+c=1
-- | Left-most coordinate.
type ACoord = Double
-- | Top-most coordinate.
type BCoord = Double
-- | Right-most coordinate.
type CCoord = Double
| Creates a centered ternary plot with a width of 5 .
--
-- Example:
--
-- @
' ternaryPlot ' 100 $ \\aCoord Codec . Picture . Types.promotePixel ' $
-- let red = round $ aCoord*255
-- green = round $ bCoord*255
-- blue = round $ cCoord*255
-- in PixelRGB8 red green blue
-- @
--
-- <<docs/gifs/doc_ternaryPlot.gif>>
^ Pixels in the X - axis . More pixels = > higher quality .
-> (ACoord -> BCoord -> CCoord -> PixelRGBA8)
-- ^ a+b+c=1. A=1 is the left-most position,
-- B=1 is the top-most position, and
-- C=1 is the right-most position.
-> Tree
ternaryPlot density fn =
scaleToWidth stdWidth $
translate (-cX) (-cY) $
scaleToWidth 1 $
flipYAxis $
translate (fromIntegral density/2) (-fromIntegral height/2) $
embedImage $ generateImage gen density height
where
stdWidth = 5
(cX, cY) = toCartesianCoords (1/3) (1/3)
height = round (fromIntegral density * (sqrt 3 / 2) :: Double)
gen x y =
let
x' = (fromIntegral x / fromIntegral density)
y' = (fromIntegral y / fromIntegral density)
aCoord = (x'*2-bCoord)/2
bCoord = y' / (sqrt 3 / 2)
cCoord = 1 - aCoord - bCoord
in if aCoord + bCoord > 1 || aCoord < 0 || bCoord < 0 || cCoord < 0
then PixelRGBA8 0 0 0 0
else fn aCoord bCoord cCoord
-- atCenter :: Double -> Tree -> Tree
atCenter stdWidth = translate ( -cX*stdWidth ) ( -cY*stdWidth )
-- where
( cX , cY ) = toCartesianCoords ( 1/3 ) ( 1/3 )
-- radius :: Double
radius = sqrt ( cX*cX + cY*cY )
-- where
( cX , cY ) = toCartesianCoords ( 1/3 ) ( 1/3 )
| Compute the XY coordinates from ternary coordinates .
Note that @CCoord@ is given because @a+b+c=1@.
toCartesianCoords :: ACoord -> BCoord -> (Double, Double)
toCartesianCoords a b = (x, y)
where
x = (a+2*b)/2
y = (sqrt 3 / 2) * a
| Compute the XY coordinates relative from the center of the
-- ternary plot.
Note that @CCoord@ is given because @a+b+c=1@.
toOffsetCartesianCoords :: ACoord -> BCoord -> (Double, Double)
toOffsetCartesianCoords a b =
(tx-zx, ty-zy)
where
(zx,zy) = toCartesianCoords (1/3) (1/3)
(tx,ty) = toCartesianCoords a b
| Compute ternary coordinates from XY coordinates .
fromCartesianCoords :: Double -> Double -> (ACoord, BCoord, CCoord)
fromCartesianCoords x y = (a,b,1-a-b)
where
a = (x*2-b)/2
b = y / (sqrt 3 / 2)
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/src/Reanimate/Builtin/TernaryPlot.hs | haskell | , atCenter
, radius
a+b+c=1
| Left-most coordinate.
| Top-most coordinate.
| Right-most coordinate.
Example:
@
let red = round $ aCoord*255
green = round $ bCoord*255
blue = round $ cCoord*255
in PixelRGB8 red green blue
@
<<docs/gifs/doc_ternaryPlot.gif>>
^ a+b+c=1. A=1 is the left-most position,
B=1 is the top-most position, and
C=1 is the right-most position.
atCenter :: Double -> Tree -> Tree
where
radius :: Double
where
ternary plot. | |
Module : Reanimate . Builtin . TernaryPlot
Copyright : Written by
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
Implementation of ternary plots : < >
Module : Reanimate.Builtin.TernaryPlot
Copyright : Written by David Himmelstrup
License : Unlicense
Maintainer :
Stability : experimental
Portability : POSIX
Implementation of ternary plots: <>
-}
module Reanimate.Builtin.TernaryPlot
( ACoord
, BCoord
, CCoord
, ternaryPlot
, toCartesianCoords
, toOffsetCartesianCoords
, fromCartesianCoords
) where
import Codec.Picture (PixelRGBA8 (..), generateImage)
import Graphics.SvgTree (Tree)
import Reanimate.Raster (embedImage)
import Reanimate.Svg (flipYAxis, scaleToWidth, translate)
type ACoord = Double
type BCoord = Double
type CCoord = Double
| Creates a centered ternary plot with a width of 5 .
' ternaryPlot ' 100 $ \\aCoord Codec . Picture . Types.promotePixel ' $
^ Pixels in the X - axis . More pixels = > higher quality .
-> (ACoord -> BCoord -> CCoord -> PixelRGBA8)
-> Tree
ternaryPlot density fn =
scaleToWidth stdWidth $
translate (-cX) (-cY) $
scaleToWidth 1 $
flipYAxis $
translate (fromIntegral density/2) (-fromIntegral height/2) $
embedImage $ generateImage gen density height
where
stdWidth = 5
(cX, cY) = toCartesianCoords (1/3) (1/3)
height = round (fromIntegral density * (sqrt 3 / 2) :: Double)
gen x y =
let
x' = (fromIntegral x / fromIntegral density)
y' = (fromIntegral y / fromIntegral density)
aCoord = (x'*2-bCoord)/2
bCoord = y' / (sqrt 3 / 2)
cCoord = 1 - aCoord - bCoord
in if aCoord + bCoord > 1 || aCoord < 0 || bCoord < 0 || cCoord < 0
then PixelRGBA8 0 0 0 0
else fn aCoord bCoord cCoord
atCenter stdWidth = translate ( -cX*stdWidth ) ( -cY*stdWidth )
( cX , cY ) = toCartesianCoords ( 1/3 ) ( 1/3 )
radius = sqrt ( cX*cX + cY*cY )
( cX , cY ) = toCartesianCoords ( 1/3 ) ( 1/3 )
| Compute the XY coordinates from ternary coordinates .
Note that @CCoord@ is given because @a+b+c=1@.
toCartesianCoords :: ACoord -> BCoord -> (Double, Double)
toCartesianCoords a b = (x, y)
where
x = (a+2*b)/2
y = (sqrt 3 / 2) * a
| Compute the XY coordinates relative from the center of the
Note that @CCoord@ is given because @a+b+c=1@.
toOffsetCartesianCoords :: ACoord -> BCoord -> (Double, Double)
toOffsetCartesianCoords a b =
(tx-zx, ty-zy)
where
(zx,zy) = toCartesianCoords (1/3) (1/3)
(tx,ty) = toCartesianCoords a b
| Compute ternary coordinates from XY coordinates .
fromCartesianCoords :: Double -> Double -> (ACoord, BCoord, CCoord)
fromCartesianCoords x y = (a,b,1-a-b)
where
a = (x*2-b)/2
b = y / (sqrt 3 / 2)
|
2b0e60468e11f300184b53e50782d6a557ac664bf31df3775b77ecef86e1d737 | i-am-tom/holmes | Ord.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE BlockArguments #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Test.Data.JoinSemilattice.Class.Ord where
import Data.Holmes (BooleanR (..), OrdR (..))
import Hedgehog
ordR_lteR
:: ( OrdR f
, OrdC f x
, Eq (f x)
, Eq (f Bool)
, Show (f x)
, Show (f Bool)
)
=> Gen (f x)
-> Property
ordR_lteR gen = property do
a <- forAll gen
b <- forAll gen
let ( _, _, c ) = lteR ( a, b, mempty )
annotateShow c
let ( a', _, _ ) = lteR ( mempty, b, c )
annotateShow a'
a' <> a === a
let ( _, b', _ ) = lteR ( a, mempty, c )
annotateShow b'
b' <> b === b
ordR_symmetry
:: ( OrdR f
, OrdC f x
, Eq (f x)
, Eq (f Bool)
, Show (f x)
)
=> Gen (f x)
-> Property
ordR_symmetry gen = property do
a <- forAll gen
b <- forAll gen
let ( _, _, x ) = lteR ( a, b, mempty )
( _, _, y ) = lteR ( b, a, mempty )
if x == trueR && y == trueR
then a === b
else success
| null | https://raw.githubusercontent.com/i-am-tom/holmes/ecbb6da0c7a73f839ea2c4d00cdb902fe7080981/test/Test/Data/JoinSemilattice/Class/Ord.hs | haskell | # LANGUAGE RankNTypes # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE BlockArguments #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Test.Data.JoinSemilattice.Class.Ord where
import Data.Holmes (BooleanR (..), OrdR (..))
import Hedgehog
ordR_lteR
:: ( OrdR f
, OrdC f x
, Eq (f x)
, Eq (f Bool)
, Show (f x)
, Show (f Bool)
)
=> Gen (f x)
-> Property
ordR_lteR gen = property do
a <- forAll gen
b <- forAll gen
let ( _, _, c ) = lteR ( a, b, mempty )
annotateShow c
let ( a', _, _ ) = lteR ( mempty, b, c )
annotateShow a'
a' <> a === a
let ( _, b', _ ) = lteR ( a, mempty, c )
annotateShow b'
b' <> b === b
ordR_symmetry
:: ( OrdR f
, OrdC f x
, Eq (f x)
, Eq (f Bool)
, Show (f x)
)
=> Gen (f x)
-> Property
ordR_symmetry gen = property do
a <- forAll gen
b <- forAll gen
let ( _, _, x ) = lteR ( a, b, mempty )
( _, _, y ) = lteR ( b, a, mempty )
if x == trueR && y == trueR
then a === b
else success
|
a0ad588f700b5bfbe77759c37c6672410c92a17c35eab99f61eec2c6aadc442d | agda/agda | Instances.hs | # OPTIONS_GHC -fno - warn - orphans #
-- Only instances exported
module Agda.TypeChecking.Serialise.Instances () where
import Agda.Syntax.Position
import Agda.Syntax.TopLevelModuleName
import Agda.TypeChecking.Monad.Base
import Agda.TypeChecking.Serialise.Base
import Agda.TypeChecking.Serialise.Instances.Common (SerialisedRange(..))
import Agda.TypeChecking.Serialise.Instances.Highlighting ()
import Agda.TypeChecking.Serialise.Instances.Errors ()
import Agda.Utils.Hash
type RangedImportedModules =
[(SerialisedRange, TopLevelModuleName, Hash)]
fromImportedModules ::
[(TopLevelModuleName, Hash)] -> RangedImportedModules
fromImportedModules ms = [(SerialisedRange $ getRange x, x, hash) | (x, hash) <- ms]
toImportedModules ::
RangedImportedModules -> [(TopLevelModuleName, Hash)]
toImportedModules ms = [(setRange (underlyingRange r) x, hash) | (r, x, hash) <- ms]
instance EmbPrj Interface where
icod_ (Interface a b c d e f g h i j k l m n o p q r s t u v) =
icodeN' interface a b c (fromImportedModules d) e f g h i j k l m n o p q r s t u v
where interface a b c = Interface a b c . toImportedModules
value = vcase valu where
valu [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v] =
valuN interface a b c d e f g h i j k l m n o p q r s t u v
where interface a b c = Interface a b c . toImportedModules
valu _ = malformed
| null | https://raw.githubusercontent.com/agda/agda/c859b5e8737a006b559723a1048bba10806bda2d/src/full/Agda/TypeChecking/Serialise/Instances.hs | haskell | Only instances exported | # OPTIONS_GHC -fno - warn - orphans #
module Agda.TypeChecking.Serialise.Instances () where
import Agda.Syntax.Position
import Agda.Syntax.TopLevelModuleName
import Agda.TypeChecking.Monad.Base
import Agda.TypeChecking.Serialise.Base
import Agda.TypeChecking.Serialise.Instances.Common (SerialisedRange(..))
import Agda.TypeChecking.Serialise.Instances.Highlighting ()
import Agda.TypeChecking.Serialise.Instances.Errors ()
import Agda.Utils.Hash
type RangedImportedModules =
[(SerialisedRange, TopLevelModuleName, Hash)]
fromImportedModules ::
[(TopLevelModuleName, Hash)] -> RangedImportedModules
fromImportedModules ms = [(SerialisedRange $ getRange x, x, hash) | (x, hash) <- ms]
toImportedModules ::
RangedImportedModules -> [(TopLevelModuleName, Hash)]
toImportedModules ms = [(setRange (underlyingRange r) x, hash) | (r, x, hash) <- ms]
instance EmbPrj Interface where
icod_ (Interface a b c d e f g h i j k l m n o p q r s t u v) =
icodeN' interface a b c (fromImportedModules d) e f g h i j k l m n o p q r s t u v
where interface a b c = Interface a b c . toImportedModules
value = vcase valu where
valu [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v] =
valuN interface a b c d e f g h i j k l m n o p q r s t u v
where interface a b c = Interface a b c . toImportedModules
valu _ = malformed
|
1c0d73c0ed57016180b62fda9d282419104045266b3e1a9c43359e6585d841f0 | fulcrologic/fulcro-rad-demo | blob_store.clj | (ns com.example.components.blob-store
(:require
[com.fulcrologic.rad.blob-storage :as storage]
[mount.core :refer [defstate]]))
(defstate temporary-blob-store
:start
(storage/transient-blob-store "" 1))
(defstate image-blob-store
:start
(storage/transient-blob-store "/images" 10000))
(defstate file-blob-store
:start
(storage/transient-blob-store "/files" 10000))
| null | https://raw.githubusercontent.com/fulcrologic/fulcro-rad-demo/28b8c2dd3cd9f9be66a621627d079bb19bd5e53b/src/shared/com/example/components/blob_store.clj | clojure | (ns com.example.components.blob-store
(:require
[com.fulcrologic.rad.blob-storage :as storage]
[mount.core :refer [defstate]]))
(defstate temporary-blob-store
:start
(storage/transient-blob-store "" 1))
(defstate image-blob-store
:start
(storage/transient-blob-store "/images" 10000))
(defstate file-blob-store
:start
(storage/transient-blob-store "/files" 10000))
| |
4d9ca339e7040c6dcc5ff539d778277085f9791dfc403ab925617fa7b6ca6a88 | facebook/infer | SourceFileGraph.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
val to_dotty : string -> unit
(** construct the file-call-graph and store it in [<results-dir>/<filename>] *)
val partition_source_file_call_graph : n_workers:int -> unit
| null | https://raw.githubusercontent.com/facebook/infer/7499c0354a412a5ceec8476a58c5953fcfeae2b9/infer/src/backend/SourceFileGraph.mli | ocaml | * construct the file-call-graph and store it in [<results-dir>/<filename>] |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
val to_dotty : string -> unit
val partition_source_file_call_graph : n_workers:int -> unit
|
b7658ba6a5828342b3655bf9d0be7914101e9491171666321ae8eef62fb6fa55 | BardurArantsson/cqrs | EventStream.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
module Data.CQRS.Types.EventStream
( EventStream(..)
, mkEmpty
, transform
, transformI
, transformE
) where
import Control.Arrow (second)
import Control.Monad ((>=>))
import Control.Monad.IO.Unlift (MonadUnliftIO(..))
import Data.Bifunctor (first)
import qualified Data.Bifunctor as B
import Data.CQRS.Types.Iso
import Data.CQRS.Types.PersistedEvent
import Data.CQRS.Types.StreamPosition
import Data.Int (Int32)
import UnliftIO.Streams (InputStream, nullInput)
import qualified UnliftIO.Streams.Combinators as SC
-- | EventStream for events of type 'e' identified by aggregate IDs of type 'i'.
data EventStream i e = EventStream {
-- | Read the event stream, starting __immediately after__ the
-- given position. The order is arbitrary-but-consistent such
-- that all events for any given aggregate are always read in
-- order of increasing sequence number and the ordering is
-- stable across calls and (assuming a persistent event store)
-- also across different runs of the program.
esReadEventStream :: forall a m . (MonadUnliftIO m) => StreamPosition -> (InputStream (StreamPosition, PersistedEvent' i e) -> m a) -> m a
,
-- | Read events for a given aggregate and from a given sequence
-- number (inclusive). The events are streamed in order of
-- increasing sequence number.
esReadAggregateEvents :: forall a m . (MonadUnliftIO m) => i -> Int32 -> (InputStream (PersistedEvent e) -> m a) -> m a
}
-- | Transform 'EventStream' via an isomorphism for the events and
-- aggregate IDs.
transform :: forall e e' i i' . Iso i' i -> Iso e' e -> EventStream i e -> EventStream i' e'
transform ifg efg eventStream = transformI ifg $ transformE efg eventStream
-- | Transform an 'EventStream i e' to an 'EventStream j e' via
-- an isomorphism between 'i' and 'j'.
transformI :: forall e i i' . Iso i' i -> EventStream i e -> EventStream i' e
transformI (fi, gi) (EventStream readEventStream' readAggregateEvents') =
EventStream readEventStream readAggregateEvents
where
readEventStream :: MonadUnliftIO m' => StreamPosition -> (InputStream (StreamPosition, PersistedEvent' i' e) -> m' a) -> m' a
readEventStream p' f =
readEventStream' p' $ SC.map (second $ first gi) >=> f
readAggregateEvents :: forall a m' . (MonadUnliftIO m') => i' -> Int32 -> (InputStream (PersistedEvent e) -> m' a) -> m' a
readAggregateEvents aggregateId' v0 p' =
readAggregateEvents' (fi aggregateId') v0 p'
-- | Transform an 'EventStream i e' to an 'EventStream i f' via
-- an isomorphism between 'e' and 'f'.
transformE :: forall i e e' . Iso e' e -> EventStream i e -> EventStream i e'
transformE (_, ge) (EventStream readEventStream' readAggregateEvents') =
EventStream readEventStream readAggregateEvents
where
readEventStream :: MonadUnliftIO m' => StreamPosition -> (InputStream (StreamPosition, PersistedEvent' i e') -> m' a) -> m' a
readEventStream p' f =
readEventStream' p' $ SC.map (second $ B.second ge) >=> f
readAggregateEvents :: forall a m' . (MonadUnliftIO m') => i -> Int32 -> (InputStream (PersistedEvent e') -> m' a) -> m' a
readAggregateEvents aggregateId v0 p' =
readAggregateEvents' aggregateId v0 $ SC.map (fmap ge) >=> p'
-- | Create an empty event stream.
mkEmpty :: MonadUnliftIO m => m (EventStream i e)
mkEmpty = do
i0 <- nullInput
i1 <- nullInput
pure $ EventStream
{ esReadEventStream = \_ f -> f i0
, esReadAggregateEvents = \_ _ f -> f i1
}
| null | https://raw.githubusercontent.com/BardurArantsson/cqrs/2491d83e2bcd68c883aaea33cdce6c5ea8c0cd1a/cqrs-core/src/Data/CQRS/Types/EventStream.hs | haskell | # LANGUAGE RankNTypes #
| EventStream for events of type 'e' identified by aggregate IDs of type 'i'.
| Read the event stream, starting __immediately after__ the
given position. The order is arbitrary-but-consistent such
that all events for any given aggregate are always read in
order of increasing sequence number and the ordering is
stable across calls and (assuming a persistent event store)
also across different runs of the program.
| Read events for a given aggregate and from a given sequence
number (inclusive). The events are streamed in order of
increasing sequence number.
| Transform 'EventStream' via an isomorphism for the events and
aggregate IDs.
| Transform an 'EventStream i e' to an 'EventStream j e' via
an isomorphism between 'i' and 'j'.
| Transform an 'EventStream i e' to an 'EventStream i f' via
an isomorphism between 'e' and 'f'.
| Create an empty event stream. | # LANGUAGE ScopedTypeVariables #
module Data.CQRS.Types.EventStream
( EventStream(..)
, mkEmpty
, transform
, transformI
, transformE
) where
import Control.Arrow (second)
import Control.Monad ((>=>))
import Control.Monad.IO.Unlift (MonadUnliftIO(..))
import Data.Bifunctor (first)
import qualified Data.Bifunctor as B
import Data.CQRS.Types.Iso
import Data.CQRS.Types.PersistedEvent
import Data.CQRS.Types.StreamPosition
import Data.Int (Int32)
import UnliftIO.Streams (InputStream, nullInput)
import qualified UnliftIO.Streams.Combinators as SC
data EventStream i e = EventStream {
esReadEventStream :: forall a m . (MonadUnliftIO m) => StreamPosition -> (InputStream (StreamPosition, PersistedEvent' i e) -> m a) -> m a
,
esReadAggregateEvents :: forall a m . (MonadUnliftIO m) => i -> Int32 -> (InputStream (PersistedEvent e) -> m a) -> m a
}
transform :: forall e e' i i' . Iso i' i -> Iso e' e -> EventStream i e -> EventStream i' e'
transform ifg efg eventStream = transformI ifg $ transformE efg eventStream
transformI :: forall e i i' . Iso i' i -> EventStream i e -> EventStream i' e
transformI (fi, gi) (EventStream readEventStream' readAggregateEvents') =
EventStream readEventStream readAggregateEvents
where
readEventStream :: MonadUnliftIO m' => StreamPosition -> (InputStream (StreamPosition, PersistedEvent' i' e) -> m' a) -> m' a
readEventStream p' f =
readEventStream' p' $ SC.map (second $ first gi) >=> f
readAggregateEvents :: forall a m' . (MonadUnliftIO m') => i' -> Int32 -> (InputStream (PersistedEvent e) -> m' a) -> m' a
readAggregateEvents aggregateId' v0 p' =
readAggregateEvents' (fi aggregateId') v0 p'
transformE :: forall i e e' . Iso e' e -> EventStream i e -> EventStream i e'
transformE (_, ge) (EventStream readEventStream' readAggregateEvents') =
EventStream readEventStream readAggregateEvents
where
readEventStream :: MonadUnliftIO m' => StreamPosition -> (InputStream (StreamPosition, PersistedEvent' i e') -> m' a) -> m' a
readEventStream p' f =
readEventStream' p' $ SC.map (second $ B.second ge) >=> f
readAggregateEvents :: forall a m' . (MonadUnliftIO m') => i -> Int32 -> (InputStream (PersistedEvent e') -> m' a) -> m' a
readAggregateEvents aggregateId v0 p' =
readAggregateEvents' aggregateId v0 $ SC.map (fmap ge) >=> p'
mkEmpty :: MonadUnliftIO m => m (EventStream i e)
mkEmpty = do
i0 <- nullInput
i1 <- nullInput
pure $ EventStream
{ esReadEventStream = \_ f -> f i0
, esReadAggregateEvents = \_ _ f -> f i1
}
|
5e6b3a01fe0995c99e7c48831b913d58b0c3c5b0a2377276b12a9522eb35c979 | rd--/hsc3 | trigControl.help.hs | trigControl ; graph with the three types of non - audio controls ; trigger controls are drawn cyan
let freq = control kr "freq" 440
phase = control ir "phase" 0
gate' = trigControl "gate" 1
amp = control kr "amp" 0.1
e = envGen kr gate' amp 0 1 DoNothing (envAsr 0.01 1 1 EnvLin)
in sinOsc ar freq phase * e
| null | https://raw.githubusercontent.com/rd--/hsc3/bb12d02f09481e7cb59ae2e9e5119d1f7c4c98c9/Help/Ugen/trigControl.help.hs | haskell | trigControl ; graph with the three types of non - audio controls ; trigger controls are drawn cyan
let freq = control kr "freq" 440
phase = control ir "phase" 0
gate' = trigControl "gate" 1
amp = control kr "amp" 0.1
e = envGen kr gate' amp 0 1 DoNothing (envAsr 0.01 1 1 EnvLin)
in sinOsc ar freq phase * e
| |
4df16d0959e2d08a68b395ac8a885a2cce8b6e2a0959da5087082cb62601bc46 | willowtreeapps/wombats-api | scheduler.clj | (ns wombats.components.scheduler
(:require [com.stuartsierra.component :as component]
[wombats.constants :refer [game-start-time-min
game-start-time-hour
add-game-request]]
[wombats.scheduler.core :as scheduler]
[wombats.daos.game :as game]
[wombats.daos.arena :as arena]
[wombats.daos.helpers :as helpers]
[clj-time.core :as t]))
(defrecord Scheduler [config datomic scheduler]
component/Lifecycle
(start [component]
(if scheduler
component
(let [conn (get-in datomic [:database :conn])
aws-credentials (get-in config [:settings :aws])
lambda-settings (get-in config [:settings :api-settings :lambda])]
;; Go through all the pending games, and schedule them
(assoc component
:scheduler
(scheduler/schedule-pending-games (game/get-all-pending-games conn)
(game/start-game conn aws-credentials lambda-settings))
:add-game
(scheduler/automatic-game-scheduler
{:initial-time (t/today-at game-start-time-hour game-start-time-min)
:game-params add-game-request
:add-game-fn (game/add-game conn)
:gen-id-fn helpers/gen-id
:get-game-by-id-fn (game/get-game-by-id conn)
:get-arena-by-id-fn (arena/get-arena-by-id conn)
:start-game-fn (game/start-game conn aws-credentials lambda-settings)})))))
(stop [component]
(if-not scheduler
component
(assoc component :scheduler nil))))
;; Public component methods
(defn new-scheduler
[]
(map->Scheduler {}))
| null | https://raw.githubusercontent.com/willowtreeapps/wombats-api/738e4cc8d7011998695ec85e663f650be71f60ae/src/wombats/components/scheduler.clj | clojure | Go through all the pending games, and schedule them
Public component methods | (ns wombats.components.scheduler
(:require [com.stuartsierra.component :as component]
[wombats.constants :refer [game-start-time-min
game-start-time-hour
add-game-request]]
[wombats.scheduler.core :as scheduler]
[wombats.daos.game :as game]
[wombats.daos.arena :as arena]
[wombats.daos.helpers :as helpers]
[clj-time.core :as t]))
(defrecord Scheduler [config datomic scheduler]
component/Lifecycle
(start [component]
(if scheduler
component
(let [conn (get-in datomic [:database :conn])
aws-credentials (get-in config [:settings :aws])
lambda-settings (get-in config [:settings :api-settings :lambda])]
(assoc component
:scheduler
(scheduler/schedule-pending-games (game/get-all-pending-games conn)
(game/start-game conn aws-credentials lambda-settings))
:add-game
(scheduler/automatic-game-scheduler
{:initial-time (t/today-at game-start-time-hour game-start-time-min)
:game-params add-game-request
:add-game-fn (game/add-game conn)
:gen-id-fn helpers/gen-id
:get-game-by-id-fn (game/get-game-by-id conn)
:get-arena-by-id-fn (arena/get-arena-by-id conn)
:start-game-fn (game/start-game conn aws-credentials lambda-settings)})))))
(stop [component]
(if-not scheduler
component
(assoc component :scheduler nil))))
(defn new-scheduler
[]
(map->Scheduler {}))
|
271770c731adba7bb822002500d6fc9f6f50d06276ed5358663f33d570fba505 | karimarttila/clojure | signin.cljs | (ns simplefrontend.signin
(:require
[reagent.core :as r]
[ajax.core :as a-core]
[simplefrontend.reagent-wrapper :as sf-rw]
[simplefrontend.components :as sf-components]
[simplefrontend.config :as sf-config]))
* * * * * vars . * * * * *
(def my-error-msg-atom (r/atom nil))
(def my-success-msg-atom (r/atom nil))
;; For debugging
(def my-response-atom (r/atom nil))
(defn reset-page
"Reset page atoms when coming here from home page."
[]
(reset! my-response-atom nil)
(reset! my-error-msg-atom nil)
(reset! my-success-msg-atom nil))
(defn -handler
"The success (http status 200) handler."
[response]
(.log js/console (str "ENTER -handler, response: " response))
(do
(reset! my-response-atom response)
(reset! my-success-msg-atom "Cool, sign-in successful! You can now proceed to Web store home page to login using your new credentials!")
(reset! my-error-msg-atom nil)))
(defn -error-handler
"The error (http status not 200) handler."
[response]
(.log js/console (str "ENTER -error-handler, response: " response))
(let [error-msg ((:response response) "msg")]
(do
(reset! my-response-atom response)
(reset! my-error-msg-atom error-msg)
(reset! my-success-msg-atom nil))))
(defn -submit-form
"Send form data to server using POST."
[first-name last-name email password]
(.log js/console (str "ENTER submit-form, email: " email))
(let [url (str (sf-config/get-base-url) "/signin")
data {:first-name first-name
:last-name last-name
:email email
:password password}]
(let [response (a-core/POST url
{:format :json
:params data
:response-format :json
:headers {"Accept" "application/json"
"Content-Type" "application/json"}
:handler -handler
:error-handler -error-handler})]
(.log js/console (str "Response: " response)))))
(defn signin-page
"The actual page function called by simplefrontend.core."
[]
(.log js/console (str "ENTER signin-page"))
(let [first-name-atom (r/atom nil)
last-name-atom (r/atom nil)
email-address-atom (r/atom nil)
password-atom (r/atom nil)]
(fn []
[:div
[:h1 "Sign-in"]
[:form
[sf-rw/grid
[:div [(sf-components/input "First name: "
"first-name"
"text"
first-name-atom)]]
[:div [(sf-components/input "Last name: "
"last-name"
"text"
last-name-atom)]]
[:div [(sf-components/input "Email address: "
"email-address"
"text"
email-address-atom)]]
[:div [(sf-components/input "Password: "
"password"
"text"
password-atom)]]]]
[:div [:input {:type "button" :value "Submit"
:on-click #(-submit-form @first-name-atom
@last-name-atom
@email-address-atom
@password-atom)}]]
[sf-rw/grid
(if (not (nil? @my-error-msg-atom))
[(sf-components/msg-field "Error: " "error" "text" "red" @my-error-msg-atom)])
(if (not (nil? @my-success-msg-atom))
[(sf-components/msg-field "Success: " "success" "text" "greenyellow" @my-success-msg-atom)])]
[:div [:a {:href "#/"} "Back to Web Store Home Page"]]])))
| null | https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/clj-ring-cljs-reagent-demo/simple-frontend/src/simplefrontend/signin.cljs | clojure | For debugging | (ns simplefrontend.signin
(:require
[reagent.core :as r]
[ajax.core :as a-core]
[simplefrontend.reagent-wrapper :as sf-rw]
[simplefrontend.components :as sf-components]
[simplefrontend.config :as sf-config]))
* * * * * vars . * * * * *
(def my-error-msg-atom (r/atom nil))
(def my-success-msg-atom (r/atom nil))
(def my-response-atom (r/atom nil))
(defn reset-page
"Reset page atoms when coming here from home page."
[]
(reset! my-response-atom nil)
(reset! my-error-msg-atom nil)
(reset! my-success-msg-atom nil))
(defn -handler
"The success (http status 200) handler."
[response]
(.log js/console (str "ENTER -handler, response: " response))
(do
(reset! my-response-atom response)
(reset! my-success-msg-atom "Cool, sign-in successful! You can now proceed to Web store home page to login using your new credentials!")
(reset! my-error-msg-atom nil)))
(defn -error-handler
"The error (http status not 200) handler."
[response]
(.log js/console (str "ENTER -error-handler, response: " response))
(let [error-msg ((:response response) "msg")]
(do
(reset! my-response-atom response)
(reset! my-error-msg-atom error-msg)
(reset! my-success-msg-atom nil))))
(defn -submit-form
"Send form data to server using POST."
[first-name last-name email password]
(.log js/console (str "ENTER submit-form, email: " email))
(let [url (str (sf-config/get-base-url) "/signin")
data {:first-name first-name
:last-name last-name
:email email
:password password}]
(let [response (a-core/POST url
{:format :json
:params data
:response-format :json
:headers {"Accept" "application/json"
"Content-Type" "application/json"}
:handler -handler
:error-handler -error-handler})]
(.log js/console (str "Response: " response)))))
(defn signin-page
"The actual page function called by simplefrontend.core."
[]
(.log js/console (str "ENTER signin-page"))
(let [first-name-atom (r/atom nil)
last-name-atom (r/atom nil)
email-address-atom (r/atom nil)
password-atom (r/atom nil)]
(fn []
[:div
[:h1 "Sign-in"]
[:form
[sf-rw/grid
[:div [(sf-components/input "First name: "
"first-name"
"text"
first-name-atom)]]
[:div [(sf-components/input "Last name: "
"last-name"
"text"
last-name-atom)]]
[:div [(sf-components/input "Email address: "
"email-address"
"text"
email-address-atom)]]
[:div [(sf-components/input "Password: "
"password"
"text"
password-atom)]]]]
[:div [:input {:type "button" :value "Submit"
:on-click #(-submit-form @first-name-atom
@last-name-atom
@email-address-atom
@password-atom)}]]
[sf-rw/grid
(if (not (nil? @my-error-msg-atom))
[(sf-components/msg-field "Error: " "error" "text" "red" @my-error-msg-atom)])
(if (not (nil? @my-success-msg-atom))
[(sf-components/msg-field "Success: " "success" "text" "greenyellow" @my-success-msg-atom)])]
[:div [:a {:href "#/"} "Back to Web Store Home Page"]]])))
|
9cdd7cb88b4dc9804c92a94d7fc75a6eeb5a9b4e55d0a6518489f5a83868efc4 | clj-commons/seesaw | options.clj | Copyright ( c ) , 2011 . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this
; distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "Functions for dealing with options."
:author "Dave Ray"}
seesaw.options
(:use [seesaw.util :only [camelize illegal-argument check-args
resource resource-key?]]))
(defprotocol OptionProvider
(get-option-maps* [this]))
(defn get-option-map [this]
(apply merge (get-option-maps* this)))
(defmacro option-provider [class options]
`(extend-protocol OptionProvider
~class
(~'get-option-maps* [this#] [~options])))
(defrecord Option [name setter getter examples])
(declare apply-options)
(defn- strip-question-mark
[^String s]
(if (.endsWith s "?")
(.substring s 0 (dec (count s)))
s))
(defn- setter-name [property]
(->> property
name
strip-question-mark
(str "set-")
camelize
symbol))
(defn- getter-name [property]
(let [property (name property)
prefix (if (.endsWith property "?") "is-" "get-")]
(->> property
name
strip-question-mark
(str prefix)
camelize
symbol)))
(defn- split-bean-option-name [v]
(cond
(vector? v) v
:else [v v]))
(defmacro bean-option
[name-arg target-type & [set-conv get-conv examples]]
(let [[option-name bean-property-name] (split-bean-option-name name-arg)
target (gensym "target")]
`(Option. ~option-name
(fn [~(with-meta target {:tag target-type}) value#]
(. ~target ~(setter-name bean-property-name) (~(or set-conv `identity) value#)))
(fn [~(with-meta target {:tag target-type})]
(~(or get-conv `identity) (. ~target ~(getter-name bean-property-name))))
~examples)))
(defn default-option
([name] (default-option name (fn [_ _] (illegal-argument "No setter defined for option %s" name))))
([name setter] (default-option name setter (fn [_] (illegal-argument "No getter defined for option %s" name))))
([name setter getter] (default-option name setter getter nil))
([name setter getter examples] (Option. name setter getter examples)))
(defn ignore-option
"Might be used to explicitly ignore the default behaviour of options."
([name examples] (default-option name (fn [_ _]) (fn [_ _]) "Internal use."))
([name] (ignore-option name nil)))
(defn resource-option
"Defines an option that takes a j18n namespace-qualified keyword as a
value. The keyword is used as a prefix for the set of properties in
the given key list. This allows subsets of widget options to be configured
from a resource bundle.
Example:
; The :resource property looks in a resource bundle for
; prefix.text, prefix.foreground, etc.
(resource-option :resource [:text :foreground :background])
"
[option-name keys]
(default-option
option-name
(fn [target value]
{:pre [(resource-key? value)]}
(let [nspace (namespace value)
prefix (name value)]
(apply-options
target (mapcat (fn [k]
(let [prop (keyword nspace (str prefix "." k))]
(when-let [v (resource prop)]
[(keyword k) v])))
(map name keys)))))
nil
[(str "A i18n prefix for a resource with keys")
(pr-str keys)]))
(defn- apply-option
[target ^Option opt v]
(if-let [setter (:setter opt)]
(setter target v)
(illegal-argument "No setter found for option %s" (:name opt))))
(defn- ^Option lookup-option [target handler-maps name]
;(println "---------------------------")
;(println handler-maps)
(if-let [opt (some #(if % (% name)) handler-maps)]
opt
(illegal-argument "%s does not support the %s option" (class target) name)))
(defn- apply-options*
[target opts handler-maps]
(let [pairs (if (map? opts) opts (partition 2 opts))]
(doseq [[k v] pairs]
(let [opt (lookup-option target handler-maps k)]
(apply-option target opt v))))
target)
(defn apply-options
[target opts]
(check-args (or (map? opts) (even? (count opts)))
"opts must be a map or have an even number of entries")
(apply-options* target opts (get-option-maps* target)))
(defn ignore-options
"Create a ignore-map for options, which should be ignored. Ready to
be merged into default option maps."
[source-options]
(into {} (for [k (keys source-options)] [k (ignore-option k)])))
(defn around-option
([parent-option set-conv get-conv examples]
(default-option (:name parent-option)
(fn [target value]
((:setter parent-option) target ((or set-conv identity) value)))
(fn [target]
((or get-conv identity) ((:getter parent-option) target)))
examples))
([parent-option set-conv get-conv]
(around-option parent-option set-conv get-conv nil)))
(defn option-map
"Construct an option map from a list of options."
[& opts]
(into {} (map (juxt :name identity) opts)))
(defn get-option-value
([target name] (get-option-value target name (get-option-maps* target)))
([target name handlers]
(let [^Option option (lookup-option target handlers name)
getter (:getter option)]
(if getter
(getter target)
(illegal-argument "Option %s cannot be read from %s" name (class target))))))
(defn set-option-value
([target name value] (set-option-value target name (get-option-maps* target)))
([target name value handlers]
(let [^Option option (lookup-option target handlers name)
setter (:setter option)]
(if setter
(setter target value)
(illegal-argument "Option %s cannot be set on %s" name (class target))))))
| null | https://raw.githubusercontent.com/clj-commons/seesaw/4ca89d0dcdf0557d99d5fa84202b7cc6e2e92263/src/seesaw/options.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
The :resource property looks in a resource bundle for
prefix.text, prefix.foreground, etc.
(println "---------------------------")
(println handler-maps) | Copyright ( c ) , 2011 . All rights reserved .
(ns ^{:doc "Functions for dealing with options."
:author "Dave Ray"}
seesaw.options
(:use [seesaw.util :only [camelize illegal-argument check-args
resource resource-key?]]))
(defprotocol OptionProvider
(get-option-maps* [this]))
(defn get-option-map [this]
(apply merge (get-option-maps* this)))
(defmacro option-provider [class options]
`(extend-protocol OptionProvider
~class
(~'get-option-maps* [this#] [~options])))
(defrecord Option [name setter getter examples])
(declare apply-options)
(defn- strip-question-mark
[^String s]
(if (.endsWith s "?")
(.substring s 0 (dec (count s)))
s))
(defn- setter-name [property]
(->> property
name
strip-question-mark
(str "set-")
camelize
symbol))
(defn- getter-name [property]
(let [property (name property)
prefix (if (.endsWith property "?") "is-" "get-")]
(->> property
name
strip-question-mark
(str prefix)
camelize
symbol)))
(defn- split-bean-option-name [v]
(cond
(vector? v) v
:else [v v]))
(defmacro bean-option
[name-arg target-type & [set-conv get-conv examples]]
(let [[option-name bean-property-name] (split-bean-option-name name-arg)
target (gensym "target")]
`(Option. ~option-name
(fn [~(with-meta target {:tag target-type}) value#]
(. ~target ~(setter-name bean-property-name) (~(or set-conv `identity) value#)))
(fn [~(with-meta target {:tag target-type})]
(~(or get-conv `identity) (. ~target ~(getter-name bean-property-name))))
~examples)))
(defn default-option
([name] (default-option name (fn [_ _] (illegal-argument "No setter defined for option %s" name))))
([name setter] (default-option name setter (fn [_] (illegal-argument "No getter defined for option %s" name))))
([name setter getter] (default-option name setter getter nil))
([name setter getter examples] (Option. name setter getter examples)))
(defn ignore-option
"Might be used to explicitly ignore the default behaviour of options."
([name examples] (default-option name (fn [_ _]) (fn [_ _]) "Internal use."))
([name] (ignore-option name nil)))
(defn resource-option
"Defines an option that takes a j18n namespace-qualified keyword as a
value. The keyword is used as a prefix for the set of properties in
the given key list. This allows subsets of widget options to be configured
from a resource bundle.
Example:
(resource-option :resource [:text :foreground :background])
"
[option-name keys]
(default-option
option-name
(fn [target value]
{:pre [(resource-key? value)]}
(let [nspace (namespace value)
prefix (name value)]
(apply-options
target (mapcat (fn [k]
(let [prop (keyword nspace (str prefix "." k))]
(when-let [v (resource prop)]
[(keyword k) v])))
(map name keys)))))
nil
[(str "A i18n prefix for a resource with keys")
(pr-str keys)]))
(defn- apply-option
[target ^Option opt v]
(if-let [setter (:setter opt)]
(setter target v)
(illegal-argument "No setter found for option %s" (:name opt))))
(defn- ^Option lookup-option [target handler-maps name]
(if-let [opt (some #(if % (% name)) handler-maps)]
opt
(illegal-argument "%s does not support the %s option" (class target) name)))
(defn- apply-options*
[target opts handler-maps]
(let [pairs (if (map? opts) opts (partition 2 opts))]
(doseq [[k v] pairs]
(let [opt (lookup-option target handler-maps k)]
(apply-option target opt v))))
target)
(defn apply-options
[target opts]
(check-args (or (map? opts) (even? (count opts)))
"opts must be a map or have an even number of entries")
(apply-options* target opts (get-option-maps* target)))
(defn ignore-options
"Create a ignore-map for options, which should be ignored. Ready to
be merged into default option maps."
[source-options]
(into {} (for [k (keys source-options)] [k (ignore-option k)])))
(defn around-option
([parent-option set-conv get-conv examples]
(default-option (:name parent-option)
(fn [target value]
((:setter parent-option) target ((or set-conv identity) value)))
(fn [target]
((or get-conv identity) ((:getter parent-option) target)))
examples))
([parent-option set-conv get-conv]
(around-option parent-option set-conv get-conv nil)))
(defn option-map
"Construct an option map from a list of options."
[& opts]
(into {} (map (juxt :name identity) opts)))
(defn get-option-value
([target name] (get-option-value target name (get-option-maps* target)))
([target name handlers]
(let [^Option option (lookup-option target handlers name)
getter (:getter option)]
(if getter
(getter target)
(illegal-argument "Option %s cannot be read from %s" name (class target))))))
(defn set-option-value
([target name value] (set-option-value target name (get-option-maps* target)))
([target name value handlers]
(let [^Option option (lookup-option target handlers name)
setter (:setter option)]
(if setter
(setter target value)
(illegal-argument "Option %s cannot be set on %s" name (class target))))))
|
a264c8464189c43bcc6b37813aa5d78c8a9dd7365b3069b195295c47a989143b | jaspervdj/blaze-html | Pretty.hs | module Text.Blaze.Html.Renderer.Pretty
( renderHtml
) where
import Text.Blaze.Html (Html)
import Text.Blaze.Renderer.Pretty (renderMarkup)
renderHtml :: Html -> String
renderHtml = renderMarkup
| null | https://raw.githubusercontent.com/jaspervdj/blaze-html/1c76db3cf02712569fd22b021fb0a367df028eb4/src/Text/Blaze/Html/Renderer/Pretty.hs | haskell | module Text.Blaze.Html.Renderer.Pretty
( renderHtml
) where
import Text.Blaze.Html (Html)
import Text.Blaze.Renderer.Pretty (renderMarkup)
renderHtml :: Html -> String
renderHtml = renderMarkup
| |
fab68cd853f4e62798d054d0f765eeef4f6b2149060c2252eaa2e37890318661 | robashton/cravendb | remote.clj | (ns cravendb.remote
(:require [http.async.client :as http])
(:require [cemerick.url :refer (url-encode)]
[clojure.edn :as edn]
[cravendb.core :refer [zero-synctag]]
[cravendb.database :refer [DocumentDatabase]]
[clojure.tools.logging :refer [debug info error]]))
(defn url-for-doc-id [url id]
(str url "/document/" id))
(defn url-for-index-id [url id]
(str url "/index/" id))
(defn url-for-bulk-ops [url]
(str url "/bulk"))
(defn url-for-conflicts [url]
(str url "/conflicts"))
(defn url-for-conflict-id [url id]
(str url "/conflict/" id))
(defn url-for-stream [url synctag]
(str url "/stream?synctag=" (or synctag "")))
(defn url-for-query [url opts]
(str
url "/query/"
(opts :index) "/"
(url-encode (opts :filter))))
(defn to-db [data]
(pr-str data))
(defn from-db [data]
(if (nil? data) nil
(edn/read-string data)))
(defn force-into-list [result]
(if (nil? result) ()
(if (seq? result) result (seq [result]))))
(defn from-http [input]
(if (= 404 (:code @(:status input)))
nil
(from-db (http/string input))))
(defn interpret-headers [input]
(let [headers (http/headers input)]
(edn/read-string (or (headers "cravendb-metadata") "{}"))))
(defn extract-headers [metadata]
{ "cravendb-metadata" (pr-str metadata)
"etag" (:history metadata) } )
(defn process-response [response]
(-> response
http/await
from-http))
(defn read-metadata [response]
(-> response
http/await
interpret-headers))
(def default-headers { :accept "application/edn" })
(defrecord RemoteDatabase [url]
DocumentDatabase
(close [this])
(load-document-metadata [this id]
(with-open [client (http/create-client)]
(read-metadata
(http/HEAD client (url-for-doc-id url id) :headers default-headers))))
(query [this opts]
(with-open [client (http/create-client)]
(force-into-list
(process-response
(http/GET client (url-for-query url opts)
:headers default-headers
:query (dissoc opts :filter :index))))))
(clear-conflicts [this id]
(with-open [client (http/create-client)]
(process-response
(http/DELETE client (url-for-conflict-id url id) :headers default-headers))))
(conflicts [this]
(with-open [client (http/create-client)]
(force-into-list
(process-response
(http/GET client (url-for-conflicts url) :headers default-headers)))))
(put-document [this id document metadata]
(with-open [client (http/create-client)]
(process-response
(http/PUT client (url-for-doc-id url id) :body (to-db document) :headers (merge default-headers (extract-headers metadata))))))
(delete-document [this id metadata]
(with-open [client (http/create-client)]
(process-response
(http/DELETE client (url-for-doc-id url id) :headers (merge default-headers (extract-headers metadata))))))
(load-document [this id]
(with-open [client (http/create-client)]
(process-response
(http/GET client (url-for-doc-id url id) :headers default-headers))))
(bulk [this operations]
(with-open [client (http/create-client)]
(process-response
(http/POST client (url-for-bulk-ops url) :body (to-db operations) :headers default-headers))))
(put-index [this index]
(with-open [client (http/create-client)]
(process-response
(http/PUT client (url-for-index-id url (:id index)) :body (to-db index)
:headers default-headers))))
(load-index-metadata [this id]
(with-open [client (http/create-client)]
(read-metadata
(http/HEAD client (url-for-index-id url id) :headers default-headers))))
(delete-index [this id]
(with-open [client (http/create-client)]
(process-response
(http/DELETE client (url-for-index-id url id) :headers default-headers))))
(load-index [this id]
(with-open [client (http/create-client)]
(process-response
(http/GET client (url-for-index-id url id) :headers default-headers)))))
(defn create [& kvs]
(let [opts (apply hash-map kvs)]
(RemoteDatabase. (:href opts))))
| null | https://raw.githubusercontent.com/robashton/cravendb/461e80c7c028478adb4287922db6ee4d2593a880/src/cravendb/remote.clj | clojure | (ns cravendb.remote
(:require [http.async.client :as http])
(:require [cemerick.url :refer (url-encode)]
[clojure.edn :as edn]
[cravendb.core :refer [zero-synctag]]
[cravendb.database :refer [DocumentDatabase]]
[clojure.tools.logging :refer [debug info error]]))
(defn url-for-doc-id [url id]
(str url "/document/" id))
(defn url-for-index-id [url id]
(str url "/index/" id))
(defn url-for-bulk-ops [url]
(str url "/bulk"))
(defn url-for-conflicts [url]
(str url "/conflicts"))
(defn url-for-conflict-id [url id]
(str url "/conflict/" id))
(defn url-for-stream [url synctag]
(str url "/stream?synctag=" (or synctag "")))
(defn url-for-query [url opts]
(str
url "/query/"
(opts :index) "/"
(url-encode (opts :filter))))
(defn to-db [data]
(pr-str data))
(defn from-db [data]
(if (nil? data) nil
(edn/read-string data)))
(defn force-into-list [result]
(if (nil? result) ()
(if (seq? result) result (seq [result]))))
(defn from-http [input]
(if (= 404 (:code @(:status input)))
nil
(from-db (http/string input))))
(defn interpret-headers [input]
(let [headers (http/headers input)]
(edn/read-string (or (headers "cravendb-metadata") "{}"))))
(defn extract-headers [metadata]
{ "cravendb-metadata" (pr-str metadata)
"etag" (:history metadata) } )
(defn process-response [response]
(-> response
http/await
from-http))
(defn read-metadata [response]
(-> response
http/await
interpret-headers))
(def default-headers { :accept "application/edn" })
(defrecord RemoteDatabase [url]
DocumentDatabase
(close [this])
(load-document-metadata [this id]
(with-open [client (http/create-client)]
(read-metadata
(http/HEAD client (url-for-doc-id url id) :headers default-headers))))
(query [this opts]
(with-open [client (http/create-client)]
(force-into-list
(process-response
(http/GET client (url-for-query url opts)
:headers default-headers
:query (dissoc opts :filter :index))))))
(clear-conflicts [this id]
(with-open [client (http/create-client)]
(process-response
(http/DELETE client (url-for-conflict-id url id) :headers default-headers))))
(conflicts [this]
(with-open [client (http/create-client)]
(force-into-list
(process-response
(http/GET client (url-for-conflicts url) :headers default-headers)))))
(put-document [this id document metadata]
(with-open [client (http/create-client)]
(process-response
(http/PUT client (url-for-doc-id url id) :body (to-db document) :headers (merge default-headers (extract-headers metadata))))))
(delete-document [this id metadata]
(with-open [client (http/create-client)]
(process-response
(http/DELETE client (url-for-doc-id url id) :headers (merge default-headers (extract-headers metadata))))))
(load-document [this id]
(with-open [client (http/create-client)]
(process-response
(http/GET client (url-for-doc-id url id) :headers default-headers))))
(bulk [this operations]
(with-open [client (http/create-client)]
(process-response
(http/POST client (url-for-bulk-ops url) :body (to-db operations) :headers default-headers))))
(put-index [this index]
(with-open [client (http/create-client)]
(process-response
(http/PUT client (url-for-index-id url (:id index)) :body (to-db index)
:headers default-headers))))
(load-index-metadata [this id]
(with-open [client (http/create-client)]
(read-metadata
(http/HEAD client (url-for-index-id url id) :headers default-headers))))
(delete-index [this id]
(with-open [client (http/create-client)]
(process-response
(http/DELETE client (url-for-index-id url id) :headers default-headers))))
(load-index [this id]
(with-open [client (http/create-client)]
(process-response
(http/GET client (url-for-index-id url id) :headers default-headers)))))
(defn create [& kvs]
(let [opts (apply hash-map kvs)]
(RemoteDatabase. (:href opts))))
| |
2c4c30d6762ecba857fe82bd6e90b916548061fbdccdd8cefb349e8a42a45e80 | taylorwood/advent-of-code | 7.clj | (ns advent-of-code.2017.7
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[clojure.walk :as walk]))
(def raw-input (slurp (io/resource "data_2017/7.txt")))
(defn parse-line [l]
(let [[name weight] (rest (re-find #"(\w+)\s\((\d+)\)" l))
kids (when-let [adj-text (re-find #".+->(.+)" l)]
(as-> adj-text $
(last $)
(cs/split $ #",")
(map cs/trim $)))]
{:name name
:weight (Integer/parseInt weight)
:children kids}))
(def graph (map parse-line (cs/split-lines raw-input)))
(def all-children (set (mapcat :children graph)))
;; solve part one: find the node that has no parents
(def root (first (filter #(not (all-children (:name %))) graph)))
part two begins .. convert adjacency list input to proper tree
(defn children
"Returns any children for a given node and adjacency list."
[adj-list node]
(when-let [children (seq (:children node))]
(for [child-name children]
(first (filter #(= child-name (:name %)) adj-list)))))
(defn ->tree
"Converts an adjacency list representation to tree."
[adj-list node]
(if-let [kids (children adj-list node)]
(assoc node :children (map #(->tree adj-list %) kids))
node))
(def tree
"Recursive representation of input graph, with child weight sums at each branch."
(walk/postwalk
(fn [v]
(cond
(and (map? v)
(seq (:children v)))
(let [{:keys [weight children]} v
child-weights (map (some-fn :sum :weight) children)
child-weight-sum (reduce + child-weights)
balanced? (every? #(= % (first child-weights))
child-weights)]
(assoc v :sum (+ weight child-weight-sum)
:balanced? balanced?))
:else v))
(->tree graph root)))
;; find the *deepest* off-balance map
(->> tree
(tree-seq (comp seq :children) :children)
(filter #(false? (:balanced? %)))
(last))
;; then I just eyeballed the weights and did the simple math manually
| null | https://raw.githubusercontent.com/taylorwood/advent-of-code/c6b08f4b618875a45c8083a04ae2c669626c43bf/src/advent_of_code/2017/7.clj | clojure | solve part one: find the node that has no parents
find the *deepest* off-balance map
then I just eyeballed the weights and did the simple math manually | (ns advent-of-code.2017.7
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[clojure.walk :as walk]))
(def raw-input (slurp (io/resource "data_2017/7.txt")))
(defn parse-line [l]
(let [[name weight] (rest (re-find #"(\w+)\s\((\d+)\)" l))
kids (when-let [adj-text (re-find #".+->(.+)" l)]
(as-> adj-text $
(last $)
(cs/split $ #",")
(map cs/trim $)))]
{:name name
:weight (Integer/parseInt weight)
:children kids}))
(def graph (map parse-line (cs/split-lines raw-input)))
(def all-children (set (mapcat :children graph)))
(def root (first (filter #(not (all-children (:name %))) graph)))
part two begins .. convert adjacency list input to proper tree
(defn children
"Returns any children for a given node and adjacency list."
[adj-list node]
(when-let [children (seq (:children node))]
(for [child-name children]
(first (filter #(= child-name (:name %)) adj-list)))))
(defn ->tree
"Converts an adjacency list representation to tree."
[adj-list node]
(if-let [kids (children adj-list node)]
(assoc node :children (map #(->tree adj-list %) kids))
node))
(def tree
"Recursive representation of input graph, with child weight sums at each branch."
(walk/postwalk
(fn [v]
(cond
(and (map? v)
(seq (:children v)))
(let [{:keys [weight children]} v
child-weights (map (some-fn :sum :weight) children)
child-weight-sum (reduce + child-weights)
balanced? (every? #(= % (first child-weights))
child-weights)]
(assoc v :sum (+ weight child-weight-sum)
:balanced? balanced?))
:else v))
(->tree graph root)))
(->> tree
(tree-seq (comp seq :children) :children)
(filter #(false? (:balanced? %)))
(last))
|
7733efcfd9504035e707a19869d3b688def3bc79df0c1d41da64b99f22d82f2b | manavpatnaik/haskell | 3_fold.hs | import Prelude
-- foldr => fold right
-- foldl => fold left
main = do
-- foldr: performs the operation on the list and adds it to the init value
Here its 0 . Its like the reduce function in JS
print(foldr (+) 0 [1,2,3,4,5])
print(foldl (+) 0 [1,2,3,4,5])
print(foldr (*) 1 [1,2,3,4,5])
print(foldl (*) 1 [1,2,3,4,5]) | null | https://raw.githubusercontent.com/manavpatnaik/haskell/9e7c805afb2607468c2e2977247266ccc19d24b6/higher_order_functions/3_fold.hs | haskell | foldr => fold right
foldl => fold left
foldr: performs the operation on the list and adds it to the init value | import Prelude
main = do
Here its 0 . Its like the reduce function in JS
print(foldr (+) 0 [1,2,3,4,5])
print(foldl (+) 0 [1,2,3,4,5])
print(foldr (*) 1 [1,2,3,4,5])
print(foldl (*) 1 [1,2,3,4,5]) |
b43bad23f204f85ed71a3ac5f7b935ef350d79112d95c2270ef00abbd3cee21a | yrashk/erlang | snmp_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(snmp_SUITE).
-export([all/1,
init_per_testcase/2, fin_per_testcase/2
]).
-export([app/1, compiler/1, misc/1, agent/1, manager/1]).
-export([
app_test/1,
appup_test/1,
compiler_test/1,
conf_test/1,
pdus_test/1,
log_test/1,
note_store_test/1,
mibs_test/1,
nfilter_test/1,
agent_test/1,
manager_config_test/1,
manager_user_test/1,
manager_test/1
]).
%%
%% -----
%%
init_per_testcase(_Case, Config) when list(Config) ->
Config.
fin_per_testcase(_Case, Config) when list(Config) ->
Config.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Top test case
all(doc) ->
["Test suites for the snmp application.",
"There are eight different sub test-suites."];
all(suite) ->
[
app,
compiler,
misc,
agent,
manager
].
app(suite) ->
[
app_test,
appup_test
].
compiler(suite) ->
[
compiler_test
].
misc(suite) ->
[
conf_test,
pdus_test,
log_test,
note_store_test
].
agent(suite) ->
[
mibs_test,
nfilter_test,
agent_test
].
manager(suite) ->
[
manager_config_test,
manager_user_test,
manager_test
].
app_test(suite) ->
[{snmp_app_test, all}].
appup_test(suite) ->
[{snmp_appup_test, all}].
compiler_test(suite) ->
[{snmp_compiler_test, all}].
conf_test(suite) ->
[{snmp_conf_test, all}].
pdus_test(suite) ->
[{snmp_pdus_test, all}].
log_test(suite) ->
[{snmp_log_test, all}].
note_store_test(suite) ->
[{snmp_note_store_test, all}].
mibs_test(suite) ->
[{snmp_agent_mibs_test, all}].
nfilter_test(suite) ->
[{snmp_agent_nfilter_test, all}].
agent_test(suite) ->
[{snmp_agent_test, all}].
manager_config_test(suite) ->
[{snmp_manager_config_test, all}].
manager_user_test(suite) ->
[{snmp_manager_user_test, all}].
manager_test(suite) ->
[{snmp_manager_test, all}].
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/snmp/test/snmp_SUITE.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
-----
Top test case | Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(snmp_SUITE).
-export([all/1,
init_per_testcase/2, fin_per_testcase/2
]).
-export([app/1, compiler/1, misc/1, agent/1, manager/1]).
-export([
app_test/1,
appup_test/1,
compiler_test/1,
conf_test/1,
pdus_test/1,
log_test/1,
note_store_test/1,
mibs_test/1,
nfilter_test/1,
agent_test/1,
manager_config_test/1,
manager_user_test/1,
manager_test/1
]).
init_per_testcase(_Case, Config) when list(Config) ->
Config.
fin_per_testcase(_Case, Config) when list(Config) ->
Config.
all(doc) ->
["Test suites for the snmp application.",
"There are eight different sub test-suites."];
all(suite) ->
[
app,
compiler,
misc,
agent,
manager
].
app(suite) ->
[
app_test,
appup_test
].
compiler(suite) ->
[
compiler_test
].
misc(suite) ->
[
conf_test,
pdus_test,
log_test,
note_store_test
].
agent(suite) ->
[
mibs_test,
nfilter_test,
agent_test
].
manager(suite) ->
[
manager_config_test,
manager_user_test,
manager_test
].
app_test(suite) ->
[{snmp_app_test, all}].
appup_test(suite) ->
[{snmp_appup_test, all}].
compiler_test(suite) ->
[{snmp_compiler_test, all}].
conf_test(suite) ->
[{snmp_conf_test, all}].
pdus_test(suite) ->
[{snmp_pdus_test, all}].
log_test(suite) ->
[{snmp_log_test, all}].
note_store_test(suite) ->
[{snmp_note_store_test, all}].
mibs_test(suite) ->
[{snmp_agent_mibs_test, all}].
nfilter_test(suite) ->
[{snmp_agent_nfilter_test, all}].
agent_test(suite) ->
[{snmp_agent_test, all}].
manager_config_test(suite) ->
[{snmp_manager_config_test, all}].
manager_user_test(suite) ->
[{snmp_manager_user_test, all}].
manager_test(suite) ->
[{snmp_manager_test, all}].
|
375a0f67f3ba463878bd5b68f2ecf0c98e17e00879209770c75496e811a93aa7 | ruHaskell/ruhaskell | About.hs | {-# LANGUAGE OverloadedStrings #-}
module About (
createAboutPage
) where
import Control.Monad.Trans (lift)
import Hakyll (applyTemplate, compile, constField, create,
defaultContext, idRoute, makeItem, relativizeUrls,
route)
import Markup.About (aboutTemplate)
import Markup.Default (defaultTemplate)
import Misc (TagsReader)
createAboutPage :: TagsReader
createAboutPage =
lift . create ["about.html"] $ do
route idRoute
compile $ do
aboutTemp <- aboutTemplate
defaultTemp <- defaultTemplate
makeItem ""
>>= applyTemplate aboutTemp indexContext
>>= applyTemplate defaultTemp indexContext
>>= relativizeUrls
where
indexContext = mconcat [constField "title" "О нас", defaultContext]
| null | https://raw.githubusercontent.com/ruHaskell/ruhaskell/1e38eae50011307d11a2026af925a23a6fd8a346/src/About.hs | haskell | # LANGUAGE OverloadedStrings # |
module About (
createAboutPage
) where
import Control.Monad.Trans (lift)
import Hakyll (applyTemplate, compile, constField, create,
defaultContext, idRoute, makeItem, relativizeUrls,
route)
import Markup.About (aboutTemplate)
import Markup.Default (defaultTemplate)
import Misc (TagsReader)
createAboutPage :: TagsReader
createAboutPage =
lift . create ["about.html"] $ do
route idRoute
compile $ do
aboutTemp <- aboutTemplate
defaultTemp <- defaultTemplate
makeItem ""
>>= applyTemplate aboutTemp indexContext
>>= applyTemplate defaultTemp indexContext
>>= relativizeUrls
where
indexContext = mconcat [constField "title" "О нас", defaultContext]
|
fc10c8824f14a3461225d20fcdc050912ca2f504cf59128f071821cb408ccb90 | Kakadu/fp2022 | parser.ml | * Copyright 2021 - 2022 , Danila Pechenev &
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Angstrom
open Ast
open List
open String
open Typing
type error_message = string
type input = string
type dispatch =
{ parse_list_constructing : dispatch -> expression Angstrom.t
; parse_tuple : dispatch -> expression Angstrom.t
; parse_binary_operation : dispatch -> expression Angstrom.t
; parse_unary_operation : dispatch -> expression Angstrom.t
; parse_list : dispatch -> expression Angstrom.t
; parse_application : dispatch -> expression Angstrom.t
; parse_fun : dispatch -> expression Angstrom.t
; parse_conditional : dispatch -> expression Angstrom.t
; parse_matching : dispatch -> expression Angstrom.t
; parse_let_in : dispatch -> expression Angstrom.t
; parse_data_constructor : dispatch -> expression Angstrom.t
; parse_expression : dispatch -> expression Angstrom.t
; parse_effect_arg : dispatch -> expression Angstrom.t
; parse_perform : dispatch -> expression Angstrom.t
; parse_continue : dispatch -> expression Angstrom.t
}
(* Smart constructors for expressions *)
let eliteral x = ELiteral x
let eidentifier x = EIdentifier x
let etuple head tail = ETuple (head :: tail)
let elist x = EList x
let efun variable_list expression = EFun (variable_list, expression)
let ebinary_operation operator left_operand right_operand =
EBinaryOperation (operator, left_operand, right_operand)
;;
let edeclaration function_name variable_list expression =
EDeclaration (function_name, variable_list, expression)
;;
let erecursivedeclaration function_name variable_list expression =
ERecursiveDeclaration (function_name, variable_list, expression)
;;
let eif condition true_branch false_branch = EIf (condition, true_branch, false_branch)
let ematchwith expression cases = EMatchWith (expression, cases)
let eletin declaration_list body = ELetIn (declaration_list, body)
let eapplication function_expression operand_expression =
EApplication (function_expression, operand_expression)
;;
let edata_constructor constructor_name expression =
EDataConstructor (constructor_name, expression)
;;
let eunary_operation operation expression = EUnaryOperation (operation, expression)
let econstruct_list head tail = EConstructList (head, tail)
let eeffect_declaration effect_name effect_type =
EEffectDeclaration (effect_name, effect_type)
;;
let eeffect_noarg effect_name = EEffectNoArg effect_name
let eeffect_arg effect_name expression = EEffectArg (effect_name, expression)
let eperform expression = EPerform expression
let econtinue expression = EContinue expression
let eeffect_pattern expression = EEffectPattern expression
(* ---------------------------------- *)
(* Smart constructors for binary operators *)
let badd _ = Add
let bsub _ = Sub
let bmul _ = Mul
let bdiv _ = Div
let beq _ = Eq
let bneq _ = NEq
let bgt _ = GT
let bgte _ = GTE
let blt _ = LT
let blte _ = LTE
let band _ = AND
let bor _ = OR
(* --------------------------------------- *)
(* Smart constructors for unary operators *)
let uminus _ = Minus
let unot _ = Not
(* -------------------------------------- *)
(* Helpers *)
let space_predicate x = x == ' ' || x == '\n' || x == '\t' || x == '\r'
let remove_spaces = take_while space_predicate
let parens parser = remove_spaces *> char '(' *> parser <* remove_spaces <* char ')'
let parse_entity =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> take_while1 (fun x ->
contains "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'_" x)
)
;;
let parse_uncapitalized_entity =
parse_entity
>>= fun entity ->
if String.contains "abcdefghijklmnopqrstuvwxyz_" entity.[0]
then return entity
else fail "Parsing error: not an uncapitalized entity."
;;
let parse_capitalized_entity =
parse_entity
>>= fun entity ->
if String.contains "ABCDEFGHIJKLMNOPQRSTUVWXYZ" entity.[0]
then return entity
else fail "Parsing error: not a capitalized entity."
;;
let data_constructors = [ "Ok"; "Error"; "Some"; "None" ]
let keywords =
[ "let"
; "rec"
; "match"
; "with"
; "if"
; "then"
; "else"
; "in"
; "fun"
; "and"
; "effect"
; "type"
; "perform"
; "continue"
]
;;
(* ------- *)
Parsers
let parse_literal =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let is_digit = function
| '0' .. '9' -> true
| _ -> false
in
let parse_int_literal = take_while1 is_digit >>| int_of_string >>| fun x -> LInt x in
let parse_string_literal =
char '"' *> take_while (( != ) '"') <* char '"' >>| fun x -> LString x
in
let parse_char_literal = char '\'' *> any_char <* char '\'' >>| fun x -> LChar x in
let parse_bool_literal =
string "true" <|> string "false" >>| bool_of_string >>| fun x -> LBool x
in
let parse_unit_literal = string "()" >>| fun _ -> LUnit in
let parse_literal =
choice
[ parse_int_literal
; parse_string_literal
; parse_char_literal
; parse_bool_literal
; parse_unit_literal
]
in
lift eliteral parse_literal)
;;
let parse_identifier =
fix
@@ fun _ ->
remove_spaces
*>
let parse_identifier =
parse_uncapitalized_entity
>>= fun entity ->
if List.exists (( = ) entity) keywords
then fail "Parsing error: keyword used."
else return @@ eidentifier entity
in
parse_identifier
;;
let parse_effect_noarg = lift eeffect_noarg parse_capitalized_entity
let parse_effect_pattern effect_parser =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift eeffect_pattern (string "effect" *> remove_spaces *> effect_parser))
;;
let parse_tuple d =
fix
@@ fun self ->
remove_spaces
*> ((let parse_content =
choice
[ parens self
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
and separator = remove_spaces *> char ',' *> remove_spaces in
lift2
etuple
(parse_content <* separator)
(sep_by1 separator parse_content <* remove_spaces))
<|> parens self)
;;
let parse_list d =
fix
@@ fun self ->
remove_spaces
*>
let brackets parser = char '[' *> parser <* char ']'
and separator = remove_spaces *> char ';' *> remove_spaces <|> remove_spaces
and parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; self
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> lift elist @@ brackets @@ (remove_spaces *> many (parse_content <* separator))
;;
let parse_fun d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; self
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> string "fun"
*> lift2
efun
(many1 parse_uncapitalized_entity
<* remove_spaces
<* string "->"
<* remove_spaces)
(parse_content <* remove_spaces)
;;
Used in parse_declaration and
let declaration_helper constructing_function d =
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift3
constructing_function
(parse_uncapitalized_entity
>>= fun name ->
if name = "_" then fail "Parsing error: wildcard not expected." else return name)
(many parse_uncapitalized_entity)
(remove_spaces *> string "=" *> parse_content)
;;
let parse_declaration d =
fix
@@ fun _ ->
remove_spaces
*> string "let"
*> take_while1 space_predicate
*> option "" (string "rec" <* take_while1 space_predicate)
>>= function
| "rec" -> declaration_helper erecursivedeclaration d
| _ -> declaration_helper edeclaration d
;;
let parse_let_in d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; self
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> (string "let"
*> take_while1 space_predicate
*> option "" (string "rec" <* take_while1 space_predicate)
>>= fun parsed_rec ->
lift2
eletin
(let separator = remove_spaces *> string "and" *> take_while1 space_predicate in
match parsed_rec with
| "rec" -> sep_by1 separator @@ declaration_helper erecursivedeclaration d
| _ -> sep_by1 separator @@ declaration_helper edeclaration d)
(remove_spaces *> string "in" *> parse_content))
;;
let parse_conditional d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; self
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> string "if"
*> lift3
eif
parse_content
(remove_spaces *> string "then" *> parse_content)
(remove_spaces *> string "else" *> parse_content)
;;
let parse_matching d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content_left =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
let parse_content_right =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; self
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> string "match"
*> lift2
ematchwith
parse_content_right
(let parse_case =
lift2
(fun case action -> case, action)
(parse_effect_pattern
(d.parse_effect_arg d <|> parse_effect_noarg <|> parse_identifier)
<|> parse_content_left)
(remove_spaces
*> string "->"
*> (d.parse_continue d <|> parse_content_right))
and separator = remove_spaces *> string "|" in
remove_spaces
*> string "with"
*> remove_spaces
*> (string "|" <|> remove_spaces)
*> sep_by1 separator parse_case)
;;
let parse_binary_operation d =
fix
@@ fun self ->
remove_spaces
*>
let multiplicative = remove_spaces *> choice [ char '*' >>| bmul; char '/' >>| bdiv ]
and additive = remove_spaces *> choice [ char '+' >>| badd; char '-' >>| bsub ]
and relational =
remove_spaces
*> choice
[ string ">=" >>| bgte
; string "<=" >>| blte
; char '>' >>| bgt
; char '<' >>| blt
]
and equality =
remove_spaces *> choice [ string "=" >>| beq; string "!=" <|> string "<>" >>| bneq ]
and logical_and = remove_spaces *> (string "&&" >>| band)
and logical_or = remove_spaces *> (string "||" >>| bor) in
let chainl1 expression_parser operation_parser =
let rec go acc =
lift2
(fun binary_operator right_operand ->
ebinary_operation binary_operator acc right_operand)
operation_parser
expression_parser
>>= go
<|> return acc
in
expression_parser >>= fun init -> go init
in
let ( <||> ) = chainl1 in
let parse_content =
choice
[ parens self
; d.parse_list_constructing d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parse_content
<||> multiplicative
<||> additive
<||> relational
<||> equality
<||> logical_and
<||> logical_or
>>= fun result ->
match result with
| EBinaryOperation (_, _, _) -> return result
| _ -> fail "Parsing error: not binary operation."
;;
let parse_application d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let function_parser =
choice
[ parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parse_identifier
]
and operand_parser =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens self
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens @@ d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
let apply_lift acc = lift (eapplication acc) operand_parser in
let rec go acc = apply_lift acc >>= go <|> return acc in
function_parser >>= fun init -> apply_lift init >>= fun init -> go init)
;;
let parse_data_constructor d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens self
; parse_literal
; parse_identifier
]
in
parens self
<|> (lift2
(fun constructor_name expression_list -> constructor_name, expression_list)
parse_capitalized_entity
(option None (parse_content >>| fun expression -> Some expression))
>>= function
| "Ok", None | "Error", None | "Some", None ->
fail "Parsing error: constructor expected 1 argument, but got 0."
| "None", Some _ ->
fail "Parsing error: constructor expected 0 arguments, but got 1."
| constructor_name, expression ->
if List.exists (( = ) constructor_name) data_constructors
then return @@ edata_constructor constructor_name expression
else fail "Parsing error: invalid constructor.")
;;
let parse_unary_operation d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content_minus =
let indent = many1 (satisfy space_predicate) in
choice
[ parens self <|> indent *> self
; parens @@ d.parse_perform d <|> indent *> d.parse_perform d
; parens @@ d.parse_application d <|> indent *> d.parse_application d
; parens @@ d.parse_conditional d <|> indent *> d.parse_conditional d
; parens @@ d.parse_matching d <|> indent *> d.parse_matching d
; parens @@ d.parse_let_in d <|> indent *> d.parse_let_in d
; parse_literal
; parse_identifier
; parens @@ d.parse_binary_operation d
]
and parse_content_not =
choice
[ parens @@ d.parse_binary_operation d
; parens self
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parse_literal
; parse_identifier
]
in
parens self
<|> lift2 eunary_operation (char '-' >>| uminus) parse_content_minus
<|> lift2 eunary_operation (string "not" >>| unot) parse_content_not
;;
let parse_list_constructing d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let separator = remove_spaces *> string "::" *> remove_spaces
and parse_content =
choice
[ parens @@ d.parse_tuple d
; parens self
; parens @@ d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift2 econstruct_list (parse_content <* separator) (self <|> parse_content))
;;
(* Parsing of type annotations *)
type type_dispatch =
{ parse_list_type : type_dispatch -> typ Angstrom.t
; parse_tuple_type : type_dispatch -> typ Angstrom.t
; parse_arrow : type_dispatch -> typ Angstrom.t
; parse_effect_type : type_dispatch -> typ Angstrom.t
; parse_type : type_dispatch -> typ Angstrom.t
}
let parse_ground_type =
fix
@@ fun self ->
remove_spaces
*>
let parse_int = string "int" *> return int_typ in
let parse_bool = string "bool" *> return bool_typ in
let parse_char = string "char" *> return char_typ in
let parse_string = string "string" *> return string_typ in
let parse_unit = string "unit" *> return unit_typ in
choice [ parens self; parse_int; parse_bool; parse_char; parse_string; parse_unit ]
;;
let parse_list_type td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let parse_ground_type' =
parse_ground_type
>>= fun typ ->
remove_spaces *> option "" (string "list")
>>= function
| "" -> return (tvar (-1))
| _ ->
remove_spaces *> many (string ")") *> remove_spaces *> option "" (string "list")
>>= (function
| "" -> return typ
| _ -> fail "Not a ground type.")
in
choice
[ parens @@ td.parse_arrow td <* remove_spaces <* string "list"
; parens @@ td.parse_tuple_type td <* remove_spaces <* string "list"
; parse_ground_type'
; self <* remove_spaces <* string "list"
]
>>= fun typ ->
remove_spaces *> option "" (string "*")
>>= function
| "" ->
(match typ with
| TVar -1 -> fail "Not a list."
| _ -> return (tlist typ))
| _ -> fail "Not a list.")
;;
let parse_tuple_type td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> (sep_by1
(remove_spaces *> string "*" <* remove_spaces)
(choice
[ parens @@ td.parse_arrow td
; parens self
; td.parse_list_type td
; parse_ground_type
])
>>= fun typ_list ->
remove_spaces *> option "" (string "list")
>>= function
| "" ->
if Base.List.length typ_list > 1
then return (ttuple typ_list)
else fail "Not a tuple."
| _ -> fail "Not a tuple."))
;;
let parse_arrow td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift2
(fun left right -> TArr (left, right))
(choice
[ parens self
; td.parse_list_type td
; td.parse_tuple_type td
; parse_ground_type
])
(remove_spaces *> string "->" *> remove_spaces *> td.parse_type td))
;;
let parse_effect_type td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift
teffect
(choice
[ parens @@ td.parse_arrow td
; parens @@ td.parse_tuple_type td
; td.parse_list_type td
; parse_ground_type
]
<* remove_spaces
<* string "effect"))
;;
let parse_type td =
fix
@@ fun self ->
remove_spaces
*> (choice
[ td.parse_arrow td
; td.parse_effect_type td
; td.parse_list_type td
; td.parse_tuple_type td
; parse_ground_type
]
<|> parens self)
;;
let default_td =
{ parse_list_type; parse_tuple_type; parse_arrow; parse_effect_type; parse_type }
;;
(* --------------------------- *)
let parse_effect_declaration =
remove_spaces
*> string "effect"
*> remove_spaces
*> lift2
eeffect_declaration
parse_capitalized_entity
(remove_spaces *> string ":" *> remove_spaces *> parse_type default_td)
;;
let parse_effect_arg d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let operand_parser =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens @@ d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift2 eeffect_arg parse_capitalized_entity operand_parser)
;;
let parse_perform d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift
eperform
(string "perform"
*> remove_spaces
*> (parse_effect_noarg <|> parse_effect_arg d)))
;;
let parse_continue d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let operand_parser =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens @@ d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift econtinue (string "continue" *> remove_spaces *> operand_parser))
;;
(* ------- *)
let parse_expression d =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
;;
let default =
{ parse_list_constructing
; parse_tuple
; parse_binary_operation
; parse_unary_operation
; parse_list
; parse_application
; parse_fun
; parse_conditional
; parse_matching
; parse_let_in
; parse_data_constructor
; parse_expression
; parse_effect_arg
; parse_perform
; parse_continue
}
;;
let parse_tuple = parse_tuple default
let parse_list = parse_list default
let parse_fun = parse_fun default
let parse_declaration = parse_declaration default
let parse_conditional = parse_conditional default
let parse_matching = parse_matching default
let parse_binary_operation = parse_binary_operation default
let parse_let_in = parse_let_in default
let parse_application = parse_application default
let parse_unary_operation = parse_unary_operation default
let parse_list_constructing = parse_list_constructing default
let parse_data_constructor = parse_data_constructor default
let parse_expression = parse_expression default
let parse_effect_arg = parse_effect_arg default
let parse_perform = parse_perform default
let parse_continue = parse_continue default
(* Main parsing function *)
let parse : input -> (expression list, error_message) result =
fun program ->
parse_string
~consume:All
(many (parse_effect_declaration <|> parse_declaration) <* remove_spaces)
program
;;
(* -------------------- TESTS -------------------- *)
1
let%test _ =
parse
"let rec factorial n acc = if n <= 1 then acc else factorial (n - 1) (acc * n)\n\
let main = factorial 5 1 "
= Result.ok
@@ [ ERecursiveDeclaration
( "factorial"
, [ "n"; "acc" ]
, EIf
( EBinaryOperation (LTE, EIdentifier "n", ELiteral (LInt 1))
, EIdentifier "acc"
, EApplication
( EApplication
( EIdentifier "factorial"
, EBinaryOperation (Sub, EIdentifier "n", ELiteral (LInt 1)) )
, EBinaryOperation (Mul, EIdentifier "acc", EIdentifier "n") ) ) )
; EDeclaration
( "main"
, []
, EApplication
( EApplication (EIdentifier "factorial", ELiteral (LInt 5))
, ELiteral (LInt 1) ) )
]
;;
2
let%test _ =
parse " let main = 1 :: 2 :: [] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
(ELiteral (LInt 1), EConstructList (ELiteral (LInt 2), EList [])) )
]
;;
3
let%test _ =
parse " let main = true :: (false) :: [false] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( ELiteral (LBool true)
, EConstructList (ELiteral (LBool false), EList [ ELiteral (LBool false) ])
) )
]
;;
4
let%test _ =
parse " let main = (10 + 20) :: [30; 4 * 10] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( EBinaryOperation (Add, ELiteral (LInt 10), ELiteral (LInt 20))
, EList
[ ELiteral (LInt 30)
; EBinaryOperation (Mul, ELiteral (LInt 4), ELiteral (LInt 10))
] ) )
]
;;
5
let%test _ =
parse " let main = (fun x -> 'a') :: [fun _ -> 'b'] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( EFun ([ "x" ], ELiteral (LChar 'a'))
, EList [ EFun ([ "_" ], ELiteral (LChar 'b')) ] ) )
]
;;
6
let%test _ =
parse " let main = () :: (()) :: ((())) :: (((()))) :: [] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( ELiteral LUnit
, EConstructList
( ELiteral LUnit
, EConstructList
(ELiteral LUnit, EConstructList (ELiteral LUnit, EList [])) ) ) )
]
;;
7
let%test _ =
parse " let main = [\"apple\";\n\"orange\";\n\"banana\";\n\"pear\"] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ ELiteral (LString "apple")
; ELiteral (LString "orange")
; ELiteral (LString "banana")
; ELiteral (LString "pear")
] )
]
;;
8
let%test _ =
parse " let main = [ 'h' ; 'e' ; 'l' ; 'l' ; 'o' ] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ ELiteral (LChar 'h')
; ELiteral (LChar 'e')
; ELiteral (LChar 'l')
; ELiteral (LChar 'l')
; ELiteral (LChar 'o')
] )
]
;;
9
let%test _ =
parse " let main = [1] "
= Result.ok @@ [ EDeclaration ("main", [], EList [ ELiteral (LInt 1) ]) ]
;;
10
let%test _ =
parse " let main = [] " = Result.ok @@ [ EDeclaration ("main", [], EList []) ]
;;
11
let%test _ =
parse
" let main = [let x = 5 and y = 7 in x + y; (fun t -> t - 1) 10; if (5 >= 1) then 1 \
else 0] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ ELetIn
( [ EDeclaration ("x", [], ELiteral (LInt 5))
; EDeclaration ("y", [], ELiteral (LInt 7))
]
, EBinaryOperation (Add, EIdentifier "x", EIdentifier "y") )
; EApplication
( EFun
( [ "t" ]
, EBinaryOperation (Sub, EIdentifier "t", ELiteral (LInt 1)) )
, ELiteral (LInt 10) )
; EIf
( EBinaryOperation (GTE, ELiteral (LInt 5), ELiteral (LInt 1))
, ELiteral (LInt 1)
, ELiteral (LInt 0) )
] )
]
;;
12
let%test _ =
parse
" let main = (if x > 0 then 1 else (if x = 0 then 0 else -1)) :: [0 ; (if y > 0 then \
1 else (if y = 0 then 0 else -1)) ; 0] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( EIf
( EBinaryOperation (GT, EIdentifier "x", ELiteral (LInt 0))
, ELiteral (LInt 1)
, EIf
( EBinaryOperation (Eq, EIdentifier "x", ELiteral (LInt 0))
, ELiteral (LInt 0)
, EUnaryOperation (Minus, ELiteral (LInt 1)) ) )
, EList
[ ELiteral (LInt 0)
; EIf
( EBinaryOperation (GT, EIdentifier "y", ELiteral (LInt 0))
, ELiteral (LInt 1)
, EIf
( EBinaryOperation (Eq, EIdentifier "y", ELiteral (LInt 0))
, ELiteral (LInt 0)
, EUnaryOperation (Minus, ELiteral (LInt 1)) ) )
; ELiteral (LInt 0)
] ) )
]
;;
13
let%test _ =
parse " let main = fun x y z -> x + y * z "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EFun
( [ "x"; "y"; "z" ]
, EBinaryOperation
( Add
, EIdentifier "x"
, EBinaryOperation (Mul, EIdentifier "y", EIdentifier "z") ) ) )
]
;;
14
let%test _ =
parse " let main = fun _ -> 42 "
= Result.ok @@ [ EDeclaration ("main", [], EFun ([ "_" ], ELiteral (LInt 42))) ]
;;
15
let%test _ =
parse " let main = fun _ -> fun _ -> \"Hello\" "
= Result.ok
@@ [ EDeclaration
("main", [], EFun ([ "_" ], EFun ([ "_" ], ELiteral (LString "Hello"))))
]
;;
16
let%test _ =
parse " let main = fun x y -> if x < 0 then [x;y] else [0;y] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EFun
( [ "x"; "y" ]
, EIf
( EBinaryOperation (LT, EIdentifier "x", ELiteral (LInt 0))
, EList [ EIdentifier "x"; EIdentifier "y" ]
, EList [ ELiteral (LInt 0); EIdentifier "y" ] ) ) )
]
;;
17
let%test _ =
parse
" let rec matrix_mult_number matrix number =\n\
\ let rec line_mult_number line =\n\
\ match line with\n\
\ | head :: tail -> (head * number) :: line_mult_number tail\n\
\ | _ -> []\n\
\ in\n\
\ match matrix with\n\
\ | head :: tail -> line_mult_number head :: matrix_mult_number tail number\n\
\ | _ -> []"
= Result.ok
@@ [ ERecursiveDeclaration
( "matrix_mult_number"
, [ "matrix"; "number" ]
, ELetIn
( [ ERecursiveDeclaration
( "line_mult_number"
, [ "line" ]
, EMatchWith
( EIdentifier "line"
, [ ( EConstructList (EIdentifier "head", EIdentifier "tail")
, EConstructList
( EBinaryOperation
(Mul, EIdentifier "head", EIdentifier "number")
, EApplication
(EIdentifier "line_mult_number", EIdentifier "tail")
) )
; EIdentifier "_", EList []
] ) )
]
, EMatchWith
( EIdentifier "matrix"
, [ ( EConstructList (EIdentifier "head", EIdentifier "tail")
, EConstructList
( EApplication
(EIdentifier "line_mult_number", EIdentifier "head")
, EApplication
( EApplication
(EIdentifier "matrix_mult_number", EIdentifier "tail")
, EIdentifier "number" ) ) )
; EIdentifier "_", EList []
] ) ) )
]
;;
18
let%test _ =
parse " let main = \"Danya\", \"Ilya\" "
= Result.ok
@@ [ EDeclaration
("main", [], ETuple [ ELiteral (LString "Danya"); ELiteral (LString "Ilya") ])
]
;;
19
let%test _ =
parse " let main = ( 123\t, \"aaa\"\t, 'b'\n, true\t, ()\t ) "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, ETuple
[ ELiteral (LInt 123)
; ELiteral (LString "aaa")
; ELiteral (LChar 'b')
; ELiteral (LBool true)
; ELiteral LUnit
] )
]
;;
20
let%test _ =
parse " let main = (fun _ -> 1, fun _ -> 2) "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EFun
([ "_" ], ETuple [ ELiteral (LInt 1); EFun ([ "_" ], ELiteral (LInt 2)) ])
)
]
;;
21
let%test _ =
parse " let main = [fun _ -> 1; fun _ -> 2] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ EFun ([ "_" ], ELiteral (LInt 1)); EFun ([ "_" ], ELiteral (LInt 2)) ] )
]
;;
22
let%test _ =
parse " let main = f (g 5, h ()) (let x = 17 and y = 6 and z = 3 in x * y / z) "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EApplication
( EApplication
( EIdentifier "f"
, ETuple
[ EApplication (EIdentifier "g", ELiteral (LInt 5))
; EApplication (EIdentifier "h", ELiteral LUnit)
] )
, ELetIn
( [ EDeclaration ("x", [], ELiteral (LInt 17))
; EDeclaration ("y", [], ELiteral (LInt 6))
; EDeclaration ("z", [], ELiteral (LInt 3))
]
, EBinaryOperation
( Div
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, EIdentifier "z" ) ) ) )
]
;;
23
let%test _ =
parse
" let main = func (if x > 0 && y < 0 then x * y else 0) (let f t = t * t * t in (f \
x) * (f x)) () "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EApplication
( EApplication
( EApplication
( EIdentifier "func"
, EIf
( EBinaryOperation
( AND
, EBinaryOperation (GT, EIdentifier "x", ELiteral (LInt 0))
, EBinaryOperation (LT, EIdentifier "y", ELiteral (LInt 0))
)
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, ELiteral (LInt 0) ) )
, ELetIn
( [ EDeclaration
( "f"
, [ "t" ]
, EBinaryOperation
( Mul
, EBinaryOperation (Mul, EIdentifier "t", EIdentifier "t")
, EIdentifier "t" ) )
]
, EBinaryOperation
( Mul
, EApplication (EIdentifier "f", EIdentifier "x")
, EApplication (EIdentifier "f", EIdentifier "x") ) ) )
, ELiteral LUnit ) )
]
;;
24
let%test _ =
parse
" let main = if x * y / (z * z) > 15 || (f t) <= 0 || (fun x -> x * x) r >= 100 then \
x - y - z * r else -1 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EIf
( EBinaryOperation
( OR
, EBinaryOperation
( OR
, EBinaryOperation
( GT
, EBinaryOperation
( Div
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, EBinaryOperation (Mul, EIdentifier "z", EIdentifier "z")
)
, ELiteral (LInt 15) )
, EBinaryOperation
( LTE
, EApplication (EIdentifier "f", EIdentifier "t")
, ELiteral (LInt 0) ) )
, EBinaryOperation
( GTE
, EApplication
( EFun
( [ "x" ]
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "x")
)
, EIdentifier "r" )
, ELiteral (LInt 100) ) )
, EBinaryOperation
( Sub
, EBinaryOperation (Sub, EIdentifier "x", EIdentifier "y")
, EBinaryOperation (Mul, EIdentifier "z", EIdentifier "r") )
, EUnaryOperation (Minus, ELiteral (LInt 1)) ) )
]
;;
25
let%test _ =
parse " let main = if not(x = 5) && y = 5 then f x else f y "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EIf
( EBinaryOperation
( AND
, EUnaryOperation
(Not, EBinaryOperation (Eq, EIdentifier "x", ELiteral (LInt 5)))
, EBinaryOperation (Eq, EIdentifier "y", ELiteral (LInt 5)) )
, EApplication (EIdentifier "f", EIdentifier "x")
, EApplication (EIdentifier "f", EIdentifier "y") ) )
]
;;
26
let%test _ =
parse " let main = match res with \n | Some x -> x\n | None -> 0 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EMatchWith
( EIdentifier "res"
, [ EDataConstructor ("Some", Some (EIdentifier "x")), EIdentifier "x"
; EDataConstructor ("None", None), ELiteral (LInt 0)
] ) )
]
;;
27
let%test _ =
parse " let main = match f x y with \n | Ok _ -> 1\n | _ -> 0 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EMatchWith
( EApplication
(EApplication (EIdentifier "f", EIdentifier "x"), EIdentifier "y")
, [ EDataConstructor ("Ok", Some (EIdentifier "_")), ELiteral (LInt 1)
; EIdentifier "_", ELiteral (LInt 0)
] ) )
]
;;
28
let%test _ =
parse " let head = fun list -> match list with \n | h :: _ -> Some h\n | _ -> None "
= Result.ok
@@ [ EDeclaration
( "head"
, []
, EFun
( [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ ( EConstructList (EIdentifier "h", EIdentifier "_")
, EDataConstructor ("Some", Some (EIdentifier "h")) )
; EIdentifier "_", EDataConstructor ("None", None)
] ) ) )
]
;;
29
let%test _ =
parse " let tail = fun list -> match list with \n | _ :: t -> Some t\n | _ -> None "
= Result.ok
@@ [ EDeclaration
( "tail"
, []
, EFun
( [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ ( EConstructList (EIdentifier "_", EIdentifier "t")
, EDataConstructor ("Some", Some (EIdentifier "t")) )
; EIdentifier "_", EDataConstructor ("None", None)
] ) ) )
]
;;
30
let%test _ =
parse " let rec length list = match list with \n | _ :: t -> 1 + length t\n | _ -> 0 "
= Result.ok
@@ [ ERecursiveDeclaration
( "length"
, [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ ( EConstructList (EIdentifier "_", EIdentifier "t")
, EBinaryOperation
( Add
, ELiteral (LInt 1)
, EApplication (EIdentifier "length", EIdentifier "t") ) )
; EIdentifier "_", ELiteral (LInt 0)
] ) )
]
;;
31
let%test _ =
parse
" let phi n = let rec helper last1 last2 n = if n > 0 then helper last2 (last1 + \
last2) (n - 1) else last2 in\n\
\ helper 1 1 (n - 2) "
= Result.ok
@@ [ EDeclaration
( "phi"
, [ "n" ]
, ELetIn
( [ ERecursiveDeclaration
( "helper"
, [ "last1"; "last2"; "n" ]
, EIf
( EBinaryOperation (GT, EIdentifier "n", ELiteral (LInt 0))
, EApplication
( EApplication
( EApplication (EIdentifier "helper", EIdentifier "last2")
, EBinaryOperation
(Add, EIdentifier "last1", EIdentifier "last2") )
, EBinaryOperation (Sub, EIdentifier "n", ELiteral (LInt 1))
)
, EIdentifier "last2" ) )
]
, EApplication
( EApplication
( EApplication (EIdentifier "helper", ELiteral (LInt 1))
, ELiteral (LInt 1) )
, EBinaryOperation (Sub, EIdentifier "n", ELiteral (LInt 2)) ) ) )
]
;;
32
let%test _ =
parse " let main = let sq x = x * x in sq x + sq y + sq z "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, ELetIn
( [ EDeclaration
( "sq"
, [ "x" ]
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "x") )
]
, EBinaryOperation
( Add
, EBinaryOperation
( Add
, EApplication (EIdentifier "sq", EIdentifier "x")
, EApplication (EIdentifier "sq", EIdentifier "y") )
, EApplication (EIdentifier "sq", EIdentifier "z") ) ) )
]
;;
33
let%test _ =
parse " let mult x y z = x * y * z \n let main = mult 5 6 7 "
= Result.ok
@@ [ EDeclaration
( "mult"
, [ "x"; "y"; "z" ]
, EBinaryOperation
( Mul
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, EIdentifier "z" ) )
; EDeclaration
( "main"
, []
, EApplication
( EApplication
( EApplication (EIdentifier "mult", ELiteral (LInt 5))
, ELiteral (LInt 6) )
, ELiteral (LInt 7) ) )
]
;;
34
let%test _ =
parse
" let main = match x, y, z with\n | Error x, Error y, Error z -> 0\n | _, _, _ -> 1 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EMatchWith
( ETuple [ EIdentifier "x"; EIdentifier "y"; EIdentifier "z" ]
, [ ( ETuple
[ EDataConstructor ("Error", Some (EIdentifier "x"))
; EDataConstructor ("Error", Some (EIdentifier "y"))
; EDataConstructor ("Error", Some (EIdentifier "z"))
]
, ELiteral (LInt 0) )
; ( ETuple [ EIdentifier "_"; EIdentifier "_"; EIdentifier "_" ]
, ELiteral (LInt 1) )
] ) )
]
;;
35
let%test _ =
parse
" let f x y z = match x, y, z with\n\
\ | true, true, false -> true\n\
\ | true, false, true -> true\n\
\ | false, true, true -> true\n\
\ | _ -> false"
= Result.ok
@@ [ EDeclaration
( "f"
, [ "x"; "y"; "z" ]
, EMatchWith
( ETuple [ EIdentifier "x"; EIdentifier "y"; EIdentifier "z" ]
, [ ( ETuple
[ ELiteral (LBool true)
; ELiteral (LBool true)
; ELiteral (LBool false)
]
, ELiteral (LBool true) )
; ( ETuple
[ ELiteral (LBool true)
; ELiteral (LBool false)
; ELiteral (LBool true)
]
, ELiteral (LBool true) )
; ( ETuple
[ ELiteral (LBool false)
; ELiteral (LBool true)
; ELiteral (LBool true)
]
, ELiteral (LBool true) )
; EIdentifier "_", ELiteral (LBool false)
] ) )
]
;;
36
let%test _ =
parse "effect EmptyListEffect: int list effect"
= Result.ok @@ [ EEffectDeclaration ("EmptyListEffect", TEffect (TList (TGround Int))) ]
;;
37
let%test _ =
parse "effect SmallDiscount : int -> int effect"
= Result.ok
@@ [ EEffectDeclaration ("SmallDiscount", TArr (TGround Int, TEffect (TGround Int))) ]
;;
38
let%test _ =
parse
"effect E: int -> int effect\n\n\
\ let helper x = match perform (E x) with\n\n\
\ | effect (E s) -> continue (s*s)\n\n\
\ | l -> l\n\n\
\ let main = match perform (E 5) with\n\n\
\ | effect (E s) -> continue (s*s)\n\n\
\ | l -> helper l"
= Result.ok
@@ [ EEffectDeclaration ("E", TArr (TGround Int, TEffect (TGround Int)))
; EDeclaration
( "helper"
, [ "x" ]
, EMatchWith
( EPerform (EEffectArg ("E", EIdentifier "x"))
, [ ( EEffectPattern (EEffectArg ("E", EIdentifier "s"))
, EContinue (EBinaryOperation (Mul, EIdentifier "s", EIdentifier "s"))
)
; EIdentifier "l", EIdentifier "l"
] ) )
; EDeclaration
( "main"
, []
, EMatchWith
( EPerform (EEffectArg ("E", ELiteral (LInt 5)))
, [ ( EEffectPattern (EEffectArg ("E", EIdentifier "s"))
, EContinue (EBinaryOperation (Mul, EIdentifier "s", EIdentifier "s"))
)
; EIdentifier "l", EApplication (EIdentifier "helper", EIdentifier "l")
] ) )
]
;;
39
let%test _ =
parse
"effect EmptyListException : int effect\n\n\
\ let list_hd list = match list with \n\n\
\ | [] -> perform EmptyListException\n\n\
\ | hd :: _ -> hd\n\n\
\ let safe_list_hd l = match list_hd l with\n\n\
\ | effect EmptyListException -> 0, false\n\n\
\ | res -> res, true\n\
\ \n\
\ let main = safe_list_hd []"
= Result.ok
@@ [ EEffectDeclaration ("EmptyListException", TEffect (TGround Int))
; EDeclaration
( "list_hd"
, [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ EList [], EPerform (EEffectNoArg "EmptyListException")
; EConstructList (EIdentifier "hd", EIdentifier "_"), EIdentifier "hd"
] ) )
; EDeclaration
( "safe_list_hd"
, [ "l" ]
, EMatchWith
( EApplication (EIdentifier "list_hd", EIdentifier "l")
, [ ( EEffectPattern (EEffectNoArg "EmptyListException")
, ETuple [ ELiteral (LInt 0); ELiteral (LBool false) ] )
; EIdentifier "res", ETuple [ EIdentifier "res"; ELiteral (LBool true) ]
] ) )
; EDeclaration ("main", [], EApplication (EIdentifier "safe_list_hd", EList []))
]
;;
40
let%test _ =
parse
"effect SmallDiscount : int -> int effect\n\n\
\ effect BigDiscount : int -> int effect\n\n\
\ let count_discount value = if value < 10000 then perform (SmallDiscount value) \
else perform (BigDiscount value)\n\n\
\ let main = match count_discount 8500 with\n\n\
\ | effect (SmallDiscount v) -> continue (v - v / 10)\n\n\
\ | effect (BigDiscount v) -> continue (v - v / 5)\n\n\
\ | v -> v"
= Result.ok
@@ [ EEffectDeclaration ("SmallDiscount", TArr (TGround Int, TEffect (TGround Int)))
; EEffectDeclaration ("BigDiscount", TArr (TGround Int, TEffect (TGround Int)))
; EDeclaration
( "count_discount"
, [ "value" ]
, EIf
( EBinaryOperation (LT, EIdentifier "value", ELiteral (LInt 10000))
, EPerform (EEffectArg ("SmallDiscount", EIdentifier "value"))
, EPerform (EEffectArg ("BigDiscount", EIdentifier "value")) ) )
; EDeclaration
( "main"
, []
, EMatchWith
( EApplication (EIdentifier "count_discount", ELiteral (LInt 8500))
, [ ( EEffectPattern (EEffectArg ("SmallDiscount", EIdentifier "v"))
, EContinue
(EBinaryOperation
( Sub
, EIdentifier "v"
, EBinaryOperation (Div, EIdentifier "v", ELiteral (LInt 10)) ))
)
; ( EEffectPattern (EEffectArg ("BigDiscount", EIdentifier "v"))
, EContinue
(EBinaryOperation
( Sub
, EIdentifier "v"
, EBinaryOperation (Div, EIdentifier "v", ELiteral (LInt 5)) ))
)
; EIdentifier "v", EIdentifier "v"
] ) )
]
;;
| null | https://raw.githubusercontent.com/Kakadu/fp2022/7f9035ae2d6fb779e2cb075ab1a0c76883f30b00/OCamlWithEffects/lib/parser.ml | ocaml | Smart constructors for expressions
----------------------------------
Smart constructors for binary operators
---------------------------------------
Smart constructors for unary operators
--------------------------------------
Helpers
-------
Parsing of type annotations
---------------------------
-------
Main parsing function
-------------------- TESTS -------------------- | * Copyright 2021 - 2022 , Danila Pechenev &
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Angstrom
open Ast
open List
open String
open Typing
type error_message = string
type input = string
type dispatch =
{ parse_list_constructing : dispatch -> expression Angstrom.t
; parse_tuple : dispatch -> expression Angstrom.t
; parse_binary_operation : dispatch -> expression Angstrom.t
; parse_unary_operation : dispatch -> expression Angstrom.t
; parse_list : dispatch -> expression Angstrom.t
; parse_application : dispatch -> expression Angstrom.t
; parse_fun : dispatch -> expression Angstrom.t
; parse_conditional : dispatch -> expression Angstrom.t
; parse_matching : dispatch -> expression Angstrom.t
; parse_let_in : dispatch -> expression Angstrom.t
; parse_data_constructor : dispatch -> expression Angstrom.t
; parse_expression : dispatch -> expression Angstrom.t
; parse_effect_arg : dispatch -> expression Angstrom.t
; parse_perform : dispatch -> expression Angstrom.t
; parse_continue : dispatch -> expression Angstrom.t
}
let eliteral x = ELiteral x
let eidentifier x = EIdentifier x
let etuple head tail = ETuple (head :: tail)
let elist x = EList x
let efun variable_list expression = EFun (variable_list, expression)
let ebinary_operation operator left_operand right_operand =
EBinaryOperation (operator, left_operand, right_operand)
;;
let edeclaration function_name variable_list expression =
EDeclaration (function_name, variable_list, expression)
;;
let erecursivedeclaration function_name variable_list expression =
ERecursiveDeclaration (function_name, variable_list, expression)
;;
let eif condition true_branch false_branch = EIf (condition, true_branch, false_branch)
let ematchwith expression cases = EMatchWith (expression, cases)
let eletin declaration_list body = ELetIn (declaration_list, body)
let eapplication function_expression operand_expression =
EApplication (function_expression, operand_expression)
;;
let edata_constructor constructor_name expression =
EDataConstructor (constructor_name, expression)
;;
let eunary_operation operation expression = EUnaryOperation (operation, expression)
let econstruct_list head tail = EConstructList (head, tail)
let eeffect_declaration effect_name effect_type =
EEffectDeclaration (effect_name, effect_type)
;;
let eeffect_noarg effect_name = EEffectNoArg effect_name
let eeffect_arg effect_name expression = EEffectArg (effect_name, expression)
let eperform expression = EPerform expression
let econtinue expression = EContinue expression
let eeffect_pattern expression = EEffectPattern expression
let badd _ = Add
let bsub _ = Sub
let bmul _ = Mul
let bdiv _ = Div
let beq _ = Eq
let bneq _ = NEq
let bgt _ = GT
let bgte _ = GTE
let blt _ = LT
let blte _ = LTE
let band _ = AND
let bor _ = OR
let uminus _ = Minus
let unot _ = Not
let space_predicate x = x == ' ' || x == '\n' || x == '\t' || x == '\r'
let remove_spaces = take_while space_predicate
let parens parser = remove_spaces *> char '(' *> parser <* remove_spaces <* char ')'
let parse_entity =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> take_while1 (fun x ->
contains "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'_" x)
)
;;
let parse_uncapitalized_entity =
parse_entity
>>= fun entity ->
if String.contains "abcdefghijklmnopqrstuvwxyz_" entity.[0]
then return entity
else fail "Parsing error: not an uncapitalized entity."
;;
let parse_capitalized_entity =
parse_entity
>>= fun entity ->
if String.contains "ABCDEFGHIJKLMNOPQRSTUVWXYZ" entity.[0]
then return entity
else fail "Parsing error: not a capitalized entity."
;;
let data_constructors = [ "Ok"; "Error"; "Some"; "None" ]
let keywords =
[ "let"
; "rec"
; "match"
; "with"
; "if"
; "then"
; "else"
; "in"
; "fun"
; "and"
; "effect"
; "type"
; "perform"
; "continue"
]
;;
Parsers
let parse_literal =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let is_digit = function
| '0' .. '9' -> true
| _ -> false
in
let parse_int_literal = take_while1 is_digit >>| int_of_string >>| fun x -> LInt x in
let parse_string_literal =
char '"' *> take_while (( != ) '"') <* char '"' >>| fun x -> LString x
in
let parse_char_literal = char '\'' *> any_char <* char '\'' >>| fun x -> LChar x in
let parse_bool_literal =
string "true" <|> string "false" >>| bool_of_string >>| fun x -> LBool x
in
let parse_unit_literal = string "()" >>| fun _ -> LUnit in
let parse_literal =
choice
[ parse_int_literal
; parse_string_literal
; parse_char_literal
; parse_bool_literal
; parse_unit_literal
]
in
lift eliteral parse_literal)
;;
let parse_identifier =
fix
@@ fun _ ->
remove_spaces
*>
let parse_identifier =
parse_uncapitalized_entity
>>= fun entity ->
if List.exists (( = ) entity) keywords
then fail "Parsing error: keyword used."
else return @@ eidentifier entity
in
parse_identifier
;;
let parse_effect_noarg = lift eeffect_noarg parse_capitalized_entity
let parse_effect_pattern effect_parser =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift eeffect_pattern (string "effect" *> remove_spaces *> effect_parser))
;;
let parse_tuple d =
fix
@@ fun self ->
remove_spaces
*> ((let parse_content =
choice
[ parens self
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
and separator = remove_spaces *> char ',' *> remove_spaces in
lift2
etuple
(parse_content <* separator)
(sep_by1 separator parse_content <* remove_spaces))
<|> parens self)
;;
let parse_list d =
fix
@@ fun self ->
remove_spaces
*>
let brackets parser = char '[' *> parser <* char ']'
and separator = remove_spaces *> char ';' *> remove_spaces <|> remove_spaces
and parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; self
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> lift elist @@ brackets @@ (remove_spaces *> many (parse_content <* separator))
;;
let parse_fun d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; self
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> string "fun"
*> lift2
efun
(many1 parse_uncapitalized_entity
<* remove_spaces
<* string "->"
<* remove_spaces)
(parse_content <* remove_spaces)
;;
Used in parse_declaration and
let declaration_helper constructing_function d =
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift3
constructing_function
(parse_uncapitalized_entity
>>= fun name ->
if name = "_" then fail "Parsing error: wildcard not expected." else return name)
(many parse_uncapitalized_entity)
(remove_spaces *> string "=" *> parse_content)
;;
let parse_declaration d =
fix
@@ fun _ ->
remove_spaces
*> string "let"
*> take_while1 space_predicate
*> option "" (string "rec" <* take_while1 space_predicate)
>>= function
| "rec" -> declaration_helper erecursivedeclaration d
| _ -> declaration_helper edeclaration d
;;
let parse_let_in d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; self
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> (string "let"
*> take_while1 space_predicate
*> option "" (string "rec" <* take_while1 space_predicate)
>>= fun parsed_rec ->
lift2
eletin
(let separator = remove_spaces *> string "and" *> take_while1 space_predicate in
match parsed_rec with
| "rec" -> sep_by1 separator @@ declaration_helper erecursivedeclaration d
| _ -> sep_by1 separator @@ declaration_helper edeclaration d)
(remove_spaces *> string "in" *> parse_content))
;;
let parse_conditional d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; self
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> string "if"
*> lift3
eif
parse_content
(remove_spaces *> string "then" *> parse_content)
(remove_spaces *> string "else" *> parse_content)
;;
let parse_matching d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content_left =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
let parse_content_right =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; self
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parens self
<|> string "match"
*> lift2
ematchwith
parse_content_right
(let parse_case =
lift2
(fun case action -> case, action)
(parse_effect_pattern
(d.parse_effect_arg d <|> parse_effect_noarg <|> parse_identifier)
<|> parse_content_left)
(remove_spaces
*> string "->"
*> (d.parse_continue d <|> parse_content_right))
and separator = remove_spaces *> string "|" in
remove_spaces
*> string "with"
*> remove_spaces
*> (string "|" <|> remove_spaces)
*> sep_by1 separator parse_case)
;;
let parse_binary_operation d =
fix
@@ fun self ->
remove_spaces
*>
let multiplicative = remove_spaces *> choice [ char '*' >>| bmul; char '/' >>| bdiv ]
and additive = remove_spaces *> choice [ char '+' >>| badd; char '-' >>| bsub ]
and relational =
remove_spaces
*> choice
[ string ">=" >>| bgte
; string "<=" >>| blte
; char '>' >>| bgt
; char '<' >>| blt
]
and equality =
remove_spaces *> choice [ string "=" >>| beq; string "!=" <|> string "<>" >>| bneq ]
and logical_and = remove_spaces *> (string "&&" >>| band)
and logical_or = remove_spaces *> (string "||" >>| bor) in
let chainl1 expression_parser operation_parser =
let rec go acc =
lift2
(fun binary_operator right_operand ->
ebinary_operation binary_operator acc right_operand)
operation_parser
expression_parser
>>= go
<|> return acc
in
expression_parser >>= fun init -> go init
in
let ( <||> ) = chainl1 in
let parse_content =
choice
[ parens self
; d.parse_list_constructing d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
parse_content
<||> multiplicative
<||> additive
<||> relational
<||> equality
<||> logical_and
<||> logical_or
>>= fun result ->
match result with
| EBinaryOperation (_, _, _) -> return result
| _ -> fail "Parsing error: not binary operation."
;;
let parse_application d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let function_parser =
choice
[ parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parse_identifier
]
and operand_parser =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens self
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens @@ d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
let apply_lift acc = lift (eapplication acc) operand_parser in
let rec go acc = apply_lift acc >>= go <|> return acc in
function_parser >>= fun init -> apply_lift init >>= fun init -> go init)
;;
let parse_data_constructor d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens self
; parse_literal
; parse_identifier
]
in
parens self
<|> (lift2
(fun constructor_name expression_list -> constructor_name, expression_list)
parse_capitalized_entity
(option None (parse_content >>| fun expression -> Some expression))
>>= function
| "Ok", None | "Error", None | "Some", None ->
fail "Parsing error: constructor expected 1 argument, but got 0."
| "None", Some _ ->
fail "Parsing error: constructor expected 0 arguments, but got 1."
| constructor_name, expression ->
if List.exists (( = ) constructor_name) data_constructors
then return @@ edata_constructor constructor_name expression
else fail "Parsing error: invalid constructor.")
;;
let parse_unary_operation d =
fix
@@ fun self ->
remove_spaces
*>
let parse_content_minus =
let indent = many1 (satisfy space_predicate) in
choice
[ parens self <|> indent *> self
; parens @@ d.parse_perform d <|> indent *> d.parse_perform d
; parens @@ d.parse_application d <|> indent *> d.parse_application d
; parens @@ d.parse_conditional d <|> indent *> d.parse_conditional d
; parens @@ d.parse_matching d <|> indent *> d.parse_matching d
; parens @@ d.parse_let_in d <|> indent *> d.parse_let_in d
; parse_literal
; parse_identifier
; parens @@ d.parse_binary_operation d
]
and parse_content_not =
choice
[ parens @@ d.parse_binary_operation d
; parens self
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parse_literal
; parse_identifier
]
in
parens self
<|> lift2 eunary_operation (char '-' >>| uminus) parse_content_minus
<|> lift2 eunary_operation (string "not" >>| unot) parse_content_not
;;
let parse_list_constructing d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let separator = remove_spaces *> string "::" *> remove_spaces
and parse_content =
choice
[ parens @@ d.parse_tuple d
; parens self
; parens @@ d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift2 econstruct_list (parse_content <* separator) (self <|> parse_content))
;;
type type_dispatch =
{ parse_list_type : type_dispatch -> typ Angstrom.t
; parse_tuple_type : type_dispatch -> typ Angstrom.t
; parse_arrow : type_dispatch -> typ Angstrom.t
; parse_effect_type : type_dispatch -> typ Angstrom.t
; parse_type : type_dispatch -> typ Angstrom.t
}
let parse_ground_type =
fix
@@ fun self ->
remove_spaces
*>
let parse_int = string "int" *> return int_typ in
let parse_bool = string "bool" *> return bool_typ in
let parse_char = string "char" *> return char_typ in
let parse_string = string "string" *> return string_typ in
let parse_unit = string "unit" *> return unit_typ in
choice [ parens self; parse_int; parse_bool; parse_char; parse_string; parse_unit ]
;;
let parse_list_type td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let parse_ground_type' =
parse_ground_type
>>= fun typ ->
remove_spaces *> option "" (string "list")
>>= function
| "" -> return (tvar (-1))
| _ ->
remove_spaces *> many (string ")") *> remove_spaces *> option "" (string "list")
>>= (function
| "" -> return typ
| _ -> fail "Not a ground type.")
in
choice
[ parens @@ td.parse_arrow td <* remove_spaces <* string "list"
; parens @@ td.parse_tuple_type td <* remove_spaces <* string "list"
; parse_ground_type'
; self <* remove_spaces <* string "list"
]
>>= fun typ ->
remove_spaces *> option "" (string "*")
>>= function
| "" ->
(match typ with
| TVar -1 -> fail "Not a list."
| _ -> return (tlist typ))
| _ -> fail "Not a list.")
;;
let parse_tuple_type td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> (sep_by1
(remove_spaces *> string "*" <* remove_spaces)
(choice
[ parens @@ td.parse_arrow td
; parens self
; td.parse_list_type td
; parse_ground_type
])
>>= fun typ_list ->
remove_spaces *> option "" (string "list")
>>= function
| "" ->
if Base.List.length typ_list > 1
then return (ttuple typ_list)
else fail "Not a tuple."
| _ -> fail "Not a tuple."))
;;
let parse_arrow td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift2
(fun left right -> TArr (left, right))
(choice
[ parens self
; td.parse_list_type td
; td.parse_tuple_type td
; parse_ground_type
])
(remove_spaces *> string "->" *> remove_spaces *> td.parse_type td))
;;
let parse_effect_type td =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift
teffect
(choice
[ parens @@ td.parse_arrow td
; parens @@ td.parse_tuple_type td
; td.parse_list_type td
; parse_ground_type
]
<* remove_spaces
<* string "effect"))
;;
let parse_type td =
fix
@@ fun self ->
remove_spaces
*> (choice
[ td.parse_arrow td
; td.parse_effect_type td
; td.parse_list_type td
; td.parse_tuple_type td
; parse_ground_type
]
<|> parens self)
;;
let default_td =
{ parse_list_type; parse_tuple_type; parse_arrow; parse_effect_type; parse_type }
;;
let parse_effect_declaration =
remove_spaces
*> string "effect"
*> remove_spaces
*> lift2
eeffect_declaration
parse_capitalized_entity
(remove_spaces *> string ":" *> remove_spaces *> parse_type default_td)
;;
let parse_effect_arg d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let operand_parser =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens @@ d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift2 eeffect_arg parse_capitalized_entity operand_parser)
;;
let parse_perform d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|> lift
eperform
(string "perform"
*> remove_spaces
*> (parse_effect_noarg <|> parse_effect_arg d)))
;;
let parse_continue d =
fix
@@ fun self ->
remove_spaces
*> (parens self
<|>
let operand_parser =
choice
[ parens @@ d.parse_tuple d
; parens @@ d.parse_list_constructing d
; parens @@ d.parse_binary_operation d
; parens @@ d.parse_unary_operation d
; d.parse_list d
; parens @@ d.parse_perform d
; parens @@ d.parse_application d
; parens @@ d.parse_fun d
; parens @@ d.parse_conditional d
; parens @@ d.parse_matching d
; parens @@ d.parse_let_in d
; parens @@ d.parse_data_constructor d
; parse_literal
; parse_identifier
]
in
lift econtinue (string "continue" *> remove_spaces *> operand_parser))
;;
let parse_expression d =
choice
[ d.parse_tuple d
; d.parse_list_constructing d
; d.parse_binary_operation d
; d.parse_unary_operation d
; d.parse_list d
; d.parse_perform d
; d.parse_application d
; d.parse_fun d
; d.parse_conditional d
; d.parse_matching d
; d.parse_let_in d
; d.parse_data_constructor d
; parse_literal
; parse_identifier
]
;;
let default =
{ parse_list_constructing
; parse_tuple
; parse_binary_operation
; parse_unary_operation
; parse_list
; parse_application
; parse_fun
; parse_conditional
; parse_matching
; parse_let_in
; parse_data_constructor
; parse_expression
; parse_effect_arg
; parse_perform
; parse_continue
}
;;
let parse_tuple = parse_tuple default
let parse_list = parse_list default
let parse_fun = parse_fun default
let parse_declaration = parse_declaration default
let parse_conditional = parse_conditional default
let parse_matching = parse_matching default
let parse_binary_operation = parse_binary_operation default
let parse_let_in = parse_let_in default
let parse_application = parse_application default
let parse_unary_operation = parse_unary_operation default
let parse_list_constructing = parse_list_constructing default
let parse_data_constructor = parse_data_constructor default
let parse_expression = parse_expression default
let parse_effect_arg = parse_effect_arg default
let parse_perform = parse_perform default
let parse_continue = parse_continue default
let parse : input -> (expression list, error_message) result =
fun program ->
parse_string
~consume:All
(many (parse_effect_declaration <|> parse_declaration) <* remove_spaces)
program
;;
1
let%test _ =
parse
"let rec factorial n acc = if n <= 1 then acc else factorial (n - 1) (acc * n)\n\
let main = factorial 5 1 "
= Result.ok
@@ [ ERecursiveDeclaration
( "factorial"
, [ "n"; "acc" ]
, EIf
( EBinaryOperation (LTE, EIdentifier "n", ELiteral (LInt 1))
, EIdentifier "acc"
, EApplication
( EApplication
( EIdentifier "factorial"
, EBinaryOperation (Sub, EIdentifier "n", ELiteral (LInt 1)) )
, EBinaryOperation (Mul, EIdentifier "acc", EIdentifier "n") ) ) )
; EDeclaration
( "main"
, []
, EApplication
( EApplication (EIdentifier "factorial", ELiteral (LInt 5))
, ELiteral (LInt 1) ) )
]
;;
2
let%test _ =
parse " let main = 1 :: 2 :: [] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
(ELiteral (LInt 1), EConstructList (ELiteral (LInt 2), EList [])) )
]
;;
3
let%test _ =
parse " let main = true :: (false) :: [false] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( ELiteral (LBool true)
, EConstructList (ELiteral (LBool false), EList [ ELiteral (LBool false) ])
) )
]
;;
4
let%test _ =
parse " let main = (10 + 20) :: [30; 4 * 10] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( EBinaryOperation (Add, ELiteral (LInt 10), ELiteral (LInt 20))
, EList
[ ELiteral (LInt 30)
; EBinaryOperation (Mul, ELiteral (LInt 4), ELiteral (LInt 10))
] ) )
]
;;
5
let%test _ =
parse " let main = (fun x -> 'a') :: [fun _ -> 'b'] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( EFun ([ "x" ], ELiteral (LChar 'a'))
, EList [ EFun ([ "_" ], ELiteral (LChar 'b')) ] ) )
]
;;
6
let%test _ =
parse " let main = () :: (()) :: ((())) :: (((()))) :: [] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( ELiteral LUnit
, EConstructList
( ELiteral LUnit
, EConstructList
(ELiteral LUnit, EConstructList (ELiteral LUnit, EList [])) ) ) )
]
;;
7
let%test _ =
parse " let main = [\"apple\";\n\"orange\";\n\"banana\";\n\"pear\"] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ ELiteral (LString "apple")
; ELiteral (LString "orange")
; ELiteral (LString "banana")
; ELiteral (LString "pear")
] )
]
;;
8
let%test _ =
parse " let main = [ 'h' ; 'e' ; 'l' ; 'l' ; 'o' ] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ ELiteral (LChar 'h')
; ELiteral (LChar 'e')
; ELiteral (LChar 'l')
; ELiteral (LChar 'l')
; ELiteral (LChar 'o')
] )
]
;;
9
let%test _ =
parse " let main = [1] "
= Result.ok @@ [ EDeclaration ("main", [], EList [ ELiteral (LInt 1) ]) ]
;;
10
let%test _ =
parse " let main = [] " = Result.ok @@ [ EDeclaration ("main", [], EList []) ]
;;
11
let%test _ =
parse
" let main = [let x = 5 and y = 7 in x + y; (fun t -> t - 1) 10; if (5 >= 1) then 1 \
else 0] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ ELetIn
( [ EDeclaration ("x", [], ELiteral (LInt 5))
; EDeclaration ("y", [], ELiteral (LInt 7))
]
, EBinaryOperation (Add, EIdentifier "x", EIdentifier "y") )
; EApplication
( EFun
( [ "t" ]
, EBinaryOperation (Sub, EIdentifier "t", ELiteral (LInt 1)) )
, ELiteral (LInt 10) )
; EIf
( EBinaryOperation (GTE, ELiteral (LInt 5), ELiteral (LInt 1))
, ELiteral (LInt 1)
, ELiteral (LInt 0) )
] )
]
;;
12
let%test _ =
parse
" let main = (if x > 0 then 1 else (if x = 0 then 0 else -1)) :: [0 ; (if y > 0 then \
1 else (if y = 0 then 0 else -1)) ; 0] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EConstructList
( EIf
( EBinaryOperation (GT, EIdentifier "x", ELiteral (LInt 0))
, ELiteral (LInt 1)
, EIf
( EBinaryOperation (Eq, EIdentifier "x", ELiteral (LInt 0))
, ELiteral (LInt 0)
, EUnaryOperation (Minus, ELiteral (LInt 1)) ) )
, EList
[ ELiteral (LInt 0)
; EIf
( EBinaryOperation (GT, EIdentifier "y", ELiteral (LInt 0))
, ELiteral (LInt 1)
, EIf
( EBinaryOperation (Eq, EIdentifier "y", ELiteral (LInt 0))
, ELiteral (LInt 0)
, EUnaryOperation (Minus, ELiteral (LInt 1)) ) )
; ELiteral (LInt 0)
] ) )
]
;;
13
let%test _ =
parse " let main = fun x y z -> x + y * z "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EFun
( [ "x"; "y"; "z" ]
, EBinaryOperation
( Add
, EIdentifier "x"
, EBinaryOperation (Mul, EIdentifier "y", EIdentifier "z") ) ) )
]
;;
14
let%test _ =
parse " let main = fun _ -> 42 "
= Result.ok @@ [ EDeclaration ("main", [], EFun ([ "_" ], ELiteral (LInt 42))) ]
;;
15
let%test _ =
parse " let main = fun _ -> fun _ -> \"Hello\" "
= Result.ok
@@ [ EDeclaration
("main", [], EFun ([ "_" ], EFun ([ "_" ], ELiteral (LString "Hello"))))
]
;;
16
let%test _ =
parse " let main = fun x y -> if x < 0 then [x;y] else [0;y] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EFun
( [ "x"; "y" ]
, EIf
( EBinaryOperation (LT, EIdentifier "x", ELiteral (LInt 0))
, EList [ EIdentifier "x"; EIdentifier "y" ]
, EList [ ELiteral (LInt 0); EIdentifier "y" ] ) ) )
]
;;
17
let%test _ =
parse
" let rec matrix_mult_number matrix number =\n\
\ let rec line_mult_number line =\n\
\ match line with\n\
\ | head :: tail -> (head * number) :: line_mult_number tail\n\
\ | _ -> []\n\
\ in\n\
\ match matrix with\n\
\ | head :: tail -> line_mult_number head :: matrix_mult_number tail number\n\
\ | _ -> []"
= Result.ok
@@ [ ERecursiveDeclaration
( "matrix_mult_number"
, [ "matrix"; "number" ]
, ELetIn
( [ ERecursiveDeclaration
( "line_mult_number"
, [ "line" ]
, EMatchWith
( EIdentifier "line"
, [ ( EConstructList (EIdentifier "head", EIdentifier "tail")
, EConstructList
( EBinaryOperation
(Mul, EIdentifier "head", EIdentifier "number")
, EApplication
(EIdentifier "line_mult_number", EIdentifier "tail")
) )
; EIdentifier "_", EList []
] ) )
]
, EMatchWith
( EIdentifier "matrix"
, [ ( EConstructList (EIdentifier "head", EIdentifier "tail")
, EConstructList
( EApplication
(EIdentifier "line_mult_number", EIdentifier "head")
, EApplication
( EApplication
(EIdentifier "matrix_mult_number", EIdentifier "tail")
, EIdentifier "number" ) ) )
; EIdentifier "_", EList []
] ) ) )
]
;;
18
let%test _ =
parse " let main = \"Danya\", \"Ilya\" "
= Result.ok
@@ [ EDeclaration
("main", [], ETuple [ ELiteral (LString "Danya"); ELiteral (LString "Ilya") ])
]
;;
19
let%test _ =
parse " let main = ( 123\t, \"aaa\"\t, 'b'\n, true\t, ()\t ) "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, ETuple
[ ELiteral (LInt 123)
; ELiteral (LString "aaa")
; ELiteral (LChar 'b')
; ELiteral (LBool true)
; ELiteral LUnit
] )
]
;;
20
let%test _ =
parse " let main = (fun _ -> 1, fun _ -> 2) "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EFun
([ "_" ], ETuple [ ELiteral (LInt 1); EFun ([ "_" ], ELiteral (LInt 2)) ])
)
]
;;
21
let%test _ =
parse " let main = [fun _ -> 1; fun _ -> 2] "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EList
[ EFun ([ "_" ], ELiteral (LInt 1)); EFun ([ "_" ], ELiteral (LInt 2)) ] )
]
;;
22
let%test _ =
parse " let main = f (g 5, h ()) (let x = 17 and y = 6 and z = 3 in x * y / z) "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EApplication
( EApplication
( EIdentifier "f"
, ETuple
[ EApplication (EIdentifier "g", ELiteral (LInt 5))
; EApplication (EIdentifier "h", ELiteral LUnit)
] )
, ELetIn
( [ EDeclaration ("x", [], ELiteral (LInt 17))
; EDeclaration ("y", [], ELiteral (LInt 6))
; EDeclaration ("z", [], ELiteral (LInt 3))
]
, EBinaryOperation
( Div
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, EIdentifier "z" ) ) ) )
]
;;
23
let%test _ =
parse
" let main = func (if x > 0 && y < 0 then x * y else 0) (let f t = t * t * t in (f \
x) * (f x)) () "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EApplication
( EApplication
( EApplication
( EIdentifier "func"
, EIf
( EBinaryOperation
( AND
, EBinaryOperation (GT, EIdentifier "x", ELiteral (LInt 0))
, EBinaryOperation (LT, EIdentifier "y", ELiteral (LInt 0))
)
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, ELiteral (LInt 0) ) )
, ELetIn
( [ EDeclaration
( "f"
, [ "t" ]
, EBinaryOperation
( Mul
, EBinaryOperation (Mul, EIdentifier "t", EIdentifier "t")
, EIdentifier "t" ) )
]
, EBinaryOperation
( Mul
, EApplication (EIdentifier "f", EIdentifier "x")
, EApplication (EIdentifier "f", EIdentifier "x") ) ) )
, ELiteral LUnit ) )
]
;;
24
let%test _ =
parse
" let main = if x * y / (z * z) > 15 || (f t) <= 0 || (fun x -> x * x) r >= 100 then \
x - y - z * r else -1 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EIf
( EBinaryOperation
( OR
, EBinaryOperation
( OR
, EBinaryOperation
( GT
, EBinaryOperation
( Div
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, EBinaryOperation (Mul, EIdentifier "z", EIdentifier "z")
)
, ELiteral (LInt 15) )
, EBinaryOperation
( LTE
, EApplication (EIdentifier "f", EIdentifier "t")
, ELiteral (LInt 0) ) )
, EBinaryOperation
( GTE
, EApplication
( EFun
( [ "x" ]
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "x")
)
, EIdentifier "r" )
, ELiteral (LInt 100) ) )
, EBinaryOperation
( Sub
, EBinaryOperation (Sub, EIdentifier "x", EIdentifier "y")
, EBinaryOperation (Mul, EIdentifier "z", EIdentifier "r") )
, EUnaryOperation (Minus, ELiteral (LInt 1)) ) )
]
;;
25
let%test _ =
parse " let main = if not(x = 5) && y = 5 then f x else f y "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EIf
( EBinaryOperation
( AND
, EUnaryOperation
(Not, EBinaryOperation (Eq, EIdentifier "x", ELiteral (LInt 5)))
, EBinaryOperation (Eq, EIdentifier "y", ELiteral (LInt 5)) )
, EApplication (EIdentifier "f", EIdentifier "x")
, EApplication (EIdentifier "f", EIdentifier "y") ) )
]
;;
26
let%test _ =
parse " let main = match res with \n | Some x -> x\n | None -> 0 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EMatchWith
( EIdentifier "res"
, [ EDataConstructor ("Some", Some (EIdentifier "x")), EIdentifier "x"
; EDataConstructor ("None", None), ELiteral (LInt 0)
] ) )
]
;;
27
let%test _ =
parse " let main = match f x y with \n | Ok _ -> 1\n | _ -> 0 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EMatchWith
( EApplication
(EApplication (EIdentifier "f", EIdentifier "x"), EIdentifier "y")
, [ EDataConstructor ("Ok", Some (EIdentifier "_")), ELiteral (LInt 1)
; EIdentifier "_", ELiteral (LInt 0)
] ) )
]
;;
28
let%test _ =
parse " let head = fun list -> match list with \n | h :: _ -> Some h\n | _ -> None "
= Result.ok
@@ [ EDeclaration
( "head"
, []
, EFun
( [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ ( EConstructList (EIdentifier "h", EIdentifier "_")
, EDataConstructor ("Some", Some (EIdentifier "h")) )
; EIdentifier "_", EDataConstructor ("None", None)
] ) ) )
]
;;
29
let%test _ =
parse " let tail = fun list -> match list with \n | _ :: t -> Some t\n | _ -> None "
= Result.ok
@@ [ EDeclaration
( "tail"
, []
, EFun
( [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ ( EConstructList (EIdentifier "_", EIdentifier "t")
, EDataConstructor ("Some", Some (EIdentifier "t")) )
; EIdentifier "_", EDataConstructor ("None", None)
] ) ) )
]
;;
30
let%test _ =
parse " let rec length list = match list with \n | _ :: t -> 1 + length t\n | _ -> 0 "
= Result.ok
@@ [ ERecursiveDeclaration
( "length"
, [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ ( EConstructList (EIdentifier "_", EIdentifier "t")
, EBinaryOperation
( Add
, ELiteral (LInt 1)
, EApplication (EIdentifier "length", EIdentifier "t") ) )
; EIdentifier "_", ELiteral (LInt 0)
] ) )
]
;;
31
let%test _ =
parse
" let phi n = let rec helper last1 last2 n = if n > 0 then helper last2 (last1 + \
last2) (n - 1) else last2 in\n\
\ helper 1 1 (n - 2) "
= Result.ok
@@ [ EDeclaration
( "phi"
, [ "n" ]
, ELetIn
( [ ERecursiveDeclaration
( "helper"
, [ "last1"; "last2"; "n" ]
, EIf
( EBinaryOperation (GT, EIdentifier "n", ELiteral (LInt 0))
, EApplication
( EApplication
( EApplication (EIdentifier "helper", EIdentifier "last2")
, EBinaryOperation
(Add, EIdentifier "last1", EIdentifier "last2") )
, EBinaryOperation (Sub, EIdentifier "n", ELiteral (LInt 1))
)
, EIdentifier "last2" ) )
]
, EApplication
( EApplication
( EApplication (EIdentifier "helper", ELiteral (LInt 1))
, ELiteral (LInt 1) )
, EBinaryOperation (Sub, EIdentifier "n", ELiteral (LInt 2)) ) ) )
]
;;
32
let%test _ =
parse " let main = let sq x = x * x in sq x + sq y + sq z "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, ELetIn
( [ EDeclaration
( "sq"
, [ "x" ]
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "x") )
]
, EBinaryOperation
( Add
, EBinaryOperation
( Add
, EApplication (EIdentifier "sq", EIdentifier "x")
, EApplication (EIdentifier "sq", EIdentifier "y") )
, EApplication (EIdentifier "sq", EIdentifier "z") ) ) )
]
;;
33
let%test _ =
parse " let mult x y z = x * y * z \n let main = mult 5 6 7 "
= Result.ok
@@ [ EDeclaration
( "mult"
, [ "x"; "y"; "z" ]
, EBinaryOperation
( Mul
, EBinaryOperation (Mul, EIdentifier "x", EIdentifier "y")
, EIdentifier "z" ) )
; EDeclaration
( "main"
, []
, EApplication
( EApplication
( EApplication (EIdentifier "mult", ELiteral (LInt 5))
, ELiteral (LInt 6) )
, ELiteral (LInt 7) ) )
]
;;
34
let%test _ =
parse
" let main = match x, y, z with\n | Error x, Error y, Error z -> 0\n | _, _, _ -> 1 "
= Result.ok
@@ [ EDeclaration
( "main"
, []
, EMatchWith
( ETuple [ EIdentifier "x"; EIdentifier "y"; EIdentifier "z" ]
, [ ( ETuple
[ EDataConstructor ("Error", Some (EIdentifier "x"))
; EDataConstructor ("Error", Some (EIdentifier "y"))
; EDataConstructor ("Error", Some (EIdentifier "z"))
]
, ELiteral (LInt 0) )
; ( ETuple [ EIdentifier "_"; EIdentifier "_"; EIdentifier "_" ]
, ELiteral (LInt 1) )
] ) )
]
;;
35
let%test _ =
parse
" let f x y z = match x, y, z with\n\
\ | true, true, false -> true\n\
\ | true, false, true -> true\n\
\ | false, true, true -> true\n\
\ | _ -> false"
= Result.ok
@@ [ EDeclaration
( "f"
, [ "x"; "y"; "z" ]
, EMatchWith
( ETuple [ EIdentifier "x"; EIdentifier "y"; EIdentifier "z" ]
, [ ( ETuple
[ ELiteral (LBool true)
; ELiteral (LBool true)
; ELiteral (LBool false)
]
, ELiteral (LBool true) )
; ( ETuple
[ ELiteral (LBool true)
; ELiteral (LBool false)
; ELiteral (LBool true)
]
, ELiteral (LBool true) )
; ( ETuple
[ ELiteral (LBool false)
; ELiteral (LBool true)
; ELiteral (LBool true)
]
, ELiteral (LBool true) )
; EIdentifier "_", ELiteral (LBool false)
] ) )
]
;;
36
let%test _ =
parse "effect EmptyListEffect: int list effect"
= Result.ok @@ [ EEffectDeclaration ("EmptyListEffect", TEffect (TList (TGround Int))) ]
;;
37
let%test _ =
parse "effect SmallDiscount : int -> int effect"
= Result.ok
@@ [ EEffectDeclaration ("SmallDiscount", TArr (TGround Int, TEffect (TGround Int))) ]
;;
38
let%test _ =
parse
"effect E: int -> int effect\n\n\
\ let helper x = match perform (E x) with\n\n\
\ | effect (E s) -> continue (s*s)\n\n\
\ | l -> l\n\n\
\ let main = match perform (E 5) with\n\n\
\ | effect (E s) -> continue (s*s)\n\n\
\ | l -> helper l"
= Result.ok
@@ [ EEffectDeclaration ("E", TArr (TGround Int, TEffect (TGround Int)))
; EDeclaration
( "helper"
, [ "x" ]
, EMatchWith
( EPerform (EEffectArg ("E", EIdentifier "x"))
, [ ( EEffectPattern (EEffectArg ("E", EIdentifier "s"))
, EContinue (EBinaryOperation (Mul, EIdentifier "s", EIdentifier "s"))
)
; EIdentifier "l", EIdentifier "l"
] ) )
; EDeclaration
( "main"
, []
, EMatchWith
( EPerform (EEffectArg ("E", ELiteral (LInt 5)))
, [ ( EEffectPattern (EEffectArg ("E", EIdentifier "s"))
, EContinue (EBinaryOperation (Mul, EIdentifier "s", EIdentifier "s"))
)
; EIdentifier "l", EApplication (EIdentifier "helper", EIdentifier "l")
] ) )
]
;;
39
let%test _ =
parse
"effect EmptyListException : int effect\n\n\
\ let list_hd list = match list with \n\n\
\ | [] -> perform EmptyListException\n\n\
\ | hd :: _ -> hd\n\n\
\ let safe_list_hd l = match list_hd l with\n\n\
\ | effect EmptyListException -> 0, false\n\n\
\ | res -> res, true\n\
\ \n\
\ let main = safe_list_hd []"
= Result.ok
@@ [ EEffectDeclaration ("EmptyListException", TEffect (TGround Int))
; EDeclaration
( "list_hd"
, [ "list" ]
, EMatchWith
( EIdentifier "list"
, [ EList [], EPerform (EEffectNoArg "EmptyListException")
; EConstructList (EIdentifier "hd", EIdentifier "_"), EIdentifier "hd"
] ) )
; EDeclaration
( "safe_list_hd"
, [ "l" ]
, EMatchWith
( EApplication (EIdentifier "list_hd", EIdentifier "l")
, [ ( EEffectPattern (EEffectNoArg "EmptyListException")
, ETuple [ ELiteral (LInt 0); ELiteral (LBool false) ] )
; EIdentifier "res", ETuple [ EIdentifier "res"; ELiteral (LBool true) ]
] ) )
; EDeclaration ("main", [], EApplication (EIdentifier "safe_list_hd", EList []))
]
;;
40
let%test _ =
parse
"effect SmallDiscount : int -> int effect\n\n\
\ effect BigDiscount : int -> int effect\n\n\
\ let count_discount value = if value < 10000 then perform (SmallDiscount value) \
else perform (BigDiscount value)\n\n\
\ let main = match count_discount 8500 with\n\n\
\ | effect (SmallDiscount v) -> continue (v - v / 10)\n\n\
\ | effect (BigDiscount v) -> continue (v - v / 5)\n\n\
\ | v -> v"
= Result.ok
@@ [ EEffectDeclaration ("SmallDiscount", TArr (TGround Int, TEffect (TGround Int)))
; EEffectDeclaration ("BigDiscount", TArr (TGround Int, TEffect (TGround Int)))
; EDeclaration
( "count_discount"
, [ "value" ]
, EIf
( EBinaryOperation (LT, EIdentifier "value", ELiteral (LInt 10000))
, EPerform (EEffectArg ("SmallDiscount", EIdentifier "value"))
, EPerform (EEffectArg ("BigDiscount", EIdentifier "value")) ) )
; EDeclaration
( "main"
, []
, EMatchWith
( EApplication (EIdentifier "count_discount", ELiteral (LInt 8500))
, [ ( EEffectPattern (EEffectArg ("SmallDiscount", EIdentifier "v"))
, EContinue
(EBinaryOperation
( Sub
, EIdentifier "v"
, EBinaryOperation (Div, EIdentifier "v", ELiteral (LInt 10)) ))
)
; ( EEffectPattern (EEffectArg ("BigDiscount", EIdentifier "v"))
, EContinue
(EBinaryOperation
( Sub
, EIdentifier "v"
, EBinaryOperation (Div, EIdentifier "v", ELiteral (LInt 5)) ))
)
; EIdentifier "v", EIdentifier "v"
] ) )
]
;;
|
a6c1088e6380bfaa2e3ebe81d7a55606613b2da5f68afb351854167b33f38d24 | adamschoenemann/clofrp | Contexts.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE NamedFieldPuns #
# LANGUAGE FunctionalDependencies #
module CloFRP.Check.Contexts
( module CloFRP.Check.Contexts
, module CloFRP.Context
, module CloFRP.Check.Destr
) where
import Data.Data
import GHC.Exts (IsList(..))
import Data.Text.Prettyprint.Doc
import qualified Data.Map.Strict as M
import Data.List (break, find)
import Data.Maybe (isJust, catMaybes, listToMaybe)
import CloFRP.Check.Destr
import CloFRP.AST hiding (exists)
import CloFRP.Context
import CloFRP.Annotated
import CloFRP.Pretty
import CloFRP.Utils (findMap)
data Binding = LamB | LetB deriving (Eq, Show)
data CtxElem a
-- | Universal
= Uni Name Kind
-- | Existential
| Exists Name Kind
-- | x :_? A
| (Binding, Name) `HasType` PolyType a
-- | a = t
| Name := MonoType a
-- | |>a
| Marker Name
deriving Eq
instance Unann (CtxElem a) (CtxElem ()) where
unann el =
case el of
Uni nm k -> Uni nm k
Exists nm k -> Exists nm k
(b,nm) `HasType` ty -> (b,nm) `HasType` unann ty
nm := ty -> nm := unann ty
Marker nm -> Marker nm
instance Pretty (CtxElem a) where
pretty = \case
Uni nm Star -> pretty nm
Uni nm k -> parens (pretty nm <+> ":" <+> pretty k)
Exists nm Star -> "^" <> pretty nm
Exists nm k -> parens ("^" <> pretty nm <+> ":" <+> pretty k)
(b, nm) `HasType` ty ->
pretty nm <+> p b <> ":" <+> pretty (unann ty)
where
p LamB = "λ"
p LetB = ""
nm := ty -> "^" <> pretty nm <+> "=" <+> pretty (unann ty)
Marker nm -> "†" <> pretty nm
instance Show (CtxElem a) where
show = show . pretty
exists :: Name -> CtxElem a
exists nm = Exists nm Star
marker :: Name -> CtxElem a
marker = Marker
uni :: Name -> CtxElem a
uni nm = Uni nm Star
(<\:) :: Name -> PolyType a -> CtxElem a
x <\: t = (LamB, x) `HasType` t
(.:) :: Name -> PolyType a -> CtxElem a
x .: t = (LetB, x) `HasType` t
-- Local contexts contains local variables and stuff
newtype LocalCtx a = LocalCtx { unLocalCtx :: [CtxElem a] }
deriving (Eq)
instance Show (LocalCtx a) where
show gamma = showW 80 (pretty gamma)
instance Pretty (LocalCtx a) where
pretty (LocalCtx xs) =
brackets $ concatWith (\x y -> x <+> softline' <> comma <> space <> y) $ map pretty (reverse xs)
-- Free contexts contains "global" mappings from names to types
newtype FreeCtx a = FreeCtx { unFreeCtx :: M.Map Name (PolyType a) }
deriving (Show, Eq, Monoid, Data)
mapFreeCtx :: (PolyType a -> PolyType b) -> FreeCtx a -> FreeCtx b
mapFreeCtx fn (FreeCtx m) = FreeCtx $ M.map fn m
instance (IsList (FreeCtx a)) where
type Item (FreeCtx a) = (Name, PolyType a)
fromList xs = FreeCtx $ M.fromList xs
toList (FreeCtx m) = M.toList m
instance Context (FreeCtx a) where
type Elem (FreeCtx a) = PolyType a
type Key (FreeCtx a) = Name
extend nm ty (FreeCtx m) = FreeCtx $ M.insert nm ty m
isMemberOf nm (FreeCtx m) = M.member nm m
query x (FreeCtx m) = M.lookup x m
delete x (FreeCtx m) = FreeCtx (M.delete x m)
-- Kind context contains "global" mappings from type-names to kinds
newtype KindCtx a = KindCtx { unKindCtx :: M.Map Name Kind }
deriving (Show, Eq, Monoid, Data)
instance Context (KindCtx a) where
type Elem (KindCtx a) = Kind
type Key (KindCtx a) = Name
extend nm ty (KindCtx m) = KindCtx $ M.insert nm ty m
isMemberOf nm (KindCtx m) = M.member nm m
query x (KindCtx m) = M.lookup x m
delete x (KindCtx m) = KindCtx (M.delete x m)
instance (IsList (KindCtx a)) where
type Item (KindCtx a) = (Name, Kind)
fromList xs = KindCtx $ M.fromList xs
toList (KindCtx m) = M.toList m
instance Pretty (KindCtx a) where
pretty (KindCtx m) = enclose "[" "]" $ cat $ punctuate ", " $ map fn $ toList m where
fn (k, v) = pretty k <+> "↦" <+> pretty v
-- context of destructors
newtype DestrCtx a = DestrCtx { unDestrCtx :: M.Map Name (Destr a) }
deriving (Show, Eq, Monoid, Data)
instance Context (DestrCtx a) where
type Elem (DestrCtx a) = Destr a
type Key (DestrCtx a) = Name
extend nm ty (DestrCtx m) = DestrCtx $ M.insert nm ty m
isMemberOf nm (DestrCtx m) = M.member nm m
query x (DestrCtx m) = M.lookup x m
delete x (DestrCtx m) = DestrCtx (M.delete x m)
instance (IsList (DestrCtx a)) where
type Item (DestrCtx a) = (Name, Destr a)
fromList xs = DestrCtx $ M.fromList xs
toList (DestrCtx m) = M.toList m
-- context of instances of type-classes
data ClassInstance a = ClassInstance
{ ciClassName :: Name
, ciInstanceTypeName :: Name
, ciParams :: [Name]
, ciDictionary :: M.Map Name (PolyType a, Expr a)
} deriving (Eq, Data, Typeable)
instance Pretty (ClassInstance a) where
pretty (ClassInstance {ciClassName, ciParams, ciDictionary, ciInstanceTypeName}) =
"Instance" <+> tupled [pretty ciClassName, pretty ciInstanceTypeName, pretty ciParams, list $ M.elems $ M.map pretty ciDictionary]
instance Show (ClassInstance a) where
show = show . pretty
newtype InstanceCtx a = InstanceCtx { unInstanceCtx :: M.Map Name [ClassInstance a] }
deriving (Show, Eq, Monoid, Data, Typeable)
instance Context (InstanceCtx a) where
type Elem (InstanceCtx a) = [ClassInstance a]
type Key (InstanceCtx a) = Name
extend nm ty (InstanceCtx m) = InstanceCtx $ M.insert nm ty m
isMemberOf nm (InstanceCtx m) = M.member nm m
query x (InstanceCtx m) = M.lookup x m
delete x (InstanceCtx m) = InstanceCtx (M.delete x m)
instance (IsList (InstanceCtx a)) where
type Item (InstanceCtx a) = (Name, [ClassInstance a])
fromList xs = InstanceCtx $ M.fromList xs
toList (InstanceCtx m) = M.toList m
instance Pretty (InstanceCtx a) where
pretty (InstanceCtx m) = enclose "[" "]" $ cat $ punctuate ", " $ map fn $ toList m where
fn (k, v) = pretty k <+> "↦" <+> pretty v
class HasInstances m a | m -> a where
getInstances :: m (InstanceCtx a)
getInstancesOf :: (Monad m, HasInstances m a) => Name -> m [ClassInstance a]
getInstancesOf name = do
is <- getInstances
case M.lookup name (unInstanceCtx is) of
Just is' -> pure is'
Nothing -> pure []
findInstanceOf :: (Monad m, HasInstances m a) => Name -> PolyType a -> m (Maybe (ClassInstance a))
findInstanceOf className ty = do
instances <- getInstancesOf className
pure (listToMaybe . catMaybes $ map hasInstance instances)
where
hasInstance ci@(ClassInstance {ciInstanceTypeName = nm , ciParams = params}) =
case genPred nm params ty of
True -> Just ci
False -> Nothing
-- FIXME: this is a crazy hack to resolve "type-class" instances by folding a predicate over
-- the bound variables of a type constructor
genPred tnm bnd = foldr folder (\x -> unann x == A () (TFree tnm)) bnd where
folder b acc ty =
case ty of
A _ (a `TApp` b) -> acc a
_ -> False
instance Pretty ( a ) where
pretty ( m ) = enclose " [ " " ] " $ cat $ punctuate " , " $ map fn $ toList m where
-- fn (k, v) = pretty k <+> "↦" <+> pretty v
instance Unann (LocalCtx a) (LocalCtx ()) where
unann (LocalCtx xs) = LocalCtx $ map unann xs
-- Lists are left-prepend but contexts are right-append
-- It doesn't matter, so we just pretend that we right-append stuff,
-- yet put it at the head
infixl 5 <+
(<+) :: LocalCtx a -> CtxElem a -> LocalCtx a
LocalCtx xs <+ x = LocalCtx (x : xs)
infixl 4 <++
(<++) :: LocalCtx a -> LocalCtx a -> LocalCtx a
LocalCtx xs <++ LocalCtx ys = LocalCtx (ys ++ xs)
instance Monoid (LocalCtx a) where
mempty = LocalCtx []
mappend = (<++)
instance (IsList (LocalCtx a)) where
type Item (LocalCtx a) = CtxElem a
fromList xs = LocalCtx $ reverse xs
toList (LocalCtx m) = reverse m
isInContext :: CtxElem a -> LocalCtx a -> Bool
isInContext el (LocalCtx xs) = isJust $ find (\x -> unann el == unann x) xs
isInFContext :: Name -> FreeCtx a -> Bool
isInFContext = isMemberOf
isInKContext :: Name -> KindCtx a -> Bool
isInKContext = isMemberOf
ctxFind :: (CtxElem a -> Bool) -> LocalCtx a -> Maybe (CtxElem a)
ctxFind p (LocalCtx xs) = find p xs
lookupTy :: Name -> LocalCtx a -> Maybe (PolyType a)
lookupTy nm (LocalCtx xs) = findMap p xs where
p ((_,nm') `HasType` ty) | nm' == nm = Just ty
p _ = Nothing
elemBy :: (a -> Bool) -> [a] -> Bool
elemBy fn = isJust . find fn
findAssigned :: Name -> LocalCtx a -> Maybe (MonoType a)
findAssigned nm (LocalCtx xs) = findMap fn xs >>= asMonotype where
fn (nm' := ty) | nm == nm' = pure ty
fn _ = Nothing
isAssigned :: Name -> LocalCtx a -> Bool
isAssigned = isJust .*. findAssigned where
(.*.) = (.) . (.)
hasTypeInCtx :: Name -> LocalCtx a -> Maybe (PolyType a)
hasTypeInCtx nm (LocalCtx xs) = findMap fn xs where
fn ((_,nm') `HasType` ty) | nm == nm' = pure ty
fn _ = Nothing
hasTypeInFCtx :: Name -> FreeCtx a -> Maybe (PolyType a)
hasTypeInFCtx nm (FreeCtx m) = M.lookup nm m
-- | drop until an element `el` is encountered in the context. Also drops `el`
dropTil :: CtxElem a -> LocalCtx a -> LocalCtx a
dropTil el (LocalCtx xs) = LocalCtx $ tl $ dropWhile ((unann el /=) . unann) xs where
tl [] = []
tl (_:ys) = ys
-- again, since contexts are "reversed" notationally, this does not yield
-- we switch ys and zs in the definition
splitCtx' :: CtxElem a -> LocalCtx a -> Maybe (LocalCtx a, CtxElem a, LocalCtx a)
splitCtx' el ctx@(LocalCtx xs) =
case break ((unann el ==) . unann) xs of
(_, []) -> Nothing
(ys, z:zs) -> pure (LocalCtx zs, z, LocalCtx ys)
-- | Check if an elem alpha comes before beta in a context
before' :: CtxElem a -> CtxElem a -> LocalCtx a -> Bool
before' alpha beta (LocalCtx ctx) = (beta `comesBefore` alpha) ctx False False where
comesBefore x y [] xr yr = yr
comesBefore x y (a:as) False False
| x =%= a = comesBefore x y as True False
| y =%= a = False
| otherwise = comesBefore x y as False False
comesBefore x y (a:as) True False
| x =%= a = False
| y =%= a = True
| otherwise = comesBefore x y as True False
comesBefore _ _ _ _ _ = False
insertAt' :: CtxElem a -> LocalCtx a -> LocalCtx a -> Maybe (LocalCtx a)
insertAt' at insertee into = do
(l, _, r) <- splitCtx' at into
pure $ l <++ insertee <++ r
containsEVar :: LocalCtx a -> Name -> Bool
containsEVar ctx alpha = isJust $ ctxFind expred ctx where
expred = \case
Exists alpha' _k -> alpha == alpha'
alpha' := _ -> alpha == alpha'
_ -> False
containsTVar :: LocalCtx a -> Name -> Bool
containsTVar ctx alpha = isJust $ ctxFind varPred ctx where
varPred = \case
Uni alpha' _k -> alpha == alpha'
_ -> False
getUnsolved :: LocalCtx a -> [(Name, Kind)]
getUnsolved (LocalCtx xs) = foldr fn [] xs where
fn (Exists nm k) acc = (nm, k) : acc
fn _ acc = acc | null | https://raw.githubusercontent.com/adamschoenemann/clofrp/c26f86aec2cdb8fa7fd317acd13f7d77af984bd3/library/CloFRP/Check/Contexts.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
| Universal
| Existential
| x :_? A
| a = t
| |>a
Local contexts contains local variables and stuff
Free contexts contains "global" mappings from names to types
Kind context contains "global" mappings from type-names to kinds
context of destructors
context of instances of type-classes
FIXME: this is a crazy hack to resolve "type-class" instances by folding a predicate over
the bound variables of a type constructor
fn (k, v) = pretty k <+> "↦" <+> pretty v
Lists are left-prepend but contexts are right-append
It doesn't matter, so we just pretend that we right-append stuff,
yet put it at the head
| drop until an element `el` is encountered in the context. Also drops `el`
again, since contexts are "reversed" notationally, this does not yield
we switch ys and zs in the definition
| Check if an elem alpha comes before beta in a context | # LANGUAGE LambdaCase #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE FunctionalDependencies #
module CloFRP.Check.Contexts
( module CloFRP.Check.Contexts
, module CloFRP.Context
, module CloFRP.Check.Destr
) where
import Data.Data
import GHC.Exts (IsList(..))
import Data.Text.Prettyprint.Doc
import qualified Data.Map.Strict as M
import Data.List (break, find)
import Data.Maybe (isJust, catMaybes, listToMaybe)
import CloFRP.Check.Destr
import CloFRP.AST hiding (exists)
import CloFRP.Context
import CloFRP.Annotated
import CloFRP.Pretty
import CloFRP.Utils (findMap)
data Binding = LamB | LetB deriving (Eq, Show)
data CtxElem a
= Uni Name Kind
| Exists Name Kind
| (Binding, Name) `HasType` PolyType a
| Name := MonoType a
| Marker Name
deriving Eq
instance Unann (CtxElem a) (CtxElem ()) where
unann el =
case el of
Uni nm k -> Uni nm k
Exists nm k -> Exists nm k
(b,nm) `HasType` ty -> (b,nm) `HasType` unann ty
nm := ty -> nm := unann ty
Marker nm -> Marker nm
instance Pretty (CtxElem a) where
pretty = \case
Uni nm Star -> pretty nm
Uni nm k -> parens (pretty nm <+> ":" <+> pretty k)
Exists nm Star -> "^" <> pretty nm
Exists nm k -> parens ("^" <> pretty nm <+> ":" <+> pretty k)
(b, nm) `HasType` ty ->
pretty nm <+> p b <> ":" <+> pretty (unann ty)
where
p LamB = "λ"
p LetB = ""
nm := ty -> "^" <> pretty nm <+> "=" <+> pretty (unann ty)
Marker nm -> "†" <> pretty nm
instance Show (CtxElem a) where
show = show . pretty
exists :: Name -> CtxElem a
exists nm = Exists nm Star
marker :: Name -> CtxElem a
marker = Marker
uni :: Name -> CtxElem a
uni nm = Uni nm Star
(<\:) :: Name -> PolyType a -> CtxElem a
x <\: t = (LamB, x) `HasType` t
(.:) :: Name -> PolyType a -> CtxElem a
x .: t = (LetB, x) `HasType` t
newtype LocalCtx a = LocalCtx { unLocalCtx :: [CtxElem a] }
deriving (Eq)
instance Show (LocalCtx a) where
show gamma = showW 80 (pretty gamma)
instance Pretty (LocalCtx a) where
pretty (LocalCtx xs) =
brackets $ concatWith (\x y -> x <+> softline' <> comma <> space <> y) $ map pretty (reverse xs)
newtype FreeCtx a = FreeCtx { unFreeCtx :: M.Map Name (PolyType a) }
deriving (Show, Eq, Monoid, Data)
mapFreeCtx :: (PolyType a -> PolyType b) -> FreeCtx a -> FreeCtx b
mapFreeCtx fn (FreeCtx m) = FreeCtx $ M.map fn m
instance (IsList (FreeCtx a)) where
type Item (FreeCtx a) = (Name, PolyType a)
fromList xs = FreeCtx $ M.fromList xs
toList (FreeCtx m) = M.toList m
instance Context (FreeCtx a) where
type Elem (FreeCtx a) = PolyType a
type Key (FreeCtx a) = Name
extend nm ty (FreeCtx m) = FreeCtx $ M.insert nm ty m
isMemberOf nm (FreeCtx m) = M.member nm m
query x (FreeCtx m) = M.lookup x m
delete x (FreeCtx m) = FreeCtx (M.delete x m)
newtype KindCtx a = KindCtx { unKindCtx :: M.Map Name Kind }
deriving (Show, Eq, Monoid, Data)
instance Context (KindCtx a) where
type Elem (KindCtx a) = Kind
type Key (KindCtx a) = Name
extend nm ty (KindCtx m) = KindCtx $ M.insert nm ty m
isMemberOf nm (KindCtx m) = M.member nm m
query x (KindCtx m) = M.lookup x m
delete x (KindCtx m) = KindCtx (M.delete x m)
instance (IsList (KindCtx a)) where
type Item (KindCtx a) = (Name, Kind)
fromList xs = KindCtx $ M.fromList xs
toList (KindCtx m) = M.toList m
instance Pretty (KindCtx a) where
pretty (KindCtx m) = enclose "[" "]" $ cat $ punctuate ", " $ map fn $ toList m where
fn (k, v) = pretty k <+> "↦" <+> pretty v
newtype DestrCtx a = DestrCtx { unDestrCtx :: M.Map Name (Destr a) }
deriving (Show, Eq, Monoid, Data)
instance Context (DestrCtx a) where
type Elem (DestrCtx a) = Destr a
type Key (DestrCtx a) = Name
extend nm ty (DestrCtx m) = DestrCtx $ M.insert nm ty m
isMemberOf nm (DestrCtx m) = M.member nm m
query x (DestrCtx m) = M.lookup x m
delete x (DestrCtx m) = DestrCtx (M.delete x m)
instance (IsList (DestrCtx a)) where
type Item (DestrCtx a) = (Name, Destr a)
fromList xs = DestrCtx $ M.fromList xs
toList (DestrCtx m) = M.toList m
data ClassInstance a = ClassInstance
{ ciClassName :: Name
, ciInstanceTypeName :: Name
, ciParams :: [Name]
, ciDictionary :: M.Map Name (PolyType a, Expr a)
} deriving (Eq, Data, Typeable)
instance Pretty (ClassInstance a) where
pretty (ClassInstance {ciClassName, ciParams, ciDictionary, ciInstanceTypeName}) =
"Instance" <+> tupled [pretty ciClassName, pretty ciInstanceTypeName, pretty ciParams, list $ M.elems $ M.map pretty ciDictionary]
instance Show (ClassInstance a) where
show = show . pretty
newtype InstanceCtx a = InstanceCtx { unInstanceCtx :: M.Map Name [ClassInstance a] }
deriving (Show, Eq, Monoid, Data, Typeable)
instance Context (InstanceCtx a) where
type Elem (InstanceCtx a) = [ClassInstance a]
type Key (InstanceCtx a) = Name
extend nm ty (InstanceCtx m) = InstanceCtx $ M.insert nm ty m
isMemberOf nm (InstanceCtx m) = M.member nm m
query x (InstanceCtx m) = M.lookup x m
delete x (InstanceCtx m) = InstanceCtx (M.delete x m)
instance (IsList (InstanceCtx a)) where
type Item (InstanceCtx a) = (Name, [ClassInstance a])
fromList xs = InstanceCtx $ M.fromList xs
toList (InstanceCtx m) = M.toList m
instance Pretty (InstanceCtx a) where
pretty (InstanceCtx m) = enclose "[" "]" $ cat $ punctuate ", " $ map fn $ toList m where
fn (k, v) = pretty k <+> "↦" <+> pretty v
class HasInstances m a | m -> a where
getInstances :: m (InstanceCtx a)
getInstancesOf :: (Monad m, HasInstances m a) => Name -> m [ClassInstance a]
getInstancesOf name = do
is <- getInstances
case M.lookup name (unInstanceCtx is) of
Just is' -> pure is'
Nothing -> pure []
findInstanceOf :: (Monad m, HasInstances m a) => Name -> PolyType a -> m (Maybe (ClassInstance a))
findInstanceOf className ty = do
instances <- getInstancesOf className
pure (listToMaybe . catMaybes $ map hasInstance instances)
where
hasInstance ci@(ClassInstance {ciInstanceTypeName = nm , ciParams = params}) =
case genPred nm params ty of
True -> Just ci
False -> Nothing
genPred tnm bnd = foldr folder (\x -> unann x == A () (TFree tnm)) bnd where
folder b acc ty =
case ty of
A _ (a `TApp` b) -> acc a
_ -> False
instance Pretty ( a ) where
pretty ( m ) = enclose " [ " " ] " $ cat $ punctuate " , " $ map fn $ toList m where
instance Unann (LocalCtx a) (LocalCtx ()) where
unann (LocalCtx xs) = LocalCtx $ map unann xs
infixl 5 <+
(<+) :: LocalCtx a -> CtxElem a -> LocalCtx a
LocalCtx xs <+ x = LocalCtx (x : xs)
infixl 4 <++
(<++) :: LocalCtx a -> LocalCtx a -> LocalCtx a
LocalCtx xs <++ LocalCtx ys = LocalCtx (ys ++ xs)
instance Monoid (LocalCtx a) where
mempty = LocalCtx []
mappend = (<++)
instance (IsList (LocalCtx a)) where
type Item (LocalCtx a) = CtxElem a
fromList xs = LocalCtx $ reverse xs
toList (LocalCtx m) = reverse m
isInContext :: CtxElem a -> LocalCtx a -> Bool
isInContext el (LocalCtx xs) = isJust $ find (\x -> unann el == unann x) xs
isInFContext :: Name -> FreeCtx a -> Bool
isInFContext = isMemberOf
isInKContext :: Name -> KindCtx a -> Bool
isInKContext = isMemberOf
ctxFind :: (CtxElem a -> Bool) -> LocalCtx a -> Maybe (CtxElem a)
ctxFind p (LocalCtx xs) = find p xs
lookupTy :: Name -> LocalCtx a -> Maybe (PolyType a)
lookupTy nm (LocalCtx xs) = findMap p xs where
p ((_,nm') `HasType` ty) | nm' == nm = Just ty
p _ = Nothing
elemBy :: (a -> Bool) -> [a] -> Bool
elemBy fn = isJust . find fn
findAssigned :: Name -> LocalCtx a -> Maybe (MonoType a)
findAssigned nm (LocalCtx xs) = findMap fn xs >>= asMonotype where
fn (nm' := ty) | nm == nm' = pure ty
fn _ = Nothing
isAssigned :: Name -> LocalCtx a -> Bool
isAssigned = isJust .*. findAssigned where
(.*.) = (.) . (.)
hasTypeInCtx :: Name -> LocalCtx a -> Maybe (PolyType a)
hasTypeInCtx nm (LocalCtx xs) = findMap fn xs where
fn ((_,nm') `HasType` ty) | nm == nm' = pure ty
fn _ = Nothing
hasTypeInFCtx :: Name -> FreeCtx a -> Maybe (PolyType a)
hasTypeInFCtx nm (FreeCtx m) = M.lookup nm m
dropTil :: CtxElem a -> LocalCtx a -> LocalCtx a
dropTil el (LocalCtx xs) = LocalCtx $ tl $ dropWhile ((unann el /=) . unann) xs where
tl [] = []
tl (_:ys) = ys
splitCtx' :: CtxElem a -> LocalCtx a -> Maybe (LocalCtx a, CtxElem a, LocalCtx a)
splitCtx' el ctx@(LocalCtx xs) =
case break ((unann el ==) . unann) xs of
(_, []) -> Nothing
(ys, z:zs) -> pure (LocalCtx zs, z, LocalCtx ys)
before' :: CtxElem a -> CtxElem a -> LocalCtx a -> Bool
before' alpha beta (LocalCtx ctx) = (beta `comesBefore` alpha) ctx False False where
comesBefore x y [] xr yr = yr
comesBefore x y (a:as) False False
| x =%= a = comesBefore x y as True False
| y =%= a = False
| otherwise = comesBefore x y as False False
comesBefore x y (a:as) True False
| x =%= a = False
| y =%= a = True
| otherwise = comesBefore x y as True False
comesBefore _ _ _ _ _ = False
insertAt' :: CtxElem a -> LocalCtx a -> LocalCtx a -> Maybe (LocalCtx a)
insertAt' at insertee into = do
(l, _, r) <- splitCtx' at into
pure $ l <++ insertee <++ r
containsEVar :: LocalCtx a -> Name -> Bool
containsEVar ctx alpha = isJust $ ctxFind expred ctx where
expred = \case
Exists alpha' _k -> alpha == alpha'
alpha' := _ -> alpha == alpha'
_ -> False
containsTVar :: LocalCtx a -> Name -> Bool
containsTVar ctx alpha = isJust $ ctxFind varPred ctx where
varPred = \case
Uni alpha' _k -> alpha == alpha'
_ -> False
getUnsolved :: LocalCtx a -> [(Name, Kind)]
getUnsolved (LocalCtx xs) = foldr fn [] xs where
fn (Exists nm k) acc = (nm, k) : acc
fn _ acc = acc |
78307c82ffe4c3e95aa0ab0ed8c715656857a7f5854fdc70e5e012f69454dcda | google/codeworld | General.hs |
Copyright 2020 The CodeWorld Authors . All rights reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2020 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Blockly.General (UUID (..)) where
newtype UUID = UUID String
| null | https://raw.githubusercontent.com/google/codeworld/77b0863075be12e3bc5f182a53fcc38b038c3e16/funblocks-client/src/Blockly/General.hs | haskell |
Copyright 2020 The CodeWorld Authors . All rights reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2020 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Blockly.General (UUID (..)) where
newtype UUID = UUID String
| |
77b87e9c721d5a5945a39dedf40278360aea07e87b67c5790ef520911dfb6a80 | abdulapopoola/SICPBook | Ex3.64.scm | #lang racket
(define (stream-limit s tolerance)
(let ((s0 (stream-ref s 0))
(s1 (stream-ref s 1)))
(if (< (abs (- s0 s1)) tolerance)
s1
(stream-limit (stream-rest s) tolerance)))) | null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%203/3.5/Ex3.64.scm | scheme | #lang racket
(define (stream-limit s tolerance)
(let ((s0 (stream-ref s 0))
(s1 (stream-ref s 1)))
(if (< (abs (- s0 s1)) tolerance)
s1
(stream-limit (stream-rest s) tolerance)))) | |
198249e220d31b802d966ce4496afc0197fe35db9fe9d9f468338a29650c14a0 | Idorobots/spartan | generator.rkt | #lang racket
(require "../env.rkt")
(require "../pass.rkt")
(require "../ast/utils.rkt")
(provide generate-target-code)
(define generate-target-code
(pass (schema "generate-target-code"
'data (list-of? (a-pair? a-symbol?
(ast-subset? '(const symbol if do let binding lambda primop-app))))
'init (ast-subset? '(const symbol if do let binding primop-app)))
(lambda (env)
;; FIXME Actually implement a proper code-gen.
(let ((data (map (lambda (v)
(list 'define
(car v)
(ast->plain (cdr v))))
(env-get env 'data)))
(init (ast->plain (env-get env 'init))))
(if (empty? data)
init
`(begin ,@data
,init))))))
| null | https://raw.githubusercontent.com/Idorobots/spartan/68ac4e02ab8aa84021ec4ed3906e6b766687e5ae/src/compiler/passes/generator.rkt | racket | FIXME Actually implement a proper code-gen. | #lang racket
(require "../env.rkt")
(require "../pass.rkt")
(require "../ast/utils.rkt")
(provide generate-target-code)
(define generate-target-code
(pass (schema "generate-target-code"
'data (list-of? (a-pair? a-symbol?
(ast-subset? '(const symbol if do let binding lambda primop-app))))
'init (ast-subset? '(const symbol if do let binding primop-app)))
(lambda (env)
(let ((data (map (lambda (v)
(list 'define
(car v)
(ast->plain (cdr v))))
(env-get env 'data)))
(init (ast->plain (env-get env 'init))))
(if (empty? data)
init
`(begin ,@data
,init))))))
|
6c51240d8141d3a77b0bdaa320a6058e107365c207ac64bdf41e805d49e04dec | iamFIREcracker/adventofcode | day24.lisp | (defpackage :aoc/2015/24 #.cl-user::*aoc-use*)
(in-package :aoc/2015/24)
(defun target-weight (weights groups) (/ (reduce #'+ weights) groups))
(defun quantum-entanglement (group) (reduce #'* group))
(defun find-perfect-balance (weights groups
&aux (target (target-weight weights groups)))
(labels ((recur (n target remaining)
(cond ((= n 1) (when-let ((found (find target remaining)))
(list (list found))))
((null remaining) '())
(t (append
(recur n target (rest remaining))
(loop for rest in (recur (1- n)
(- target (first remaining))
(rest remaining))
collect (cons (first remaining) rest)))))))
(loop for n from 1 for solutions = (recur n target weights)
when solutions return (reduce #'min solutions
:key #'quantum-entanglement))))
(defun part1 (weights) (find-perfect-balance weights 3))
(defun part2 (weights) (find-perfect-balance weights 4))
(define-solution (2015 24) (weights parse-integers)
(values (part1 weights) (part2 weights)))
(define-test (2015 24) (11266889531 77387711))
| null | https://raw.githubusercontent.com/iamFIREcracker/adventofcode/c395df5e15657f0b9be6ec555e68dc777b0eb7ab/src/2015/day24.lisp | lisp | (defpackage :aoc/2015/24 #.cl-user::*aoc-use*)
(in-package :aoc/2015/24)
(defun target-weight (weights groups) (/ (reduce #'+ weights) groups))
(defun quantum-entanglement (group) (reduce #'* group))
(defun find-perfect-balance (weights groups
&aux (target (target-weight weights groups)))
(labels ((recur (n target remaining)
(cond ((= n 1) (when-let ((found (find target remaining)))
(list (list found))))
((null remaining) '())
(t (append
(recur n target (rest remaining))
(loop for rest in (recur (1- n)
(- target (first remaining))
(rest remaining))
collect (cons (first remaining) rest)))))))
(loop for n from 1 for solutions = (recur n target weights)
when solutions return (reduce #'min solutions
:key #'quantum-entanglement))))
(defun part1 (weights) (find-perfect-balance weights 3))
(defun part2 (weights) (find-perfect-balance weights 4))
(define-solution (2015 24) (weights parse-integers)
(values (part1 weights) (part2 weights)))
(define-test (2015 24) (11266889531 77387711))
| |
39eb8a5f04f657feb191594c50d14223ec5bf15a788db9120c1dde713a722478 | BranchTaken/Hemlock | test_to_string_escape.ml | open! Basis.Rudiments
open! Basis
open Codepoint
let pp_uns_x u formatter =
formatter |> Uns.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex u
let utf8_pp t formatter =
formatter |> Fmt.fmt (Utf8.escape t)
let test () =
let rec fn i = begin
match i with
| 0x80L -> ()
| _ -> begin
let cp = trunc_of_uns i in
let utf8 = Utf8.of_codepoint cp in
File.Fmt.stdout
|> pp_uns_x i
|> Fmt.fmt " -> "
|> pp cp
|> Fmt.fmt " `_`"
|> Fmt.fmt (if Uns.(i > 0x1fL && i < 0x7fL) then (to_string cp) else "�")
|> Fmt.fmt "`_` \""
|> utf8_pp utf8
|> Fmt.fmt "\"\n"
|> ignore;
fn (Uns.succ i)
end
end in
fn 0L
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/a21b462fe7f70475591d2ffae185c91552bf6372/bootstrap/test/basis/codepoint/test_to_string_escape.ml | ocaml | open! Basis.Rudiments
open! Basis
open Codepoint
let pp_uns_x u formatter =
formatter |> Uns.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex u
let utf8_pp t formatter =
formatter |> Fmt.fmt (Utf8.escape t)
let test () =
let rec fn i = begin
match i with
| 0x80L -> ()
| _ -> begin
let cp = trunc_of_uns i in
let utf8 = Utf8.of_codepoint cp in
File.Fmt.stdout
|> pp_uns_x i
|> Fmt.fmt " -> "
|> pp cp
|> Fmt.fmt " `_`"
|> Fmt.fmt (if Uns.(i > 0x1fL && i < 0x7fL) then (to_string cp) else "�")
|> Fmt.fmt "`_` \""
|> utf8_pp utf8
|> Fmt.fmt "\"\n"
|> ignore;
fn (Uns.succ i)
end
end in
fn 0L
let _ = test ()
| |
b2aa1c561e24b9a2db817e16cf908c656e2a518ad1b5bf01c2b86b50677537c4 | incoherentsoftware/defect-process | Data.hs | module Enemy.All.Blob.Data
( BlobEnemyData(..)
, mkBlobEnemyData
) where
import Control.Monad.IO.Class (MonadIO)
import Configs
import Configs.All.Enemy
import Enemy.All.Blob.AttackDescriptions
import Enemy.All.Blob.Behavior
import Enemy.All.Blob.Sprites
import FileCache
import Window.Graphics
data BlobEnemyData = BlobEnemyData
{ _sprites :: EnemySprites
, _attackDescs :: EnemyAttackDescriptions
, _behavior :: BlobEnemyBehavior
, _prevBehavior :: BlobEnemyBehavior
, _config :: EnemyConfig
}
mkBlobEnemyData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m BlobEnemyData
mkBlobEnemyData = do
sprs <- mkEnemySprites
attackDescs <- mkEnemyAttackDescs
cfg <- _enemy <$> readConfigs
return $ BlobEnemyData
{ _sprites = sprs
, _attackDescs = attackDescs
, _behavior = SpawnBehavior
, _prevBehavior = SpawnBehavior
, _config = cfg
}
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/8797aad1d93bff5aadd7226c39a48f45cf76746e/src/Enemy/All/Blob/Data.hs | haskell | module Enemy.All.Blob.Data
( BlobEnemyData(..)
, mkBlobEnemyData
) where
import Control.Monad.IO.Class (MonadIO)
import Configs
import Configs.All.Enemy
import Enemy.All.Blob.AttackDescriptions
import Enemy.All.Blob.Behavior
import Enemy.All.Blob.Sprites
import FileCache
import Window.Graphics
data BlobEnemyData = BlobEnemyData
{ _sprites :: EnemySprites
, _attackDescs :: EnemyAttackDescriptions
, _behavior :: BlobEnemyBehavior
, _prevBehavior :: BlobEnemyBehavior
, _config :: EnemyConfig
}
mkBlobEnemyData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m BlobEnemyData
mkBlobEnemyData = do
sprs <- mkEnemySprites
attackDescs <- mkEnemyAttackDescs
cfg <- _enemy <$> readConfigs
return $ BlobEnemyData
{ _sprites = sprs
, _attackDescs = attackDescs
, _behavior = SpawnBehavior
, _prevBehavior = SpawnBehavior
, _config = cfg
}
| |
3dd05646bcb0435eca5d3636657312a2b30e6186d55df4f13abb010ed7a4f137 | mfoemmel/erlang-otp | wxBoxSizer.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxBoxSizer</a>.
%% <p>This class is derived (and can use functions) from:
%% <br />{@link wxSizer}
%% </p>
%% @type wxBoxSizer(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxBoxSizer).
-include("wxe.hrl").
-export([destroy/1,getOrientation/1,new/1]).
%% inherited exports
-export([add/2,add/3,add/4,addSpacer/2,addStretchSpacer/1,addStretchSpacer/2,
calcMin/1,clear/1,clear/2,detach/2,fit/2,fitInside/2,getChildren/1,getItem/2,
getItem/3,getMinSize/1,getPosition/1,getSize/1,hide/2,hide/3,insert/3,
insert/4,insert/5,insertSpacer/3,insertStretchSpacer/2,insertStretchSpacer/3,
isShown/2,layout/1,parent_class/1,prepend/2,prepend/3,prepend/4,prependSpacer/2,
prependStretchSpacer/1,prependStretchSpacer/2,recalcSizes/1,remove/2,
replace/3,replace/4,setDimension/5,setItemMinSize/3,setItemMinSize/4,
setMinSize/2,setMinSize/3,setSizeHints/2,setVirtualSizeHints/2,show/2,
show/3]).
%% @hidden
parent_class(wxSizer) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @spec (Orient::integer()) -> wxBoxSizer()
%% @doc See <a href="#wxboxsizerwxboxsizer">external documentation</a>.
new(Orient)
when is_integer(Orient) ->
wxe_util:construct(?wxBoxSizer_new,
<<Orient:32/?UI>>).
%% @spec (This::wxBoxSizer()) -> integer()
%% @doc See <a href="#wxboxsizergetorientation">external documentation</a>.
getOrientation(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxBoxSizer),
wxe_util:call(?wxBoxSizer_GetOrientation,
<<ThisRef:32/?UI>>).
%% @spec (This::wxBoxSizer()) -> ok
%% @doc Destroys this object, do not use object again
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxBoxSizer),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
From wxSizer
%% @hidden
show(This,Index, Options) -> wxSizer:show(This,Index, Options).
%% @hidden
show(This,Index) -> wxSizer:show(This,Index).
%% @hidden
setVirtualSizeHints(This,Window) -> wxSizer:setVirtualSizeHints(This,Window).
%% @hidden
setSizeHints(This,Window) -> wxSizer:setSizeHints(This,Window).
%% @hidden
setItemMinSize(This,Index,Width,Height) -> wxSizer:setItemMinSize(This,Index,Width,Height).
%% @hidden
setItemMinSize(This,Index,Size) -> wxSizer:setItemMinSize(This,Index,Size).
%% @hidden
setMinSize(This,Width,Height) -> wxSizer:setMinSize(This,Width,Height).
%% @hidden
setMinSize(This,Size) -> wxSizer:setMinSize(This,Size).
%% @hidden
setDimension(This,X,Y,Width,Height) -> wxSizer:setDimension(This,X,Y,Width,Height).
%% @hidden
replace(This,Oldwin,Newwin, Options) -> wxSizer:replace(This,Oldwin,Newwin, Options).
%% @hidden
replace(This,Oldwin,Newwin) -> wxSizer:replace(This,Oldwin,Newwin).
%% @hidden
remove(This,Index) -> wxSizer:remove(This,Index).
%% @hidden
recalcSizes(This) -> wxSizer:recalcSizes(This).
%% @hidden
prependStretchSpacer(This, Options) -> wxSizer:prependStretchSpacer(This, Options).
%% @hidden
prependStretchSpacer(This) -> wxSizer:prependStretchSpacer(This).
%% @hidden
prependSpacer(This,Size) -> wxSizer:prependSpacer(This,Size).
%% @hidden
prepend(This,Width,Height, Options) -> wxSizer:prepend(This,Width,Height, Options).
%% @hidden
prepend(This,Width,Height) -> wxSizer:prepend(This,Width,Height).
%% @hidden
prepend(This,Window) -> wxSizer:prepend(This,Window).
%% @hidden
layout(This) -> wxSizer:layout(This).
%% @hidden
isShown(This,Index) -> wxSizer:isShown(This,Index).
%% @hidden
insertStretchSpacer(This,Index, Options) -> wxSizer:insertStretchSpacer(This,Index, Options).
%% @hidden
insertStretchSpacer(This,Index) -> wxSizer:insertStretchSpacer(This,Index).
%% @hidden
insertSpacer(This,Index,Size) -> wxSizer:insertSpacer(This,Index,Size).
%% @hidden
insert(This,Index,Width,Height, Options) -> wxSizer:insert(This,Index,Width,Height, Options).
%% @hidden
insert(This,Index,Width,Height) -> wxSizer:insert(This,Index,Width,Height).
%% @hidden
insert(This,Index,Window) -> wxSizer:insert(This,Index,Window).
%% @hidden
hide(This,Window, Options) -> wxSizer:hide(This,Window, Options).
%% @hidden
hide(This,Window) -> wxSizer:hide(This,Window).
%% @hidden
getMinSize(This) -> wxSizer:getMinSize(This).
%% @hidden
getPosition(This) -> wxSizer:getPosition(This).
%% @hidden
getSize(This) -> wxSizer:getSize(This).
%% @hidden
getItem(This,Window, Options) -> wxSizer:getItem(This,Window, Options).
%% @hidden
getItem(This,Window) -> wxSizer:getItem(This,Window).
%% @hidden
getChildren(This) -> wxSizer:getChildren(This).
%% @hidden
fitInside(This,Window) -> wxSizer:fitInside(This,Window).
%% @hidden
fit(This,Window) -> wxSizer:fit(This,Window).
%% @hidden
detach(This,Index) -> wxSizer:detach(This,Index).
%% @hidden
clear(This, Options) -> wxSizer:clear(This, Options).
%% @hidden
clear(This) -> wxSizer:clear(This).
%% @hidden
calcMin(This) -> wxSizer:calcMin(This).
%% @hidden
addStretchSpacer(This, Options) -> wxSizer:addStretchSpacer(This, Options).
%% @hidden
addStretchSpacer(This) -> wxSizer:addStretchSpacer(This).
%% @hidden
addSpacer(This,Size) -> wxSizer:addSpacer(This,Size).
%% @hidden
add(This,Width,Height, Options) -> wxSizer:add(This,Width,Height, Options).
%% @hidden
add(This,Width,Height) -> wxSizer:add(This,Width,Height).
%% @hidden
add(This,Window) -> wxSizer:add(This,Window).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxBoxSizer.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxBoxSizer</a>.
<p>This class is derived (and can use functions) from:
<br />{@link wxSizer}
</p>
@type wxBoxSizer(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
@spec (Orient::integer()) -> wxBoxSizer()
@doc See <a href="#wxboxsizerwxboxsizer">external documentation</a>.
@spec (This::wxBoxSizer()) -> integer()
@doc See <a href="#wxboxsizergetorientation">external documentation</a>.
@spec (This::wxBoxSizer()) -> ok
@doc Destroys this object, do not use object again
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxBoxSizer).
-include("wxe.hrl").
-export([destroy/1,getOrientation/1,new/1]).
-export([add/2,add/3,add/4,addSpacer/2,addStretchSpacer/1,addStretchSpacer/2,
calcMin/1,clear/1,clear/2,detach/2,fit/2,fitInside/2,getChildren/1,getItem/2,
getItem/3,getMinSize/1,getPosition/1,getSize/1,hide/2,hide/3,insert/3,
insert/4,insert/5,insertSpacer/3,insertStretchSpacer/2,insertStretchSpacer/3,
isShown/2,layout/1,parent_class/1,prepend/2,prepend/3,prepend/4,prependSpacer/2,
prependStretchSpacer/1,prependStretchSpacer/2,recalcSizes/1,remove/2,
replace/3,replace/4,setDimension/5,setItemMinSize/3,setItemMinSize/4,
setMinSize/2,setMinSize/3,setSizeHints/2,setVirtualSizeHints/2,show/2,
show/3]).
parent_class(wxSizer) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
new(Orient)
when is_integer(Orient) ->
wxe_util:construct(?wxBoxSizer_new,
<<Orient:32/?UI>>).
getOrientation(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxBoxSizer),
wxe_util:call(?wxBoxSizer_GetOrientation,
<<ThisRef:32/?UI>>).
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxBoxSizer),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
From wxSizer
show(This,Index, Options) -> wxSizer:show(This,Index, Options).
show(This,Index) -> wxSizer:show(This,Index).
setVirtualSizeHints(This,Window) -> wxSizer:setVirtualSizeHints(This,Window).
setSizeHints(This,Window) -> wxSizer:setSizeHints(This,Window).
setItemMinSize(This,Index,Width,Height) -> wxSizer:setItemMinSize(This,Index,Width,Height).
setItemMinSize(This,Index,Size) -> wxSizer:setItemMinSize(This,Index,Size).
setMinSize(This,Width,Height) -> wxSizer:setMinSize(This,Width,Height).
setMinSize(This,Size) -> wxSizer:setMinSize(This,Size).
setDimension(This,X,Y,Width,Height) -> wxSizer:setDimension(This,X,Y,Width,Height).
replace(This,Oldwin,Newwin, Options) -> wxSizer:replace(This,Oldwin,Newwin, Options).
replace(This,Oldwin,Newwin) -> wxSizer:replace(This,Oldwin,Newwin).
remove(This,Index) -> wxSizer:remove(This,Index).
recalcSizes(This) -> wxSizer:recalcSizes(This).
prependStretchSpacer(This, Options) -> wxSizer:prependStretchSpacer(This, Options).
prependStretchSpacer(This) -> wxSizer:prependStretchSpacer(This).
prependSpacer(This,Size) -> wxSizer:prependSpacer(This,Size).
prepend(This,Width,Height, Options) -> wxSizer:prepend(This,Width,Height, Options).
prepend(This,Width,Height) -> wxSizer:prepend(This,Width,Height).
prepend(This,Window) -> wxSizer:prepend(This,Window).
layout(This) -> wxSizer:layout(This).
isShown(This,Index) -> wxSizer:isShown(This,Index).
insertStretchSpacer(This,Index, Options) -> wxSizer:insertStretchSpacer(This,Index, Options).
insertStretchSpacer(This,Index) -> wxSizer:insertStretchSpacer(This,Index).
insertSpacer(This,Index,Size) -> wxSizer:insertSpacer(This,Index,Size).
insert(This,Index,Width,Height, Options) -> wxSizer:insert(This,Index,Width,Height, Options).
insert(This,Index,Width,Height) -> wxSizer:insert(This,Index,Width,Height).
insert(This,Index,Window) -> wxSizer:insert(This,Index,Window).
hide(This,Window, Options) -> wxSizer:hide(This,Window, Options).
hide(This,Window) -> wxSizer:hide(This,Window).
getMinSize(This) -> wxSizer:getMinSize(This).
getPosition(This) -> wxSizer:getPosition(This).
getSize(This) -> wxSizer:getSize(This).
getItem(This,Window, Options) -> wxSizer:getItem(This,Window, Options).
getItem(This,Window) -> wxSizer:getItem(This,Window).
getChildren(This) -> wxSizer:getChildren(This).
fitInside(This,Window) -> wxSizer:fitInside(This,Window).
fit(This,Window) -> wxSizer:fit(This,Window).
detach(This,Index) -> wxSizer:detach(This,Index).
clear(This, Options) -> wxSizer:clear(This, Options).
clear(This) -> wxSizer:clear(This).
calcMin(This) -> wxSizer:calcMin(This).
addStretchSpacer(This, Options) -> wxSizer:addStretchSpacer(This, Options).
addStretchSpacer(This) -> wxSizer:addStretchSpacer(This).
addSpacer(This,Size) -> wxSizer:addSpacer(This,Size).
add(This,Width,Height, Options) -> wxSizer:add(This,Width,Height, Options).
add(This,Width,Height) -> wxSizer:add(This,Width,Height).
add(This,Window) -> wxSizer:add(This,Window).
|
c90a9b67438f042db8cc14506a194fb0f3c67b1a2bfaadbb1c9084072b4ac72c | fjvallarino/monomer | Util.hs | |
Module : . Core . Util
Copyright : ( c ) 2018
License : BSD-3 - Clause ( see the LICENSE file )
Maintainer :
Stability : experimental
Portability : non - portable
Helper functions for Core types .
Module : Monomer.Core.Util
Copyright : (c) 2018 Francisco Vallarino
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : experimental
Portability : non-portable
Helper functions for Core types.
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module Monomer.Core.Util where
import Control.Lens ((&), (^.), (^?), (.~), (?~), _Just)
import Data.Maybe
import Data.Text (Text)
import Data.Typeable (cast)
import Data.Sequence (Seq(..))
import qualified Data.Map.Strict as Map
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import Monomer.Common
import Monomer.Core.Style
import Monomer.Core.WidgetTypes
import Monomer.Helper
import qualified Monomer.Core.Lens as L
| Returns the ' Path ' associated to a given ' WidgetKey ' , if any . The search is
restricted to the parent " Monomer . Widgets . Composite " .
pathFromKey :: WidgetEnv s e -> WidgetKey -> Maybe Path
pathFromKey wenv key = fmap (^. L.info . L.path) node where
node = Map.lookup key (wenv ^. L.widgetKeyMap)
| Returns the ' WidgetId ' associated to a given ' WidgetKey ' , if any . The
search is restricted to the parent " Monomer . Widgets . Composite " .
widgetIdFromKey :: WidgetEnv s e -> WidgetKey -> Maybe WidgetId
widgetIdFromKey wenv key = fmap (^. L.info . L.widgetId) node where
node = Map.lookup key (wenv ^. L.widgetKeyMap)
| Returns the ' WidgetNodeInfo ' associated to the given ' WidgetKey ' , if any .
The search is restricted to the parent " Monomer . Widgets . Composite " .
nodeInfoFromKey :: WidgetEnv s e -> WidgetKey -> Maybe WidgetNodeInfo
nodeInfoFromKey wenv key = path >>= nodeInfoFromPath wenv where
path = pathFromKey wenv key
| Returns the ' WidgetId ' associated to the given ' Path ' , if any .
widgetIdFromPath :: WidgetEnv s e -> Path -> Maybe WidgetId
widgetIdFromPath wenv path = mwni ^? _Just . L.widgetId where
branch = wenv ^. L.findBranchByPath $ path
mwni = Seq.lookup (length branch - 1) branch
{-# DEPRECATED findWidgetIdFromPath "Use 'widgetIdFromPath' instead." #-}
findWidgetIdFromPath :: WidgetEnv s e -> Path -> Maybe WidgetId
findWidgetIdFromPath = widgetIdFromPath
| Returns the ' WidgetNodeInfo ' associated to the given ' Path ' , if any .
nodeInfoFromPath :: WidgetEnv s e -> Path -> Maybe WidgetNodeInfo
nodeInfoFromPath wenv path = mwni where
branch = wenv ^. L.findBranchByPath $ path
mwni = Seq.lookup (length branch - 1) branch
| Returns the ' WidgetNodeInfo ' associated to a given ' Path ' . The path will be
searched for starting from the provided ' ' .
findChildNodeInfoByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Maybe WidgetNodeInfo
findChildNodeInfoByPath wenv node target = mnode where
branch = widgetFindBranchByPath (node ^. L.widget) wenv node target
mnode = case Seq.lookup (length branch - 1) branch of
Just child
| child ^. L.path == target -> Just child
_ -> Nothing
{-# DEPRECATED findWidgetByPath "Use 'findChildNodeInfoByPath' instead." #-}
findWidgetByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Maybe WidgetNodeInfo
findWidgetByPath = findChildNodeInfoByPath
| Returns the ' WidgetNodeInfo ' branch associated to a given ' Path ' . The path
will be searched for starting from the provided ' ' .
findChildBranchByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Seq WidgetNodeInfo
findChildBranchByPath wenv node target = branch where
branch = widgetFindBranchByPath (node ^. L.widget) wenv node target
{-# DEPRECATED findWidgetBranchByPath "Use 'findChildBranchByPath' instead." #-}
findWidgetBranchByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Seq WidgetNodeInfo
findWidgetBranchByPath = findChildBranchByPath
| Returns the first parent ' WidgetNodeInfo ' of the ' Path ' that matches the
given ' WidgetType ' .
findParentNodeInfoByType
:: WidgetEnv s e -> Path -> WidgetType -> Maybe WidgetNodeInfo
findParentNodeInfoByType wenv path wtype = wniParent where
isMatch wni = wni ^. L.widgetType == wtype
branch = wenv ^. L.findBranchByPath $ path
matches = Seq.filter isMatch branch
wniParent = Seq.lookup (length matches - 1) matches
| Helper functions that associates False to Vertical and True to Horizontal .
getLayoutDirection :: Bool -> LayoutDirection
getLayoutDirection False = LayoutVertical
getLayoutDirection True = LayoutHorizontal
| Filters user events from a list of WidgetRequests .
eventsFromReqs :: Seq (WidgetRequest s e) -> Seq e
eventsFromReqs reqs = seqCatMaybes mevents where
mevents = flip fmap reqs $ \case
RaiseEvent ev -> cast ev
_ -> Nothing
{-|
Ignore events generated by the parent. Could be used to consume the tab key and
avoid having the focus move to the next widget.
-}
isIgnoreParentEvents :: WidgetRequest s e -> Bool
isIgnoreParentEvents IgnoreParentEvents = True
isIgnoreParentEvents _ = False
-- | Ignore children events. Scroll relies on this to handle click/wheel.
isIgnoreChildrenEvents :: WidgetRequest s e -> Bool
isIgnoreChildrenEvents IgnoreChildrenEvents = True
isIgnoreChildrenEvents _ = False
{-|
The widget content changed and requires a different size. Processed at the end
of the cycle, since several widgets may request it.
-}
isResizeWidgets :: WidgetRequest s e -> Bool
isResizeWidgets ResizeWidgets{} = True
isResizeWidgets _ = False
{-|
The widget content changed and requires a different size. Processed immediately.
Avoid if possible, since it can affect performance.
-}
isResizeWidgetsImmediate :: WidgetRequest s e -> Bool
isResizeWidgetsImmediate ResizeWidgetsImmediate{} = True
isResizeWidgetsImmediate _ = False
| Moves the focus , optionally indicating a starting widgetId .
isMoveFocus :: WidgetRequest s e -> Bool
isMoveFocus MoveFocus{} = True
isMoveFocus _ = False
| Sets the focus to the given widgetId .
isSetFocus :: WidgetRequest s e -> Bool
isSetFocus SetFocus{} = True
isSetFocus _ = False
-- | Requests the clipboard contents. It will be received as a SystemEvent.
isGetClipboard :: WidgetRequest s e -> Bool
isGetClipboard GetClipboard{} = True
isGetClipboard _ = False
| Sets the clipboard to the given ClipboardData .
isSetClipboard :: WidgetRequest s e -> Bool
isSetClipboard SetClipboard{} = True
isSetClipboard _ = False
{-|
Sets the viewport which should be remain visible when an on-screen keyboard is
displayed. Required for mobile.
-}
isStartTextInput :: WidgetRequest s e -> Bool
isStartTextInput StartTextInput{} = True
isStartTextInput _ = False
-- | Resets the keyboard viewport,
isStopTextInput :: WidgetRequest s e -> Bool
isStopTextInput StopTextInput{} = True
isStopTextInput _ = False
{-|
Sets a widget as the base target of future events. This is used by the dropdown
component to handle list events (which is on top of everything).
-}
isSetOverlay :: WidgetRequest s e -> Bool
isSetOverlay SetOverlay{} = True
isSetOverlay _ = False
-- | Removes the existing overlay.
isResetOverlay :: WidgetRequest s e -> Bool
isResetOverlay ResetOverlay{} = True
isResetOverlay _ = False
{-|
Sets the current active cursor icon. This acts as a stack, so removing means
going back a step to the cursor set by a parent widget.
-}
isSetCursorIcon :: WidgetRequest s e -> Bool
isSetCursorIcon SetCursorIcon{} = True
isSetCursorIcon _ = False
-- | Removes a cursor icon setting from the stack.
isResetCursorIcon :: WidgetRequest s e -> Bool
isResetCursorIcon ResetCursorIcon{} = True
isResetCursorIcon _ = False
{-|
Sets the current item being dragged and the message it carries. This message is
used by targets to check if they accept it or not.
-}
isStartDrag :: WidgetRequest s e -> Bool
isStartDrag StartDrag{} = True
isStartDrag _ = False
-- | Cancels the current dragging process.
isStopDrag :: WidgetRequest s e -> Bool
isStopDrag StopDrag{} = True
isStopDrag _ = False
|
Requests rendering a single frame . Rendering is not done at a fixed rate , in
order to reduce CPU usage . Widgets are responsible of requesting rendering at
points of interest . Mouse and keyboard events automatically generate render
requests , but the result of a WidgetTask does not .
Requests rendering a single frame. Rendering is not done at a fixed rate, in
order to reduce CPU usage. Widgets are responsible of requesting rendering at
points of interest. Mouse and keyboard events automatically generate render
requests, but the result of a WidgetTask does not.
-}
isRenderOnce :: WidgetRequest s e -> Bool
isRenderOnce RenderOnce{} = True
isRenderOnce _ = False
{-|
Useful if a widget requires periodic rendering. An optional maximum number of
frames can be provided.
-}
isRenderEvery :: WidgetRequest s e -> Bool
isRenderEvery RenderEvery{} = True
isRenderEvery _ = False
-- | Stops a previous periodic rendering request.
isRenderStop :: WidgetRequest s e -> Bool
isRenderStop RenderStop{} = True
isRenderStop _ = False
-- | Requests to have an image removed from the renderer.
isRemoveRendererImage :: WidgetRequest s e -> Bool
isRemoveRendererImage RemoveRendererImage{} = True
isRemoveRendererImage _ = False
{-|
Requests to exit the application. Can also be used to cancel a previous request
(or a window close).
-}
isExitApplication :: WidgetRequest s e -> Bool
isExitApplication ExitApplication{} = True
isExitApplication _ = False
-- | Performs a "WindowRequest".
isUpdateWindow :: WidgetRequest s e -> Bool
isUpdateWindow UpdateWindow{} = True
isUpdateWindow _ = False
-- | Request a model update. This usually involves lenses and "widgetDataSet".
isUpdateModel :: WidgetRequest s e -> Bool
isUpdateModel UpdateModel{} = True
isUpdateModel _ = False
|
Updates the path of a given widget . Both " . Widgets . Single " and
" Monomer . Widgets . Container " handle this automatically .
Updates the path of a given widget. Both "Monomer.Widgets.Single" and
"Monomer.Widgets.Container" handle this automatically.
-}
isSetWidgetPath :: WidgetRequest s e -> Bool
isSetWidgetPath SetWidgetPath{} = True
isSetWidgetPath _ = False
| Clears an association between widgetId and path .
isResetWidgetPath :: WidgetRequest s e -> Bool
isResetWidgetPath ResetWidgetPath{} = True
isResetWidgetPath _ = False
|
Raises a user event , which usually will be processed in handleEvent in a
" Monomer . Widgets . Composite " instance .
Raises a user event, which usually will be processed in handleEvent in a
"Monomer.Widgets.Composite" instance.
-}
isRaiseEvent :: WidgetRequest s e -> Bool
isRaiseEvent RaiseEvent{} = True
isRaiseEvent _ = False
|
Sends a message to the given widgetId . If the target does not expect the
message 's type , it will be ignored .
Sends a message to the given widgetId. If the target does not expect the
message's type, it will be ignored.
-}
isSendMessage :: WidgetRequest s e -> Bool
isSendMessage SendMessage{} = True
isSendMessage _ = False
{-|
Runs an asynchronous tasks. It is mandatory to return a message that will be
sent to the task owner (this is the only way to feed data back).
-}
isRunTask :: WidgetRequest s e -> Bool
isRunTask RunTask{} = True
isRunTask _ = False
|
Similar to , but can generate unlimited messages . This is useful for
WebSockets and similar data sources . It receives a function that with which to
send messages to the producer owner .
Similar to RunTask, but can generate unlimited messages. This is useful for
WebSockets and similar data sources. It receives a function that with which to
send messages to the producer owner.
-}
isRunProducer :: WidgetRequest s e -> Bool
isRunProducer RunProducer{} = True
isRunProducer _ = False
| Checks if the request is either MoveFocus or SetFocus .
isFocusRequest :: WidgetRequest s e -> Bool
isFocusRequest MoveFocus{} = True
isFocusRequest SetFocus{} = True
isFocusRequest _ = False
| Checks if the result contains a Resize request .
isResizeResult :: Maybe (WidgetResult s e) -> Bool
isResizeResult result = isJust resizeReq where
requests = maybe Empty (^. L.requests) result
resizeReq = Seq.findIndexL isResizeWidgets requests
-- | Checks if the result contains a ResizeImmediate request.
isResizeImmediateResult :: Maybe (WidgetResult s e) -> Bool
isResizeImmediateResult result = isJust resizeReq where
requests = maybe Empty (^. L.requests) result
resizeReq = Seq.findIndexL isResizeWidgetsImmediate requests
-- | Checks if the result contains any kind of resize request.
isResizeAnyResult :: Maybe (WidgetResult s e) -> Bool
isResizeAnyResult res = isResizeResult res || isResizeImmediateResult res
-- | Checks if the platform is Linux
isLinux :: WidgetEnv s e -> Bool
isLinux wenv = _weOs wenv == "Linux"
| Checks if the platform is macOS
isMacOS :: WidgetEnv s e -> Bool
isMacOS wenv = _weOs wenv == "Mac OS X"
| Checks if the platform is Windows
isWindows :: WidgetEnv s e -> Bool
isWindows wenv = _weOs wenv == "Windows"
|
Returns the current time in milliseconds . Adds appStartTs and timestamp fields
from ' WidgetEnv ' and converts the result to the expected ' Integral ' type .
Returns the current time in milliseconds. Adds appStartTs and timestamp fields
from 'WidgetEnv' and converts the result to the expected 'Integral' type.
-}
currentTimeMs :: Integral a => WidgetEnv s e -> a
currentTimeMs wenv = fromIntegral ts where
ts = wenv ^. L.appStartTs + wenv ^. L.timestamp
-- | Returns a string description of a node and its children.
widgetTreeDesc :: Int -> WidgetNode s e -> String
widgetTreeDesc level node = desc where
desc = nodeDesc level node ++ "\n" ++ childDesc
childDesc = foldMap (widgetTreeDesc (level + 1)) (_wnChildren node)
-- | Returns a string description of a node.
nodeDesc :: Int -> WidgetNode s e -> String
nodeDesc level node = infoDesc (_wnInfo node) where
spaces = replicate (level * 2) ' '
infoDesc info =
spaces ++ "type: " ++ show (_wniWidgetType info) ++ "\n" ++
spaces ++ "path: " ++ show (_wniPath info) ++ "\n" ++
spaces ++ "vp: " ++ rectDesc (_wniViewport info) ++ "\n" ++
spaces ++ "req: " ++ show (_wniSizeReqW info, _wniSizeReqH info) ++ "\n"
rectDesc r = show (_rX r, _rY r, _rW r, _rH r)
-- | Returns a string description of a node info and its children.
widgetInstTreeDesc :: Int -> WidgetInstanceNode -> String
widgetInstTreeDesc level node = desc where
desc = nodeInstDesc level node ++ "\n" ++ childDesc
childDesc = foldMap (widgetInstTreeDesc (level + 1)) (_winChildren node)
-- | Returns a string description of a node info.
nodeInstDesc :: Int -> WidgetInstanceNode -> String
nodeInstDesc level node = infoDesc (_winInfo node) where
spaces = replicate (level * 2) ' '
infoDesc info =
spaces ++ "type: " ++ show (_wniWidgetType info) ++ "\n" ++
spaces ++ "path: " ++ show (_wniPath info) ++ "\n" ++
spaces ++ "vp: " ++ rectDesc (_wniViewport info) ++ "\n" ++
spaces ++ "req: " ++ show (_wniSizeReqW info, _wniSizeReqH info) ++ "\n"
rectDesc r = show (_rX r, _rY r, _rW r, _rH r)
-- | Returns a string description of a node info and its children, from a node.
treeInstDescFromNode :: WidgetEnv s e -> Int -> WidgetNode s e -> String
treeInstDescFromNode wenv level node = widgetInstTreeDesc level nodeInst where
nodeInst = widgetGetInstanceTree (node ^. L.widget) wenv node
| null | https://raw.githubusercontent.com/fjvallarino/monomer/d4270caafea4ff4fdd80bb1c9b78443ae480cfc5/src/Monomer/Core/Util.hs | haskell | # DEPRECATED findWidgetIdFromPath "Use 'widgetIdFromPath' instead." #
# DEPRECATED findWidgetByPath "Use 'findChildNodeInfoByPath' instead." #
# DEPRECATED findWidgetBranchByPath "Use 'findChildBranchByPath' instead." #
|
Ignore events generated by the parent. Could be used to consume the tab key and
avoid having the focus move to the next widget.
| Ignore children events. Scroll relies on this to handle click/wheel.
|
The widget content changed and requires a different size. Processed at the end
of the cycle, since several widgets may request it.
|
The widget content changed and requires a different size. Processed immediately.
Avoid if possible, since it can affect performance.
| Requests the clipboard contents. It will be received as a SystemEvent.
|
Sets the viewport which should be remain visible when an on-screen keyboard is
displayed. Required for mobile.
| Resets the keyboard viewport,
|
Sets a widget as the base target of future events. This is used by the dropdown
component to handle list events (which is on top of everything).
| Removes the existing overlay.
|
Sets the current active cursor icon. This acts as a stack, so removing means
going back a step to the cursor set by a parent widget.
| Removes a cursor icon setting from the stack.
|
Sets the current item being dragged and the message it carries. This message is
used by targets to check if they accept it or not.
| Cancels the current dragging process.
|
Useful if a widget requires periodic rendering. An optional maximum number of
frames can be provided.
| Stops a previous periodic rendering request.
| Requests to have an image removed from the renderer.
|
Requests to exit the application. Can also be used to cancel a previous request
(or a window close).
| Performs a "WindowRequest".
| Request a model update. This usually involves lenses and "widgetDataSet".
|
Runs an asynchronous tasks. It is mandatory to return a message that will be
sent to the task owner (this is the only way to feed data back).
| Checks if the result contains a ResizeImmediate request.
| Checks if the result contains any kind of resize request.
| Checks if the platform is Linux
| Returns a string description of a node and its children.
| Returns a string description of a node.
| Returns a string description of a node info and its children.
| Returns a string description of a node info.
| Returns a string description of a node info and its children, from a node. | |
Module : . Core . Util
Copyright : ( c ) 2018
License : BSD-3 - Clause ( see the LICENSE file )
Maintainer :
Stability : experimental
Portability : non - portable
Helper functions for Core types .
Module : Monomer.Core.Util
Copyright : (c) 2018 Francisco Vallarino
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : experimental
Portability : non-portable
Helper functions for Core types.
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module Monomer.Core.Util where
import Control.Lens ((&), (^.), (^?), (.~), (?~), _Just)
import Data.Maybe
import Data.Text (Text)
import Data.Typeable (cast)
import Data.Sequence (Seq(..))
import qualified Data.Map.Strict as Map
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import Monomer.Common
import Monomer.Core.Style
import Monomer.Core.WidgetTypes
import Monomer.Helper
import qualified Monomer.Core.Lens as L
| Returns the ' Path ' associated to a given ' WidgetKey ' , if any . The search is
restricted to the parent " Monomer . Widgets . Composite " .
pathFromKey :: WidgetEnv s e -> WidgetKey -> Maybe Path
pathFromKey wenv key = fmap (^. L.info . L.path) node where
node = Map.lookup key (wenv ^. L.widgetKeyMap)
| Returns the ' WidgetId ' associated to a given ' WidgetKey ' , if any . The
search is restricted to the parent " Monomer . Widgets . Composite " .
widgetIdFromKey :: WidgetEnv s e -> WidgetKey -> Maybe WidgetId
widgetIdFromKey wenv key = fmap (^. L.info . L.widgetId) node where
node = Map.lookup key (wenv ^. L.widgetKeyMap)
| Returns the ' WidgetNodeInfo ' associated to the given ' WidgetKey ' , if any .
The search is restricted to the parent " Monomer . Widgets . Composite " .
nodeInfoFromKey :: WidgetEnv s e -> WidgetKey -> Maybe WidgetNodeInfo
nodeInfoFromKey wenv key = path >>= nodeInfoFromPath wenv where
path = pathFromKey wenv key
| Returns the ' WidgetId ' associated to the given ' Path ' , if any .
widgetIdFromPath :: WidgetEnv s e -> Path -> Maybe WidgetId
widgetIdFromPath wenv path = mwni ^? _Just . L.widgetId where
branch = wenv ^. L.findBranchByPath $ path
mwni = Seq.lookup (length branch - 1) branch
findWidgetIdFromPath :: WidgetEnv s e -> Path -> Maybe WidgetId
findWidgetIdFromPath = widgetIdFromPath
| Returns the ' WidgetNodeInfo ' associated to the given ' Path ' , if any .
nodeInfoFromPath :: WidgetEnv s e -> Path -> Maybe WidgetNodeInfo
nodeInfoFromPath wenv path = mwni where
branch = wenv ^. L.findBranchByPath $ path
mwni = Seq.lookup (length branch - 1) branch
| Returns the ' WidgetNodeInfo ' associated to a given ' Path ' . The path will be
searched for starting from the provided ' ' .
findChildNodeInfoByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Maybe WidgetNodeInfo
findChildNodeInfoByPath wenv node target = mnode where
branch = widgetFindBranchByPath (node ^. L.widget) wenv node target
mnode = case Seq.lookup (length branch - 1) branch of
Just child
| child ^. L.path == target -> Just child
_ -> Nothing
findWidgetByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Maybe WidgetNodeInfo
findWidgetByPath = findChildNodeInfoByPath
| Returns the ' WidgetNodeInfo ' branch associated to a given ' Path ' . The path
will be searched for starting from the provided ' ' .
findChildBranchByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Seq WidgetNodeInfo
findChildBranchByPath wenv node target = branch where
branch = widgetFindBranchByPath (node ^. L.widget) wenv node target
findWidgetBranchByPath
:: WidgetEnv s e -> WidgetNode s e -> Path -> Seq WidgetNodeInfo
findWidgetBranchByPath = findChildBranchByPath
| Returns the first parent ' WidgetNodeInfo ' of the ' Path ' that matches the
given ' WidgetType ' .
findParentNodeInfoByType
:: WidgetEnv s e -> Path -> WidgetType -> Maybe WidgetNodeInfo
findParentNodeInfoByType wenv path wtype = wniParent where
isMatch wni = wni ^. L.widgetType == wtype
branch = wenv ^. L.findBranchByPath $ path
matches = Seq.filter isMatch branch
wniParent = Seq.lookup (length matches - 1) matches
| Helper functions that associates False to Vertical and True to Horizontal .
getLayoutDirection :: Bool -> LayoutDirection
getLayoutDirection False = LayoutVertical
getLayoutDirection True = LayoutHorizontal
| Filters user events from a list of WidgetRequests .
eventsFromReqs :: Seq (WidgetRequest s e) -> Seq e
eventsFromReqs reqs = seqCatMaybes mevents where
mevents = flip fmap reqs $ \case
RaiseEvent ev -> cast ev
_ -> Nothing
isIgnoreParentEvents :: WidgetRequest s e -> Bool
isIgnoreParentEvents IgnoreParentEvents = True
isIgnoreParentEvents _ = False
isIgnoreChildrenEvents :: WidgetRequest s e -> Bool
isIgnoreChildrenEvents IgnoreChildrenEvents = True
isIgnoreChildrenEvents _ = False
isResizeWidgets :: WidgetRequest s e -> Bool
isResizeWidgets ResizeWidgets{} = True
isResizeWidgets _ = False
isResizeWidgetsImmediate :: WidgetRequest s e -> Bool
isResizeWidgetsImmediate ResizeWidgetsImmediate{} = True
isResizeWidgetsImmediate _ = False
| Moves the focus , optionally indicating a starting widgetId .
isMoveFocus :: WidgetRequest s e -> Bool
isMoveFocus MoveFocus{} = True
isMoveFocus _ = False
| Sets the focus to the given widgetId .
isSetFocus :: WidgetRequest s e -> Bool
isSetFocus SetFocus{} = True
isSetFocus _ = False
isGetClipboard :: WidgetRequest s e -> Bool
isGetClipboard GetClipboard{} = True
isGetClipboard _ = False
| Sets the clipboard to the given ClipboardData .
isSetClipboard :: WidgetRequest s e -> Bool
isSetClipboard SetClipboard{} = True
isSetClipboard _ = False
isStartTextInput :: WidgetRequest s e -> Bool
isStartTextInput StartTextInput{} = True
isStartTextInput _ = False
isStopTextInput :: WidgetRequest s e -> Bool
isStopTextInput StopTextInput{} = True
isStopTextInput _ = False
isSetOverlay :: WidgetRequest s e -> Bool
isSetOverlay SetOverlay{} = True
isSetOverlay _ = False
isResetOverlay :: WidgetRequest s e -> Bool
isResetOverlay ResetOverlay{} = True
isResetOverlay _ = False
isSetCursorIcon :: WidgetRequest s e -> Bool
isSetCursorIcon SetCursorIcon{} = True
isSetCursorIcon _ = False
isResetCursorIcon :: WidgetRequest s e -> Bool
isResetCursorIcon ResetCursorIcon{} = True
isResetCursorIcon _ = False
isStartDrag :: WidgetRequest s e -> Bool
isStartDrag StartDrag{} = True
isStartDrag _ = False
isStopDrag :: WidgetRequest s e -> Bool
isStopDrag StopDrag{} = True
isStopDrag _ = False
|
Requests rendering a single frame . Rendering is not done at a fixed rate , in
order to reduce CPU usage . Widgets are responsible of requesting rendering at
points of interest . Mouse and keyboard events automatically generate render
requests , but the result of a WidgetTask does not .
Requests rendering a single frame. Rendering is not done at a fixed rate, in
order to reduce CPU usage. Widgets are responsible of requesting rendering at
points of interest. Mouse and keyboard events automatically generate render
requests, but the result of a WidgetTask does not.
-}
isRenderOnce :: WidgetRequest s e -> Bool
isRenderOnce RenderOnce{} = True
isRenderOnce _ = False
isRenderEvery :: WidgetRequest s e -> Bool
isRenderEvery RenderEvery{} = True
isRenderEvery _ = False
isRenderStop :: WidgetRequest s e -> Bool
isRenderStop RenderStop{} = True
isRenderStop _ = False
isRemoveRendererImage :: WidgetRequest s e -> Bool
isRemoveRendererImage RemoveRendererImage{} = True
isRemoveRendererImage _ = False
isExitApplication :: WidgetRequest s e -> Bool
isExitApplication ExitApplication{} = True
isExitApplication _ = False
isUpdateWindow :: WidgetRequest s e -> Bool
isUpdateWindow UpdateWindow{} = True
isUpdateWindow _ = False
isUpdateModel :: WidgetRequest s e -> Bool
isUpdateModel UpdateModel{} = True
isUpdateModel _ = False
|
Updates the path of a given widget . Both " . Widgets . Single " and
" Monomer . Widgets . Container " handle this automatically .
Updates the path of a given widget. Both "Monomer.Widgets.Single" and
"Monomer.Widgets.Container" handle this automatically.
-}
isSetWidgetPath :: WidgetRequest s e -> Bool
isSetWidgetPath SetWidgetPath{} = True
isSetWidgetPath _ = False
| Clears an association between widgetId and path .
isResetWidgetPath :: WidgetRequest s e -> Bool
isResetWidgetPath ResetWidgetPath{} = True
isResetWidgetPath _ = False
|
Raises a user event , which usually will be processed in handleEvent in a
" Monomer . Widgets . Composite " instance .
Raises a user event, which usually will be processed in handleEvent in a
"Monomer.Widgets.Composite" instance.
-}
isRaiseEvent :: WidgetRequest s e -> Bool
isRaiseEvent RaiseEvent{} = True
isRaiseEvent _ = False
|
Sends a message to the given widgetId . If the target does not expect the
message 's type , it will be ignored .
Sends a message to the given widgetId. If the target does not expect the
message's type, it will be ignored.
-}
isSendMessage :: WidgetRequest s e -> Bool
isSendMessage SendMessage{} = True
isSendMessage _ = False
isRunTask :: WidgetRequest s e -> Bool
isRunTask RunTask{} = True
isRunTask _ = False
|
Similar to , but can generate unlimited messages . This is useful for
WebSockets and similar data sources . It receives a function that with which to
send messages to the producer owner .
Similar to RunTask, but can generate unlimited messages. This is useful for
WebSockets and similar data sources. It receives a function that with which to
send messages to the producer owner.
-}
isRunProducer :: WidgetRequest s e -> Bool
isRunProducer RunProducer{} = True
isRunProducer _ = False
| Checks if the request is either MoveFocus or SetFocus .
isFocusRequest :: WidgetRequest s e -> Bool
isFocusRequest MoveFocus{} = True
isFocusRequest SetFocus{} = True
isFocusRequest _ = False
| Checks if the result contains a Resize request .
isResizeResult :: Maybe (WidgetResult s e) -> Bool
isResizeResult result = isJust resizeReq where
requests = maybe Empty (^. L.requests) result
resizeReq = Seq.findIndexL isResizeWidgets requests
isResizeImmediateResult :: Maybe (WidgetResult s e) -> Bool
isResizeImmediateResult result = isJust resizeReq where
requests = maybe Empty (^. L.requests) result
resizeReq = Seq.findIndexL isResizeWidgetsImmediate requests
isResizeAnyResult :: Maybe (WidgetResult s e) -> Bool
isResizeAnyResult res = isResizeResult res || isResizeImmediateResult res
isLinux :: WidgetEnv s e -> Bool
isLinux wenv = _weOs wenv == "Linux"
| Checks if the platform is macOS
isMacOS :: WidgetEnv s e -> Bool
isMacOS wenv = _weOs wenv == "Mac OS X"
| Checks if the platform is Windows
isWindows :: WidgetEnv s e -> Bool
isWindows wenv = _weOs wenv == "Windows"
|
Returns the current time in milliseconds . Adds appStartTs and timestamp fields
from ' WidgetEnv ' and converts the result to the expected ' Integral ' type .
Returns the current time in milliseconds. Adds appStartTs and timestamp fields
from 'WidgetEnv' and converts the result to the expected 'Integral' type.
-}
currentTimeMs :: Integral a => WidgetEnv s e -> a
currentTimeMs wenv = fromIntegral ts where
ts = wenv ^. L.appStartTs + wenv ^. L.timestamp
widgetTreeDesc :: Int -> WidgetNode s e -> String
widgetTreeDesc level node = desc where
desc = nodeDesc level node ++ "\n" ++ childDesc
childDesc = foldMap (widgetTreeDesc (level + 1)) (_wnChildren node)
nodeDesc :: Int -> WidgetNode s e -> String
nodeDesc level node = infoDesc (_wnInfo node) where
spaces = replicate (level * 2) ' '
infoDesc info =
spaces ++ "type: " ++ show (_wniWidgetType info) ++ "\n" ++
spaces ++ "path: " ++ show (_wniPath info) ++ "\n" ++
spaces ++ "vp: " ++ rectDesc (_wniViewport info) ++ "\n" ++
spaces ++ "req: " ++ show (_wniSizeReqW info, _wniSizeReqH info) ++ "\n"
rectDesc r = show (_rX r, _rY r, _rW r, _rH r)
widgetInstTreeDesc :: Int -> WidgetInstanceNode -> String
widgetInstTreeDesc level node = desc where
desc = nodeInstDesc level node ++ "\n" ++ childDesc
childDesc = foldMap (widgetInstTreeDesc (level + 1)) (_winChildren node)
nodeInstDesc :: Int -> WidgetInstanceNode -> String
nodeInstDesc level node = infoDesc (_winInfo node) where
spaces = replicate (level * 2) ' '
infoDesc info =
spaces ++ "type: " ++ show (_wniWidgetType info) ++ "\n" ++
spaces ++ "path: " ++ show (_wniPath info) ++ "\n" ++
spaces ++ "vp: " ++ rectDesc (_wniViewport info) ++ "\n" ++
spaces ++ "req: " ++ show (_wniSizeReqW info, _wniSizeReqH info) ++ "\n"
rectDesc r = show (_rX r, _rY r, _rW r, _rH r)
treeInstDescFromNode :: WidgetEnv s e -> Int -> WidgetNode s e -> String
treeInstDescFromNode wenv level node = widgetInstTreeDesc level nodeInst where
nodeInst = widgetGetInstanceTree (node ^. L.widget) wenv node
|
f5c3df4c420afd3bb0fd71d52b6a68066fa9f2733b2ec825fcb843cfb95f3290 | basho/riak_test | kv679_tombstone.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2014 Basho Technologies , Inc.
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
( C ) 2014 , Basho Technologies
%%% @doc
riak_test for kv679 doomstone flavour .
%%%
issue kv679 is a possible dataloss issue , it 's basically caused by
%%% the fact that per key logical clocks can go backwards in time in
%%% certain situations. The situation under test here is as follows:
%%% Create value
Delete value ( write tombstone ( including one fallback ) reap tombstone from primaries only )
%%% write new value
%%% fallback hands off and the tombstone dominates the new value.
%%% @end
-module(kv679_tombstone).
-behavior(riak_test).
-compile([export_all]).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
-define(BUCKET, <<"kv679">>).
-define(KEY, <<"test">>).
confirm() ->
Config = [{riak_core, [{ring_creation_size, 8},
{vnode_management_timer, 1000},
{handoff_concurrency, 100},
{vnode_inactivity_timeout, 1000}]}],
Nodes = rt:build_cluster(4, Config),
Clients=[P1, _P2, _P3, _P4] = create_pb_clients(Nodes),
%% Get preflist for key
PL = get_preflist(hd(Nodes)),
CoordClient = coordinating_client(Clients, PL),
%% Write key some times
write_key(CoordClient, [<<"bob">>, <<"phil">>, <<"pete">>]),
lager:info("wrote key thrice"),
%% %% take a node that is a primary down
{NewPL, DeadPrimary, _} = kill_primary(PL),
lager:info("killed a primary"),
%% %% This way a tombstone finds its way to a fallback, to later
%% %% wreak DOOM!!!!
Client = up_client(DeadPrimary, Clients),
delete_key(Client),
lager:info("deleted key, and have tombstone response"),
%% %% Take down the fallback
{NewPL2, DeadFallback, _DeadPartition} = kill_fallback(NewPL),
%% %% Bring the primary back up
_PL3 = start_node(DeadPrimary, NewPL2),
lager:info("killed the fallback, and restored the primary"),
%% %% wait for reaping maybe read for vclock ts and wait until there
% % is not one
UpClient = up_client(DeadFallback, Clients),
read_it_and_reap(UpClient),
lager:info("read repaired, and reaped the tombstone"),
%% %% write the key again, this will start a new clock, a clock
%% that is in the past of that lingering tombstone. We use the
%% same node to get the same clock.
write_key(CoordClient, [<<"jon">>]),
%% %% bring up that fallback, and wait for it to hand off
start_fallback_and_wait_for_handoff(DeadFallback),
%% Read twice, just in case (repair, reap.)
Res1 = read_key(P1),
lager:info("TS? ~p~n", [Res1]),
Res2 = read_key(P1),
lager:info("res ~p", [Res2]),
?assertMatch({ok, _}, Res2),
{ok, Obj} = Res2,
?assertEqual(<<"jon">>, riakc_obj:get_value(Obj)),
pass.
%%% Client/Key ops
create_pb_clients(Nodes) ->
[begin
C = rt:pbc(N),
riakc_pb_socket:set_options(C, [queue_if_disconnected]),
{N, C}
end || N <- Nodes].
coordinating_client(Clients, Preflist) ->
{{_, FirstPrimary}, primary} = lists:keyfind(primary, 2, Preflist),
lists:keyfind(FirstPrimary, 1, Clients).
up_client(DeadNode, Clients) ->
{value, _, LiveClients} = lists:keytake(DeadNode, 1, Clients),
hd(LiveClients).
write_key(Client, Vals) ->
write_key(Client, Vals, []).
write_key(_, [], _Opts) ->
ok;
write_key(Client, [Val | Rest], Opts) ->
ok = write_key(Client, Val, Opts),
ok = write_key(Client, Rest, Opts);
write_key({_, Client}, Val, Opts) when is_binary(Val) ->
Object = case riakc_pb_socket:get(Client, ?BUCKET, ?KEY, []) of
{ok, O1} ->
lager:info("writing existing!"),
O2 = riakc_obj:update_metadata(O1, dict:new()),
riakc_obj:update_value(O2, Val);
_ ->
lager:info("writing new!"),
riakc_obj:new(?BUCKET, ?KEY, Val)
end,
riakc_pb_socket:put(Client, Object, Opts).
read_key({_, Client}, Opts) ->
riakc_pb_socket:get(Client, ?BUCKET, ?KEY, Opts).
read_key(C) ->
read_key(C, []).
delete_key({_, Client}) ->
riakc_pb_socket:delete(Client, ?BUCKET, ?KEY),
rt:wait_until(fun() ->
case riakc_pb_socket:get(Client, ?BUCKET, ?KEY, [deletedvclock]) of
{error, notfound, VC} ->
lager:info("TSVC ~p~n", [VC]),
true;
Res ->
lager:info("no ts yet: ~p~n", [Res]),
false
end
end).
read_it_and_reap({_, Client}) ->
rt:wait_until(fun() ->
case riakc_pb_socket:get(Client, ?BUCKET, ?KEY, [deletedvclock]) of
{error, notfound} ->
true;
Res ->
lager:info("not reaped ts yet: ~p~n", [Res]),
false
end
end).
Node ops
start_node(Node, Preflist) ->
rt:start_and_wait(Node),
wait_for_new_pl(Preflist, Node).
get_preflist(Node) ->
get_preflist(Node, 3).
get_preflist(Node, NVal) ->
Chash = rpc:call(Node, riak_core_util, chash_key, [{?BUCKET, ?KEY}]),
UpNodes = rpc:call(Node, riak_core_node_watcher, nodes, [riak_kv]),
PL = rpc:call(Node, riak_core_apl, get_apl_ann, [Chash, NVal, UpNodes]),
PL.
kill_primary(Preflist) ->
kill_and_wait(Preflist, primary).
kill_fallback(Preflist) ->
kill_and_wait(Preflist, fallback).
kill_and_wait(Preflist, Type) ->
case lists:keytake(Type, 2, Preflist) of
false ->
erlang:error(no_nodes_of_type, [Type, Preflist]);
{value, {{Idx, Node}, Type}, PL2} ->
kill_node(Node),
lager:info("killed ~p~n", [Node]),
[{{_, N2}, _}|_] = PL2,
{wait_for_new_pl(Preflist, N2), Node, Idx}
end.
kill_node(Node) ->
rt:stop_and_wait(Node).
wait_for_new_pl(PL, Node) ->
rt:wait_until(fun() ->
NewPL = get_preflist(Node),
lager:info("new ~p~n old ~p~nNode ~p~n", [NewPL, PL, Node]),
NewPL /= PL
end),
get_preflist(Node).
start_fallback_and_wait_for_handoff(DeadFallback) ->
%% Below is random voodoo shit as I have no idea how to _KNOW_ that handoff has happened
whatver , it takes 2 minutes , force_handoff ? 2 minutes son !
rt:start_and_wait(DeadFallback),
rpc:call(DeadFallback, riak_core_vnode_manager, force_handoffs, []),
rt:wait_until_transfers_complete([DeadFallback]).
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/kv679_tombstone.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc
the fact that per key logical clocks can go backwards in time in
certain situations. The situation under test here is as follows:
Create value
write new value
fallback hands off and the tombstone dominates the new value.
@end
Get preflist for key
Write key some times
%% take a node that is a primary down
%% This way a tombstone finds its way to a fallback, to later
%% wreak DOOM!!!!
%% Take down the fallback
%% Bring the primary back up
%% wait for reaping maybe read for vclock ts and wait until there
% is not one
%% write the key again, this will start a new clock, a clock
that is in the past of that lingering tombstone. We use the
same node to get the same clock.
%% bring up that fallback, and wait for it to hand off
Read twice, just in case (repair, reap.)
Client/Key ops
Below is random voodoo shit as I have no idea how to _KNOW_ that handoff has happened | Copyright ( c ) 2014 Basho Technologies , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
( C ) 2014 , Basho Technologies
riak_test for kv679 doomstone flavour .
issue kv679 is a possible dataloss issue , it 's basically caused by
Delete value ( write tombstone ( including one fallback ) reap tombstone from primaries only )
-module(kv679_tombstone).
-behavior(riak_test).
-compile([export_all]).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
-define(BUCKET, <<"kv679">>).
-define(KEY, <<"test">>).
confirm() ->
Config = [{riak_core, [{ring_creation_size, 8},
{vnode_management_timer, 1000},
{handoff_concurrency, 100},
{vnode_inactivity_timeout, 1000}]}],
Nodes = rt:build_cluster(4, Config),
Clients=[P1, _P2, _P3, _P4] = create_pb_clients(Nodes),
PL = get_preflist(hd(Nodes)),
CoordClient = coordinating_client(Clients, PL),
write_key(CoordClient, [<<"bob">>, <<"phil">>, <<"pete">>]),
lager:info("wrote key thrice"),
{NewPL, DeadPrimary, _} = kill_primary(PL),
lager:info("killed a primary"),
Client = up_client(DeadPrimary, Clients),
delete_key(Client),
lager:info("deleted key, and have tombstone response"),
{NewPL2, DeadFallback, _DeadPartition} = kill_fallback(NewPL),
_PL3 = start_node(DeadPrimary, NewPL2),
lager:info("killed the fallback, and restored the primary"),
UpClient = up_client(DeadFallback, Clients),
read_it_and_reap(UpClient),
lager:info("read repaired, and reaped the tombstone"),
write_key(CoordClient, [<<"jon">>]),
start_fallback_and_wait_for_handoff(DeadFallback),
Res1 = read_key(P1),
lager:info("TS? ~p~n", [Res1]),
Res2 = read_key(P1),
lager:info("res ~p", [Res2]),
?assertMatch({ok, _}, Res2),
{ok, Obj} = Res2,
?assertEqual(<<"jon">>, riakc_obj:get_value(Obj)),
pass.
create_pb_clients(Nodes) ->
[begin
C = rt:pbc(N),
riakc_pb_socket:set_options(C, [queue_if_disconnected]),
{N, C}
end || N <- Nodes].
coordinating_client(Clients, Preflist) ->
{{_, FirstPrimary}, primary} = lists:keyfind(primary, 2, Preflist),
lists:keyfind(FirstPrimary, 1, Clients).
up_client(DeadNode, Clients) ->
{value, _, LiveClients} = lists:keytake(DeadNode, 1, Clients),
hd(LiveClients).
write_key(Client, Vals) ->
write_key(Client, Vals, []).
write_key(_, [], _Opts) ->
ok;
write_key(Client, [Val | Rest], Opts) ->
ok = write_key(Client, Val, Opts),
ok = write_key(Client, Rest, Opts);
write_key({_, Client}, Val, Opts) when is_binary(Val) ->
Object = case riakc_pb_socket:get(Client, ?BUCKET, ?KEY, []) of
{ok, O1} ->
lager:info("writing existing!"),
O2 = riakc_obj:update_metadata(O1, dict:new()),
riakc_obj:update_value(O2, Val);
_ ->
lager:info("writing new!"),
riakc_obj:new(?BUCKET, ?KEY, Val)
end,
riakc_pb_socket:put(Client, Object, Opts).
read_key({_, Client}, Opts) ->
riakc_pb_socket:get(Client, ?BUCKET, ?KEY, Opts).
read_key(C) ->
read_key(C, []).
delete_key({_, Client}) ->
riakc_pb_socket:delete(Client, ?BUCKET, ?KEY),
rt:wait_until(fun() ->
case riakc_pb_socket:get(Client, ?BUCKET, ?KEY, [deletedvclock]) of
{error, notfound, VC} ->
lager:info("TSVC ~p~n", [VC]),
true;
Res ->
lager:info("no ts yet: ~p~n", [Res]),
false
end
end).
read_it_and_reap({_, Client}) ->
rt:wait_until(fun() ->
case riakc_pb_socket:get(Client, ?BUCKET, ?KEY, [deletedvclock]) of
{error, notfound} ->
true;
Res ->
lager:info("not reaped ts yet: ~p~n", [Res]),
false
end
end).
Node ops
start_node(Node, Preflist) ->
rt:start_and_wait(Node),
wait_for_new_pl(Preflist, Node).
get_preflist(Node) ->
get_preflist(Node, 3).
get_preflist(Node, NVal) ->
Chash = rpc:call(Node, riak_core_util, chash_key, [{?BUCKET, ?KEY}]),
UpNodes = rpc:call(Node, riak_core_node_watcher, nodes, [riak_kv]),
PL = rpc:call(Node, riak_core_apl, get_apl_ann, [Chash, NVal, UpNodes]),
PL.
kill_primary(Preflist) ->
kill_and_wait(Preflist, primary).
kill_fallback(Preflist) ->
kill_and_wait(Preflist, fallback).
kill_and_wait(Preflist, Type) ->
case lists:keytake(Type, 2, Preflist) of
false ->
erlang:error(no_nodes_of_type, [Type, Preflist]);
{value, {{Idx, Node}, Type}, PL2} ->
kill_node(Node),
lager:info("killed ~p~n", [Node]),
[{{_, N2}, _}|_] = PL2,
{wait_for_new_pl(Preflist, N2), Node, Idx}
end.
kill_node(Node) ->
rt:stop_and_wait(Node).
wait_for_new_pl(PL, Node) ->
rt:wait_until(fun() ->
NewPL = get_preflist(Node),
lager:info("new ~p~n old ~p~nNode ~p~n", [NewPL, PL, Node]),
NewPL /= PL
end),
get_preflist(Node).
start_fallback_and_wait_for_handoff(DeadFallback) ->
whatver , it takes 2 minutes , force_handoff ? 2 minutes son !
rt:start_and_wait(DeadFallback),
rpc:call(DeadFallback, riak_core_vnode_manager, force_handoffs, []),
rt:wait_until_transfers_complete([DeadFallback]).
|
98639a5801191ff751a55f3cedbe2f8121c9e48e8d1297ccf6122c342d4105a5 | Dimercel/listopia | searching-lists.lisp | (defpackage listopia-bench.searching-lists
(:use :cl
:prove
:listopia-bench.utils)
(:import-from :listopia
:elem
:not-elem
:filter
:partition)
(:shadowing-import-from :listopia :find))
(in-package :listopia-bench.searching-lists)
(plan nil)
(ok (bench "elem"
(elem 1 '(1 2 3))))
(ok (bench "not-elem"
(not-elem 1 '(2 3 4))))
(ok (bench "find"
(find #'numberp '(:foo :bar 1))))
(ok (bench "filter"
(filter #'numberp '(:foo 1 :bar 2))))
(ok (bench "partition"
(partition #'numberp '(:foo 1 :bar 2))))
(finalize)
| null | https://raw.githubusercontent.com/Dimercel/listopia/2d2a1a3c35580252ca0085e15ebf625f73230d60/bench/searching-lists.lisp | lisp | (defpackage listopia-bench.searching-lists
(:use :cl
:prove
:listopia-bench.utils)
(:import-from :listopia
:elem
:not-elem
:filter
:partition)
(:shadowing-import-from :listopia :find))
(in-package :listopia-bench.searching-lists)
(plan nil)
(ok (bench "elem"
(elem 1 '(1 2 3))))
(ok (bench "not-elem"
(not-elem 1 '(2 3 4))))
(ok (bench "find"
(find #'numberp '(:foo :bar 1))))
(ok (bench "filter"
(filter #'numberp '(:foo 1 :bar 2))))
(ok (bench "partition"
(partition #'numberp '(:foo 1 :bar 2))))
(finalize)
| |
b1c858ea73e7bb9f95687e1f132cf967dd63f8547a16df1601bc42daf11cd468 | CindyLinz/Haskell.js | ForgetL.hs | module ForgetL where
import Data.Functor
forgetL :: Functor f => f a -> f ()
forgetL = fmap (const ())
| null | https://raw.githubusercontent.com/CindyLinz/Haskell.js/78429a49181a15f6bdae426f17bdae722ad17141/trans/src/ForgetL.hs | haskell | module ForgetL where
import Data.Functor
forgetL :: Functor f => f a -> f ()
forgetL = fmap (const ())
| |
6e687b555f92e4d0b00455454c1604136fe55dc8d0f3810c865a04b771c5ba53 | apache/couchdb-ddoc-cache | ddoc_cache_app.erl | 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(ddoc_cache_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
ddoc_cache_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/apache/couchdb-ddoc-cache/c762e90a33ce3cda19ef142dd1120f1087ecd876/src/ddoc_cache_app.erl | erlang | 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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(ddoc_cache_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
ddoc_cache_sup:start_link().
stop(_State) ->
ok.
|
1054a15e86dfe4a4e163dd9332951ba4f243b7d21651a5e175462980b48fa848 | jqueiroz/lojban.io | Home.hs | {-# LANGUAGE OverloadedStrings #-}
module Server.Website.Views.Home
( displayHome
) where
import Core
import Server.Core
import Server.Website.Views.Core
import qualified Data.Text as T
import qualified Text.Blaze as B
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Study.Courses.English.Grammar.Introduction.Course
import qualified Study.Courses.English.Grammar.Crash.Course
import qualified Study.Courses.English.Vocabulary.Attitudinals.Course
import qualified Study . Courses . English . Vocabulary . Brivla . Course
import qualified Study.Decks.English.ContextualizedBrivla
TODO : link to official lojban wiki
-- TODO: take more info from this brochure:
TODO : also link to
displayHome :: ServerConfiguration -> Maybe UserIdentity -> H.Html
displayHome serverConfiguration userIdentityMaybe = do
let shortDescription = "A free and open-source platform for studying the artificial language Lojban."
H.docType
H.html B.! A.lang (H.stringValue "en-us") $ do
H.head $ do
H.title $ H.toHtml ("lojban.io" :: T.Text)
H.meta B.! A.name (H.textValue "description") B.! A.content (H.textValue shortDescription)
includeUniversalStylesheets
includeUniversalScripts
includeInternalStylesheet "home.css"
includeInternalScript "home-min.js"
H.body $ do
displayTopbar serverConfiguration userIdentityMaybe TopbarHome
H.div B.! A.class_ (H.textValue "main") $ do
H.div B.! A.class_ (H.textValue "body") $ do
H.div B.! A.class_ (H.textValue "welcome") $ do
displayWelcome2
H.div B.! A.class_ (H.textValue "courses") $ do
H.h2 $ H.toHtml ("Courses" :: T.Text)
H.div B.! A.class_ (H.textValue "carousel") $ do
H.div B.! A.class_ (H.textValue "previous") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_before" :: T.Text)
H.ul $ do
displayCourse ("/courses/introduction", Study.Courses.English.Grammar.Introduction.Course.course)
( " /courses / crash " , Study.Courses.English.Grammar.Crash.Course.course )
( " /courses / attitudinals " , Study.Courses.English.Vocabulary.Attitudinals.Course.course )
( " /courses / brivla " , Study.Courses.English.Vocabulary.Brivla.Course.course )
H.div B.! A.class_ (H.textValue "next") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_next" :: T.Text)
H.div B.! A.class_ (H.textValue "decks") $ do
H.h2 $ H.toHtml ("Decks" :: T.Text)
H.div B.! A.class_ (H.textValue "carousel") $ do
H.div B.! A.class_ (H.textValue "previous") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_before" :: T.Text)
H.ul $ do
displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
--displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
--displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
--displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
H.div B.! A.class_ (H.textValue "next") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_next" :: T.Text)
displayFooter
displayWelcome1 :: H.Html
displayWelcome1 = do
displayWhat
displayWhy
displayLearn
displayWelcome2 :: H.Html
displayWelcome2 = do
displaySpeak
displayWhy
TODO : url to official lojban website ( with " external website " icon )
displaySpeak :: H.Html
displaySpeak = do
H.div B.! A.class_ (H.textValue "speak-lojban") $ do
H.h1 $ do
H.span B.! A.class_ (H.textValue "speak") $ H.toHtml ("Speak " :: T.Text)
H.span B.! A.class_ (H.textValue "logically") $ H.toHtml ("logically" :: T.Text)
H.p $ H.toHtml ("Lojban is a carefully constructed spoken language. It has been built for over 50 years by dozens of workers and hundreds of supporters." :: T.Text)
H.p $ H.toHtml ("Lojban's grammar is based on simple rules, and its linguistic features are inspired by predicate logic." :: T.Text)
H.div B.! A.class_ (H.textValue "buttons") $ do
H.a (H.toHtml ("Courses" :: T.Text))
B.! A.href (H.textValue "/courses")
H.a (H.toHtml ("Decks" :: T.Text))
B.! A.href (H.textValue "/decks")
displayWhat :: H.Html
displayWhat = do
H.div B.! A.class_ (H.textValue "what-lojban") $ do
H.h1 $ H.toHtml ("What is Lojban?" :: T.Text)
H.p $ H.toHtml ("Lojban is a carefully constructed spoken language. It has been built for over 50 years by dozens of workers and hundreds of supporters." :: T.Text)
H.p $ H.toHtml ("Lojban's grammar is based on simple rules, and its linguistic features are inspired by predicate logic." :: T.Text)
displayWhy :: H.Html
displayWhy = do
H.div B.! A.class_ (H.textValue "why-lojban") $ do
H.h1 $ H.toHtml ("Why lojban?" :: T.Text)
H.p $ H.toHtml ("Lojban means different things to different people:" :: T.Text)
H.ul $ do
H.li $ H.toHtml ("a new perspective on languages;" :: T.Text)
H.li $ H.toHtml ("a challenging way to expand their minds or discipline their thoughts;" :: T.Text)
H.li $ H.toHtml ("an entertaining medium to communicate with friends or create art;" :: T.Text)
H.li $ H.toHtml ("a linguistic curiosity – a test-bed for language experimentation;" :: T.Text)
H.li $ H.toHtml ("a domain for exploring the intersection of human language and software." :: T.Text)
H.p $ H.toHtml ( " What will Lojban mean for you ? " : : T.Text )
H.a (H.toHtml ("Find out more" :: T.Text))
B.! A.href (H.textValue "")
B.! A.class_ (H.textValue "external")
H.a (H.toHtml ("Join the community Discord server" :: T.Text))
B.! A.href ""
B.! A.class_ (H.textValue "discord")
displayLearn :: H.Html
displayLearn = do
H.div B.! A.class_ (H.textValue "learn-logically") $ do
H.h1 $ do
H.span B.! A.class_ (H.textValue "learn") $ H.toHtml ("Learn " :: T.Text)
H.span B.! A.class_ (H.textValue "logically") $ H.toHtml ("logically" :: T.Text)
H.p $ H.toHtml ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor." :: String)
H.div B.! A.class_ (H.textValue "buttons") $ do
H.a (H.toHtml ("Courses" :: T.Text))
B.! A.href (H.textValue "/courses")
H.a (H.toHtml ("Decks" :: T.Text))
B.! A.href (H.textValue "/decks")
displayCourse :: (T.Text, Course) -> H.Html
displayCourse (url, course) = do
let title = courseTitle course
let shortDescription = courseShortDescription course
let linkText = "Learn more" :: T.Text
H.li B.! A.class_ (H.textValue "course") $ do
H.div B.! A.class_ (H.textValue "course-title") $ H.toHtml title
H.div B.! A.class_ (H.textValue "course-description") $ H.toHtml shortDescription
H.div B.! A.class_ (H.textValue "course-link") $ do
H.a B.! A.href (H.textValue url) $ H.toHtml linkText
displayDeck :: (T.Text, Deck) -> H.Html
displayDeck (url, course) = do
let title = deckTitle course
let shortDescription = deckShortDescription course
let linkText = "Learn more" :: T.Text
H.li B.! A.class_ (H.textValue "deck") $ do
H.div B.! A.class_ (H.textValue "deck-title") $ H.toHtml title
H.div B.! A.class_ (H.textValue "deck-description") $ H.toHtml shortDescription
H.div B.! A.class_ (H.textValue "deck-link") $ do
H.a B.! A.href (H.textValue url) $ H.toHtml linkText
| null | https://raw.githubusercontent.com/jqueiroz/lojban.io/68c3e919f92ea1294f32ee7772662ab5667ecef6/haskell/src/Server/Website/Views/Home.hs | haskell | # LANGUAGE OverloadedStrings #
TODO: take more info from this brochure:
displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck) |
module Server.Website.Views.Home
( displayHome
) where
import Core
import Server.Core
import Server.Website.Views.Core
import qualified Data.Text as T
import qualified Text.Blaze as B
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Study.Courses.English.Grammar.Introduction.Course
import qualified Study.Courses.English.Grammar.Crash.Course
import qualified Study.Courses.English.Vocabulary.Attitudinals.Course
import qualified Study . Courses . English . Vocabulary . Brivla . Course
import qualified Study.Decks.English.ContextualizedBrivla
TODO : link to official lojban wiki
TODO : also link to
displayHome :: ServerConfiguration -> Maybe UserIdentity -> H.Html
displayHome serverConfiguration userIdentityMaybe = do
let shortDescription = "A free and open-source platform for studying the artificial language Lojban."
H.docType
H.html B.! A.lang (H.stringValue "en-us") $ do
H.head $ do
H.title $ H.toHtml ("lojban.io" :: T.Text)
H.meta B.! A.name (H.textValue "description") B.! A.content (H.textValue shortDescription)
includeUniversalStylesheets
includeUniversalScripts
includeInternalStylesheet "home.css"
includeInternalScript "home-min.js"
H.body $ do
displayTopbar serverConfiguration userIdentityMaybe TopbarHome
H.div B.! A.class_ (H.textValue "main") $ do
H.div B.! A.class_ (H.textValue "body") $ do
H.div B.! A.class_ (H.textValue "welcome") $ do
displayWelcome2
H.div B.! A.class_ (H.textValue "courses") $ do
H.h2 $ H.toHtml ("Courses" :: T.Text)
H.div B.! A.class_ (H.textValue "carousel") $ do
H.div B.! A.class_ (H.textValue "previous") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_before" :: T.Text)
H.ul $ do
displayCourse ("/courses/introduction", Study.Courses.English.Grammar.Introduction.Course.course)
( " /courses / crash " , Study.Courses.English.Grammar.Crash.Course.course )
( " /courses / attitudinals " , Study.Courses.English.Vocabulary.Attitudinals.Course.course )
( " /courses / brivla " , Study.Courses.English.Vocabulary.Brivla.Course.course )
H.div B.! A.class_ (H.textValue "next") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_next" :: T.Text)
H.div B.! A.class_ (H.textValue "decks") $ do
H.h2 $ H.toHtml ("Decks" :: T.Text)
H.div B.! A.class_ (H.textValue "carousel") $ do
H.div B.! A.class_ (H.textValue "previous") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_before" :: T.Text)
H.ul $ do
displayDeck ("/decks/contextualized-brivla", Study.Decks.English.ContextualizedBrivla.deck)
H.div B.! A.class_ (H.textValue "next") $ do
H.span B.! A.class_ (H.textValue "material-icons") $ H.toHtml ("navigate_next" :: T.Text)
displayFooter
displayWelcome1 :: H.Html
displayWelcome1 = do
displayWhat
displayWhy
displayLearn
displayWelcome2 :: H.Html
displayWelcome2 = do
displaySpeak
displayWhy
TODO : url to official lojban website ( with " external website " icon )
displaySpeak :: H.Html
displaySpeak = do
H.div B.! A.class_ (H.textValue "speak-lojban") $ do
H.h1 $ do
H.span B.! A.class_ (H.textValue "speak") $ H.toHtml ("Speak " :: T.Text)
H.span B.! A.class_ (H.textValue "logically") $ H.toHtml ("logically" :: T.Text)
H.p $ H.toHtml ("Lojban is a carefully constructed spoken language. It has been built for over 50 years by dozens of workers and hundreds of supporters." :: T.Text)
H.p $ H.toHtml ("Lojban's grammar is based on simple rules, and its linguistic features are inspired by predicate logic." :: T.Text)
H.div B.! A.class_ (H.textValue "buttons") $ do
H.a (H.toHtml ("Courses" :: T.Text))
B.! A.href (H.textValue "/courses")
H.a (H.toHtml ("Decks" :: T.Text))
B.! A.href (H.textValue "/decks")
displayWhat :: H.Html
displayWhat = do
H.div B.! A.class_ (H.textValue "what-lojban") $ do
H.h1 $ H.toHtml ("What is Lojban?" :: T.Text)
H.p $ H.toHtml ("Lojban is a carefully constructed spoken language. It has been built for over 50 years by dozens of workers and hundreds of supporters." :: T.Text)
H.p $ H.toHtml ("Lojban's grammar is based on simple rules, and its linguistic features are inspired by predicate logic." :: T.Text)
displayWhy :: H.Html
displayWhy = do
H.div B.! A.class_ (H.textValue "why-lojban") $ do
H.h1 $ H.toHtml ("Why lojban?" :: T.Text)
H.p $ H.toHtml ("Lojban means different things to different people:" :: T.Text)
H.ul $ do
H.li $ H.toHtml ("a new perspective on languages;" :: T.Text)
H.li $ H.toHtml ("a challenging way to expand their minds or discipline their thoughts;" :: T.Text)
H.li $ H.toHtml ("an entertaining medium to communicate with friends or create art;" :: T.Text)
H.li $ H.toHtml ("a linguistic curiosity – a test-bed for language experimentation;" :: T.Text)
H.li $ H.toHtml ("a domain for exploring the intersection of human language and software." :: T.Text)
H.p $ H.toHtml ( " What will Lojban mean for you ? " : : T.Text )
H.a (H.toHtml ("Find out more" :: T.Text))
B.! A.href (H.textValue "")
B.! A.class_ (H.textValue "external")
H.a (H.toHtml ("Join the community Discord server" :: T.Text))
B.! A.href ""
B.! A.class_ (H.textValue "discord")
displayLearn :: H.Html
displayLearn = do
H.div B.! A.class_ (H.textValue "learn-logically") $ do
H.h1 $ do
H.span B.! A.class_ (H.textValue "learn") $ H.toHtml ("Learn " :: T.Text)
H.span B.! A.class_ (H.textValue "logically") $ H.toHtml ("logically" :: T.Text)
H.p $ H.toHtml ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor." :: String)
H.div B.! A.class_ (H.textValue "buttons") $ do
H.a (H.toHtml ("Courses" :: T.Text))
B.! A.href (H.textValue "/courses")
H.a (H.toHtml ("Decks" :: T.Text))
B.! A.href (H.textValue "/decks")
displayCourse :: (T.Text, Course) -> H.Html
displayCourse (url, course) = do
let title = courseTitle course
let shortDescription = courseShortDescription course
let linkText = "Learn more" :: T.Text
H.li B.! A.class_ (H.textValue "course") $ do
H.div B.! A.class_ (H.textValue "course-title") $ H.toHtml title
H.div B.! A.class_ (H.textValue "course-description") $ H.toHtml shortDescription
H.div B.! A.class_ (H.textValue "course-link") $ do
H.a B.! A.href (H.textValue url) $ H.toHtml linkText
displayDeck :: (T.Text, Deck) -> H.Html
displayDeck (url, course) = do
let title = deckTitle course
let shortDescription = deckShortDescription course
let linkText = "Learn more" :: T.Text
H.li B.! A.class_ (H.textValue "deck") $ do
H.div B.! A.class_ (H.textValue "deck-title") $ H.toHtml title
H.div B.! A.class_ (H.textValue "deck-description") $ H.toHtml shortDescription
H.div B.! A.class_ (H.textValue "deck-link") $ do
H.a B.! A.href (H.textValue url) $ H.toHtml linkText
|
c41a6862ccd532c71bf7a4249676fd5fc20661d867d7e0b50733b75ae01a0a54 | xsc/claro | transform.clj | (ns claro.data.transform
(:require [claro.data.protocols :as p]))
(defmacro ^{:added "0.2.7"} extend-list-transform
"Implement the [[Transform]] protocol for the given `resolvable-class`,
assuming it returns a seq of elements to-be-processed with
`element-constructor`.
```clojure
(extend-list-transform
PeopleByLocation
[->Person])
```
This is equivalent to:
```clojure
(extend-protocol claro.data/Transform
PeopleByLocation
(transform [_ results]
(mapv ->Person results)))
```
It's also possible to supply extra parameters to be passed to the element
constructor, e.g.:
```clojure
(extend-list-transform
PeopleByLocation
[->Person {:by :location}])
```
This will call `(->Person element {:by :location})` on each element."
([resolvable-class [element-constructor & args]]
{:pre [resolvable-class element-constructor]}
`(let [constructor# #(~element-constructor % ~@args)]
(extend-protocol p/Transform
~resolvable-class
(~'transform [_# elements#]
(mapv constructor# elements#)))))
([resolvable-class element-constructor & more]
`(do
(extend-list-transform ~resolvable-class ~element-constructor)
(extend-list-transform ~@more))))
(defmacro ^{:added "0.2.7"} extend-transform
"Implement the [[Transform]] protocol for the given `resolvable-class` by
transforming/renaming fields according to a given field spec.
```clojure
(extend-transform
Person
{:pet [->Pet :pet-id]
:location (fn [{:keys [latitude longitude]}]
(->Location latitude longitude))
:name :username})
```
This will:
- create `:pet` as `(->Pet (:pet-id result))`,
- create `:location` as the result of the given function, and
- copy `:username` to `:name`.
All these take the resolution result (!) as input but will not alter `nil`
values."
([resolvable-class fields]
{:pre [resolvable-class (map? fields)]}
(letfn [(->fn [[field-key value]]
(let [result (gensym "result")]
(cond (vector? value)
(let [[f & fields] value]
`(fn [~result]
(assoc ~result
~field-key
(~f ~@(map #(list % result) fields)))))
(keyword? value)
`(fn [~result]
(assoc ~result
~field-key
(get ~result ~value)))
:else
`(let [f# ~value]
(fn [~result]
(assoc ~result
~field-key
(f# ~result)))))))]
`(let [transform# (comp ~@(map ->fn fields))]
(extend-protocol p/Transform
~resolvable-class
(~'transform [_# result#]
(some-> result# transform#))))))
([resolvable-class fields & more]
`(do
(extend-transform ~resolvable-class ~fields)
(extend-transform ~@more))))
| null | https://raw.githubusercontent.com/xsc/claro/16db75b7a775a14f3b656362e8ee4f65dd8b0d49/src/claro/data/transform.clj | clojure | (ns claro.data.transform
(:require [claro.data.protocols :as p]))
(defmacro ^{:added "0.2.7"} extend-list-transform
"Implement the [[Transform]] protocol for the given `resolvable-class`,
assuming it returns a seq of elements to-be-processed with
`element-constructor`.
```clojure
(extend-list-transform
PeopleByLocation
[->Person])
```
This is equivalent to:
```clojure
(extend-protocol claro.data/Transform
PeopleByLocation
(transform [_ results]
(mapv ->Person results)))
```
It's also possible to supply extra parameters to be passed to the element
constructor, e.g.:
```clojure
(extend-list-transform
PeopleByLocation
[->Person {:by :location}])
```
This will call `(->Person element {:by :location})` on each element."
([resolvable-class [element-constructor & args]]
{:pre [resolvable-class element-constructor]}
`(let [constructor# #(~element-constructor % ~@args)]
(extend-protocol p/Transform
~resolvable-class
(~'transform [_# elements#]
(mapv constructor# elements#)))))
([resolvable-class element-constructor & more]
`(do
(extend-list-transform ~resolvable-class ~element-constructor)
(extend-list-transform ~@more))))
(defmacro ^{:added "0.2.7"} extend-transform
"Implement the [[Transform]] protocol for the given `resolvable-class` by
transforming/renaming fields according to a given field spec.
```clojure
(extend-transform
Person
{:pet [->Pet :pet-id]
:location (fn [{:keys [latitude longitude]}]
(->Location latitude longitude))
:name :username})
```
This will:
- create `:pet` as `(->Pet (:pet-id result))`,
- create `:location` as the result of the given function, and
- copy `:username` to `:name`.
All these take the resolution result (!) as input but will not alter `nil`
values."
([resolvable-class fields]
{:pre [resolvable-class (map? fields)]}
(letfn [(->fn [[field-key value]]
(let [result (gensym "result")]
(cond (vector? value)
(let [[f & fields] value]
`(fn [~result]
(assoc ~result
~field-key
(~f ~@(map #(list % result) fields)))))
(keyword? value)
`(fn [~result]
(assoc ~result
~field-key
(get ~result ~value)))
:else
`(let [f# ~value]
(fn [~result]
(assoc ~result
~field-key
(f# ~result)))))))]
`(let [transform# (comp ~@(map ->fn fields))]
(extend-protocol p/Transform
~resolvable-class
(~'transform [_# result#]
(some-> result# transform#))))))
([resolvable-class fields & more]
`(do
(extend-transform ~resolvable-class ~fields)
(extend-transform ~@more))))
| |
1d13f04d67919cb87198e90447e619699cb5df79f56c421f13dd353376c074f9 | ros/roslisp_common | package.lisp | (in-package :cl-user)
(defpackage :actionlib-test
(:use :cl :lisp-unit :roslisp :actionlib-lisp)) | null | https://raw.githubusercontent.com/ros/roslisp_common/4db311da26497d84a147f190200e50c7a5b4106e/actionlib_lisp/test/package.lisp | lisp | (in-package :cl-user)
(defpackage :actionlib-test
(:use :cl :lisp-unit :roslisp :actionlib-lisp)) | |
7eb0f85ff08dce1af731fe56504b37d548cb84b848c29499b65e280fe67f9a3b | ulricha/dsh | DSH.hs | -- | This module is intended to be imported @qualified@, to avoid name clashes
with " Prelude " functions . For example :
--
> import qualified Database . DSH as Q
> import Database . DSH ( Q )
--
Alternatively you can hide " Prelude " and import this module like this :
--
> import Prelude ( )
> import Database . DSH
--
-- In this case you still get Prelude definitions that are not provided
by Database . DSH .
module Database.DSH
( module Database.DSH.Frontend.Externals
, Q, QA, TA, Elim, elim, View, view, Key(..), TableHints(..), Emptiness(..)
, module Database.DSH.Frontend.TH
, module Data.String
, module Data.Text
, module Data.Decimal
, module Data.Time.Calendar
, module Prelude
) where
import Database.DSH.Frontend.Externals
import Database.DSH.Frontend.Internals (Q,QA,TA,Elim,elim,View,view,Key(..),TableHints(..), Emptiness(..))
import Database.DSH.Frontend.TH
import Data.String (IsString,fromString)
import Data.Text (Text)
import Data.Decimal (Decimal)
import Data.Time.Calendar (Day)
import Prelude hiding (
not
, (&&)
, (||)
, (==) , (/=)
, (<)
, (<=)
, (>=)
, (>)
, (++)
, mod
, min
, max
, head
, tail
, take
, drop
, map
, filter
, last
, init
, null
, length
, (!!)
, (++)
, reverse
, and
, or
, any
, all
, sum
, concat
, concatMap
, maximum
, minimum
, splitAt
, takeWhile
, dropWhile
, span
, break
, elem
, notElem
, lookup
, zip
, zipWith
, unzip
, zip3
, zipWith3
, unzip3
, fst
, snd
, maybe
, either
, return
, (>>=)
, (>>)
, quot
, rem
)
| null | https://raw.githubusercontent.com/ulricha/dsh/e6cd5c6bea575e62a381e89bfc4cc7cb97485106/src/Database/DSH.hs | haskell | | This module is intended to be imported @qualified@, to avoid name clashes
In this case you still get Prelude definitions that are not provided | with " Prelude " functions . For example :
> import qualified Database . DSH as Q
> import Database . DSH ( Q )
Alternatively you can hide " Prelude " and import this module like this :
> import Prelude ( )
> import Database . DSH
by Database . DSH .
module Database.DSH
( module Database.DSH.Frontend.Externals
, Q, QA, TA, Elim, elim, View, view, Key(..), TableHints(..), Emptiness(..)
, module Database.DSH.Frontend.TH
, module Data.String
, module Data.Text
, module Data.Decimal
, module Data.Time.Calendar
, module Prelude
) where
import Database.DSH.Frontend.Externals
import Database.DSH.Frontend.Internals (Q,QA,TA,Elim,elim,View,view,Key(..),TableHints(..), Emptiness(..))
import Database.DSH.Frontend.TH
import Data.String (IsString,fromString)
import Data.Text (Text)
import Data.Decimal (Decimal)
import Data.Time.Calendar (Day)
import Prelude hiding (
not
, (&&)
, (||)
, (==) , (/=)
, (<)
, (<=)
, (>=)
, (>)
, (++)
, mod
, min
, max
, head
, tail
, take
, drop
, map
, filter
, last
, init
, null
, length
, (!!)
, (++)
, reverse
, and
, or
, any
, all
, sum
, concat
, concatMap
, maximum
, minimum
, splitAt
, takeWhile
, dropWhile
, span
, break
, elem
, notElem
, lookup
, zip
, zipWith
, unzip
, zip3
, zipWith3
, unzip3
, fst
, snd
, maybe
, either
, return
, (>>=)
, (>>)
, quot
, rem
)
|
158df266faa188f8a9ebb0a632f9b2c2fea94a99719ea6f1a055f107843a5a70 | blindglobe/clocc | streams.lisp | ;;; based on v1.6 -*- mode: lisp -*-
(in-package :cl-user)
#+xcl
(check-for-bug :streams-legacy-5
(progn (in-package :sys) t)
t)
#-(or akcl allegro)
(check-for-bug :streams-legacy-10
(prin1-to-string (make-broadcast-stream))
#+xcl "#<%TYPE-STRUCTURE-STREAM NIL>"
#+clisp "#<OUTPUT BROADCAST-STREAM>"
#+(or cmu sbcl) "#<Broadcast Stream>"
#+ecls "#<broadcast stream 8>"
#-(or xcl clisp akcl allegro cmu sbcl ecls) unknown)
(check-for-bug :streams-legacy-18
(progn (setq s1 (open "d1.plc" :direction :output))
(setq s2 (open "d2.plc" :direction :output))
(setq s3 (open "d3.plc" :direction :output))
(setq b1 (make-broadcast-stream s1 s2 s3 *standard-output*)) t)
t)
(check-for-bug :streams-legacy-25
(print "test broadcast satz 1" b1)
"test broadcast satz 1")
(check-for-bug :streams-legacy-29
(print "test broadcast satz 2" b1)
"test broadcast satz 2")
(check-for-bug :streams-legacy-33
(print "test broadcast satz 3" b1)
"test broadcast satz 3")
;; CLOSE should not delete information about
;; element type, direction, and external format
(defun close-1 (s)
(let* ((i (input-stream-p s))
(o (output-stream-p s))
(e (stream-element-type s))
(f (stream-external-format s))
(c (close s)))
(and (eq i (input-stream-p s))
(eq o (output-stream-p s))
(equal e (stream-element-type s))
(equal f (stream-external-format s))
c)))
(check-for-bug :streams-legacy-37
(close-1 s1)
t)
(check-for-bug :streams-legacy-41
(close-1 s2)
t)
(check-for-bug :streams-legacy-45
(close-1 s3)
t)
(check-for-bug :streams-legacy-49
(progn (setq s (open "d1.plc")) t)
t)
(check-for-bug :streams-legacy-53
(read s)
"test broadcast satz 1")
(check-for-bug :streams-legacy-57
(read s)
"test broadcast satz 2")
(check-for-bug :streams-legacy-61
(read s)
"test broadcast satz 3")
(check-for-bug :streams-legacy-65
(close-1 s)
t)
(check-for-bug :streams-legacy-69
(progn (setq s (open "d2.plc")) t)
t)
(check-for-bug :streams-legacy-73
(read s)
"test broadcast satz 1")
(check-for-bug :streams-legacy-77
(read s)
"test broadcast satz 2")
(check-for-bug :streams-legacy-81
(read s)
"test broadcast satz 3")
(check-for-bug :streams-legacy-85
(close-1 s)
t)
(check-for-bug :streams-legacy-89
(progn (setq s (open "d3.plc")) t)
t)
(check-for-bug :streams-legacy-93
(read s)
"test broadcast satz 1")
(check-for-bug :streams-legacy-97
(read s)
"test broadcast satz 2")
(check-for-bug :streams-legacy-101
(read s)
"test broadcast satz 3")
(check-for-bug :streams-legacy-105
(close-1 s)
t)
(check-for-bug :streams-legacy-109
(progn (setq s (open "t0.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-113
(print (quote read1) s)
read1)
(check-for-bug :streams-legacy-117
(print (quote read2) s)
read2)
(check-for-bug :streams-legacy-121
(close-1 s)
t)
(check-for-bug :streams-legacy-125
(progn (setq inptw (open "t0.plc"))
(setq s1 (open "d1.plc" :direction :output))
(setq s2 (open "d2.plc" :direction :output))
(setq sy (make-synonym-stream (quote s2)))
(setq s3 (open "d3.plc" :direction :output))
(setq tw (make-two-way-stream inptw s3))
(setq s4 (open "d4.plc" :direction :output))
(setq ec (make-echo-stream inptw s4))
(setq s5 (open "d5.plc" :direction :output))
(setq s6 (open "d6.plc" :direction :output))
(setq b1 (make-broadcast-stream s5 s6))
(setq s7 (open "d7.plc" :direction :output))
(setq b2 (make-broadcast-stream s1 sy tw ec b1 s7)) t)
t)
(check-for-bug :streams-legacy-141
(print "w to b2 1.satz" b2)
"w to b2 1.satz")
(check-for-bug :streams-legacy-145
(print "w to sy" sy)
"w to sy")
(check-for-bug :streams-legacy-149
(print "w to b2 2.satz" b2)
"w to b2 2.satz")
(check-for-bug :streams-legacy-153
(print "w to tw" tw)
"w to tw")
(check-for-bug :streams-legacy-157
(print "w to b2 3.satz" b2)
"w to b2 3.satz")
(check-for-bug :streams-legacy-161
(print "w to ec" ec)
"w to ec")
(check-for-bug :streams-legacy-165
(print "w to b2 4.satz" b2)
"w to b2 4.satz")
(check-for-bug :streams-legacy-169
(print "w to b1" b1)
"w to b1")
(check-for-bug :streams-legacy-173
(print "w to b2 5.satz" b2)
"w to b2 5.satz")
(check-for-bug :streams-legacy-177
(print "w to s7" s7)
"w to s7")
(check-for-bug :streams-legacy-181
(print "w to b2 6.satz" b2)
"w to b2 6.satz")
(check-for-bug :streams-legacy-185
(read tw)
read1)
(check-for-bug :streams-legacy-189
(read ec)
read2)
(check-for-bug :streams-legacy-193
(print "w to b2 7.satz" b2)
"w to b2 7.satz")
(check-for-bug :streams-legacy-197
(print "w to b2 8.satz" b2)
"w to b2 8.satz")
(check-for-bug :streams-legacy-201
(close-1 inptw)
t)
(check-for-bug :streams-legacy-205
(close-1 s1)
t)
(check-for-bug :streams-legacy-209
(close-1 s2)
t)
(check-for-bug :streams-legacy-213
(close-1 s3)
t)
(check-for-bug :streams-legacy-217
(close-1 s4)
t)
(check-for-bug :streams-legacy-221
(close-1 s5)
t)
(check-for-bug :streams-legacy-225
(close-1 s6)
t)
(check-for-bug :streams-legacy-229
(close-1 s7)
t)
(check-for-bug :streams-legacy-233
(progn (setq s (open "d1.plc")) t)
t)
(check-for-bug :streams-legacy-237
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-241
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-245
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-249
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-253
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-257
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-261
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-265
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-269
(close-1 s)
t)
(check-for-bug :streams-legacy-273
(progn (setq s (open "d2.plc")) t)
t)
(check-for-bug :streams-legacy-277
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-281
(read s)
"w to sy")
(check-for-bug :streams-legacy-285
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-289
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-293
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-297
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-301
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-305
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-309
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-313
(close-1 s)
t)
(check-for-bug :streams-legacy-317
(progn (setq s (open "d3.plc")) t)
t)
(check-for-bug :streams-legacy-321
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-325
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-329
(read s)
"w to tw")
(check-for-bug :streams-legacy-333
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-337
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-341
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-345
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-349
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-353
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-357
(close-1 s)
t)
(check-for-bug :streams-legacy-361
(progn (setq s (open "d4.plc")) t)
t)
(check-for-bug :streams-legacy-365
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-369
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-373
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-377
(read s)
"w to ec")
(check-for-bug :streams-legacy-381
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-385
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-389
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-393
(read s)
read2)
(check-for-bug :streams-legacy-397
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-401
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-405
(close-1 s)
t)
(check-for-bug :streams-legacy-409
(progn (setq s (open "d5.plc")) t)
t)
(check-for-bug :streams-legacy-413
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-417
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-421
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-425
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-429
(read s)
"w to b1")
(check-for-bug :streams-legacy-433
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-437
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-441
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-445
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-449
(close-1 s)
t)
(check-for-bug :streams-legacy-453
(progn (setq s (open "d6.plc")) t)
t)
(check-for-bug :streams-legacy-457
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-461
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-465
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-469
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-473
(read s)
"w to b1")
(check-for-bug :streams-legacy-477
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-481
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-485
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-489
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-493
(close-1 s)
t)
(check-for-bug :streams-legacy-497
(progn (setq s (open "d7.plc")) t)
t)
(check-for-bug :streams-legacy-501
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-505
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-509
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-513
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-517
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-521
(read s)
"w to s7")
(check-for-bug :streams-legacy-525
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-529
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-533
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-537
(close-1 s)
t)
(check-for-bug :streams-legacy-541
(progn (setq s (open "t1.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-545
(print "1.satz t1" s)
"1.satz t1")
(check-for-bug :streams-legacy-549
(print "2.satz t1" s)
"2.satz t1")
(check-for-bug :streams-legacy-553
(close-1 s)
t)
(check-for-bug :streams-legacy-557
(progn (setq s (open "t2.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-561
(print "1.satz t2" s)
"1.satz t2")
(check-for-bug :streams-legacy-565
(print "2.satz t2" s)
"2.satz t2")
(check-for-bug :streams-legacy-569
(close-1 s)
t)
(check-for-bug :streams-legacy-573
(progn (setq s (open "t3.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-577
(print "1.satz t3" s)
"1.satz t3")
(check-for-bug :streams-legacy-581
(print "2.satz t3" s)
"2.satz t3")
(check-for-bug :streams-legacy-585
(close-1 s)
t)
(check-for-bug :streams-legacy-589
(progn (setq s (open "t4.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-593
(print "1.satz t4" s)
"1.satz t4")
(check-for-bug :streams-legacy-597
(print "2.satz t4" s)
"2.satz t4")
(check-for-bug :streams-legacy-601
(close-1 s)
t)
(check-for-bug :streams-legacy-605
(progn (setq s (open "t5.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-609
(print "1.satz t5" s)
"1.satz t5")
(check-for-bug :streams-legacy-613
(print "2.satz t5" s)
"2.satz t5")
(check-for-bug :streams-legacy-617
(close-1 s)
t)
(check-for-bug :streams-legacy-621
(progn (setq s (open "t6.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-625
(print "1.satz t6" s)
"1.satz t6")
(check-for-bug :streams-legacy-629
(print "2.satz t6" s)
"2.satz t6")
(check-for-bug :streams-legacy-633
(close-1 s)
t)
(check-for-bug :streams-legacy-637
(progn (setq s (open "t7.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-641
(print "1.satz t7" s)
"1.satz t7")
(check-for-bug :streams-legacy-645
(print "2.satz t7" s)
"2.satz t7")
(check-for-bug :streams-legacy-649
(close-1 s)
t)
(check-for-bug :streams-legacy-653
(progn (setq s (open "t8.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-657
(print "1.satz t8" s)
"1.satz t8")
(check-for-bug :streams-legacy-661
(print "2.satz t8" s)
"2.satz t8")
(check-for-bug :streams-legacy-665
(close-1 s)
t)
(check-for-bug :streams-legacy-669
(progn (setq s (open "t9.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-673
(print "1.satz t9" s)
"1.satz t9")
(check-for-bug :streams-legacy-677
(print "2.satz t9" s)
"2.satz t9")
(check-for-bug :streams-legacy-681
(close-1 s)
t)
(check-for-bug :streams-legacy-685
(progn (setq s (open "t10.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-689
(print "1.satz t10" s)
"1.satz t10")
(check-for-bug :streams-legacy-693
(print "2.satz t10" s)
"2.satz t10")
(check-for-bug :streams-legacy-697
(close-1 s)
t)
(check-for-bug :streams-legacy-701
(progn (setq s1 (open "t1.plc")) (setq s2 (open "t2.plc"))
(setq s3 (open "t3.plc")) (setq s4 (open "t4.plc")) (setq s5 (open
"t5.plc"))
(setq c1 (make-concatenated-stream s1 s2 s3))
(setq c2 (make-concatenated-stream s4 s5)) t)
t)
(check-for-bug :streams-legacy-709
(read c1)
"1.satz t1")
(check-for-bug :streams-legacy-713
(read c2)
"1.satz t4")
(check-for-bug :streams-legacy-717
(read c1)
"2.satz t1")
(check-for-bug :streams-legacy-721
(read c1)
"1.satz t2")
(check-for-bug :streams-legacy-725
(read c2)
"2.satz t4")
(check-for-bug :streams-legacy-729
(read c2)
"1.satz t5")
(check-for-bug :streams-legacy-733
(read c1)
"2.satz t2")
(check-for-bug :streams-legacy-737
(read c1)
"1.satz t3")
(check-for-bug :streams-legacy-741
(read c1)
"2.satz t3")
(check-for-bug :streams-legacy-745
(read c2)
"2.satz t5")
(check-for-bug :streams-legacy-749
(close-1 s1)
t)
(check-for-bug :streams-legacy-753
(close-1 s2)
t)
(check-for-bug :streams-legacy-757
(close-1 s3)
t)
(check-for-bug :streams-legacy-761
(close-1 s4)
t)
(check-for-bug :streams-legacy-765
(close-1 s5)
t)
(check-for-bug :streams-legacy-769
(progn (setq s1 (open "t1.plc")) (setq s2 (open "t2.plc"))
(setq s3 (open "t3.plc")) (setq s4 (open "t4.plc")) (setq s5 (open
"t5.plc"))
(setq s6 (open "t6.plc")) (setq s7 (open "t7.plc")) (setq s8 (open
"t8.plc"))
(setq s9 (open "t9.plc")) (setq s10 (open "t10.plc"))
(setq c1 (make-concatenated-stream s1 s2))
(setq c2 (make-concatenated-stream s3))
(setq c3 (make-concatenated-stream c1 c2 s4))
(setq c4 (make-concatenated-stream s5 s6 s7 s8 s9 s10)) t)
t)
(check-for-bug :streams-legacy-782
(read c4)
"1.satz t5")
(check-for-bug :streams-legacy-786
(read c3)
"1.satz t1")
(check-for-bug :streams-legacy-790
(read c4)
"2.satz t5")
(check-for-bug :streams-legacy-794
(read c4)
"1.satz t6")
(check-for-bug :streams-legacy-798
(read c3)
"2.satz t1")
(check-for-bug :streams-legacy-802
(read c3)
"1.satz t2")
(check-for-bug :streams-legacy-806
(read c4)
"2.satz t6")
(check-for-bug :streams-legacy-810
(read c4)
"1.satz t7")
(check-for-bug :streams-legacy-814
(read c4)
"2.satz t7")
(check-for-bug :streams-legacy-818
(read c3)
"2.satz t2")
(check-for-bug :streams-legacy-822
(read c3)
"1.satz t3")
(check-for-bug :streams-legacy-826
(read c3)
"2.satz t3")
(check-for-bug :streams-legacy-830
(read c4)
"1.satz t8")
(check-for-bug :streams-legacy-834
(read c4)
"2.satz t8")
(check-for-bug :streams-legacy-838
(read c4)
"1.satz t9")
(check-for-bug :streams-legacy-842
(read c4)
"2.satz t9")
(check-for-bug :streams-legacy-846
(read c3)
"1.satz t4")
(check-for-bug :streams-legacy-850
(read c3)
"2.satz t4")
(check-for-bug :streams-legacy-854
(read c4)
"1.satz t10")
(check-for-bug :streams-legacy-858
(read c4)
"2.satz t10")
(check-for-bug :streams-legacy-862
(close-1 s1)
t)
(check-for-bug :streams-legacy-866
(close-1 s2)
t)
(check-for-bug :streams-legacy-870
(close-1 s3)
t)
(check-for-bug :streams-legacy-874
(close-1 s4)
t)
(check-for-bug :streams-legacy-878
(close-1 s5)
t)
(check-for-bug :streams-legacy-882
(close-1 s6)
t)
(check-for-bug :streams-legacy-886
(close-1 s7)
t)
(check-for-bug :streams-legacy-890
(close-1 s8)
t)
(check-for-bug :streams-legacy-894
(close-1 s9)
t)
(check-for-bug :streams-legacy-898
(close-1 s10)
t)
(check-for-bug :streams-legacy-902
(setq str1 "test 123456")
"test 123456")
(check-for-bug :streams-legacy-906
(progn (setq s1 (make-string-input-stream str1)) t)
t)
(check-for-bug :streams-legacy-910
(read s1)
test)
(check-for-bug :streams-legacy-914
(read-char s1)
#\1)
(check-for-bug :streams-legacy-918
(read-char s1)
#\2)
(check-for-bug :streams-legacy-922
(unread-char #\2 s1)
nil)
(check-for-bug :streams-legacy-926
(read-char s1)
#\2)
(check-for-bug :streams-legacy-930
(read-char s1)
#\3)
(check-for-bug :streams-legacy-934
(read-char s1)
#\4)
(check-for-bug :streams-legacy-938
(unread-char #\a s1)
error
"We previously read #\4 from S1, we are not allowed to
put #\a back in!")
(check-for-bug :streams-legacy-944
(read-char s1)
#\5
"The previous unread-char should have failed, so
we expect to see #\5 here. If the unread-char worked
we will (wrongly!) see #\4 or #\a")
(check-for-bug :streams-legacy-951
(read-char s1)
#\6
"Likewise the unread-char should have failed")
(check-for-bug :streams-legacy-956
(close-1 s1)
t)
(check-for-bug :streams-legacy-960
str1
"test 123456")
(check-for-bug :streams-legacy-964
(multiple-value-list (read-from-string "012345 789"))
(12345 7))
(check-for-bug :streams-legacy-968
(multiple-value-list (read-from-string "012345 789" t nil
:preserve-whitespace t))
(12345 6))
(check-for-bug :streams-legacy-973
(multiple-value-list (read-from-string "012345 789" t nil :end 4))
(123 4))
(check-for-bug :streams-legacy-977
(multiple-value-list (read-from-string "012345 789" t nil :start 2))
(2345 7))
(check-for-bug :streams-legacy-981
(progn (setq strgstream (make-string-input-stream "0123456789" 5 8))
t)
t)
(check-for-bug :streams-legacy-986
(read strgstream)
567)
(check-for-bug :streams-legacy-990
(progn (setq strgstream
(make-string-input-stream "wenn alles gut geht ist das ein stream 012"))
t)
t)
(check-for-bug :streams-legacy-996
(read strgstream)
wenn)
(check-for-bug :streams-legacy-1000
(read strgstream)
alles)
(check-for-bug :streams-legacy-1004
(read strgstream)
gut)
(check-for-bug :streams-legacy-1008
(read strgstream)
geht)
(check-for-bug :streams-legacy-1012
(read strgstream)
ist)
(check-for-bug :streams-legacy-1016
(read strgstream)
das)
(check-for-bug :streams-legacy-1020
(read strgstream)
ein)
(check-for-bug :streams-legacy-1024
(read strgstream)
stream)
(check-for-bug :streams-legacy-1028
(read strgstream)
12)
(check-for-bug :streams-legacy-1032
(progn (setq strgstream (make-string-output-stream)) t)
t)
(check-for-bug :streams-legacy-1036
(princ "das " strgstream)
"das ")
(check-for-bug :streams-legacy-1040
(princ "ist " strgstream)
"ist ")
(check-for-bug :streams-legacy-1044
(princ "ein " strgstream)
"ein ")
(check-for-bug :streams-legacy-1048
(princ "string " strgstream)
"string ")
(check-for-bug :streams-legacy-1052
(princ "output " strgstream)
"output ")
(check-for-bug :streams-legacy-1056
(princ "stream " strgstream)
"stream ")
(check-for-bug :streams-legacy-1060
(get-output-stream-string strgstream)
"das ist ein string output stream ")
(check-for-bug :streams-legacy-1064
(get-output-stream-string strgstream)
"")
(check-for-bug :streams-legacy-1068
(princ "das ist ein neuer string output stream" strgstream)
"das ist ein neuer string output stream")
(check-for-bug :streams-legacy-1072
(get-output-stream-string strgstream)
"das ist ein neuer string output stream")
(check-for-bug :streams-legacy-1076
(setq *print-length* 50)
50)
(check-for-bug :streams-legacy-1080
(write-to-string 123456789)
"123456789")
(check-for-bug :streams-legacy-1084
"(write-to-string '#1=(123456789 . #1#))"
"(write-to-string '#1=(123456789 . #1#))")
(check-for-bug :streams-legacy-1088
(prin1-to-string "abc")
"\"abc\"")
(check-for-bug :streams-legacy-1092
(princ-to-string "abc")
"abc")
(check-for-bug :streams-legacy-1096
(progn (setq os (make-string-output-stream)) t)
t)
(check-for-bug :streams-legacy-1100
(setq s50 "123456789A123456789B123456789C123456789D12345678
E")
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1106
(setq s49 "123456789A123456789B123456789C123456789D1234567
*")
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1112
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1117
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1122
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1127
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1132
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1137
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1142
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1147
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1152
(princ "A" os)
"A")
(check-for-bug :streams-legacy-1156
(princ "B" os)
"B")
(check-for-bug :streams-legacy-1160
(princ "C" os)
"C")
(check-for-bug :streams-legacy-1164
(length (princ (get-output-stream-string os)))
402)
(check-for-bug :streams-legacy-1168
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1173
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1178
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1183
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1188
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1193
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1198
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1203
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1208
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1213
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1218
(length (princ (get-output-stream-string os)))
496)
(check-for-bug :streams-legacy-1222
(progn (setq os (open "d0.plc" :direction :output))
(setq os1 (open "d1.plc" :direction :output))
(setq is (open "t0.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-1228
(princ "'(a b #.(print \"1.zwischenwert\" os1) c d)" is)
"'(a b #.(print \"1.zwischenwert\" os1) c d)")
(check-for-bug :streams-legacy-1232
(princ "'(a b #.(prin1-to-string \"2.zwischenwert\") c d)" is)
"'(a b #.(prin1-to-string \"2.zwischenwert\") c d)")
(check-for-bug :streams-legacy-1236
(princ "'(a b #.(format nil \"3.zwischenwert\") c d)" is)
"'(a b #.(format nil \"3.zwischenwert\") c d)")
(check-for-bug :streams-legacy-1240
(close-1 is)
t)
(check-for-bug :streams-legacy-1244
(progn (setq is (open "t0.plc")) (setq es (make-echo-stream is os))
t)
t)
(check-for-bug :streams-legacy-1249
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1253
(read es)
(quote (a b "1.zwischenwert" c d)))
(check-for-bug :streams-legacy-1257
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1261
(read es)
(quote (a b "\"2.zwischenwert\"" c d)))
(check-for-bug :streams-legacy-1265
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1269
(read es)
(quote (a b "3.zwischenwert" c d)))
(check-for-bug :streams-legacy-1273
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1277
(close-1 is)
t)
(check-for-bug :streams-legacy-1281
(close-1 os)
t)
(check-for-bug :streams-legacy-1285
(progn (setq is (open "d0.plc")) t)
t)
(check-for-bug :streams-legacy-1289
(read is)
(quote (a b "1.zwischenwert" c d)))
(check-for-bug :streams-legacy-1293
(read is)
(quote (a b "\"2.zwischenwert\"" c d)))
(check-for-bug :streams-legacy-1297
(read is)
(quote (a b "3.zwischenwert" c d)))
(check-for-bug :streams-legacy-1301
(close-1 is)
t)
(check-for-bug :streams-legacy-1305
(close-1 os1)
t)
(check-for-bug :streams-legacy-1309
(progn (setq is (open "d1.plc")) t)
t)
(check-for-bug :streams-legacy-1313
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1317
(read is)
"1.zwischenwert")
(check-for-bug :streams-legacy-1321
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1325
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1329
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1333
(read is)
"1.zwischenwert")
(check-for-bug :streams-legacy-1337
(close-1 is)
t)
(check-for-bug :streams-legacy-1341
(progn (mapc #'delete-file (directory "*.plc")) t)
t)
(check-for-bug :streams-legacy-1345
(progn
(makunbound 's)
(makunbound 's1)
(makunbound 's2)
(makunbound 's3)
(makunbound 's4)
(makunbound 's5)
(makunbound 's6)
(makunbound 's7)
(makunbound 's8)
(makunbound 's9)
(makunbound 's10)
(makunbound 'b1)
(makunbound 'b2)
(makunbound 'c1)
(makunbound 'c2)
(makunbound 'c3)
(makunbound 'c4)
(makunbound 'inptw)
(makunbound 'sy)
(makunbound 'tw)
(makunbound 'ec)
(makunbound 'str1)
(makunbound 'strgstream)
(makunbound 'os)
(makunbound 'os1)
(makunbound 'is)
(makunbound 'es)
(makunbound 's50)
(makunbound 's49)
(setq *print-length* nil)
t)
t)
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/tools/ansi-test/streams.lisp | lisp | based on v1.6 -*- mode: lisp -*-
CLOSE should not delete information about
element type, direction, and external format | (in-package :cl-user)
#+xcl
(check-for-bug :streams-legacy-5
(progn (in-package :sys) t)
t)
#-(or akcl allegro)
(check-for-bug :streams-legacy-10
(prin1-to-string (make-broadcast-stream))
#+xcl "#<%TYPE-STRUCTURE-STREAM NIL>"
#+clisp "#<OUTPUT BROADCAST-STREAM>"
#+(or cmu sbcl) "#<Broadcast Stream>"
#+ecls "#<broadcast stream 8>"
#-(or xcl clisp akcl allegro cmu sbcl ecls) unknown)
(check-for-bug :streams-legacy-18
(progn (setq s1 (open "d1.plc" :direction :output))
(setq s2 (open "d2.plc" :direction :output))
(setq s3 (open "d3.plc" :direction :output))
(setq b1 (make-broadcast-stream s1 s2 s3 *standard-output*)) t)
t)
(check-for-bug :streams-legacy-25
(print "test broadcast satz 1" b1)
"test broadcast satz 1")
(check-for-bug :streams-legacy-29
(print "test broadcast satz 2" b1)
"test broadcast satz 2")
(check-for-bug :streams-legacy-33
(print "test broadcast satz 3" b1)
"test broadcast satz 3")
(defun close-1 (s)
(let* ((i (input-stream-p s))
(o (output-stream-p s))
(e (stream-element-type s))
(f (stream-external-format s))
(c (close s)))
(and (eq i (input-stream-p s))
(eq o (output-stream-p s))
(equal e (stream-element-type s))
(equal f (stream-external-format s))
c)))
(check-for-bug :streams-legacy-37
(close-1 s1)
t)
(check-for-bug :streams-legacy-41
(close-1 s2)
t)
(check-for-bug :streams-legacy-45
(close-1 s3)
t)
(check-for-bug :streams-legacy-49
(progn (setq s (open "d1.plc")) t)
t)
(check-for-bug :streams-legacy-53
(read s)
"test broadcast satz 1")
(check-for-bug :streams-legacy-57
(read s)
"test broadcast satz 2")
(check-for-bug :streams-legacy-61
(read s)
"test broadcast satz 3")
(check-for-bug :streams-legacy-65
(close-1 s)
t)
(check-for-bug :streams-legacy-69
(progn (setq s (open "d2.plc")) t)
t)
(check-for-bug :streams-legacy-73
(read s)
"test broadcast satz 1")
(check-for-bug :streams-legacy-77
(read s)
"test broadcast satz 2")
(check-for-bug :streams-legacy-81
(read s)
"test broadcast satz 3")
(check-for-bug :streams-legacy-85
(close-1 s)
t)
(check-for-bug :streams-legacy-89
(progn (setq s (open "d3.plc")) t)
t)
(check-for-bug :streams-legacy-93
(read s)
"test broadcast satz 1")
(check-for-bug :streams-legacy-97
(read s)
"test broadcast satz 2")
(check-for-bug :streams-legacy-101
(read s)
"test broadcast satz 3")
(check-for-bug :streams-legacy-105
(close-1 s)
t)
(check-for-bug :streams-legacy-109
(progn (setq s (open "t0.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-113
(print (quote read1) s)
read1)
(check-for-bug :streams-legacy-117
(print (quote read2) s)
read2)
(check-for-bug :streams-legacy-121
(close-1 s)
t)
(check-for-bug :streams-legacy-125
(progn (setq inptw (open "t0.plc"))
(setq s1 (open "d1.plc" :direction :output))
(setq s2 (open "d2.plc" :direction :output))
(setq sy (make-synonym-stream (quote s2)))
(setq s3 (open "d3.plc" :direction :output))
(setq tw (make-two-way-stream inptw s3))
(setq s4 (open "d4.plc" :direction :output))
(setq ec (make-echo-stream inptw s4))
(setq s5 (open "d5.plc" :direction :output))
(setq s6 (open "d6.plc" :direction :output))
(setq b1 (make-broadcast-stream s5 s6))
(setq s7 (open "d7.plc" :direction :output))
(setq b2 (make-broadcast-stream s1 sy tw ec b1 s7)) t)
t)
(check-for-bug :streams-legacy-141
(print "w to b2 1.satz" b2)
"w to b2 1.satz")
(check-for-bug :streams-legacy-145
(print "w to sy" sy)
"w to sy")
(check-for-bug :streams-legacy-149
(print "w to b2 2.satz" b2)
"w to b2 2.satz")
(check-for-bug :streams-legacy-153
(print "w to tw" tw)
"w to tw")
(check-for-bug :streams-legacy-157
(print "w to b2 3.satz" b2)
"w to b2 3.satz")
(check-for-bug :streams-legacy-161
(print "w to ec" ec)
"w to ec")
(check-for-bug :streams-legacy-165
(print "w to b2 4.satz" b2)
"w to b2 4.satz")
(check-for-bug :streams-legacy-169
(print "w to b1" b1)
"w to b1")
(check-for-bug :streams-legacy-173
(print "w to b2 5.satz" b2)
"w to b2 5.satz")
(check-for-bug :streams-legacy-177
(print "w to s7" s7)
"w to s7")
(check-for-bug :streams-legacy-181
(print "w to b2 6.satz" b2)
"w to b2 6.satz")
(check-for-bug :streams-legacy-185
(read tw)
read1)
(check-for-bug :streams-legacy-189
(read ec)
read2)
(check-for-bug :streams-legacy-193
(print "w to b2 7.satz" b2)
"w to b2 7.satz")
(check-for-bug :streams-legacy-197
(print "w to b2 8.satz" b2)
"w to b2 8.satz")
(check-for-bug :streams-legacy-201
(close-1 inptw)
t)
(check-for-bug :streams-legacy-205
(close-1 s1)
t)
(check-for-bug :streams-legacy-209
(close-1 s2)
t)
(check-for-bug :streams-legacy-213
(close-1 s3)
t)
(check-for-bug :streams-legacy-217
(close-1 s4)
t)
(check-for-bug :streams-legacy-221
(close-1 s5)
t)
(check-for-bug :streams-legacy-225
(close-1 s6)
t)
(check-for-bug :streams-legacy-229
(close-1 s7)
t)
(check-for-bug :streams-legacy-233
(progn (setq s (open "d1.plc")) t)
t)
(check-for-bug :streams-legacy-237
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-241
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-245
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-249
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-253
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-257
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-261
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-265
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-269
(close-1 s)
t)
(check-for-bug :streams-legacy-273
(progn (setq s (open "d2.plc")) t)
t)
(check-for-bug :streams-legacy-277
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-281
(read s)
"w to sy")
(check-for-bug :streams-legacy-285
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-289
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-293
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-297
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-301
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-305
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-309
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-313
(close-1 s)
t)
(check-for-bug :streams-legacy-317
(progn (setq s (open "d3.plc")) t)
t)
(check-for-bug :streams-legacy-321
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-325
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-329
(read s)
"w to tw")
(check-for-bug :streams-legacy-333
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-337
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-341
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-345
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-349
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-353
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-357
(close-1 s)
t)
(check-for-bug :streams-legacy-361
(progn (setq s (open "d4.plc")) t)
t)
(check-for-bug :streams-legacy-365
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-369
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-373
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-377
(read s)
"w to ec")
(check-for-bug :streams-legacy-381
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-385
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-389
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-393
(read s)
read2)
(check-for-bug :streams-legacy-397
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-401
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-405
(close-1 s)
t)
(check-for-bug :streams-legacy-409
(progn (setq s (open "d5.plc")) t)
t)
(check-for-bug :streams-legacy-413
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-417
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-421
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-425
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-429
(read s)
"w to b1")
(check-for-bug :streams-legacy-433
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-437
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-441
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-445
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-449
(close-1 s)
t)
(check-for-bug :streams-legacy-453
(progn (setq s (open "d6.plc")) t)
t)
(check-for-bug :streams-legacy-457
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-461
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-465
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-469
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-473
(read s)
"w to b1")
(check-for-bug :streams-legacy-477
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-481
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-485
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-489
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-493
(close-1 s)
t)
(check-for-bug :streams-legacy-497
(progn (setq s (open "d7.plc")) t)
t)
(check-for-bug :streams-legacy-501
(read s)
"w to b2 1.satz")
(check-for-bug :streams-legacy-505
(read s)
"w to b2 2.satz")
(check-for-bug :streams-legacy-509
(read s)
"w to b2 3.satz")
(check-for-bug :streams-legacy-513
(read s)
"w to b2 4.satz")
(check-for-bug :streams-legacy-517
(read s)
"w to b2 5.satz")
(check-for-bug :streams-legacy-521
(read s)
"w to s7")
(check-for-bug :streams-legacy-525
(read s)
"w to b2 6.satz")
(check-for-bug :streams-legacy-529
(read s)
"w to b2 7.satz")
(check-for-bug :streams-legacy-533
(read s)
"w to b2 8.satz")
(check-for-bug :streams-legacy-537
(close-1 s)
t)
(check-for-bug :streams-legacy-541
(progn (setq s (open "t1.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-545
(print "1.satz t1" s)
"1.satz t1")
(check-for-bug :streams-legacy-549
(print "2.satz t1" s)
"2.satz t1")
(check-for-bug :streams-legacy-553
(close-1 s)
t)
(check-for-bug :streams-legacy-557
(progn (setq s (open "t2.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-561
(print "1.satz t2" s)
"1.satz t2")
(check-for-bug :streams-legacy-565
(print "2.satz t2" s)
"2.satz t2")
(check-for-bug :streams-legacy-569
(close-1 s)
t)
(check-for-bug :streams-legacy-573
(progn (setq s (open "t3.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-577
(print "1.satz t3" s)
"1.satz t3")
(check-for-bug :streams-legacy-581
(print "2.satz t3" s)
"2.satz t3")
(check-for-bug :streams-legacy-585
(close-1 s)
t)
(check-for-bug :streams-legacy-589
(progn (setq s (open "t4.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-593
(print "1.satz t4" s)
"1.satz t4")
(check-for-bug :streams-legacy-597
(print "2.satz t4" s)
"2.satz t4")
(check-for-bug :streams-legacy-601
(close-1 s)
t)
(check-for-bug :streams-legacy-605
(progn (setq s (open "t5.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-609
(print "1.satz t5" s)
"1.satz t5")
(check-for-bug :streams-legacy-613
(print "2.satz t5" s)
"2.satz t5")
(check-for-bug :streams-legacy-617
(close-1 s)
t)
(check-for-bug :streams-legacy-621
(progn (setq s (open "t6.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-625
(print "1.satz t6" s)
"1.satz t6")
(check-for-bug :streams-legacy-629
(print "2.satz t6" s)
"2.satz t6")
(check-for-bug :streams-legacy-633
(close-1 s)
t)
(check-for-bug :streams-legacy-637
(progn (setq s (open "t7.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-641
(print "1.satz t7" s)
"1.satz t7")
(check-for-bug :streams-legacy-645
(print "2.satz t7" s)
"2.satz t7")
(check-for-bug :streams-legacy-649
(close-1 s)
t)
(check-for-bug :streams-legacy-653
(progn (setq s (open "t8.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-657
(print "1.satz t8" s)
"1.satz t8")
(check-for-bug :streams-legacy-661
(print "2.satz t8" s)
"2.satz t8")
(check-for-bug :streams-legacy-665
(close-1 s)
t)
(check-for-bug :streams-legacy-669
(progn (setq s (open "t9.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-673
(print "1.satz t9" s)
"1.satz t9")
(check-for-bug :streams-legacy-677
(print "2.satz t9" s)
"2.satz t9")
(check-for-bug :streams-legacy-681
(close-1 s)
t)
(check-for-bug :streams-legacy-685
(progn (setq s (open "t10.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-689
(print "1.satz t10" s)
"1.satz t10")
(check-for-bug :streams-legacy-693
(print "2.satz t10" s)
"2.satz t10")
(check-for-bug :streams-legacy-697
(close-1 s)
t)
(check-for-bug :streams-legacy-701
(progn (setq s1 (open "t1.plc")) (setq s2 (open "t2.plc"))
(setq s3 (open "t3.plc")) (setq s4 (open "t4.plc")) (setq s5 (open
"t5.plc"))
(setq c1 (make-concatenated-stream s1 s2 s3))
(setq c2 (make-concatenated-stream s4 s5)) t)
t)
(check-for-bug :streams-legacy-709
(read c1)
"1.satz t1")
(check-for-bug :streams-legacy-713
(read c2)
"1.satz t4")
(check-for-bug :streams-legacy-717
(read c1)
"2.satz t1")
(check-for-bug :streams-legacy-721
(read c1)
"1.satz t2")
(check-for-bug :streams-legacy-725
(read c2)
"2.satz t4")
(check-for-bug :streams-legacy-729
(read c2)
"1.satz t5")
(check-for-bug :streams-legacy-733
(read c1)
"2.satz t2")
(check-for-bug :streams-legacy-737
(read c1)
"1.satz t3")
(check-for-bug :streams-legacy-741
(read c1)
"2.satz t3")
(check-for-bug :streams-legacy-745
(read c2)
"2.satz t5")
(check-for-bug :streams-legacy-749
(close-1 s1)
t)
(check-for-bug :streams-legacy-753
(close-1 s2)
t)
(check-for-bug :streams-legacy-757
(close-1 s3)
t)
(check-for-bug :streams-legacy-761
(close-1 s4)
t)
(check-for-bug :streams-legacy-765
(close-1 s5)
t)
(check-for-bug :streams-legacy-769
(progn (setq s1 (open "t1.plc")) (setq s2 (open "t2.plc"))
(setq s3 (open "t3.plc")) (setq s4 (open "t4.plc")) (setq s5 (open
"t5.plc"))
(setq s6 (open "t6.plc")) (setq s7 (open "t7.plc")) (setq s8 (open
"t8.plc"))
(setq s9 (open "t9.plc")) (setq s10 (open "t10.plc"))
(setq c1 (make-concatenated-stream s1 s2))
(setq c2 (make-concatenated-stream s3))
(setq c3 (make-concatenated-stream c1 c2 s4))
(setq c4 (make-concatenated-stream s5 s6 s7 s8 s9 s10)) t)
t)
(check-for-bug :streams-legacy-782
(read c4)
"1.satz t5")
(check-for-bug :streams-legacy-786
(read c3)
"1.satz t1")
(check-for-bug :streams-legacy-790
(read c4)
"2.satz t5")
(check-for-bug :streams-legacy-794
(read c4)
"1.satz t6")
(check-for-bug :streams-legacy-798
(read c3)
"2.satz t1")
(check-for-bug :streams-legacy-802
(read c3)
"1.satz t2")
(check-for-bug :streams-legacy-806
(read c4)
"2.satz t6")
(check-for-bug :streams-legacy-810
(read c4)
"1.satz t7")
(check-for-bug :streams-legacy-814
(read c4)
"2.satz t7")
(check-for-bug :streams-legacy-818
(read c3)
"2.satz t2")
(check-for-bug :streams-legacy-822
(read c3)
"1.satz t3")
(check-for-bug :streams-legacy-826
(read c3)
"2.satz t3")
(check-for-bug :streams-legacy-830
(read c4)
"1.satz t8")
(check-for-bug :streams-legacy-834
(read c4)
"2.satz t8")
(check-for-bug :streams-legacy-838
(read c4)
"1.satz t9")
(check-for-bug :streams-legacy-842
(read c4)
"2.satz t9")
(check-for-bug :streams-legacy-846
(read c3)
"1.satz t4")
(check-for-bug :streams-legacy-850
(read c3)
"2.satz t4")
(check-for-bug :streams-legacy-854
(read c4)
"1.satz t10")
(check-for-bug :streams-legacy-858
(read c4)
"2.satz t10")
(check-for-bug :streams-legacy-862
(close-1 s1)
t)
(check-for-bug :streams-legacy-866
(close-1 s2)
t)
(check-for-bug :streams-legacy-870
(close-1 s3)
t)
(check-for-bug :streams-legacy-874
(close-1 s4)
t)
(check-for-bug :streams-legacy-878
(close-1 s5)
t)
(check-for-bug :streams-legacy-882
(close-1 s6)
t)
(check-for-bug :streams-legacy-886
(close-1 s7)
t)
(check-for-bug :streams-legacy-890
(close-1 s8)
t)
(check-for-bug :streams-legacy-894
(close-1 s9)
t)
(check-for-bug :streams-legacy-898
(close-1 s10)
t)
(check-for-bug :streams-legacy-902
(setq str1 "test 123456")
"test 123456")
(check-for-bug :streams-legacy-906
(progn (setq s1 (make-string-input-stream str1)) t)
t)
(check-for-bug :streams-legacy-910
(read s1)
test)
(check-for-bug :streams-legacy-914
(read-char s1)
#\1)
(check-for-bug :streams-legacy-918
(read-char s1)
#\2)
(check-for-bug :streams-legacy-922
(unread-char #\2 s1)
nil)
(check-for-bug :streams-legacy-926
(read-char s1)
#\2)
(check-for-bug :streams-legacy-930
(read-char s1)
#\3)
(check-for-bug :streams-legacy-934
(read-char s1)
#\4)
(check-for-bug :streams-legacy-938
(unread-char #\a s1)
error
"We previously read #\4 from S1, we are not allowed to
put #\a back in!")
(check-for-bug :streams-legacy-944
(read-char s1)
#\5
"The previous unread-char should have failed, so
we expect to see #\5 here. If the unread-char worked
we will (wrongly!) see #\4 or #\a")
(check-for-bug :streams-legacy-951
(read-char s1)
#\6
"Likewise the unread-char should have failed")
(check-for-bug :streams-legacy-956
(close-1 s1)
t)
(check-for-bug :streams-legacy-960
str1
"test 123456")
(check-for-bug :streams-legacy-964
(multiple-value-list (read-from-string "012345 789"))
(12345 7))
(check-for-bug :streams-legacy-968
(multiple-value-list (read-from-string "012345 789" t nil
:preserve-whitespace t))
(12345 6))
(check-for-bug :streams-legacy-973
(multiple-value-list (read-from-string "012345 789" t nil :end 4))
(123 4))
(check-for-bug :streams-legacy-977
(multiple-value-list (read-from-string "012345 789" t nil :start 2))
(2345 7))
(check-for-bug :streams-legacy-981
(progn (setq strgstream (make-string-input-stream "0123456789" 5 8))
t)
t)
(check-for-bug :streams-legacy-986
(read strgstream)
567)
(check-for-bug :streams-legacy-990
(progn (setq strgstream
(make-string-input-stream "wenn alles gut geht ist das ein stream 012"))
t)
t)
(check-for-bug :streams-legacy-996
(read strgstream)
wenn)
(check-for-bug :streams-legacy-1000
(read strgstream)
alles)
(check-for-bug :streams-legacy-1004
(read strgstream)
gut)
(check-for-bug :streams-legacy-1008
(read strgstream)
geht)
(check-for-bug :streams-legacy-1012
(read strgstream)
ist)
(check-for-bug :streams-legacy-1016
(read strgstream)
das)
(check-for-bug :streams-legacy-1020
(read strgstream)
ein)
(check-for-bug :streams-legacy-1024
(read strgstream)
stream)
(check-for-bug :streams-legacy-1028
(read strgstream)
12)
(check-for-bug :streams-legacy-1032
(progn (setq strgstream (make-string-output-stream)) t)
t)
(check-for-bug :streams-legacy-1036
(princ "das " strgstream)
"das ")
(check-for-bug :streams-legacy-1040
(princ "ist " strgstream)
"ist ")
(check-for-bug :streams-legacy-1044
(princ "ein " strgstream)
"ein ")
(check-for-bug :streams-legacy-1048
(princ "string " strgstream)
"string ")
(check-for-bug :streams-legacy-1052
(princ "output " strgstream)
"output ")
(check-for-bug :streams-legacy-1056
(princ "stream " strgstream)
"stream ")
(check-for-bug :streams-legacy-1060
(get-output-stream-string strgstream)
"das ist ein string output stream ")
(check-for-bug :streams-legacy-1064
(get-output-stream-string strgstream)
"")
(check-for-bug :streams-legacy-1068
(princ "das ist ein neuer string output stream" strgstream)
"das ist ein neuer string output stream")
(check-for-bug :streams-legacy-1072
(get-output-stream-string strgstream)
"das ist ein neuer string output stream")
(check-for-bug :streams-legacy-1076
(setq *print-length* 50)
50)
(check-for-bug :streams-legacy-1080
(write-to-string 123456789)
"123456789")
(check-for-bug :streams-legacy-1084
"(write-to-string '#1=(123456789 . #1#))"
"(write-to-string '#1=(123456789 . #1#))")
(check-for-bug :streams-legacy-1088
(prin1-to-string "abc")
"\"abc\"")
(check-for-bug :streams-legacy-1092
(princ-to-string "abc")
"abc")
(check-for-bug :streams-legacy-1096
(progn (setq os (make-string-output-stream)) t)
t)
(check-for-bug :streams-legacy-1100
(setq s50 "123456789A123456789B123456789C123456789D12345678
E")
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1106
(setq s49 "123456789A123456789B123456789C123456789D1234567
*")
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1112
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1117
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1122
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1127
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1132
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1137
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1142
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1147
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1152
(princ "A" os)
"A")
(check-for-bug :streams-legacy-1156
(princ "B" os)
"B")
(check-for-bug :streams-legacy-1160
(princ "C" os)
"C")
(check-for-bug :streams-legacy-1164
(length (princ (get-output-stream-string os)))
402)
(check-for-bug :streams-legacy-1168
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1173
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1178
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1183
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1188
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1193
(princ s50 os)
"123456789A123456789B123456789C123456789D12345678
E")
(check-for-bug :streams-legacy-1198
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1203
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1208
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1213
(princ s49 os)
"123456789A123456789B123456789C123456789D1234567
*")
(check-for-bug :streams-legacy-1218
(length (princ (get-output-stream-string os)))
496)
(check-for-bug :streams-legacy-1222
(progn (setq os (open "d0.plc" :direction :output))
(setq os1 (open "d1.plc" :direction :output))
(setq is (open "t0.plc" :direction :output)) t)
t)
(check-for-bug :streams-legacy-1228
(princ "'(a b #.(print \"1.zwischenwert\" os1) c d)" is)
"'(a b #.(print \"1.zwischenwert\" os1) c d)")
(check-for-bug :streams-legacy-1232
(princ "'(a b #.(prin1-to-string \"2.zwischenwert\") c d)" is)
"'(a b #.(prin1-to-string \"2.zwischenwert\") c d)")
(check-for-bug :streams-legacy-1236
(princ "'(a b #.(format nil \"3.zwischenwert\") c d)" is)
"'(a b #.(format nil \"3.zwischenwert\") c d)")
(check-for-bug :streams-legacy-1240
(close-1 is)
t)
(check-for-bug :streams-legacy-1244
(progn (setq is (open "t0.plc")) (setq es (make-echo-stream is os))
t)
t)
(check-for-bug :streams-legacy-1249
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1253
(read es)
(quote (a b "1.zwischenwert" c d)))
(check-for-bug :streams-legacy-1257
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1261
(read es)
(quote (a b "\"2.zwischenwert\"" c d)))
(check-for-bug :streams-legacy-1265
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1269
(read es)
(quote (a b "3.zwischenwert" c d)))
(check-for-bug :streams-legacy-1273
(print "ausgabe os1" os1)
"ausgabe os1")
(check-for-bug :streams-legacy-1277
(close-1 is)
t)
(check-for-bug :streams-legacy-1281
(close-1 os)
t)
(check-for-bug :streams-legacy-1285
(progn (setq is (open "d0.plc")) t)
t)
(check-for-bug :streams-legacy-1289
(read is)
(quote (a b "1.zwischenwert" c d)))
(check-for-bug :streams-legacy-1293
(read is)
(quote (a b "\"2.zwischenwert\"" c d)))
(check-for-bug :streams-legacy-1297
(read is)
(quote (a b "3.zwischenwert" c d)))
(check-for-bug :streams-legacy-1301
(close-1 is)
t)
(check-for-bug :streams-legacy-1305
(close-1 os1)
t)
(check-for-bug :streams-legacy-1309
(progn (setq is (open "d1.plc")) t)
t)
(check-for-bug :streams-legacy-1313
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1317
(read is)
"1.zwischenwert")
(check-for-bug :streams-legacy-1321
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1325
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1329
(read is)
"ausgabe os1")
(check-for-bug :streams-legacy-1333
(read is)
"1.zwischenwert")
(check-for-bug :streams-legacy-1337
(close-1 is)
t)
(check-for-bug :streams-legacy-1341
(progn (mapc #'delete-file (directory "*.plc")) t)
t)
(check-for-bug :streams-legacy-1345
(progn
(makunbound 's)
(makunbound 's1)
(makunbound 's2)
(makunbound 's3)
(makunbound 's4)
(makunbound 's5)
(makunbound 's6)
(makunbound 's7)
(makunbound 's8)
(makunbound 's9)
(makunbound 's10)
(makunbound 'b1)
(makunbound 'b2)
(makunbound 'c1)
(makunbound 'c2)
(makunbound 'c3)
(makunbound 'c4)
(makunbound 'inptw)
(makunbound 'sy)
(makunbound 'tw)
(makunbound 'ec)
(makunbound 'str1)
(makunbound 'strgstream)
(makunbound 'os)
(makunbound 'os1)
(makunbound 'is)
(makunbound 'es)
(makunbound 's50)
(makunbound 's49)
(setq *print-length* nil)
t)
t)
|
c87d74aa037f264d61dbcaf2e33899ece3fca1d8c2d0376b0b56b69ad53d1732 | kadena-io/chainweaver | ApiClient.hs | # LANGUAGE CPP #
# LANGUAGE TupleSections #
# LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE QuasiQuotes #
Limit API to the parts that are common to chainweb and ` pact -s ` .
module Pact.Server.ApiClient
( -- * Named V1 from Pact
ApiV1API
, ApiClient(..)
, apiV1Client
-- * Parent structure for log entries
, LogEntry (..)
, WalletEvent (..)
-- * Command log structures, versioned in submodules
, CommandLog(..)
, commandLogCurrentVersion
, commandLogFilename
-- * Transaction specific logging impl
, HasTransactionLogger(..)
, TransactionLoggerT(..)
, TransactionLogger (..)
, runTransactionLoggerT
, logTransactionStdout
, logTransactionFile
, noLogger
) where
import Control.Applicative ((<|>))
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Primitive
import Control.Monad.Reader hiding (local)
import Control.Monad.Except
import Control.Exception (try, displayException, catch)
import Control.Monad.Ref
import Data.Coerce
import Data.Foldable (for_)
import Data.Proxy
import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import Language.Javascript.JSaddle (MonadJSM)
import Obelisk.Configs
import Obelisk.Route.Frontend
import Pact.Server.API
import Pact.Types.API
import Pact.Types.Command
import Pact.Types.Hash (Hash)
import Reflex.Dom.Core
import Reflex.Host.Class (MonadReflexCreateTrigger)
import Servant.API
import Servant.Client.Core hiding (Client)
import Servant.Client.JSaddle hiding (Client)
import Data.Aeson (ToJSON (..), FromJSON (..))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Text as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Builder as BSL
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.IO as LT
import qualified Data.Text.Lazy.Encoding as LT
import qualified Data.List.NonEmpty as NE
import qualified Control.Monad.Reader as Reader
import qualified Data.Map as Map
import qualified Data.Csv.Builder as Csv
import Text.Printf (printf)
import Data.Time (TimeLocale, formatTime, iso8601DateFormat)
import System.Locale.Read (getCurrentLocale)
import qualified System.Directory as Dir
import qualified System.FilePath as File
import qualified Pact.Types.Util as Pact
import Pact.Types.ChainId (ChainId)
import Pact.Server.ApiClient.V1 (CommandLog (..))
import qualified Pact.Server.ApiClient.V1 as Latest
data WalletEvent
= WalletEvent_Import
| WalletEvent_Export
deriving (Eq, Show)
instance FromJSON WalletEvent where
parseJSON = Aeson.withText "WalletEvent" $ \case
"import" -> pure WalletEvent_Import
"export" -> pure WalletEvent_Export
x -> fail $ "Unknown WalletEvent value: " <> T.unpack x
instance ToJSON WalletEvent where
toJSON WalletEvent_Import = Aeson.String "import"
toJSON WalletEvent_Export = Aeson.String "export"
data LogEntry
= LogEntry_Cmd Latest.CommandLog
| LogEntry_Event
{ _logEntry_eventType :: WalletEvent
, _logEntry_zeroKey :: Text
, _logEntry_timestamp :: UTCTime
}
encodeLogEntryEvent :: WalletEvent -> Text -> UTCTime -> Aeson.Value
encodeLogEntryEvent etype sender timestamp = Aeson.object
[ "event_type" Aeson..= etype
, "sender" Aeson..= sender
, "timestamp" Aeson..= timestamp
]
instance FromJSON LogEntry where
parseJSON v = (LogEntry_Cmd <$> parseJSON v) <|> parseLogEvent v
where
parseLogEvent = Aeson.withObject "LogEntry_Event" $ \o -> LogEntry_Event
<$> (o Aeson..: "event_type")
<*> (o Aeson..: "sender")
<*> (o Aeson..: "timestamp")
instance ToJSON LogEntry where
toJSON (LogEntry_Cmd clog) = toJSON clog
toJSON (LogEntry_Event e s t) = encodeLogEntryEvent e s t
data TransactionLogger = TransactionLogger
{ _transactionLogger_appendLog :: Latest.CommandLog -> IO ()
, _transactionLogger_walletEvent :: WalletEvent -> Text -> UTCTime -> IO ()
, _transactionLogger_destination :: Maybe FilePath
, _transactionLogger_loadLastNLogs :: Int -> IO (Either String (TimeLocale, [LogEntry]))
, _transactionLogger_exportFile :: Text -> IO (Either String (FilePath, Text))
, _transactionLogger_rotateLogFile :: IO ()
}
data ApiClient m = ApiClient
{ send :: TransactionLogger -> Text -> ChainId -> SubmitBatch -> m RequestKeys
, poll :: Poll -> m PollResponses
, listen :: ListenerRequest -> m ListenResponse
, local :: Command Text -> m (CommandResult Hash)
}
{- apiV1API :: Proxy ApiV1API -}
{- apiV1API = Proxy -}
-- | Commands are logged with the time they were sent and the node URL they were sent
to . We only define ' toJSON ' for the current version , thus only write logs in the latest
-- version.
apiV1Client :: forall m. (MonadIO m, MonadReader ClientEnv m, RunClient m) => ApiClient m
apiV1Client = ApiClient
{ send = \txnLogger sender chain batch@(SubmitBatch commands) -> do
url <- asks baseUrl
timestamp <- liftIO getCurrentTime
rqkeys <- sendF batch
for_ commands $ \command -> liftIO $ _transactionLogger_appendLog txnLogger $ CommandLog
{ _commandLog_command = command
, _commandLog_sender = sender
, _commandLog_chain = chain
, _commandLog_requestKey = NE.head $ _rkRequestKeys rqkeys
, _commandLog_timestamp = timestamp
, _commandLog_url = T.pack $ showBaseUrl url
}
pure rqkeys
, poll = pollF
, listen = listenF
, local = localF
}
where
sendF :<|> pollF :<|> listenF :<|> localF = clientIn apiV1API (Proxy :: Proxy m)
commandLogCurrentVersion :: Int
commandLogCurrentVersion = Latest.versionNumber
commandLogFilename :: FilePath
commandLogFilename = "chainweaver_transaction_log"
class HasTransactionLogger m where
askTransactionLogger :: m TransactionLogger
instance (HasTransactionLogger m, Monad m) => HasTransactionLogger (RoutedT t r m) where
askTransactionLogger = lift askTransactionLogger
instance (HasTransactionLogger m, Monad m) => HasTransactionLogger (ReaderT r m) where
askTransactionLogger = lift askTransactionLogger
newtype TransactionLoggerT m a = TransactionLoggerT
{ unTransactionLoggerT :: ReaderT TransactionLogger m a
} deriving
( Functor, Applicative, Monad, MonadTrans
, MonadFix, MonadIO, MonadRef, MonadAtomicRef
, DomBuilder t, NotReady t, MonadHold t, MonadSample t
, TriggerEvent t, PostBuild t, HasJS x
, MonadReflexCreateTrigger t, MonadQuery t q, Requester t
, HasDocument
, Routed t r, RouteToUrl r, SetRoute t r, EventWriter t w
, DomRenderHook t
, HasConfigs
)
instance PerformEvent t m => PerformEvent t (TransactionLoggerT m) where
type Performable (TransactionLoggerT m) = TransactionLoggerT (Performable m)
performEvent_ e = do
logger <- askTransactionLogger
lift . performEvent_ $ flip runTransactionLoggerT logger <$> e
performEvent e = do
logger <- askTransactionLogger
lift . performEvent $ flip runTransactionLoggerT logger <$> e
instance PrimMonad m => PrimMonad (TransactionLoggerT m) where
type PrimState (TransactionLoggerT m) = PrimState m
primitive = lift . primitive
instance HasJSContext m => HasJSContext (TransactionLoggerT m) where
type JSContextPhantom (TransactionLoggerT m) = JSContextPhantom m
askJSContext = TransactionLoggerT askJSContext
#if !defined(ghcjs_HOST_OS)
instance MonadJSM m => MonadJSM (TransactionLoggerT m)
#endif
instance (Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (TransactionLoggerT m) where
runWithReplace a0 a' = TransactionLoggerT $ runWithReplace (unTransactionLoggerT a0) (fmapCheap unTransactionLoggerT a')
traverseDMapWithKeyWithAdjust f dm0 dm' = TransactionLoggerT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TransactionLoggerT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
traverseIntMapWithKeyWithAdjust f im0 im' = TransactionLoggerT $ traverseIntMapWithKeyWithAdjust (coerce f) im0 im'
instance (Prerender js t m, Reflex t, Monad m) => Prerender js t (TransactionLoggerT m) where
type Client (TransactionLoggerT m) = TransactionLoggerT (Client m)
prerender a b = do
l <- askTransactionLogger
lift $ prerender (runTransactionLoggerT a l) (runTransactionLoggerT b l)
instance (Monad m, RunClient m) => RunClient (TransactionLoggerT m) where
runRequest = lift . runRequest
throwClientError = lift . throwClientError
instance MonadReader r m => MonadReader r (TransactionLoggerT m) where
ask = lift ask
local g t = do
l <- askTransactionLogger
lift $ Reader.local g (runTransactionLoggerT t l)
instance Monad m => HasTransactionLogger (TransactionLoggerT m) where
askTransactionLogger = TransactionLoggerT ask
runTransactionLoggerT :: TransactionLoggerT m a -> TransactionLogger -> m a
runTransactionLoggerT = runReaderT . unTransactionLoggerT
noLogger :: TransactionLogger
noLogger = TransactionLogger
{ _transactionLogger_appendLog = const $ pure ()
, _transactionLogger_walletEvent = \_ _ _ -> pure ()
, _transactionLogger_destination = Nothing
, _transactionLogger_loadLastNLogs = logsdisabled
, _transactionLogger_exportFile = logsdisabled
, _transactionLogger_rotateLogFile = pure ()
}
where
logsdisabled = const $ pure $ Left "Logs Disabled"
logTransactionStdout :: TransactionLogger
logTransactionStdout = TransactionLogger
{ _transactionLogger_appendLog = LT.putStrLn . Aeson.encodeToLazyText
, _transactionLogger_walletEvent = \wE pk t ->
T.putStrLn $ T.unwords [T.pack $ show wE, "[", pk, "]", T.pack $ show t]
, _transactionLogger_destination = Nothing
, _transactionLogger_loadLastNLogs = logsdisabled
, _transactionLogger_exportFile = logsdisabled
, _transactionLogger_rotateLogFile = pure ()
}
where
logsdisabled = const $ pure $ Left "Logs Disabled"
logTransactionFile :: FilePath -> TransactionLogger
logTransactionFile f = TransactionLogger
{ _transactionLogger_appendLog =
LT.appendFile f . (<> "\n") . Aeson.encodeToLazyText
, _transactionLogger_walletEvent = \etype pk t ->
LT.appendFile f $ (<> "\n") $ Aeson.encodeToLazyText $ encodeLogEntryEvent etype pk t
, _transactionLogger_destination =
Just f
, _transactionLogger_loadLastNLogs = \n -> runExceptT $ do
logmsg $ printf "Loading logs from: %s" f
nLogs <- liftIO (Dir.doesFileExist f) >>= \case
True -> do
logmsg "Log file exists"
ExceptT $ over (mapped . _Left) ppIOException $ try $ lastN n . BS8.lines <$> BS.readFile f
False -> do
logmsg $ printf "No log file found at %s" f
throwError "Chainweaver transaction log is currently empty"
tl <- liftIO getCurrentLocale
xs <- liftEither $ traverse Aeson.eitherDecodeStrict nLogs
pure (tl,xs)
, _transactionLogger_exportFile = \pk ->
createCommandLogExportFileV1 pk f
, _transactionLogger_rotateLogFile = Dir.doesFileExist f >>= \exists -> when exists $ do
putStrLn "Moving existing log file."
tl <- getCurrentLocale
nowish <- getCurrentTime
let timestamp = formatTime tl (iso8601DateFormat (Just "%H-%M-%S")) nowish
catch (Dir.renameFile f $ printf "%s_v%i_%s" f commandLogCurrentVersion timestamp) $ \(e :: IOError) ->
putStrLn $ "Unable to move existing log file. Reason: " <> displayException e
}
where
logmsg = liftIO . putStrLn
lastN n as = drop (length as - n) as
ppIOException :: IOError -> String
ppIOException = displayException
createCommandLogExportFileV1 :: Text -> FilePath -> IO (Either String (FilePath, Text))
createCommandLogExportFileV1 filePfx fp = runExceptT $ do
let
-- Use system-filepath to avoid being caught out by platform differences
filename = snd $ File.splitFileName fp
exportFilePath = printf "%s_%s_v%i" filePfx filename commandLogCurrentVersion
logContents <- ExceptT $ catch (Right . BS8.lines <$> BS.readFile fp)
$ \(e :: IOError) -> pure $ Left $ displayException e
xs <- liftEither $ traverse Aeson.eitherDecodeStrict logContents
let
aesonTextEncode :: ToJSON a => a -> Text
aesonTextEncode = LT.toStrict . LT.decodeUtf8With T.lenientDecode . Aeson.encode
toCsv i (LogEntry_Cmd cmdLog) = Latest.exportCommandLog i cmdLog
toCsv i (LogEntry_Event eType sender timestamp) = Csv.encodeNamedRecord Latest.exportHeader $ Map.fromList
[ ("index" :: BSL.ByteString, Pact.tShow i)
, ("timestamp", aesonTextEncode timestamp)
, ("sender", sender)
, ("chain", mempty)
, ("requestKey", aesonTextEncode eType)
, ("url", mempty)
, ("command_payload", mempty)
, ("command_sigs", mempty)
, ("command_hash", mempty)
]
let
csvContents = BSL.toStrict $ BSL.toLazyByteString $ ifoldMap toCsv xs
pure (exportFilePath, T.decodeUtf8With T.lenientDecode csvContents)
| null | https://raw.githubusercontent.com/kadena-io/chainweaver/4e9af3848b86ecda244c1e111899b4a2ac16bf28/frontend/src/Pact/Server/ApiClient.hs | haskell | * Named V1 from Pact
* Parent structure for log entries
* Command log structures, versioned in submodules
* Transaction specific logging impl
apiV1API :: Proxy ApiV1API
apiV1API = Proxy
| Commands are logged with the time they were sent and the node URL they were sent
version.
Use system-filepath to avoid being caught out by platform differences | # LANGUAGE CPP #
# LANGUAGE TupleSections #
# LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE QuasiQuotes #
Limit API to the parts that are common to chainweb and ` pact -s ` .
module Pact.Server.ApiClient
ApiV1API
, ApiClient(..)
, apiV1Client
, LogEntry (..)
, WalletEvent (..)
, CommandLog(..)
, commandLogCurrentVersion
, commandLogFilename
, HasTransactionLogger(..)
, TransactionLoggerT(..)
, TransactionLogger (..)
, runTransactionLoggerT
, logTransactionStdout
, logTransactionFile
, noLogger
) where
import Control.Applicative ((<|>))
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Primitive
import Control.Monad.Reader hiding (local)
import Control.Monad.Except
import Control.Exception (try, displayException, catch)
import Control.Monad.Ref
import Data.Coerce
import Data.Foldable (for_)
import Data.Proxy
import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import Language.Javascript.JSaddle (MonadJSM)
import Obelisk.Configs
import Obelisk.Route.Frontend
import Pact.Server.API
import Pact.Types.API
import Pact.Types.Command
import Pact.Types.Hash (Hash)
import Reflex.Dom.Core
import Reflex.Host.Class (MonadReflexCreateTrigger)
import Servant.API
import Servant.Client.Core hiding (Client)
import Servant.Client.JSaddle hiding (Client)
import Data.Aeson (ToJSON (..), FromJSON (..))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Text as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Builder as BSL
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.IO as LT
import qualified Data.Text.Lazy.Encoding as LT
import qualified Data.List.NonEmpty as NE
import qualified Control.Monad.Reader as Reader
import qualified Data.Map as Map
import qualified Data.Csv.Builder as Csv
import Text.Printf (printf)
import Data.Time (TimeLocale, formatTime, iso8601DateFormat)
import System.Locale.Read (getCurrentLocale)
import qualified System.Directory as Dir
import qualified System.FilePath as File
import qualified Pact.Types.Util as Pact
import Pact.Types.ChainId (ChainId)
import Pact.Server.ApiClient.V1 (CommandLog (..))
import qualified Pact.Server.ApiClient.V1 as Latest
data WalletEvent
= WalletEvent_Import
| WalletEvent_Export
deriving (Eq, Show)
instance FromJSON WalletEvent where
parseJSON = Aeson.withText "WalletEvent" $ \case
"import" -> pure WalletEvent_Import
"export" -> pure WalletEvent_Export
x -> fail $ "Unknown WalletEvent value: " <> T.unpack x
instance ToJSON WalletEvent where
toJSON WalletEvent_Import = Aeson.String "import"
toJSON WalletEvent_Export = Aeson.String "export"
data LogEntry
= LogEntry_Cmd Latest.CommandLog
| LogEntry_Event
{ _logEntry_eventType :: WalletEvent
, _logEntry_zeroKey :: Text
, _logEntry_timestamp :: UTCTime
}
encodeLogEntryEvent :: WalletEvent -> Text -> UTCTime -> Aeson.Value
encodeLogEntryEvent etype sender timestamp = Aeson.object
[ "event_type" Aeson..= etype
, "sender" Aeson..= sender
, "timestamp" Aeson..= timestamp
]
instance FromJSON LogEntry where
parseJSON v = (LogEntry_Cmd <$> parseJSON v) <|> parseLogEvent v
where
parseLogEvent = Aeson.withObject "LogEntry_Event" $ \o -> LogEntry_Event
<$> (o Aeson..: "event_type")
<*> (o Aeson..: "sender")
<*> (o Aeson..: "timestamp")
instance ToJSON LogEntry where
toJSON (LogEntry_Cmd clog) = toJSON clog
toJSON (LogEntry_Event e s t) = encodeLogEntryEvent e s t
data TransactionLogger = TransactionLogger
{ _transactionLogger_appendLog :: Latest.CommandLog -> IO ()
, _transactionLogger_walletEvent :: WalletEvent -> Text -> UTCTime -> IO ()
, _transactionLogger_destination :: Maybe FilePath
, _transactionLogger_loadLastNLogs :: Int -> IO (Either String (TimeLocale, [LogEntry]))
, _transactionLogger_exportFile :: Text -> IO (Either String (FilePath, Text))
, _transactionLogger_rotateLogFile :: IO ()
}
data ApiClient m = ApiClient
{ send :: TransactionLogger -> Text -> ChainId -> SubmitBatch -> m RequestKeys
, poll :: Poll -> m PollResponses
, listen :: ListenerRequest -> m ListenResponse
, local :: Command Text -> m (CommandResult Hash)
}
to . We only define ' toJSON ' for the current version , thus only write logs in the latest
apiV1Client :: forall m. (MonadIO m, MonadReader ClientEnv m, RunClient m) => ApiClient m
apiV1Client = ApiClient
{ send = \txnLogger sender chain batch@(SubmitBatch commands) -> do
url <- asks baseUrl
timestamp <- liftIO getCurrentTime
rqkeys <- sendF batch
for_ commands $ \command -> liftIO $ _transactionLogger_appendLog txnLogger $ CommandLog
{ _commandLog_command = command
, _commandLog_sender = sender
, _commandLog_chain = chain
, _commandLog_requestKey = NE.head $ _rkRequestKeys rqkeys
, _commandLog_timestamp = timestamp
, _commandLog_url = T.pack $ showBaseUrl url
}
pure rqkeys
, poll = pollF
, listen = listenF
, local = localF
}
where
sendF :<|> pollF :<|> listenF :<|> localF = clientIn apiV1API (Proxy :: Proxy m)
commandLogCurrentVersion :: Int
commandLogCurrentVersion = Latest.versionNumber
commandLogFilename :: FilePath
commandLogFilename = "chainweaver_transaction_log"
class HasTransactionLogger m where
askTransactionLogger :: m TransactionLogger
instance (HasTransactionLogger m, Monad m) => HasTransactionLogger (RoutedT t r m) where
askTransactionLogger = lift askTransactionLogger
instance (HasTransactionLogger m, Monad m) => HasTransactionLogger (ReaderT r m) where
askTransactionLogger = lift askTransactionLogger
newtype TransactionLoggerT m a = TransactionLoggerT
{ unTransactionLoggerT :: ReaderT TransactionLogger m a
} deriving
( Functor, Applicative, Monad, MonadTrans
, MonadFix, MonadIO, MonadRef, MonadAtomicRef
, DomBuilder t, NotReady t, MonadHold t, MonadSample t
, TriggerEvent t, PostBuild t, HasJS x
, MonadReflexCreateTrigger t, MonadQuery t q, Requester t
, HasDocument
, Routed t r, RouteToUrl r, SetRoute t r, EventWriter t w
, DomRenderHook t
, HasConfigs
)
instance PerformEvent t m => PerformEvent t (TransactionLoggerT m) where
type Performable (TransactionLoggerT m) = TransactionLoggerT (Performable m)
performEvent_ e = do
logger <- askTransactionLogger
lift . performEvent_ $ flip runTransactionLoggerT logger <$> e
performEvent e = do
logger <- askTransactionLogger
lift . performEvent $ flip runTransactionLoggerT logger <$> e
instance PrimMonad m => PrimMonad (TransactionLoggerT m) where
type PrimState (TransactionLoggerT m) = PrimState m
primitive = lift . primitive
instance HasJSContext m => HasJSContext (TransactionLoggerT m) where
type JSContextPhantom (TransactionLoggerT m) = JSContextPhantom m
askJSContext = TransactionLoggerT askJSContext
#if !defined(ghcjs_HOST_OS)
instance MonadJSM m => MonadJSM (TransactionLoggerT m)
#endif
instance (Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (TransactionLoggerT m) where
runWithReplace a0 a' = TransactionLoggerT $ runWithReplace (unTransactionLoggerT a0) (fmapCheap unTransactionLoggerT a')
traverseDMapWithKeyWithAdjust f dm0 dm' = TransactionLoggerT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'
traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TransactionLoggerT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'
traverseIntMapWithKeyWithAdjust f im0 im' = TransactionLoggerT $ traverseIntMapWithKeyWithAdjust (coerce f) im0 im'
instance (Prerender js t m, Reflex t, Monad m) => Prerender js t (TransactionLoggerT m) where
type Client (TransactionLoggerT m) = TransactionLoggerT (Client m)
prerender a b = do
l <- askTransactionLogger
lift $ prerender (runTransactionLoggerT a l) (runTransactionLoggerT b l)
instance (Monad m, RunClient m) => RunClient (TransactionLoggerT m) where
runRequest = lift . runRequest
throwClientError = lift . throwClientError
instance MonadReader r m => MonadReader r (TransactionLoggerT m) where
ask = lift ask
local g t = do
l <- askTransactionLogger
lift $ Reader.local g (runTransactionLoggerT t l)
instance Monad m => HasTransactionLogger (TransactionLoggerT m) where
askTransactionLogger = TransactionLoggerT ask
runTransactionLoggerT :: TransactionLoggerT m a -> TransactionLogger -> m a
runTransactionLoggerT = runReaderT . unTransactionLoggerT
noLogger :: TransactionLogger
noLogger = TransactionLogger
{ _transactionLogger_appendLog = const $ pure ()
, _transactionLogger_walletEvent = \_ _ _ -> pure ()
, _transactionLogger_destination = Nothing
, _transactionLogger_loadLastNLogs = logsdisabled
, _transactionLogger_exportFile = logsdisabled
, _transactionLogger_rotateLogFile = pure ()
}
where
logsdisabled = const $ pure $ Left "Logs Disabled"
logTransactionStdout :: TransactionLogger
logTransactionStdout = TransactionLogger
{ _transactionLogger_appendLog = LT.putStrLn . Aeson.encodeToLazyText
, _transactionLogger_walletEvent = \wE pk t ->
T.putStrLn $ T.unwords [T.pack $ show wE, "[", pk, "]", T.pack $ show t]
, _transactionLogger_destination = Nothing
, _transactionLogger_loadLastNLogs = logsdisabled
, _transactionLogger_exportFile = logsdisabled
, _transactionLogger_rotateLogFile = pure ()
}
where
logsdisabled = const $ pure $ Left "Logs Disabled"
logTransactionFile :: FilePath -> TransactionLogger
logTransactionFile f = TransactionLogger
{ _transactionLogger_appendLog =
LT.appendFile f . (<> "\n") . Aeson.encodeToLazyText
, _transactionLogger_walletEvent = \etype pk t ->
LT.appendFile f $ (<> "\n") $ Aeson.encodeToLazyText $ encodeLogEntryEvent etype pk t
, _transactionLogger_destination =
Just f
, _transactionLogger_loadLastNLogs = \n -> runExceptT $ do
logmsg $ printf "Loading logs from: %s" f
nLogs <- liftIO (Dir.doesFileExist f) >>= \case
True -> do
logmsg "Log file exists"
ExceptT $ over (mapped . _Left) ppIOException $ try $ lastN n . BS8.lines <$> BS.readFile f
False -> do
logmsg $ printf "No log file found at %s" f
throwError "Chainweaver transaction log is currently empty"
tl <- liftIO getCurrentLocale
xs <- liftEither $ traverse Aeson.eitherDecodeStrict nLogs
pure (tl,xs)
, _transactionLogger_exportFile = \pk ->
createCommandLogExportFileV1 pk f
, _transactionLogger_rotateLogFile = Dir.doesFileExist f >>= \exists -> when exists $ do
putStrLn "Moving existing log file."
tl <- getCurrentLocale
nowish <- getCurrentTime
let timestamp = formatTime tl (iso8601DateFormat (Just "%H-%M-%S")) nowish
catch (Dir.renameFile f $ printf "%s_v%i_%s" f commandLogCurrentVersion timestamp) $ \(e :: IOError) ->
putStrLn $ "Unable to move existing log file. Reason: " <> displayException e
}
where
logmsg = liftIO . putStrLn
lastN n as = drop (length as - n) as
ppIOException :: IOError -> String
ppIOException = displayException
createCommandLogExportFileV1 :: Text -> FilePath -> IO (Either String (FilePath, Text))
createCommandLogExportFileV1 filePfx fp = runExceptT $ do
let
filename = snd $ File.splitFileName fp
exportFilePath = printf "%s_%s_v%i" filePfx filename commandLogCurrentVersion
logContents <- ExceptT $ catch (Right . BS8.lines <$> BS.readFile fp)
$ \(e :: IOError) -> pure $ Left $ displayException e
xs <- liftEither $ traverse Aeson.eitherDecodeStrict logContents
let
aesonTextEncode :: ToJSON a => a -> Text
aesonTextEncode = LT.toStrict . LT.decodeUtf8With T.lenientDecode . Aeson.encode
toCsv i (LogEntry_Cmd cmdLog) = Latest.exportCommandLog i cmdLog
toCsv i (LogEntry_Event eType sender timestamp) = Csv.encodeNamedRecord Latest.exportHeader $ Map.fromList
[ ("index" :: BSL.ByteString, Pact.tShow i)
, ("timestamp", aesonTextEncode timestamp)
, ("sender", sender)
, ("chain", mempty)
, ("requestKey", aesonTextEncode eType)
, ("url", mempty)
, ("command_payload", mempty)
, ("command_sigs", mempty)
, ("command_hash", mempty)
]
let
csvContents = BSL.toStrict $ BSL.toLazyByteString $ ifoldMap toCsv xs
pure (exportFilePath, T.decodeUtf8With T.lenientDecode csvContents)
|
593830550afc65c64987497c7ee6ddc982fa8522363bba67f717b5188d3f215b | MarkCurtiss/sicp | 3_77_to_3_82_spec.scm | (load "3_77_to_3_82.scm")
(describe "Delayed integral"
(it "can be used in solvers with delayed functions"
(lambda ()
(define (solve f y0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (stream-map f y))
y)
(assert (equal?
(stream-ref (solve (lambda (y) y) 1 0.001) 1000)
2.716923932235896))
))
(it "can solve 2nd order differential equations"
(lambda ()
(define 2nd-deriv-test (solve-2nd 2 3 5 8 13))
(assert (equal?
(first-n-elements-of-stream 2nd-deriv-test 5)
'(8 73 1388 21328 344768)))
))
(it "can solve some other type of 2nd order differential equations"
(lambda ()
(define 2nd-deriv-test (solve-2nd-with-f * 3 5 8))
(assert (equal?
(first-n-elements-of-stream 2nd-deriv-test 5)
'(5 29 413 34205 41936285)))
))
)
(describe "RLC circuits"
(it "takes a bunch of inputs and outputs a stream vC (voltage across the capacitor) and iL (current in the inductor)"
(lambda ()
(define vC0 10)
(define iL0 0)
(define RLC1 (RLC 1 1 0.2 0.1))
(define output-streams (RLC1 vC0 il0))
(assert (equal?
(first-n-elements-of-stream (car output-streams) 5)
'(10 10 9.5 8.55 7.220000000000001)))
(assert (equal?
(first-n-elements-of-stream (cdr output-streams) 5)
'(0 1. 1.9 2.66 3.249)))
))
)
(describe "rand"
(it "lets you generate random numbers from a stream of input requests"
(lambda ()
(define generate (list 'generate 'throwawayvalue))
(define inputs (cons-stream generate inputs))
(define rands (rand inputs))
(assert (equal?
(first-n-elements-of-stream rands 3)
'(0 1 2)))
))
(it "lets you reset the sequence"
(lambda ()
(define generate (list 'generate 'throwawayvalue))
(define reset (list 'reset 8))
(define inputs (stream generate generate reset generate generate generate))
(define rands (rand inputs))
(assert (equal?
(first-n-elements-of-stream rands 5)
'(0 1 2 8 9)))
))
)
(describe "Monte Carlo integration"
(it "estimates the integral of a circle of radius 3 centered at (5,7)"
(lambda ()
(define (predicate x y)
(<=
(+ (square (- x 5))
(square (- y 7)))
(square 3)))
(define estimates (estimate-integral predicate 2.0 8.0 4.0 10.0))
(assert (equal?
(floor (stream-ref estimates 10000))
28.0))
))
)
| null | https://raw.githubusercontent.com/MarkCurtiss/sicp/8b55a3371458014c815ba8792218b6440127ab40/chapter_3_exercises/spec/3_77_to_3_82_spec.scm | scheme | (load "3_77_to_3_82.scm")
(describe "Delayed integral"
(it "can be used in solvers with delayed functions"
(lambda ()
(define (solve f y0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (stream-map f y))
y)
(assert (equal?
(stream-ref (solve (lambda (y) y) 1 0.001) 1000)
2.716923932235896))
))
(it "can solve 2nd order differential equations"
(lambda ()
(define 2nd-deriv-test (solve-2nd 2 3 5 8 13))
(assert (equal?
(first-n-elements-of-stream 2nd-deriv-test 5)
'(8 73 1388 21328 344768)))
))
(it "can solve some other type of 2nd order differential equations"
(lambda ()
(define 2nd-deriv-test (solve-2nd-with-f * 3 5 8))
(assert (equal?
(first-n-elements-of-stream 2nd-deriv-test 5)
'(5 29 413 34205 41936285)))
))
)
(describe "RLC circuits"
(it "takes a bunch of inputs and outputs a stream vC (voltage across the capacitor) and iL (current in the inductor)"
(lambda ()
(define vC0 10)
(define iL0 0)
(define RLC1 (RLC 1 1 0.2 0.1))
(define output-streams (RLC1 vC0 il0))
(assert (equal?
(first-n-elements-of-stream (car output-streams) 5)
'(10 10 9.5 8.55 7.220000000000001)))
(assert (equal?
(first-n-elements-of-stream (cdr output-streams) 5)
'(0 1. 1.9 2.66 3.249)))
))
)
(describe "rand"
(it "lets you generate random numbers from a stream of input requests"
(lambda ()
(define generate (list 'generate 'throwawayvalue))
(define inputs (cons-stream generate inputs))
(define rands (rand inputs))
(assert (equal?
(first-n-elements-of-stream rands 3)
'(0 1 2)))
))
(it "lets you reset the sequence"
(lambda ()
(define generate (list 'generate 'throwawayvalue))
(define reset (list 'reset 8))
(define inputs (stream generate generate reset generate generate generate))
(define rands (rand inputs))
(assert (equal?
(first-n-elements-of-stream rands 5)
'(0 1 2 8 9)))
))
)
(describe "Monte Carlo integration"
(it "estimates the integral of a circle of radius 3 centered at (5,7)"
(lambda ()
(define (predicate x y)
(<=
(+ (square (- x 5))
(square (- y 7)))
(square 3)))
(define estimates (estimate-integral predicate 2.0 8.0 4.0 10.0))
(assert (equal?
(floor (stream-ref estimates 10000))
28.0))
))
)
| |
56277e1f06878233d2f6d24867aee9a931e1b7bf8237a03f8b87212ad5a03a50 | threatgrid/ctim | openc2vocabularies.cljc | (ns ctim.schemas.openc2vocabularies
(:require #?(:clj [flanders.core :refer [def-enum-type]]
:cljs [flanders.core :refer-macros [def-enum-type]])))
(def COA-type
#{"alert"
"allow"
"augment"
"contain"
"delete"
"deny"
"detonate"
"distill"
"get"
"investigate"
"locate"
"mitigate"
"modify"
"move"
"notify"
"other"
"pause"
"query"
"redirect"
"remediate"
"report"
"response"
"restart"
"restore"
"resume"
"save"
"scan"
"set"
"snapshot"
"start"
"stop"
"substitute"
"sync"
"throttle"
"update"})
(def-enum-type COAType
COA-type
:reference (str "[OpenC2/STIX COA XML schema](https://"
"github.com/OpenC2-org/subgroup-stix/blob/"
"master/schema/openc2_stix_coa.xsd)"))
(def actuator-type
#{"endpoint",
"endpoint.digital-telephone-handset",
"endpoint.laptop",
"endpoint.pos-terminal",
"endpoint.printer",
"endpoint.sensor",
"endpoint.server",
"endpoint.smart-meter",
"endpoint.smart-phone",
"endpoint.tablet",
"endpoint.workstation",
"network",
"network.bridge",
"network.firewall",
"network.gateway",
"network.guard",
"network.hips",
"network.hub",
"network.ids",
"network.ips",
"network.modem",
"network.nic",
"network.proxy",
"network.router",
"network.security_manager",
"network.sense_making",
"network.sensor",
"network.switch",
"network.vpn",
"network.wap",
"process",
"process.aaa-server",
"process.anti-virus-scanner",
"process.connection-scanner",
"process.directory-service",
"process.dns-server",
"process.email-service",
"process.file-scanner",
"process.location-service",
"process.network-scanner",
"process.remediation-service",
"process.reputation-service",
"process.sandbox",
"process.virtualization-service",
"process.vulnerability-scanner",
"other"})
(def-enum-type ActuatorType actuator-type)
(def modifier-type
#{"delay"
"duration"
"frequency"
"response"
"time"
"reportTo"})
(def-enum-type ModifierType modifier-type)
(def location-class
#{"Internally-Located"
"Externally-Located"
"Co-Located"
"Mobile"
"Unknown"})
(def-enum-type LocationClass location-class)
(def loss-duration
#{"Permanent"
"Weeks"
"Days"
"Hours"
"Minutes"
"Seconds"
"Unknown"})
(def-enum-type LossDuration loss-duration)
| null | https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/src/ctim/schemas/openc2vocabularies.cljc | clojure | (ns ctim.schemas.openc2vocabularies
(:require #?(:clj [flanders.core :refer [def-enum-type]]
:cljs [flanders.core :refer-macros [def-enum-type]])))
(def COA-type
#{"alert"
"allow"
"augment"
"contain"
"delete"
"deny"
"detonate"
"distill"
"get"
"investigate"
"locate"
"mitigate"
"modify"
"move"
"notify"
"other"
"pause"
"query"
"redirect"
"remediate"
"report"
"response"
"restart"
"restore"
"resume"
"save"
"scan"
"set"
"snapshot"
"start"
"stop"
"substitute"
"sync"
"throttle"
"update"})
(def-enum-type COAType
COA-type
:reference (str "[OpenC2/STIX COA XML schema](https://"
"github.com/OpenC2-org/subgroup-stix/blob/"
"master/schema/openc2_stix_coa.xsd)"))
(def actuator-type
#{"endpoint",
"endpoint.digital-telephone-handset",
"endpoint.laptop",
"endpoint.pos-terminal",
"endpoint.printer",
"endpoint.sensor",
"endpoint.server",
"endpoint.smart-meter",
"endpoint.smart-phone",
"endpoint.tablet",
"endpoint.workstation",
"network",
"network.bridge",
"network.firewall",
"network.gateway",
"network.guard",
"network.hips",
"network.hub",
"network.ids",
"network.ips",
"network.modem",
"network.nic",
"network.proxy",
"network.router",
"network.security_manager",
"network.sense_making",
"network.sensor",
"network.switch",
"network.vpn",
"network.wap",
"process",
"process.aaa-server",
"process.anti-virus-scanner",
"process.connection-scanner",
"process.directory-service",
"process.dns-server",
"process.email-service",
"process.file-scanner",
"process.location-service",
"process.network-scanner",
"process.remediation-service",
"process.reputation-service",
"process.sandbox",
"process.virtualization-service",
"process.vulnerability-scanner",
"other"})
(def-enum-type ActuatorType actuator-type)
(def modifier-type
#{"delay"
"duration"
"frequency"
"response"
"time"
"reportTo"})
(def-enum-type ModifierType modifier-type)
(def location-class
#{"Internally-Located"
"Externally-Located"
"Co-Located"
"Mobile"
"Unknown"})
(def-enum-type LocationClass location-class)
(def loss-duration
#{"Permanent"
"Weeks"
"Days"
"Hours"
"Minutes"
"Seconds"
"Unknown"})
(def-enum-type LossDuration loss-duration)
| |
25c43fb130859559f520b81d7051b1dbdb00d7709fddf1165438895c578513df | dongcarl/guix | lean.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages lean)
#:use-module (gnu packages multiprecision)
#:use-module (guix build-system cmake)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix git-download))
(define-public lean
(package
(name "lean")
(version "3.23.0")
(home-page "-community/lean")
(source (origin
(method git-fetch)
(uri (git-reference (url home-page)
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"09mklc1p6ms1jayg2f89hqfmhca3h5744lli936l38ypn1d00sxx"))))
(build-system cmake-build-system)
(inputs
`(("gmp" ,gmp)))
(arguments
`(#:build-type "Release" ; default upstream build type
XXX : Test phases currently fail on 32 - bit sytems .
;; Tests for those architectures have been temporarily
;; disabled, pending further investigation.
#:tests? ,(let ((arch (or (%current-target-system)
(%current-system))))
(not (or (string-prefix? "i686" arch)
(string-prefix? "armhf" arch))))
#:phases
(modify-phases %standard-phases
(add-after 'patch-source-shebangs 'patch-tests-shebangs
(lambda _
(let ((sh (which "sh"))
(bash (which "bash")))
(substitute* (find-files "tests/lean" "\\.sh$")
(("#![[:blank:]]?/bin/sh")
(string-append "#!" sh))
(("#![[:blank:]]?/bin/bash")
(string-append "#!" bash))
(("#![[:blank:]]?usr/bin/env bash")
(string-append "#!" bash)))
#t)))
(add-before 'configure 'chdir-to-src
(lambda _ (chdir "src") #t)))))
(synopsis "Theorem prover and programming language")
(description
"Lean is a theorem prover and programming language with a small trusted
core based on dependent typed theory, aiming to bridge the gap between
interactive and automated theorem proving.")
(license license:asl2.0)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/lean.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
default upstream build type
Tests for those architectures have been temporarily
disabled, pending further investigation. | Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages lean)
#:use-module (gnu packages multiprecision)
#:use-module (guix build-system cmake)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix git-download))
(define-public lean
(package
(name "lean")
(version "3.23.0")
(home-page "-community/lean")
(source (origin
(method git-fetch)
(uri (git-reference (url home-page)
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"09mklc1p6ms1jayg2f89hqfmhca3h5744lli936l38ypn1d00sxx"))))
(build-system cmake-build-system)
(inputs
`(("gmp" ,gmp)))
(arguments
XXX : Test phases currently fail on 32 - bit sytems .
#:tests? ,(let ((arch (or (%current-target-system)
(%current-system))))
(not (or (string-prefix? "i686" arch)
(string-prefix? "armhf" arch))))
#:phases
(modify-phases %standard-phases
(add-after 'patch-source-shebangs 'patch-tests-shebangs
(lambda _
(let ((sh (which "sh"))
(bash (which "bash")))
(substitute* (find-files "tests/lean" "\\.sh$")
(("#![[:blank:]]?/bin/sh")
(string-append "#!" sh))
(("#![[:blank:]]?/bin/bash")
(string-append "#!" bash))
(("#![[:blank:]]?usr/bin/env bash")
(string-append "#!" bash)))
#t)))
(add-before 'configure 'chdir-to-src
(lambda _ (chdir "src") #t)))))
(synopsis "Theorem prover and programming language")
(description
"Lean is a theorem prover and programming language with a small trusted
core based on dependent typed theory, aiming to bridge the gap between
interactive and automated theorem proving.")
(license license:asl2.0)))
|
783a18c9ad853e268bb67f15666b0f8c87d6e7d81eab5ea5a5458467cc4d4796 | serokell/ariadne | Orphans.hs | # OPTIONS_GHC -fno - warn - orphans #
module Ariadne.Cardano.Orphans () where
import Pos.Client.CLI.NodeOptions (CommonNodeArgs(..))
import Pos.Client.CLI.Options (CommonArgs(..))
import Pos.Client.Txp.Util (InputSelectionPolicy(..))
import Pos.Infra.Network.CLI (NetworkConfigOpts(..))
import Pos.Infra.Statistics (EkgParams(..), StatsdParams(..))
import Pos.Launcher
deriving instance Eq CommonNodeArgs
deriving instance Eq NetworkConfigOpts
deriving instance Eq CommonArgs
deriving instance Eq EkgParams
deriving instance Eq ConfigurationOptions
deriving instance Eq StatsdParams
deriving instance Ord InputSelectionPolicy
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Cardano/Orphans.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Ariadne.Cardano.Orphans () where
import Pos.Client.CLI.NodeOptions (CommonNodeArgs(..))
import Pos.Client.CLI.Options (CommonArgs(..))
import Pos.Client.Txp.Util (InputSelectionPolicy(..))
import Pos.Infra.Network.CLI (NetworkConfigOpts(..))
import Pos.Infra.Statistics (EkgParams(..), StatsdParams(..))
import Pos.Launcher
deriving instance Eq CommonNodeArgs
deriving instance Eq NetworkConfigOpts
deriving instance Eq CommonArgs
deriving instance Eq EkgParams
deriving instance Eq ConfigurationOptions
deriving instance Eq StatsdParams
deriving instance Ord InputSelectionPolicy
| |
caaf1141cb0053c6db6b81f7e0795646a340ea34673d1a91945a067d70b52ae5 | karlhof26/gimp-scheme | AutoColorize_FlavorA_1_02.scm | ; Auto colorize image into random number of colors of random hues
author :
date : 2015
; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program; if not, see <>.
;
; Define the function
(define (script-fu-auto-colorize-a
image
layer
hatches
)
(let* (
(color-map 0)
(colors 0)
(red 0)
(green 0)
(blue 0)
(y 0)
(hue 0)
(floating 0)
)
;(gimp-image-undo-disable image); DN = NO UNDO
undo - group in one step
; (gimp-message "one")
;convert to indexed
(gimp-image-convert-indexed image CONVERT-DITHER-NONE CONVERT-PALETTE-GENERATE hatches FALSE FALSE "unused palette name")
;grabs color map
(set! colors (vector->list (cadr (gimp-image-get-colormap image))))
(gimp-image-convert-rgb image) ;converts it to rgb before we call hatch loop
(set! y hatches) ;loop hatches number of times
(srand (car (gettimeofday)))
(gimp-context-set-sample-threshold 0.01) ; was 0
( gimp - message " two " )
(while (> y 0)
;do work here
( gimp - message " three " )
(set! red (car colors))
(set! green (cadr colors))
(set! blue (caddr colors))
;select each color
(gimp-image-set-active-layer image layer)
(gimp-image-select-color image CHANNEL-OP-REPLACE layer (list red green blue))
( set ! hue ( rand 360 ) )
( gimp - colorize layer hue 100 0 )
(gimp-edit-copy layer)
(set! floating (car(gimp-edit-paste layer TRUE)))
(gimp-floating-sel-to-layer floating)
(gimp-image-set-active-layer image floating)
was rand 360
(gimp-drawable-colorize-hsl floating hue 100 0)
( script - fu - colorize image floating ( list ( rand 255 ) ( rand 255 ) ( rand 255 ) ) 100 )
(if (> y 1) ;if y is still valid we set colors to the next colors
(begin
(set! colors (cdddr colors))
)
(begin ;else
)
)
;loop control
(set! y (- y 1))
);end of while
( gimp - message " four " )
(gimp-selection-none image)
;(gimp-image-undo-enable image) ;DN = NO UNDO
undo group in one step
(gimp-displays-flush)
)
) ;end of define
(script-fu-register
"script-fu-auto-colorize-a" ;function name
"<Image>/Script-Fu2/Create from Image/Auto Colorize Flavor A" ;menu register
"Randomly colorize image with specified number of colors. \nfile:AutoColorize_FlavorA_1_02.scm" ;description
"Tin Tran" ;author name
"copyright info and description" ;copyright info or description
"2015" ;date
"RGB*, GRAY*" ;mode
SF-IMAGE "Image" 0
SF-DRAWABLE "Layer" 0
SF-ADJUSTMENT "Number of colors" '(5 2 255 1 10 0 0)
)
;------------------------
;end of script | null | https://raw.githubusercontent.com/karlhof26/gimp-scheme/b79c32f34e365d7579f1ca17144fb144b79a86e4/AutoColorize_FlavorA_1_02.scm | scheme | Auto colorize image into random number of colors of random hues
This program is free software; you can redistribute it and/or modify
either version 3 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, see <>.
Define the function
(gimp-image-undo-disable image); DN = NO UNDO
(gimp-message "one")
convert to indexed
grabs color map
converts it to rgb before we call hatch loop
loop hatches number of times
was 0
do work here
select each color
if y is still valid we set colors to the next colors
else
loop control
end of while
(gimp-image-undo-enable image) ;DN = NO UNDO
end of define
function name
menu register
description
author name
copyright info or description
date
mode
------------------------
end of script | author :
date : 2015
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(define (script-fu-auto-colorize-a
image
layer
hatches
)
(let* (
(color-map 0)
(colors 0)
(red 0)
(green 0)
(blue 0)
(y 0)
(hue 0)
(floating 0)
)
undo - group in one step
(gimp-image-convert-indexed image CONVERT-DITHER-NONE CONVERT-PALETTE-GENERATE hatches FALSE FALSE "unused palette name")
(set! colors (vector->list (cadr (gimp-image-get-colormap image))))
(srand (car (gettimeofday)))
( gimp - message " two " )
(while (> y 0)
( gimp - message " three " )
(set! red (car colors))
(set! green (cadr colors))
(set! blue (caddr colors))
(gimp-image-set-active-layer image layer)
(gimp-image-select-color image CHANNEL-OP-REPLACE layer (list red green blue))
( set ! hue ( rand 360 ) )
( gimp - colorize layer hue 100 0 )
(gimp-edit-copy layer)
(set! floating (car(gimp-edit-paste layer TRUE)))
(gimp-floating-sel-to-layer floating)
(gimp-image-set-active-layer image floating)
was rand 360
(gimp-drawable-colorize-hsl floating hue 100 0)
( script - fu - colorize image floating ( list ( rand 255 ) ( rand 255 ) ( rand 255 ) ) 100 )
(begin
(set! colors (cdddr colors))
)
)
)
(set! y (- y 1))
( gimp - message " four " )
(gimp-selection-none image)
undo group in one step
(gimp-displays-flush)
)
(script-fu-register
SF-IMAGE "Image" 0
SF-DRAWABLE "Layer" 0
SF-ADJUSTMENT "Number of colors" '(5 2 255 1 10 0 0)
)
|
8e6442794791bdb419c9f9f1ff2a9ea4b2a9861badc3f763a097c617e83dbfd4 | KirinDave/fuzed | fuzed_frontend_app.erl | -module(fuzed_frontend_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_Type, StartArgs) ->
net_kernel:set_net_ticktime(30),
fuzed_frontend_supervisor:start_link(StartArgs).
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/KirinDave/fuzed/56098d9e4c139613845289bdd5acebdfe608981a/elibs/fuzed_frontend_app.erl | erlang | -module(fuzed_frontend_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_Type, StartArgs) ->
net_kernel:set_net_ticktime(30),
fuzed_frontend_supervisor:start_link(StartArgs).
stop(_State) ->
ok.
| |
281c90c8f5a154d41225bb7b50822b02b8d7e9b868e599d94c034737b7867984 | abyala/advent-2022-clojure | day09.clj | (ns advent-2022-clojure.day09
(:require [clojure.string :as str]
[advent-2022-clojure.point :as p]))
(defn create-rope [n] (vec (repeat n p/origin)))
(defn parse-line [line]
(let [[dir amt] (str/split line #" ")]
(repeat (parse-long amt)
({"L" p/left "R" p/right "U" p/up "D" p/down} dir))))
(defn parse-input [input]
(mapcat parse-line (str/split-lines input)))
(defn move-head [state dir]
(update state 0 (partial mapv + dir)))
(defn move-ordinate [head-ord tail-ord]
(condp apply [head-ord tail-ord] = tail-ord
< (dec tail-ord)
> (inc tail-ord)))
(defn pull-rope [state]
(reduce (fn [acc tail] (let [head (last acc)]
(conj acc (if (p/touching? head tail)
tail
(mapv move-ordinate head tail)))))
[(first state)]
(rest state)))
(defn move [state dir]
(-> state (move-head dir) pull-rope))
(defn solve [knots input]
(->> (parse-input input)
(reductions move (create-rope knots))
(map last)
set
count))
(defn part1 [input] (solve 2 input))
(defn part2 [input] (solve 10 input))
| null | https://raw.githubusercontent.com/abyala/advent-2022-clojure/d3a6401279de63f6e2af34098e32ffbb3307e77d/src/advent_2022_clojure/day09.clj | clojure | (ns advent-2022-clojure.day09
(:require [clojure.string :as str]
[advent-2022-clojure.point :as p]))
(defn create-rope [n] (vec (repeat n p/origin)))
(defn parse-line [line]
(let [[dir amt] (str/split line #" ")]
(repeat (parse-long amt)
({"L" p/left "R" p/right "U" p/up "D" p/down} dir))))
(defn parse-input [input]
(mapcat parse-line (str/split-lines input)))
(defn move-head [state dir]
(update state 0 (partial mapv + dir)))
(defn move-ordinate [head-ord tail-ord]
(condp apply [head-ord tail-ord] = tail-ord
< (dec tail-ord)
> (inc tail-ord)))
(defn pull-rope [state]
(reduce (fn [acc tail] (let [head (last acc)]
(conj acc (if (p/touching? head tail)
tail
(mapv move-ordinate head tail)))))
[(first state)]
(rest state)))
(defn move [state dir]
(-> state (move-head dir) pull-rope))
(defn solve [knots input]
(->> (parse-input input)
(reductions move (create-rope knots))
(map last)
set
count))
(defn part1 [input] (solve 2 input))
(defn part2 [input] (solve 10 input))
| |
313c752f8208cd6fefbb4a12f82727360261fec2e5ab1f9e65fd3200dc7aa3cd | ConsumerDataStandardsAustralia/validation-prototype | Payees.hs | {-# LANGUAGE OverloadedStrings #-}
module Web.ConsumerData.Au.LambdaBank.Server.Banking.Payees where
import Control.Lens
import Web.ConsumerData.Au.Api.Types
import Servant.API.Generic (ToServant)
import Servant.Server.Generic (AsServerT, genericServerT)
import Web.ConsumerData.Au.LambdaBank.FakeData (fakePaginator)
import Web.ConsumerData.Au.LambdaBank.Model
import Web.ConsumerData.Au.LambdaBank.Server.Internal
(LambdaBankM, bankPaginatedResponse, bankStandardResponse)
payeesServer :: ToServant PayeesApi (AsServerT LambdaBankM)
payeesServer =genericServerT PayeesApi
{ _payeesGet = \pt pn ps -> do
payees <- getPayeesAll pt pn ps
bankPaginatedResponse payees (fakePaginator pn ps (links^.bankingLinks.bankingPayeesLinks.payeesGet. to ($ pt)))
, _payeesByIdGet = \payeeId -> do
payee <- getPayeeDetail payeeId
bankStandardResponse payee (links^.bankingLinks.bankingPayeesLinks.payeesByIdGet $ payeeId)
}
| null | https://raw.githubusercontent.com/ConsumerDataStandardsAustralia/validation-prototype/ff63338b77339ee49fa3e0be5bb9d7f74e50c28b/consumer-data-au-lambdabank/src/Web/ConsumerData/Au/LambdaBank/Server/Banking/Payees.hs | haskell | # LANGUAGE OverloadedStrings # | module Web.ConsumerData.Au.LambdaBank.Server.Banking.Payees where
import Control.Lens
import Web.ConsumerData.Au.Api.Types
import Servant.API.Generic (ToServant)
import Servant.Server.Generic (AsServerT, genericServerT)
import Web.ConsumerData.Au.LambdaBank.FakeData (fakePaginator)
import Web.ConsumerData.Au.LambdaBank.Model
import Web.ConsumerData.Au.LambdaBank.Server.Internal
(LambdaBankM, bankPaginatedResponse, bankStandardResponse)
payeesServer :: ToServant PayeesApi (AsServerT LambdaBankM)
payeesServer =genericServerT PayeesApi
{ _payeesGet = \pt pn ps -> do
payees <- getPayeesAll pt pn ps
bankPaginatedResponse payees (fakePaginator pn ps (links^.bankingLinks.bankingPayeesLinks.payeesGet. to ($ pt)))
, _payeesByIdGet = \payeeId -> do
payee <- getPayeeDetail payeeId
bankStandardResponse payee (links^.bankingLinks.bankingPayeesLinks.payeesByIdGet $ payeeId)
}
|
c74fa78d822deea4663f44d1edc71fd787e598cf9af58abc81f2e84f91256ae9 | collaborativetrust/WikiTrust | combinestatsfiles.ml |
Copyright ( c ) 2007 - 2008 The Regents of the University of California
Copyright ( c ) 2010
All rights reserved .
Authors : ,
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2007-2008 The Regents of the University of California
Copyright (c) 2010 Luca de Alfaro
All rights reserved.
Authors: Gillian Smith, Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
Combine stats files uses bucket sort to combine all of the statistics files in a specified directory .
* It writes its output to a specified file .
* It writes its output to a specified file. *)
let usage_message = "Usage: combinestats"
let input_dir = ref ""
let bucket_dir = ref ""
let hours_per_bucket = ref 24.
let max_lines_in_mem = ref 1000000
let do_bucketing = ref false
let do_sorting = ref false
let remove_unsorted = ref false
let use_dirs = ref false
let lines_in_cache = ref 0
let noop s = ()
let command_line_format = [
("-input_dir", Arg.Set_string input_dir,
"directory where the input files are");
("-bucket_dir", Arg.Set_string bucket_dir,
"directory where the unsorted and sorted buckets are");
("-hours_per_bucket", Arg.Set_float hours_per_bucket,
"number of hours of data that go into the same bucket (default: 24)");
("-use_subdirs", Arg.Set use_dirs,
"Uses subdirectory structure for files to sort (default: false)");
("-skip_bucketing", Arg.Set do_bucketing,
"Skips the bucketing step");
("-skip_sorting", Arg.Set do_sorting,
"Skips the sorting step");
("-remove_unsorted", Arg.Set remove_unsorted,
"Remove unsorted files after sorting");
("-cache_lines", Arg.Set_int max_lines_in_mem,
"number of lines to read into memory before flushing to disk (default: 1000000)")
];;
let _ = Arg.parse command_line_format noop usage_message;;
(* There is Arg.Set but no Arg.Reset, hence this kludge *)
do_sorting := not !do_sorting;;
do_bucketing := not !do_bucketing;;
(* Hash table where lines are stored *)
let tempbuckets = Hashtbl.create 20000
(* Create a temporary working directory tree *)
if !do_bucketing then begin
ignore (Unix.system ("mkdir " ^ !bucket_dir));
(* Gets the list of files to bucketize *)
let file_list_f = Unix.open_process_in ("find " ^ !input_dir ^ " -name *" ^ ".stats*") in
(* Waits a bit before reading from the pipe *)
Unix.sleep 3;
let flush_tmp () =
(* Now writes the hashtable *)
print_endline "Flushing";
(* This function is iterated on the hash table *)
let f k lines_list =
(* The key of the hashtable is the index of the file to open. *)
(* We need to produce a filename. *)
let (f_name, d_name) =
if !use_dirs then begin
let s = Printf.sprintf "%08d.bkt" k in
let p1 = String.sub s 0 5 in
let d = !bucket_dir ^ "/" ^ p1 in
(d ^ "/" ^ s, d)
end else (Printf.sprintf "%s/%08d.bkt" !bucket_dir k, "")
in
let file =
try
open_out_gen [Open_append] 0o640 f_name
with Sys_error _ -> begin
If we use subdirs , make sure the subdir exists .
if !use_dirs then begin
try
Unix.mkdir d_name 0o750
with Unix.Unix_error (Unix.EEXIST, _, _) -> ()
end;
Opens the file
open_out f_name
end
in
let p (l: string) = begin output_string file l; output_string file "\n"; end in
List.iter p lines_list;
close_out file;
in
Hashtbl.iter f tempbuckets;
Hashtbl.clear tempbuckets;
lines_in_cache := 0
in
This function processes one .stat file
let bucketize_file () =
(* raises End_of_file when we are done *)
let filename = input_line file_list_f in
Opens the file
print_string ("Processing: " ^ filename ^ "\n"); flush stdout;
let use_compression =
(String.length filename > 3 && (Str.last_chars filename 3 = ".gz")) in
let infile =
if use_compression
then Filesystem_store.open_compressed_file filename "gunzip -c"
else open_in filename
in
let file_todo = ref true in
while !file_todo do begin
let line = try
input_line infile
with End_of_file -> begin
file_todo := false;
""
end
in
if !file_todo then begin
try begin
let idx1 = String.index line ' ' in
if (String.sub line 0 idx1) <> "Page:" then begin
let idx2 = String.index_from line (idx1 + 1) ' ' in
let time_piece = String.sub line (idx1 + 1) (idx2 - idx1 - 1) in
let time = float_of_string time_piece in
let bucketnum = int_of_float (time /. (!hours_per_bucket *. 3600.)) in
if Hashtbl.mem tempbuckets bucketnum then begin
let l = Hashtbl.find tempbuckets bucketnum in
Hashtbl.remove tempbuckets bucketnum;
Hashtbl.add tempbuckets bucketnum (line :: l)
end else Hashtbl.add tempbuckets bucketnum [line];
lines_in_cache := !lines_in_cache + 1;
if !lines_in_cache >= !max_lines_in_mem then flush_tmp ()
end
end
with Not_found | Invalid_argument _ | Failure _ -> ()
end
end done; (* while loop over lines of file *)
begin
if use_compression
then Filesystem_store.close_compressed_file infile
else close_in infile
end
in
(* Bucketizes all files *)
try
while true do bucketize_file () done
with End_of_file -> ();
flush_tmp ();
ignore (Unix.close_process_in file_list_f)
end;;
if !do_sorting then begin
(* Gets the list of files to sort *)
let file_list_f = Unix.open_process_in ("find " ^ !bucket_dir ^ " -name *.bkt") in
(* Waits a bit before reading from the pipe *)
Unix.sleep 3;
try
while true do begin
let filename = input_line file_list_f in
let sorted_filename = filename ^ ".sorted" in
let commandtext = ("sort -n -k 2,2 " ^ filename ^ " > " ^ sorted_filename) in
print_string ("Sorting: " ^ filename ^ "\n"); flush stdout;
ignore (Unix.system commandtext);
if !remove_unsorted then ignore (Unix.system ("rm " ^ filename))
end done
with End_of_file -> ();
ignore (Unix.close_process_in file_list_f)
end;;
| null | https://raw.githubusercontent.com/collaborativetrust/WikiTrust/9dd056e65c37a22f67d600dd1e87753aa0ec9e2c/analysis/combinestatsfiles.ml | ocaml | There is Arg.Set but no Arg.Reset, hence this kludge
Hash table where lines are stored
Create a temporary working directory tree
Gets the list of files to bucketize
Waits a bit before reading from the pipe
Now writes the hashtable
This function is iterated on the hash table
The key of the hashtable is the index of the file to open.
We need to produce a filename.
raises End_of_file when we are done
while loop over lines of file
Bucketizes all files
Gets the list of files to sort
Waits a bit before reading from the pipe |
Copyright ( c ) 2007 - 2008 The Regents of the University of California
Copyright ( c ) 2010
All rights reserved .
Authors : ,
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2007-2008 The Regents of the University of California
Copyright (c) 2010 Luca de Alfaro
All rights reserved.
Authors: Gillian Smith, Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
Combine stats files uses bucket sort to combine all of the statistics files in a specified directory .
* It writes its output to a specified file .
* It writes its output to a specified file. *)
let usage_message = "Usage: combinestats"
let input_dir = ref ""
let bucket_dir = ref ""
let hours_per_bucket = ref 24.
let max_lines_in_mem = ref 1000000
let do_bucketing = ref false
let do_sorting = ref false
let remove_unsorted = ref false
let use_dirs = ref false
let lines_in_cache = ref 0
let noop s = ()
let command_line_format = [
("-input_dir", Arg.Set_string input_dir,
"directory where the input files are");
("-bucket_dir", Arg.Set_string bucket_dir,
"directory where the unsorted and sorted buckets are");
("-hours_per_bucket", Arg.Set_float hours_per_bucket,
"number of hours of data that go into the same bucket (default: 24)");
("-use_subdirs", Arg.Set use_dirs,
"Uses subdirectory structure for files to sort (default: false)");
("-skip_bucketing", Arg.Set do_bucketing,
"Skips the bucketing step");
("-skip_sorting", Arg.Set do_sorting,
"Skips the sorting step");
("-remove_unsorted", Arg.Set remove_unsorted,
"Remove unsorted files after sorting");
("-cache_lines", Arg.Set_int max_lines_in_mem,
"number of lines to read into memory before flushing to disk (default: 1000000)")
];;
let _ = Arg.parse command_line_format noop usage_message;;
do_sorting := not !do_sorting;;
do_bucketing := not !do_bucketing;;
let tempbuckets = Hashtbl.create 20000
if !do_bucketing then begin
ignore (Unix.system ("mkdir " ^ !bucket_dir));
let file_list_f = Unix.open_process_in ("find " ^ !input_dir ^ " -name *" ^ ".stats*") in
Unix.sleep 3;
let flush_tmp () =
print_endline "Flushing";
let f k lines_list =
let (f_name, d_name) =
if !use_dirs then begin
let s = Printf.sprintf "%08d.bkt" k in
let p1 = String.sub s 0 5 in
let d = !bucket_dir ^ "/" ^ p1 in
(d ^ "/" ^ s, d)
end else (Printf.sprintf "%s/%08d.bkt" !bucket_dir k, "")
in
let file =
try
open_out_gen [Open_append] 0o640 f_name
with Sys_error _ -> begin
If we use subdirs , make sure the subdir exists .
if !use_dirs then begin
try
Unix.mkdir d_name 0o750
with Unix.Unix_error (Unix.EEXIST, _, _) -> ()
end;
Opens the file
open_out f_name
end
in
let p (l: string) = begin output_string file l; output_string file "\n"; end in
List.iter p lines_list;
close_out file;
in
Hashtbl.iter f tempbuckets;
Hashtbl.clear tempbuckets;
lines_in_cache := 0
in
This function processes one .stat file
let bucketize_file () =
let filename = input_line file_list_f in
Opens the file
print_string ("Processing: " ^ filename ^ "\n"); flush stdout;
let use_compression =
(String.length filename > 3 && (Str.last_chars filename 3 = ".gz")) in
let infile =
if use_compression
then Filesystem_store.open_compressed_file filename "gunzip -c"
else open_in filename
in
let file_todo = ref true in
while !file_todo do begin
let line = try
input_line infile
with End_of_file -> begin
file_todo := false;
""
end
in
if !file_todo then begin
try begin
let idx1 = String.index line ' ' in
if (String.sub line 0 idx1) <> "Page:" then begin
let idx2 = String.index_from line (idx1 + 1) ' ' in
let time_piece = String.sub line (idx1 + 1) (idx2 - idx1 - 1) in
let time = float_of_string time_piece in
let bucketnum = int_of_float (time /. (!hours_per_bucket *. 3600.)) in
if Hashtbl.mem tempbuckets bucketnum then begin
let l = Hashtbl.find tempbuckets bucketnum in
Hashtbl.remove tempbuckets bucketnum;
Hashtbl.add tempbuckets bucketnum (line :: l)
end else Hashtbl.add tempbuckets bucketnum [line];
lines_in_cache := !lines_in_cache + 1;
if !lines_in_cache >= !max_lines_in_mem then flush_tmp ()
end
end
with Not_found | Invalid_argument _ | Failure _ -> ()
end
begin
if use_compression
then Filesystem_store.close_compressed_file infile
else close_in infile
end
in
try
while true do bucketize_file () done
with End_of_file -> ();
flush_tmp ();
ignore (Unix.close_process_in file_list_f)
end;;
if !do_sorting then begin
let file_list_f = Unix.open_process_in ("find " ^ !bucket_dir ^ " -name *.bkt") in
Unix.sleep 3;
try
while true do begin
let filename = input_line file_list_f in
let sorted_filename = filename ^ ".sorted" in
let commandtext = ("sort -n -k 2,2 " ^ filename ^ " > " ^ sorted_filename) in
print_string ("Sorting: " ^ filename ^ "\n"); flush stdout;
ignore (Unix.system commandtext);
if !remove_unsorted then ignore (Unix.system ("rm " ^ filename))
end done
with End_of_file -> ();
ignore (Unix.close_process_in file_list_f)
end;;
|
9e22a16c2fd4125c37ce344aea3c3b055027008a3fc254e90fdf7a48bf066f3b | imteekay/functional-programming-learning-path | hello-world-test.clj | (ns hello-world-test
(:require [clojure.test :refer [deftest is]]
hello-world))
(deftest hello-world-test
(is (= "Hello, World!" (hello-world/hello))))
| null | https://raw.githubusercontent.com/imteekay/functional-programming-learning-path/07dac09c9fabfa54f8b4d80b62f43b092cb87b0d/programming_challenges/exercism/clojure/hello-world/test/hello-world-test.clj | clojure | (ns hello-world-test
(:require [clojure.test :refer [deftest is]]
hello-world))
(deftest hello-world-test
(is (= "Hello, World!" (hello-world/hello))))
| |
a024673c2bc8d92ac6cdad2c66e53fe1cc7739af04b0ec374f94ef39668183cc | ygmpkk/house | Console.hs | module Kernel.Types.Console where
import H.Concurrency(Chan,MVar)
import Data.Word ( Word8 )
type VideoAttributes = Word8
type Row = Int
type Col = Int
data ConsoleCommand
= NewLine
| CarriageReturn
| ClearEOL
| PutChar VideoAttributes Char
| MoveCursorBackward Int
| ClearScreen
data ConsoleData = ConsoleData
{ consoleChan :: Chan ConsoleCommand
, consoleHeight :: Int
, consoleWidth :: Int
}
data Console = Console (MVar ConsoleData)
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/kernel/Kernel/Types/Console.hs | haskell | module Kernel.Types.Console where
import H.Concurrency(Chan,MVar)
import Data.Word ( Word8 )
type VideoAttributes = Word8
type Row = Int
type Col = Int
data ConsoleCommand
= NewLine
| CarriageReturn
| ClearEOL
| PutChar VideoAttributes Char
| MoveCursorBackward Int
| ClearScreen
data ConsoleData = ConsoleData
{ consoleChan :: Chan ConsoleCommand
, consoleHeight :: Int
, consoleWidth :: Int
}
data Console = Console (MVar ConsoleData)
| |
87805b2aaba432bc3187508ad028ff9bd5e755b4cfa401bd324f610547872d94 | nablaa/hchesslib | HLint.hs | module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "src"
, "test"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
| null | https://raw.githubusercontent.com/nablaa/hchesslib/f69dab2f1ea12c24f30bbfc5155ac4c08549a91b/test/HLint.hs | haskell | module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "src"
, "test"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
| |
8f525cf286fc6b6172feef8deb2d456acc85f0d7472139448fa070fe00ba4301 | NetASM/NetASM-haskell | Code.hs | ---------------------------------------------------------------------------------
--
--
--
-- File:
-- Hub/Code.hs
--
-- Project:
: A Network Assembly for Orchestrating Programmable Network Devices
--
-- Author:
--
-- Copyright notice:
Copyright ( C ) 2014 Georgia Institute of Technology
Network Operations and Internet Security Lab
--
-- Licence:
This file is a part of the development base package .
--
-- This file is free code: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 2.1 as
published by the Free Software Foundation .
--
-- This package is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
You should have received a copy of the GNU Lesser General Public
License along with the source package . If not , see
-- /.
module Apps.Hub.Code where
import Utils.Map
import Core.Language
import Core.PacketParser
----------
-- Hub ---
----------
Topology code for hub
c = [ OPF("outport", "inport", Xor, _1s) -- set "outport" (bitmap) to all 1s except the incoming port
, HLT] -- halt
| null | https://raw.githubusercontent.com/NetASM/NetASM-haskell/08e102691e4f343148b6cc270d89bbf0b97cac96/Apps/Hub/Code.hs | haskell | -------------------------------------------------------------------------------
File:
Hub/Code.hs
Project:
Author:
Copyright notice:
Licence:
This file is free code: you can redistribute it and/or modify it under
This package is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
/.
--------
Hub ---
--------
set "outport" (bitmap) to all 1s except the incoming port
halt | : A Network Assembly for Orchestrating Programmable Network Devices
Copyright ( C ) 2014 Georgia Institute of Technology
Network Operations and Internet Security Lab
This file is a part of the development base package .
the terms of the GNU Lesser General Public License version 2.1 as
published by the Free Software Foundation .
You should have received a copy of the GNU Lesser General Public
License along with the source package . If not , see
module Apps.Hub.Code where
import Utils.Map
import Core.Language
import Core.PacketParser
Topology code for hub
|
7fa7ab1e4bb08afc8da32a2f27355c8c453ed3c8fda7dd72229bc38075dc2ebe | mbutterick/brag | test-01-equal.rkt | #lang racket/base
(require brag/examples/01-equal
rackunit)
(check-equal? (syntax->datum (parse ""))
'(equal))
(check-equal? (syntax->datum (parse "01"))
'(equal (zero (equal) "0")
(one (equal) "1")))
(check-equal? (syntax->datum (parse "10"))
'(equal (one (equal) "1")
(zero (equal) "0")))
(check-equal? (syntax->datum (parse "0011"))
'(equal (zero (equal) "0")
(one (equal (zero (equal) "0")
(one (equal) "1"))
"1")))
(check-equal? (syntax->datum (parse "0110"))
'(equal (one (equal (zero (equal) "0")
(one (equal) "1"))
"1")
(zero (equal) "0")))
(check-equal? (syntax->datum (parse "1100"))
'(equal (one (equal) "1")
(zero (equal (one (equal) "1")
(zero (equal) "0"))
"0")))
| null | https://raw.githubusercontent.com/mbutterick/brag/6c161ae31df9b4ae7f55a14f754c0b216b60c9a6/brag-lib/brag/test/test-01-equal.rkt | racket | #lang racket/base
(require brag/examples/01-equal
rackunit)
(check-equal? (syntax->datum (parse ""))
'(equal))
(check-equal? (syntax->datum (parse "01"))
'(equal (zero (equal) "0")
(one (equal) "1")))
(check-equal? (syntax->datum (parse "10"))
'(equal (one (equal) "1")
(zero (equal) "0")))
(check-equal? (syntax->datum (parse "0011"))
'(equal (zero (equal) "0")
(one (equal (zero (equal) "0")
(one (equal) "1"))
"1")))
(check-equal? (syntax->datum (parse "0110"))
'(equal (one (equal (zero (equal) "0")
(one (equal) "1"))
"1")
(zero (equal) "0")))
(check-equal? (syntax->datum (parse "1100"))
'(equal (one (equal) "1")
(zero (equal (one (equal) "1")
(zero (equal) "0"))
"0")))
| |
4e9b2010e35fc3bc7006ad1db49269f4be493ad140068d783e2df1de18a85a3d | bn-d/ppx_make | test_make_variant.ml | open Variant_types
let tuple_basic _ =
OUnit2.assert_equal (T_baisc 32) (make_t_baisc_of_tuple_v ~v0:32 ())
let tuple_option _ =
OUnit2.assert_equal (T_option None) (make_t_option_of_tuple_v ());
OUnit2.assert_equal (T_option (Some 2718))
(make_t_option_of_tuple_v ~v0:2718 ())
let tuple_complex_1 _ =
OUnit2.assert_equal
(T_complex (32, None, [], "", 1024, "Z06"))
(make_t_complex_of_tuple_v ~v0:32 ~v5:"Z06" ());
OUnit2.assert_equal
(T_complex (32, Some 64, [ 128; 256; 512 ], "boom", 0, "Z06"))
(make_t_complex_of_tuple_v ~v0:32 ~v1:64 ~v2:[ 128; 256; 512 ] ~v3:"boom"
~v4:0 ~v5:"Z06" ())
let record_basic _ =
OUnit2.assert_equal (R_basic { b1 = 32 }) (make_r_basic_of_record_v ~b1:32 ())
let record_complex_1 _ =
OUnit2.assert_equal
(R_complex { c1 = 32; c2 = None; c3 = []; c4 = ""; c5 = 1024; c6 = "Z06" })
(make_r_complex_of_record_v ~c1:32 ~c6:"Z06" ());
OUnit2.assert_equal
(R_complex
{
c1 = 32;
c2 = Some 64;
c3 = [ 128; 256; 512 ];
c4 = "boom";
c5 = 0;
c6 = "Z06";
})
(make_r_complex_of_record_v ~c1:32 ~c2:64 ~c3:[ 128; 256; 512 ] ~c4:"boom"
~c5:0 ~c6:"Z06" ())
let record_complex_2 _ =
OUnit2.assert_equal
(R_complex_with_main { cm1 = 8; cm2 = None; cm3 = None })
(make_r_complex_with_main_of_record_v 8 None);
OUnit2.assert_equal
(R_complex_with_main { cm1 = 8; cm2 = Some 27; cm3 = Some 64 })
(make_r_complex_with_main_of_record_v ~cm2:27 8 (Some 64))
let none _ = OUnit2.assert_equal N_none (make_n_none_of_none_v ())
let suite =
let open OUnit2 in
"variant"
>::: [
"tuple_basic" >:: tuple_basic;
"tuple_option" >:: tuple_option;
"tuple_complex_1" >:: tuple_complex_1;
"record_basic" >:: record_basic;
"record_complex_1" >:: record_complex_1;
"record_complex_2" >:: record_complex_2;
"none" >:: none;
]
| null | https://raw.githubusercontent.com/bn-d/ppx_make/19057d86b603230fd5e211564f3911ccf2305ab5/test/test_make_variant.ml | ocaml | open Variant_types
let tuple_basic _ =
OUnit2.assert_equal (T_baisc 32) (make_t_baisc_of_tuple_v ~v0:32 ())
let tuple_option _ =
OUnit2.assert_equal (T_option None) (make_t_option_of_tuple_v ());
OUnit2.assert_equal (T_option (Some 2718))
(make_t_option_of_tuple_v ~v0:2718 ())
let tuple_complex_1 _ =
OUnit2.assert_equal
(T_complex (32, None, [], "", 1024, "Z06"))
(make_t_complex_of_tuple_v ~v0:32 ~v5:"Z06" ());
OUnit2.assert_equal
(T_complex (32, Some 64, [ 128; 256; 512 ], "boom", 0, "Z06"))
(make_t_complex_of_tuple_v ~v0:32 ~v1:64 ~v2:[ 128; 256; 512 ] ~v3:"boom"
~v4:0 ~v5:"Z06" ())
let record_basic _ =
OUnit2.assert_equal (R_basic { b1 = 32 }) (make_r_basic_of_record_v ~b1:32 ())
let record_complex_1 _ =
OUnit2.assert_equal
(R_complex { c1 = 32; c2 = None; c3 = []; c4 = ""; c5 = 1024; c6 = "Z06" })
(make_r_complex_of_record_v ~c1:32 ~c6:"Z06" ());
OUnit2.assert_equal
(R_complex
{
c1 = 32;
c2 = Some 64;
c3 = [ 128; 256; 512 ];
c4 = "boom";
c5 = 0;
c6 = "Z06";
})
(make_r_complex_of_record_v ~c1:32 ~c2:64 ~c3:[ 128; 256; 512 ] ~c4:"boom"
~c5:0 ~c6:"Z06" ())
let record_complex_2 _ =
OUnit2.assert_equal
(R_complex_with_main { cm1 = 8; cm2 = None; cm3 = None })
(make_r_complex_with_main_of_record_v 8 None);
OUnit2.assert_equal
(R_complex_with_main { cm1 = 8; cm2 = Some 27; cm3 = Some 64 })
(make_r_complex_with_main_of_record_v ~cm2:27 8 (Some 64))
let none _ = OUnit2.assert_equal N_none (make_n_none_of_none_v ())
let suite =
let open OUnit2 in
"variant"
>::: [
"tuple_basic" >:: tuple_basic;
"tuple_option" >:: tuple_option;
"tuple_complex_1" >:: tuple_complex_1;
"record_basic" >:: record_basic;
"record_complex_1" >:: record_complex_1;
"record_complex_2" >:: record_complex_2;
"none" >:: none;
]
| |
8df5a22afaf1727ca2f0c8508867cb2c3959eb26a42db7703b30748d490948c1 | ijvcms/chuanqi_dev | scene_mgr_lib.erl | %%%-------------------------------------------------------------------
@author zhengsiying
( C ) 2015 , < COMPANY >
%%% @doc
%%% 场景管理模块
%%% @end
Created : 27 . 七月 2015 上午10:57
%%%-------------------------------------------------------------------
-module(scene_mgr_lib).
-include("common.hrl").
-include("record.hrl").
-include("config.hrl").
-include("cache.hrl").
-include("proto.hrl").
-include("language_config.hrl").
-include("log_type_config.hrl").
-define(SERVER, scene_mgr_mod).
%% API
-export([
create_scene/1,
create_scene/2,
change_scene/3,
change_scene/4,
change_scene/5,
change_scene/6,
change_scene/7,
succeed_change_scene/3,
leave_scene/2,
close_all_scene/0,
close_scene/1,
exit_instance/1,
create_permanently_scene/0,
update_boss_refresh/4,
get_boss_refresh/2,
get_new_pk_mode/3,
change_scene_line/6,
get_line_num/2,
get_scene_player_num/1,
get_scene_player_num/2,
check_condition/5
]).
%% callbacks
-export([
do_create_scene/2,
do_create_scene/3,
do_change_scene/7,
do_succeed_change_scene/4,
do_leave_scene/3,
do_close_scene/2,
do_create_permanently_scene/1
]).
%% ====================================================================
%% API functions
%% ====================================================================
%% 创建场景(非场景管理进程使用)
create_scene(SceneId) ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_create_scene, [SceneId]}).
create_scene(SceneId, PlayerState) ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_create_scene, [SceneId, PlayerState]}).
%% 创建场景(场景管理进程使用)
do_create_scene(_State, SceneId) ->
%% 获取属于的线路
LineNum = get_use_scene_line_scene_id(SceneId),
初始化 场景 并获取盗场景的 状态pid
{ok, Pid} ->
EtsScene = #ets_scene{
pid = Pid,
scene_id = SceneId,
player_list = []
},
ets:insert(?ETS_SCENE, EtsScene),
PidLine = #pid_line{
pid = Pid,
line_num = LineNum
},
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
NewPidLineList = EtsMaps#ets_scene_maps.pid_list ++ [PidLine],
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidLineList});
_ ->
ets:insert(?ETS_SCENE_MAPS, #ets_scene_maps{scene_id = SceneId, pid_list = [PidLine]})
end,
{ok, Pid};
Err ->
?ERR("create scene ~p error: ~p", [SceneId, Err]),
{fail, Err}
end.
do_create_scene(_State, SceneId, PlayerState) ->
%% 获取属于的线路
LineNum = get_use_scene_line_scene_id(SceneId, PlayerState),
初始化 场景 并获取盗场景的 状态pid
{ok, Pid} ->
EtsScene = #ets_scene{
pid = Pid,
scene_id = SceneId,
player_list = []
},
ets:insert(?ETS_SCENE, EtsScene),
PidLine = #pid_line{
pid = Pid,
line_num = LineNum
},
case instance_base_lib:is_multiple_instance(SceneId) of
false ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
NewPidLineList = EtsMaps#ets_scene_maps.pid_list ++ [PidLine],
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidLineList});
_ ->
ets:insert(?ETS_SCENE_MAPS, #ets_scene_maps{scene_id = SceneId, pid_list = [PidLine]})
end;
true ->
SceneSign = instance_base_lib:get_instance_sign(PlayerState, SceneId),
case ets:lookup(?ETS_SCENE_MAPS, {SceneId, SceneSign}) of
[EtsMaps] ->
NewPidLineList = EtsMaps#ets_scene_maps.pid_list ++ [PidLine],
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidLineList});
_ ->
ets:insert(?ETS_SCENE_MAPS, #ets_scene_maps{scene_id = {SceneId, SceneSign}, pid_list = [PidLine]})
end
end,
{ok, Pid};
Err ->
?ERR("create scene ~p error: ~p", [SceneId, Err]),
{fail, Err}
end.
创建永存场景
create_permanently_scene() ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_create_permanently_scene, []}, 10 * 1000).
%% 创建永存场景2
do_create_permanently_scene(_State) ->
F = fun(Type) ->
SceneList = scene_config:get_type_list(Type),
F1 = fun(X) ->
do_create_scene(_State, X)
end,
[F1(SceneId) || SceneId <- SceneList, not lists:member(SceneId, scene_config:get_cross_list())]
end,
永存场景类型
PermSceneList = [?SCENE_TYPE_MAIN_CITY, ?SCENE_TYPE_OUTDOOR],
[F(Type) || Type <- PermSceneList],
%% 创建完场景创建随机怪物(随机怪物只刷新在1线)
create_random_monster().
create_random_monster() ->
List = random_monster_config:get_list(),
create_random_monster([], List).
create_random_monster(_, []) ->
skip;
create_random_monster(TypeList, [Id | T]) ->
Conf = random_monster_config:get(Id),
Type = Conf#random_monster_conf.batch,
case lists:member(Type, TypeList) of
true ->
skip;
false ->
%% 属怪
scene_obj_lib:refuse_random_monster(Conf),
create_random_monster([Type] ++ TypeList, T)
end.
)
? CHANGE_SCENE_TYPE_CHANGE 主动切换场景
change_scene(PlayerState, PlayerPid, SceneId, ?CHANGE_SCENE_TYPE_CHANGE, null).%%
%% 切换场景
change_scene(PlayerState, PlayerPid, SceneId, ChangeType) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, null).%%
)
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, null, false).
%%主动切换线,本服幻境有使用
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, null, false, LineNum).
%% 如果是合服场景,判断是否放
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem, 0).
%% 如果是合服场景,判断是否放
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem, LineNum) ->
case function_db:is_open_scene(SceneId) of
true ->
change_scene_new(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem, LineNum);
_ ->
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_SCENE_MERGE_NO_OPEN}),
{ok, PlayerState}
end.
) 有特殊道具消耗 IsDelItem是否 验证道具
change_scene_new(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItemTemp, LineNum) ->
SceneConf = scene_config:get(SceneId),
case ChangeType of
?CHANGE_SCENE_TYPE_CHANGE ->
只有切换场景才需要做条件判断和扣物品的检查
{PlayerState1, EnterTimes} = player_instance_lib:get_instance_enter_times(PlayerState, SceneId),
IsNotItem =
case IsNotItemTemp of
false ->
check_scene_cost(PlayerState1, SceneConf);
_ ->
IsNotItemTemp
end,
case check_condition(PlayerState1, SceneId, EnterTimes, ItemLoss, IsNotItem, LineNum) of
{true, TimeSpan} ->
NewPlayerState =
case SceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->
case active_instance_config:get(SceneId) of
#active_instance_conf{} = _ ->
PlayerState1#player_state{
scene_parameters = TimeSpan
};
_ ->
?INFO("TTTSSS1111 ~p", [11]),
如果进入副本则需要扣相应的道具并且增加副本进入次数
InstanceConf = instance_config:get(SceneId),
{ok, PlayerState2} = goods_util:delete_special_list(PlayerState1, InstanceConf#instance_conf.cost, ?LOG_TYPE_TRANSFER),
PlayerState3 = player_instance_lib:add_instance_enter_times(PlayerState2, SceneConf#scene_conf.belong_scene_id),
PlayerState3
end;
_ ->
?INFO("TTTSSS222 ~p", [11]),
Cost = SceneConf#scene_conf.cost,
%% 判断是否扣除道具信息
{ok, PlayerState2} =
case Cost =:= [] orelse IsNotItem of
true -> {ok, PlayerState1};
_ ->
goods_util:delete_special_list(PlayerState1, Cost, ?LOG_TYPE_TRANSFER)
end,
{ok, PlayerState4} = case ItemLoss of
null -> {ok, PlayerState2};
{ItemId, ItemNum, Type} ->
case goods_lib_log:delete_goods_by_num(PlayerState2, ItemId, ItemNum, Type) of
{ok, PlayerState3} ->
{ok, PlayerState3};
_ ->
{ok, PlayerState2}
end
end,
PlayerState4
end,
change_scene_cross(NewPlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum);
{fail, Err} ->
?INFO("TTTSSS333 ~p", [Err]),
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = Err}),
{ok, PlayerState}
end;
_ ->
change_scene_cross(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum)
end.
%% 检测场景消耗
check_scene_cost(PlayerState, SceneConf) ->
OldSceneConf = scene_config:get(PlayerState#player_state.scene_id),
case is_record(OldSceneConf, scene_conf) andalso
OldSceneConf#scene_conf.belong_scene_id =:= SceneConf#scene_conf.belong_scene_id andalso
OldSceneConf#scene_conf.power_limit > SceneConf#scene_conf.power_limit
of
true ->
true;
_ ->
false
end.
%% 检查切换场景条件是否满足
check_condition(PlayerState, SceneId, EnterTimes, ItemLoss, IsNotItem) ->
check_condition(PlayerState, SceneId, EnterTimes, ItemLoss, IsNotItem, 0).
%% 检查切换场景条件是否满足
check_condition(PlayerState, SceneId, EnterTimes, ItemLoss, IsNotItem, LineNum) ->
case scene_config:get(SceneId) of
#scene_conf{} = SceneConf ->
DbPlayerBase = PlayerState#player_state.db_player_base,
%% 如何是副本场景,还需要进一步判断副本进入次数和道具
case active_instance_config:get(SceneId) of
#active_instance_conf{} = _ ->
check_condition2(PlayerState, SceneConf, ItemLoss, IsNotItem);
_ ->
%% 判断场景类型
case SceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->
check_condition1(PlayerState, SceneConf, EnterTimes, IsNotItem, LineNum);
_ ->
case DbPlayerBase#db_player_base.lv >= SceneConf#scene_conf.lv_limit of
true ->
case PlayerState#player_state.fighting > SceneConf#scene_conf.power_limit of
true ->
case IsNotItem orelse goods_util:check_special_list(PlayerState, SceneConf#scene_conf.cost) of
true ->
是否还有其他的道具消耗
case ItemLoss of
{ItemId, ItemNum, _Type} ->
case goods_util:check_special_list(PlayerState, [{ItemId, ItemNum}]) of
true ->
case DbPlayerBase#db_player_base.vip >= SceneConf#scene_conf.viplv_limit of
true -> {true, 0};
false -> {fail, ?ERR_PLAYER_VIPLV_NOT_ENOUGH}
end;
Fail ->
Fail
end;
_ ->
{true, 0}
end;
Fail ->
Fail
end;
_ ->
{fail, ?ERR_PLAYER_FIGHT_NOT_ENOUGH}
end;
_ ->
{fail, ?ERR_PLAYER_LV_NOT_GO_TO} %% 等级不足
end
end
end;
_ ->
{fail, ?ERR_COMMON_FAIL}
end.
%% 如何是副本场景,还需要进一步判断副本进入次数和道具
check_condition1(PlayerState, SceneConf, EnterTimes, IsNotItem, LineNum) ->
case scene_config:get(PlayerState#player_state.scene_id) of
#scene_conf{} = OldSceneConf ->
%% 玩家原先所在的场景
case OldSceneConf#scene_conf.type =:= ?SCENE_TYPE_INSTANCE andalso PlayerState#player_state.scene_id =:= SceneConf#scene_conf.scene_id
andalso PlayerState#player_state.scene_line_num =:= LineNum of
true ->
{fail, ?ERR_SCENE_INSTANCE};
_ ->
SceneId = SceneConf#scene_conf.scene_id,
DbPlayerBase = PlayerState#player_state.db_player_base,
case DbPlayerBase#db_player_base.lv >= SceneConf#scene_conf.lv_limit of
true ->
case PlayerState#player_state.fighting > SceneConf#scene_conf.power_limit of
true ->
InstanceConf = instance_config:get(SceneId),
case (EnterTimes < InstanceConf#instance_conf.times_limit
orelse InstanceConf#instance_conf.times_limit =< 0 orelse IsNotItem)
andalso check_instance(InstanceConf#instance_conf.type, InstanceConf) of
true ->
case IsNotItem orelse goods_util:check_special_list(PlayerState, InstanceConf#instance_conf.cost) of
true ->
检查个人boss剩余时间
case InstanceConf#instance_conf.type =/= 9
orelse DbPlayerBase#db_player_base.instance_left_time > 0 of
true ->
{true, 0};
false ->
{fail, ?ERR_INSTANCE_LEFT_TIME_LIMIT}
end;
_ ->
{fail, ?ERR_GOODS_NOT_ENOUGH}
end;
_ ->
{fail, ?ERR_ARENA_CHALL_NOT_ENOUGH} %% 副本进入次数用光了
end;
_ ->
{fail, ?ERR_PLAYER_FIGHT_NOT_ENOUGH}%% 玩家战力不足
end;
_ ->
{fail, ?ERR_PLAYER_LV_NOT_GO_TO} %% 等级不足
end
end;
_ ->
{fail, ?ERR_SCENE}
end.
%% 如何是活动,判断活动的开启时间
check_condition2(PlayerState, SceneConf, ItemLoss, IsNotItem) ->
%% 玩家原先所在的场景
DbPlayerBase = PlayerState#player_state.db_player_base,
case DbPlayerBase#db_player_base.lv >= SceneConf#scene_conf.lv_limit of
true ->
case PlayerState#player_state.fighting > SceneConf#scene_conf.power_limit of
true ->
case active_instance_lib:is_open_active(SceneConf#scene_conf.scene_id) of
{ok, TimeSpam} ->
case IsNotItem of
true ->
{true, TimeSpam};
_ ->
case goods_util:check_special_list(PlayerState, SceneConf#scene_conf.cost) of
true ->
是否还有其他的道具消耗
case ItemLoss of
{ItemId, ItemNum, _Type} ->
case goods_util:check_special_list(PlayerState, [{ItemId, ItemNum}]) of
true ->
{true, TimeSpam};
Fail ->
Fail
end;
_ ->
{true, TimeSpam}
end;
Fail ->
Fail
end
end;
Fail ->
Fail
end;
_ ->
{fail, ?ERR_PLAYER_FIGHT_NOT_ENOUGH}
end;
_ ->
{fail, ?ERR_PLAYER_LV_NOT_GO_TO} %% 等级不足
end.
%% 判断玩家是否可以进入剧情副本
check_instance(?INSTANCE_TYPE_PLOT, InstanceConf) ->
TaskList = player_task_dict:get_player_task_list(),
F = fun(X, IsOk) ->
case IsOk of
true ->
IsOk;
_ ->
case X#db_player_task.isfinish of
1 ->
false;
_ ->
TaskConf = task_config:get(X#db_player_task.taskid_id),
case TaskConf#task_conf.openinstance of
<<"">> ->
false;
OpenWinInfo ->
OpenWinInfo1 = erlang:binary_to_list(OpenWinInfo),
TList = string:tokens(OpenWinInfo1, ","),
TId = list_to_integer(lists:last(TList)),
Conf = scene_transport_config:get(TId),
Conf#scene_transport_conf.scene_id =:= InstanceConf#instance_conf.scene_id
end
end
end
end,
lists:foldr(F, false, TaskList);
check_instance(_, _) ->
true.
%% 检查切换场景是否需要恢复血量
need_recover(ChangeType, CurSceneId, NewSceneId) ->
case ChangeType of
?CHANGE_SCENE_TYPE_CHANGE ->%% 主动切换场景
新场景信息
case NewSceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->%% 普通副本
NewInstanceConf = instance_config:get(NewSceneId),%% 获取普通副本信息
NewInstanceConf#instance_conf.recover =:= ?INSTANCE_RECOVER_IS;%% 进出满状态
_ ->
case util_data:is_null(CurSceneId) of%% 检查cursceneid是否为空
true ->
false;
_ ->
case CurSceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->%% 普通副本
CurInstanceConf = instance_config:get(CurSceneId),
CurInstanceConf#instance_conf.recover =:= ?INSTANCE_RECOVER_IS;
_ ->
false
end
end
end;
?CHANGE_SCENE_TYPE_LEAVE_INSTANCE ->%% 离开副本
case util_data:is_null(CurSceneId) of
true ->
false;
_ ->
CurSceneConf = scene_config:get(CurSceneId),
case CurSceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->
CurInstanceConf = instance_config:get(CurSceneId),
CurInstanceConf#instance_conf.recover =:= ?INSTANCE_RECOVER_IS;
_ ->
false
end
end;
_ ->
false
end.
%% 跨服验证
change_scene_cross(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
SceneConf = scene_config:get(SceneId),
#player_state{server_pass = ServerPass} = PlayerState,
case SceneConf#scene_conf.is_cross of
1 ->
?INFO("change_scene_cross ~p", [1111]),
如果是在跨服的话 那么处理跨服信息
Result = case util_data:is_null(ServerPass) of
true ->
scene_cross:send_cross(PlayerState);
_ ->
{ok, PlayerState}
end,
case Result of
{ok, PlayerState1} ->
case cross_lib:send_cross_mfc(PlayerState1#player_state.server_pass, ?MODULE, change_scene, [PlayerState1, PlayerPid, SceneId, ChangeType, Point, LineNum]) of
{ok, PlayerState2} ->
{ok, PlayerState2};
_Err ->
?ERR("~p", [_Err]),
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_COMMON_FAIL})
end;
{fail, Err} ->
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = Err}),
{ok, PlayerState}
end;
_ ->
?INFO("change_scene_cross ~p", [2222]),
如果不是在跨服的话 那么移除跨服信息
PlayerState1 = scene_cross:send_log_out(PlayerState),
change_scene1(PlayerState1, PlayerPid, SceneId, ChangeType, Point, LineNum)
end.
%% 切换场景(这里必须用异步操作,原来用同步操作压力大时会出现timeout)
change_scene1(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
%% 如果是同一张场景
#player_state{
player_id = PlayerId,
scene_id = CurSceneId,
scene_pid = CurScenePid,
scene_line_num = OldLineNum
} = PlayerState,
case CurSceneId =:= SceneId andalso is_pid(CurScenePid) andalso (OldLineNum =:= LineNum orelse LineNum =:= 0) andalso not util_data:is_null(Point) of
true ->
?INFO("TTTSSS444 ~p", [11]),
%% 如果是同场景,只需要瞬移就可以
scene_obj_lib:instant_move(CurScenePid, ?OBJ_TYPE_PLAYER, PlayerId, Point, ?DIRECTION_UP),
{ok, PlayerState#player_state{recover_pet_list = []}};
_ ->
?INFO("TTTSSS555 ~p", [11]),
%% 非同场景需要正常的跑进入流程
PlayerState1 =
case need_recover(ChangeType, CurSceneId, SceneId) of %% %% 检查切换场景是否需要恢复血量
true ->
AttrTotal = PlayerState#player_state.attr_total,%% 获取玩家的属性信息
Update = #player_state{
db_player_attr = #db_player_attr{cur_mp = AttrTotal#attr_base.mp, cur_hp = AttrTotal#attr_base.hp}
},
{ok, _PlayerState1} = player_lib:update_player_state(PlayerState, Update),
_PlayerState1;
_ ->
PlayerState
end,
%% 异步切换场景
gen_server2:apply_async(misc:whereis_name({local, ?SERVER}), {?MODULE, do_change_scene, [PlayerState1, PlayerPid, SceneId, ChangeType, Point, LineNum]}),
{ok, PlayerState1#player_state{recover_pet_list = []}}
end.
%% 切换线路
change_scene_line(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
%% 异步切换场景
gen_server2:apply_async(misc:whereis_name({local, ?SERVER}), {?MODULE, do_change_scene, [PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum]}),
{ok, PlayerState#player_state{recover_pet_list = []}}.
切换场景(场景管理进程调用 )
do_change_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
case scene_config:get(SceneId) of
#scene_conf{} = _SceneConf ->
do_change_scene1(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, null, LineNum);
= PlayerState#player_state.player_id ,
SceneType = SceneConf#scene_conf.type ,
case ets : lookup(?ETS_PLAYER_SCENE , ) of
[
? INFO("do_change_scene1 222 ~p " , [ 11 ] ) ,
do_change_scene1(State , PlayerState , PlayerPid , SceneId , ChangeType , Point , EtsPlayerScene , LineNum ) ;
%% _ ->
%% %% 进入新场景
? INFO("do_enter_new_scene 11 ~p " , [ 11 ] ) ,
do_enter_new_scene(SceneType , State , PlayerState , PlayerPid , SceneId , ChangeType , Point , LineNum )
%% end;
_ ->
?ERR("enter scene ~p error: not scene config!", [SceneId])
end.
%% 切换场景
do_change_scene1(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, _EtsPlayerScene, LineNum) ->
ScenePid = PlayerState#player_state.scene_pid,
case PlayerState#player_state.scene_id =:= SceneId andalso LineNum =:= 0 of
true ->
%% 判断该场景是否还存在
case ets:lookup(?ETS_SCENE, ScenePid) of
[_EtsScene] ->
?INFO("ooo 11 ~p", [11]),
leave_and_enter_new_scene(State , PlayerState , PlayerPid , SceneId , ChangeType , Point , ScenePid , LineNum ) ;
do_change_scene2(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, PlayerState#player_state.scene_line_num);
_ ->
?INFO("ooo 22 ~p", [22]),
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum)
end;
_ ->
?INFO("ooo 33 ~p", [33]),
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum)
end.
%% 切换场景
do_change_scene2(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum) ->
SceneConf = scene_config:get(SceneId),
#scene_conf{
type = SceneType,
activity_id = ActivityId,
exit_scene = ExitScene
} = SceneConf,
case misc:is_process_alive(ScenePid) of
true ->
case ChangeType =:= ?CHANGE_SCENE_TYPE_ENTER andalso ActivityId =:= ?SCENE_ACTIVITY_PALACE of
true ->
%% 如果进入场景的时候是皇宫场景,则要传送到出口
case ets:lookup(?ETS_SCENE_MAPS, ExitScene) of
[EtsMaps] ->
ExitSceneConf = scene_config:get(ExitScene),
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, ExitSceneConf, null) of
null ->
{fail, 1};
Pid ->
?INFO("ooo 55 ~p", [55]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, null)
end;
_ ->
{fail, 1}
end;
_ ->
%% 重新进入场景
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, null) of
null ->
{fail, 1};
Pid ->
?INFO("ooo 44 ~p ~p", [length(PidLineList), 44]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point)
end;
_ ->
?INFO("ooo 99 ~p", [44]),
%% 重新进入场景
scene_obj_lib_copy:enter(PlayerState, PlayerPid, ScenePid, ChangeType, Point)
end
end;
_ ->
%% 如果场景进程已经崩溃
%% 先清理掉无效的ets信息
do_close_scene(State, ScenePid),
%% 根据不同的场景做不同的操作
case SceneType of
?SCENE_TYPE_INSTANCE ->
%% 如果是副本场景需要跑正常的逻辑
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, 0);
_ ->
如果是野外或者主城,必须修正(重建主城 / 野外)再进入场景
case do_create_scene(State, SceneId, PlayerState) of
{ok, Pid} ->
?INFO("ooo 66", [66]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point);
{fail, Err} ->
{fail, Err}
end
end
end.
%% 离开旧场景且进入新场景
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum) ->
PlayerId = PlayerState#player_state.player_id,
SceneConf = scene_config:get(SceneId),
SceneType = SceneConf#scene_conf.type,
%% 离开旧场景
do_leave_scene(State, PlayerId, ScenePid, ?LEAVE_SCENE_TYPE_INITIATIVE),
%% 进入新场景
do_enter_new_scene(SceneType, State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum).
保存玩家的id 进入场景的进程中 ( 玩家进程调用 )
succeed_change_scene(PlayerId, SceneId, ScenePid) ->
gen_server2:apply_async(misc:whereis_name({local, ?SERVER}), {?MODULE, do_succeed_change_scene, [PlayerId, SceneId, ScenePid]}).
保存玩家的id 进入场景的进程中 ( 玩家进程调用 )
do_succeed_change_scene(_State, PlayerId, SceneId, ScenePid) ->
case ets:lookup(?ETS_SCENE, ScenePid) of
[EtsScene] ->
NewPlayerList = util_list:store(PlayerId, EtsScene#ets_scene.player_list),
ets:update_element(?ETS_SCENE, ScenePid, {#ets_scene.player_list, NewPlayerList}),
ets:insert(?ETS_PLAYER_SCENE, #ets_player_scene{player_id = PlayerId, scene_id = SceneId, pid = ScenePid});
_ ->
skip
end.
%% 离开场景
leave_scene(PlayerState, LeaveType) ->
%% 跨服退出
scene_cross:send_log_out(PlayerState),
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_leave_scene, [PlayerState#player_state.player_id, LeaveType]}).
do_leave_scene(State, PlayerId, LeaveType) ->
case ets:lookup(?ETS_PLAYER_SCENE, PlayerId) of
[EtsPlayerScene] ->
do_leave_scene(State, PlayerId, EtsPlayerScene#ets_player_scene.pid, LeaveType),
case LeaveType of
?LEAVE_SCENE_TYPE_INITIATIVE ->
ets:delete(?ETS_PLAYER_SCENE, PlayerId);
_ ->
skip
end;
_ ->
skip
end.
do_leave_scene(_State, PlayerId, ScenePid, LeaveType) ->
case util_data:check_pid(ScenePid) of
true ->
%% 调用这个方法从参加进程移除玩家并通知同屏玩家
scene_obj_lib:remove_obj(ScenePid, ?OBJ_TYPE_PLAYER, PlayerId, LeaveType);
_ ->
skip
end.
%% 关闭所有场景,用于场景管理进程崩溃或者关服
close_all_scene() ->
List = ets:tab2list(?ETS_SCENE),
[gen_server2:apply_async(EtsScene#ets_scene.pid, {scene_mod, stop, []}) || EtsScene <- List].
%% 场景进程调用(场景自动关闭或者出错关闭的时候调用)
close_scene(ScenePid) ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_close_scene, [ScenePid]}).
do_close_scene(_State, ScenePid) ->
case ets:lookup(?ETS_SCENE, ScenePid) of
[EtsScene] ->
SceneId = EtsScene#ets_scene.scene_id,
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
NewPidList = lists:keydelete(ScenePid, #pid_line.pid, EtsMaps#ets_scene_maps.pid_list),
case NewPidList of
[] ->
ets:delete(?ETS_SCENE_MAPS, SceneId);
_ ->
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidList})
end;
_ ->
skip
end,
ets:delete(?ETS_SCENE, ScenePid);
_ ->
skip
end.
%% 退出副本(只有玩家进程才能掉用)
exit_instance(PlayerState) ->
SceneId = PlayerState#player_state.scene_id,
case scene_config:get(SceneId) of
#scene_conf{exit_scene = ExitScene} when ExitScene > 0 ->
%% CHANGE_SCENE_TYPE_LEAVE_INSTANCE 离开副本
change_scene(PlayerState, self(), ExitScene, ?CHANGE_SCENE_TYPE_LEAVE_INSTANCE);
_ ->
skip
end.
%% 更新boss刷新时间,只有需要记录刷新倒计时的boss才会用到
update_boss_refresh(SceneId, LineNum, BossId, RefreshTime) ->
EtsBossRefresh = #ets_boss_refresh{
scene_boss_id = {SceneId, LineNum, BossId},
refresh_time = RefreshTime
},
ets:insert(?ETS_BOSS_REFRESH, EtsBossRefresh).
获取boss刷新时间
get_boss_refresh(SceneId, BossId) ->
case ets:lookup(?ETS_BOSS_REFRESH, {SceneId, 1, BossId}) of
[EtsBossRefresh] ->
EtsBossRefresh;
_ ->
null
end.
%% 根据进入的场景id获取合理的pk模式
get_new_pk_mode(SceneId, _OldPkMode, SetPkMode) ->
SceneConf = scene_config:get(SceneId),
PkModeList = SceneConf#scene_conf.pk_mode_list,
%% 如果自己设定的模式符合场景允许的pk模式则用自己的设定的模式
case lists:member(SetPkMode, PkModeList) orelse PkModeList =:= [] of
true ->
SetPkMode;
_ ->
%% 如果自己设定的模式以场景允许的模式不符合则使用场景允许的第一个模式
[NewPkMode | _T] = PkModeList,
NewPkMode
end.
%% ====================================================================
Internal functions
%% ====================================================================
%% 根据不同的场景类型来做不同的操作
%% 如果是副本类型场景
do_enter_new_scene(?SCENE_TYPE_INSTANCE, State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
case ChangeType of
?CHANGE_SCENE_TYPE_CHANGE ->% 主动切换场景
%% 自动切换
case instance_base_lib:is_multiple_instance(SceneId) of%% 检测是否是多人副本类型
true ->
%% 如果是多人副本判断副本是否已经创建,如果是已经创建随机选择一个进入就行
SceneSign = instance_base_lib:get_instance_sign(PlayerState, SceneId),%% 获取场景副本标记
case ets:lookup(?ETS_SCENE_MAPS, {SceneId, SceneSign}) of
[EtsMaps] ->
SceneConf = scene_config:get(SceneId),
PidLineList = EtsMaps#ets_scene_maps.pid_list,%%
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, PlayerState) of%% 随机一个场景pid用于进入场景
null ->
{fail, 1};
Pid ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point)
end;
_ ->
%% 如果没有创建,先创建场景然后再进入
case do_create_scene(State, SceneId, PlayerState) of
{ok, Pid} ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point);
{fail, Err} ->
{fail, Err}
end
end;
false ->
%% 其他副本直接直接创建新的场景再进入
case do_create_scene(State, SceneId, PlayerState) of
{ok, Pid} ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point);
{fail, Err} ->
{fail, Err}
end
end;
_ ->
%% 非自动(这里一般情况不会进来,即使进来,一般场景都是已经创建好的了,否则场景管理进程已经出问题)
SceneConf = scene_config:get(SceneId),
ExitScene = SceneConf#scene_conf.exit_scene ,
Key = case instance_base_lib:is_multiple_instance(SceneId) of%% 检测是否是多人副本类型
true ->
SceneSign = instance_base_lib:get_instance_sign(PlayerState, SceneId),%% 获取场景副本标记
{SceneId, SceneSign};
_ ->
SceneId
end,
?WARNING("do_enter_new_scene ~p", [[SceneId, LineNum]]),
case ets:lookup(?ETS_SCENE_MAPS, Key) of
[EtsMaps] ->
%%ExitSceneConf = scene_config:get(ExitScene),
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, null) of
null ->
{fail, 1};
Pid ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, null)
end;
_ ->
{fail, 1}
end
end;
%% 主城和野外等非副本类的场景都在这里判断
do_enter_new_scene(_Type, _State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
正常情况都不需要再创建场景,在服务器开启的时候已经预先创建好(以后如过做分线可以修改这里 )
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
SceneConf = scene_config:get(SceneId),
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, null) of
null ->
{fail, 1};
Pid ->
Pid2 = case is_process_alive(Pid) of
true ->
Pid;
_ ->
scene_tool:create_scene_pid(SceneId),
case scene_mgr_lib:do_create_scene(_State, SceneId) of
{ok, Pid1} ->
Pid1;
_ ->
Pid
end
end,
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid2, ChangeType, Point)
end;
_ ->
{fail, 1}
end.
%%***********************************************
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
get_pid_top([], PidLineList, _LineNum, SceneConf, PlayerState) ->
case SceneConf#scene_conf.copy_num =:= 1 of
true ->
case util_rand:list_rand(PidLineList) of
null ->
null;
PidLine ->
?INFO("linenum 33 ~p", [PidLine#pid_line.line_num]),
PidLine#pid_line.pid
end;
_ ->
Result = case util_data:is_null(PlayerState) of
true ->
do_create_scene(null, SceneConf#scene_conf.scene_id);
_ ->
do_create_scene(null, SceneConf#scene_conf.scene_id, PlayerState)
end,
case Result of
{ok, Pid} ->
Pid;
_ ->
case util_rand:list_rand(PidLineList) of
null ->
null;
PidLine ->
?INFO("linenum 33 ~p", [PidLine#pid_line.line_num]),
PidLine#pid_line.pid
end
end
end;
get_pid_top([PidLine | H], PidLineList, LineNum, SceneConf, PlayerState) ->
%% 如果linenum不为0那么就是寻找跳转的具体线路
NowPid = case LineNum /= 0 of
true ->
case lists:keyfind(LineNum, #pid_line.line_num, PidLineList) of
false ->
0;
NowPidLine ->
?INFO("linenum 22 ~p ~p", [NowPidLine#pid_line.line_num, LineNum]),
NowPidLine#pid_line.pid
end;
_ ->
0
end,
case NowPid =:= 0 of
true ->
%% 随机线路
case ets:lookup(?ETS_SCENE, PidLine#pid_line.pid) of
[EtsScene] ->
case length(EtsScene#ets_scene.player_list) < SceneConf#scene_conf.limit_num of
true ->
?INFO("linenum 11 ~p", [PidLine#pid_line.line_num]),
PidLine#pid_line.pid;
_ ->
get_pid_top(H, PidLineList, 0, SceneConf, PlayerState)
end;
_ ->
get_pid_top(H, PidLineList, 0, SceneConf, PlayerState)
end;
_ ->
NowPid
end.
%% 获取场景里面的玩家人数
get_scene_player_num(ScenePid) ->
%% 随机线路
case ets:lookup(?ETS_SCENE, ScenePid) of
[EtsScene] ->
length(EtsScene#ets_scene.player_list);
_ ->
0
end.
%% 获取场景里面的玩家人数
get_scene_player_num(SceneId, LineNum) ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case lists:keyfind(LineNum, #pid_line.line_num, PidLineList) of
false ->
0;
PidLine ->
get_scene_player_num(PidLine#pid_line.pid)
end;
_ ->
0
end.
%% 获取场景pid所在线路
get_line_num(ScenePid, SceneId) ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case lists:keyfind(ScenePid, #pid_line.pid, PidLineList) of
false ->
{0, PidLineList};
PidLine ->
{PidLine#pid_line.line_num, PidLineList}
end;
_ ->
{0, []}
end.
%% 获取以用的线路信息
get_use_scene_line_scene_id(SceneId) ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
get_use_scene_line(EtsMaps#ets_scene_maps.pid_list);
_ ->
1
end.
%% 获取可以用的线路信息
get_use_scene_line_scene_id(SceneId, PlayerState) ->
case instance_base_lib:is_multiple_instance(SceneId) of
false ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
get_use_scene_line(EtsMaps#ets_scene_maps.pid_list);
_ ->
1
end;
true ->
SceneSign = instance_base_lib:get_instance_sign(PlayerState, SceneId),
case ets:lookup(?ETS_SCENE_MAPS, {SceneId, SceneSign}) of
[EtsMaps] ->
get_use_scene_line(EtsMaps#ets_scene_maps.pid_list);
_ ->
1
end
end.
%% 获取可以用的线路信息
get_use_scene_line(PidLineList) ->
Length = length(PidLineList),
case Length =:= 0 of
true ->
1;
_ ->
LineList = [X#pid_line.line_num || X <- PidLineList],
MaxLine = lists:max(LineList),
get_use_scene_line1(MaxLine, 1, LineList)
end.
%% 获取还未使用的线路
get_use_scene_line1(MaxLine, MaxLine, _LineList) ->
MaxLine + 1;
get_use_scene_line1(NowLine, MaxLine, LineList) ->
case lists:member(NowLine, LineList) of
true ->
get_use_scene_line1(NowLine + 1, MaxLine, LineList);
_ ->
NowLine
end. | null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/scene/scene_mgr_lib.erl | erlang | -------------------------------------------------------------------
@doc
场景管理模块
@end
-------------------------------------------------------------------
API
callbacks
====================================================================
API functions
====================================================================
创建场景(非场景管理进程使用)
创建场景(场景管理进程使用)
获取属于的线路
获取属于的线路
创建永存场景2
创建完场景创建随机怪物(随机怪物只刷新在1线)
属怪
切换场景
主动切换线,本服幻境有使用
如果是合服场景,判断是否放
如果是合服场景,判断是否放
判断是否扣除道具信息
检测场景消耗
检查切换场景条件是否满足
检查切换场景条件是否满足
如何是副本场景,还需要进一步判断副本进入次数和道具
判断场景类型
等级不足
如何是副本场景,还需要进一步判断副本进入次数和道具
玩家原先所在的场景
副本进入次数用光了
玩家战力不足
等级不足
如何是活动,判断活动的开启时间
玩家原先所在的场景
等级不足
判断玩家是否可以进入剧情副本
检查切换场景是否需要恢复血量
主动切换场景
普通副本
获取普通副本信息
进出满状态
检查cursceneid是否为空
普通副本
离开副本
跨服验证
切换场景(这里必须用异步操作,原来用同步操作压力大时会出现timeout)
如果是同一张场景
如果是同场景,只需要瞬移就可以
非同场景需要正常的跑进入流程
%% 检查切换场景是否需要恢复血量
获取玩家的属性信息
异步切换场景
切换线路
异步切换场景
_ ->
%% 进入新场景
end;
切换场景
判断该场景是否还存在
切换场景
如果进入场景的时候是皇宫场景,则要传送到出口
重新进入场景
重新进入场景
如果场景进程已经崩溃
先清理掉无效的ets信息
根据不同的场景做不同的操作
如果是副本场景需要跑正常的逻辑
离开旧场景且进入新场景
离开旧场景
进入新场景
离开场景
跨服退出
调用这个方法从参加进程移除玩家并通知同屏玩家
关闭所有场景,用于场景管理进程崩溃或者关服
场景进程调用(场景自动关闭或者出错关闭的时候调用)
退出副本(只有玩家进程才能掉用)
CHANGE_SCENE_TYPE_LEAVE_INSTANCE 离开副本
更新boss刷新时间,只有需要记录刷新倒计时的boss才会用到
根据进入的场景id获取合理的pk模式
如果自己设定的模式符合场景允许的pk模式则用自己的设定的模式
如果自己设定的模式以场景允许的模式不符合则使用场景允许的第一个模式
====================================================================
====================================================================
根据不同的场景类型来做不同的操作
如果是副本类型场景
主动切换场景
自动切换
检测是否是多人副本类型
如果是多人副本判断副本是否已经创建,如果是已经创建随机选择一个进入就行
获取场景副本标记
随机一个场景pid用于进入场景
如果没有创建,先创建场景然后再进入
其他副本直接直接创建新的场景再进入
非自动(这里一般情况不会进来,即使进来,一般场景都是已经创建好的了,否则场景管理进程已经出问题)
检测是否是多人副本类型
获取场景副本标记
ExitSceneConf = scene_config:get(ExitScene),
主城和野外等非副本类的场景都在这里判断
***********************************************
如果linenum不为0那么就是寻找跳转的具体线路
随机线路
获取场景里面的玩家人数
随机线路
获取场景里面的玩家人数
获取场景pid所在线路
获取以用的线路信息
获取可以用的线路信息
获取可以用的线路信息
获取还未使用的线路 | @author zhengsiying
( C ) 2015 , < COMPANY >
Created : 27 . 七月 2015 上午10:57
-module(scene_mgr_lib).
-include("common.hrl").
-include("record.hrl").
-include("config.hrl").
-include("cache.hrl").
-include("proto.hrl").
-include("language_config.hrl").
-include("log_type_config.hrl").
-define(SERVER, scene_mgr_mod).
-export([
create_scene/1,
create_scene/2,
change_scene/3,
change_scene/4,
change_scene/5,
change_scene/6,
change_scene/7,
succeed_change_scene/3,
leave_scene/2,
close_all_scene/0,
close_scene/1,
exit_instance/1,
create_permanently_scene/0,
update_boss_refresh/4,
get_boss_refresh/2,
get_new_pk_mode/3,
change_scene_line/6,
get_line_num/2,
get_scene_player_num/1,
get_scene_player_num/2,
check_condition/5
]).
-export([
do_create_scene/2,
do_create_scene/3,
do_change_scene/7,
do_succeed_change_scene/4,
do_leave_scene/3,
do_close_scene/2,
do_create_permanently_scene/1
]).
create_scene(SceneId) ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_create_scene, [SceneId]}).
create_scene(SceneId, PlayerState) ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_create_scene, [SceneId, PlayerState]}).
do_create_scene(_State, SceneId) ->
LineNum = get_use_scene_line_scene_id(SceneId),
初始化 场景 并获取盗场景的 状态pid
{ok, Pid} ->
EtsScene = #ets_scene{
pid = Pid,
scene_id = SceneId,
player_list = []
},
ets:insert(?ETS_SCENE, EtsScene),
PidLine = #pid_line{
pid = Pid,
line_num = LineNum
},
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
NewPidLineList = EtsMaps#ets_scene_maps.pid_list ++ [PidLine],
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidLineList});
_ ->
ets:insert(?ETS_SCENE_MAPS, #ets_scene_maps{scene_id = SceneId, pid_list = [PidLine]})
end,
{ok, Pid};
Err ->
?ERR("create scene ~p error: ~p", [SceneId, Err]),
{fail, Err}
end.
do_create_scene(_State, SceneId, PlayerState) ->
LineNum = get_use_scene_line_scene_id(SceneId, PlayerState),
初始化 场景 并获取盗场景的 状态pid
{ok, Pid} ->
EtsScene = #ets_scene{
pid = Pid,
scene_id = SceneId,
player_list = []
},
ets:insert(?ETS_SCENE, EtsScene),
PidLine = #pid_line{
pid = Pid,
line_num = LineNum
},
case instance_base_lib:is_multiple_instance(SceneId) of
false ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
NewPidLineList = EtsMaps#ets_scene_maps.pid_list ++ [PidLine],
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidLineList});
_ ->
ets:insert(?ETS_SCENE_MAPS, #ets_scene_maps{scene_id = SceneId, pid_list = [PidLine]})
end;
true ->
SceneSign = instance_base_lib:get_instance_sign(PlayerState, SceneId),
case ets:lookup(?ETS_SCENE_MAPS, {SceneId, SceneSign}) of
[EtsMaps] ->
NewPidLineList = EtsMaps#ets_scene_maps.pid_list ++ [PidLine],
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidLineList});
_ ->
ets:insert(?ETS_SCENE_MAPS, #ets_scene_maps{scene_id = {SceneId, SceneSign}, pid_list = [PidLine]})
end
end,
{ok, Pid};
Err ->
?ERR("create scene ~p error: ~p", [SceneId, Err]),
{fail, Err}
end.
创建永存场景
create_permanently_scene() ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_create_permanently_scene, []}, 10 * 1000).
do_create_permanently_scene(_State) ->
F = fun(Type) ->
SceneList = scene_config:get_type_list(Type),
F1 = fun(X) ->
do_create_scene(_State, X)
end,
[F1(SceneId) || SceneId <- SceneList, not lists:member(SceneId, scene_config:get_cross_list())]
end,
永存场景类型
PermSceneList = [?SCENE_TYPE_MAIN_CITY, ?SCENE_TYPE_OUTDOOR],
[F(Type) || Type <- PermSceneList],
create_random_monster().
create_random_monster() ->
List = random_monster_config:get_list(),
create_random_monster([], List).
create_random_monster(_, []) ->
skip;
create_random_monster(TypeList, [Id | T]) ->
Conf = random_monster_config:get(Id),
Type = Conf#random_monster_conf.batch,
case lists:member(Type, TypeList) of
true ->
skip;
false ->
scene_obj_lib:refuse_random_monster(Conf),
create_random_monster([Type] ++ TypeList, T)
end.
)
? CHANGE_SCENE_TYPE_CHANGE 主动切换场景
change_scene(PlayerState, PlayerPid, SceneId, ChangeType) ->
)
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, null, false).
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, null, false, LineNum).
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem) ->
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem, 0).
change_scene(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem, LineNum) ->
case function_db:is_open_scene(SceneId) of
true ->
change_scene_new(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItem, LineNum);
_ ->
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_SCENE_MERGE_NO_OPEN}),
{ok, PlayerState}
end.
) 有特殊道具消耗 IsDelItem是否 验证道具
change_scene_new(PlayerState, PlayerPid, SceneId, ChangeType, Point, ItemLoss, IsNotItemTemp, LineNum) ->
SceneConf = scene_config:get(SceneId),
case ChangeType of
?CHANGE_SCENE_TYPE_CHANGE ->
只有切换场景才需要做条件判断和扣物品的检查
{PlayerState1, EnterTimes} = player_instance_lib:get_instance_enter_times(PlayerState, SceneId),
IsNotItem =
case IsNotItemTemp of
false ->
check_scene_cost(PlayerState1, SceneConf);
_ ->
IsNotItemTemp
end,
case check_condition(PlayerState1, SceneId, EnterTimes, ItemLoss, IsNotItem, LineNum) of
{true, TimeSpan} ->
NewPlayerState =
case SceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->
case active_instance_config:get(SceneId) of
#active_instance_conf{} = _ ->
PlayerState1#player_state{
scene_parameters = TimeSpan
};
_ ->
?INFO("TTTSSS1111 ~p", [11]),
如果进入副本则需要扣相应的道具并且增加副本进入次数
InstanceConf = instance_config:get(SceneId),
{ok, PlayerState2} = goods_util:delete_special_list(PlayerState1, InstanceConf#instance_conf.cost, ?LOG_TYPE_TRANSFER),
PlayerState3 = player_instance_lib:add_instance_enter_times(PlayerState2, SceneConf#scene_conf.belong_scene_id),
PlayerState3
end;
_ ->
?INFO("TTTSSS222 ~p", [11]),
Cost = SceneConf#scene_conf.cost,
{ok, PlayerState2} =
case Cost =:= [] orelse IsNotItem of
true -> {ok, PlayerState1};
_ ->
goods_util:delete_special_list(PlayerState1, Cost, ?LOG_TYPE_TRANSFER)
end,
{ok, PlayerState4} = case ItemLoss of
null -> {ok, PlayerState2};
{ItemId, ItemNum, Type} ->
case goods_lib_log:delete_goods_by_num(PlayerState2, ItemId, ItemNum, Type) of
{ok, PlayerState3} ->
{ok, PlayerState3};
_ ->
{ok, PlayerState2}
end
end,
PlayerState4
end,
change_scene_cross(NewPlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum);
{fail, Err} ->
?INFO("TTTSSS333 ~p", [Err]),
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = Err}),
{ok, PlayerState}
end;
_ ->
change_scene_cross(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum)
end.
check_scene_cost(PlayerState, SceneConf) ->
OldSceneConf = scene_config:get(PlayerState#player_state.scene_id),
case is_record(OldSceneConf, scene_conf) andalso
OldSceneConf#scene_conf.belong_scene_id =:= SceneConf#scene_conf.belong_scene_id andalso
OldSceneConf#scene_conf.power_limit > SceneConf#scene_conf.power_limit
of
true ->
true;
_ ->
false
end.
check_condition(PlayerState, SceneId, EnterTimes, ItemLoss, IsNotItem) ->
check_condition(PlayerState, SceneId, EnterTimes, ItemLoss, IsNotItem, 0).
check_condition(PlayerState, SceneId, EnterTimes, ItemLoss, IsNotItem, LineNum) ->
case scene_config:get(SceneId) of
#scene_conf{} = SceneConf ->
DbPlayerBase = PlayerState#player_state.db_player_base,
case active_instance_config:get(SceneId) of
#active_instance_conf{} = _ ->
check_condition2(PlayerState, SceneConf, ItemLoss, IsNotItem);
_ ->
case SceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->
check_condition1(PlayerState, SceneConf, EnterTimes, IsNotItem, LineNum);
_ ->
case DbPlayerBase#db_player_base.lv >= SceneConf#scene_conf.lv_limit of
true ->
case PlayerState#player_state.fighting > SceneConf#scene_conf.power_limit of
true ->
case IsNotItem orelse goods_util:check_special_list(PlayerState, SceneConf#scene_conf.cost) of
true ->
是否还有其他的道具消耗
case ItemLoss of
{ItemId, ItemNum, _Type} ->
case goods_util:check_special_list(PlayerState, [{ItemId, ItemNum}]) of
true ->
case DbPlayerBase#db_player_base.vip >= SceneConf#scene_conf.viplv_limit of
true -> {true, 0};
false -> {fail, ?ERR_PLAYER_VIPLV_NOT_ENOUGH}
end;
Fail ->
Fail
end;
_ ->
{true, 0}
end;
Fail ->
Fail
end;
_ ->
{fail, ?ERR_PLAYER_FIGHT_NOT_ENOUGH}
end;
_ ->
end
end
end;
_ ->
{fail, ?ERR_COMMON_FAIL}
end.
check_condition1(PlayerState, SceneConf, EnterTimes, IsNotItem, LineNum) ->
case scene_config:get(PlayerState#player_state.scene_id) of
#scene_conf{} = OldSceneConf ->
case OldSceneConf#scene_conf.type =:= ?SCENE_TYPE_INSTANCE andalso PlayerState#player_state.scene_id =:= SceneConf#scene_conf.scene_id
andalso PlayerState#player_state.scene_line_num =:= LineNum of
true ->
{fail, ?ERR_SCENE_INSTANCE};
_ ->
SceneId = SceneConf#scene_conf.scene_id,
DbPlayerBase = PlayerState#player_state.db_player_base,
case DbPlayerBase#db_player_base.lv >= SceneConf#scene_conf.lv_limit of
true ->
case PlayerState#player_state.fighting > SceneConf#scene_conf.power_limit of
true ->
InstanceConf = instance_config:get(SceneId),
case (EnterTimes < InstanceConf#instance_conf.times_limit
orelse InstanceConf#instance_conf.times_limit =< 0 orelse IsNotItem)
andalso check_instance(InstanceConf#instance_conf.type, InstanceConf) of
true ->
case IsNotItem orelse goods_util:check_special_list(PlayerState, InstanceConf#instance_conf.cost) of
true ->
检查个人boss剩余时间
case InstanceConf#instance_conf.type =/= 9
orelse DbPlayerBase#db_player_base.instance_left_time > 0 of
true ->
{true, 0};
false ->
{fail, ?ERR_INSTANCE_LEFT_TIME_LIMIT}
end;
_ ->
{fail, ?ERR_GOODS_NOT_ENOUGH}
end;
_ ->
end;
_ ->
end;
_ ->
end
end;
_ ->
{fail, ?ERR_SCENE}
end.
check_condition2(PlayerState, SceneConf, ItemLoss, IsNotItem) ->
DbPlayerBase = PlayerState#player_state.db_player_base,
case DbPlayerBase#db_player_base.lv >= SceneConf#scene_conf.lv_limit of
true ->
case PlayerState#player_state.fighting > SceneConf#scene_conf.power_limit of
true ->
case active_instance_lib:is_open_active(SceneConf#scene_conf.scene_id) of
{ok, TimeSpam} ->
case IsNotItem of
true ->
{true, TimeSpam};
_ ->
case goods_util:check_special_list(PlayerState, SceneConf#scene_conf.cost) of
true ->
是否还有其他的道具消耗
case ItemLoss of
{ItemId, ItemNum, _Type} ->
case goods_util:check_special_list(PlayerState, [{ItemId, ItemNum}]) of
true ->
{true, TimeSpam};
Fail ->
Fail
end;
_ ->
{true, TimeSpam}
end;
Fail ->
Fail
end
end;
Fail ->
Fail
end;
_ ->
{fail, ?ERR_PLAYER_FIGHT_NOT_ENOUGH}
end;
_ ->
end.
check_instance(?INSTANCE_TYPE_PLOT, InstanceConf) ->
TaskList = player_task_dict:get_player_task_list(),
F = fun(X, IsOk) ->
case IsOk of
true ->
IsOk;
_ ->
case X#db_player_task.isfinish of
1 ->
false;
_ ->
TaskConf = task_config:get(X#db_player_task.taskid_id),
case TaskConf#task_conf.openinstance of
<<"">> ->
false;
OpenWinInfo ->
OpenWinInfo1 = erlang:binary_to_list(OpenWinInfo),
TList = string:tokens(OpenWinInfo1, ","),
TId = list_to_integer(lists:last(TList)),
Conf = scene_transport_config:get(TId),
Conf#scene_transport_conf.scene_id =:= InstanceConf#instance_conf.scene_id
end
end
end
end,
lists:foldr(F, false, TaskList);
check_instance(_, _) ->
true.
need_recover(ChangeType, CurSceneId, NewSceneId) ->
case ChangeType of
新场景信息
case NewSceneConf#scene_conf.type of
_ ->
true ->
false;
_ ->
case CurSceneConf#scene_conf.type of
CurInstanceConf = instance_config:get(CurSceneId),
CurInstanceConf#instance_conf.recover =:= ?INSTANCE_RECOVER_IS;
_ ->
false
end
end
end;
case util_data:is_null(CurSceneId) of
true ->
false;
_ ->
CurSceneConf = scene_config:get(CurSceneId),
case CurSceneConf#scene_conf.type of
?SCENE_TYPE_INSTANCE ->
CurInstanceConf = instance_config:get(CurSceneId),
CurInstanceConf#instance_conf.recover =:= ?INSTANCE_RECOVER_IS;
_ ->
false
end
end;
_ ->
false
end.
change_scene_cross(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
SceneConf = scene_config:get(SceneId),
#player_state{server_pass = ServerPass} = PlayerState,
case SceneConf#scene_conf.is_cross of
1 ->
?INFO("change_scene_cross ~p", [1111]),
如果是在跨服的话 那么处理跨服信息
Result = case util_data:is_null(ServerPass) of
true ->
scene_cross:send_cross(PlayerState);
_ ->
{ok, PlayerState}
end,
case Result of
{ok, PlayerState1} ->
case cross_lib:send_cross_mfc(PlayerState1#player_state.server_pass, ?MODULE, change_scene, [PlayerState1, PlayerPid, SceneId, ChangeType, Point, LineNum]) of
{ok, PlayerState2} ->
{ok, PlayerState2};
_Err ->
?ERR("~p", [_Err]),
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_COMMON_FAIL})
end;
{fail, Err} ->
net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = Err}),
{ok, PlayerState}
end;
_ ->
?INFO("change_scene_cross ~p", [2222]),
如果不是在跨服的话 那么移除跨服信息
PlayerState1 = scene_cross:send_log_out(PlayerState),
change_scene1(PlayerState1, PlayerPid, SceneId, ChangeType, Point, LineNum)
end.
change_scene1(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
#player_state{
player_id = PlayerId,
scene_id = CurSceneId,
scene_pid = CurScenePid,
scene_line_num = OldLineNum
} = PlayerState,
case CurSceneId =:= SceneId andalso is_pid(CurScenePid) andalso (OldLineNum =:= LineNum orelse LineNum =:= 0) andalso not util_data:is_null(Point) of
true ->
?INFO("TTTSSS444 ~p", [11]),
scene_obj_lib:instant_move(CurScenePid, ?OBJ_TYPE_PLAYER, PlayerId, Point, ?DIRECTION_UP),
{ok, PlayerState#player_state{recover_pet_list = []}};
_ ->
?INFO("TTTSSS555 ~p", [11]),
PlayerState1 =
true ->
Update = #player_state{
db_player_attr = #db_player_attr{cur_mp = AttrTotal#attr_base.mp, cur_hp = AttrTotal#attr_base.hp}
},
{ok, _PlayerState1} = player_lib:update_player_state(PlayerState, Update),
_PlayerState1;
_ ->
PlayerState
end,
gen_server2:apply_async(misc:whereis_name({local, ?SERVER}), {?MODULE, do_change_scene, [PlayerState1, PlayerPid, SceneId, ChangeType, Point, LineNum]}),
{ok, PlayerState1#player_state{recover_pet_list = []}}
end.
change_scene_line(PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
gen_server2:apply_async(misc:whereis_name({local, ?SERVER}), {?MODULE, do_change_scene, [PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum]}),
{ok, PlayerState#player_state{recover_pet_list = []}}.
切换场景(场景管理进程调用 )
do_change_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
case scene_config:get(SceneId) of
#scene_conf{} = _SceneConf ->
do_change_scene1(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, null, LineNum);
= PlayerState#player_state.player_id ,
SceneType = SceneConf#scene_conf.type ,
case ets : lookup(?ETS_PLAYER_SCENE , ) of
[
? INFO("do_change_scene1 222 ~p " , [ 11 ] ) ,
do_change_scene1(State , PlayerState , PlayerPid , SceneId , ChangeType , Point , EtsPlayerScene , LineNum ) ;
? INFO("do_enter_new_scene 11 ~p " , [ 11 ] ) ,
do_enter_new_scene(SceneType , State , PlayerState , PlayerPid , SceneId , ChangeType , Point , LineNum )
_ ->
?ERR("enter scene ~p error: not scene config!", [SceneId])
end.
do_change_scene1(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, _EtsPlayerScene, LineNum) ->
ScenePid = PlayerState#player_state.scene_pid,
case PlayerState#player_state.scene_id =:= SceneId andalso LineNum =:= 0 of
true ->
case ets:lookup(?ETS_SCENE, ScenePid) of
[_EtsScene] ->
?INFO("ooo 11 ~p", [11]),
leave_and_enter_new_scene(State , PlayerState , PlayerPid , SceneId , ChangeType , Point , ScenePid , LineNum ) ;
do_change_scene2(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, PlayerState#player_state.scene_line_num);
_ ->
?INFO("ooo 22 ~p", [22]),
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum)
end;
_ ->
?INFO("ooo 33 ~p", [33]),
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum)
end.
do_change_scene2(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum) ->
SceneConf = scene_config:get(SceneId),
#scene_conf{
type = SceneType,
activity_id = ActivityId,
exit_scene = ExitScene
} = SceneConf,
case misc:is_process_alive(ScenePid) of
true ->
case ChangeType =:= ?CHANGE_SCENE_TYPE_ENTER andalso ActivityId =:= ?SCENE_ACTIVITY_PALACE of
true ->
case ets:lookup(?ETS_SCENE_MAPS, ExitScene) of
[EtsMaps] ->
ExitSceneConf = scene_config:get(ExitScene),
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, ExitSceneConf, null) of
null ->
{fail, 1};
Pid ->
?INFO("ooo 55 ~p", [55]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, null)
end;
_ ->
{fail, 1}
end;
_ ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, null) of
null ->
{fail, 1};
Pid ->
?INFO("ooo 44 ~p ~p", [length(PidLineList), 44]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point)
end;
_ ->
?INFO("ooo 99 ~p", [44]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, ScenePid, ChangeType, Point)
end
end;
_ ->
do_close_scene(State, ScenePid),
case SceneType of
?SCENE_TYPE_INSTANCE ->
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, 0);
_ ->
如果是野外或者主城,必须修正(重建主城 / 野外)再进入场景
case do_create_scene(State, SceneId, PlayerState) of
{ok, Pid} ->
?INFO("ooo 66", [66]),
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point);
{fail, Err} ->
{fail, Err}
end
end
end.
leave_and_enter_new_scene(State, PlayerState, PlayerPid, SceneId, ChangeType, Point, ScenePid, LineNum) ->
PlayerId = PlayerState#player_state.player_id,
SceneConf = scene_config:get(SceneId),
SceneType = SceneConf#scene_conf.type,
do_leave_scene(State, PlayerId, ScenePid, ?LEAVE_SCENE_TYPE_INITIATIVE),
do_enter_new_scene(SceneType, State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum).
保存玩家的id 进入场景的进程中 ( 玩家进程调用 )
succeed_change_scene(PlayerId, SceneId, ScenePid) ->
gen_server2:apply_async(misc:whereis_name({local, ?SERVER}), {?MODULE, do_succeed_change_scene, [PlayerId, SceneId, ScenePid]}).
保存玩家的id 进入场景的进程中 ( 玩家进程调用 )
do_succeed_change_scene(_State, PlayerId, SceneId, ScenePid) ->
case ets:lookup(?ETS_SCENE, ScenePid) of
[EtsScene] ->
NewPlayerList = util_list:store(PlayerId, EtsScene#ets_scene.player_list),
ets:update_element(?ETS_SCENE, ScenePid, {#ets_scene.player_list, NewPlayerList}),
ets:insert(?ETS_PLAYER_SCENE, #ets_player_scene{player_id = PlayerId, scene_id = SceneId, pid = ScenePid});
_ ->
skip
end.
leave_scene(PlayerState, LeaveType) ->
scene_cross:send_log_out(PlayerState),
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_leave_scene, [PlayerState#player_state.player_id, LeaveType]}).
do_leave_scene(State, PlayerId, LeaveType) ->
case ets:lookup(?ETS_PLAYER_SCENE, PlayerId) of
[EtsPlayerScene] ->
do_leave_scene(State, PlayerId, EtsPlayerScene#ets_player_scene.pid, LeaveType),
case LeaveType of
?LEAVE_SCENE_TYPE_INITIATIVE ->
ets:delete(?ETS_PLAYER_SCENE, PlayerId);
_ ->
skip
end;
_ ->
skip
end.
do_leave_scene(_State, PlayerId, ScenePid, LeaveType) ->
case util_data:check_pid(ScenePid) of
true ->
scene_obj_lib:remove_obj(ScenePid, ?OBJ_TYPE_PLAYER, PlayerId, LeaveType);
_ ->
skip
end.
close_all_scene() ->
List = ets:tab2list(?ETS_SCENE),
[gen_server2:apply_async(EtsScene#ets_scene.pid, {scene_mod, stop, []}) || EtsScene <- List].
close_scene(ScenePid) ->
gen_server2:apply_sync(misc:whereis_name({local, ?SERVER}), {?MODULE, do_close_scene, [ScenePid]}).
do_close_scene(_State, ScenePid) ->
case ets:lookup(?ETS_SCENE, ScenePid) of
[EtsScene] ->
SceneId = EtsScene#ets_scene.scene_id,
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
NewPidList = lists:keydelete(ScenePid, #pid_line.pid, EtsMaps#ets_scene_maps.pid_list),
case NewPidList of
[] ->
ets:delete(?ETS_SCENE_MAPS, SceneId);
_ ->
ets:insert(?ETS_SCENE_MAPS, EtsMaps#ets_scene_maps{pid_list = NewPidList})
end;
_ ->
skip
end,
ets:delete(?ETS_SCENE, ScenePid);
_ ->
skip
end.
exit_instance(PlayerState) ->
SceneId = PlayerState#player_state.scene_id,
case scene_config:get(SceneId) of
#scene_conf{exit_scene = ExitScene} when ExitScene > 0 ->
change_scene(PlayerState, self(), ExitScene, ?CHANGE_SCENE_TYPE_LEAVE_INSTANCE);
_ ->
skip
end.
update_boss_refresh(SceneId, LineNum, BossId, RefreshTime) ->
EtsBossRefresh = #ets_boss_refresh{
scene_boss_id = {SceneId, LineNum, BossId},
refresh_time = RefreshTime
},
ets:insert(?ETS_BOSS_REFRESH, EtsBossRefresh).
获取boss刷新时间
get_boss_refresh(SceneId, BossId) ->
case ets:lookup(?ETS_BOSS_REFRESH, {SceneId, 1, BossId}) of
[EtsBossRefresh] ->
EtsBossRefresh;
_ ->
null
end.
get_new_pk_mode(SceneId, _OldPkMode, SetPkMode) ->
SceneConf = scene_config:get(SceneId),
PkModeList = SceneConf#scene_conf.pk_mode_list,
case lists:member(SetPkMode, PkModeList) orelse PkModeList =:= [] of
true ->
SetPkMode;
_ ->
[NewPkMode | _T] = PkModeList,
NewPkMode
end.
Internal functions
do_enter_new_scene(?SCENE_TYPE_INSTANCE, State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
case ChangeType of
true ->
case ets:lookup(?ETS_SCENE_MAPS, {SceneId, SceneSign}) of
[EtsMaps] ->
SceneConf = scene_config:get(SceneId),
null ->
{fail, 1};
Pid ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point)
end;
_ ->
case do_create_scene(State, SceneId, PlayerState) of
{ok, Pid} ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point);
{fail, Err} ->
{fail, Err}
end
end;
false ->
case do_create_scene(State, SceneId, PlayerState) of
{ok, Pid} ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, Point);
{fail, Err} ->
{fail, Err}
end
end;
_ ->
SceneConf = scene_config:get(SceneId),
ExitScene = SceneConf#scene_conf.exit_scene ,
true ->
{SceneId, SceneSign};
_ ->
SceneId
end,
?WARNING("do_enter_new_scene ~p", [[SceneId, LineNum]]),
case ets:lookup(?ETS_SCENE_MAPS, Key) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, null) of
null ->
{fail, 1};
Pid ->
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid, ChangeType, null)
end;
_ ->
{fail, 1}
end
end;
do_enter_new_scene(_Type, _State, PlayerState, PlayerPid, SceneId, ChangeType, Point, LineNum) ->
正常情况都不需要再创建场景,在服务器开启的时候已经预先创建好(以后如过做分线可以修改这里 )
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
SceneConf = scene_config:get(SceneId),
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case get_pid_top(PidLineList, PidLineList, LineNum, SceneConf, null) of
null ->
{fail, 1};
Pid ->
Pid2 = case is_process_alive(Pid) of
true ->
Pid;
_ ->
scene_tool:create_scene_pid(SceneId),
case scene_mgr_lib:do_create_scene(_State, SceneId) of
{ok, Pid1} ->
Pid1;
_ ->
Pid
end
end,
scene_obj_lib_copy:enter(PlayerState, PlayerPid, Pid2, ChangeType, Point)
end;
_ ->
{fail, 1}
end.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
get_pid_top([], PidLineList, _LineNum, SceneConf, PlayerState) ->
case SceneConf#scene_conf.copy_num =:= 1 of
true ->
case util_rand:list_rand(PidLineList) of
null ->
null;
PidLine ->
?INFO("linenum 33 ~p", [PidLine#pid_line.line_num]),
PidLine#pid_line.pid
end;
_ ->
Result = case util_data:is_null(PlayerState) of
true ->
do_create_scene(null, SceneConf#scene_conf.scene_id);
_ ->
do_create_scene(null, SceneConf#scene_conf.scene_id, PlayerState)
end,
case Result of
{ok, Pid} ->
Pid;
_ ->
case util_rand:list_rand(PidLineList) of
null ->
null;
PidLine ->
?INFO("linenum 33 ~p", [PidLine#pid_line.line_num]),
PidLine#pid_line.pid
end
end
end;
get_pid_top([PidLine | H], PidLineList, LineNum, SceneConf, PlayerState) ->
NowPid = case LineNum /= 0 of
true ->
case lists:keyfind(LineNum, #pid_line.line_num, PidLineList) of
false ->
0;
NowPidLine ->
?INFO("linenum 22 ~p ~p", [NowPidLine#pid_line.line_num, LineNum]),
NowPidLine#pid_line.pid
end;
_ ->
0
end,
case NowPid =:= 0 of
true ->
case ets:lookup(?ETS_SCENE, PidLine#pid_line.pid) of
[EtsScene] ->
case length(EtsScene#ets_scene.player_list) < SceneConf#scene_conf.limit_num of
true ->
?INFO("linenum 11 ~p", [PidLine#pid_line.line_num]),
PidLine#pid_line.pid;
_ ->
get_pid_top(H, PidLineList, 0, SceneConf, PlayerState)
end;
_ ->
get_pid_top(H, PidLineList, 0, SceneConf, PlayerState)
end;
_ ->
NowPid
end.
get_scene_player_num(ScenePid) ->
case ets:lookup(?ETS_SCENE, ScenePid) of
[EtsScene] ->
length(EtsScene#ets_scene.player_list);
_ ->
0
end.
get_scene_player_num(SceneId, LineNum) ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case lists:keyfind(LineNum, #pid_line.line_num, PidLineList) of
false ->
0;
PidLine ->
get_scene_player_num(PidLine#pid_line.pid)
end;
_ ->
0
end.
get_line_num(ScenePid, SceneId) ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
PidLineList = EtsMaps#ets_scene_maps.pid_list,
case lists:keyfind(ScenePid, #pid_line.pid, PidLineList) of
false ->
{0, PidLineList};
PidLine ->
{PidLine#pid_line.line_num, PidLineList}
end;
_ ->
{0, []}
end.
get_use_scene_line_scene_id(SceneId) ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
get_use_scene_line(EtsMaps#ets_scene_maps.pid_list);
_ ->
1
end.
get_use_scene_line_scene_id(SceneId, PlayerState) ->
case instance_base_lib:is_multiple_instance(SceneId) of
false ->
case ets:lookup(?ETS_SCENE_MAPS, SceneId) of
[EtsMaps] ->
get_use_scene_line(EtsMaps#ets_scene_maps.pid_list);
_ ->
1
end;
true ->
SceneSign = instance_base_lib:get_instance_sign(PlayerState, SceneId),
case ets:lookup(?ETS_SCENE_MAPS, {SceneId, SceneSign}) of
[EtsMaps] ->
get_use_scene_line(EtsMaps#ets_scene_maps.pid_list);
_ ->
1
end
end.
get_use_scene_line(PidLineList) ->
Length = length(PidLineList),
case Length =:= 0 of
true ->
1;
_ ->
LineList = [X#pid_line.line_num || X <- PidLineList],
MaxLine = lists:max(LineList),
get_use_scene_line1(MaxLine, 1, LineList)
end.
get_use_scene_line1(MaxLine, MaxLine, _LineList) ->
MaxLine + 1;
get_use_scene_line1(NowLine, MaxLine, LineList) ->
case lists:member(NowLine, LineList) of
true ->
get_use_scene_line1(NowLine + 1, MaxLine, LineList);
_ ->
NowLine
end. |
ac81e16d14415c5b93bd434f2142dfa713d18cbd88f0bd9b35e9fb8e2a71dadf | dorchard/effect-monad | WriteOnceWriter.hs | # LANGUAGE RebindableSyntax , NoMonomorphismRestriction #
import Prelude hiding (Monad(..))
import Control.Effect
import Control.Effect.WriteOnceWriter
foo = do put 42
put "hello"
return () | null | https://raw.githubusercontent.com/dorchard/effect-monad/5750ef8438f750e528002a0a4e255514cbf3150a/examples/WriteOnceWriter.hs | haskell | # LANGUAGE RebindableSyntax , NoMonomorphismRestriction #
import Prelude hiding (Monad(..))
import Control.Effect
import Control.Effect.WriteOnceWriter
foo = do put 42
put "hello"
return () | |
b5bb55a13a026acbb05b62c28cc4bcc0a1c6f21089ea79c17534100678fd96ca | helium/blockchain-core | blockchain_poc_path.erl | %%%-------------------------------------------------------------------
%% @doc
%% == Blockchain PoC Path ==
%% @end
%%%-------------------------------------------------------------------
-module(blockchain_poc_path).
-include("blockchain_vars.hrl").
-include("blockchain_caps.hrl").
-export([
build/5,
shortest/3, shortest/4,
length/3, length/4,
build_graph/4,
target/3,
neighbors/3,
entropy/1,
check_sync/2,
active_gateways/2 %% exported for debug purposes
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
KRing of 1
% Scale 3.57
distance 1.028 miles @ resolution 8
distance 0.38 miles @ resolution 9
KRing of 2
Scale 5.42
distance 1.564 miles @ resolution 8 < ---
distance 0.59 miles @ resolution 9
%
KRing of 3
% Scale: unknown
distance : unknown , presumably larger than 1.54 miles
-type graph() :: #{any() => [{number(), any()}]}.
-type gateways() :: #{libp2p_crypto:pubkey_bin() => {blockchain_ledger_gateway_v2:gateway(), float()}}.
-export_type([graph/0]).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec build(Hash :: binary(),
Target :: binary(),
Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> {ok, list()} | {error, any()}.
build(Hash, Target, Gateways, Height, Ledger) ->
Graph = build_graph_int([Target], Gateways, Height, Ledger, #{}),
GraphList = maps:fold(
fun(Addr, _, Acc) ->
case Addr == Target of
true ->
Acc;
false ->
{_G, Score} = maps:get(Addr, Gateways),
[{Score, Addr}|Acc]
end
end,
[],
Graph
),
case erlang:length(GraphList) >= 2 of
false ->
lager:error("target/gateways ~p", [{Target, Gateways}]),
lager:error("graph: ~p GraphList ~p", [Graph, GraphList]),
{error, not_enough_gateways};
true ->
PathLimit = case ?get_var(?poc_version, Ledger) of
{ok, POCVersion0} when POCVersion0 >= 3 ->
case ?get_var(?poc_path_limit, Ledger) of
{ok, Val0} when is_integer(Val0) ->
we 're only interested in half paths up to
the half total path limit
ceil(Val0/2);
_ ->
infinity
end;
_ ->
infinity
end,
%% find the longest, highest scoring paths that don't exceed any path limits
%% paths that are too long are filtered because their score ends up as 0
Lengths =
[ {S, G} || {S, G} <- [{Score * ?MODULE:length(Graph, Target, Addr, PathLimit), G}
|| {Score, Addr} = G <- blockchain_utils:shuffle_from_hash(Hash, GraphList)], S > 0 ],
sort the highest scoring paths first
[{_, {_, Start}}, {_, {_, End}}|_] = lists:sort(fun({S1, _}, {S2, _}) -> S1 > S2 end,
Lengths),
{_, Path1} = ?MODULE:shortest(Graph, Start, Target),
{_, [Target|Path2]} = ?MODULE:shortest(Graph, Target, End),
%% NOTE: It is possible the path contains dupes, these are also considered valid
Path3 = Path1 ++ Path2,
case erlang:length(Path3) > 2 of
false ->
lager:error("target/gateways ~p", [{Target, Gateways}]),
lager:error("graph: ~p GraphList ~p", [Graph, GraphList]),
lager:error("path: ~p", [Path3]),
{error, path_too_small};
true ->
blockchain_utils:rand_from_hash(Hash),
Path4 = case rand:uniform(2) of
1 ->
Path3;
2 ->
lists:reverse(Path3)
end,
case ?get_var(?poc_version, Ledger) of
{error, not_found} ->
{ok, Path4};
{ok, POCVersion} when POCVersion >= 2 ->
case ?get_var(?poc_path_limit, Ledger) of
{error, not_found} ->
{ok, Path4};
{ok, Val} ->
%% NOTE: The tradeoff here is that we may potentially lose target and end
%% from the path, but the fact that we would still have constructed it should
%% suffice to build interesting paths which conform to the given path_limit
{ok, lists:sublist(Path4, Val)}
end
end
end
end.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec shortest(Graph :: graph(), Start :: any(), End :: any()) -> {number(), list()}.
shortest(Graph, Start, End) ->
shortest(Graph, Start, End, infinity).
-spec shortest(Graph :: graph(), Start :: any(), End :: any(), Limit :: pos_integer() | 'infinity') -> {number(), list()}.
shortest(Graph, Start, End, Limit) ->
path(Graph, [{0, [Start]}], End, #{}, Limit).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec length(Graph :: graph(), Start :: any(), End :: any()) -> integer().
length(Graph, Start, End) ->
length(Graph, Start, End, infinity).
-spec length(Graph :: graph(), Start :: any(), End :: any(), Limit :: pos_integer() | 'infinity') -> integer().
length(Graph, Start, End, Limit) ->
{_Cost, Path} = ?MODULE:shortest(Graph, Start, End, Limit),
erlang:length(Path).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec build_graph(Address :: binary(),
Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> graph().
build_graph(Address, Gateways, Height, Ledger) ->
build_graph_int([Address], Gateways, Height, Ledger, #{}).
-spec build_graph_int([binary()],
Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger(),
Graph :: graph()) -> graph().
build_graph_int([], _Gateways, _Height, _Ledger, Graph) ->
Graph;
build_graph_int([Address0|Addresses], Gateways, Height, Ledger, Graph0) ->
%% find all the neighbors of address 0
case Gateways of
#{Address0 := {Gw0, Score0}} ->
Neighbors0_0 = blockchain_ledger_gateway_v2:neighbors(Gw0),
Neighbors0 = filter_neighbors(Address0, Score0, Neighbors0_0, Gateways, Height, Ledger),
%% fold over the list of neighbors
Graph1 = lists:foldl(
fun({_W, Address1}, Acc) ->
%% if the neighbor address is already in the
%% graph, skip it.
case maps:is_key(Address1, Acc) of
true ->
Acc;
false ->
%% otherwise, calculate its neighbors
#{Address1 := {Gw1, Score1}} = Gateways,
Neighbors1_0 = blockchain_ledger_gateway_v2:neighbors(Gw1),
Neighbors1 = filter_neighbors(Address1, Score1, Neighbors1_0, Gateways, Height, Ledger),
Graph1 = maps:put(Address1, Neighbors1, Acc),
%% and append all of its neighbor's neighbors?
build_graph_int([A || {_, A} <- Neighbors1,
A /= maps:is_key(A, Graph1)],
Gateways, Height, Ledger, Graph1)
end
end,
first , map address to neighbors
maps:put(Address0, Neighbors0, Graph0),
Neighbors0
),
FilteredAddresses = lists:filter(fun(A) -> not maps:is_key(A, Graph1) end,
Addresses),
build_graph_int(FilteredAddresses, Gateways, Height, Ledger, Graph1);
_ ->
Graph0
end.
%% ------------------------------------------------------------------
%% Internal Function Definitions
%% ------------------------------------------------------------------
-spec path(Graph :: graph(),
Path :: [{number(), list()}],
End :: any(),
Seen :: map(),
Limit :: pos_integer() | 'infinity') -> {number(), list()}.
path(_Graph, [], _End, _Seen, _Limit) ->
% nowhere to go
{0, []};
path(_Graph, [{Cost, [End | _] = Path} | _], End, _Seen, _Limit) ->
% base case
{Cost, lists:reverse(Path)};
path(Graph, [{Cost, [Node | _] = Path} | Routes] = _OldRoutes, End, Seen, Limit) ->
NewRoutes = lists:filter(fun({_, P}) -> length(P) =< Limit end,
[{Cost + NewCost, [NewNode | Path]} || {NewCost, NewNode} <- maps:get(Node, Graph, [{0, []}]), not maps:get(NewNode, Seen, false)]),
NextRoutes = cheapest_to_front(NewRoutes ++ Routes),
path(Graph, NextRoutes, End, Seen#{Node => true}, Limit).
cheapest_to_front([]) -> [];
cheapest_to_front([H | T]) ->
cheapest_to_front(H, T, []).
cheapest_to_front(C, [], Acc) ->
[C | Acc];
cheapest_to_front(C, [H | T], Acc) ->
case C > H of
true ->
cheapest_to_front(H, T, [C | Acc]);
_ ->
cheapest_to_front(C, T, [H | Acc])
end.
%%--------------------------------------------------------------------
%% @doc neighbors iterates through `Gateways` to find any Gateways
that are within max grid distance from the address in pubkeybin
%% @end
%%--------------------------------------------------------------------
neighbors(PubkeyBin, Gateways, Ledger) when is_binary(PubkeyBin) ->
case maps:get(PubkeyBin, Gateways, undefined) of
undefined ->
{error, bad_gateway};
{Gw, _S} ->
neighbors(Gw, Gateways, Ledger);
Gw ->
neighbors(Gw, Gateways, Ledger)
end;
neighbors(Gw, Gateways, Ledger) ->
GwH3 = blockchain_ledger_gateway_v2:location(Gw),
{ok, H3ExclusionRingDist} = ?get_var(?h3_exclusion_ring_dist, Ledger),
{ok, H3MaxGridDistance} = ?get_var(?h3_max_grid_distance, Ledger),
{ok, H3NeighborRes} = ?get_var(?h3_neighbor_res, Ledger),
ExclusionIndices = h3:k_ring(GwH3, H3ExclusionRingDist),
ScaledGwH3 = h3:parent(GwH3, H3NeighborRes),
lists:foldl(
fun({A, G0}, Acc) ->
G = case G0 of
{G1, _S} ->
G1;
_ ->
G0
end,
Mode = blockchain_ledger_gateway_v2:mode(G),
case {blockchain_ledger_gateway_v2:location(G),
blockchain_ledger_gateway_v2:is_valid_capability(Mode, ?GW_CAPABILITY_POC_CHALLENGEE, Ledger)} of
{undefined, _} -> Acc;
{_, false} -> Acc;
{Index, _} ->
ScaledIndex = scale(Index, H3NeighborRes),
case lists:member(ScaledIndex, ExclusionIndices) of
false ->
case (catch h3:grid_distance(ScaledGwH3, ScaledIndex)) of
{'EXIT', _} -> Acc;
D when D > H3MaxGridDistance -> Acc;
_ ->
[A | Acc]
end;
true -> Acc
end
end
end,
[],
maps:to_list(Gateways)).
filter_neighbors(Addr, Score, Neighbors, Gateways, Height, Ledger) ->
Gw = maps:get(Addr, Gateways),
{ok, MinScore} = ?get_var(?min_score, Ledger),
lists:reverse(lists:foldl(
fun(A, Acc) ->
case maps:get(A, Gateways, undefined) of
{G, S} when S >= MinScore ->
[{edge_weight(Addr, Gw, Score, A, G, S, Height, Ledger), A}|Acc];
_ ->
Acc
end
end,
[], Neighbors)).
scale(Index, Res) ->
case h3:get_resolution(Index) of
R when R > Res ->
h3:parent(Index, Res);
_ ->
Index
end.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec edge_weight(A1 :: libp2p_crypto:pubkey_bin(),
Gw1 :: blockchain_ledger_gateway_v2:gateway(),
S1 :: float(),
A2 :: libp2p_crypto:pubkey_bin(),
Gw2 :: blockchain_ledger_gateway_v2:gateway(),
S2 :: float(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> float().
edge_weight(_A1, _Gw1, S1, _A2, _Gw2, S2, _Height, _Ledger) ->
1 - abs(prob_fun(S1) - prob_fun(S2)).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec target(Hash :: binary(),
Ledger :: blockchain_ledger_v1:ledger(), libp2p_crypto:pubkey_bin()) ->
{libp2p_crypto:pubkey_bin(), gateways()} | no_target.
target(Hash, Ledger, Challenger) ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
ActiveGateways = active_gateways(Ledger, Challenger),
ProbsAndGatewayAddrs = create_probs(ActiveGateways, Height, Ledger),
Entropy = entropy(Hash),
{RandVal, _} = rand:uniform_s(Entropy),
case select_target(ProbsAndGatewayAddrs, RandVal) of
{ok, Target} ->
{Target, ActiveGateways};
_ ->
no_target
end.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec create_probs(Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> [{float(), libp2p_crypto:pubkey_bin()}].
create_probs(Gateways, _Height, _Ledger) ->
GwScores = lists:foldl(fun({A, {_G, Score}}, Acc) ->
[{A, prob_fun(Score)} | Acc]
end,
[],
maps:to_list(Gateways)),
Scores = [S || {_A, S} <- GwScores],
LenGwScores = erlang:length(GwScores),
SumGwScores = lists:sum(Scores),
[{prob(Score, LenGwScores, SumGwScores), GwAddr} || {GwAddr, Score} <- GwScores].
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec entropy(Entropy :: binary()) -> rand:state().
entropy(Entropy) ->
<<A:85/integer-unsigned-little, B:85/integer-unsigned-little,
C:86/integer-unsigned-little, _/binary>> = crypto:hash(sha256, Entropy),
rand:seed_s(exs1024s, {A, B, C}).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec active_gateways(blockchain_ledger_v1:ledger(), libp2p_crypto:pubkey_bin()) -> gateways().
active_gateways(Ledger, Challenger) ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
Gateways = blockchain_utils:score_gateways(Ledger),
{ok, MinScore} = ?get_var(?min_score, Ledger),
%% fold over all the gateways
maps:fold(
fun(PubkeyBin, {Gateway, Score}, Acc0) ->
CheckSync = check_sync(Gateway, Ledger),
Mode = blockchain_ledger_gateway_v2:mode(Gateway),
case
%% if we're some other gateway who has a location
%% and hasn't been added to the graph and our score
%% is good enough and we also have the required capability
CheckSync andalso
(PubkeyBin == Challenger orelse
blockchain_ledger_gateway_v2:location(Gateway) == undefined orelse
maps:is_key(PubkeyBin, Acc0) orelse
Score =< MinScore) orelse
not blockchain_ledger_gateway_v2:is_valid_capability(Mode, ?GW_CAPABILITY_POC_CHALLENGEE, Ledger)
of
true ->
Acc0;
false ->
%% build the graph originating at this location
Graph = build_graph_int([PubkeyBin], Gateways, Height, Ledger, #{}),
case maps:size(Graph) > 2 of
false ->
Acc0;
true ->
%% then filter the graph, removing the challenger for some
%% reason. is challenger here the path start?
maps:fold(
fun(Addr, Neighbors, Acc1) ->
Acc2 = case Addr == Challenger of
true ->
Acc1;
false ->
%% if we're not the challenger, add
our full gw information into the acc
maps:put(Addr, maps:get(Addr, Gateways), Acc1)
end,
%% fold over the neighbors, adding them to the
%% list if they're not the challenger
lists:foldl(
fun({_, Neighbor}, Acc3) ->
case Neighbor == Challenger of
true ->
Acc3;
false ->
maps:put(Neighbor, maps:get(Neighbor, Gateways), Acc3)
end
end,
Acc2,
Neighbors
)
end,
Acc0,
Graph
)
end
end
end,
#{},
Gateways
).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
select_target([], _Rnd) ->
no_target;
select_target([{Prob1, GwAddr1}=_Head | _], Rnd) when Rnd - Prob1 < 0 ->
{ok, GwAddr1};
select_target([{Prob1, _GwAddr1} | Tail], Rnd) ->
select_target(Tail, Rnd - Prob1).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec prob(Score :: float(),
LenScores :: pos_integer(),
SumScores :: float()) -> float().
prob(Score, _LenScores, SumScores) ->
Score / SumScores.
%%--------------------------------------------------------------------
@doc An adjustment curve which favors hotspots closer to a score of 0.25 ,
%% when selecting a target
%% @end
%%--------------------------------------------------------------------
prob_fun(Score) when Score =< 0.25 ->
-16 * math:pow((Score - 0.25), 2) + 1;
prob_fun(Score) ->
-1.77 * math:pow((Score - 0.25), 2) + 1.
check_sync(Gateway, Ledger) ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
case ?get_var(?poc_version, Ledger) of
{error, not_found} ->
%% Follow old code path, allow to be challenged
true;
{ok, POCVersion} when POCVersion >= 2 ->
case ?get_var(?poc_challenge_sync_interval, Ledger) of
{error, not_found} ->
%% poc_challenge_sync_interval is not set, allow
true;
{ok, I} ->
case blockchain_ledger_gateway_v2:last_poc_challenge(Gateway) of
undefined ->
%% Ignore
false;
L ->
case (Height - L) =< I of
true ->
%% ledger_height - last_poc_challenge is within our set interval,
allow to participate in poc challenge
true;
false ->
%% Ignore
false
end
end
end
end.
%% ------------------------------------------------------------------
EUNIT Tests
%% ------------------------------------------------------------------
-ifdef(TEST).
-endif.
| null | https://raw.githubusercontent.com/helium/blockchain-core/0caf2295d0576c0ef803258e834bf6ec3b3e74bc/src/poc/blockchain_poc_path.erl | erlang | -------------------------------------------------------------------
@doc
== Blockchain PoC Path ==
@end
-------------------------------------------------------------------
exported for debug purposes
Scale 3.57
Scale: unknown
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
find the longest, highest scoring paths that don't exceed any path limits
paths that are too long are filtered because their score ends up as 0
NOTE: It is possible the path contains dupes, these are also considered valid
NOTE: The tradeoff here is that we may potentially lose target and end
from the path, but the fact that we would still have constructed it should
suffice to build interesting paths which conform to the given path_limit
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
find all the neighbors of address 0
fold over the list of neighbors
if the neighbor address is already in the
graph, skip it.
otherwise, calculate its neighbors
and append all of its neighbor's neighbors?
------------------------------------------------------------------
Internal Function Definitions
------------------------------------------------------------------
nowhere to go
base case
--------------------------------------------------------------------
@doc neighbors iterates through `Gateways` to find any Gateways
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
fold over all the gateways
if we're some other gateway who has a location
and hasn't been added to the graph and our score
is good enough and we also have the required capability
build the graph originating at this location
then filter the graph, removing the challenger for some
reason. is challenger here the path start?
if we're not the challenger, add
fold over the neighbors, adding them to the
list if they're not the challenger
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
when selecting a target
@end
--------------------------------------------------------------------
Follow old code path, allow to be challenged
poc_challenge_sync_interval is not set, allow
Ignore
ledger_height - last_poc_challenge is within our set interval,
Ignore
------------------------------------------------------------------
------------------------------------------------------------------ | -module(blockchain_poc_path).
-include("blockchain_vars.hrl").
-include("blockchain_caps.hrl").
-export([
build/5,
shortest/3, shortest/4,
length/3, length/4,
build_graph/4,
target/3,
neighbors/3,
entropy/1,
check_sync/2,
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
KRing of 1
distance 1.028 miles @ resolution 8
distance 0.38 miles @ resolution 9
KRing of 2
Scale 5.42
distance 1.564 miles @ resolution 8 < ---
distance 0.59 miles @ resolution 9
KRing of 3
distance : unknown , presumably larger than 1.54 miles
-type graph() :: #{any() => [{number(), any()}]}.
-type gateways() :: #{libp2p_crypto:pubkey_bin() => {blockchain_ledger_gateway_v2:gateway(), float()}}.
-export_type([graph/0]).
-spec build(Hash :: binary(),
Target :: binary(),
Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> {ok, list()} | {error, any()}.
build(Hash, Target, Gateways, Height, Ledger) ->
Graph = build_graph_int([Target], Gateways, Height, Ledger, #{}),
GraphList = maps:fold(
fun(Addr, _, Acc) ->
case Addr == Target of
true ->
Acc;
false ->
{_G, Score} = maps:get(Addr, Gateways),
[{Score, Addr}|Acc]
end
end,
[],
Graph
),
case erlang:length(GraphList) >= 2 of
false ->
lager:error("target/gateways ~p", [{Target, Gateways}]),
lager:error("graph: ~p GraphList ~p", [Graph, GraphList]),
{error, not_enough_gateways};
true ->
PathLimit = case ?get_var(?poc_version, Ledger) of
{ok, POCVersion0} when POCVersion0 >= 3 ->
case ?get_var(?poc_path_limit, Ledger) of
{ok, Val0} when is_integer(Val0) ->
we 're only interested in half paths up to
the half total path limit
ceil(Val0/2);
_ ->
infinity
end;
_ ->
infinity
end,
Lengths =
[ {S, G} || {S, G} <- [{Score * ?MODULE:length(Graph, Target, Addr, PathLimit), G}
|| {Score, Addr} = G <- blockchain_utils:shuffle_from_hash(Hash, GraphList)], S > 0 ],
sort the highest scoring paths first
[{_, {_, Start}}, {_, {_, End}}|_] = lists:sort(fun({S1, _}, {S2, _}) -> S1 > S2 end,
Lengths),
{_, Path1} = ?MODULE:shortest(Graph, Start, Target),
{_, [Target|Path2]} = ?MODULE:shortest(Graph, Target, End),
Path3 = Path1 ++ Path2,
case erlang:length(Path3) > 2 of
false ->
lager:error("target/gateways ~p", [{Target, Gateways}]),
lager:error("graph: ~p GraphList ~p", [Graph, GraphList]),
lager:error("path: ~p", [Path3]),
{error, path_too_small};
true ->
blockchain_utils:rand_from_hash(Hash),
Path4 = case rand:uniform(2) of
1 ->
Path3;
2 ->
lists:reverse(Path3)
end,
case ?get_var(?poc_version, Ledger) of
{error, not_found} ->
{ok, Path4};
{ok, POCVersion} when POCVersion >= 2 ->
case ?get_var(?poc_path_limit, Ledger) of
{error, not_found} ->
{ok, Path4};
{ok, Val} ->
{ok, lists:sublist(Path4, Val)}
end
end
end
end.
-spec shortest(Graph :: graph(), Start :: any(), End :: any()) -> {number(), list()}.
shortest(Graph, Start, End) ->
shortest(Graph, Start, End, infinity).
-spec shortest(Graph :: graph(), Start :: any(), End :: any(), Limit :: pos_integer() | 'infinity') -> {number(), list()}.
shortest(Graph, Start, End, Limit) ->
path(Graph, [{0, [Start]}], End, #{}, Limit).
-spec length(Graph :: graph(), Start :: any(), End :: any()) -> integer().
length(Graph, Start, End) ->
length(Graph, Start, End, infinity).
-spec length(Graph :: graph(), Start :: any(), End :: any(), Limit :: pos_integer() | 'infinity') -> integer().
length(Graph, Start, End, Limit) ->
{_Cost, Path} = ?MODULE:shortest(Graph, Start, End, Limit),
erlang:length(Path).
-spec build_graph(Address :: binary(),
Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> graph().
build_graph(Address, Gateways, Height, Ledger) ->
build_graph_int([Address], Gateways, Height, Ledger, #{}).
-spec build_graph_int([binary()],
Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger(),
Graph :: graph()) -> graph().
build_graph_int([], _Gateways, _Height, _Ledger, Graph) ->
Graph;
build_graph_int([Address0|Addresses], Gateways, Height, Ledger, Graph0) ->
case Gateways of
#{Address0 := {Gw0, Score0}} ->
Neighbors0_0 = blockchain_ledger_gateway_v2:neighbors(Gw0),
Neighbors0 = filter_neighbors(Address0, Score0, Neighbors0_0, Gateways, Height, Ledger),
Graph1 = lists:foldl(
fun({_W, Address1}, Acc) ->
case maps:is_key(Address1, Acc) of
true ->
Acc;
false ->
#{Address1 := {Gw1, Score1}} = Gateways,
Neighbors1_0 = blockchain_ledger_gateway_v2:neighbors(Gw1),
Neighbors1 = filter_neighbors(Address1, Score1, Neighbors1_0, Gateways, Height, Ledger),
Graph1 = maps:put(Address1, Neighbors1, Acc),
build_graph_int([A || {_, A} <- Neighbors1,
A /= maps:is_key(A, Graph1)],
Gateways, Height, Ledger, Graph1)
end
end,
first , map address to neighbors
maps:put(Address0, Neighbors0, Graph0),
Neighbors0
),
FilteredAddresses = lists:filter(fun(A) -> not maps:is_key(A, Graph1) end,
Addresses),
build_graph_int(FilteredAddresses, Gateways, Height, Ledger, Graph1);
_ ->
Graph0
end.
-spec path(Graph :: graph(),
Path :: [{number(), list()}],
End :: any(),
Seen :: map(),
Limit :: pos_integer() | 'infinity') -> {number(), list()}.
path(_Graph, [], _End, _Seen, _Limit) ->
{0, []};
path(_Graph, [{Cost, [End | _] = Path} | _], End, _Seen, _Limit) ->
{Cost, lists:reverse(Path)};
path(Graph, [{Cost, [Node | _] = Path} | Routes] = _OldRoutes, End, Seen, Limit) ->
NewRoutes = lists:filter(fun({_, P}) -> length(P) =< Limit end,
[{Cost + NewCost, [NewNode | Path]} || {NewCost, NewNode} <- maps:get(Node, Graph, [{0, []}]), not maps:get(NewNode, Seen, false)]),
NextRoutes = cheapest_to_front(NewRoutes ++ Routes),
path(Graph, NextRoutes, End, Seen#{Node => true}, Limit).
cheapest_to_front([]) -> [];
cheapest_to_front([H | T]) ->
cheapest_to_front(H, T, []).
cheapest_to_front(C, [], Acc) ->
[C | Acc];
cheapest_to_front(C, [H | T], Acc) ->
case C > H of
true ->
cheapest_to_front(H, T, [C | Acc]);
_ ->
cheapest_to_front(C, T, [H | Acc])
end.
that are within max grid distance from the address in pubkeybin
neighbors(PubkeyBin, Gateways, Ledger) when is_binary(PubkeyBin) ->
case maps:get(PubkeyBin, Gateways, undefined) of
undefined ->
{error, bad_gateway};
{Gw, _S} ->
neighbors(Gw, Gateways, Ledger);
Gw ->
neighbors(Gw, Gateways, Ledger)
end;
neighbors(Gw, Gateways, Ledger) ->
GwH3 = blockchain_ledger_gateway_v2:location(Gw),
{ok, H3ExclusionRingDist} = ?get_var(?h3_exclusion_ring_dist, Ledger),
{ok, H3MaxGridDistance} = ?get_var(?h3_max_grid_distance, Ledger),
{ok, H3NeighborRes} = ?get_var(?h3_neighbor_res, Ledger),
ExclusionIndices = h3:k_ring(GwH3, H3ExclusionRingDist),
ScaledGwH3 = h3:parent(GwH3, H3NeighborRes),
lists:foldl(
fun({A, G0}, Acc) ->
G = case G0 of
{G1, _S} ->
G1;
_ ->
G0
end,
Mode = blockchain_ledger_gateway_v2:mode(G),
case {blockchain_ledger_gateway_v2:location(G),
blockchain_ledger_gateway_v2:is_valid_capability(Mode, ?GW_CAPABILITY_POC_CHALLENGEE, Ledger)} of
{undefined, _} -> Acc;
{_, false} -> Acc;
{Index, _} ->
ScaledIndex = scale(Index, H3NeighborRes),
case lists:member(ScaledIndex, ExclusionIndices) of
false ->
case (catch h3:grid_distance(ScaledGwH3, ScaledIndex)) of
{'EXIT', _} -> Acc;
D when D > H3MaxGridDistance -> Acc;
_ ->
[A | Acc]
end;
true -> Acc
end
end
end,
[],
maps:to_list(Gateways)).
filter_neighbors(Addr, Score, Neighbors, Gateways, Height, Ledger) ->
Gw = maps:get(Addr, Gateways),
{ok, MinScore} = ?get_var(?min_score, Ledger),
lists:reverse(lists:foldl(
fun(A, Acc) ->
case maps:get(A, Gateways, undefined) of
{G, S} when S >= MinScore ->
[{edge_weight(Addr, Gw, Score, A, G, S, Height, Ledger), A}|Acc];
_ ->
Acc
end
end,
[], Neighbors)).
scale(Index, Res) ->
case h3:get_resolution(Index) of
R when R > Res ->
h3:parent(Index, Res);
_ ->
Index
end.
-spec edge_weight(A1 :: libp2p_crypto:pubkey_bin(),
Gw1 :: blockchain_ledger_gateway_v2:gateway(),
S1 :: float(),
A2 :: libp2p_crypto:pubkey_bin(),
Gw2 :: blockchain_ledger_gateway_v2:gateway(),
S2 :: float(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> float().
edge_weight(_A1, _Gw1, S1, _A2, _Gw2, S2, _Height, _Ledger) ->
1 - abs(prob_fun(S1) - prob_fun(S2)).
-spec target(Hash :: binary(),
Ledger :: blockchain_ledger_v1:ledger(), libp2p_crypto:pubkey_bin()) ->
{libp2p_crypto:pubkey_bin(), gateways()} | no_target.
target(Hash, Ledger, Challenger) ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
ActiveGateways = active_gateways(Ledger, Challenger),
ProbsAndGatewayAddrs = create_probs(ActiveGateways, Height, Ledger),
Entropy = entropy(Hash),
{RandVal, _} = rand:uniform_s(Entropy),
case select_target(ProbsAndGatewayAddrs, RandVal) of
{ok, Target} ->
{Target, ActiveGateways};
_ ->
no_target
end.
-spec create_probs(Gateways :: gateways(),
Height :: non_neg_integer(),
Ledger :: blockchain_ledger_v1:ledger()) -> [{float(), libp2p_crypto:pubkey_bin()}].
create_probs(Gateways, _Height, _Ledger) ->
GwScores = lists:foldl(fun({A, {_G, Score}}, Acc) ->
[{A, prob_fun(Score)} | Acc]
end,
[],
maps:to_list(Gateways)),
Scores = [S || {_A, S} <- GwScores],
LenGwScores = erlang:length(GwScores),
SumGwScores = lists:sum(Scores),
[{prob(Score, LenGwScores, SumGwScores), GwAddr} || {GwAddr, Score} <- GwScores].
-spec entropy(Entropy :: binary()) -> rand:state().
entropy(Entropy) ->
<<A:85/integer-unsigned-little, B:85/integer-unsigned-little,
C:86/integer-unsigned-little, _/binary>> = crypto:hash(sha256, Entropy),
rand:seed_s(exs1024s, {A, B, C}).
-spec active_gateways(blockchain_ledger_v1:ledger(), libp2p_crypto:pubkey_bin()) -> gateways().
active_gateways(Ledger, Challenger) ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
Gateways = blockchain_utils:score_gateways(Ledger),
{ok, MinScore} = ?get_var(?min_score, Ledger),
maps:fold(
fun(PubkeyBin, {Gateway, Score}, Acc0) ->
CheckSync = check_sync(Gateway, Ledger),
Mode = blockchain_ledger_gateway_v2:mode(Gateway),
case
CheckSync andalso
(PubkeyBin == Challenger orelse
blockchain_ledger_gateway_v2:location(Gateway) == undefined orelse
maps:is_key(PubkeyBin, Acc0) orelse
Score =< MinScore) orelse
not blockchain_ledger_gateway_v2:is_valid_capability(Mode, ?GW_CAPABILITY_POC_CHALLENGEE, Ledger)
of
true ->
Acc0;
false ->
Graph = build_graph_int([PubkeyBin], Gateways, Height, Ledger, #{}),
case maps:size(Graph) > 2 of
false ->
Acc0;
true ->
maps:fold(
fun(Addr, Neighbors, Acc1) ->
Acc2 = case Addr == Challenger of
true ->
Acc1;
false ->
our full gw information into the acc
maps:put(Addr, maps:get(Addr, Gateways), Acc1)
end,
lists:foldl(
fun({_, Neighbor}, Acc3) ->
case Neighbor == Challenger of
true ->
Acc3;
false ->
maps:put(Neighbor, maps:get(Neighbor, Gateways), Acc3)
end
end,
Acc2,
Neighbors
)
end,
Acc0,
Graph
)
end
end
end,
#{},
Gateways
).
select_target([], _Rnd) ->
no_target;
select_target([{Prob1, GwAddr1}=_Head | _], Rnd) when Rnd - Prob1 < 0 ->
{ok, GwAddr1};
select_target([{Prob1, _GwAddr1} | Tail], Rnd) ->
select_target(Tail, Rnd - Prob1).
-spec prob(Score :: float(),
LenScores :: pos_integer(),
SumScores :: float()) -> float().
prob(Score, _LenScores, SumScores) ->
Score / SumScores.
@doc An adjustment curve which favors hotspots closer to a score of 0.25 ,
prob_fun(Score) when Score =< 0.25 ->
-16 * math:pow((Score - 0.25), 2) + 1;
prob_fun(Score) ->
-1.77 * math:pow((Score - 0.25), 2) + 1.
check_sync(Gateway, Ledger) ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
case ?get_var(?poc_version, Ledger) of
{error, not_found} ->
true;
{ok, POCVersion} when POCVersion >= 2 ->
case ?get_var(?poc_challenge_sync_interval, Ledger) of
{error, not_found} ->
true;
{ok, I} ->
case blockchain_ledger_gateway_v2:last_poc_challenge(Gateway) of
undefined ->
false;
L ->
case (Height - L) =< I of
true ->
allow to participate in poc challenge
true;
false ->
false
end
end
end
end.
EUNIT Tests
-ifdef(TEST).
-endif.
|
0727474014f8f92a85b463b94d932116973d2ee4cedc64a4c8437dfe5e7ea3e9 | seantempesta/cljs-react-navigation | externs.clj | (ns externs
(:require [cljs.compiler.api :as compiler]
[cljs.analyzer.api :as analyzer]
[cljs.analyzer :as ana]
[clojure.walk :refer [prewalk]]
[clojure.pprint :refer [pprint]]
[clojure.java.io :as io]
[clojure.string :as str]
[cljs.env :as env]
[clojure.tools.reader :as r]
[clojure.tools.reader.reader-types :refer [string-push-back-reader]]
[cljs.tagged-literals :as tags])
(:import (clojure.lang LineNumberingPushbackReader)))
Idea from
TODO ( NAMESPACE / MODULE.method ... args ) or NAMESPACE / MODULE.field not work
;; For example, (ui/Facebook.logInWithReadPermissionsAsync ...args)
;; or ui/Permissions.REMOTE_NOTIFICATIONS,
;; we already know logInWithReadPermissionsAsync is `invoke' op
;; and REMOTE_NOTIFICATIONS is a property, need to dig deeper to the ast
;; TODO ana/analyze is slow
(defonce cenv (analyzer/empty-state))
(defn compile-project
[src target]
(analyzer/with-state cenv
(compiler/with-core-cljs
(compiler/compile-root src target))))
(defn get-namespaces
[]
(:cljs.analyzer/namespaces @cenv))
(defn get-namespace
([]
(get-namespace ana/*cljs-ns*))
([k]
(get (get-namespaces) k)))
(defn get-alias
[ns]
(apply merge
((juxt :requires :require-macros)
(get-namespace ns))))
(defn print-ast [ast]
(pprint ;; pprint indents output nicely
(prewalk ;; rewrite each node of the ast
(fn [x]
(if (map? x)
(select-keys x [:children :name :form :op]) ;; return selected entries of each map node
x)) ;; non-map nodes are left unchanged
ast)))
(defn get-ns
[s]
(some->>
(re-find #"\(ns[\s]+([^\s]+)" s)
(last)
(symbol)))
(defn read-file
[filename]
(try
(let [form-str (slurp filename)
current-ns (get-ns form-str)
reader (string-push-back-reader form-str)
endof (gensym)]
(binding [r/*read-eval* false
r/*data-readers* tags/*cljs-data-readers*
r/*alias-map* (try
(get-alias (ns-name current-ns))
(catch Exception e
{}))]
(->> #(r/read reader false endof)
(repeatedly)
(take-while #(not= % endof))
(doall))))
(catch Exception e
(println e)
'())))
(defn file-ast
"Return the ClojureScript AST for the contents of filename. Tends to
be large and to contain cycles -- be careful printing at the REPL."
[filename]
(binding [ana/*cljs-ns* 'cljs.user ;; default namespace
ana/*cljs-file* filename]
(mapv
(fn [form]
(try (ana/no-warn (ana/analyze (ana/empty-env) form {:cache-analysis true}))
(catch Exception e
(prn filename e))))
(read-file filename))))
(defn flatten-ast [ast]
(mapcat #(tree-seq :children :children %) ast))
(defn get-interop-used
"Return a set of symbols representing the method and field names
used in interop forms in the given sequence of AST nodes."
[flat-ast]
(keep #(let [ret (and (map? %)
(when-let [sym (some % [:method :field])]
(when-not (str/starts-with? sym "cljs")
sym)))]
(if ret
ret
nil)) flat-ast))
(defn externs-for-interop [syms]
(apply str
"var DummyClass={};\n"
(map #(str "DummyClass." % "=function(){};\n")
syms)))
(defn var-defined?
"Returns true if the given fully-qualified symbol is known by the
ClojureScript compiler to have been defined, based on its mutable set
of namespaces."
[sym]
(contains? (let [ns (get (get-namespaces) (symbol (namespace sym)))]
(merge (:defs ns)
(:macros ns)))
(symbol (name sym))))
(defn get-vars-used
"Return a set of symbols representing all vars used or referenced in
the given sequence of AST nodes."
[requires flat-ast]
(->> flat-ast
(filter #(let [ns (-> % :info :ns)]
(and (= (:op %) :var)
ns
(not= ns 'js))))
(map #(let [sym (-> % :info :name)
sym-namespace (get requires (symbol (namespace sym)))
sym-name (name sym)]
(if sym-namespace
(symbol (str sym-namespace) sym-name)
sym)))))
(defn extern-for-var [[str-namespace symbols]]
(let [symbols-str (->> symbols
(map (fn [sym] (format "%s.%s={};\n" (namespace sym) (name sym))))
(apply str))]
(format "var %s={};\n%s"
str-namespace symbols-str)))
(defn externs-for-vars [grouped-syms]
(apply str (map extern-for-var grouped-syms)))
(defn get-undefined-vars [requires flat-ast]
(->> (get-vars-used requires flat-ast)
(remove var-defined?)))
(defn get-undefined-vars-and-interop-used [file]
(let [ast (file-ast file)
ns-name (:name (first ast))
ns-requires (:requires (first ast))
flat-ast (flatten-ast ast)]
[(get-undefined-vars ns-requires flat-ast)
(get-interop-used flat-ast)]))
;; copy from -externs/blob/master/src/leiningen/externs.clj
(defn cljs-file?
"Returns true if the java.io.File represents a normal Clojurescript source
file."
[^java.io.File file]
(and (.isFile file)
(.endsWith (.getName file) ".cljs")))
(defn get-source-paths [build-type builds]
(or
(when build-type
(:source-paths
(or ((keyword build-type) builds)
(first (filter #(= (name (:id %)) build-type) builds)))))
["src" "cljs"]))
(defn -main
"Generate an externs file"
[]
TODO configurable
(println "Start to generate externs...")
(compile-project (io/file "src") (io/file "target"))
(let [source-paths ["src" "env/prod"]
files (->> source-paths
(map io/file)
(mapcat file-seq)
(filter cljs-file?))
col (apply concat (doall (pmap get-undefined-vars-and-interop-used files)))
vars (->> (take-nth 2 col)
(remove empty?)
(flatten)
(set)
(sort)
(group-by namespace)
;; remove goog dependencies, need to dig deeper(TODO)
(remove (fn [[ns _]] (str/starts-with? ns "goog")))
(externs-for-vars))
interop (->> (take-nth 2 (rest col))
(remove empty?)
(flatten)
(set)
(sort)
(externs-for-interop))
result (str vars interop)]
(spit "js/externs.js" result)
(println "Generated externs to js/externs.js")
prevent jvm hang after this task , maybe Clojurescript uses pmap for parallel compilation .
(shutdown-agents)))
| null | https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/uiexplorer/env/dev/externs.clj | clojure | For example, (ui/Facebook.logInWithReadPermissionsAsync ...args)
or ui/Permissions.REMOTE_NOTIFICATIONS,
we already know logInWithReadPermissionsAsync is `invoke' op
and REMOTE_NOTIFICATIONS is a property, need to dig deeper to the ast
TODO ana/analyze is slow
pprint indents output nicely
rewrite each node of the ast
return selected entries of each map node
non-map nodes are left unchanged
default namespace
copy from -externs/blob/master/src/leiningen/externs.clj
remove goog dependencies, need to dig deeper(TODO) | (ns externs
(:require [cljs.compiler.api :as compiler]
[cljs.analyzer.api :as analyzer]
[cljs.analyzer :as ana]
[clojure.walk :refer [prewalk]]
[clojure.pprint :refer [pprint]]
[clojure.java.io :as io]
[clojure.string :as str]
[cljs.env :as env]
[clojure.tools.reader :as r]
[clojure.tools.reader.reader-types :refer [string-push-back-reader]]
[cljs.tagged-literals :as tags])
(:import (clojure.lang LineNumberingPushbackReader)))
Idea from
TODO ( NAMESPACE / MODULE.method ... args ) or NAMESPACE / MODULE.field not work
(defonce cenv (analyzer/empty-state))
(defn compile-project
[src target]
(analyzer/with-state cenv
(compiler/with-core-cljs
(compiler/compile-root src target))))
(defn get-namespaces
[]
(:cljs.analyzer/namespaces @cenv))
(defn get-namespace
([]
(get-namespace ana/*cljs-ns*))
([k]
(get (get-namespaces) k)))
(defn get-alias
[ns]
(apply merge
((juxt :requires :require-macros)
(get-namespace ns))))
(defn print-ast [ast]
(fn [x]
(if (map? x)
ast)))
(defn get-ns
[s]
(some->>
(re-find #"\(ns[\s]+([^\s]+)" s)
(last)
(symbol)))
(defn read-file
[filename]
(try
(let [form-str (slurp filename)
current-ns (get-ns form-str)
reader (string-push-back-reader form-str)
endof (gensym)]
(binding [r/*read-eval* false
r/*data-readers* tags/*cljs-data-readers*
r/*alias-map* (try
(get-alias (ns-name current-ns))
(catch Exception e
{}))]
(->> #(r/read reader false endof)
(repeatedly)
(take-while #(not= % endof))
(doall))))
(catch Exception e
(println e)
'())))
(defn file-ast
"Return the ClojureScript AST for the contents of filename. Tends to
be large and to contain cycles -- be careful printing at the REPL."
[filename]
ana/*cljs-file* filename]
(mapv
(fn [form]
(try (ana/no-warn (ana/analyze (ana/empty-env) form {:cache-analysis true}))
(catch Exception e
(prn filename e))))
(read-file filename))))
(defn flatten-ast [ast]
(mapcat #(tree-seq :children :children %) ast))
(defn get-interop-used
"Return a set of symbols representing the method and field names
used in interop forms in the given sequence of AST nodes."
[flat-ast]
(keep #(let [ret (and (map? %)
(when-let [sym (some % [:method :field])]
(when-not (str/starts-with? sym "cljs")
sym)))]
(if ret
ret
nil)) flat-ast))
(defn externs-for-interop [syms]
(apply str
"var DummyClass={};\n"
(map #(str "DummyClass." % "=function(){};\n")
syms)))
(defn var-defined?
"Returns true if the given fully-qualified symbol is known by the
ClojureScript compiler to have been defined, based on its mutable set
of namespaces."
[sym]
(contains? (let [ns (get (get-namespaces) (symbol (namespace sym)))]
(merge (:defs ns)
(:macros ns)))
(symbol (name sym))))
(defn get-vars-used
"Return a set of symbols representing all vars used or referenced in
the given sequence of AST nodes."
[requires flat-ast]
(->> flat-ast
(filter #(let [ns (-> % :info :ns)]
(and (= (:op %) :var)
ns
(not= ns 'js))))
(map #(let [sym (-> % :info :name)
sym-namespace (get requires (symbol (namespace sym)))
sym-name (name sym)]
(if sym-namespace
(symbol (str sym-namespace) sym-name)
sym)))))
(defn extern-for-var [[str-namespace symbols]]
(let [symbols-str (->> symbols
(map (fn [sym] (format "%s.%s={};\n" (namespace sym) (name sym))))
(apply str))]
(format "var %s={};\n%s"
str-namespace symbols-str)))
(defn externs-for-vars [grouped-syms]
(apply str (map extern-for-var grouped-syms)))
(defn get-undefined-vars [requires flat-ast]
(->> (get-vars-used requires flat-ast)
(remove var-defined?)))
(defn get-undefined-vars-and-interop-used [file]
(let [ast (file-ast file)
ns-name (:name (first ast))
ns-requires (:requires (first ast))
flat-ast (flatten-ast ast)]
[(get-undefined-vars ns-requires flat-ast)
(get-interop-used flat-ast)]))
(defn cljs-file?
"Returns true if the java.io.File represents a normal Clojurescript source
file."
[^java.io.File file]
(and (.isFile file)
(.endsWith (.getName file) ".cljs")))
(defn get-source-paths [build-type builds]
(or
(when build-type
(:source-paths
(or ((keyword build-type) builds)
(first (filter #(= (name (:id %)) build-type) builds)))))
["src" "cljs"]))
(defn -main
"Generate an externs file"
[]
TODO configurable
(println "Start to generate externs...")
(compile-project (io/file "src") (io/file "target"))
(let [source-paths ["src" "env/prod"]
files (->> source-paths
(map io/file)
(mapcat file-seq)
(filter cljs-file?))
col (apply concat (doall (pmap get-undefined-vars-and-interop-used files)))
vars (->> (take-nth 2 col)
(remove empty?)
(flatten)
(set)
(sort)
(group-by namespace)
(remove (fn [[ns _]] (str/starts-with? ns "goog")))
(externs-for-vars))
interop (->> (take-nth 2 (rest col))
(remove empty?)
(flatten)
(set)
(sort)
(externs-for-interop))
result (str vars interop)]
(spit "js/externs.js" result)
(println "Generated externs to js/externs.js")
prevent jvm hang after this task , maybe Clojurescript uses pmap for parallel compilation .
(shutdown-agents)))
|
e91cb6ef1ff94fdc25053b140dac0e900f4c881149637d2d40f4b7881d21e042 | input-output-hk/plutus | Scoped.hs | module Scoped where
import PlutusCore
data ScKind = ScKiStar
| ScKiFun ScKind ScKind
deriving Show
data ScType = ScTyVar Integer
| ScTyFun ScType ScType
| ScTyPi ScKind ScType
| ScTyLambda ScKind ScType
| ScTyApp ScType ScType
| ScTyCon (SomeTypeIn DefaultUni)
deriving Show
| null | https://raw.githubusercontent.com/input-output-hk/plutus/1f31e640e8a258185db01fa899da63f9018c0e85/plutus-metatheory/src/Scoped.hs | haskell | module Scoped where
import PlutusCore
data ScKind = ScKiStar
| ScKiFun ScKind ScKind
deriving Show
data ScType = ScTyVar Integer
| ScTyFun ScType ScType
| ScTyPi ScKind ScType
| ScTyLambda ScKind ScType
| ScTyApp ScType ScType
| ScTyCon (SomeTypeIn DefaultUni)
deriving Show
| |
71ef83918f8f3fab89b27b8feb791c76d184272e34975474fa33d17923124382 | emqx/emqx | emqx_gateway_http.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
%% @doc Gateway Interface Module for HTTP-APIs
-module(emqx_gateway_http).
-include("include/emqx_gateway.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("emqx/include/emqx_authentication.hrl").
-define(AUTHN, ?EMQX_AUTHENTICATION_CONFIG_ROOT_NAME_ATOM).
-import(emqx_gateway_utils, [listener_id/3]).
Mgmt APIs - gateway
-export([gateways/1]).
Mgmt APIs
-export([
add_listener/2,
remove_listener/1,
update_listener/2
]).
-export([
authn/1,
authn/2,
add_authn/2,
add_authn/3,
update_authn/2,
update_authn/3,
remove_authn/1,
remove_authn/2
]).
Mgmt APIs - clients
-export([
lookup_client/3,
kickout_client/2,
list_client_subscriptions/2,
client_subscribe/4,
client_unsubscribe/3
]).
%% Utils for http, swagger, etc.
-export([
return_http_error/2,
with_gateway/2,
with_authn/2,
with_listener_authn/3,
checks/2,
reason2resp/1,
reason2msg/1,
sum_cluster_connections/1
]).
%% RPC
-export([gateway_status/1, cluster_gateway_status/1]).
-type gateway_summary() ::
#{
name := binary(),
status := running | stopped | unloaded,
created_at => binary(),
started_at => binary(),
stopped_at => binary(),
max_connections => integer(),
current_connections => integer(),
listeners => []
}.
-elvis([
{elvis_style, god_modules, disable},
{elvis_style, no_nested_try_catch, disable},
{elvis_style, invalid_dynamic_call, disable}
]).
-define(DEFAULT_CALL_TIMEOUT, 15000).
%%--------------------------------------------------------------------
Mgmt APIs - gateway
%%--------------------------------------------------------------------
-spec gateways(Status :: all | running | stopped | unloaded) ->
[gateway_summary()].
gateways(Status) ->
Gateways = lists:map(
fun({GwName, _}) ->
case emqx_gateway:lookup(GwName) of
undefined ->
#{name => GwName, status => unloaded};
GwInfo = #{config := Config} ->
GwInfo0 = emqx_gateway_utils:unix_ts_to_rfc3339(
[created_at, started_at, stopped_at],
GwInfo
),
GwInfo1 = maps:with(
[
name,
status,
created_at,
started_at,
stopped_at
],
GwInfo0
),
NodeStatus = cluster_gateway_status(GwName),
{MaxCons, CurrCons} = sum_cluster_connections(NodeStatus),
GwInfo1#{
max_connections => MaxCons,
current_connections => CurrCons,
listeners => get_listeners_status(GwName, Config),
node_status => NodeStatus
}
end
end,
emqx_gateway_registry:list()
),
case Status of
all -> Gateways;
_ -> [Gw || Gw = #{status := S} <- Gateways, S == Status]
end.
gateway_status(GwName) ->
case emqx_gateway:lookup(GwName) of
undefined ->
#{node => node(), status => unloaded};
#{status := Status, config := Config} ->
#{
node => node(),
status => Status,
max_connections => max_connections_count(Config),
current_connections => current_connections_count(GwName)
}
end.
cluster_gateway_status(GwName) ->
Nodes = mria_mnesia:running_nodes(),
case emqx_gateway_http_proto_v1:get_cluster_status(Nodes, GwName) of
{Results, []} ->
Results;
{_, _BadNodes} ->
error(badrpc)
end.
@private
max_connections_count(Config) ->
Listeners = emqx_gateway_utils:normalize_config(Config),
lists:foldl(
fun({_, _, _, SocketOpts, _}, Acc) ->
Acc + proplists:get_value(max_connections, SocketOpts, 0)
end,
0,
Listeners
).
@private
current_connections_count(GwName) ->
try
InfoTab = emqx_gateway_cm:tabname(info, GwName),
ets:info(InfoTab, size)
catch
_:_ ->
0
end.
@private
get_listeners_status(GwName, Config) ->
Listeners = emqx_gateway_utils:normalize_config(Config),
lists:map(
fun({Type, LisName, ListenOn, _, _}) ->
Name0 = listener_id(GwName, Type, LisName),
Name = {Name0, ListenOn},
LisO = #{id => Name0, type => Type, name => LisName},
case catch esockd:listener(Name) of
_Pid when is_pid(_Pid) ->
LisO#{running => true};
_ ->
LisO#{running => false}
end
end,
Listeners
).
%%--------------------------------------------------------------------
Mgmt APIs - listeners
%%--------------------------------------------------------------------
-spec add_listener(atom() | binary(), map()) -> {ok, map()}.
add_listener(ListenerId, NewConf0) ->
{GwName, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
NewConf = maps:without(
[
<<"id">>,
<<"name">>,
<<"type">>,
<<"running">>
],
NewConf0
),
confexp(emqx_gateway_conf:add_listener(GwName, {Type, Name}, NewConf)).
-spec update_listener(atom() | binary(), map()) -> {ok, map()}.
update_listener(ListenerId, NewConf0) ->
{GwName, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
NewConf = maps:without(
[
<<"id">>,
<<"name">>,
<<"type">>,
<<"running">>
],
NewConf0
),
confexp(emqx_gateway_conf:update_listener(GwName, {Type, Name}, NewConf)).
-spec remove_listener(binary()) -> ok.
remove_listener(ListenerId) ->
{GwName, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:remove_listener(GwName, {Type, Name})).
-spec authn(gateway_name()) -> map().
authn(GwName) ->
%% XXX: Need append chain-nanme, authenticator-id?
Path = [gateway, GwName, ?AUTHN],
ChainName = emqx_gateway_utils:global_chain(GwName),
wrap_chain_name(
ChainName,
emqx_map_lib:jsonable_map(emqx:get_raw_config(Path))
).
-spec authn(gateway_name(), binary()) -> map().
authn(GwName, ListenerId) ->
{_, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
Path = [gateway, GwName, listeners, Type, Name, ?AUTHN],
ChainName = emqx_gateway_utils:listener_chain(GwName, Type, Name),
wrap_chain_name(
ChainName,
emqx_map_lib:jsonable_map(emqx:get_raw_config(Path))
).
wrap_chain_name(ChainName, Conf) ->
case emqx_authentication:list_authenticators(ChainName) of
{ok, [#{id := Id} | _]} ->
Conf#{chain_name => ChainName, id => Id};
_ ->
Conf
end.
-spec add_authn(gateway_name(), map()) -> {ok, map()}.
add_authn(GwName, AuthConf) ->
confexp(emqx_gateway_conf:add_authn(GwName, AuthConf)).
-spec add_authn(gateway_name(), binary(), map()) -> {ok, map()}.
add_authn(GwName, ListenerId, AuthConf) ->
{_, LType, LName} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:add_authn(GwName, {LType, LName}, AuthConf)).
-spec update_authn(gateway_name(), map()) -> {ok, map()}.
update_authn(GwName, AuthConf) ->
confexp(emqx_gateway_conf:update_authn(GwName, AuthConf)).
-spec update_authn(gateway_name(), binary(), map()) -> {ok, map()}.
update_authn(GwName, ListenerId, AuthConf) ->
{_, LType, LName} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:update_authn(GwName, {LType, LName}, AuthConf)).
-spec remove_authn(gateway_name()) -> ok.
remove_authn(GwName) ->
confexp(emqx_gateway_conf:remove_authn(GwName)).
-spec remove_authn(gateway_name(), binary()) -> ok.
remove_authn(GwName, ListenerId) ->
{_, LType, LName} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:remove_authn(GwName, {LType, LName})).
confexp(ok) -> ok;
confexp({ok, Res}) -> {ok, Res};
confexp({error, Reason}) -> error(Reason).
%%--------------------------------------------------------------------
Mgmt APIs - clients
%%--------------------------------------------------------------------
-spec lookup_client(
gateway_name(),
emqx_types:clientid(),
{module(), atom()}
) -> list().
lookup_client(GwName, ClientId, {M, F}) ->
[
begin
Info = emqx_gateway_cm:get_chan_info(GwName, ClientId, Pid),
Stats = emqx_gateway_cm:get_chan_stats(GwName, ClientId, Pid),
M:F({{ClientId, Pid}, Info, Stats})
end
|| Pid <- emqx_gateway_cm:lookup_by_clientid(GwName, ClientId)
].
-spec kickout_client(gateway_name(), emqx_types:clientid()) ->
{error, any()}
| ok.
kickout_client(GwName, ClientId) ->
Results = [
emqx_gateway_cm:kick_session(GwName, ClientId, Pid)
|| Pid <- emqx_gateway_cm:lookup_by_clientid(GwName, ClientId)
],
IsOk = lists:any(fun(Item) -> Item =:= ok end, Results),
case {IsOk, Results} of
{true, _} -> ok;
{_, []} -> {error, not_found};
{false, _} -> lists:last(Results)
end.
-spec list_client_subscriptions(gateway_name(), emqx_types:clientid()) ->
{error, any()}
| {ok, list()}.
list_client_subscriptions(GwName, ClientId) ->
case client_call(GwName, ClientId, subscriptions) of
{error, Reason} ->
{error, Reason};
{ok, Subs} ->
{ok,
lists:map(
fun({Topic, SubOpts}) ->
SubOpts#{topic => Topic}
end,
Subs
)}
end.
-spec client_subscribe(
gateway_name(),
emqx_types:clientid(),
emqx_types:topic(),
emqx_types:subopts()
) ->
{error, any()}
| {ok, {emqx_types:topic(), emqx_types:subopts()}}.
client_subscribe(GwName, ClientId, Topic, SubOpts) ->
client_call(GwName, ClientId, {subscribe, Topic, SubOpts}).
-spec client_unsubscribe(
gateway_name(),
emqx_types:clientid(),
emqx_types:topic()
) ->
{error, any()}
| ok.
client_unsubscribe(GwName, ClientId, Topic) ->
client_call(GwName, ClientId, {unsubscribe, Topic}).
client_call(GwName, ClientId, Req) ->
try
emqx_gateway_cm:call(
GwName,
ClientId,
Req,
?DEFAULT_CALL_TIMEOUT
)
of
undefined ->
{error, not_found};
Res ->
Res
catch
throw:noproc ->
{error, not_found};
throw:{badrpc, Reason} ->
{error, {badrpc, Reason}}
end.
%%--------------------------------------------------------------------
Utils
%%--------------------------------------------------------------------
-spec reason2resp({atom(), map()} | any()) -> binary() | any().
reason2resp(R) ->
case reason2msg(R) of
error ->
return_http_error(500, R);
Msg ->
return_http_error(400, Msg)
end.
-spec return_http_error(integer(), any()) -> {integer(), atom(), binary()}.
return_http_error(Code, Msg) ->
{Code, codestr(Code), emqx_gateway_utils:stringfy(Msg)}.
-spec reason2msg({atom(), map()} | any()) -> error | string().
reason2msg({badconf, #{key := Key, value := Value, reason := Reason}}) ->
NValue =
case emqx_json:safe_encode(Value) of
{ok, Str} -> Str;
{error, _} -> emqx_gateway_utils:stringfy(Value)
end,
fmtstr(
"Bad config value '~s' for '~s', reason: ~s",
[NValue, Key, emqx_gateway_utils:stringfy(Reason)]
);
reason2msg(
{badres, #{
resource := gateway,
gateway := GwName,
reason := not_found
}}
) ->
fmtstr("The ~s gateway is unloaded", [GwName]);
reason2msg(
{badres, #{
resource := gateway,
gateway := GwName,
reason := already_exist
}}
) ->
fmtstr("The ~s gateway already loaded", [GwName]);
reason2msg(
{badres, #{
resource := listener,
listener := {GwName, LType, LName},
reason := not_found
}}
) ->
fmtstr("Listener ~s not found", [listener_id(GwName, LType, LName)]);
reason2msg(
{badres, #{
resource := listener,
listener := {GwName, LType, LName},
reason := already_exist
}}
) ->
fmtstr(
"The listener ~s of ~s already exist",
[listener_id(GwName, LType, LName), GwName]
);
reason2msg(
{badres, #{
resource := authn,
gateway := GwName,
reason := not_found
}}
) ->
fmtstr("The authentication not found on ~s", [GwName]);
reason2msg(
{badres, #{
resource := authn,
gateway := GwName,
reason := already_exist
}}
) ->
fmtstr("The authentication already exist on ~s", [GwName]);
reason2msg(
{badres, #{
resource := listener_authn,
listener := {GwName, LType, LName},
reason := not_found
}}
) ->
fmtstr(
"The authentication not found on ~s",
[listener_id(GwName, LType, LName)]
);
reason2msg(
{badres, #{
resource := listener_authn,
listener := {GwName, LType, LName},
reason := already_exist
}}
) ->
fmtstr(
"The authentication already exist on ~s",
[listener_id(GwName, LType, LName)]
);
reason2msg(
{bad_ssl_config, #{
reason := Reason,
which_options := Options
}}
) ->
fmtstr("Bad TLS configuration for ~p, reason: ~s", [Options, Reason]);
reason2msg(
{#{roots := [{gateway, _}]}, [_ | _]} = Error
) ->
Bin = emqx_misc:readable_error_msg(Error),
<<"Invalid configurations: ", Bin/binary>>;
reason2msg(_) ->
error.
codestr(400) -> 'BAD_REQUEST';
codestr(404) -> 'RESOURCE_NOT_FOUND';
codestr(405) -> 'METHOD_NOT_ALLOWED';
codestr(409) -> 'NOT_SUPPORT';
codestr(500) -> 'UNKNOW_ERROR';
codestr(501) -> 'NOT_IMPLEMENTED'.
fmtstr(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
-spec with_authn(binary(), function()) -> any().
with_authn(GwName0, Fun) ->
with_gateway(GwName0, fun(GwName, _GwConf) ->
Authn = emqx_gateway_http:authn(GwName),
Fun(GwName, Authn)
end).
-spec with_listener_authn(binary(), binary(), function()) -> any().
with_listener_authn(GwName0, Id, Fun) ->
with_gateway(GwName0, fun(GwName, _GwConf) ->
Authn = emqx_gateway_http:authn(GwName, Id),
Fun(GwName, Authn)
end).
-spec with_gateway(binary(), function()) -> any().
with_gateway(GwName0, Fun) ->
try
GwName =
try
binary_to_existing_atom(GwName0)
catch
_:_ -> error(badname)
end,
case emqx_gateway:lookup(GwName) of
undefined ->
return_http_error(404, "Gateway not loaded");
Gateway ->
Fun(GwName, Gateway)
end
catch
error:badname ->
return_http_error(404, "Bad gateway name");
%% Exceptions from: checks/2
error:{miss_param, K} ->
return_http_error(400, [K, " is required"]);
%% Exceptions from emqx_gateway_utils:parse_listener_id/1
error:{invalid_listener_id, Id} ->
return_http_error(400, ["Invalid listener id: ", Id]);
%% Exceptions from emqx:get_config/1
error:{config_not_found, Path0} ->
Path = lists:concat(
lists:join(".", lists:map(fun to_list/1, Path0))
),
return_http_error(404, "Resource not found. path: " ++ Path);
error:{badmatch, {error, einval}} ->
return_http_error(400, "Invalid bind address");
error:{badauth, Reason} ->
Reason1 = emqx_gateway_utils:stringfy(Reason),
return_http_error(400, ["Bad authentication config: ", Reason1]);
Class:Reason:Stk ->
?SLOG(error, #{
msg => "uncaught_exception",
exception => Class,
reason => Reason,
stacktrace => Stk
}),
reason2resp(Reason)
end.
-spec checks(list(), map()) -> ok.
checks([], _) ->
ok;
checks([K | Ks], Map) ->
case maps:is_key(K, Map) of
true -> checks(Ks, Map);
false -> error({miss_param, K})
end.
to_list(A) when is_atom(A) ->
atom_to_list(A);
to_list(B) when is_binary(B) ->
binary_to_list(B).
sum_cluster_connections(List) ->
sum_cluster_connections(List, 0, 0).
%%--------------------------------------------------------------------
Internal funcs
sum_cluster_connections(
[#{max_connections := Max, current_connections := Current} | T], MaxAcc, CurrAcc
) ->
sum_cluster_connections(T, MaxAcc + Max, Current + CurrAcc);
sum_cluster_connections([_ | T], MaxAcc, CurrAcc) ->
sum_cluster_connections(T, MaxAcc, CurrAcc);
sum_cluster_connections([], MaxAcc, CurrAcc) ->
{MaxAcc, CurrAcc}.
| null | https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_gateway/src/emqx_gateway_http.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
@doc Gateway Interface Module for HTTP-APIs
Utils for http, swagger, etc.
RPC
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
XXX: Need append chain-nanme, authenticator-id?
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Exceptions from: checks/2
Exceptions from emqx_gateway_utils:parse_listener_id/1
Exceptions from emqx:get_config/1
-------------------------------------------------------------------- | Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_gateway_http).
-include("include/emqx_gateway.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("emqx/include/emqx_authentication.hrl").
-define(AUTHN, ?EMQX_AUTHENTICATION_CONFIG_ROOT_NAME_ATOM).
-import(emqx_gateway_utils, [listener_id/3]).
Mgmt APIs - gateway
-export([gateways/1]).
Mgmt APIs
-export([
add_listener/2,
remove_listener/1,
update_listener/2
]).
-export([
authn/1,
authn/2,
add_authn/2,
add_authn/3,
update_authn/2,
update_authn/3,
remove_authn/1,
remove_authn/2
]).
Mgmt APIs - clients
-export([
lookup_client/3,
kickout_client/2,
list_client_subscriptions/2,
client_subscribe/4,
client_unsubscribe/3
]).
-export([
return_http_error/2,
with_gateway/2,
with_authn/2,
with_listener_authn/3,
checks/2,
reason2resp/1,
reason2msg/1,
sum_cluster_connections/1
]).
-export([gateway_status/1, cluster_gateway_status/1]).
-type gateway_summary() ::
#{
name := binary(),
status := running | stopped | unloaded,
created_at => binary(),
started_at => binary(),
stopped_at => binary(),
max_connections => integer(),
current_connections => integer(),
listeners => []
}.
-elvis([
{elvis_style, god_modules, disable},
{elvis_style, no_nested_try_catch, disable},
{elvis_style, invalid_dynamic_call, disable}
]).
-define(DEFAULT_CALL_TIMEOUT, 15000).
Mgmt APIs - gateway
-spec gateways(Status :: all | running | stopped | unloaded) ->
[gateway_summary()].
gateways(Status) ->
Gateways = lists:map(
fun({GwName, _}) ->
case emqx_gateway:lookup(GwName) of
undefined ->
#{name => GwName, status => unloaded};
GwInfo = #{config := Config} ->
GwInfo0 = emqx_gateway_utils:unix_ts_to_rfc3339(
[created_at, started_at, stopped_at],
GwInfo
),
GwInfo1 = maps:with(
[
name,
status,
created_at,
started_at,
stopped_at
],
GwInfo0
),
NodeStatus = cluster_gateway_status(GwName),
{MaxCons, CurrCons} = sum_cluster_connections(NodeStatus),
GwInfo1#{
max_connections => MaxCons,
current_connections => CurrCons,
listeners => get_listeners_status(GwName, Config),
node_status => NodeStatus
}
end
end,
emqx_gateway_registry:list()
),
case Status of
all -> Gateways;
_ -> [Gw || Gw = #{status := S} <- Gateways, S == Status]
end.
gateway_status(GwName) ->
case emqx_gateway:lookup(GwName) of
undefined ->
#{node => node(), status => unloaded};
#{status := Status, config := Config} ->
#{
node => node(),
status => Status,
max_connections => max_connections_count(Config),
current_connections => current_connections_count(GwName)
}
end.
cluster_gateway_status(GwName) ->
Nodes = mria_mnesia:running_nodes(),
case emqx_gateway_http_proto_v1:get_cluster_status(Nodes, GwName) of
{Results, []} ->
Results;
{_, _BadNodes} ->
error(badrpc)
end.
@private
max_connections_count(Config) ->
Listeners = emqx_gateway_utils:normalize_config(Config),
lists:foldl(
fun({_, _, _, SocketOpts, _}, Acc) ->
Acc + proplists:get_value(max_connections, SocketOpts, 0)
end,
0,
Listeners
).
@private
current_connections_count(GwName) ->
try
InfoTab = emqx_gateway_cm:tabname(info, GwName),
ets:info(InfoTab, size)
catch
_:_ ->
0
end.
@private
get_listeners_status(GwName, Config) ->
Listeners = emqx_gateway_utils:normalize_config(Config),
lists:map(
fun({Type, LisName, ListenOn, _, _}) ->
Name0 = listener_id(GwName, Type, LisName),
Name = {Name0, ListenOn},
LisO = #{id => Name0, type => Type, name => LisName},
case catch esockd:listener(Name) of
_Pid when is_pid(_Pid) ->
LisO#{running => true};
_ ->
LisO#{running => false}
end
end,
Listeners
).
Mgmt APIs - listeners
-spec add_listener(atom() | binary(), map()) -> {ok, map()}.
add_listener(ListenerId, NewConf0) ->
{GwName, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
NewConf = maps:without(
[
<<"id">>,
<<"name">>,
<<"type">>,
<<"running">>
],
NewConf0
),
confexp(emqx_gateway_conf:add_listener(GwName, {Type, Name}, NewConf)).
-spec update_listener(atom() | binary(), map()) -> {ok, map()}.
update_listener(ListenerId, NewConf0) ->
{GwName, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
NewConf = maps:without(
[
<<"id">>,
<<"name">>,
<<"type">>,
<<"running">>
],
NewConf0
),
confexp(emqx_gateway_conf:update_listener(GwName, {Type, Name}, NewConf)).
-spec remove_listener(binary()) -> ok.
remove_listener(ListenerId) ->
{GwName, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:remove_listener(GwName, {Type, Name})).
-spec authn(gateway_name()) -> map().
authn(GwName) ->
Path = [gateway, GwName, ?AUTHN],
ChainName = emqx_gateway_utils:global_chain(GwName),
wrap_chain_name(
ChainName,
emqx_map_lib:jsonable_map(emqx:get_raw_config(Path))
).
-spec authn(gateway_name(), binary()) -> map().
authn(GwName, ListenerId) ->
{_, Type, Name} = emqx_gateway_utils:parse_listener_id(ListenerId),
Path = [gateway, GwName, listeners, Type, Name, ?AUTHN],
ChainName = emqx_gateway_utils:listener_chain(GwName, Type, Name),
wrap_chain_name(
ChainName,
emqx_map_lib:jsonable_map(emqx:get_raw_config(Path))
).
wrap_chain_name(ChainName, Conf) ->
case emqx_authentication:list_authenticators(ChainName) of
{ok, [#{id := Id} | _]} ->
Conf#{chain_name => ChainName, id => Id};
_ ->
Conf
end.
-spec add_authn(gateway_name(), map()) -> {ok, map()}.
add_authn(GwName, AuthConf) ->
confexp(emqx_gateway_conf:add_authn(GwName, AuthConf)).
-spec add_authn(gateway_name(), binary(), map()) -> {ok, map()}.
add_authn(GwName, ListenerId, AuthConf) ->
{_, LType, LName} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:add_authn(GwName, {LType, LName}, AuthConf)).
-spec update_authn(gateway_name(), map()) -> {ok, map()}.
update_authn(GwName, AuthConf) ->
confexp(emqx_gateway_conf:update_authn(GwName, AuthConf)).
-spec update_authn(gateway_name(), binary(), map()) -> {ok, map()}.
update_authn(GwName, ListenerId, AuthConf) ->
{_, LType, LName} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:update_authn(GwName, {LType, LName}, AuthConf)).
-spec remove_authn(gateway_name()) -> ok.
remove_authn(GwName) ->
confexp(emqx_gateway_conf:remove_authn(GwName)).
-spec remove_authn(gateway_name(), binary()) -> ok.
remove_authn(GwName, ListenerId) ->
{_, LType, LName} = emqx_gateway_utils:parse_listener_id(ListenerId),
confexp(emqx_gateway_conf:remove_authn(GwName, {LType, LName})).
confexp(ok) -> ok;
confexp({ok, Res}) -> {ok, Res};
confexp({error, Reason}) -> error(Reason).
Mgmt APIs - clients
-spec lookup_client(
gateway_name(),
emqx_types:clientid(),
{module(), atom()}
) -> list().
lookup_client(GwName, ClientId, {M, F}) ->
[
begin
Info = emqx_gateway_cm:get_chan_info(GwName, ClientId, Pid),
Stats = emqx_gateway_cm:get_chan_stats(GwName, ClientId, Pid),
M:F({{ClientId, Pid}, Info, Stats})
end
|| Pid <- emqx_gateway_cm:lookup_by_clientid(GwName, ClientId)
].
-spec kickout_client(gateway_name(), emqx_types:clientid()) ->
{error, any()}
| ok.
kickout_client(GwName, ClientId) ->
Results = [
emqx_gateway_cm:kick_session(GwName, ClientId, Pid)
|| Pid <- emqx_gateway_cm:lookup_by_clientid(GwName, ClientId)
],
IsOk = lists:any(fun(Item) -> Item =:= ok end, Results),
case {IsOk, Results} of
{true, _} -> ok;
{_, []} -> {error, not_found};
{false, _} -> lists:last(Results)
end.
-spec list_client_subscriptions(gateway_name(), emqx_types:clientid()) ->
{error, any()}
| {ok, list()}.
list_client_subscriptions(GwName, ClientId) ->
case client_call(GwName, ClientId, subscriptions) of
{error, Reason} ->
{error, Reason};
{ok, Subs} ->
{ok,
lists:map(
fun({Topic, SubOpts}) ->
SubOpts#{topic => Topic}
end,
Subs
)}
end.
-spec client_subscribe(
gateway_name(),
emqx_types:clientid(),
emqx_types:topic(),
emqx_types:subopts()
) ->
{error, any()}
| {ok, {emqx_types:topic(), emqx_types:subopts()}}.
client_subscribe(GwName, ClientId, Topic, SubOpts) ->
client_call(GwName, ClientId, {subscribe, Topic, SubOpts}).
-spec client_unsubscribe(
gateway_name(),
emqx_types:clientid(),
emqx_types:topic()
) ->
{error, any()}
| ok.
client_unsubscribe(GwName, ClientId, Topic) ->
client_call(GwName, ClientId, {unsubscribe, Topic}).
client_call(GwName, ClientId, Req) ->
try
emqx_gateway_cm:call(
GwName,
ClientId,
Req,
?DEFAULT_CALL_TIMEOUT
)
of
undefined ->
{error, not_found};
Res ->
Res
catch
throw:noproc ->
{error, not_found};
throw:{badrpc, Reason} ->
{error, {badrpc, Reason}}
end.
Utils
-spec reason2resp({atom(), map()} | any()) -> binary() | any().
reason2resp(R) ->
case reason2msg(R) of
error ->
return_http_error(500, R);
Msg ->
return_http_error(400, Msg)
end.
-spec return_http_error(integer(), any()) -> {integer(), atom(), binary()}.
return_http_error(Code, Msg) ->
{Code, codestr(Code), emqx_gateway_utils:stringfy(Msg)}.
-spec reason2msg({atom(), map()} | any()) -> error | string().
reason2msg({badconf, #{key := Key, value := Value, reason := Reason}}) ->
NValue =
case emqx_json:safe_encode(Value) of
{ok, Str} -> Str;
{error, _} -> emqx_gateway_utils:stringfy(Value)
end,
fmtstr(
"Bad config value '~s' for '~s', reason: ~s",
[NValue, Key, emqx_gateway_utils:stringfy(Reason)]
);
reason2msg(
{badres, #{
resource := gateway,
gateway := GwName,
reason := not_found
}}
) ->
fmtstr("The ~s gateway is unloaded", [GwName]);
reason2msg(
{badres, #{
resource := gateway,
gateway := GwName,
reason := already_exist
}}
) ->
fmtstr("The ~s gateway already loaded", [GwName]);
reason2msg(
{badres, #{
resource := listener,
listener := {GwName, LType, LName},
reason := not_found
}}
) ->
fmtstr("Listener ~s not found", [listener_id(GwName, LType, LName)]);
reason2msg(
{badres, #{
resource := listener,
listener := {GwName, LType, LName},
reason := already_exist
}}
) ->
fmtstr(
"The listener ~s of ~s already exist",
[listener_id(GwName, LType, LName), GwName]
);
reason2msg(
{badres, #{
resource := authn,
gateway := GwName,
reason := not_found
}}
) ->
fmtstr("The authentication not found on ~s", [GwName]);
reason2msg(
{badres, #{
resource := authn,
gateway := GwName,
reason := already_exist
}}
) ->
fmtstr("The authentication already exist on ~s", [GwName]);
reason2msg(
{badres, #{
resource := listener_authn,
listener := {GwName, LType, LName},
reason := not_found
}}
) ->
fmtstr(
"The authentication not found on ~s",
[listener_id(GwName, LType, LName)]
);
reason2msg(
{badres, #{
resource := listener_authn,
listener := {GwName, LType, LName},
reason := already_exist
}}
) ->
fmtstr(
"The authentication already exist on ~s",
[listener_id(GwName, LType, LName)]
);
reason2msg(
{bad_ssl_config, #{
reason := Reason,
which_options := Options
}}
) ->
fmtstr("Bad TLS configuration for ~p, reason: ~s", [Options, Reason]);
reason2msg(
{#{roots := [{gateway, _}]}, [_ | _]} = Error
) ->
Bin = emqx_misc:readable_error_msg(Error),
<<"Invalid configurations: ", Bin/binary>>;
reason2msg(_) ->
error.
codestr(400) -> 'BAD_REQUEST';
codestr(404) -> 'RESOURCE_NOT_FOUND';
codestr(405) -> 'METHOD_NOT_ALLOWED';
codestr(409) -> 'NOT_SUPPORT';
codestr(500) -> 'UNKNOW_ERROR';
codestr(501) -> 'NOT_IMPLEMENTED'.
fmtstr(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
-spec with_authn(binary(), function()) -> any().
with_authn(GwName0, Fun) ->
with_gateway(GwName0, fun(GwName, _GwConf) ->
Authn = emqx_gateway_http:authn(GwName),
Fun(GwName, Authn)
end).
-spec with_listener_authn(binary(), binary(), function()) -> any().
with_listener_authn(GwName0, Id, Fun) ->
with_gateway(GwName0, fun(GwName, _GwConf) ->
Authn = emqx_gateway_http:authn(GwName, Id),
Fun(GwName, Authn)
end).
-spec with_gateway(binary(), function()) -> any().
with_gateway(GwName0, Fun) ->
try
GwName =
try
binary_to_existing_atom(GwName0)
catch
_:_ -> error(badname)
end,
case emqx_gateway:lookup(GwName) of
undefined ->
return_http_error(404, "Gateway not loaded");
Gateway ->
Fun(GwName, Gateway)
end
catch
error:badname ->
return_http_error(404, "Bad gateway name");
error:{miss_param, K} ->
return_http_error(400, [K, " is required"]);
error:{invalid_listener_id, Id} ->
return_http_error(400, ["Invalid listener id: ", Id]);
error:{config_not_found, Path0} ->
Path = lists:concat(
lists:join(".", lists:map(fun to_list/1, Path0))
),
return_http_error(404, "Resource not found. path: " ++ Path);
error:{badmatch, {error, einval}} ->
return_http_error(400, "Invalid bind address");
error:{badauth, Reason} ->
Reason1 = emqx_gateway_utils:stringfy(Reason),
return_http_error(400, ["Bad authentication config: ", Reason1]);
Class:Reason:Stk ->
?SLOG(error, #{
msg => "uncaught_exception",
exception => Class,
reason => Reason,
stacktrace => Stk
}),
reason2resp(Reason)
end.
-spec checks(list(), map()) -> ok.
checks([], _) ->
ok;
checks([K | Ks], Map) ->
case maps:is_key(K, Map) of
true -> checks(Ks, Map);
false -> error({miss_param, K})
end.
to_list(A) when is_atom(A) ->
atom_to_list(A);
to_list(B) when is_binary(B) ->
binary_to_list(B).
sum_cluster_connections(List) ->
sum_cluster_connections(List, 0, 0).
Internal funcs
sum_cluster_connections(
[#{max_connections := Max, current_connections := Current} | T], MaxAcc, CurrAcc
) ->
sum_cluster_connections(T, MaxAcc + Max, Current + CurrAcc);
sum_cluster_connections([_ | T], MaxAcc, CurrAcc) ->
sum_cluster_connections(T, MaxAcc, CurrAcc);
sum_cluster_connections([], MaxAcc, CurrAcc) ->
{MaxAcc, CurrAcc}.
|
b0e81bf3340bfe34005ca89fe7e478750d6d9e8bbd7e911829b87358ab1a9ea3 | iburzynski/EMURGO_71 | Reader.hs | # LANGUAGE InstanceSigs #
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Use const" #-}
{-# HLINT ignore "Avoid lambda" #-}
# HLINT ignore " Use i d " #
import Data.Char ( toUpper )
* * * Part 2 - the Reader Monad : simulating a read - only global variable ( constant ) * * *
-- Reference: -07-19-deriving-reader-monad.html
-- We want our program to have some kind of global runtime config:
-- * i.e. using different database connection strings depending on deployment environment
We could use the State monad , but would prefer the config be read - only ( set once at runtime )
-- Example: for some reason we're doing an A/B test where we exclude the letter E or L
We define ABConfig as a product type with two Bool fields indicating whether each test is active :
data ABConfig = ABConfig
{ noEs :: Bool
, noLs :: Bool
}
-- We could add the config as an extra parameter to all our functions and pass it downward:
toUpperStr :: ABConfig -> String -> String
-- convert the string to uppercase and keep only characters that pass all the filter predicates
toUpperStr cfg str = filter passesAll (map toUpper str)
where
-- check if a character satisfies all the predicates in a list
passesAll :: Char -> Bool
passesAll char = all (\pred -> pred char) preds
-- ex. on 'E' with `noEs` test enabled:
-- passesAll 'E' => all [('E' /= 'E'), ('E' /= 'L')] => all [False, True] => False
-- create a list of predicate functions to filter with:
preds :: [Char -> Bool]
preds =
[ if noEs cfg then (/= 'E') else const True
-- ^ the predicate always returns True if the test is disabled
, if noLs cfg then (/= 'L') else const True
]
Any function that calls ` toUpperStr ` needs to pass the ABConfig value downward :
welcomeMessage :: ABConfig -> String -> String -> String
welcomeMessage cfg msg username = concat [
"Welcome, "
, toUpperStr cfg username
, "! Message of the day: "
, toUpperStr cfg msg
]
type FirstName = String
type NickName = String
type LastName = String
fullName :: ABConfig -> FirstName -> NickName -> LastName -> String
fullName cfg fn nn ln = concat [
toUpperStr cfg fn
, " \""
, toUpperStr cfg nn
, "\" "
, toUpperStr cfg ln
]
-- This solution is annoying: we need to manually pass our "global" through every single function
Many of them may do nothing with the ABConfig data themselves ...
-- but still need it as a parameter so they can pass it on to functions that do!
-- We're also increasing surface area for possible errors:
-- * i.e. mixing up parameter order if the "global" has the same type as another parameter
-- The core of a configurable function is one that takes in a config and produces a value.
-- We can abstract this into its own type, which we'll call Reader:
newtype Reader c a = Reader { runReader :: c -> a }
-- If we squint a little, we'll notice this type is essentially just a generic function (a -> b)
-- If we make it a monad, we can abstract away the config variable into the monadic context
-- This way we can chain configurable functions together using (>>=) and ignore the config parameter
toUpperStrM :: String -> Reader ABConfig String
toUpperStrM str = Reader (\cfg ->
let
passesAll char = all (\pred -> pred char) preds
preds =
[ if noEs cfg then (/= 'E') else const True
, if noLs cfg then (/= 'L') else const True
]
in
filter passesAll (map toUpper str))
Same function as before , but the ABConfig parameter has been moved into the Reader value
welcomeMessageM :: String -> String -> Reader ABConfig String
welcomeMessageM msg username =
Now we can pass the ABConfig implicitly via ( > > =) , only working with the Strings in the Readers
toUpperStrM msg >>= (\upperMsg ->
toUpperStrM username >>= (\upperUsername ->
Reader (\_ ->
-- ^ we don't do anything with the config value, so we can use a wildcard placeholder
concat [ "Welcome, "
, upperUsername
, "! Message of the day: "
, upperMsg
])))
fullNameM :: FirstName -> NickName -> LastName -> Reader ABConfig String
fullNameM fn nn ln =
toUpperStrM fn >>= (\upperFN ->
toUpperStrM nn >>= (\upperNN ->
toUpperStrM ln >>= (\upperLN ->
Reader (\_ -> concat [ upperFN
, " \""
, upperNN
, "\" "
, upperLN
]))))
instance Functor (Reader g) where
fmap :: (a -> b) -> Reader c a -> Reader c b
fmap ab (Reader ca) = Reader (\c -> ab $ ca c)
-- same as: Reader (ab . ca)
instance Applicative (Reader c) where
pure :: a -> Reader c a
pure a = Reader (\c -> a)
-- same as: Reader $ const a
(<*>) :: Reader c (a -> b) -> Reader c a -> Reader c b
Reader cab <*> Reader ca = Reader (\c -> cab c (ca c))
instance Monad (Reader g) where
(>>=) :: Reader c a -> (a -> Reader c b) -> Reader c b
Reader ca >>= aRcb = Reader (\c -> runReader (aRcb (ca c)) c)
-- Since we abstracted over the config parameter, we no longer have a way to access it
-- (it has become part of the monadic context)
-- But some functions like `toUpperStr` need to inspect the config
-- We can solve this by implementing a utility function to get the config value:
ask :: Reader c c
ask = Reader (\c -> c)
-- same as: Reader id
` ask ` duplicates the config value from Reader 's first type parameter to its second type parameter
-- This way it can be accessed outside the monadic context
-- We can also define a utility function to transform the config:
asks :: (c -> a) -> Reader c a
asks ca = Reader (\c -> ca c)
-- same as: Reader ca
-- With these utility functions, we can refactor our functions again using do-notation:
toUpperStr' :: String -> Reader ABConfig String
toUpperStr' str = do
cfg <- ask -- get the config value from the Reader context
let
preds =
[ if noEs cfg then (/= 'E') else const True
, if noLs cfg then (/= 'L') else const True
]
passesAll c = all (\pred -> pred c) preds
pure . filter passesAll . map toUpper $ str
welcomeMessage' :: String -> String -> Reader ABConfig String
welcomeMessage' msg username = do
upperMsg <- toUpperStr' msg
upperUsername <- toUpperStr' username
pure $ concat [ "Welcome, "
, upperUsername
, "! Message of the day: "
, upperMsg
]
fullName' :: FirstName -> NickName -> LastName -> Reader ABConfig String
fullName' fn nn ln = do
upperFN <- toUpperStr' fn
upperNN <- toUpperStr' nn
upperLN <- toUpperStr' ln
pure $ concat [ upperFN
, " \""
, upperNN
, "\" "
, upperLN
]
-- Bonus: we can run a sub-function as if it is using a different config, like a "local environment"
-- The environment reverts once we return to the current function.
local :: (c -> l) -> Reader l a -> Reader c a
-- ^ function that transforms global config to a local config
-- ^ a Reader that uses the local config
-- ^ returns a Reader with the original config restored
local cl (Reader la) = Reader (\c -> la (cl c))
-- same as: Reader (la . cl) | null | https://raw.githubusercontent.com/iburzynski/EMURGO_71/b273f43967efd8d81d6f02695e7ccf37686b15c0/Monads/Reader.hs | haskell | # OPTIONS_GHC -Wno-unrecognised-pragmas #
# HLINT ignore "Use const" #
# HLINT ignore "Avoid lambda" #
Reference: -07-19-deriving-reader-monad.html
We want our program to have some kind of global runtime config:
* i.e. using different database connection strings depending on deployment environment
Example: for some reason we're doing an A/B test where we exclude the letter E or L
We could add the config as an extra parameter to all our functions and pass it downward:
convert the string to uppercase and keep only characters that pass all the filter predicates
check if a character satisfies all the predicates in a list
ex. on 'E' with `noEs` test enabled:
passesAll 'E' => all [('E' /= 'E'), ('E' /= 'L')] => all [False, True] => False
create a list of predicate functions to filter with:
^ the predicate always returns True if the test is disabled
This solution is annoying: we need to manually pass our "global" through every single function
but still need it as a parameter so they can pass it on to functions that do!
We're also increasing surface area for possible errors:
* i.e. mixing up parameter order if the "global" has the same type as another parameter
The core of a configurable function is one that takes in a config and produces a value.
We can abstract this into its own type, which we'll call Reader:
If we squint a little, we'll notice this type is essentially just a generic function (a -> b)
If we make it a monad, we can abstract away the config variable into the monadic context
This way we can chain configurable functions together using (>>=) and ignore the config parameter
^ we don't do anything with the config value, so we can use a wildcard placeholder
same as: Reader (ab . ca)
same as: Reader $ const a
Since we abstracted over the config parameter, we no longer have a way to access it
(it has become part of the monadic context)
But some functions like `toUpperStr` need to inspect the config
We can solve this by implementing a utility function to get the config value:
same as: Reader id
This way it can be accessed outside the monadic context
We can also define a utility function to transform the config:
same as: Reader ca
With these utility functions, we can refactor our functions again using do-notation:
get the config value from the Reader context
Bonus: we can run a sub-function as if it is using a different config, like a "local environment"
The environment reverts once we return to the current function.
^ function that transforms global config to a local config
^ a Reader that uses the local config
^ returns a Reader with the original config restored
same as: Reader (la . cl) | # LANGUAGE InstanceSigs #
# HLINT ignore " Use i d " #
import Data.Char ( toUpper )
* * * Part 2 - the Reader Monad : simulating a read - only global variable ( constant ) * * *
We could use the State monad , but would prefer the config be read - only ( set once at runtime )
We define ABConfig as a product type with two Bool fields indicating whether each test is active :
data ABConfig = ABConfig
{ noEs :: Bool
, noLs :: Bool
}
toUpperStr :: ABConfig -> String -> String
toUpperStr cfg str = filter passesAll (map toUpper str)
where
passesAll :: Char -> Bool
passesAll char = all (\pred -> pred char) preds
preds :: [Char -> Bool]
preds =
[ if noEs cfg then (/= 'E') else const True
, if noLs cfg then (/= 'L') else const True
]
Any function that calls ` toUpperStr ` needs to pass the ABConfig value downward :
welcomeMessage :: ABConfig -> String -> String -> String
welcomeMessage cfg msg username = concat [
"Welcome, "
, toUpperStr cfg username
, "! Message of the day: "
, toUpperStr cfg msg
]
type FirstName = String
type NickName = String
type LastName = String
fullName :: ABConfig -> FirstName -> NickName -> LastName -> String
fullName cfg fn nn ln = concat [
toUpperStr cfg fn
, " \""
, toUpperStr cfg nn
, "\" "
, toUpperStr cfg ln
]
Many of them may do nothing with the ABConfig data themselves ...
newtype Reader c a = Reader { runReader :: c -> a }
toUpperStrM :: String -> Reader ABConfig String
toUpperStrM str = Reader (\cfg ->
let
passesAll char = all (\pred -> pred char) preds
preds =
[ if noEs cfg then (/= 'E') else const True
, if noLs cfg then (/= 'L') else const True
]
in
filter passesAll (map toUpper str))
Same function as before , but the ABConfig parameter has been moved into the Reader value
welcomeMessageM :: String -> String -> Reader ABConfig String
welcomeMessageM msg username =
Now we can pass the ABConfig implicitly via ( > > =) , only working with the Strings in the Readers
toUpperStrM msg >>= (\upperMsg ->
toUpperStrM username >>= (\upperUsername ->
Reader (\_ ->
concat [ "Welcome, "
, upperUsername
, "! Message of the day: "
, upperMsg
])))
fullNameM :: FirstName -> NickName -> LastName -> Reader ABConfig String
fullNameM fn nn ln =
toUpperStrM fn >>= (\upperFN ->
toUpperStrM nn >>= (\upperNN ->
toUpperStrM ln >>= (\upperLN ->
Reader (\_ -> concat [ upperFN
, " \""
, upperNN
, "\" "
, upperLN
]))))
instance Functor (Reader g) where
fmap :: (a -> b) -> Reader c a -> Reader c b
fmap ab (Reader ca) = Reader (\c -> ab $ ca c)
instance Applicative (Reader c) where
pure :: a -> Reader c a
pure a = Reader (\c -> a)
(<*>) :: Reader c (a -> b) -> Reader c a -> Reader c b
Reader cab <*> Reader ca = Reader (\c -> cab c (ca c))
instance Monad (Reader g) where
(>>=) :: Reader c a -> (a -> Reader c b) -> Reader c b
Reader ca >>= aRcb = Reader (\c -> runReader (aRcb (ca c)) c)
ask :: Reader c c
ask = Reader (\c -> c)
` ask ` duplicates the config value from Reader 's first type parameter to its second type parameter
asks :: (c -> a) -> Reader c a
asks ca = Reader (\c -> ca c)
toUpperStr' :: String -> Reader ABConfig String
toUpperStr' str = do
let
preds =
[ if noEs cfg then (/= 'E') else const True
, if noLs cfg then (/= 'L') else const True
]
passesAll c = all (\pred -> pred c) preds
pure . filter passesAll . map toUpper $ str
welcomeMessage' :: String -> String -> Reader ABConfig String
welcomeMessage' msg username = do
upperMsg <- toUpperStr' msg
upperUsername <- toUpperStr' username
pure $ concat [ "Welcome, "
, upperUsername
, "! Message of the day: "
, upperMsg
]
fullName' :: FirstName -> NickName -> LastName -> Reader ABConfig String
fullName' fn nn ln = do
upperFN <- toUpperStr' fn
upperNN <- toUpperStr' nn
upperLN <- toUpperStr' ln
pure $ concat [ upperFN
, " \""
, upperNN
, "\" "
, upperLN
]
local :: (c -> l) -> Reader l a -> Reader c a
local cl (Reader la) = Reader (\c -> la (cl c)) |
e344b5a689fc5c405275da072c32afc5347920d297fe508efc99e72a938e1e44 | cognesence/matcher | project.clj | (defproject org.clojars.cognesence/matcher "1.0.1"
:description "A fully-featured symbolic pattern matcher for Clojure."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]])
| null | https://raw.githubusercontent.com/cognesence/matcher/a2e303d7b8803ef8bbe5b4296d6c8269194486b5/project.clj | clojure | (defproject org.clojars.cognesence/matcher "1.0.1"
:description "A fully-featured symbolic pattern matcher for Clojure."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]])
| |
14da6c860ab851ed39fcf1a93bf239809b90c663ee9151781ab95cc4358c785e | craigl64/clim-ccl | db-list.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : SILICA ; Base : 10 ; Lowercase : Yes -*-
"Copyright (c) 1992 by Symbolics, Inc. All rights reserved."
(in-package :silica) ;yes, this file is in the Silica package
;;; List panes and option panes
;; We use "simple" toggle buttons inside of list and option panes
(defclass simple-toggle-button-pane (toggle-button button-pane-mixin)
()
(:default-initargs :label nil
:text-style *default-button-label-text-style*
:show-as-default nil))
(defparameter *check-mark-pattern*
(make-pattern #2a((0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)
(0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1)
(0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0)
(0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0)
(0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0)
(0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0)
(0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0)
(0 1 1 1 1 0 0 1 1 1 0 0 0 0 0 0)
(1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 0)
(0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0)
(0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0)
(0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0)
(0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0)
(0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0))
(list +background-ink+ +foreground-ink+)))
(defmethod compose-space ((pane simple-toggle-button-pane) &key width height)
(declare (ignore width height))
(multiple-value-bind (width height)
(compute-gadget-label-size pane)
(incf width (+ (pattern-width *check-mark-pattern*) 2))
(maxf height (+ (pattern-height *check-mark-pattern*) 1))
(make-space-requirement :width width :height height)))
;; Draw the text, invert the whole button when it's armed. Add a check
;; mark when the button is toggled on.
(defmethod handle-repaint ((pane simple-toggle-button-pane) region)
(declare (ignore region))
(with-sheet-medium (medium pane)
(let ((text (gadget-label pane))
(text-style (slot-value pane 'text-style))
(armed (slot-value pane 'armed))
(pattern *check-mark-pattern*))
(with-bounding-rectangle* (left top right bottom) (sheet-region pane)
(if (gadget-value pane)
(draw-pattern* medium pattern (- right (+ (pattern-width pattern) 2)) (+ top 1))
(draw-rectangle* medium
(- right (+ (pattern-width pattern) 2)) (+ top 1) right bottom
:filled t :ink +background-ink+))
(draw-rectangle* medium left top (1- right) (1- bottom)
:filled nil)
(draw-text* medium text (+ left 2) (+ top (floor (- bottom top) 2))
:text-style text-style
:align-x :left :align-y :center))
(when (eq armed :active)
(highlight-button pane medium)))))
(defmethod handle-event ((pane simple-toggle-button-pane) (event pointer-button-release-event))
(with-slots (armed) pane
(when (eq armed :active)
(setf armed t)
(with-sheet-medium (medium pane)
(highlight-button pane medium))
(setf (gadget-value pane :invoke-callback t) (not (gadget-value pane))))))
This is done in the ( SETF GADGET - VALUE ) method because that 's where it
would be done in , say , . ( That is , we 'd pass the SET - GADGET - VALUE
off to which would toggle the indicator . )
(defmethod (setf gadget-value) :after (value (pane simple-toggle-button-pane)
&key invoke-callback)
(declare (ignore value invoke-callback))
(when (port pane)
(handle-repaint pane +everywhere+)))
(defclass generic-list-pane
(list-pane
wrapping-space-mixin
sheet-permanently-enabled-mixin
sheet-mute-input-mixin
sheet-multiple-child-mixin
space-requirement-mixin
basic-pane)
())
(defmethod initialize-instance :after ((pane generic-list-pane) &key)
(with-slots (items name-key value-key test mode) pane
(let* ((frame (pane-frame pane))
(framem (frame-manager frame)))
(assert (and frame framem) ()
"There must be both a frame and frame manager active")
(with-look-and-feel-realization (framem frame)
(dolist (item items)
(make-pane 'simple-toggle-button-pane
:value (ecase mode
(:exclusive
(funcall test (funcall value-key item) (gadget-value pane)))
(:nonexclusive
(and (member (funcall value-key item) (gadget-value pane) :test test)
t)))
:label (funcall name-key item)
:id item
:parent pane))
(let ((buttons (copy-list (sheet-children pane))))
(setq items buttons) ;save them away
(dolist (button buttons)
(setf (gadget-client button) pane)
(sheet-disown-child pane button))
(let ((inferiors
(make-pane 'vbox-pane
:spacing 3
:contents buttons)))
(sheet-adopt-child pane inferiors)))))))
(defmethod value-changed-callback :around
((selection toggle-button) (client generic-list-pane) gadget-id value)
(declare (ignore gadget-id))
(with-slots (items value-key mode) client
(let ((real-value (funcall value-key (gadget-id selection)))
(old-selection nil))
(ecase mode
(:exclusive
(setq old-selection (gadget-value client))
(setf (gadget-value client) (and value real-value)))
(:nonexclusive
(if value
(pushnew real-value (gadget-value client))
(setf (gadget-value client) (delete real-value (gadget-value client))))))
(when old-selection
(let ((button (find old-selection items :key #'gadget-id)))
(setf (gadget-value button :invoke-callback nil) nil)))
(value-changed-callback
client (gadget-client client) (gadget-id client) (gadget-value client))))
(call-next-method))
(defmethod handle-event :after ((pane generic-list-pane) (event pointer-event))
(deallocate-event event))
(defclass generic-option-pane (option-pane push-button-pane)
((menu :initform nil))
(:default-initargs :pattern *right-triangle-button-pattern*))
;;--- The idea is the the option pane itself is a pushbutton which, when
;;--- pressed, pops up a menu containing the options.
(defmethod initialize-instance :after ((pane generic-option-pane) &key)
(with-slots (external-label label
items name-key value-key test mode) pane
(shiftf external-label label nil)
(let* ((frame (pane-frame pane))
(framem (frame-manager frame))
(buttons nil))
(assert (and frame framem) ()
"There must be both a frame and frame manager active")
(with-look-and-feel-realization (framem frame)
(dolist (item items)
(push (make-pane 'simple-toggle-button-pane
:value (ecase mode
(:exclusive
(funcall test (funcall value-key item) (gadget-value pane)))
(:nonexclusive
(and (member (funcall value-key item) (gadget-value pane) :test test)
t)))
:label (funcall name-key item)
:id item
:client pane)
buttons))
(setq buttons (nreverse buttons))
(setq items (copy-list buttons)) ;save them away
(let ((menu (make-pull-down-menu :port (port frame))))
(initialize-pull-down-menu menu buttons)
(setf (slot-value pane 'menu) menu))))))
(defmethod handle-event ((pane generic-option-pane) (event pointer-button-release-event))
(with-slots (armed menu) pane
(when (eq armed :active)
(setf armed t)
(with-sheet-medium (medium pane)
(highlight-button pane medium))
(choose-from-pull-down-menu menu pane))))
(defmethod value-changed-callback :around
((selection toggle-button) (client generic-option-pane) gadget-id value)
(declare (ignore gadget-id))
(with-slots (items value-key mode) client
(let ((real-value (funcall value-key (gadget-id selection)))
(old-selection nil))
(ecase mode
(:exclusive
(setq old-selection (gadget-value client))
(setf (gadget-value client) (and value real-value)))
(:nonexclusive
(if value
(pushnew real-value (gadget-value client))
(setf (gadget-value client) (delete real-value (gadget-value client))))))
(when old-selection
(let ((button (find old-selection items :key #'gadget-id)))
(setf (gadget-value button :invoke-callback nil) nil)))
(value-changed-callback
client (gadget-client client) (gadget-id client) (gadget-value client))))
(call-next-method))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/homegrown/db-list.lisp | lisp | Syntax : ANSI - Common - Lisp ; Package : SILICA ; Base : 10 ; Lowercase : Yes -*-
yes, this file is in the Silica package
List panes and option panes
We use "simple" toggle buttons inside of list and option panes
Draw the text, invert the whole button when it's armed. Add a check
mark when the button is toggled on.
save them away
--- The idea is the the option pane itself is a pushbutton which, when
--- pressed, pops up a menu containing the options.
save them away |
"Copyright (c) 1992 by Symbolics, Inc. All rights reserved."
(defclass simple-toggle-button-pane (toggle-button button-pane-mixin)
()
(:default-initargs :label nil
:text-style *default-button-label-text-style*
:show-as-default nil))
(defparameter *check-mark-pattern*
(make-pattern #2a((0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)
(0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1)
(0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0)
(0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0)
(0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0)
(0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0)
(0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0)
(0 1 1 1 1 0 0 1 1 1 0 0 0 0 0 0)
(1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 0)
(0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0)
(0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0)
(0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0)
(0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0)
(0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0))
(list +background-ink+ +foreground-ink+)))
(defmethod compose-space ((pane simple-toggle-button-pane) &key width height)
(declare (ignore width height))
(multiple-value-bind (width height)
(compute-gadget-label-size pane)
(incf width (+ (pattern-width *check-mark-pattern*) 2))
(maxf height (+ (pattern-height *check-mark-pattern*) 1))
(make-space-requirement :width width :height height)))
(defmethod handle-repaint ((pane simple-toggle-button-pane) region)
(declare (ignore region))
(with-sheet-medium (medium pane)
(let ((text (gadget-label pane))
(text-style (slot-value pane 'text-style))
(armed (slot-value pane 'armed))
(pattern *check-mark-pattern*))
(with-bounding-rectangle* (left top right bottom) (sheet-region pane)
(if (gadget-value pane)
(draw-pattern* medium pattern (- right (+ (pattern-width pattern) 2)) (+ top 1))
(draw-rectangle* medium
(- right (+ (pattern-width pattern) 2)) (+ top 1) right bottom
:filled t :ink +background-ink+))
(draw-rectangle* medium left top (1- right) (1- bottom)
:filled nil)
(draw-text* medium text (+ left 2) (+ top (floor (- bottom top) 2))
:text-style text-style
:align-x :left :align-y :center))
(when (eq armed :active)
(highlight-button pane medium)))))
(defmethod handle-event ((pane simple-toggle-button-pane) (event pointer-button-release-event))
(with-slots (armed) pane
(when (eq armed :active)
(setf armed t)
(with-sheet-medium (medium pane)
(highlight-button pane medium))
(setf (gadget-value pane :invoke-callback t) (not (gadget-value pane))))))
This is done in the ( SETF GADGET - VALUE ) method because that 's where it
would be done in , say , . ( That is , we 'd pass the SET - GADGET - VALUE
off to which would toggle the indicator . )
(defmethod (setf gadget-value) :after (value (pane simple-toggle-button-pane)
&key invoke-callback)
(declare (ignore value invoke-callback))
(when (port pane)
(handle-repaint pane +everywhere+)))
(defclass generic-list-pane
(list-pane
wrapping-space-mixin
sheet-permanently-enabled-mixin
sheet-mute-input-mixin
sheet-multiple-child-mixin
space-requirement-mixin
basic-pane)
())
(defmethod initialize-instance :after ((pane generic-list-pane) &key)
(with-slots (items name-key value-key test mode) pane
(let* ((frame (pane-frame pane))
(framem (frame-manager frame)))
(assert (and frame framem) ()
"There must be both a frame and frame manager active")
(with-look-and-feel-realization (framem frame)
(dolist (item items)
(make-pane 'simple-toggle-button-pane
:value (ecase mode
(:exclusive
(funcall test (funcall value-key item) (gadget-value pane)))
(:nonexclusive
(and (member (funcall value-key item) (gadget-value pane) :test test)
t)))
:label (funcall name-key item)
:id item
:parent pane))
(let ((buttons (copy-list (sheet-children pane))))
(dolist (button buttons)
(setf (gadget-client button) pane)
(sheet-disown-child pane button))
(let ((inferiors
(make-pane 'vbox-pane
:spacing 3
:contents buttons)))
(sheet-adopt-child pane inferiors)))))))
(defmethod value-changed-callback :around
((selection toggle-button) (client generic-list-pane) gadget-id value)
(declare (ignore gadget-id))
(with-slots (items value-key mode) client
(let ((real-value (funcall value-key (gadget-id selection)))
(old-selection nil))
(ecase mode
(:exclusive
(setq old-selection (gadget-value client))
(setf (gadget-value client) (and value real-value)))
(:nonexclusive
(if value
(pushnew real-value (gadget-value client))
(setf (gadget-value client) (delete real-value (gadget-value client))))))
(when old-selection
(let ((button (find old-selection items :key #'gadget-id)))
(setf (gadget-value button :invoke-callback nil) nil)))
(value-changed-callback
client (gadget-client client) (gadget-id client) (gadget-value client))))
(call-next-method))
(defmethod handle-event :after ((pane generic-list-pane) (event pointer-event))
(deallocate-event event))
(defclass generic-option-pane (option-pane push-button-pane)
((menu :initform nil))
(:default-initargs :pattern *right-triangle-button-pattern*))
(defmethod initialize-instance :after ((pane generic-option-pane) &key)
(with-slots (external-label label
items name-key value-key test mode) pane
(shiftf external-label label nil)
(let* ((frame (pane-frame pane))
(framem (frame-manager frame))
(buttons nil))
(assert (and frame framem) ()
"There must be both a frame and frame manager active")
(with-look-and-feel-realization (framem frame)
(dolist (item items)
(push (make-pane 'simple-toggle-button-pane
:value (ecase mode
(:exclusive
(funcall test (funcall value-key item) (gadget-value pane)))
(:nonexclusive
(and (member (funcall value-key item) (gadget-value pane) :test test)
t)))
:label (funcall name-key item)
:id item
:client pane)
buttons))
(setq buttons (nreverse buttons))
(let ((menu (make-pull-down-menu :port (port frame))))
(initialize-pull-down-menu menu buttons)
(setf (slot-value pane 'menu) menu))))))
(defmethod handle-event ((pane generic-option-pane) (event pointer-button-release-event))
(with-slots (armed menu) pane
(when (eq armed :active)
(setf armed t)
(with-sheet-medium (medium pane)
(highlight-button pane medium))
(choose-from-pull-down-menu menu pane))))
(defmethod value-changed-callback :around
((selection toggle-button) (client generic-option-pane) gadget-id value)
(declare (ignore gadget-id))
(with-slots (items value-key mode) client
(let ((real-value (funcall value-key (gadget-id selection)))
(old-selection nil))
(ecase mode
(:exclusive
(setq old-selection (gadget-value client))
(setf (gadget-value client) (and value real-value)))
(:nonexclusive
(if value
(pushnew real-value (gadget-value client))
(setf (gadget-value client) (delete real-value (gadget-value client))))))
(when old-selection
(let ((button (find old-selection items :key #'gadget-id)))
(setf (gadget-value button :invoke-callback nil) nil)))
(value-changed-callback
client (gadget-client client) (gadget-id client) (gadget-value client))))
(call-next-method))
|
09a327c1f7c91da5784ec7a0803ed3baa03f9f756914c2af6f335b192f570321 | ocaml-multicore/kcas | barrier.mli | type t
val make : int -> t
val await : t -> unit
| null | https://raw.githubusercontent.com/ocaml-multicore/kcas/4d8179858c5449e0f4c0309bad547b344d69d3e4/test/barrier.mli | ocaml | type t
val make : int -> t
val await : t -> unit
| |
df4b96cfee48eb70d8ff3b4ab692f466e009f30fcc24f6217b9da193ad8e9697 | tali713/mit-scheme | comcon.scm | ;;; This alternative version of `combination/constant!' attempts to
;;; keep the data structures more consistent. It doesn't seem to be
;;; needed yet.
(define (combination/constant! combination rvalue)
(let ((continuation (combination/continuation combination)))
(for-each (lambda (continuation)
(set-continuation/combinations!
continuation
(delq! combination (continuation/combinations continuation)))
(set-continuation/returns!
continuation
(cons combination (continuation/returns continuation))))
(rvalue-values continuation))
(for-each (lambda (operator)
(if (rvalue/procedure? operator)
(delete-procedure-application! operator combination)))
(rvalue-values (combination/operator combination)))
(maybe-kill-application-procedure! combination)
(set-application-type! combination 'RETURN)
(set-application-operator! combination continuation)
(set-application-operands! combination (list rvalue))
(let ((push (combination/continuation-push combination)))
(if (and push (rvalue-known-value continuation))
(set-virtual-continuation/type! (virtual-return-operator push)
continuation-type/effect)))))
(define (maybe-kill-application-procedure! application)
(let ((operator (rvalue-known-value (application-operator application))))
(if (and operator
(rvalue/procedure? operator)
(procedure-always-known-operator? operator)
(null? (procedure-applications operator)))
(kill-procedure! operator))))
(define (kill-procedure! procedure)
(set! *procedures* (delq! procedure *procedures*))
(let ((block (procedure-block procedure)))
(set! *blocks* (delq! block *blocks*))
(let ((parent (block-parent block)))
(set-block-children! parent (delq! block (block-children parent))))
;; This should probably be accomplished by a codewalk, but for
;; current purposes it's adequate.
(for-each kill-application! (block-applications block))))
(define (kill-application! application)
(set! *applications* (delq! application *applications*))
(for-each (lambda (operator)
(if (rvalue/procedure? operator)
(delete-procedure-application! operator application)))
(rvalue-values (application-operator application)))
(if (application/combination? application)
(for-each (lambda (continuation)
(delete-continuation/combination! continuation application))
(rvalue-values (combination/continuation application))))
(maybe-kill-application-procedure! application))
(define (delete-procedure-application! procedure combination)
(let ((applications (delq! combination (procedure-applications procedure))))
(set-procedure-applications! procedure applications)
(if (null? applications)
(set-procedure-always-known-operator?! procedure false))))
(define (delete-continuation/combination! continuation combination)
(let ((combinations
(delq! combination (continuation/combinations continuation))))
(set-continuation/combinations! continuation combinations)
(if (and (null? combinations)
(null? (continuation/returns continuation)))
(set-procedure-always-known-operator?! continuation false)))) | null | https://raw.githubusercontent.com/tali713/mit-scheme/6c703a838081fe2418bc0dbfe003bdb429d8c479/src/compiler/improvements/comcon.scm | scheme | This alternative version of `combination/constant!' attempts to
keep the data structures more consistent. It doesn't seem to be
needed yet.
This should probably be accomplished by a codewalk, but for
current purposes it's adequate. |
(define (combination/constant! combination rvalue)
(let ((continuation (combination/continuation combination)))
(for-each (lambda (continuation)
(set-continuation/combinations!
continuation
(delq! combination (continuation/combinations continuation)))
(set-continuation/returns!
continuation
(cons combination (continuation/returns continuation))))
(rvalue-values continuation))
(for-each (lambda (operator)
(if (rvalue/procedure? operator)
(delete-procedure-application! operator combination)))
(rvalue-values (combination/operator combination)))
(maybe-kill-application-procedure! combination)
(set-application-type! combination 'RETURN)
(set-application-operator! combination continuation)
(set-application-operands! combination (list rvalue))
(let ((push (combination/continuation-push combination)))
(if (and push (rvalue-known-value continuation))
(set-virtual-continuation/type! (virtual-return-operator push)
continuation-type/effect)))))
(define (maybe-kill-application-procedure! application)
(let ((operator (rvalue-known-value (application-operator application))))
(if (and operator
(rvalue/procedure? operator)
(procedure-always-known-operator? operator)
(null? (procedure-applications operator)))
(kill-procedure! operator))))
(define (kill-procedure! procedure)
(set! *procedures* (delq! procedure *procedures*))
(let ((block (procedure-block procedure)))
(set! *blocks* (delq! block *blocks*))
(let ((parent (block-parent block)))
(set-block-children! parent (delq! block (block-children parent))))
(for-each kill-application! (block-applications block))))
(define (kill-application! application)
(set! *applications* (delq! application *applications*))
(for-each (lambda (operator)
(if (rvalue/procedure? operator)
(delete-procedure-application! operator application)))
(rvalue-values (application-operator application)))
(if (application/combination? application)
(for-each (lambda (continuation)
(delete-continuation/combination! continuation application))
(rvalue-values (combination/continuation application))))
(maybe-kill-application-procedure! application))
(define (delete-procedure-application! procedure combination)
(let ((applications (delq! combination (procedure-applications procedure))))
(set-procedure-applications! procedure applications)
(if (null? applications)
(set-procedure-always-known-operator?! procedure false))))
(define (delete-continuation/combination! continuation combination)
(let ((combinations
(delq! combination (continuation/combinations continuation))))
(set-continuation/combinations! continuation combinations)
(if (and (null? combinations)
(null? (continuation/returns continuation)))
(set-procedure-always-known-operator?! continuation false)))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.