_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
13d78db35286d08ce340004e07579425f79e926caba52ae434d31ebf4b13bfbf
mpickering/500-sql-haskell
LMS.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # # LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE KindSignatures # # LANGUAGE DataKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeApplications # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE InstanceSigs # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE TypeFamilies # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveLift #-} module LMS where import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.ByteString (ByteString) import Control.Monad import Data.List import Data.Maybe import Language.Haskell.TH import Language.Haskell.TH.Syntax import Prelude hiding (Applicative(..)) import Instances.TH.Lift () import Data . FileEmbed import Data.Functor.Identity import Control.Applicative (liftA2) import System.IO.Unsafe import qualified Prelude as P import GHC.TypeLits import Control.Applicative (liftA3) import Instances.TH.Lift import Criterion import Criterion.Main import System.IO.Silently import System.Mem import Debug.Trace import System.IO for = flip map class Ops r where eq :: Eq a => r a -> r a -> r Bool neq :: Eq a => r a -> r a -> r Bool bc_split :: r Char -> r ByteString -> r [ByteString] tail_dropwhile :: Char -> r ByteString -> r ByteString take_while :: Char -> r ByteString -> r ByteString _if :: r Bool -> r a -> r a -> r a _caseString :: r ByteString -> r a -> r a -> r a _fix :: (r a -> r a) -> r a _lam :: (r a -> r b) -> r (a -> b) _bind :: Monad m => r (m a) -> (r (a -> m b)) -> r (m b) _print :: Show a => r a -> r Res _putStr :: r ByteString -> r Res _hPutStr :: r Handle -> r ByteString -> r Res (>>>) :: Monoid m => r m -> r m -> r m _empty :: Monoid m => r m _pure :: P.Applicative f => r a -> r (f a) Scanner interface _newScanner :: FilePath -> r (IO Scanner) _hasNext :: r Scanner -> r Bool _nextLine :: r Scanner -> (r ByteString, r Scanner) pure :: Lift a => a -> r a (<*>) :: r (a -> b) -> r a -> r b _case_record :: r (Record r1) -> r ((Fields r1) -> Schema -> c) -> r c _lup :: r ByteString -> r (Fields r1) -> r Schema -> r (r1 ByteString) _intersect :: Eq a => r [a] -> r [a] -> r [a] _mkRecord :: r (Fields r1) -> r Schema -> r (Record r1) _cons :: r a -> r [a] -> r [a] infixl 4 <*> newtype Code a = Code (Q (TExp a)) instance Ops Code where eq (Code e1) (Code e2) = Code [|| $$e1 == $$e2 ||] neq (Code e1) (Code e2) = Code [|| $$e1 /= $$e2 ||] bc_split (Code e1) (Code e2) = Code [|| BC.split $$e1 $$e2 ||] _if (Code a) (Code b) (Code c) = Code [|| if $$a then $$b else $$c ||] _caseString (Code a) (Code b) (Code c) = Code [|| case $$a of "" -> $$b _ -> $$c ||] (>>>) (Code a) (Code b) = Code [|| $$a <> $$b ||] _bind (Code a) (Code b) = Code [|| $$a >>= $$b ||] _empty = Code [|| mempty ||] _pure (Code p) = Code [|| P.pure $$p ||] _print (Code a) = Code [|| print $$a ||] _putStr (Code a) = Code [|| BC.putStr $$a ||] _hPutStr (Code a) (Code b) = Code [|| BC.hPutStr $$a $$b ||] tail_dropwhile c (Code b) = Code [|| BC.tail (BC.dropWhile (/= c) $$b) ||] take_while c (Code b) = Code [|| BC.takeWhile (/= c) $$b ||] _fix f = Code [|| fix (\a -> $$(runCode $ f (Code [||a||]))) ||] _lam f = Code $ [|| \a -> $$(runCode $ f (Code [|| a ||])) ||] _newScanner fp = Code [|| newScanner fp ||] _hasNext s = Code [|| hasNext $$(runCode s) ||] _nextLine = _nextLineCode pure = Code . unsafeTExpCoerce . lift (Code f) <*> (Code a) = Code [|| $$f $$a ||] _case_record (Code r) (Code k1) = Code [|| case $$r of Record rs ss -> $$(k1) rs ss ||] _lup (Code l1) (Code l2) (Code l3) = Code [|| lup $$l1 $$l2 $$l3 ||] _intersect (Code l1) (Code l2) = Code [|| $$l1 `intersect` $$l2 ||] _mkRecord (Code l1) (Code l2) = Code [|| Record $$l1 $$l2 ||] _cons (Code l1) (Code l2) = Code [|| $$l1 : $$l2 ||] instance Ops Identity where eq = liftA2 (==) neq = liftA2 (/=) bc_split = liftA2 (BC.split) tail_dropwhile c = fmap (BC.tail . (BC.dropWhile (/= c))) take_while c = fmap (BC.takeWhile (/= c)) _print = fmap print _putStr = fmap (BC.putStr) _hPutStr = liftA2 BC.hPut _empty = Identity mempty _if (Identity b) (Identity c1) (Identity c2) = Identity (if b then c1 else c2) _fix = fix _lam f = Identity (\a -> runIdentity (f (Identity a))) (>>>) = liftA2 mappend _bind = liftA2 (>>=) _pure = fmap (P.pure) _newScanner fp = Identity (newScanner fp) _hasNext = fmap hasNext _nextLine = nextLine pure = Identity (<*>) (Identity a1) (Identity a2) = Identity (a1 a2) _case_record (Identity r) (Identity k) = case r of Record rs ss -> Identity (k rs ss) _lup = liftA3 lup _intersect = liftA2 intersect _mkRecord = liftA2 Record _cons = liftA2 (:) _when :: (Monoid m, Ops r) => r Bool -> r m -> r m _when cond act = _if cond act _empty _whenA :: (P.Applicative f, Ops r) => r Bool -> r (f ()) -> r (f ()) _whenA cond act = _if cond act (_pure (pure ())) runCode :: Code a -> Q (TExp a) runCode (Code a) = a type Fields r = [r ByteString] type Schema = [ByteString] type Table = FilePath type Res = IO () data Record r = Record { fields :: Fields r, schema :: Schema } getField :: Ops r1 => r1 ByteString -> r1 (Record r) -> r1 (r ByteString) getField field r = _case_record r (_lam $ \fs -> _lam $ \sch -> _lup field fs sch) lup :: ByteString -> Fields r -> Schema -> r ByteString lup field fs sch = let i = fromJust (elemIndex field sch) in (fs !! i) getFields : : [ ByteString ] - > Record r - > [ r ByteString ] getFields fs r = map ( flip r ) fs data Operator = Scan FilePath Schema | Project Schema Schema Operator | Filter Predicate Operator | Join Operator Operator deriving (Lift, Show) cols n = take (2 ^ n) [BC.pack('f':show n) | n <- [0..]] fp c n = "data/data-" ++ show (10^n) ++ "-" ++ show (2 ^ c) ++ ".csv" queryP, queryJoin, queryLast, query, query2 :: Int -> Int -> Operator query c n = Project ["f0"] ["f0"] (Filter (Eq (Value "a") (Field "f0")) (Scan (fp c n) (cols c))) query2 c n = Project ["f0"] ["f0"] (Filter (Eq (Value "a") (Field "f0")) (Scan (fp c n) (cols c))) queryJoin c n = Join (Scan (fp c n) (cols c)) (Scan (fp c n) (cols c)) queryP c n = Project ["f0"] ["f0"] (Scan (fp c n) (cols c)) queryLast c n = let cs = cols c in Project [last cs] [last cs] (Scan (fp c n) cs) data Predicate = Eq Ref Ref | Ne Ref Ref deriving (Show, Lift) data Ref = Field ByteString | Value ByteString deriving (Show, Lift) type QTExp a = Code a fix :: (a -> a) -> a fix f = let x = f x in x data Scanner = Scanner ByteString newScanner :: FilePath -> IO Scanner newScanner fp = Scanner <$> B.readFile fp nextLine :: Identity Scanner -> (Identity ByteString, Identity Scanner) nextLine (Identity (Scanner bs)) = let (fs, rs) = BC.span (/= '\n') bs in (Identity fs, Identity (Scanner (BC.tail rs))) -- As |span| is not stage aware, it is more dynamic an necessary. Splitting -- the implementation up means that we can skip over entire rows if -- necessary in the generated code. _nextLineCode :: Code Scanner -> (Code ByteString, Code Scanner) _nextLineCode scanner = let fs = Code [|| let (Scanner s) = $$(runCode scanner) in BC.takeWhile (/= '\n') s ||] ts = Code [|| let (Scanner s) = $$(runCode scanner) in Scanner (BC.tail (BC.dropWhile (/= '\n') s)) ||] in (fs, ts) hasNext :: Scanner -> Bool hasNext (Scanner bs) = bs /= "" while :: (Ops r, Monoid m) => r (t -> Bool) -> r ((t -> IO m) -> t -> IO m) -> r (t -> IO m) while k b = _fix (\r -> _lam $ \rs -> _when (k <*> rs) (b <*> r <*> rs)) whenM :: Monoid m => Bool -> m -> m whenM b act = if b then act else mempty type family ResT r1 r2 :: * -> * where ResT Identity Code = Code ResT Code Identity = Code ResT Identity r = r processCSV :: forall m r r1 . (Monoid m, O r1 r) => Schema -> FilePath -> (r1 (Record r) -> (ResT r1 r) (IO m)) -> (ResT r1 r) (IO m) processCSV ss f yld = _newScanner f `_bind` rows ss where rows :: Schema -> (ResT r1 r) (Scanner -> (IO m)) rows sch = do while (_lam _hasNext) (_lam $ \r -> _lam $ \rs -> (let (hs, ts) = _nextLine rs rec = _mkRecord (parseRow sch hs) (pure sch) in yld rec >>> (r <*> ts)) ) -- We can't use the standard |BC.split| function here because -- we we statically know how far we will unroll. The result is then -- more static as we can do things like drop certain fields if we -- perform a projection. parseRow :: Schema -> (ResT r1 r) ByteString -> r1 [r ByteString] parseRow [] _ = _empty parseRow [_] b = weaken (take_while '\n' b) `_cons` _empty parseRow (_:ss') b = let new = tail_dropwhile ',' b rs = parseRow ss' new in weaken (take_while ',' b) `_cons` rs class Weaken r1 r where weaken :: (ResT r1 r) a -> r1 (r a) instance Weaken Code Identity where weaken (Code c) = Code [|| Identity $$c ||] instance Weaken Identity i where weaken i = Identity i printFields :: Ops r => r Handle -> Fields r -> r Res printFields _ [] = _empty printFields h [x] = _hPutStr h x >>> _hPutStr h (pure "\n") printFields h (x:xs) = _hPutStr h x >>> _hPutStr h (pure ",") >>> printFields h xs class Collapse r1 r2 where c :: r1 (r2 a) -> (ResT r1 r2) a instance Collapse Identity r where c (Identity a) = a instance Collapse Code Identity where c (Code c) = Code [|| runIdentity $$c ||] type O r1 r = (Collapse r1 r , Ops r , Ops (ResT r1 r) , Ops r1 , Weaken r1 r) evalPred :: forall r1 r . (O r1 r) => Predicate -> r1 (Record r) -> (ResT r1 r) Bool evalPred predicate rec = case predicate of Eq a b -> eq (evalRef a rec) (evalRef b rec) Ne a b -> neq (evalRef a rec) (evalRef b rec) evalRef :: (Collapse r1 r , Ops r , Ops (ResT r1 r) , Ops r1 ) => Ref -> r1 (Record r) -> (ResT r1 r) ByteString evalRef (Value a) _ = pure a evalRef (Field name) r = c $ getField (pure name) r class O r1 r => ListEq (s :: Symbol) r r1 where list_eq :: (Eq a) => r1 [r a] -> r1 [r a] -> (ResT r1 r) Bool class O r1 r => Restrict (s :: Symbol) r r1 where restrict :: Ops r => r1 (Record r) -> Schema -> Schema -> r1 (Record r) Point of this instance is that we can use the normal ` map ` in order to -- get the value of each field at instance Restrict "unrolled" Code Identity where restrict r newSchema parentSchema | length parentSchema <= 10 = let ns = map Identity parentSchema nfs = sequence $ map (flip getField r) ns in Record <$> nfs <*> Identity newSchema restrict r newSchema parentSchema = restrict @"recursive" r newSchema parentSchema Record < $ > ( map ( flip r ) parentSchema ) < * > _ instance Restrict s Identity Identity where restrict rec newSchema parentSchema = let ns = map Identity parentSchema r = map (runIdentity . flip getField rec) ns in Identity $ Record r parentSchema -- In this instance we lost the static information about instance Restrict "recursive" Identity Code where restrict :: Code (Record Identity) -> Schema -> Schema -> Code (Record Identity) restrict rec news ps = let ns = map pure ps r = map (flip getField rec) ns in Code [|| Record $$(runCode $ spillL r) ps ||] -- In this instance we just do the same as the unrolled version because -- that's already recursive so err, that's good I guess. -- -- Can't really think how to make this totally suck now because the problem -- is that we have to maintain the staticness of the schema so we can't -- really weaken. instance Restrict "recursive" Code Identity where restrict :: Identity (Record Code) -> Schema -> Schema -> Identity (Record Code) restrict (Identity rec) new ps = let fs = fields rec fs' = map (getField2 fs ps) (map pure ps) getField' = getField2 in Identity (Record fs' new) getField2 :: Fields Code -> Schema -> Code ByteString -> Code ByteString getField2 fields ps lup_field = Code [|| runIdentity $ lup $$(runCode lup_field) $$(runCode $ spill2 fields) ps ||] One of my favourite functions <3 spillL :: [Code a] -> Code [a] spillL [] = Code [|| [] ||] spillL (x:xs) = Code [|| $$(runCode x) : $$(runCode $ spillL xs) ||] spillQ :: [Q (TExp a)] -> Q (TExp [a]) spillQ [] = [|| [] ||] spillQ (x:xs) = [|| $$x : $$(spillQ xs) ||] instance ListEq "unrolled" Code Identity where list_eq :: (Eq a) => Identity [Code a] -> Identity [Code a] -> Code Bool list_eq (Identity xs) (Identity ys) = let lxs = length xs lys = length ys in if max lxs lys <= 10 then list_eq_r xs ys else list_eq @"recursive" (Identity xs) (Identity ys) list_eq_r [] [] = pure True list_eq_r (v:vs) (v1:v1s) = _if (eq v v1) (list_eq_r vs v1s) (pure False) list_eq_r _ _ = pure False instance ListEq s Identity Identity where list_eq :: (Eq a) => Identity [Identity a] -> Identity [Identity a] -> Identity Bool list_eq xs ys = Identity (xs == ys) instance ListEq "recursive" Identity Code where list_eq :: Eq a => Code [Identity a] -> Code [Identity a] -> Code Bool list_eq (Code xs) (Code ys) = Code [|| $$(xs) == $$(ys) ||] pull :: [Code a] -> Code [a] pull [] = Code [|| [] ||] pull (x:xs) = Code [|| $$(runCode x) : $$(runCode $ pull xs) ||] instance ListEq "recursive" Code Identity where list_eq :: (Eq a) => Identity [Code a] -> Identity [Code a] -> Code Bool list_eq (Identity xs) (Identity ys) = Code [|| $$(runCode $ pull xs) == $$(runCode $ pull ys) ||] -- if r = Code then r1 = Identity -- -- if r = Identity then r1 = Code or Identity Having two type parameters means that we can either choose to use a -- continuation which statically knows the argument (r1 = Identity) or not. execOp :: forall restrict le r r1 m . ( Restrict restrict r r1 , ListEq le r r1 , Monoid m , Ops r , Ops r1) => Operator -> (r1 (Record r) -> (ResT r1 r) (IO m)) -> (ResT r1 r) (IO m) execOp op yld = case op of Scan file sch -> processCSV sch file yld Filter predicate parent -> execOp @restrict @le parent (\rec -> _if (evalPred @r1 @r predicate rec) (yld rec) _empty ) Project newSchema parentSchema parent -> execOp @restrict @le parent (\rec -> yld (restrict @restrict rec newSchema parentSchema )) Join left right -> execOp @restrict @le left (\rec -> execOp @restrict @le right (\rec' -> let k1 = _schema rec k2 = _fields rec keys = _intersect (_schema rec) (_schema rec') leq = list_eq @le @r @r1 @ByteString k2 (_fields rec') in _when leq (yld (_mkRecord (_fields rec >>> _fields rec') (_schema rec >>> _schema rec') )))) _fields r = _case_record r (_lam $ \fs -> _lam $ \_ -> fs) _schema r = _case_record r (_lam $ \_ -> _lam $ \ss -> ss) execOpU :: forall r r1 m . (Monoid m, O r r1 , Restrict "unrolled" r r1 , ListEq "unrolled" r r1) => Operator -> (r1 (Record r) -> (ResT r1 r) (IO m)) -> (ResT r1 r) (IO m) execOpU = execOp @"unrolled" @"unrolled" print_k h = (\r -> Code [|| $$(runCode $ printFields h (fields (runIdentity r))) ||]) wrap :: Code (Handle -> IO ()) -> Code (IO ()) wrap (Code c) = Code [|| withFile "/dev/null" WriteMode $$c ||] -- r1 = Identity; r = Code runQuery :: Operator -> Q (TExp ( Res)) runQuery q = runCode $ wrap (Code [|| \h -> $$(runCode $ execOpU q (print_k (Code [|| h ||]))) ||]) -- r = Identity; r1 = Identity runQueryUnstaged :: Operator -> ( Res) runQueryUnstaged q = --traceShow q withFile "/dev/null" WriteMode (\handle -> runIdentity (execOpU q (\r -> Identity ( runIdentity (printFields (Identity handle) (fields (runIdentity r))))))) runQueryUnstagedC :: Operator -> Q (TExp ( Res)) runQueryUnstagedC q = [|| runQueryUnstaged q ||] -- Unrolled le, rec r runQueryUR :: Operator -> Q (TExp ( Res)) runQueryUR q = runCode $ wrap (Code [|| \h -> $$(runCode $ execOp @"unrolled" @"recursive" q (print_k (Code [|| h ||]))) ||]) -- Rec le, unrolled r runQueryRU :: Operator -> Q (TExp ( Res)) runQueryRU q = runCode $ wrap (_lam $ \h -> execOp @"recursive" @"unrolled" q (print_k h)) Rec le , rec r runQueryRR :: Operator -> Q (TExp ( Res)) runQueryRR q = runCode $ wrap (_lam $ \h -> execOp @"recursive" @"recursive" q (print_k h)) -- r1 = Code; r = Identity -- If r1 = Code then we can't use the unrolled versions as we don't know -- the schema. We can only unroll the loop. runQueryDynamic :: Operator -> Q (TExp ( Res)) runQueryDynamic q = runCode ( wrap (_lam $ \h -> execOp @"recursive" @"recursive" @Identity @Code q (printFields17 h))) queries = [ --("query", query) --, ("query2", query2) --("queryJoin", queryJoin) ("queryP", queryP) , ("queryLast", queryLast)] runners = [ ("best", runQuery) , ("ur", runQueryUR) , ("ru", runQueryRU) , ("rr", runQueryRR) , ("dynamic", runQueryDynamic) , ("unstaged", runQueryUnstagedC) ] files = [(n, c) | n <- [3..3], c <- [1..3] ] genBench :: Q (TExp [Benchmark]) genBench = spillQ $ for runners $ \(name, r) -> [|| bgroup name $$(spillQ $ for queries $ \(qname, q) -> [|| bgroup qname $ $$(spillQ $ for files $ \(n, c) -> [|| let b = $$(r (q c n)) in bench $$(runCode $ pure $ fp c n) $ perBatchEnv (const performGC) (\() -> b) ||]) ||]) ||] printFields17 :: (Code Handle) -> Code (Record Identity) -> Code (IO ()) printFields17 (Code h) (Code c) = Code [|| runIdentity $ printFields (Identity $$h) (fields $$(c)) ||] spill :: Record Code -> Code (Record Identity) spill (Record rs ss) = Code [|| Record $$(runCode $ spill2 rs) ss ||] spill2 :: [Code ByteString] -> Code [Identity ByteString] spill2 [] = Code [|| [] ||] spill2 (x:xs) = Code [|| (Identity $$(runCode x)) : $$(runCode $ spill2 xs) ||] runQueryUnstagedL :: Operator -> IO [Record Identity] runQueryUnstagedL q = runIdentity (execOpU @Identity @Identity q (return . return . return . runIdentity)) test :: IO () test = do processCSV " data / test.csv " ( print . " name " ) expr < - runQ $ unTypeQ $ runCode $ execOpU query ( printFields . fields ) expr < - runQ $ unTypeQ $ power --putStrLn $ pprint expr print "" bsToExp :: B.ByteString -> Q Exp bsToExp bs = do helper <- [| stringToBs |] let chars = BC.unpack . BC.tail . (BC.dropWhile (/= '\n')) $ bs return $! AppE helper $! LitE $! StringL chars stringToBs :: String -> B.ByteString stringToBs = BC.pack
null
https://raw.githubusercontent.com/mpickering/500-sql-haskell/b2beb269de21f37bc3c014ceb8233eec86c678d1/src/LMS.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE GADTs # # LANGUAGE ConstraintKinds # # LANGUAGE DeriveLift # As |span| is not stage aware, it is more dynamic an necessary. Splitting the implementation up means that we can skip over entire rows if necessary in the generated code. We can't use the standard |BC.split| function here because we we statically know how far we will unroll. The result is then more static as we can do things like drop certain fields if we perform a projection. get the value of each field at In this instance we lost the static information about In this instance we just do the same as the unrolled version because that's already recursive so err, that's good I guess. Can't really think how to make this totally suck now because the problem is that we have to maintain the staticness of the schema so we can't really weaken. if r = Code then r1 = Identity if r = Identity then r1 = Code or Identity continuation which statically knows the argument (r1 = Identity) or not. r1 = Identity; r = Code r = Identity; r1 = Identity traceShow q Unrolled le, rec r Rec le, unrolled r r1 = Code; r = Identity If r1 = Code then we can't use the unrolled versions as we don't know the schema. We can only unroll the loop. ("query", query) , ("query2", query2) ("queryJoin", queryJoin) putStrLn $ pprint expr
# LANGUAGE TemplateHaskell # # LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE KindSignatures # # LANGUAGE DataKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeApplications # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE InstanceSigs # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # module LMS where import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.ByteString (ByteString) import Control.Monad import Data.List import Data.Maybe import Language.Haskell.TH import Language.Haskell.TH.Syntax import Prelude hiding (Applicative(..)) import Instances.TH.Lift () import Data . FileEmbed import Data.Functor.Identity import Control.Applicative (liftA2) import System.IO.Unsafe import qualified Prelude as P import GHC.TypeLits import Control.Applicative (liftA3) import Instances.TH.Lift import Criterion import Criterion.Main import System.IO.Silently import System.Mem import Debug.Trace import System.IO for = flip map class Ops r where eq :: Eq a => r a -> r a -> r Bool neq :: Eq a => r a -> r a -> r Bool bc_split :: r Char -> r ByteString -> r [ByteString] tail_dropwhile :: Char -> r ByteString -> r ByteString take_while :: Char -> r ByteString -> r ByteString _if :: r Bool -> r a -> r a -> r a _caseString :: r ByteString -> r a -> r a -> r a _fix :: (r a -> r a) -> r a _lam :: (r a -> r b) -> r (a -> b) _bind :: Monad m => r (m a) -> (r (a -> m b)) -> r (m b) _print :: Show a => r a -> r Res _putStr :: r ByteString -> r Res _hPutStr :: r Handle -> r ByteString -> r Res (>>>) :: Monoid m => r m -> r m -> r m _empty :: Monoid m => r m _pure :: P.Applicative f => r a -> r (f a) Scanner interface _newScanner :: FilePath -> r (IO Scanner) _hasNext :: r Scanner -> r Bool _nextLine :: r Scanner -> (r ByteString, r Scanner) pure :: Lift a => a -> r a (<*>) :: r (a -> b) -> r a -> r b _case_record :: r (Record r1) -> r ((Fields r1) -> Schema -> c) -> r c _lup :: r ByteString -> r (Fields r1) -> r Schema -> r (r1 ByteString) _intersect :: Eq a => r [a] -> r [a] -> r [a] _mkRecord :: r (Fields r1) -> r Schema -> r (Record r1) _cons :: r a -> r [a] -> r [a] infixl 4 <*> newtype Code a = Code (Q (TExp a)) instance Ops Code where eq (Code e1) (Code e2) = Code [|| $$e1 == $$e2 ||] neq (Code e1) (Code e2) = Code [|| $$e1 /= $$e2 ||] bc_split (Code e1) (Code e2) = Code [|| BC.split $$e1 $$e2 ||] _if (Code a) (Code b) (Code c) = Code [|| if $$a then $$b else $$c ||] _caseString (Code a) (Code b) (Code c) = Code [|| case $$a of "" -> $$b _ -> $$c ||] (>>>) (Code a) (Code b) = Code [|| $$a <> $$b ||] _bind (Code a) (Code b) = Code [|| $$a >>= $$b ||] _empty = Code [|| mempty ||] _pure (Code p) = Code [|| P.pure $$p ||] _print (Code a) = Code [|| print $$a ||] _putStr (Code a) = Code [|| BC.putStr $$a ||] _hPutStr (Code a) (Code b) = Code [|| BC.hPutStr $$a $$b ||] tail_dropwhile c (Code b) = Code [|| BC.tail (BC.dropWhile (/= c) $$b) ||] take_while c (Code b) = Code [|| BC.takeWhile (/= c) $$b ||] _fix f = Code [|| fix (\a -> $$(runCode $ f (Code [||a||]))) ||] _lam f = Code $ [|| \a -> $$(runCode $ f (Code [|| a ||])) ||] _newScanner fp = Code [|| newScanner fp ||] _hasNext s = Code [|| hasNext $$(runCode s) ||] _nextLine = _nextLineCode pure = Code . unsafeTExpCoerce . lift (Code f) <*> (Code a) = Code [|| $$f $$a ||] _case_record (Code r) (Code k1) = Code [|| case $$r of Record rs ss -> $$(k1) rs ss ||] _lup (Code l1) (Code l2) (Code l3) = Code [|| lup $$l1 $$l2 $$l3 ||] _intersect (Code l1) (Code l2) = Code [|| $$l1 `intersect` $$l2 ||] _mkRecord (Code l1) (Code l2) = Code [|| Record $$l1 $$l2 ||] _cons (Code l1) (Code l2) = Code [|| $$l1 : $$l2 ||] instance Ops Identity where eq = liftA2 (==) neq = liftA2 (/=) bc_split = liftA2 (BC.split) tail_dropwhile c = fmap (BC.tail . (BC.dropWhile (/= c))) take_while c = fmap (BC.takeWhile (/= c)) _print = fmap print _putStr = fmap (BC.putStr) _hPutStr = liftA2 BC.hPut _empty = Identity mempty _if (Identity b) (Identity c1) (Identity c2) = Identity (if b then c1 else c2) _fix = fix _lam f = Identity (\a -> runIdentity (f (Identity a))) (>>>) = liftA2 mappend _bind = liftA2 (>>=) _pure = fmap (P.pure) _newScanner fp = Identity (newScanner fp) _hasNext = fmap hasNext _nextLine = nextLine pure = Identity (<*>) (Identity a1) (Identity a2) = Identity (a1 a2) _case_record (Identity r) (Identity k) = case r of Record rs ss -> Identity (k rs ss) _lup = liftA3 lup _intersect = liftA2 intersect _mkRecord = liftA2 Record _cons = liftA2 (:) _when :: (Monoid m, Ops r) => r Bool -> r m -> r m _when cond act = _if cond act _empty _whenA :: (P.Applicative f, Ops r) => r Bool -> r (f ()) -> r (f ()) _whenA cond act = _if cond act (_pure (pure ())) runCode :: Code a -> Q (TExp a) runCode (Code a) = a type Fields r = [r ByteString] type Schema = [ByteString] type Table = FilePath type Res = IO () data Record r = Record { fields :: Fields r, schema :: Schema } getField :: Ops r1 => r1 ByteString -> r1 (Record r) -> r1 (r ByteString) getField field r = _case_record r (_lam $ \fs -> _lam $ \sch -> _lup field fs sch) lup :: ByteString -> Fields r -> Schema -> r ByteString lup field fs sch = let i = fromJust (elemIndex field sch) in (fs !! i) getFields : : [ ByteString ] - > Record r - > [ r ByteString ] getFields fs r = map ( flip r ) fs data Operator = Scan FilePath Schema | Project Schema Schema Operator | Filter Predicate Operator | Join Operator Operator deriving (Lift, Show) cols n = take (2 ^ n) [BC.pack('f':show n) | n <- [0..]] fp c n = "data/data-" ++ show (10^n) ++ "-" ++ show (2 ^ c) ++ ".csv" queryP, queryJoin, queryLast, query, query2 :: Int -> Int -> Operator query c n = Project ["f0"] ["f0"] (Filter (Eq (Value "a") (Field "f0")) (Scan (fp c n) (cols c))) query2 c n = Project ["f0"] ["f0"] (Filter (Eq (Value "a") (Field "f0")) (Scan (fp c n) (cols c))) queryJoin c n = Join (Scan (fp c n) (cols c)) (Scan (fp c n) (cols c)) queryP c n = Project ["f0"] ["f0"] (Scan (fp c n) (cols c)) queryLast c n = let cs = cols c in Project [last cs] [last cs] (Scan (fp c n) cs) data Predicate = Eq Ref Ref | Ne Ref Ref deriving (Show, Lift) data Ref = Field ByteString | Value ByteString deriving (Show, Lift) type QTExp a = Code a fix :: (a -> a) -> a fix f = let x = f x in x data Scanner = Scanner ByteString newScanner :: FilePath -> IO Scanner newScanner fp = Scanner <$> B.readFile fp nextLine :: Identity Scanner -> (Identity ByteString, Identity Scanner) nextLine (Identity (Scanner bs)) = let (fs, rs) = BC.span (/= '\n') bs in (Identity fs, Identity (Scanner (BC.tail rs))) _nextLineCode :: Code Scanner -> (Code ByteString, Code Scanner) _nextLineCode scanner = let fs = Code [|| let (Scanner s) = $$(runCode scanner) in BC.takeWhile (/= '\n') s ||] ts = Code [|| let (Scanner s) = $$(runCode scanner) in Scanner (BC.tail (BC.dropWhile (/= '\n') s)) ||] in (fs, ts) hasNext :: Scanner -> Bool hasNext (Scanner bs) = bs /= "" while :: (Ops r, Monoid m) => r (t -> Bool) -> r ((t -> IO m) -> t -> IO m) -> r (t -> IO m) while k b = _fix (\r -> _lam $ \rs -> _when (k <*> rs) (b <*> r <*> rs)) whenM :: Monoid m => Bool -> m -> m whenM b act = if b then act else mempty type family ResT r1 r2 :: * -> * where ResT Identity Code = Code ResT Code Identity = Code ResT Identity r = r processCSV :: forall m r r1 . (Monoid m, O r1 r) => Schema -> FilePath -> (r1 (Record r) -> (ResT r1 r) (IO m)) -> (ResT r1 r) (IO m) processCSV ss f yld = _newScanner f `_bind` rows ss where rows :: Schema -> (ResT r1 r) (Scanner -> (IO m)) rows sch = do while (_lam _hasNext) (_lam $ \r -> _lam $ \rs -> (let (hs, ts) = _nextLine rs rec = _mkRecord (parseRow sch hs) (pure sch) in yld rec >>> (r <*> ts)) ) parseRow :: Schema -> (ResT r1 r) ByteString -> r1 [r ByteString] parseRow [] _ = _empty parseRow [_] b = weaken (take_while '\n' b) `_cons` _empty parseRow (_:ss') b = let new = tail_dropwhile ',' b rs = parseRow ss' new in weaken (take_while ',' b) `_cons` rs class Weaken r1 r where weaken :: (ResT r1 r) a -> r1 (r a) instance Weaken Code Identity where weaken (Code c) = Code [|| Identity $$c ||] instance Weaken Identity i where weaken i = Identity i printFields :: Ops r => r Handle -> Fields r -> r Res printFields _ [] = _empty printFields h [x] = _hPutStr h x >>> _hPutStr h (pure "\n") printFields h (x:xs) = _hPutStr h x >>> _hPutStr h (pure ",") >>> printFields h xs class Collapse r1 r2 where c :: r1 (r2 a) -> (ResT r1 r2) a instance Collapse Identity r where c (Identity a) = a instance Collapse Code Identity where c (Code c) = Code [|| runIdentity $$c ||] type O r1 r = (Collapse r1 r , Ops r , Ops (ResT r1 r) , Ops r1 , Weaken r1 r) evalPred :: forall r1 r . (O r1 r) => Predicate -> r1 (Record r) -> (ResT r1 r) Bool evalPred predicate rec = case predicate of Eq a b -> eq (evalRef a rec) (evalRef b rec) Ne a b -> neq (evalRef a rec) (evalRef b rec) evalRef :: (Collapse r1 r , Ops r , Ops (ResT r1 r) , Ops r1 ) => Ref -> r1 (Record r) -> (ResT r1 r) ByteString evalRef (Value a) _ = pure a evalRef (Field name) r = c $ getField (pure name) r class O r1 r => ListEq (s :: Symbol) r r1 where list_eq :: (Eq a) => r1 [r a] -> r1 [r a] -> (ResT r1 r) Bool class O r1 r => Restrict (s :: Symbol) r r1 where restrict :: Ops r => r1 (Record r) -> Schema -> Schema -> r1 (Record r) Point of this instance is that we can use the normal ` map ` in order to instance Restrict "unrolled" Code Identity where restrict r newSchema parentSchema | length parentSchema <= 10 = let ns = map Identity parentSchema nfs = sequence $ map (flip getField r) ns in Record <$> nfs <*> Identity newSchema restrict r newSchema parentSchema = restrict @"recursive" r newSchema parentSchema Record < $ > ( map ( flip r ) parentSchema ) < * > _ instance Restrict s Identity Identity where restrict rec newSchema parentSchema = let ns = map Identity parentSchema r = map (runIdentity . flip getField rec) ns in Identity $ Record r parentSchema instance Restrict "recursive" Identity Code where restrict :: Code (Record Identity) -> Schema -> Schema -> Code (Record Identity) restrict rec news ps = let ns = map pure ps r = map (flip getField rec) ns in Code [|| Record $$(runCode $ spillL r) ps ||] instance Restrict "recursive" Code Identity where restrict :: Identity (Record Code) -> Schema -> Schema -> Identity (Record Code) restrict (Identity rec) new ps = let fs = fields rec fs' = map (getField2 fs ps) (map pure ps) getField' = getField2 in Identity (Record fs' new) getField2 :: Fields Code -> Schema -> Code ByteString -> Code ByteString getField2 fields ps lup_field = Code [|| runIdentity $ lup $$(runCode lup_field) $$(runCode $ spill2 fields) ps ||] One of my favourite functions <3 spillL :: [Code a] -> Code [a] spillL [] = Code [|| [] ||] spillL (x:xs) = Code [|| $$(runCode x) : $$(runCode $ spillL xs) ||] spillQ :: [Q (TExp a)] -> Q (TExp [a]) spillQ [] = [|| [] ||] spillQ (x:xs) = [|| $$x : $$(spillQ xs) ||] instance ListEq "unrolled" Code Identity where list_eq :: (Eq a) => Identity [Code a] -> Identity [Code a] -> Code Bool list_eq (Identity xs) (Identity ys) = let lxs = length xs lys = length ys in if max lxs lys <= 10 then list_eq_r xs ys else list_eq @"recursive" (Identity xs) (Identity ys) list_eq_r [] [] = pure True list_eq_r (v:vs) (v1:v1s) = _if (eq v v1) (list_eq_r vs v1s) (pure False) list_eq_r _ _ = pure False instance ListEq s Identity Identity where list_eq :: (Eq a) => Identity [Identity a] -> Identity [Identity a] -> Identity Bool list_eq xs ys = Identity (xs == ys) instance ListEq "recursive" Identity Code where list_eq :: Eq a => Code [Identity a] -> Code [Identity a] -> Code Bool list_eq (Code xs) (Code ys) = Code [|| $$(xs) == $$(ys) ||] pull :: [Code a] -> Code [a] pull [] = Code [|| [] ||] pull (x:xs) = Code [|| $$(runCode x) : $$(runCode $ pull xs) ||] instance ListEq "recursive" Code Identity where list_eq :: (Eq a) => Identity [Code a] -> Identity [Code a] -> Code Bool list_eq (Identity xs) (Identity ys) = Code [|| $$(runCode $ pull xs) == $$(runCode $ pull ys) ||] Having two type parameters means that we can either choose to use a execOp :: forall restrict le r r1 m . ( Restrict restrict r r1 , ListEq le r r1 , Monoid m , Ops r , Ops r1) => Operator -> (r1 (Record r) -> (ResT r1 r) (IO m)) -> (ResT r1 r) (IO m) execOp op yld = case op of Scan file sch -> processCSV sch file yld Filter predicate parent -> execOp @restrict @le parent (\rec -> _if (evalPred @r1 @r predicate rec) (yld rec) _empty ) Project newSchema parentSchema parent -> execOp @restrict @le parent (\rec -> yld (restrict @restrict rec newSchema parentSchema )) Join left right -> execOp @restrict @le left (\rec -> execOp @restrict @le right (\rec' -> let k1 = _schema rec k2 = _fields rec keys = _intersect (_schema rec) (_schema rec') leq = list_eq @le @r @r1 @ByteString k2 (_fields rec') in _when leq (yld (_mkRecord (_fields rec >>> _fields rec') (_schema rec >>> _schema rec') )))) _fields r = _case_record r (_lam $ \fs -> _lam $ \_ -> fs) _schema r = _case_record r (_lam $ \_ -> _lam $ \ss -> ss) execOpU :: forall r r1 m . (Monoid m, O r r1 , Restrict "unrolled" r r1 , ListEq "unrolled" r r1) => Operator -> (r1 (Record r) -> (ResT r1 r) (IO m)) -> (ResT r1 r) (IO m) execOpU = execOp @"unrolled" @"unrolled" print_k h = (\r -> Code [|| $$(runCode $ printFields h (fields (runIdentity r))) ||]) wrap :: Code (Handle -> IO ()) -> Code (IO ()) wrap (Code c) = Code [|| withFile "/dev/null" WriteMode $$c ||] runQuery :: Operator -> Q (TExp ( Res)) runQuery q = runCode $ wrap (Code [|| \h -> $$(runCode $ execOpU q (print_k (Code [|| h ||]))) ||]) runQueryUnstaged :: Operator -> ( Res) runQueryUnstaged q = withFile "/dev/null" WriteMode (\handle -> runIdentity (execOpU q (\r -> Identity ( runIdentity (printFields (Identity handle) (fields (runIdentity r))))))) runQueryUnstagedC :: Operator -> Q (TExp ( Res)) runQueryUnstagedC q = [|| runQueryUnstaged q ||] runQueryUR :: Operator -> Q (TExp ( Res)) runQueryUR q = runCode $ wrap (Code [|| \h -> $$(runCode $ execOp @"unrolled" @"recursive" q (print_k (Code [|| h ||]))) ||]) runQueryRU :: Operator -> Q (TExp ( Res)) runQueryRU q = runCode $ wrap (_lam $ \h -> execOp @"recursive" @"unrolled" q (print_k h)) Rec le , rec r runQueryRR :: Operator -> Q (TExp ( Res)) runQueryRR q = runCode $ wrap (_lam $ \h -> execOp @"recursive" @"recursive" q (print_k h)) runQueryDynamic :: Operator -> Q (TExp ( Res)) runQueryDynamic q = runCode ( wrap (_lam $ \h -> execOp @"recursive" @"recursive" @Identity @Code q (printFields17 h))) ("queryP", queryP) , ("queryLast", queryLast)] runners = [ ("best", runQuery) , ("ur", runQueryUR) , ("ru", runQueryRU) , ("rr", runQueryRR) , ("dynamic", runQueryDynamic) , ("unstaged", runQueryUnstagedC) ] files = [(n, c) | n <- [3..3], c <- [1..3] ] genBench :: Q (TExp [Benchmark]) genBench = spillQ $ for runners $ \(name, r) -> [|| bgroup name $$(spillQ $ for queries $ \(qname, q) -> [|| bgroup qname $ $$(spillQ $ for files $ \(n, c) -> [|| let b = $$(r (q c n)) in bench $$(runCode $ pure $ fp c n) $ perBatchEnv (const performGC) (\() -> b) ||]) ||]) ||] printFields17 :: (Code Handle) -> Code (Record Identity) -> Code (IO ()) printFields17 (Code h) (Code c) = Code [|| runIdentity $ printFields (Identity $$h) (fields $$(c)) ||] spill :: Record Code -> Code (Record Identity) spill (Record rs ss) = Code [|| Record $$(runCode $ spill2 rs) ss ||] spill2 :: [Code ByteString] -> Code [Identity ByteString] spill2 [] = Code [|| [] ||] spill2 (x:xs) = Code [|| (Identity $$(runCode x)) : $$(runCode $ spill2 xs) ||] runQueryUnstagedL :: Operator -> IO [Record Identity] runQueryUnstagedL q = runIdentity (execOpU @Identity @Identity q (return . return . return . runIdentity)) test :: IO () test = do processCSV " data / test.csv " ( print . " name " ) expr < - runQ $ unTypeQ $ runCode $ execOpU query ( printFields . fields ) expr < - runQ $ unTypeQ $ power print "" bsToExp :: B.ByteString -> Q Exp bsToExp bs = do helper <- [| stringToBs |] let chars = BC.unpack . BC.tail . (BC.dropWhile (/= '\n')) $ bs return $! AppE helper $! LitE $! StringL chars stringToBs :: String -> B.ByteString stringToBs = BC.pack
b8e9cecdd3722ce70a937cee4fe747889a95b06531394dc3ba52c2120e88a0fb
haskell-opengl/GLUT
ReadImage.hs
ReadImage.hs ( adapted from readImage.c which is ( c ) Silicon Graphics , Inc. ) Copyright ( c ) 2002 - 2018 < > This file is part of HOpenGL and distributed under a BSD - style license See the file libraries / GLUT / LICENSE Support for reading a file of raw RGB data : 4 bytes big - endian width 4 bytes big - endian height width * height RGB byte triples ReadImage.hs (adapted from readImage.c which is (c) Silicon Graphics, Inc.) Copyright (c) Sven Panne 2002-2018 <> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE Support for reading a file of raw RGB data: 4 bytes big-endian width 4 bytes big-endian height width * height RGB byte triples -} module ReadImage ( readImage ) where import Data.Word ( Word8, Word32 ) import Control.Exception ( bracket ) import Control.Monad ( when ) import System.IO ( Handle, IOMode(ReadMode), openBinaryFile, hGetBuf, hClose ) import System.IO.Error ( mkIOError, eofErrorType ) import Foreign ( Ptr, alloca, mallocBytes, Storable(..) ) import Graphics.UI.GLUT -- This is probably overkill, but anyway... newtype Word32BigEndian = Word32BigEndian Word32 word32BigEndianToGLsizei :: Word32BigEndian -> GLsizei word32BigEndianToGLsizei (Word32BigEndian x) = fromIntegral x instance Storable Word32BigEndian where sizeOf ~(Word32BigEndian x) = sizeOf x alignment ~(Word32BigEndian x) = alignment x peek ptr = do let numBytes = sizeOf (undefined :: Word32BigEndian) bytes <- mapM (peekByteOff ptr) [ 0 .. numBytes - 1 ] :: IO [Word8] let value = foldl (\val byte -> val * 256 + fromIntegral byte) 0 bytes return $ Word32BigEndian value poke = error "" -- This is the reason for all this stuff above... readGLsizei :: Handle -> IO GLsizei readGLsizei handle = alloca $ \buf -> do hGetBufFully handle buf (sizeOf (undefined :: Word32BigEndian)) fmap word32BigEndianToGLsizei $ peek buf A handy variant of hGetBuf with additional error checking hGetBufFully :: Handle -> Ptr a -> Int -> IO () hGetBufFully handle ptr numBytes = do bytesRead <- hGetBuf handle ptr numBytes when (bytesRead /= numBytes) $ ioError $ mkIOError eofErrorType "hGetBufFully" (Just handle) Nothing -- Closing a file is nice, even when an error occurs during reading. withBinaryFile :: FilePath -> (Handle -> IO a) -> IO a withBinaryFile filePath = bracket (openBinaryFile filePath ReadMode) hClose readImage :: FilePath -> IO (Size, PixelData a) readImage filePath = withBinaryFile filePath $ \handle -> do width <- readGLsizei handle height <- readGLsizei handle let numBytes = fromIntegral (3 * width * height) buf <- mallocBytes numBytes hGetBufFully handle buf numBytes return (Size width height, PixelData RGB UnsignedByte buf)
null
https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/RedBook4/ReadImage.hs
haskell
This is probably overkill, but anyway... This is the reason for all this stuff above... Closing a file is nice, even when an error occurs during reading.
ReadImage.hs ( adapted from readImage.c which is ( c ) Silicon Graphics , Inc. ) Copyright ( c ) 2002 - 2018 < > This file is part of HOpenGL and distributed under a BSD - style license See the file libraries / GLUT / LICENSE Support for reading a file of raw RGB data : 4 bytes big - endian width 4 bytes big - endian height width * height RGB byte triples ReadImage.hs (adapted from readImage.c which is (c) Silicon Graphics, Inc.) Copyright (c) Sven Panne 2002-2018 <> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE Support for reading a file of raw RGB data: 4 bytes big-endian width 4 bytes big-endian height width * height RGB byte triples -} module ReadImage ( readImage ) where import Data.Word ( Word8, Word32 ) import Control.Exception ( bracket ) import Control.Monad ( when ) import System.IO ( Handle, IOMode(ReadMode), openBinaryFile, hGetBuf, hClose ) import System.IO.Error ( mkIOError, eofErrorType ) import Foreign ( Ptr, alloca, mallocBytes, Storable(..) ) import Graphics.UI.GLUT newtype Word32BigEndian = Word32BigEndian Word32 word32BigEndianToGLsizei :: Word32BigEndian -> GLsizei word32BigEndianToGLsizei (Word32BigEndian x) = fromIntegral x instance Storable Word32BigEndian where sizeOf ~(Word32BigEndian x) = sizeOf x alignment ~(Word32BigEndian x) = alignment x peek ptr = do let numBytes = sizeOf (undefined :: Word32BigEndian) bytes <- mapM (peekByteOff ptr) [ 0 .. numBytes - 1 ] :: IO [Word8] let value = foldl (\val byte -> val * 256 + fromIntegral byte) 0 bytes return $ Word32BigEndian value poke = error "" readGLsizei :: Handle -> IO GLsizei readGLsizei handle = alloca $ \buf -> do hGetBufFully handle buf (sizeOf (undefined :: Word32BigEndian)) fmap word32BigEndianToGLsizei $ peek buf A handy variant of hGetBuf with additional error checking hGetBufFully :: Handle -> Ptr a -> Int -> IO () hGetBufFully handle ptr numBytes = do bytesRead <- hGetBuf handle ptr numBytes when (bytesRead /= numBytes) $ ioError $ mkIOError eofErrorType "hGetBufFully" (Just handle) Nothing withBinaryFile :: FilePath -> (Handle -> IO a) -> IO a withBinaryFile filePath = bracket (openBinaryFile filePath ReadMode) hClose readImage :: FilePath -> IO (Size, PixelData a) readImage filePath = withBinaryFile filePath $ \handle -> do width <- readGLsizei handle height <- readGLsizei handle let numBytes = fromIntegral (3 * width * height) buf <- mallocBytes numBytes hGetBufFully handle buf numBytes return (Size width height, PixelData RGB UnsignedByte buf)
8a8d51da038ee78070915f15d12ada96cce66f1d166c37c9fe1d22e483c2a8ee
uhc/uhc
IORef.hs
# LANGUAGE NoImplicitPrelude , CPP # # OPTIONS_GHC -XNoImplicitPrelude # ----------------------------------------------------------------------------- -- | -- Module : Data.IORef Copyright : ( c ) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- Mutable references in the IO monad . -- ----------------------------------------------------------------------------- module Data.IORef ( * IORefs abstract , instance of : , newIORef, -- :: a -> IO (IORef a) readIORef, -- :: IORef a -> IO a writeIORef, -- :: IORef a -> a -> IO () modifyIORef, -- :: IORef a -> (a -> a) -> IO () atomicModifyIORef, -- :: IORef a -> (a -> (a,b)) -> IO b #if !defined(__PARALLEL_HASKELL__) && defined(__GLASGOW_HASKELL__) mkWeakIORef, -- :: IORef a -> IO () -> IO (Weak (IORef a)) #endif ) where #ifdef __HUGS__ import Hugs.IORef #endif #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.STRef import GHC.IOBase #if !defined(__PARALLEL_HASKELL__) import GHC.Weak #endif #endif /* __GLASGOW_HASKELL__ */ #ifdef __NHC__ import NHC.IOExtras ( IORef , newIORef , readIORef , writeIORef , excludeFinalisers ) #endif #ifdef __UHC__ import UHC.MutVar import UHC.STRef import UHC.IOBase import UHC.Base #endif #if defined(__GLASGOW_HASKELL__) && !defined(__PARALLEL_HASKELL__) -- |Make a 'Weak' pointer to an 'IORef' mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a)) mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s -> case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #) #endif -- |Mutate the contents of an 'IORef' modifyIORef :: IORef a -> (a -> a) -> IO () modifyIORef ref f = readIORef ref >>= writeIORef ref . f -- |Atomically modifies the contents of an 'IORef'. -- -- This function is useful for using 'IORef' in a safe way in a multithreaded -- program. If you only have one 'IORef', then using 'atomicModifyIORef' to -- access and modify it will prevent race conditions. -- -- Extending the atomicity to multiple 'IORef's is problematic, so it -- is recommended that if you need to do anything more complicated then using ' Control . Concurrent . MVar . MVar ' instead is a good idea . -- atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b #if defined(__GLASGOW_HASKELL__) atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s #elif defined(__UHC__) atomicModifyIORef (IORef (STRef r)) f = IO $ \s -> atomicModifyMutVar r f s atomicModifyIORef ( IORef ( STRef r ) ) f = ioFromPrim ( \s - > case atomicModifyMutVar r f s of { ( _ , r ' ) - > r ' } ) #elif defined(__HUGS__) atomicModifyIORef = plainModifyIORef -- Hugs has no preemption where plainModifyIORef r f = do a <- readIORef r case f a of (a',b) -> writeIORef r a' >> return b #elif defined(__NHC__) atomicModifyIORef r f = excludeFinalisers $ do a <- readIORef r let (a',b) = f a writeIORef r a' return b #endif
null
https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/ehclib/uhcbase/Data/IORef.hs
haskell
--------------------------------------------------------------------------- | Module : Data.IORef License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable --------------------------------------------------------------------------- :: a -> IO (IORef a) :: IORef a -> IO a :: IORef a -> a -> IO () :: IORef a -> (a -> a) -> IO () :: IORef a -> (a -> (a,b)) -> IO b :: IORef a -> IO () -> IO (Weak (IORef a)) |Make a 'Weak' pointer to an 'IORef' |Mutate the contents of an 'IORef' |Atomically modifies the contents of an 'IORef'. This function is useful for using 'IORef' in a safe way in a multithreaded program. If you only have one 'IORef', then using 'atomicModifyIORef' to access and modify it will prevent race conditions. Extending the atomicity to multiple 'IORef's is problematic, so it is recommended that if you need to do anything more complicated Hugs has no preemption
# LANGUAGE NoImplicitPrelude , CPP # # OPTIONS_GHC -XNoImplicitPrelude # Copyright : ( c ) The University of Glasgow 2001 Mutable references in the IO monad . module Data.IORef ( * IORefs abstract , instance of : , #if !defined(__PARALLEL_HASKELL__) && defined(__GLASGOW_HASKELL__) #endif ) where #ifdef __HUGS__ import Hugs.IORef #endif #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.STRef import GHC.IOBase #if !defined(__PARALLEL_HASKELL__) import GHC.Weak #endif #endif /* __GLASGOW_HASKELL__ */ #ifdef __NHC__ import NHC.IOExtras ( IORef , newIORef , readIORef , writeIORef , excludeFinalisers ) #endif #ifdef __UHC__ import UHC.MutVar import UHC.STRef import UHC.IOBase import UHC.Base #endif #if defined(__GLASGOW_HASKELL__) && !defined(__PARALLEL_HASKELL__) mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a)) mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s -> case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #) #endif modifyIORef :: IORef a -> (a -> a) -> IO () modifyIORef ref f = readIORef ref >>= writeIORef ref . f then using ' Control . Concurrent . MVar . MVar ' instead is a good idea . atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b #if defined(__GLASGOW_HASKELL__) atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s #elif defined(__UHC__) atomicModifyIORef (IORef (STRef r)) f = IO $ \s -> atomicModifyMutVar r f s atomicModifyIORef ( IORef ( STRef r ) ) f = ioFromPrim ( \s - > case atomicModifyMutVar r f s of { ( _ , r ' ) - > r ' } ) #elif defined(__HUGS__) where plainModifyIORef r f = do a <- readIORef r case f a of (a',b) -> writeIORef r a' >> return b #elif defined(__NHC__) atomicModifyIORef r f = excludeFinalisers $ do a <- readIORef r let (a',b) = f a writeIORef r a' return b #endif
0e535643872df48a78b24ab66353a51d07e3c9c2eec5154ff41c904d668beb3f
code54/buildversion-plugin
mojo.clj
(ns buildversion-plugin.mojo "Buildversion Maven Plugin" (:use clojure.maven.mojo.defmojo) (:require [clojure.maven.mojo.log :as log] [buildversion-plugin.git :as git])) (defn- eval-custom-script [properties snippet-str] (let [props-as-bindings (vec (mapcat (fn [[k v]] [(symbol (name k)) v]) properties)) snippet (read-string snippet-str)] (eval `(let ~props-as-bindings ~snippet)))) (defmojo BuildVersionMojo {:goal "set-properties" :phase "initialize" } ;; Mojo parameters [project {:expression "${project}" :required true :readonly true} base-dir {:expression "${basedir}" :required true :readonly true} tstamp-format {:alias "tstampFormat" :default "yyyyMMddHHmmss" :typename "java.lang.String"} custom-script {:alias "customProperties" :typename "java.lang.String"} git-cmd {:alias "gitCmd" :default "git" :typename "java.lang.String"} ] ;; Goal execution (let [log-fn #(.debug log/*plexus-log* (str "[buildversion-plugin] " %)) inferred-props (git/infer-project-version base-dir {:tstamp-format tstamp-format :git-cmd (or git-cmd "git") :debug-fn log-fn } ) final-props (if custom-script (merge inferred-props (eval-custom-script inferred-props custom-script)) inferred-props) maven-project-props (.getProperties project)] (log-fn "Setting properties: ") (doseq [[prop value] final-props] (log-fn (str (name prop) ": " value)) (.put maven-project-props (name prop) value)))) ;; injecting project version does not work well :-( ; (if-let [ver (:build-tag final-props)] ; (.setVersion project))
null
https://raw.githubusercontent.com/code54/buildversion-plugin/c4666f4c4e22a9b8b572b97962fdec4ddd8f11de/src/main/clojure/buildversion_plugin/mojo.clj
clojure
Mojo parameters Goal execution injecting project version does not work well :-( (if-let [ver (:build-tag final-props)] (.setVersion project))
(ns buildversion-plugin.mojo "Buildversion Maven Plugin" (:use clojure.maven.mojo.defmojo) (:require [clojure.maven.mojo.log :as log] [buildversion-plugin.git :as git])) (defn- eval-custom-script [properties snippet-str] (let [props-as-bindings (vec (mapcat (fn [[k v]] [(symbol (name k)) v]) properties)) snippet (read-string snippet-str)] (eval `(let ~props-as-bindings ~snippet)))) (defmojo BuildVersionMojo {:goal "set-properties" :phase "initialize" } [project {:expression "${project}" :required true :readonly true} base-dir {:expression "${basedir}" :required true :readonly true} tstamp-format {:alias "tstampFormat" :default "yyyyMMddHHmmss" :typename "java.lang.String"} custom-script {:alias "customProperties" :typename "java.lang.String"} git-cmd {:alias "gitCmd" :default "git" :typename "java.lang.String"} ] (let [log-fn #(.debug log/*plexus-log* (str "[buildversion-plugin] " %)) inferred-props (git/infer-project-version base-dir {:tstamp-format tstamp-format :git-cmd (or git-cmd "git") :debug-fn log-fn } ) final-props (if custom-script (merge inferred-props (eval-custom-script inferred-props custom-script)) inferred-props) maven-project-props (.getProperties project)] (log-fn "Setting properties: ") (doseq [[prop value] final-props] (log-fn (str (name prop) ": " value)) (.put maven-project-props (name prop) value))))
55eb415149770be33b79582d6a855b3c4a101d2005a4eeaeedf3340d521bc6d5
stathissideris/spec-provider
merge_test.cljc
(ns spec-provider.merge-test (:require [spec-provider.merge :as m] [clojure.test :refer [deftest testing is]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest] [spec-provider.stats :as st])) (stest/instrument [`merge-with-fns `merge-pred-stats `merge-pred-map `merge-stats]) ;; (alias 'stc 'clojure.spec.test.check) ;; (deftest test-check ( binding [ s/*recursion - limit * 3 ] ;; (stest/check [`merge-with-fns ;; `merge-pred-stats ;; `merge-pred-map ;; `merge-stats] { : : stc / opts { : num - tests 1 } } ) ) ) (deftest test-merge-stats (is (= #::st {:name "foo" :sample-count 45 :distinct-values #{:c :b :a} :keys {:a #::st {:name "bar" :sample-count 1 :distinct-values #{"bar-val"} :pred-map {string? #::st {:sample-count 1}}} :b #::st {:name "baz" :sample-count 1 :distinct-values #{"baz-val"} :pred-map {string? #::st {:sample-count 1}}}} :pred-map {string? #::st{:sample-count 35 :min 1 :max 100 :min-length 0 :max-length 20}} :hit-distinct-values-limit true :hit-key-size-limit false :elements [:a :b :c]} (m/merge-stats #::st {:name "foo" :sample-count 10 :distinct-values #{:a :b} :keys {:a #::st {:name "bar" :sample-count 1 :distinct-values #{"bar-val"} :pred-map {string? #::st {:sample-count 1}}}} :pred-map {string? #::st{:sample-count 15 :min 2 :max 80 :min-length 0 :max-length 18}} :hit-distinct-values-limit true :hit-key-size-limit false :elements [:a :b]} #::st {:name "foo" :sample-count 35 :distinct-values #{:c} :keys {:b #::st {:name "baz" :sample-count 1 :distinct-values #{"baz-val"} :pred-map {string? #::st {:sample-count 1}}}} :pred-map {string? #::st{:sample-count 20 :min 1 :max 100 :min-length 10 :max-length 20}} :hit-distinct-values-limit false :hit-key-size-limit false :elements [:c]}))))
null
https://raw.githubusercontent.com/stathissideris/spec-provider/f9e4b3a9a54752a1c2c8df0291ff517679442a1a/test/spec_provider/merge_test.cljc
clojure
(alias 'stc 'clojure.spec.test.check) (deftest test-check (stest/check [`merge-with-fns `merge-pred-stats `merge-pred-map `merge-stats]
(ns spec-provider.merge-test (:require [spec-provider.merge :as m] [clojure.test :refer [deftest testing is]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest] [spec-provider.stats :as st])) (stest/instrument [`merge-with-fns `merge-pred-stats `merge-pred-map `merge-stats]) ( binding [ s/*recursion - limit * 3 ] { : : stc / opts { : num - tests 1 } } ) ) ) (deftest test-merge-stats (is (= #::st {:name "foo" :sample-count 45 :distinct-values #{:c :b :a} :keys {:a #::st {:name "bar" :sample-count 1 :distinct-values #{"bar-val"} :pred-map {string? #::st {:sample-count 1}}} :b #::st {:name "baz" :sample-count 1 :distinct-values #{"baz-val"} :pred-map {string? #::st {:sample-count 1}}}} :pred-map {string? #::st{:sample-count 35 :min 1 :max 100 :min-length 0 :max-length 20}} :hit-distinct-values-limit true :hit-key-size-limit false :elements [:a :b :c]} (m/merge-stats #::st {:name "foo" :sample-count 10 :distinct-values #{:a :b} :keys {:a #::st {:name "bar" :sample-count 1 :distinct-values #{"bar-val"} :pred-map {string? #::st {:sample-count 1}}}} :pred-map {string? #::st{:sample-count 15 :min 2 :max 80 :min-length 0 :max-length 18}} :hit-distinct-values-limit true :hit-key-size-limit false :elements [:a :b]} #::st {:name "foo" :sample-count 35 :distinct-values #{:c} :keys {:b #::st {:name "baz" :sample-count 1 :distinct-values #{"baz-val"} :pred-map {string? #::st {:sample-count 1}}}} :pred-map {string? #::st{:sample-count 20 :min 1 :max 100 :min-length 10 :max-length 20}} :hit-distinct-values-limit false :hit-key-size-limit false :elements [:c]}))))
68cfbd29236b36f24c46d3a350a9276c8d23d306022b54cbfae9fb7f5ec069f7
Abhiroop/okasaki
FloydWarshall.hs
module FloydWarshall where import Data.IntMap.Strict as Map hiding (foldl',foldr) import Data.List This is n't a purely functional data structure . But contains a purely functional implementation of the Floyd Warshall 's shortest path algorithm . -- The representation of the graph is a map of each node to a map of its adjacent node to its weight. type Vertex = Int type Weight = Int type Graph = IntMap (IntMap Weight) weight :: Graph -> Vertex -> Vertex -> Maybe Weight weight g i j = do jmap <- Map.lookup i g Map.lookup j jmap shortestPaths :: [Vertex] -> Graph -> Graph shortestPaths vs g = foldl' update g vs where update :: Graph -> Vertex -> Graph update g k = mapWithKey shortmap g where shortmap :: Key -> IntMap Weight -> IntMap Weight shortmap i jmap = foldr shortest Map.empty vs where shortest j m = case (old,new) of (Nothing, Nothing) -> m (Nothing, Just w ) -> Map.insert j w m (Just w, Nothing) -> Map.insert j w m (Just w1, Just w2) -> Map.insert j (min w1 w2) m where old = Map.lookup j jmap new = do w1 <- weight g i k w2 <- weight g k j return (w1+w2)
null
https://raw.githubusercontent.com/Abhiroop/okasaki/b4e8b6261cf9c44b7b273116be3da6efde76232d/src/FloydWarshall.hs
haskell
The representation of the graph is a map of each node to a map of its adjacent node to its weight.
module FloydWarshall where import Data.IntMap.Strict as Map hiding (foldl',foldr) import Data.List This is n't a purely functional data structure . But contains a purely functional implementation of the Floyd Warshall 's shortest path algorithm . type Vertex = Int type Weight = Int type Graph = IntMap (IntMap Weight) weight :: Graph -> Vertex -> Vertex -> Maybe Weight weight g i j = do jmap <- Map.lookup i g Map.lookup j jmap shortestPaths :: [Vertex] -> Graph -> Graph shortestPaths vs g = foldl' update g vs where update :: Graph -> Vertex -> Graph update g k = mapWithKey shortmap g where shortmap :: Key -> IntMap Weight -> IntMap Weight shortmap i jmap = foldr shortest Map.empty vs where shortest j m = case (old,new) of (Nothing, Nothing) -> m (Nothing, Just w ) -> Map.insert j w m (Just w, Nothing) -> Map.insert j w m (Just w1, Just w2) -> Map.insert j (min w1 w2) m where old = Map.lookup j jmap new = do w1 <- weight g i k w2 <- weight g k j return (w1+w2)
f273fa7d5fbf832bc0767b1efa4651f39e43488a2dca2b29f050aa5eff74d96c
elben/neblen
Tests.hs
module Neblen.Eval.Tests where import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit ((@?=)) import Control.Monad.Trans.State import Control.Monad.Trans.Except import qualified Data.Map.Strict as M import Neblen.Eval import Neblen.Data import Neblen.Parser tests :: Test tests = testGroup "Neblen.Eval.Tests" $ concat [ testLit , testUnaryApp ] testLit :: [Test] testLit = [ testCase "eval: 1" $ (eval' M.empty (Lit (IntV 1))) @?= (Lit (IntV 1)) , testCase "eval: true" $ (eval' M.empty (Lit (BoolV True))) @?= (Lit (BoolV True)) , testCase "eval: \"hello\"" $ (eval' M.empty (Lit (StringV "hello"))) @?= (Lit (StringV "hello")) ] testUnaryApp :: [Test] testUnaryApp = [ testCase "eval: (((fn [x] (fn [y] y)) 10) 20) => 20" $ (eval' M.empty (p "(((fn [x] (fn [y] y)) 10) 20)")) @?= (Lit (IntV 20)) , testCase "eval: ((fn [x y] (x y)) (fn [a] a) 3) => 3" $ (eval' M.empty (p "((fn [x y] (x y)) (fn [a] a) 3)")) @?= (Lit (IntV 3)) , testCase "eval: ((fn [x y z] (x y z)) (fn [a] a) (fn [b] b) 3) => 3" $ (eval' M.empty (p "((fn [x y z] (x y z)) (fn [a] a) (fn [b] b) 3)")) @?= (Lit (IntV 3)) ] eval ' M.empty ( UnaryApp ( UnaryApp ( Fun ( Var " x " ) ( Fun ( Var " y " ) ( UnaryApp ( Var " x " ) ( Var " y " ) ) ) ) ( Fun ( Var " a " ) ( Var " a " ) ) ) ( Lit ( IntV 3 ) ) ) eval ' M.empty ( UnaryApp ( UnaryApp ( UnaryApp ( Fun ( Var " x " ) ( Fun ( Var " y " ) ( Fun ( Var " z " ) ( UnaryApp ( UnaryApp ( Var " x " ) ( Var " y " ) ) ( Var " z " ) ) ) ) ) ( Fun ( Var " a " ) ( Var " a " ) ) ) ( Fun ( Var " b " ) ( Var " b " ) ) ) ( Lit ( IntV 3 ) ) ) p :: NeblenProgram -> Exp p np = case parseProgram np of Left _ -> error "wrong program" Right e -> e
null
https://raw.githubusercontent.com/elben/neblen/3a586c212613cd5e731788605b4f8ae1e86ed9f5/tests/Neblen/Eval/Tests.hs
haskell
module Neblen.Eval.Tests where import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit ((@?=)) import Control.Monad.Trans.State import Control.Monad.Trans.Except import qualified Data.Map.Strict as M import Neblen.Eval import Neblen.Data import Neblen.Parser tests :: Test tests = testGroup "Neblen.Eval.Tests" $ concat [ testLit , testUnaryApp ] testLit :: [Test] testLit = [ testCase "eval: 1" $ (eval' M.empty (Lit (IntV 1))) @?= (Lit (IntV 1)) , testCase "eval: true" $ (eval' M.empty (Lit (BoolV True))) @?= (Lit (BoolV True)) , testCase "eval: \"hello\"" $ (eval' M.empty (Lit (StringV "hello"))) @?= (Lit (StringV "hello")) ] testUnaryApp :: [Test] testUnaryApp = [ testCase "eval: (((fn [x] (fn [y] y)) 10) 20) => 20" $ (eval' M.empty (p "(((fn [x] (fn [y] y)) 10) 20)")) @?= (Lit (IntV 20)) , testCase "eval: ((fn [x y] (x y)) (fn [a] a) 3) => 3" $ (eval' M.empty (p "((fn [x y] (x y)) (fn [a] a) 3)")) @?= (Lit (IntV 3)) , testCase "eval: ((fn [x y z] (x y z)) (fn [a] a) (fn [b] b) 3) => 3" $ (eval' M.empty (p "((fn [x y z] (x y z)) (fn [a] a) (fn [b] b) 3)")) @?= (Lit (IntV 3)) ] eval ' M.empty ( UnaryApp ( UnaryApp ( Fun ( Var " x " ) ( Fun ( Var " y " ) ( UnaryApp ( Var " x " ) ( Var " y " ) ) ) ) ( Fun ( Var " a " ) ( Var " a " ) ) ) ( Lit ( IntV 3 ) ) ) eval ' M.empty ( UnaryApp ( UnaryApp ( UnaryApp ( Fun ( Var " x " ) ( Fun ( Var " y " ) ( Fun ( Var " z " ) ( UnaryApp ( UnaryApp ( Var " x " ) ( Var " y " ) ) ( Var " z " ) ) ) ) ) ( Fun ( Var " a " ) ( Var " a " ) ) ) ( Fun ( Var " b " ) ( Var " b " ) ) ) ( Lit ( IntV 3 ) ) ) p :: NeblenProgram -> Exp p np = case parseProgram np of Left _ -> error "wrong program" Right e -> e
363ec252b62f7343125d75fecbc78dbfe40444a508f412b685b8140165255b6b
osa1/sc-plugin
Foldr.hs
module Main where -- optimizes fine (with -O) sum_foldr :: [Int] -> Int sum_foldr = foldr (+) 0 -- optimizes fine (with -O) and_foldr :: [Bool] -> Bool and_foldr = foldr (&&) True -- decimal_foldr :: Int -> Int decimal_foldr = foldr ( \d x - > ( fromInteger d + x ) / 10 ) 0 this is pretty awesome , GHC optimizes this to i d with -O. I think there are -- multiple passes involved in this, but I'm not sure exactly which passes. id_foldr :: [a] -> [a] id_foldr = foldr (:) [] -- optimizes fine with -O length_foldr :: [a] -> Int length_foldr = foldr (\x n -> 1 + n) 0 -- optimizes fine with -O map_foldr :: (a -> b) -> [a] -> [b] map_foldr f = foldr ((:) . f) [] -- optimizes fine with -O filter_foldr :: (a -> Bool) -> [a] -> [a] filter_foldr p = foldr (\x xs -> if p x then x : xs else xs) [] -- optimizes fine with -O concat_foldr :: [[a]] -> [a] concat_foldr = foldr (++) [] -- optimizes fine, but quadratic. TODO: Is it possible to improve this somehow? reverse_foldr :: [a] -> [a] reverse_foldr = foldr snoc [] where snoc x xs = xs ++ [x] -- THIS IS RIDICULOUS!! this is compiled to (++). How is this even possible? -- (with -O) app_foldr :: [a] -> [a] -> [a] app_foldr xs ys = foldr (:) ys xs inits :: [a] -> [[a]] inits = foldr (\x xss -> [] : map (x:) xss) [[]] tails :: [a] -> [[a]] tails = foldr (\x xss -> (x : head xss) : xss) [[]] main :: IO () main = do let lsti = [1, 2, 3] lstb = [True, True, False] print $ sum_foldr lsti print $ and_foldr lstb print $ id_foldr lsti print $ length_foldr lsti print $ map_foldr (+1) lsti print $ filter_foldr even lsti print $ concat_foldr [lsti, lsti] print $ reverse_foldr lsti print $ app_foldr lsti lsti print $ inits lsti print $ tails lsti
null
https://raw.githubusercontent.com/osa1/sc-plugin/1969ad81f16ca8ed8110ca8dadfccf6f3d463635/examples/Foldr.hs
haskell
optimizes fine (with -O) optimizes fine (with -O) decimal_foldr :: Int -> Int multiple passes involved in this, but I'm not sure exactly which passes. optimizes fine with -O optimizes fine with -O optimizes fine with -O optimizes fine with -O optimizes fine, but quadratic. TODO: Is it possible to improve this somehow? THIS IS RIDICULOUS!! this is compiled to (++). How is this even possible? (with -O)
module Main where sum_foldr :: [Int] -> Int sum_foldr = foldr (+) 0 and_foldr :: [Bool] -> Bool and_foldr = foldr (&&) True decimal_foldr = foldr ( \d x - > ( fromInteger d + x ) / 10 ) 0 this is pretty awesome , GHC optimizes this to i d with -O. I think there are id_foldr :: [a] -> [a] id_foldr = foldr (:) [] length_foldr :: [a] -> Int length_foldr = foldr (\x n -> 1 + n) 0 map_foldr :: (a -> b) -> [a] -> [b] map_foldr f = foldr ((:) . f) [] filter_foldr :: (a -> Bool) -> [a] -> [a] filter_foldr p = foldr (\x xs -> if p x then x : xs else xs) [] concat_foldr :: [[a]] -> [a] concat_foldr = foldr (++) [] reverse_foldr :: [a] -> [a] reverse_foldr = foldr snoc [] where snoc x xs = xs ++ [x] app_foldr :: [a] -> [a] -> [a] app_foldr xs ys = foldr (:) ys xs inits :: [a] -> [[a]] inits = foldr (\x xss -> [] : map (x:) xss) [[]] tails :: [a] -> [[a]] tails = foldr (\x xss -> (x : head xss) : xss) [[]] main :: IO () main = do let lsti = [1, 2, 3] lstb = [True, True, False] print $ sum_foldr lsti print $ and_foldr lstb print $ id_foldr lsti print $ length_foldr lsti print $ map_foldr (+1) lsti print $ filter_foldr even lsti print $ concat_foldr [lsti, lsti] print $ reverse_foldr lsti print $ app_foldr lsti lsti print $ inits lsti print $ tails lsti
4b23c1ed750ebaf385c71db58cd6c7c0fdf81e1af5dca2ca1752423a695bb0c6
blockapps/eth-pruner
Prune.hs
# OPTIONS_GHC -fno - warn - orphans # {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Prune where import Control.Exception hiding (catch) import Control.Monad (when) import Control.Monad.Catch import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as B import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Char8 as BC import Data.Default import Data.Maybe (catMaybes) import Data.Monoid import qualified Database.LevelDB as DB import Database import Prune.Types import Blockchain.Data.RLP import Blockchain.Database.MerklePatricia.NodeData (NodeData (..), NodeRef (..)) import Blockchain.Database.MerklePatricia.StateRoot (StateRoot (..)) prune :: (DB.MonadResource m, MonadCatch m) => String -> String -> Int -> m () prune originDir toDir bn = do inDB <- DB.open originDir def outDB <- DB.open toDir def{DB.createIfMissing=True} let blockNums = if bn < 15 then [0..bn] else [(15-bn)..bn] mStateRootsAndBlockHashes <- liftIO (sequence <$> mapM (stateRootAndHashFromBlockNumber inDB) blockNums) case mStateRootsAndBlockHashes of Just stateRootsAndBlockHashes -> do let (_,targetBH) = last stateRootsAndBlockHashes stateRoots = map fst stateRootsAndBlockHashes backupBlocksTransactionsMiscData inDB outDB targetBH liftIO $ do privSRs <- catMaybes <$> mapM (getPrivateStateRoot inDB) stateRoots mapM_ (copyMPTFromStateRoot inDB outDB) stateRoots mapM_ (copyMPTFromStateRoot inDB outDB) privSRs Nothing -> liftIO . putStrLn $ "Issue finding stateroots and hash of blocks" return () getPrivateStateRoot :: DB.DB -> StateRoot -> IO (Maybe StateRoot) getPrivateStateRoot db (StateRoot sr) = (StateRoot <$>) <$> getValByKey db ("P" <> sr) stateRootAndHashFromBlockNumber :: DB.DB -> Int -> IO (Maybe (StateRoot, B.ByteString)) stateRootAndHashFromBlockNumber db bn = do let key = "h" <> B.pack (leftPad 8 0 [fromIntegral bn]) <> "n" mBlockHash <- getValByKey db key case mBlockHash of Nothing -> do liftIO . putStrLn $ "Block " <> show bn <> " not found." return Nothing Just bh -> do mSR <- stateRootFromBlockHash bh case mSR of Nothing -> return Nothing Just sr -> return . Just $ (sr,bh) where stateRootFromBlockHash bh = do let key = "h" <> B.pack (leftPad 8 0 [fromIntegral bn]) <> bh mblockBodyRLP <- getValByKey db key case mblockBodyRLP of Nothing -> return Nothing Just blockBodyRLP -> let blockHeader = rlpDecode . rlpDeserialize $ blockBodyRLP :: BlockHeader in return . Just $ stateRoot blockHeader backupBlocksTransactionsMiscData :: (DB.MonadResource m, MonadCatch m) => DB.DB -> DB.DB -> B.ByteString -> m () backupBlocksTransactionsMiscData inDB outDB bh = do iter <- DB.iterOpen inDB def liftIO $ do insertToLvlDB outDB "LastHeader" bh insertToLvlDB outDB "LastBlock" bh insertToLvlDB outDB "LastFast" bh ldbForEach iter $ \key val -> case getFirst . foldMap (\v -> First $ BC.stripPrefix v key) $ [ "secure-key-" , "ethereum-config-" , "BlockchainVersion" , "mipmap-log-bloom-" , "receipts-" ] of Just _ -> insertToLvlDB outDB key val Nothing -> case BC.length key of totalDifficulty : headerPrefix(1 ) + num ( uint64 big endian)(8 ) + hash(32 ) + tdSuffix(1 ) 42 -> insertToLvlDB outDB key val blockHeader : headerPrefix(1 ) + num ( uint64 big endian)(8 ) + hash(32 ) blockBody : bodyPrefix(1 ) + num ( uint64 big endian)(8 ) + hash(32 ) blockReciept : ) + num ( uint64 big endian)(8 ) + hash(32 ) 41 -> insertToLvlDB outDB key val 33 -> case BC.length val of blockNumber : ) + hash(32 ) - > blockNumber(8 ) 8 -> insertToLvlDB outDB key val _ -> case BC.unpack . B16.encode $ B.drop 32 key of -- transactionMetadata: hash(32) + txMetaSuffix(1) "01" -> do let hash = BC.take 32 key mTx <- getValByKey inDB hash case mTx of Just tx -> do insertToLvlDB outDB key val insertToLvlDB outDB hash tx Nothing -> putStrLn $ "Missing Transaction" <> (BC.unpack . B16.encode $ hash) -- privateRoot: privateRootPrefix(1) + hash(32) _ -> insertToLvlDB outDB key val blockHash : headerPrefix(1 ) + num ( uint64 big endian)(8 ) + numSuffix(1 ) privateBlockBloom : bloomPrefix(2 ) + num ( uint64 big endian)(8 ) 10 -> when (key /= "LastHeader") (insertToLvlDB outDB key val) _ -> return () copyMPTFromStateRoot :: DB.DB -> DB.DB -> StateRoot -> IO () copyMPTFromStateRoot inDB outDB = recCopyMPT where recCopyMPT (StateRoot sr) = do let key = sr mVal <- getValByKey inDB sr case mVal of Nothing -> return () Just val -> do insertToLvlDB outDB key val mNodeData <- catch (Just <$> liftIO (evaluate (rlpDecode $ rlpDeserialize val::NodeData))) (\ (_ :: IOException) -> return Nothing) case mNodeData of Just nd -> handleNodeData nd Nothing -> return () handleNodeData = \case ShortcutNodeData { nextVal= Left (PtrRef sr') } -> recCopyMPT sr' ShortcutNodeData { nextVal= Right (RLPString rlpData )} -> do mAddrState <- catch (Just <$> liftIO (evaluate (rlpDecode $ rlpDeserialize rlpData::AddressState))) (\ (_ :: SomeException) -> return Nothing) case mAddrState of Just as -> handleAddressState as Nothing -> return () FullNodeData {choices=nodeRefs} -> do _ <- mapM (\nr -> case nr of PtrRef sr' -> recCopyMPT sr' _ -> return () ) nodeRefs return () _ -> return () handleAddressState as = do let codeHash = addressStateCodeHash as mCode <- getValByKey inDB codeHash case mCode of Just code -> do insertToLvlDB outDB codeHash code recCopyMPT (addressStateContractRoot as) Nothing -> return () leftPad :: Int -> a -> [a] -> [a] leftPad n x xs = replicate (max 0 (n - length xs)) x ++ xs
null
https://raw.githubusercontent.com/blockapps/eth-pruner/513fcc884c93974a29b380ca80669dc0aebec125/src_backup_withthreads/Prune.hs
haskell
# LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # transactionMetadata: hash(32) + txMetaSuffix(1) privateRoot: privateRootPrefix(1) + hash(32)
# OPTIONS_GHC -fno - warn - orphans # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # module Prune where import Control.Exception hiding (catch) import Control.Monad (when) import Control.Monad.Catch import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as B import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Char8 as BC import Data.Default import Data.Maybe (catMaybes) import Data.Monoid import qualified Database.LevelDB as DB import Database import Prune.Types import Blockchain.Data.RLP import Blockchain.Database.MerklePatricia.NodeData (NodeData (..), NodeRef (..)) import Blockchain.Database.MerklePatricia.StateRoot (StateRoot (..)) prune :: (DB.MonadResource m, MonadCatch m) => String -> String -> Int -> m () prune originDir toDir bn = do inDB <- DB.open originDir def outDB <- DB.open toDir def{DB.createIfMissing=True} let blockNums = if bn < 15 then [0..bn] else [(15-bn)..bn] mStateRootsAndBlockHashes <- liftIO (sequence <$> mapM (stateRootAndHashFromBlockNumber inDB) blockNums) case mStateRootsAndBlockHashes of Just stateRootsAndBlockHashes -> do let (_,targetBH) = last stateRootsAndBlockHashes stateRoots = map fst stateRootsAndBlockHashes backupBlocksTransactionsMiscData inDB outDB targetBH liftIO $ do privSRs <- catMaybes <$> mapM (getPrivateStateRoot inDB) stateRoots mapM_ (copyMPTFromStateRoot inDB outDB) stateRoots mapM_ (copyMPTFromStateRoot inDB outDB) privSRs Nothing -> liftIO . putStrLn $ "Issue finding stateroots and hash of blocks" return () getPrivateStateRoot :: DB.DB -> StateRoot -> IO (Maybe StateRoot) getPrivateStateRoot db (StateRoot sr) = (StateRoot <$>) <$> getValByKey db ("P" <> sr) stateRootAndHashFromBlockNumber :: DB.DB -> Int -> IO (Maybe (StateRoot, B.ByteString)) stateRootAndHashFromBlockNumber db bn = do let key = "h" <> B.pack (leftPad 8 0 [fromIntegral bn]) <> "n" mBlockHash <- getValByKey db key case mBlockHash of Nothing -> do liftIO . putStrLn $ "Block " <> show bn <> " not found." return Nothing Just bh -> do mSR <- stateRootFromBlockHash bh case mSR of Nothing -> return Nothing Just sr -> return . Just $ (sr,bh) where stateRootFromBlockHash bh = do let key = "h" <> B.pack (leftPad 8 0 [fromIntegral bn]) <> bh mblockBodyRLP <- getValByKey db key case mblockBodyRLP of Nothing -> return Nothing Just blockBodyRLP -> let blockHeader = rlpDecode . rlpDeserialize $ blockBodyRLP :: BlockHeader in return . Just $ stateRoot blockHeader backupBlocksTransactionsMiscData :: (DB.MonadResource m, MonadCatch m) => DB.DB -> DB.DB -> B.ByteString -> m () backupBlocksTransactionsMiscData inDB outDB bh = do iter <- DB.iterOpen inDB def liftIO $ do insertToLvlDB outDB "LastHeader" bh insertToLvlDB outDB "LastBlock" bh insertToLvlDB outDB "LastFast" bh ldbForEach iter $ \key val -> case getFirst . foldMap (\v -> First $ BC.stripPrefix v key) $ [ "secure-key-" , "ethereum-config-" , "BlockchainVersion" , "mipmap-log-bloom-" , "receipts-" ] of Just _ -> insertToLvlDB outDB key val Nothing -> case BC.length key of totalDifficulty : headerPrefix(1 ) + num ( uint64 big endian)(8 ) + hash(32 ) + tdSuffix(1 ) 42 -> insertToLvlDB outDB key val blockHeader : headerPrefix(1 ) + num ( uint64 big endian)(8 ) + hash(32 ) blockBody : bodyPrefix(1 ) + num ( uint64 big endian)(8 ) + hash(32 ) blockReciept : ) + num ( uint64 big endian)(8 ) + hash(32 ) 41 -> insertToLvlDB outDB key val 33 -> case BC.length val of blockNumber : ) + hash(32 ) - > blockNumber(8 ) 8 -> insertToLvlDB outDB key val _ -> case BC.unpack . B16.encode $ B.drop 32 key of "01" -> do let hash = BC.take 32 key mTx <- getValByKey inDB hash case mTx of Just tx -> do insertToLvlDB outDB key val insertToLvlDB outDB hash tx Nothing -> putStrLn $ "Missing Transaction" <> (BC.unpack . B16.encode $ hash) _ -> insertToLvlDB outDB key val blockHash : headerPrefix(1 ) + num ( uint64 big endian)(8 ) + numSuffix(1 ) privateBlockBloom : bloomPrefix(2 ) + num ( uint64 big endian)(8 ) 10 -> when (key /= "LastHeader") (insertToLvlDB outDB key val) _ -> return () copyMPTFromStateRoot :: DB.DB -> DB.DB -> StateRoot -> IO () copyMPTFromStateRoot inDB outDB = recCopyMPT where recCopyMPT (StateRoot sr) = do let key = sr mVal <- getValByKey inDB sr case mVal of Nothing -> return () Just val -> do insertToLvlDB outDB key val mNodeData <- catch (Just <$> liftIO (evaluate (rlpDecode $ rlpDeserialize val::NodeData))) (\ (_ :: IOException) -> return Nothing) case mNodeData of Just nd -> handleNodeData nd Nothing -> return () handleNodeData = \case ShortcutNodeData { nextVal= Left (PtrRef sr') } -> recCopyMPT sr' ShortcutNodeData { nextVal= Right (RLPString rlpData )} -> do mAddrState <- catch (Just <$> liftIO (evaluate (rlpDecode $ rlpDeserialize rlpData::AddressState))) (\ (_ :: SomeException) -> return Nothing) case mAddrState of Just as -> handleAddressState as Nothing -> return () FullNodeData {choices=nodeRefs} -> do _ <- mapM (\nr -> case nr of PtrRef sr' -> recCopyMPT sr' _ -> return () ) nodeRefs return () _ -> return () handleAddressState as = do let codeHash = addressStateCodeHash as mCode <- getValByKey inDB codeHash case mCode of Just code -> do insertToLvlDB outDB codeHash code recCopyMPT (addressStateContractRoot as) Nothing -> return () leftPad :: Int -> a -> [a] -> [a] leftPad n x xs = replicate (max 0 (n - length xs)) x ++ xs
cc9a66df96d5b9283849d03585ee518a9b57966082d3c60c573d336d49365781
2600hz/kazoo
knm_search.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(knm_search). -behaviour(gen_listener). -export([start_link/0]). -export([init/1 ,handle_call/3 ,handle_cast/2 ,handle_info/2 ,handle_event/2 ,terminate/2 ,code_change/3 ]). -export([find/1 ,next/1 ,discovery/1, discovery/2 ,quantity/1 ,prefix/1, prefix/2 ,normalized_prefix/1, normalized_prefix/2 ,query_options/1, query_options/2 ,dialcode/1 ,country/1 ,offset/1 ,query_id/1 ,account_id/1 ,reseller_id/1 ]). -include("knm.hrl"). -type option() :: {'quantity', pos_integer()} | {'prefix', kz_term:ne_binary()} | {'dialcode', kz_term:ne_binary()} | {'country', knm_util:country_iso3166a2()} | {'offset', non_neg_integer()} | {'blocks', boolean()} | %% FIXME: knm_managed.erl:76: The test ` < < _ : 8,_:_*8 > > = : = undefined ' %% can never evaluate to `true' {'account_id', kz_term:api_ne_binary()} | {'query_id', kz_term:ne_binary()} | {'reseller_id', kz_term:api_ne_binary()}. %% Same dialyzer warning -type result() :: {kz_term:ne_binary(), {kz_term:ne_binary(), module(), kz_term:ne_binary(), kz_json:object()}}. -type results() :: [result()]. -type mod_response() :: kz_either:either(kz_term:ne_binary() | atom(), results()) | {'bulk', results()}. -type options() :: [option()]. -export_type([option/0, options/0 ,results/0 ,result/0 ,mod_response/0 ]). -define(MAX_SEARCH, kapps_config:get_pos_integer(?KNM_CONFIG_CAT, <<"maximum_search_quantity">>, 500)). -define(NUMBER_SEARCH_TIMEOUT ,kapps_config:get_pos_integer(?KNM_CONFIG_CAT, <<"number_search_timeout_ms">>, 5 * ?MILLISECONDS_IN_SECOND) ). -define(POLLING_INTERVAL, 5000). -define(EOT, '$end_of_table'). -type state() :: #{node => kz_term:ne_binary() ,cache => ets:tid() | atom() }. -define(ETS_DISCOVERY_CACHE, 'knm_discovery_cache'). -define(ETS_DISCOVERY_CACHE_OPTIONS, ['bag', 'named_table', {'read_concurrency', 'true'}]). -define(BINDINGS, [{'self', []} ,{'discovery', ['federate']} ]). -define(RESPONDERS, []). -define(QUEUE_NAME, <<>>). -define(QUEUE_OPTIONS, []). -define(CONSUME_OPTIONS, []). %%------------------------------------------------------------------------------ %% @doc Starts the server. %% @end %%------------------------------------------------------------------------------ -spec start_link() -> kz_types:startlink_ret(). -ifdef(TEST). start_link() -> gen_listener:start_link({'local', ?MODULE} ,?MODULE ,[] ,[]). -else. start_link() -> gen_listener:start_link({'local', ?MODULE} ,?MODULE ,[{'bindings', ?BINDINGS} ,{'responders', ?RESPONDERS} ,{'queue_name', ?QUEUE_NAME} ,{'queue_options', ?QUEUE_OPTIONS} ,{'consume_options', ?CONSUME_OPTIONS} ] ,[]). -endif. %%%============================================================================= %%% gen_server callbacks %%%============================================================================= %%------------------------------------------------------------------------------ %% @doc Initializes the server. %% @end %%------------------------------------------------------------------------------ -spec init([]) -> {'ok', state(), timeout()}. init([]) -> State = #{node => kz_term:to_binary(node()) ,cache => ets:new(?ETS_DISCOVERY_CACHE, ?ETS_DISCOVERY_CACHE_OPTIONS) }, {'ok', State, ?POLLING_INTERVAL}. %%------------------------------------------------------------------------------ %% @doc Handling call messages. %% @end %%------------------------------------------------------------------------------ -spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()). handle_call({'first', Options}, _From, State) -> QueryId = query_id(Options), flush(QueryId), {'reply', next(Options), State, ?POLLING_INTERVAL}; handle_call(_Request, _From, State) -> {'reply', {'error', 'not_implemented'}, State, ?POLLING_INTERVAL}. %%------------------------------------------------------------------------------ %% @doc Handling cast messages. %% @end %%------------------------------------------------------------------------------ -spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()). handle_cast({'gen_listener',{'created_queue', Queue}}, State) -> {'noreply', State#{queue => Queue}, ?POLLING_INTERVAL}; handle_cast({'gen_listener',{'is_consuming',_IsConsuming}}, State) -> {'noreply', State}; handle_cast({'gen_listener',{'federators_consuming', _AreFederatorsConsuming}}, State) -> {'noreply', State}; handle_cast({'reset_search',QID}, #{cache := Cache} = State) -> lager:debug("resetting query id ~s", [QID]), ets:delete(Cache, QID), {'noreply', State, ?POLLING_INTERVAL}; handle_cast({'add_result', Numbers}, #{cache := Cache} = State) -> ets:insert(Cache, Numbers), {'noreply', State, ?POLLING_INTERVAL}; handle_cast(_Msg, State) -> lager:debug("unhandled cast: ~p", [_Msg]), {'noreply', State, ?POLLING_INTERVAL}. %%------------------------------------------------------------------------------ %% @doc Handling all non call/cast messages. %% @end %%------------------------------------------------------------------------------ -spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()). handle_info(_Info, State) -> {'noreply', State, ?POLLING_INTERVAL}. -spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return(). handle_event(JObj, #{node := Node}) -> _ = case kz_api:node(JObj) =/= Node andalso kz_api:event_name(JObj) of <<"flush">> -> kz_process:spawn(fun handle_flush/1, [JObj]); <<"request">> -> kz_process:spawn(fun handle_search/1, [JObj]); <<"number">> -> kz_process:spawn(fun handle_number/1, [JObj]); _ -> 'ok' end, 'ignore'. %%------------------------------------------------------------------------------ %% @doc This function is called by a `gen_server' when it is about to %% terminate. It should be the opposite of `Module:init/1' and do any %% necessary cleaning up. When it returns, the `gen_server' terminates with . The return value is ignored . %% %% @end %%------------------------------------------------------------------------------ -spec terminate(any(), state()) -> 'ok'. terminate(_Reason, #{}) -> lager:debug("terminating number search : ~p", [_Reason]). %%------------------------------------------------------------------------------ %% @doc Convert process state when code is changed. %% @end %%------------------------------------------------------------------------------ -spec code_change(any(), state(), any()) -> {'ok', state()}. code_change(_OldVsn, State, _Extra) -> {'ok', State}. %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec flush(kz_term:ne_binary()) -> 'ok'. -ifdef(TEST). flush(_QID) -> 'ok'. -else. flush(QID) -> Payload = [{<<"Query-ID">>, QID} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], kz_amqp_worker:cast(Payload, fun kapi_discovery:publish_flush/1). -endif. -spec find(options()) -> kz_json:objects(). find(Options) -> find(Options, offset(Options)). find(Options, 0) -> first(Options); find(Options, _) -> do_find(Options, is_local(query_id(Options))). do_find(Options, 'true') -> next(Options); do_find(Options, 'false') -> Payload = [{<<"Query-ID">>, query_id(Options)} ,{<<"Prefix">>, normalized_prefix(Options)} ,{<<"Quantity">>, quantity(Options)} ,{<<"Offset">>, offset(Options)} ,{<<"Account-ID">>, account_id(Options)} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], case kz_amqp_worker:call(Payload ,fun kapi_discovery:publish_req/1 ,fun kapi_discovery:resp_v/1 ) of {'ok', JObj} -> kapi_discovery:results(JObj); {'error', _Error} -> lager:debug("error requesting search from amqp: ~p", [_Error]), [] end. -spec first(options()) -> kz_json:objects(). first(Options) -> Carriers = knm_carriers:available_carriers(Options), lager:debug("contacting, in order: ~p", [Carriers]), QID = query_id(Options), gen_listener:cast(?MODULE, {'reset_search', QID}), Self = self(), Opts = [{'quantity', ?MAX_SEARCH} ,{'offset', 0} ,{'normalized_prefix', normalized_prefix(Options)} | Options ], lists:foreach(fun(Carrier) -> search_spawn(Self, Carrier, Opts) end, Carriers), wait_for_search(length(Carriers)), gen_listener:call(?MODULE, {'first', Options}). -spec search_spawn(pid(), atom(), kz_term:proplist()) -> any(). search_spawn(Pid, Carrier, Options) -> F = fun() -> Pid ! {Carrier, search_carrier(Carrier, Options)} end, kz_process:spawn(F). -spec search_carrier(atom(), kz_term:proplist()) -> any(). search_carrier(Carrier, Options) -> Prefix = normalized_prefix(Options), Quantity = quantity(Options), catch (Carrier:find_numbers(Prefix, Quantity, Options)). -spec wait_for_search(integer()) -> 'ok'. wait_for_search(0) -> 'ok'; wait_for_search(N) -> receive {_Carrier, {'ok', []}} -> lager:debug("~s found no numbers", [_Carrier]), wait_for_search(N - 1); {_Carrier, {'ok', Numbers}} -> lager:debug("~s found numbers", [_Carrier]), gen_listener:cast(?MODULE, {'add_result', Numbers}), wait_for_search(N - 1); {_Carrier, {'bulk', Numbers}} -> lager:debug("~s found bulk numbers", [_Carrier]), gen_listener:cast(?MODULE, {'add_result', Numbers}), wait_for_search(N - 1); {_Carrier, {'error', 'not_available'}} -> lager:debug("~s had no results", [_Carrier]), wait_for_search(N - 1); _Other -> lager:debug("unexpected search result ~p", [_Other]), wait_for_search(N - 1) after ?NUMBER_SEARCH_TIMEOUT -> lager:debug("timeout (~B) collecting responses from search providers", [?NUMBER_SEARCH_TIMEOUT]), wait_for_search(N - 1) end. -spec next(options()) -> kz_json:objects(). next(Options) -> QID = query_id(Options), Quantity = quantity(Options), Offset = offset(Options), MatchSpec = [{{QID,'$1'},[],['$1']}], QLH = qlc:keysort(1, ets:table(?ETS_DISCOVERY_CACHE, [{'traverse', {'select', MatchSpec}}])), QLC = qlc:cursor(QLH), _ = Offset > 0 andalso qlc:next_answers(QLC, Offset), Results = qlc:next_answers(QLC, Quantity), qlc:delete_cursor(QLC), lager:debug("returning ~B results", [length(Results)]), [kz_json:from_list( [{<<"number">>, Num} ,{<<"state">>, State} ]) || {Num, _ModuleName, State, _CarrierData} <- Results ]. %%------------------------------------------------------------------------------ %% @doc Create a number in a discovery state. %% @end %%------------------------------------------------------------------------------ -ifndef(TEST). -spec create_discovery(kz_term:ne_binary(), module(), kz_json:object(), knm_options:options()) -> knm_phone_number:record(). create_discovery(DID=?NE_BINARY, Carrier, Data, Options0) -> Options = [{'state', ?NUMBER_STATE_DISCOVERY} ,{'module_name', kz_term:to_binary(Carrier)} | Options0 ], {'ok', PhoneNumber} = knm_phone_number:setters(knm_phone_number:from_number_with_options(DID, Options) ,[{fun knm_phone_number:set_carrier_data/2, Data}] ), PhoneNumber. -spec create_discovery(kz_json:object(), knm_options:options()) -> knm_phone_number:record(). create_discovery(JObj, Options) -> knm_phone_number:from_json_with_options(JObj, Options). -endif. -spec quantity(options()) -> pos_integer(). quantity(Options) -> Quantity = props:get_integer_value('quantity', Options, 1), min(Quantity, ?MAX_SEARCH). -spec prefix(options()) -> kz_term:ne_binary(). prefix(Options) -> props:get_ne_binary_value('prefix', Options). -spec prefix(options(), kz_term:ne_binary()) -> kz_term:ne_binary(). prefix(Options, Default) -> props:get_ne_binary_value('prefix', Options, Default). -spec query_options(options()) -> kz_term:api_object(). query_options(Options) -> props:get_value('query_options', Options). -spec query_options(options(), kz_term:api_object()) -> kz_term:api_object(). query_options(Options, Default) -> props:get_value('query_options', Options, Default). -spec normalized_prefix(options()) -> kz_term:ne_binary(). normalized_prefix(Options) -> JObj = query_options(Options, kz_json:new()), Dialcode = dialcode(Options), Prefix = kz_json:get_ne_binary_value(<<"Prefix">>, JObj, prefix(Options)), normalized_prefix(Options, <<Dialcode/binary, Prefix/binary>>). -spec normalized_prefix(options(), kz_term:ne_binary()) -> kz_term:ne_binary(). normalized_prefix(Options, Default) -> props:get_ne_binary_value('normalized_prefix', Options, Default). -spec dialcode(options()) -> kz_term:ne_binary(). dialcode(Options) -> Default = knm_util:prefix_for_country(country(Options)), props:get_ne_binary_value('dialcode', Options, Default). -spec country(options()) -> knm_util:country_iso3166a2(). country(Options) -> case props:get_ne_binary_value('country', Options, ?KNM_DEFAULT_COUNTRY) of <<_:8, _:8>>=Country -> Country; _Else -> lager:debug("~p is not iso3166a2, using default"), ?KNM_DEFAULT_COUNTRY end. -spec query_id(options()) -> kz_term:api_binary(). query_id(Options) -> props:get_ne_binary_value('query_id', Options). -spec offset(options()) -> non_neg_integer(). offset(Options) -> props:get_integer_value('offset', Options, 0). -spec account_id(options()) -> kz_term:api_ne_binary(). account_id(Options) -> props:get_value('account_id', Options). -spec reseller_id(options()) -> kz_term:api_ne_binary(). reseller_id(Options) -> props:get_value('reseller_id', Options). -spec is_local(kz_term:ne_binary()) -> boolean(). is_local(QID) -> ets:match_object(?ETS_DISCOVERY_CACHE, {QID, '_'}) =/= []. -spec discovery(kz_term:ne_binary()) -> {'ok', knm_phone_number:record()} | {'error', any()}. discovery(Num) -> discovery(Num, []). -spec discovery(kz_term:ne_binary(), knm_options:options()) -> {'ok', knm_phone_number:record()} | {'error', any()}. discovery(Num, Options) -> case local_discovery(Num, Options) of {'ok', _}=OK -> OK; {'error', 'not_found'} -> remote_discovery(Num, Options) end. -spec local_discovery(kz_term:ne_binary(), knm_options:options()) -> {'ok', knm_phone_number:record()} | {'error', any()}. -ifdef(TEST). local_discovery(_Num, _Options) -> {'error', 'not_found'}. -else. local_discovery(Num, Options) -> case ets:match_object(?ETS_DISCOVERY_CACHE, {'_', {Num, '_', ?NUMBER_STATE_DISCOVERY, '_'}}) of [] -> {'error', 'not_found'}; [{_QID, {Num, Carrier, _, Data}} | _] -> {'ok', create_discovery(Num, Carrier, Data, Options)} end. -endif. -spec remote_discovery(kz_term:ne_binary(), knm_options:options()) -> {'ok', knm_phone_number:record()} | {'error', any()}. -ifdef(TEST). remote_discovery(_Num, _Options) -> {'error', 'not_found'}. -else. remote_discovery(Number, Options) -> Payload = [{<<"Number">>, Number} ,{<<"Account-ID">>, knm_options:account_id(Options)} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], case kz_amqp_worker:call(Payload ,fun kapi_discovery:publish_number_req/1 ,fun kapi_discovery:resp_v/1 ) of {'ok', JObj} -> {'ok', create_discovery(kapi_discovery:results(JObj), Options)}; {'error', _Error} -> lager:debug("error requesting number from amqp: ~p", [_Error]), {'error', 'not_found'} end. -endif. %%%============================================================================= Internal functions %%%============================================================================= %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ handle_flush(JObj) -> 'true' = kapi_discovery:flush_v(JObj), QID = kapi_discovery:query_id(JObj), gen_listener:cast(?MODULE, {'reset_search',QID}). -spec handle_search(kz_json:object()) -> 'ok'. handle_search(JObj) -> 'true' = kapi_discovery:req_v(JObj), handle_search(JObj, is_local(kapi_discovery:query_id(JObj))). handle_search(JObj, 'false') -> lager:debug("query id ~s not handled in this node", [kapi_discovery:query_id(JObj)]); handle_search(JObj, 'true') -> lager:debug("query id ~s handled in this node", [kapi_discovery:query_id(JObj)]), 'true' = kapi_discovery:req_v(JObj), QID = kapi_discovery:query_id(JObj), Offset = kapi_discovery:offset(JObj), Quantity = kapi_discovery:quantity(JObj), Prefix = kapi_discovery:prefix(JObj), AccountId = kz_api:account_id(JObj), Options = [{'quantity', Quantity} ,{'prefix', Prefix} ,{'offset', Offset} ,{'account_id', AccountId} ,{'query_id', QID} ], Results = find(Options), Payload = [{<<"Msg-ID">>, kz_api:msg_id(JObj)} ,{<<"Query-ID">>, QID} ,{<<"Results">>, Results} | kz_api:default_headers(kz_api:server_id(JObj), ?APP_NAME, ?APP_VERSION) ], Publisher = fun(P) -> kapi_discovery:publish_resp(kz_api:server_id(JObj), P) end, kz_amqp_worker:cast(Payload, Publisher). -spec handle_number(kz_json:object()) -> 'ok'. handle_number(JObj) -> 'true' = kapi_discovery:number_req_v(JObj), Number = kapi_discovery:number(JObj), case local_discovery(Number, []) of {'error', 'not_found'} -> 'ok'; {'ok', PN} -> Payload = [{<<"Msg-ID">>, kz_api:msg_id(JObj)} ,{<<"Results">>, knm_phone_number:to_json(PN)} | kz_api:default_headers(kz_api:server_id(JObj), ?APP_NAME, ?APP_VERSION) ], Publisher = fun(P) -> kapi_discovery:publish_resp(kz_api:server_id(JObj), P) end, kz_amqp_worker:cast(Payload, Publisher) end.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_numbers/src/knm_search.erl
erlang
----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- FIXME: knm_managed.erl:76: can never evaluate to `true' Same dialyzer warning ------------------------------------------------------------------------------ @doc Starts the server. @end ------------------------------------------------------------------------------ ============================================================================= gen_server callbacks ============================================================================= ------------------------------------------------------------------------------ @doc Initializes the server. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Handling call messages. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Handling cast messages. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Handling all non call/cast messages. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc This function is called by a `gen_server' when it is about to terminate. It should be the opposite of `Module:init/1' and do any necessary cleaning up. When it returns, the `gen_server' terminates @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Convert process state when code is changed. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Create a number in a discovery state. @end ------------------------------------------------------------------------------ ============================================================================= ============================================================================= ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(knm_search). -behaviour(gen_listener). -export([start_link/0]). -export([init/1 ,handle_call/3 ,handle_cast/2 ,handle_info/2 ,handle_event/2 ,terminate/2 ,code_change/3 ]). -export([find/1 ,next/1 ,discovery/1, discovery/2 ,quantity/1 ,prefix/1, prefix/2 ,normalized_prefix/1, normalized_prefix/2 ,query_options/1, query_options/2 ,dialcode/1 ,country/1 ,offset/1 ,query_id/1 ,account_id/1 ,reseller_id/1 ]). -include("knm.hrl"). -type option() :: {'quantity', pos_integer()} | {'prefix', kz_term:ne_binary()} | {'dialcode', kz_term:ne_binary()} | {'country', knm_util:country_iso3166a2()} | {'offset', non_neg_integer()} | {'blocks', boolean()} | The test ` < < _ : 8,_:_*8 > > = : = undefined ' {'account_id', kz_term:api_ne_binary()} | {'query_id', kz_term:ne_binary()} | -type result() :: {kz_term:ne_binary(), {kz_term:ne_binary(), module(), kz_term:ne_binary(), kz_json:object()}}. -type results() :: [result()]. -type mod_response() :: kz_either:either(kz_term:ne_binary() | atom(), results()) | {'bulk', results()}. -type options() :: [option()]. -export_type([option/0, options/0 ,results/0 ,result/0 ,mod_response/0 ]). -define(MAX_SEARCH, kapps_config:get_pos_integer(?KNM_CONFIG_CAT, <<"maximum_search_quantity">>, 500)). -define(NUMBER_SEARCH_TIMEOUT ,kapps_config:get_pos_integer(?KNM_CONFIG_CAT, <<"number_search_timeout_ms">>, 5 * ?MILLISECONDS_IN_SECOND) ). -define(POLLING_INTERVAL, 5000). -define(EOT, '$end_of_table'). -type state() :: #{node => kz_term:ne_binary() ,cache => ets:tid() | atom() }. -define(ETS_DISCOVERY_CACHE, 'knm_discovery_cache'). -define(ETS_DISCOVERY_CACHE_OPTIONS, ['bag', 'named_table', {'read_concurrency', 'true'}]). -define(BINDINGS, [{'self', []} ,{'discovery', ['federate']} ]). -define(RESPONDERS, []). -define(QUEUE_NAME, <<>>). -define(QUEUE_OPTIONS, []). -define(CONSUME_OPTIONS, []). -spec start_link() -> kz_types:startlink_ret(). -ifdef(TEST). start_link() -> gen_listener:start_link({'local', ?MODULE} ,?MODULE ,[] ,[]). -else. start_link() -> gen_listener:start_link({'local', ?MODULE} ,?MODULE ,[{'bindings', ?BINDINGS} ,{'responders', ?RESPONDERS} ,{'queue_name', ?QUEUE_NAME} ,{'queue_options', ?QUEUE_OPTIONS} ,{'consume_options', ?CONSUME_OPTIONS} ] ,[]). -endif. -spec init([]) -> {'ok', state(), timeout()}. init([]) -> State = #{node => kz_term:to_binary(node()) ,cache => ets:new(?ETS_DISCOVERY_CACHE, ?ETS_DISCOVERY_CACHE_OPTIONS) }, {'ok', State, ?POLLING_INTERVAL}. -spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()). handle_call({'first', Options}, _From, State) -> QueryId = query_id(Options), flush(QueryId), {'reply', next(Options), State, ?POLLING_INTERVAL}; handle_call(_Request, _From, State) -> {'reply', {'error', 'not_implemented'}, State, ?POLLING_INTERVAL}. -spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()). handle_cast({'gen_listener',{'created_queue', Queue}}, State) -> {'noreply', State#{queue => Queue}, ?POLLING_INTERVAL}; handle_cast({'gen_listener',{'is_consuming',_IsConsuming}}, State) -> {'noreply', State}; handle_cast({'gen_listener',{'federators_consuming', _AreFederatorsConsuming}}, State) -> {'noreply', State}; handle_cast({'reset_search',QID}, #{cache := Cache} = State) -> lager:debug("resetting query id ~s", [QID]), ets:delete(Cache, QID), {'noreply', State, ?POLLING_INTERVAL}; handle_cast({'add_result', Numbers}, #{cache := Cache} = State) -> ets:insert(Cache, Numbers), {'noreply', State, ?POLLING_INTERVAL}; handle_cast(_Msg, State) -> lager:debug("unhandled cast: ~p", [_Msg]), {'noreply', State, ?POLLING_INTERVAL}. -spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()). handle_info(_Info, State) -> {'noreply', State, ?POLLING_INTERVAL}. -spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return(). handle_event(JObj, #{node := Node}) -> _ = case kz_api:node(JObj) =/= Node andalso kz_api:event_name(JObj) of <<"flush">> -> kz_process:spawn(fun handle_flush/1, [JObj]); <<"request">> -> kz_process:spawn(fun handle_search/1, [JObj]); <<"number">> -> kz_process:spawn(fun handle_number/1, [JObj]); _ -> 'ok' end, 'ignore'. with . The return value is ignored . -spec terminate(any(), state()) -> 'ok'. terminate(_Reason, #{}) -> lager:debug("terminating number search : ~p", [_Reason]). -spec code_change(any(), state(), any()) -> {'ok', state()}. code_change(_OldVsn, State, _Extra) -> {'ok', State}. -spec flush(kz_term:ne_binary()) -> 'ok'. -ifdef(TEST). flush(_QID) -> 'ok'. -else. flush(QID) -> Payload = [{<<"Query-ID">>, QID} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], kz_amqp_worker:cast(Payload, fun kapi_discovery:publish_flush/1). -endif. -spec find(options()) -> kz_json:objects(). find(Options) -> find(Options, offset(Options)). find(Options, 0) -> first(Options); find(Options, _) -> do_find(Options, is_local(query_id(Options))). do_find(Options, 'true') -> next(Options); do_find(Options, 'false') -> Payload = [{<<"Query-ID">>, query_id(Options)} ,{<<"Prefix">>, normalized_prefix(Options)} ,{<<"Quantity">>, quantity(Options)} ,{<<"Offset">>, offset(Options)} ,{<<"Account-ID">>, account_id(Options)} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], case kz_amqp_worker:call(Payload ,fun kapi_discovery:publish_req/1 ,fun kapi_discovery:resp_v/1 ) of {'ok', JObj} -> kapi_discovery:results(JObj); {'error', _Error} -> lager:debug("error requesting search from amqp: ~p", [_Error]), [] end. -spec first(options()) -> kz_json:objects(). first(Options) -> Carriers = knm_carriers:available_carriers(Options), lager:debug("contacting, in order: ~p", [Carriers]), QID = query_id(Options), gen_listener:cast(?MODULE, {'reset_search', QID}), Self = self(), Opts = [{'quantity', ?MAX_SEARCH} ,{'offset', 0} ,{'normalized_prefix', normalized_prefix(Options)} | Options ], lists:foreach(fun(Carrier) -> search_spawn(Self, Carrier, Opts) end, Carriers), wait_for_search(length(Carriers)), gen_listener:call(?MODULE, {'first', Options}). -spec search_spawn(pid(), atom(), kz_term:proplist()) -> any(). search_spawn(Pid, Carrier, Options) -> F = fun() -> Pid ! {Carrier, search_carrier(Carrier, Options)} end, kz_process:spawn(F). -spec search_carrier(atom(), kz_term:proplist()) -> any(). search_carrier(Carrier, Options) -> Prefix = normalized_prefix(Options), Quantity = quantity(Options), catch (Carrier:find_numbers(Prefix, Quantity, Options)). -spec wait_for_search(integer()) -> 'ok'. wait_for_search(0) -> 'ok'; wait_for_search(N) -> receive {_Carrier, {'ok', []}} -> lager:debug("~s found no numbers", [_Carrier]), wait_for_search(N - 1); {_Carrier, {'ok', Numbers}} -> lager:debug("~s found numbers", [_Carrier]), gen_listener:cast(?MODULE, {'add_result', Numbers}), wait_for_search(N - 1); {_Carrier, {'bulk', Numbers}} -> lager:debug("~s found bulk numbers", [_Carrier]), gen_listener:cast(?MODULE, {'add_result', Numbers}), wait_for_search(N - 1); {_Carrier, {'error', 'not_available'}} -> lager:debug("~s had no results", [_Carrier]), wait_for_search(N - 1); _Other -> lager:debug("unexpected search result ~p", [_Other]), wait_for_search(N - 1) after ?NUMBER_SEARCH_TIMEOUT -> lager:debug("timeout (~B) collecting responses from search providers", [?NUMBER_SEARCH_TIMEOUT]), wait_for_search(N - 1) end. -spec next(options()) -> kz_json:objects(). next(Options) -> QID = query_id(Options), Quantity = quantity(Options), Offset = offset(Options), MatchSpec = [{{QID,'$1'},[],['$1']}], QLH = qlc:keysort(1, ets:table(?ETS_DISCOVERY_CACHE, [{'traverse', {'select', MatchSpec}}])), QLC = qlc:cursor(QLH), _ = Offset > 0 andalso qlc:next_answers(QLC, Offset), Results = qlc:next_answers(QLC, Quantity), qlc:delete_cursor(QLC), lager:debug("returning ~B results", [length(Results)]), [kz_json:from_list( [{<<"number">>, Num} ,{<<"state">>, State} ]) || {Num, _ModuleName, State, _CarrierData} <- Results ]. -ifndef(TEST). -spec create_discovery(kz_term:ne_binary(), module(), kz_json:object(), knm_options:options()) -> knm_phone_number:record(). create_discovery(DID=?NE_BINARY, Carrier, Data, Options0) -> Options = [{'state', ?NUMBER_STATE_DISCOVERY} ,{'module_name', kz_term:to_binary(Carrier)} | Options0 ], {'ok', PhoneNumber} = knm_phone_number:setters(knm_phone_number:from_number_with_options(DID, Options) ,[{fun knm_phone_number:set_carrier_data/2, Data}] ), PhoneNumber. -spec create_discovery(kz_json:object(), knm_options:options()) -> knm_phone_number:record(). create_discovery(JObj, Options) -> knm_phone_number:from_json_with_options(JObj, Options). -endif. -spec quantity(options()) -> pos_integer(). quantity(Options) -> Quantity = props:get_integer_value('quantity', Options, 1), min(Quantity, ?MAX_SEARCH). -spec prefix(options()) -> kz_term:ne_binary(). prefix(Options) -> props:get_ne_binary_value('prefix', Options). -spec prefix(options(), kz_term:ne_binary()) -> kz_term:ne_binary(). prefix(Options, Default) -> props:get_ne_binary_value('prefix', Options, Default). -spec query_options(options()) -> kz_term:api_object(). query_options(Options) -> props:get_value('query_options', Options). -spec query_options(options(), kz_term:api_object()) -> kz_term:api_object(). query_options(Options, Default) -> props:get_value('query_options', Options, Default). -spec normalized_prefix(options()) -> kz_term:ne_binary(). normalized_prefix(Options) -> JObj = query_options(Options, kz_json:new()), Dialcode = dialcode(Options), Prefix = kz_json:get_ne_binary_value(<<"Prefix">>, JObj, prefix(Options)), normalized_prefix(Options, <<Dialcode/binary, Prefix/binary>>). -spec normalized_prefix(options(), kz_term:ne_binary()) -> kz_term:ne_binary(). normalized_prefix(Options, Default) -> props:get_ne_binary_value('normalized_prefix', Options, Default). -spec dialcode(options()) -> kz_term:ne_binary(). dialcode(Options) -> Default = knm_util:prefix_for_country(country(Options)), props:get_ne_binary_value('dialcode', Options, Default). -spec country(options()) -> knm_util:country_iso3166a2(). country(Options) -> case props:get_ne_binary_value('country', Options, ?KNM_DEFAULT_COUNTRY) of <<_:8, _:8>>=Country -> Country; _Else -> lager:debug("~p is not iso3166a2, using default"), ?KNM_DEFAULT_COUNTRY end. -spec query_id(options()) -> kz_term:api_binary(). query_id(Options) -> props:get_ne_binary_value('query_id', Options). -spec offset(options()) -> non_neg_integer(). offset(Options) -> props:get_integer_value('offset', Options, 0). -spec account_id(options()) -> kz_term:api_ne_binary(). account_id(Options) -> props:get_value('account_id', Options). -spec reseller_id(options()) -> kz_term:api_ne_binary(). reseller_id(Options) -> props:get_value('reseller_id', Options). -spec is_local(kz_term:ne_binary()) -> boolean(). is_local(QID) -> ets:match_object(?ETS_DISCOVERY_CACHE, {QID, '_'}) =/= []. -spec discovery(kz_term:ne_binary()) -> {'ok', knm_phone_number:record()} | {'error', any()}. discovery(Num) -> discovery(Num, []). -spec discovery(kz_term:ne_binary(), knm_options:options()) -> {'ok', knm_phone_number:record()} | {'error', any()}. discovery(Num, Options) -> case local_discovery(Num, Options) of {'ok', _}=OK -> OK; {'error', 'not_found'} -> remote_discovery(Num, Options) end. -spec local_discovery(kz_term:ne_binary(), knm_options:options()) -> {'ok', knm_phone_number:record()} | {'error', any()}. -ifdef(TEST). local_discovery(_Num, _Options) -> {'error', 'not_found'}. -else. local_discovery(Num, Options) -> case ets:match_object(?ETS_DISCOVERY_CACHE, {'_', {Num, '_', ?NUMBER_STATE_DISCOVERY, '_'}}) of [] -> {'error', 'not_found'}; [{_QID, {Num, Carrier, _, Data}} | _] -> {'ok', create_discovery(Num, Carrier, Data, Options)} end. -endif. -spec remote_discovery(kz_term:ne_binary(), knm_options:options()) -> {'ok', knm_phone_number:record()} | {'error', any()}. -ifdef(TEST). remote_discovery(_Num, _Options) -> {'error', 'not_found'}. -else. remote_discovery(Number, Options) -> Payload = [{<<"Number">>, Number} ,{<<"Account-ID">>, knm_options:account_id(Options)} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], case kz_amqp_worker:call(Payload ,fun kapi_discovery:publish_number_req/1 ,fun kapi_discovery:resp_v/1 ) of {'ok', JObj} -> {'ok', create_discovery(kapi_discovery:results(JObj), Options)}; {'error', _Error} -> lager:debug("error requesting number from amqp: ~p", [_Error]), {'error', 'not_found'} end. -endif. Internal functions handle_flush(JObj) -> 'true' = kapi_discovery:flush_v(JObj), QID = kapi_discovery:query_id(JObj), gen_listener:cast(?MODULE, {'reset_search',QID}). -spec handle_search(kz_json:object()) -> 'ok'. handle_search(JObj) -> 'true' = kapi_discovery:req_v(JObj), handle_search(JObj, is_local(kapi_discovery:query_id(JObj))). handle_search(JObj, 'false') -> lager:debug("query id ~s not handled in this node", [kapi_discovery:query_id(JObj)]); handle_search(JObj, 'true') -> lager:debug("query id ~s handled in this node", [kapi_discovery:query_id(JObj)]), 'true' = kapi_discovery:req_v(JObj), QID = kapi_discovery:query_id(JObj), Offset = kapi_discovery:offset(JObj), Quantity = kapi_discovery:quantity(JObj), Prefix = kapi_discovery:prefix(JObj), AccountId = kz_api:account_id(JObj), Options = [{'quantity', Quantity} ,{'prefix', Prefix} ,{'offset', Offset} ,{'account_id', AccountId} ,{'query_id', QID} ], Results = find(Options), Payload = [{<<"Msg-ID">>, kz_api:msg_id(JObj)} ,{<<"Query-ID">>, QID} ,{<<"Results">>, Results} | kz_api:default_headers(kz_api:server_id(JObj), ?APP_NAME, ?APP_VERSION) ], Publisher = fun(P) -> kapi_discovery:publish_resp(kz_api:server_id(JObj), P) end, kz_amqp_worker:cast(Payload, Publisher). -spec handle_number(kz_json:object()) -> 'ok'. handle_number(JObj) -> 'true' = kapi_discovery:number_req_v(JObj), Number = kapi_discovery:number(JObj), case local_discovery(Number, []) of {'error', 'not_found'} -> 'ok'; {'ok', PN} -> Payload = [{<<"Msg-ID">>, kz_api:msg_id(JObj)} ,{<<"Results">>, knm_phone_number:to_json(PN)} | kz_api:default_headers(kz_api:server_id(JObj), ?APP_NAME, ?APP_VERSION) ], Publisher = fun(P) -> kapi_discovery:publish_resp(kz_api:server_id(JObj), P) end, kz_amqp_worker:cast(Payload, Publisher) end.
f1ac34fa1d1dd9899726fee245ce8033ba9d2d2311a584d6f2e958d14d1fc66d
bvaugon/ocapic
mac.ml
(*************************************************************************) (* *) (* OCaPIC *) (* *) (* *) This file is distributed under the terms of the CeCILL license . (* See file ../../LICENSE-en. *) (* *) (*************************************************************************) open Pic;; open Lcd;; let disp = connect ~bus_size:Lcd.Four ~e:LATD0 ~rs:LATD2 ~rw:LATD1 ~bus:PORTB;; disp.init ();; disp.config ();; disp.print_string "Hello world";; Sys.sleep 4;; let rec f () = 4l and g () = Int32.add (f ()) 1l and h () = Int32.add (f ()) (g ());; disp.clear ();; Printf.fprintf disp.output "%b %b %b\n" (f () = g ()) (f () < g ()) (f () > g ());; Sys.sleep 4;; let r = ref [];; for i = 1 to 10 do r := 1 :: !r; done;; disp.clear ();; try while true do Gc.run (); Printf.fprintf disp.output "%d %lx " (Gc.running_number ()) (h ()); disp.print_int ( ( ) ) ; Sys.sleep 4; r := []; done; with Out_of_memory -> disp.clear (); disp.print_string "OUT OF MEMORY"; ;;
null
https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/tests/mac/mac.ml
ocaml
*********************************************************************** OCaPIC See file ../../LICENSE-en. ***********************************************************************
This file is distributed under the terms of the CeCILL license . open Pic;; open Lcd;; let disp = connect ~bus_size:Lcd.Four ~e:LATD0 ~rs:LATD2 ~rw:LATD1 ~bus:PORTB;; disp.init ();; disp.config ();; disp.print_string "Hello world";; Sys.sleep 4;; let rec f () = 4l and g () = Int32.add (f ()) 1l and h () = Int32.add (f ()) (g ());; disp.clear ();; Printf.fprintf disp.output "%b %b %b\n" (f () = g ()) (f () < g ()) (f () > g ());; Sys.sleep 4;; let r = ref [];; for i = 1 to 10 do r := 1 :: !r; done;; disp.clear ();; try while true do Gc.run (); Printf.fprintf disp.output "%d %lx " (Gc.running_number ()) (h ()); disp.print_int ( ( ) ) ; Sys.sleep 4; r := []; done; with Out_of_memory -> disp.clear (); disp.print_string "OUT OF MEMORY"; ;;
5cd3de7934e1c63a4f01ef670803e0aa21631810f6c0f6b7e719f0a5db396752
haskell-opengl/OpenGLRaw
TimerQuery.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.EXT.TimerQuery Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.EXT.TimerQuery ( -- * Extension Support glGetEXTTimerQuery, gl_EXT_timer_query, -- * Enums pattern GL_TIME_ELAPSED_EXT, -- * Functions glGetQueryObjecti64vEXT, glGetQueryObjectui64vEXT ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/EXT/TimerQuery.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.EXT.TimerQuery License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums * Functions
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.EXT.TimerQuery ( glGetEXTTimerQuery, gl_EXT_timer_query, pattern GL_TIME_ELAPSED_EXT, glGetQueryObjecti64vEXT, glGetQueryObjectui64vEXT ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
98023f2eaea8d8569592e38a878a542ce356a887ff9c1ddea9b66ed885dcb89a
huangz1990/real-world-haskell-cn
myFilter.hs
-- file: ch04/myFilter.hs myFilter p xs = foldr step [] xs where step x ys | p x = x : ys | otherwise = ys
null
https://raw.githubusercontent.com/huangz1990/real-world-haskell-cn/f67b07dd846b1950d17ff941d650089fcbbe9586/code/ch04/myFilter.hs
haskell
file: ch04/myFilter.hs
myFilter p xs = foldr step [] xs where step x ys | p x = x : ys | otherwise = ys
b570cc286528f46af921644d2b57d69270260b62230b32e0d8a5282b8fe39320
ocaml/ocaml
location.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) * Source code locations ( ranges of positions ) , used in parsetree . { b Warning :} this module is unstable and part of { { ! Compiler_libs}compiler - libs } . {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) open Format type t = Warnings.loc = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } (** Note on the use of Lexing.position in this module. If [pos_fname = ""], then use [!input_name] instead. If [pos_lnum = -1], then [pos_bol = 0]. Use [pos_cnum] and re-parse the file to get the line and character numbers. Else all fields are correct. *) val none : t (** An arbitrary value of type [t]; describes an empty ghost range. *) val is_none : t -> bool (** True for [Location.none], false any other location *) val in_file : string -> t (** Return an empty ghost range located in a given file. *) val init : Lexing.lexbuf -> string -> unit (** Set the file name and line number of the [lexbuf] to be the start of the named file. *) val curr : Lexing.lexbuf -> t (** Get the location of the current token from the [lexbuf]. *) val symbol_rloc: unit -> t val symbol_gloc: unit -> t * [ rhs_loc n ] returns the location of the symbol at position [ n ] , starting at 1 , in the current parser rule . at 1, in the current parser rule. *) val rhs_loc: int -> t val rhs_interval: int -> int -> t val get_pos_info: Lexing.position -> string * int * int (** file, line, char *) type 'a loc = { txt : 'a; loc : t; } val mknoloc : 'a -> 'a loc val mkloc : 'a -> t -> 'a loc (** {1 Input info} *) val input_name: string ref val input_lexbuf: Lexing.lexbuf option ref This is used for reporting errors coming from the toplevel . When running a toplevel session ( i.e. when [ ! input_name ] is " //toplevel// " ) , [ ! input_phrase_buffer ] should be [ Some buf ] where [ buf ] contains the last toplevel phrase . When running a toplevel session (i.e. when [!input_name] is "//toplevel//"), [!input_phrase_buffer] should be [Some buf] where [buf] contains the last toplevel phrase. *) val input_phrase_buffer: Buffer.t option ref * { 1 Toplevel - specific functions } val echo_eof: unit -> unit val separate_new_message: formatter -> unit val reset: unit -> unit * { 1 Printing locations } val rewrite_absolute_path: string -> string (** rewrite absolute path to honor the BUILD_PATH_PREFIX_MAP variable (-builds.org/specs/build-path-prefix-map/) if it is set. *) val absolute_path: string -> string val show_filename: string -> string (** In -absname mode, return the absolute path for this filename. Otherwise, returns the filename unchanged. *) val print_filename: formatter -> string -> unit val print_loc: formatter -> t -> unit val print_locs: formatter -> t list -> unit * { 1 Toplevel - specific location highlighting } val highlight_terminfo: Lexing.lexbuf -> formatter -> t list -> unit * { 1 Reporting errors and warnings } * { 2 The type of reports and report printers } type msg = (Format.formatter -> unit) loc val msg: ?loc:t -> ('a, Format.formatter, unit, msg) format4 -> 'a type report_kind = | Report_error | Report_warning of string | Report_warning_as_error of string | Report_alert of string | Report_alert_as_error of string type report = { kind : report_kind; main : msg; sub : msg list; } type report_printer = { (* The entry point *) pp : report_printer -> Format.formatter -> report -> unit; pp_report_kind : report_printer -> report -> Format.formatter -> report_kind -> unit; pp_main_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_main_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; pp_submsgs : report_printer -> report -> Format.formatter -> msg list -> unit; pp_submsg : report_printer -> report -> Format.formatter -> msg -> unit; pp_submsg_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_submsg_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; } (** A printer for [report]s, defined using open-recursion. The goal is to make it easy to define new printers by re-using code from existing ones. *) * { 2 Report printers used in the compiler } val batch_mode_printer: report_printer val terminfo_toplevel_printer: Lexing.lexbuf -> report_printer val best_toplevel_printer: unit -> report_printer (** Detects the terminal capabilities and selects an adequate printer *) * { 2 Printing a [ report ] } val print_report: formatter -> report -> unit (** Display an error or warning report. *) val report_printer: (unit -> report_printer) ref (** Hook for redefining the printer of reports. The hook is a [unit -> report_printer] and not simply a [report_printer]: this is useful so that it can detect the type of the output (a file, a terminal, ...) and select a printer accordingly. *) val default_report_printer: unit -> report_printer (** Original report printer for use in hooks. *) (** {1 Reporting warnings} *) (** {2 Converting a [Warnings.t] into a [report]} *) val report_warning: t -> Warnings.t -> report option * [ report_warning w ] produces a report for the given warning [ w ] , or [ None ] if the warning is not to be printed . [None] if the warning is not to be printed. *) val warning_reporter: (t -> Warnings.t -> report option) ref (** Hook for intercepting warnings. *) val default_warning_reporter: t -> Warnings.t -> report option (** Original warning reporter for use in hooks. *) * { 2 Printing warnings } val formatter_for_warnings : formatter ref val print_warning: t -> formatter -> Warnings.t -> unit * Prints a warning . This is simply the composition of [ report_warning ] and [ print_report ] . [print_report]. *) val prerr_warning: t -> Warnings.t -> unit (** Same as [print_warning], but uses [!formatter_for_warnings] as output formatter. *) (** {1 Reporting alerts} *) (** {2 Converting an [Alert.t] into a [report]} *) val report_alert: t -> Warnings.alert -> report option (** [report_alert loc w] produces a report for the given alert [w], or [None] if the alert is not to be printed. *) val alert_reporter: (t -> Warnings.alert -> report option) ref (** Hook for intercepting alerts. *) val default_alert_reporter: t -> Warnings.alert -> report option (** Original alert reporter for use in hooks. *) * { 2 Printing alerts } val print_alert: t -> formatter -> Warnings.alert -> unit * Prints an alert . This is simply the composition of [ report_alert ] and [ print_report ] . [print_report]. *) val prerr_alert: t -> Warnings.alert -> unit (** Same as [print_alert], but uses [!formatter_for_warnings] as output formatter. *) val deprecated: ?def:t -> ?use:t -> t -> string -> unit (** Prints a deprecation alert. *) val alert: ?def:t -> ?use:t -> kind:string -> t -> string -> unit (** Prints an arbitrary alert. *) val auto_include_alert: string -> unit (** Prints an alert that -I +lib has been automatically added to the load path *) val deprecated_script_alert: string -> unit * [ deprecated_script_alert command ] prints an alert that [ command foo ] has been deprecated in favour of [ command ./foo ] been deprecated in favour of [command ./foo] *) * { 1 Reporting errors } type error = report (** An [error] is a [report] which [report_kind] must be [Report_error]. *) val error: ?loc:t -> ?sub:msg list -> string -> error val errorf: ?loc:t -> ?sub:msg list -> ('a, Format.formatter, unit, error) format4 -> 'a val error_of_printer: ?loc:t -> ?sub:msg list -> (formatter -> 'a -> unit) -> 'a -> error val error_of_printer_file: (formatter -> 'a -> unit) -> 'a -> error (** {1 Automatically reporting errors for raised exceptions} *) val register_error_of_exn: (exn -> error option) -> unit (** Each compiler module which defines a custom type of exception which can surface as a user-visible error should register a "printer" for this exception using [register_error_of_exn]. The result of the printer is an [error] value containing a location, a message, and optionally sub-messages (each of them being located as well). *) val error_of_exn: exn -> [ `Ok of error | `Already_displayed ] option exception Error of error (** Raising [Error e] signals an error [e]; the exception will be caught and the error will be printed. *) exception Already_displayed_error (** Raising [Already_displayed_error] signals an error which has already been printed. The exception will be caught, but nothing will be printed *) val raise_errorf: ?loc:t -> ?sub:msg list -> ('a, Format.formatter, unit, 'b) format4 -> 'a val report_exception: formatter -> exn -> unit * the exception if it is unknown .
null
https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/parsing/location.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Note on the use of Lexing.position in this module. If [pos_fname = ""], then use [!input_name] instead. If [pos_lnum = -1], then [pos_bol = 0]. Use [pos_cnum] and re-parse the file to get the line and character numbers. Else all fields are correct. * An arbitrary value of type [t]; describes an empty ghost range. * True for [Location.none], false any other location * Return an empty ghost range located in a given file. * Set the file name and line number of the [lexbuf] to be the start of the named file. * Get the location of the current token from the [lexbuf]. * file, line, char * {1 Input info} * rewrite absolute path to honor the BUILD_PATH_PREFIX_MAP variable (-builds.org/specs/build-path-prefix-map/) if it is set. * In -absname mode, return the absolute path for this filename. Otherwise, returns the filename unchanged. The entry point * A printer for [report]s, defined using open-recursion. The goal is to make it easy to define new printers by re-using code from existing ones. * Detects the terminal capabilities and selects an adequate printer * Display an error or warning report. * Hook for redefining the printer of reports. The hook is a [unit -> report_printer] and not simply a [report_printer]: this is useful so that it can detect the type of the output (a file, a terminal, ...) and select a printer accordingly. * Original report printer for use in hooks. * {1 Reporting warnings} * {2 Converting a [Warnings.t] into a [report]} * Hook for intercepting warnings. * Original warning reporter for use in hooks. * Same as [print_warning], but uses [!formatter_for_warnings] as output formatter. * {1 Reporting alerts} * {2 Converting an [Alert.t] into a [report]} * [report_alert loc w] produces a report for the given alert [w], or [None] if the alert is not to be printed. * Hook for intercepting alerts. * Original alert reporter for use in hooks. * Same as [print_alert], but uses [!formatter_for_warnings] as output formatter. * Prints a deprecation alert. * Prints an arbitrary alert. * Prints an alert that -I +lib has been automatically added to the load path * An [error] is a [report] which [report_kind] must be [Report_error]. * {1 Automatically reporting errors for raised exceptions} * Each compiler module which defines a custom type of exception which can surface as a user-visible error should register a "printer" for this exception using [register_error_of_exn]. The result of the printer is an [error] value containing a location, a message, and optionally sub-messages (each of them being located as well). * Raising [Error e] signals an error [e]; the exception will be caught and the error will be printed. * Raising [Already_displayed_error] signals an error which has already been printed. The exception will be caught, but nothing will be printed
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * Source code locations ( ranges of positions ) , used in parsetree . { b Warning :} this module is unstable and part of { { ! Compiler_libs}compiler - libs } . {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) open Format type t = Warnings.loc = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } val none : t val is_none : t -> bool val in_file : string -> t val init : Lexing.lexbuf -> string -> unit val curr : Lexing.lexbuf -> t val symbol_rloc: unit -> t val symbol_gloc: unit -> t * [ rhs_loc n ] returns the location of the symbol at position [ n ] , starting at 1 , in the current parser rule . at 1, in the current parser rule. *) val rhs_loc: int -> t val rhs_interval: int -> int -> t val get_pos_info: Lexing.position -> string * int * int type 'a loc = { txt : 'a; loc : t; } val mknoloc : 'a -> 'a loc val mkloc : 'a -> t -> 'a loc val input_name: string ref val input_lexbuf: Lexing.lexbuf option ref This is used for reporting errors coming from the toplevel . When running a toplevel session ( i.e. when [ ! input_name ] is " //toplevel// " ) , [ ! input_phrase_buffer ] should be [ Some buf ] where [ buf ] contains the last toplevel phrase . When running a toplevel session (i.e. when [!input_name] is "//toplevel//"), [!input_phrase_buffer] should be [Some buf] where [buf] contains the last toplevel phrase. *) val input_phrase_buffer: Buffer.t option ref * { 1 Toplevel - specific functions } val echo_eof: unit -> unit val separate_new_message: formatter -> unit val reset: unit -> unit * { 1 Printing locations } val rewrite_absolute_path: string -> string val absolute_path: string -> string val show_filename: string -> string val print_filename: formatter -> string -> unit val print_loc: formatter -> t -> unit val print_locs: formatter -> t list -> unit * { 1 Toplevel - specific location highlighting } val highlight_terminfo: Lexing.lexbuf -> formatter -> t list -> unit * { 1 Reporting errors and warnings } * { 2 The type of reports and report printers } type msg = (Format.formatter -> unit) loc val msg: ?loc:t -> ('a, Format.formatter, unit, msg) format4 -> 'a type report_kind = | Report_error | Report_warning of string | Report_warning_as_error of string | Report_alert of string | Report_alert_as_error of string type report = { kind : report_kind; main : msg; sub : msg list; } type report_printer = { pp : report_printer -> Format.formatter -> report -> unit; pp_report_kind : report_printer -> report -> Format.formatter -> report_kind -> unit; pp_main_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_main_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; pp_submsgs : report_printer -> report -> Format.formatter -> msg list -> unit; pp_submsg : report_printer -> report -> Format.formatter -> msg -> unit; pp_submsg_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_submsg_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; } * { 2 Report printers used in the compiler } val batch_mode_printer: report_printer val terminfo_toplevel_printer: Lexing.lexbuf -> report_printer val best_toplevel_printer: unit -> report_printer * { 2 Printing a [ report ] } val print_report: formatter -> report -> unit val report_printer: (unit -> report_printer) ref val default_report_printer: unit -> report_printer val report_warning: t -> Warnings.t -> report option * [ report_warning w ] produces a report for the given warning [ w ] , or [ None ] if the warning is not to be printed . [None] if the warning is not to be printed. *) val warning_reporter: (t -> Warnings.t -> report option) ref val default_warning_reporter: t -> Warnings.t -> report option * { 2 Printing warnings } val formatter_for_warnings : formatter ref val print_warning: t -> formatter -> Warnings.t -> unit * Prints a warning . This is simply the composition of [ report_warning ] and [ print_report ] . [print_report]. *) val prerr_warning: t -> Warnings.t -> unit val report_alert: t -> Warnings.alert -> report option val alert_reporter: (t -> Warnings.alert -> report option) ref val default_alert_reporter: t -> Warnings.alert -> report option * { 2 Printing alerts } val print_alert: t -> formatter -> Warnings.alert -> unit * Prints an alert . This is simply the composition of [ report_alert ] and [ print_report ] . [print_report]. *) val prerr_alert: t -> Warnings.alert -> unit val deprecated: ?def:t -> ?use:t -> t -> string -> unit val alert: ?def:t -> ?use:t -> kind:string -> t -> string -> unit val auto_include_alert: string -> unit val deprecated_script_alert: string -> unit * [ deprecated_script_alert command ] prints an alert that [ command foo ] has been deprecated in favour of [ command ./foo ] been deprecated in favour of [command ./foo] *) * { 1 Reporting errors } type error = report val error: ?loc:t -> ?sub:msg list -> string -> error val errorf: ?loc:t -> ?sub:msg list -> ('a, Format.formatter, unit, error) format4 -> 'a val error_of_printer: ?loc:t -> ?sub:msg list -> (formatter -> 'a -> unit) -> 'a -> error val error_of_printer_file: (formatter -> 'a -> unit) -> 'a -> error val register_error_of_exn: (exn -> error option) -> unit val error_of_exn: exn -> [ `Ok of error | `Already_displayed ] option exception Error of error exception Already_displayed_error val raise_errorf: ?loc:t -> ?sub:msg list -> ('a, Format.formatter, unit, 'b) format4 -> 'a val report_exception: formatter -> exn -> unit * the exception if it is unknown .
7b1057d90ea2c9ad0e002515f5c409ef1c64c74182867739f9459137a64c7526
nh2/conduit-concurrent-map
ConcurrentMap.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # | Functions for concurrent mapping over Conduits . module Data.Conduit.ConcurrentMap ( -- * Explicit number of threads concurrentMapM_ -- * CPU-bound use case , concurrentMapM_numCaps ) where import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import Control.Monad.IO.Unlift (MonadUnliftIO, UnliftIO, unliftIO, askUnliftIO) import Control.Monad.Trans (lift) import Control.Monad.Trans.Resource (MonadResource) import Data.Conduit (ConduitT, await, bracketP) import qualified Data.Conduit as C import Data.Foldable (for_) import Data.Maybe (fromMaybe) import Data.Sequence (Seq, ViewL((:<)), (|>)) import qualified Data.Sequence as Seq import Data.Vector ((!)) import qualified Data.Vector as V import GHC.Conc (getNumCapabilities) import UnliftIO.MVar (MVar, newEmptyMVar, takeMVar, tryTakeMVar, putMVar) import UnliftIO.Async (Async, async, forConcurrently_, wait, link, uninterruptibleCancel) import UnliftIO.IORef (IORef, newIORef, readIORef, atomicModifyIORef') atomicModifyIORef_' :: IORef a -> (a -> a) -> IO () atomicModifyIORef_' ref f = atomicModifyIORef' ref $ \a -> (f a, ()) seqUncons :: Seq a -> (Seq a, Maybe a) seqUncons s = case Seq.viewl s of Seq.EmptyL -> (s, Nothing) a :< s' -> (s', Just a) seqHeadMaybe :: Seq a -> Maybe a seqHeadMaybe s = case Seq.viewl s of Seq.EmptyL -> Nothing a :< _ -> Just a | @concurrentMapM _ workerOutputBufferSize f@ -- -- Concurrent, order-preserving conduit mapping function. -- -- Like `Data.Conduit.mapM`, but runs in parallel with the given number of threads, returns outputs in the order of inputs ( like , no reordering ) , and allows defining a bounded size output buffer for elements of type @b@ to -- maintain high parallelism despite head-of-line blocking. -- -- Because of the no-reordering guarantee, there is head-of-line blocking: -- When the conduit has to process a long-running computation and a short-running -- computation in parallel, the result of short one cannot be yielded before -- the long one is done. -- Unless we buffer the queued result somewhere, the thread that finished the -- short-running computation is now blocked and sits idle (low utilisation). -- -- To cope with this, this function gives each -- thread @workerOutputBufferSize@ output slots to store @b@s while they are blocked. -- Use the convenience ` concurrentMapM_numCaps ` when @f@ is CPU - bound . -- @workerOutputBufferSize@ must be given > = 1 . -- -- The @workerOutputBufferSize@ keeps the memory usage of the conduit bounded, -- namely to @numThreads * (workerOutputBufferSize + 1)@ many @b@s at any -- given time (the @+ 1@ is for the currently processing ones). -- -- To achieve maximum parallelism/utilisation, you should choose -- @workerOutputBufferSize@ ideally as the time factor between the fastest and slowest @f@ that will likely pass through the conduit ; for example , if most @f@s take 3 seconds , but some take 15 seconds , choose @workerOutputBufferSize = 5@ to avoid an earlier 15 - second @f@ blocking a later 3 - second @f@. -- The threads inside the conduit will evaluate the results of the @f@ to WHNF , as in @!b < - f a@ , so do n't forget to make @f@ itself ` deepseq ` the -- result if there is any lazy data structure involved and you want to make -- sure that they are evaluated *inside* the conduit (fully in parallel) -- as opposed to the lazy parts of them being evaluated after being yielded. -- As @f@s happen concurrently , they can not depend on each other 's monadic -- state. This is enforced by the `MonadUnliftIO` constraint. This means the function can not be used with e.g. ` StateT ` . -- -- Properties: -- -- * Ordering / head of line blocking for outputs: The `b`s will come out in -- the same order as their corresponding `a`s came in (the parallelism -- doesn't change the order). -- * Bounded memory: The conduit will only hold to -- @numThreads * (workerOutputBufferSize + 1)@ as many @b@s. * High utilisation : The conduit will try to keep all cores busy as much as -- it can. This means that after `await`ing an input, it will only block -- to wait for an output from a worker thread if it has to because -- we're at the `workerOutputBufferSize` output buffer bound of `b` elements. -- (It may, however, `yield` even if the queue is not full. -- Since `yield` will block the conduit's thread until downstream -- conduits in the pipeline `await`, utilisation will be poor if other -- conduits in the pipeline have low throughput. -- This makes sense because a conduit pipeline's total throughput -- is bottlenecked by the segment in the pipeline.) -- It also ensures that any worker running for longer than others does not -- prevent other free workers from starting new work, except from when -- we're at the `workerOutputBufferSize` output buffer bound of `b` elements. -- * Prompt starting: The conduit will start each `await`ed value immediately, -- it will not batch up multiple `await`s before starting. -- * Async exception safety: When then conduit is killed, the worker threads -- will be killed too. -- -- Example: -- -- > puts :: (MonadIO m) => String -> m () -- for non-interleaved output > puts s = liftIO $ BS8.putStrLn ( BS8.pack s ) > runConduitRes ( CL.sourceList [ 1 .. 6 ] .| concurrentMapM _ 4 ( \i - > liftIO $ puts ( show i + + " before " ) > > threadDelay ( i * 1000000 ) > > puts ( show i + + " after " ) > > return ( i*2 ) ) .| CL.consume ) concurrentMapM_ :: (MonadUnliftIO m, MonadResource m) => Int -> Int -> (a -> m b) -> ConduitT a b m () concurrentMapM_ numThreads workerOutputBufferSize f = do when (workerOutputBufferSize < 1) $ do error $ "Data.Conduit.Concurrent.concurrentMapM_ requires workerOutputBufferSize < 1, got " ++ show workerOutputBufferSize Diagram : -- -- cyclic buffers with `workerOutputBufferSize` many slots {a,b,c,...} for each of N threads -- | [ workerOutVar ( 1 ) a workerOutVar ( 1 ) b ... ] < - f \ ------------------------- [ workerOutVar ( 2 ) a workerOutVar ( 2 ) b ... ] < - f \ outQueue of workerOutVars ... - inVar ------------------------- [ ... ] < - f / -- [ workerOutVar(N )a workerOutVar(N )b ... ] <- f / -- o <- button to signal -- inVarEnqueued -- Any worker that 's not busy is hanging onto ` inVar ` , grabbing its contents as soon as ` inVar ` is filled . -- The conduit ("foreman") `awaits` upstream work, and when it gets some , puts it into the ` inVar ` . -- When a worker manages to grab it, the worker immediately puts its ` workerOutVar ` onto the ` outQueue ` , and then presses the -- `inVarEnqueued` button to tell the foreman that it has completed -- taking the work and placing its `workerOutVar` onto the queue. -- The foreman will wait for the signal button to be pressed before -- continuing their job; this guarantees that the take-inVar-queue-workerOutVar -- action is atomic, which guarantees input order = output order. -- -- As visible in the diagram, maximally N invocations of `f` can happen at -- the same time, and since the `workerOutVar`s are storage places for f 's outputs ( ` b ` ) , maximally N*workerOutputBufferSize many ` b`s are are -- buffered in there while the workers are working. -- When all storage places are full, `f`s that finish processing -- block on putting their `b`s in, so there are maximally -- `N * (workerOutputBufferSize + 1)` many `b`s held alive -- by this function. -- Note that as per this " + 1 " logic , for each worker there may up to 1 ` workerOutVar ` that is in in the ` outQueue ` twice . For example , for ` numThreads = 2 ` and ` workerOutputBufferSize = 2 ` , -- we may have: -- -- ------------------------- [ worker1OutVarSlotA worker1OutVarSlotB ] <- f \ outQueue of workerOutVars - inVar -- ------------------------- [ worker2OutVarSlotA worker2OutVarSlotB ] <- f / -- -- with an input conduit streaming elements -- [A, B, C, D] -- with processing times [ 9 , 0 , 0 , 0 ] this may lead to an ` outQueue ` as follows : -- -- +-----------------------------------+ -- | | -- V | -- ------------------------- [ worker1OutVarSlot_a worker1OutVarSlot_a ] <- f \ -- A B C - inVar (containing element D) -- ------------------------- [ worker2OutVarSlot_b worker2OutVarSlot_b ] <- f / -- ^ ^ | | -- +--|-----------------------------+ | -- | | -- +--------------------------------------------------+ -- where worker 1 is still processing work item A , and worker 2 has just finished -- processing work items B and C. Now worker 2 is idle , pops element D as the next work item from the ` inVar ` , and MVar ` worker2OutVarSlot_b ` into ` outQueue ` , -- processes element D, and runs `putMVar worker2OutVarSlot_b (f D)`; it is at this time that worker 2 blocks until ` worker2OutVarSlot_b ` -- is emptied when the conduit `yield`s the result. -- Thus we have this situation: -- -- +-----------------------------------+ -- | | -- V | -- ------------------------- [ worker1OutVarSlot_a worker1OutVarSlot_a ] <- f \ -- A B C D - inVar -- ------------------------- [ worker2OutVarSlot_b worker2OutVarSlot_b ] <- f / -- ^ ^ ^ | | | -- +--|--|--------------------------+ | | -- | | | | -- +--|-----------------------------|-----------------+ -- | | -- +-----------------------------+ -- It is thus NOT an invariant that every ` outVar ` is in the ` outQueue ` only once . -- -- TODO: This whole design has producing the "+ 1" logic has a bit of an ugliness in that it 's not possible to make each worker use at max 1 ` b ` ; only 2 or more ` b`s are possible . -- The whole design might be simplified by changing it so that instead -- of each worker having a fixed number of `workerOutVar`s, -- workers make up new `workerOutVar`s on demand (enqueuing them into ` outQueue ` as before ) , and the conduit keeping track of how many work items are between ` inVar ` and being yielded -- (this is currently `numInQueue`), and ensuring that this number is < than some maximum number M ( blocking on ` takeMVar ` of the front MVar in ` outQueue ` when the M limit is reached ) . inVar :: MVar (Maybe a) <- newEmptyMVar inVarEnqueued :: MVar () <- newEmptyMVar outQueueRef :: IORef (Seq (MVar b)) <- newIORef Seq.empty let putInVar x = putMVar inVar x let signal mv = putMVar mv () let waitForSignal = takeMVar We use ` MonadUnliftIO ` to make ` f ` run in ` IO ` instead of ` m ` , so that -- we can use it in conduit `bracketP`'s IO-based resource acquisition -- function (where we have to spawn our workers to guarantee they shut down -- when somebody async-kills the conduit). u :: UnliftIO m <- lift askUnliftIO -- `lift` here brings us into `m` -- `spawnWorkers` uses `async` and thus MUST be run with interrupts disabled -- (e.g. as initialisation function of `bracket`) to be async exception safe. -- Note ` async ` does not unmask , but ` unliftIO u ` will restore the original -- masking state (thus typically unmask). let spawnWorkers :: IO (Async ()) spawnWorkers = do workersAsync <- async $ do -- see comment above for exception safety unliftIO u $ liftIO $ do -- use `runInIO` to restore masking state forConcurrently_ [1..numThreads] $ \_i_worker -> do -- Each worker has `workerOutputBufferSize` many `workerOutVar`s -- in a ring buffer; until the shutdown signal is received, a worker loops to : grab an ` a ` from the ` inVar ` , pick its next ` workerOutVar , put it into the ` outQueue ` , signal that it has atomically done these 2 actions , process ` b < - f x ` , and write the ` b ` to the ` workerOutVar ` . workerOutVars <- V.replicateM workerOutputBufferSize newEmptyMVar let loop :: Int -> IO () loop !i_outVarSlot = do m'a <- takeMVar inVar case m'a of Nothing -> return () -- shutdown signal, worker quits Just a -> do let workerOutVar = workerOutVars ! i_outVarSlot atomicModifyIORef_' outQueueRef (|> workerOutVar) signal inVarEnqueued -- Important: Force WHNF here so that f gets evaluated inside the -- worker; it's `f`'s job to decide whether to deepseq or not. !b <- unliftIO u (f a) putMVar workerOutVar b loop ((i_outVarSlot + 1) `rem` workerOutputBufferSize) loop 0 link workersAsync return workersAsync bracketP spawnWorkers (\workersAsync -> uninterruptibleCancel workersAsync) $ \workersAsync -> do let mustBeNonempty = fromMaybe (error "Data.Conduit.Concurrent.concurrentMapM_: outQueue cannot be empty") let yieldQueueHead = do workerVar <- mustBeNonempty <$> atomicModifyIORef' outQueueRef seqUncons b <- takeMVar workerVar C.yield b let tryYieldQueueHead = do m'workerVar <- seqHeadMaybe <$> readIORef outQueueRef case m'workerVar of Nothing -> return False Just workerVar -> do m'b <- tryTakeMVar workerVar case m'b of Nothing -> return False Just b -> do _ <- mustBeNonempty <$> atomicModifyIORef' outQueueRef seqUncons C.yield b return True There are 3 phases in the life of this conduit , which happen subsequentially : 1 ) Ramp - up phase , while we 've received less inputs than we have ` numThreads ` . -- We remember how many elements were received (`numWorkersRampedUp`). 2 ) Cruise phase , -- during which we always have at least `numWorkersRampedUp` many -- `workerOutVar`s in the output queue (this is an invariant). -- At all times `numInQueue` keeps track of how many work units are under processing ( that is , are after being read off the ` inVar ` -- and before being read off an `outVar`; -- so <= `N * (workerOutputBufferSize + 1)` many). -- Cruise phase doesn't happen if the conduit terminates before ` numThreads ` elements are awaited . 3 ) Drain phase , -- in which we drain off the `numInQueue` elements in the queue, -- send all workers the stop signal and wait for their orderly termination. let loop :: Int -> Int -> ConduitT a b m () loop numWorkersRampedUp numInQueue = do await >>= \case Nothing -> do -- Drain phase: Upstream conduit is done. for_ [1..numInQueue] $ \_ -> do yieldQueueHead -- Drain the queue. for_ [1..numThreads] $ \_ -> do putInVar Nothing -- tell all workers to finish. wait workersAsync -- wait for workers to shut down Just a | numWorkersRampedUp < numThreads -> do -- Ramp-up phase: This branch is taken until all `numThreads` -- are doing something or the upstream conduit is done; -- after that it is never taken again. putInVar (Just a) >> waitForSignal inVarEnqueued loop (numWorkersRampedUp + 1) (numInQueue + 1) | otherwise -> do Cruise phase : putInVar (Just a) >> waitForSignal inVarEnqueued -- `waitForSignal` will not block forever because at least the worker in the head of ` outQueue ` will always be able to take the value : -- Either: 1 . it is currently running ` f ` , in which case its ` workerOutVar ` -- is empty, it will eventually write the `b` into it, and then be ready to take the ` inVar ` . 2 . or it has already done that and is currently doing ` takeMVar invar ` -- -- At the time `waitForSignal inVarEnqueued` completes, we know that there is a ` workerOutVar ` in the ` outQueue ` we can wait for . -- -- If it was indeed the `workerOutVar` of the head worker, -- Then we will take that `workerOutVar` below below, to restoring -- the above invariant for the next head worker. let numInQueueAfterEnqueued = numInQueue + 1 let popAsManyAsPossible !remainingInQueue | remainingInQueue < numWorkersRampedUp = error "Data.Conduit.Concurrent.concurrentMapM_: remainingInQueue < numWorkersRampedUp" | remainingInQueue == numWorkersRampedUp = return remainingInQueue | otherwise = do popped <- tryYieldQueueHead if not popped then return remainingInQueue else popAsManyAsPossible (remainingInQueue - 1) remainingInQueue <- popAsManyAsPossible numInQueueAfterEnqueued loop numWorkersRampedUp remainingInQueue loop 0 0 -- | `concurrentMapM_` with the number of threads set to `getNumCapabilities`. -- -- Useful when `f` is CPU-bound. -- -- If `f` is IO-bound, you probably want to use `concurrentMapM_` with -- explicitly given amount of threads instead. concurrentMapM_numCaps :: (MonadUnliftIO m, MonadResource m) => Int -> (a -> m b) -> ConduitT a b m () concurrentMapM_numCaps workerOutputBufferSize f = do numCaps <- liftIO getNumCapabilities concurrentMapM_ numCaps workerOutputBufferSize f
null
https://raw.githubusercontent.com/nh2/conduit-concurrent-map/5dd839f01b3207e3dcb99a099c5aee6540adbe33/src/Data/Conduit/ConcurrentMap.hs
haskell
# LANGUAGE BangPatterns # * Explicit number of threads * CPU-bound use case Concurrent, order-preserving conduit mapping function. Like `Data.Conduit.mapM`, but runs in parallel with the given number of threads, maintain high parallelism despite head-of-line blocking. Because of the no-reordering guarantee, there is head-of-line blocking: When the conduit has to process a long-running computation and a short-running computation in parallel, the result of short one cannot be yielded before the long one is done. Unless we buffer the queued result somewhere, the thread that finished the short-running computation is now blocked and sits idle (low utilisation). To cope with this, this function gives each thread @workerOutputBufferSize@ output slots to store @b@s while they are blocked. The @workerOutputBufferSize@ keeps the memory usage of the conduit bounded, namely to @numThreads * (workerOutputBufferSize + 1)@ many @b@s at any given time (the @+ 1@ is for the currently processing ones). To achieve maximum parallelism/utilisation, you should choose @workerOutputBufferSize@ ideally as the time factor between the fastest result if there is any lazy data structure involved and you want to make sure that they are evaluated *inside* the conduit (fully in parallel) as opposed to the lazy parts of them being evaluated after being yielded. state. This is enforced by the `MonadUnliftIO` constraint. Properties: * Ordering / head of line blocking for outputs: The `b`s will come out in the same order as their corresponding `a`s came in (the parallelism doesn't change the order). * Bounded memory: The conduit will only hold to @numThreads * (workerOutputBufferSize + 1)@ as many @b@s. it can. This means that after `await`ing an input, it will only block to wait for an output from a worker thread if it has to because we're at the `workerOutputBufferSize` output buffer bound of `b` elements. (It may, however, `yield` even if the queue is not full. Since `yield` will block the conduit's thread until downstream conduits in the pipeline `await`, utilisation will be poor if other conduits in the pipeline have low throughput. This makes sense because a conduit pipeline's total throughput is bottlenecked by the segment in the pipeline.) It also ensures that any worker running for longer than others does not prevent other free workers from starting new work, except from when we're at the `workerOutputBufferSize` output buffer bound of `b` elements. * Prompt starting: The conduit will start each `await`ed value immediately, it will not batch up multiple `await`s before starting. * Async exception safety: When then conduit is killed, the worker threads will be killed too. Example: > puts :: (MonadIO m) => String -> m () -- for non-interleaved output cyclic buffers with `workerOutputBufferSize` many slots {a,b,c,...} for each of N threads | ----------------------- [ workerOutVar ( 2 ) a workerOutVar ( 2 ) b ... ] < - f \ ----------------------- [ ... ] < - f / [ workerOutVar(N )a workerOutVar(N )b ... ] <- f / o <- button to signal inVarEnqueued The conduit ("foreman") `awaits` upstream work, and when it gets When a worker manages to grab it, the worker immediately puts `inVarEnqueued` button to tell the foreman that it has completed taking the work and placing its `workerOutVar` onto the queue. The foreman will wait for the signal button to be pressed before continuing their job; this guarantees that the take-inVar-queue-workerOutVar action is atomic, which guarantees input order = output order. As visible in the diagram, maximally N invocations of `f` can happen at the same time, and since the `workerOutVar`s are storage places for buffered in there while the workers are working. When all storage places are full, `f`s that finish processing block on putting their `b`s in, so there are maximally `N * (workerOutputBufferSize + 1)` many `b`s held alive by this function. we may have: ------------------------- [ worker1OutVarSlotA worker1OutVarSlotB ] <- f \ ------------------------- [ worker2OutVarSlotA worker2OutVarSlotB ] <- f / with an input conduit streaming elements [A, B, C, D] with processing times +-----------------------------------+ | | V | ------------------------- [ worker1OutVarSlot_a worker1OutVarSlot_a ] <- f \ A B C - inVar (containing element D) ------------------------- [ worker2OutVarSlot_b worker2OutVarSlot_b ] <- f / ^ ^ | | +--|-----------------------------+ | | | +--------------------------------------------------+ processing work items B and C. processes element D, and runs `putMVar worker2OutVarSlot_b (f D)`; is emptied when the conduit `yield`s the result. Thus we have this situation: +-----------------------------------+ | | V | ------------------------- [ worker1OutVarSlot_a worker1OutVarSlot_a ] <- f \ A B C D - inVar ------------------------- [ worker2OutVarSlot_b worker2OutVarSlot_b ] <- f / ^ ^ ^ | | | +--|--|--------------------------+ | | | | | | +--|-----------------------------|-----------------+ | | +-----------------------------+ TODO: This whole design has producing the "+ 1" logic has a bit of an ugliness The whole design might be simplified by changing it so that instead of each worker having a fixed number of `workerOutVar`s, workers make up new `workerOutVar`s on demand (enqueuing them (this is currently `numInQueue`), and ensuring that this number we can use it in conduit `bracketP`'s IO-based resource acquisition function (where we have to spawn our workers to guarantee they shut down when somebody async-kills the conduit). `lift` here brings us into `m` `spawnWorkers` uses `async` and thus MUST be run with interrupts disabled (e.g. as initialisation function of `bracket`) to be async exception safe. masking state (thus typically unmask). see comment above for exception safety use `runInIO` to restore masking state Each worker has `workerOutputBufferSize` many `workerOutVar`s in a ring buffer; until the shutdown signal is received, a worker shutdown signal, worker quits Important: Force WHNF here so that f gets evaluated inside the worker; it's `f`'s job to decide whether to deepseq or not. We remember how many elements were received (`numWorkersRampedUp`). during which we always have at least `numWorkersRampedUp` many `workerOutVar`s in the output queue (this is an invariant). At all times `numInQueue` keeps track of how many work units and before being read off an `outVar`; so <= `N * (workerOutputBufferSize + 1)` many). Cruise phase doesn't happen if the conduit terminates before in which we drain off the `numInQueue` elements in the queue, send all workers the stop signal and wait for their orderly termination. Drain phase: Upstream conduit is done. Drain the queue. tell all workers to finish. wait for workers to shut down Ramp-up phase: This branch is taken until all `numThreads` are doing something or the upstream conduit is done; after that it is never taken again. `waitForSignal` will not block forever because at least the worker Either: is empty, it will eventually write the `b` into it, and then At the time `waitForSignal inVarEnqueued` completes, we know If it was indeed the `workerOutVar` of the head worker, Then we will take that `workerOutVar` below below, to restoring the above invariant for the next head worker. | `concurrentMapM_` with the number of threads set to `getNumCapabilities`. Useful when `f` is CPU-bound. If `f` is IO-bound, you probably want to use `concurrentMapM_` with explicitly given amount of threads instead.
# LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # | Functions for concurrent mapping over Conduits . module Data.Conduit.ConcurrentMap concurrentMapM_ , concurrentMapM_numCaps ) where import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import Control.Monad.IO.Unlift (MonadUnliftIO, UnliftIO, unliftIO, askUnliftIO) import Control.Monad.Trans (lift) import Control.Monad.Trans.Resource (MonadResource) import Data.Conduit (ConduitT, await, bracketP) import qualified Data.Conduit as C import Data.Foldable (for_) import Data.Maybe (fromMaybe) import Data.Sequence (Seq, ViewL((:<)), (|>)) import qualified Data.Sequence as Seq import Data.Vector ((!)) import qualified Data.Vector as V import GHC.Conc (getNumCapabilities) import UnliftIO.MVar (MVar, newEmptyMVar, takeMVar, tryTakeMVar, putMVar) import UnliftIO.Async (Async, async, forConcurrently_, wait, link, uninterruptibleCancel) import UnliftIO.IORef (IORef, newIORef, readIORef, atomicModifyIORef') atomicModifyIORef_' :: IORef a -> (a -> a) -> IO () atomicModifyIORef_' ref f = atomicModifyIORef' ref $ \a -> (f a, ()) seqUncons :: Seq a -> (Seq a, Maybe a) seqUncons s = case Seq.viewl s of Seq.EmptyL -> (s, Nothing) a :< s' -> (s', Just a) seqHeadMaybe :: Seq a -> Maybe a seqHeadMaybe s = case Seq.viewl s of Seq.EmptyL -> Nothing a :< _ -> Just a | @concurrentMapM _ workerOutputBufferSize f@ returns outputs in the order of inputs ( like , no reordering ) , and allows defining a bounded size output buffer for elements of type @b@ to Use the convenience ` concurrentMapM_numCaps ` when @f@ is CPU - bound . @workerOutputBufferSize@ must be given > = 1 . and slowest @f@ that will likely pass through the conduit ; for example , if most @f@s take 3 seconds , but some take 15 seconds , choose @workerOutputBufferSize = 5@ to avoid an earlier 15 - second @f@ blocking a later 3 - second @f@. The threads inside the conduit will evaluate the results of the @f@ to WHNF , as in @!b < - f a@ , so do n't forget to make @f@ itself ` deepseq ` the As @f@s happen concurrently , they can not depend on each other 's monadic This means the function can not be used with e.g. ` StateT ` . * High utilisation : The conduit will try to keep all cores busy as much as > puts s = liftIO $ BS8.putStrLn ( BS8.pack s ) > runConduitRes ( CL.sourceList [ 1 .. 6 ] .| concurrentMapM _ 4 ( \i - > liftIO $ puts ( show i + + " before " ) > > threadDelay ( i * 1000000 ) > > puts ( show i + + " after " ) > > return ( i*2 ) ) .| CL.consume ) concurrentMapM_ :: (MonadUnliftIO m, MonadResource m) => Int -> Int -> (a -> m b) -> ConduitT a b m () concurrentMapM_ numThreads workerOutputBufferSize f = do when (workerOutputBufferSize < 1) $ do error $ "Data.Conduit.Concurrent.concurrentMapM_ requires workerOutputBufferSize < 1, got " ++ show workerOutputBufferSize Diagram : [ workerOutVar ( 1 ) a workerOutVar ( 1 ) b ... ] < - f \ outQueue of workerOutVars ... - inVar Any worker that 's not busy is hanging onto ` inVar ` , grabbing its contents as soon as ` inVar ` is filled . some , puts it into the ` inVar ` . its ` workerOutVar ` onto the ` outQueue ` , and then presses the f 's outputs ( ` b ` ) , maximally N*workerOutputBufferSize many ` b`s are are Note that as per this " + 1 " logic , for each worker there may up to 1 ` workerOutVar ` that is in in the ` outQueue ` twice . For example , for ` numThreads = 2 ` and ` workerOutputBufferSize = 2 ` , outQueue of workerOutVars - inVar [ 9 , 0 , 0 , 0 ] this may lead to an ` outQueue ` as follows : where worker 1 is still processing work item A , and worker 2 has just finished Now worker 2 is idle , pops element D as the next work item from the ` inVar ` , and MVar ` worker2OutVarSlot_b ` into ` outQueue ` , it is at this time that worker 2 blocks until ` worker2OutVarSlot_b ` It is thus NOT an invariant that every ` outVar ` is in the ` outQueue ` only once . in that it 's not possible to make each worker use at max 1 ` b ` ; only 2 or more ` b`s are possible . into ` outQueue ` as before ) , and the conduit keeping track of how many work items are between ` inVar ` and being yielded is < than some maximum number M ( blocking on ` takeMVar ` of the front MVar in ` outQueue ` when the M limit is reached ) . inVar :: MVar (Maybe a) <- newEmptyMVar inVarEnqueued :: MVar () <- newEmptyMVar outQueueRef :: IORef (Seq (MVar b)) <- newIORef Seq.empty let putInVar x = putMVar inVar x let signal mv = putMVar mv () let waitForSignal = takeMVar We use ` MonadUnliftIO ` to make ` f ` run in ` IO ` instead of ` m ` , so that Note ` async ` does not unmask , but ` unliftIO u ` will restore the original let spawnWorkers :: IO (Async ()) spawnWorkers = do forConcurrently_ [1..numThreads] $ \_i_worker -> do loops to : grab an ` a ` from the ` inVar ` , pick its next ` workerOutVar , put it into the ` outQueue ` , signal that it has atomically done these 2 actions , process ` b < - f x ` , and write the ` b ` to the ` workerOutVar ` . workerOutVars <- V.replicateM workerOutputBufferSize newEmptyMVar let loop :: Int -> IO () loop !i_outVarSlot = do m'a <- takeMVar inVar case m'a of Just a -> do let workerOutVar = workerOutVars ! i_outVarSlot atomicModifyIORef_' outQueueRef (|> workerOutVar) signal inVarEnqueued !b <- unliftIO u (f a) putMVar workerOutVar b loop ((i_outVarSlot + 1) `rem` workerOutputBufferSize) loop 0 link workersAsync return workersAsync bracketP spawnWorkers (\workersAsync -> uninterruptibleCancel workersAsync) $ \workersAsync -> do let mustBeNonempty = fromMaybe (error "Data.Conduit.Concurrent.concurrentMapM_: outQueue cannot be empty") let yieldQueueHead = do workerVar <- mustBeNonempty <$> atomicModifyIORef' outQueueRef seqUncons b <- takeMVar workerVar C.yield b let tryYieldQueueHead = do m'workerVar <- seqHeadMaybe <$> readIORef outQueueRef case m'workerVar of Nothing -> return False Just workerVar -> do m'b <- tryTakeMVar workerVar case m'b of Nothing -> return False Just b -> do _ <- mustBeNonempty <$> atomicModifyIORef' outQueueRef seqUncons C.yield b return True There are 3 phases in the life of this conduit , which happen subsequentially : 1 ) Ramp - up phase , while we 've received less inputs than we have ` numThreads ` . 2 ) Cruise phase , are under processing ( that is , are after being read off the ` inVar ` ` numThreads ` elements are awaited . 3 ) Drain phase , let loop :: Int -> Int -> ConduitT a b m () loop numWorkersRampedUp numInQueue = do await >>= \case for_ [1..numInQueue] $ \_ -> do for_ [1..numThreads] $ \_ -> do Just a | numWorkersRampedUp < numThreads -> do putInVar (Just a) >> waitForSignal inVarEnqueued loop (numWorkersRampedUp + 1) (numInQueue + 1) | otherwise -> do Cruise phase : putInVar (Just a) >> waitForSignal inVarEnqueued in the head of ` outQueue ` will always be able to take the value : 1 . it is currently running ` f ` , in which case its ` workerOutVar ` be ready to take the ` inVar ` . 2 . or it has already done that and is currently doing ` takeMVar invar ` that there is a ` workerOutVar ` in the ` outQueue ` we can wait for . let numInQueueAfterEnqueued = numInQueue + 1 let popAsManyAsPossible !remainingInQueue | remainingInQueue < numWorkersRampedUp = error "Data.Conduit.Concurrent.concurrentMapM_: remainingInQueue < numWorkersRampedUp" | remainingInQueue == numWorkersRampedUp = return remainingInQueue | otherwise = do popped <- tryYieldQueueHead if not popped then return remainingInQueue else popAsManyAsPossible (remainingInQueue - 1) remainingInQueue <- popAsManyAsPossible numInQueueAfterEnqueued loop numWorkersRampedUp remainingInQueue loop 0 0 concurrentMapM_numCaps :: (MonadUnliftIO m, MonadResource m) => Int -> (a -> m b) -> ConduitT a b m () concurrentMapM_numCaps workerOutputBufferSize f = do numCaps <- liftIO getNumCapabilities concurrentMapM_ numCaps workerOutputBufferSize f
c0d47806109c192ec79b38b0314a42a2fa06e73fec2742bdae67c9e51f163d06
camlp5/camlp5
pa_rp.ml
(* camlp5r *) (* pa_rp.ml,v *) Copyright ( c ) INRIA 2007 - 2017 #load "pa_extend.cmo"; #load "q_MLast.cmo"; open Asttools; open Exparser; open Pcaml; Syntax extensions in Revised Syntax grammar EXTEND GLOBAL: expr ipatt ext_attributes; expr: LEVEL "top" [ [ "parser"; po = OPT ipatt; "["; pcl = LIST0 parser_case SEP "|"; "]" -> <:expr< $cparser loc (po, pcl)$ >> | "parser"; po = OPT ipatt; pc = parser_case -> <:expr< $cparser loc (po, [pc])$ >> | "match"; (ext,attrs) = ext_attributes; e = SELF; "with"; "parser"; po = OPT ipatt; "["; pcl = LIST0 parser_case SEP "|"; "]" -> expr_to_inline <:expr< $cparser_match loc e (po, pcl)$ >> ext attrs | "match"; (ext,attrs) = ext_attributes; e = SELF; "with"; "parser"; po = OPT ipatt; pc = parser_case -> expr_to_inline <:expr< $cparser_match loc e (po, [pc])$ >> ext attrs ] ] ; parser_case: [ [ "[:"; sp = stream_patt; ":]"; po = OPT ipatt; "->"; e = expr -> (sp, po, e) ] ] ; stream_patt: [ [ spc = stream_patt_comp -> [(spc, SpoNoth)] | spc = stream_patt_comp; ";"; sp = stream_patt_kont -> [(spc, SpoNoth) :: sp] | spc = stream_patt_let; sp = stream_patt -> [spc :: sp] | -> [] ] ] ; stream_patt_kont: [ [ spc = stream_patt_comp_err -> [spc] | spc = stream_patt_comp_err; ";"; sp = stream_patt_kont -> [spc :: sp] | spc = stream_patt_let; sp = stream_patt_kont -> [spc :: sp] ] ] ; stream_patt_comp_err: [ [ spc = stream_patt_comp; "?"; e = expr -> (spc, SpoQues e) | spc = stream_patt_comp; "!" -> (spc, SpoBang) | spc = stream_patt_comp -> (spc, SpoNoth) ] ] ; stream_patt_comp: [ [ "`"; p = patt; eo = V (OPT [ "when"; e = expr -> e ]) -> SpTrm loc p eo | "?="; pll = LIST1 lookahead SEP "|" -> SpLhd loc pll | p = patt; "="; e = expr -> SpNtr loc p e | p = patt -> SpStr loc p ] ] ; stream_patt_let: [ [ "let"; p = ipatt; "="; e = expr; "in" -> (SpLet loc p e, SpoNoth) ] ] ; lookahead: [ [ "["; pl = LIST1 patt SEP ";"; "]" -> pl ] ] ; expr: LEVEL "simple" [ [ "[:"; se = LIST0 stream_expr_comp SEP ";"; ":]" -> <:expr< $cstream loc se$ >> ] ] ; stream_expr_comp: [ [ "`"; e = expr -> SeTrm loc e | e = expr -> SeNtr loc e ] ] ; END;
null
https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/meta/pa_rp.ml
ocaml
camlp5r pa_rp.ml,v
Copyright ( c ) INRIA 2007 - 2017 #load "pa_extend.cmo"; #load "q_MLast.cmo"; open Asttools; open Exparser; open Pcaml; Syntax extensions in Revised Syntax grammar EXTEND GLOBAL: expr ipatt ext_attributes; expr: LEVEL "top" [ [ "parser"; po = OPT ipatt; "["; pcl = LIST0 parser_case SEP "|"; "]" -> <:expr< $cparser loc (po, pcl)$ >> | "parser"; po = OPT ipatt; pc = parser_case -> <:expr< $cparser loc (po, [pc])$ >> | "match"; (ext,attrs) = ext_attributes; e = SELF; "with"; "parser"; po = OPT ipatt; "["; pcl = LIST0 parser_case SEP "|"; "]" -> expr_to_inline <:expr< $cparser_match loc e (po, pcl)$ >> ext attrs | "match"; (ext,attrs) = ext_attributes; e = SELF; "with"; "parser"; po = OPT ipatt; pc = parser_case -> expr_to_inline <:expr< $cparser_match loc e (po, [pc])$ >> ext attrs ] ] ; parser_case: [ [ "[:"; sp = stream_patt; ":]"; po = OPT ipatt; "->"; e = expr -> (sp, po, e) ] ] ; stream_patt: [ [ spc = stream_patt_comp -> [(spc, SpoNoth)] | spc = stream_patt_comp; ";"; sp = stream_patt_kont -> [(spc, SpoNoth) :: sp] | spc = stream_patt_let; sp = stream_patt -> [spc :: sp] | -> [] ] ] ; stream_patt_kont: [ [ spc = stream_patt_comp_err -> [spc] | spc = stream_patt_comp_err; ";"; sp = stream_patt_kont -> [spc :: sp] | spc = stream_patt_let; sp = stream_patt_kont -> [spc :: sp] ] ] ; stream_patt_comp_err: [ [ spc = stream_patt_comp; "?"; e = expr -> (spc, SpoQues e) | spc = stream_patt_comp; "!" -> (spc, SpoBang) | spc = stream_patt_comp -> (spc, SpoNoth) ] ] ; stream_patt_comp: [ [ "`"; p = patt; eo = V (OPT [ "when"; e = expr -> e ]) -> SpTrm loc p eo | "?="; pll = LIST1 lookahead SEP "|" -> SpLhd loc pll | p = patt; "="; e = expr -> SpNtr loc p e | p = patt -> SpStr loc p ] ] ; stream_patt_let: [ [ "let"; p = ipatt; "="; e = expr; "in" -> (SpLet loc p e, SpoNoth) ] ] ; lookahead: [ [ "["; pl = LIST1 patt SEP ";"; "]" -> pl ] ] ; expr: LEVEL "simple" [ [ "[:"; se = LIST0 stream_expr_comp SEP ";"; ":]" -> <:expr< $cstream loc se$ >> ] ] ; stream_expr_comp: [ [ "`"; e = expr -> SeTrm loc e | e = expr -> SeNtr loc e ] ] ; END;
4439ce8aac9cdc0f0780eeee0badcd3caa5f02006c06937f8ddebb58e4771342
ocaml/ocaml
typeclass.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Parsetree open Asttypes open Path open Types open Typecore open Typetexp open Format type 'a class_info = { cls_id : Ident.t; cls_id_loc : string loc; cls_decl : class_declaration; cls_ty_id : Ident.t; cls_ty_decl : class_type_declaration; cls_obj_id : Ident.t; cls_obj_abbr : type_declaration; cls_abbr : type_declaration; cls_arity : int; cls_pub_methods : string list; cls_info : 'a; } type class_type_info = { clsty_ty_id : Ident.t; clsty_id_loc : string loc; clsty_ty_decl : class_type_declaration; clsty_obj_id : Ident.t; clsty_obj_abbr : type_declaration; clsty_abbr : type_declaration; clsty_info : Typedtree.class_type_declaration; } type 'a full_class = { id : Ident.t; id_loc : tag loc; clty: class_declaration; ty_id: Ident.t; cltydef: class_type_declaration; obj_id: Ident.t; obj_abbr: type_declaration; arity: int; pub_meths: string list; coe: Warnings.loc list; req: 'a Typedtree.class_infos; } type kind = | Object | Class | Class_type type final = | Final | Not_final let kind_of_final = function | Final -> Object | Not_final -> Class type error = | Unconsistent_constraint of Errortrace.unification_error | Field_type_mismatch of string * string * Errortrace.unification_error | Unexpected_field of type_expr * string | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of arg_label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class_2 of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * Errortrace.unification_error | Virtual_class of kind * string list * string list | Undeclared_methods of kind * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of Errortrace.unification_error | Bad_parameters of Ident.t * type_expr list * type_expr list | Bad_class_type_parameters of Ident.t * type_expr list * type_expr list | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * Errortrace.unification_error | Self_clash of Errortrace.unification_error | Mutability_mismatch of string * mutable_flag | No_overriding of string * string | Duplicate of string * string | Closing_self_type of class_signature exception Error of Location.t * Env.t * error exception Error_forward of Location.error open Typedtree let type_open_descr : (?used_slot:bool ref -> Env.t -> Parsetree.open_description -> open_description * Env.t) ref = ref (fun ?used_slot:_ _ -> assert false) let ctyp desc typ env loc = { ctyp_desc = desc; ctyp_type = typ; ctyp_loc = loc; ctyp_env = env; ctyp_attributes = [] } (* Path associated to the temporary class type of a class being typed (its constructor is not available). *) let unbound_class = Path.Pident (Ident.create_local "*undef*") (************************************) (* Some operations on class types *) (************************************) let extract_constraints cty = let sign = Btype.signature_of_class_type cty in (Btype.instance_vars sign, Btype.methods sign, Btype.concrete_methods sign) (* Record a class type *) let rc node = Cmt_format.add_saved_type (Cmt_format.Partial_class_expr node); node let update_class_signature loc env ~warn_implicit_public virt kind sign = let implicit_public, implicit_declared = Ctype.update_class_signature env sign in if implicit_declared <> [] then begin match virt with Should perhaps emit warning 17 here | Concrete -> raise (Error(loc, env, Undeclared_methods(kind, implicit_declared))) end; if warn_implicit_public && implicit_public <> [] then begin Location.prerr_warning loc (Warnings.Implicit_public_methods implicit_public) end let complete_class_signature loc env virt kind sign = update_class_signature loc env ~warn_implicit_public:false virt kind sign; Ctype.hide_private_methods env sign let complete_class_type loc env virt kind typ = let sign = Btype.signature_of_class_type typ in complete_class_signature loc env virt kind sign let check_virtual loc env virt kind sign = match virt with | Virtual -> () | Concrete -> match Btype.virtual_methods sign, Btype.virtual_instance_vars sign with | [], [] -> () | meths, vars -> raise(Error(loc, env, Virtual_class(kind, meths, vars))) let rec check_virtual_clty loc env virt kind clty = match clty with | Cty_constr(_, _, clty) | Cty_arrow(_, _, clty) -> check_virtual_clty loc env virt kind clty | Cty_signature sign -> check_virtual loc env virt kind sign (* Return the constructor type associated to a class type *) let rec constructor_type constr cty = match cty with Cty_constr (_, _, cty) -> constructor_type constr cty | Cty_signature _ -> constr | Cty_arrow (l, ty, cty) -> Ctype.newty (Tarrow (l, ty, constructor_type constr cty, commu_ok)) (***********************************) (* Primitives for typing classes *) (***********************************) let raise_add_method_failure loc env label sign failure = match (failure : Ctype.add_method_failure) with | Ctype.Unexpected_method -> raise(Error(loc, env, Unexpected_field (sign.Types.csig_self, label))) | Ctype.Type_mismatch trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let raise_add_instance_variable_failure loc env label failure = match (failure : Ctype.add_instance_variable_failure) with | Ctype.Mutability_mismatch mut -> raise (Error(loc, env, Mutability_mismatch(label, mut))) | Ctype.Type_mismatch trace -> raise (Error(loc, env, Field_type_mismatch("instance variable", label, trace))) let raise_inherit_class_signature_failure loc env sign = function | Ctype.Self_type_mismatch trace -> raise(Error(loc, env, Self_clash trace)) | Ctype.Method(label, failure) -> raise_add_method_failure loc env label sign failure | Ctype.Instance_variable(label, failure) -> raise_add_instance_variable_failure loc env label failure let add_method loc env label priv virt ty sign = match Ctype.add_method env label priv virt ty sign with | () -> () | exception Ctype.Add_method_failed failure -> raise_add_method_failure loc env label sign failure let add_instance_variable ~strict loc env label mut virt ty sign = match Ctype.add_instance_variable ~strict env label mut virt ty sign with | () -> () | exception Ctype.Add_instance_variable_failed failure -> raise_add_instance_variable_failure loc env label failure let inherit_class_signature ~strict loc env sign1 sign2 = match Ctype.inherit_class_signature ~strict env sign1 sign2 with | () -> () | exception Ctype.Inherit_class_signature_failed failure -> raise_inherit_class_signature_failure loc env sign1 failure let inherit_class_type ~strict loc env sign1 cty2 = let sign2 = match Btype.scrape_class_type cty2 with | Cty_signature sign2 -> sign2 | _ -> raise(Error(loc, env, Structure_expected cty2)) in inherit_class_signature ~strict loc env sign1 sign2 let unify_delayed_method_type loc env label ty expected_ty= match Ctype.unify env ty expected_ty with | () -> () | exception Ctype.Unify trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let type_constraint val_env sty sty' loc = let cty = transl_simple_type val_env ~closed:false sty in let ty = cty.ctyp_type in let cty' = transl_simple_type val_env ~closed:false sty' in let ty' = cty'.ctyp_type in begin try Ctype.unify val_env ty ty' with Ctype.Unify err -> raise(Error(loc, val_env, Unconsistent_constraint err)); end; (cty, cty') let make_method loc cl_num expr = let open Ast_helper in let mkid s = mkloc s loc in Exp.fun_ ~loc:expr.pexp_loc Nolabel None (Pat.alias ~loc (Pat.var ~loc (mkid "self-*")) (mkid ("self-" ^ cl_num))) expr (*******************************) let delayed_meth_specs = ref [] let rec class_type_field env sign self_scope ctf = let loc = ctf.pctf_loc in let mkctf desc = { ctf_desc = desc; ctf_loc = loc; ctf_attributes = ctf.pctf_attributes } in let mkctf_with_attrs f = Builtin_attributes.warning_scope ctf.pctf_attributes (fun () -> mkctf (f ())) in match ctf.pctf_desc with | Pctf_inherit sparent -> mkctf_with_attrs (fun () -> let parent = class_type env Virtual self_scope sparent in complete_class_type parent.cltyp_loc env Virtual Class_type parent.cltyp_type; inherit_class_type ~strict:false loc env sign parent.cltyp_type; Tctf_inherit parent) | Pctf_val ({txt=lab}, mut, virt, sty) -> mkctf_with_attrs (fun () -> let cty = transl_simple_type env ~closed:false sty in let ty = cty.ctyp_type in add_instance_variable ~strict:false loc env lab mut virt ty sign; Tctf_val (lab, mut, virt, cty)) | Pctf_method ({txt=lab}, priv, virt, sty) -> mkctf_with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in match sty.ptyp_desc, priv with | Ptyp_poly ([],sty'), Public -> let expected_ty = Ctype.newvar () in add_method loc env lab priv virt expected_ty sign; let returned_cty = ctyp Ttyp_any (Ctype.newty Tnil) env loc in delayed_meth_specs := Warnings.mk_lazy (fun () -> let cty = transl_simple_type_univars env sty' in let ty = cty.ctyp_type in unify_delayed_method_type loc env lab ty expected_ty; returned_cty.ctyp_desc <- Ttyp_poly ([], cty); returned_cty.ctyp_type <- ty; ) :: !delayed_meth_specs; Tctf_method (lab, priv, virt, returned_cty) | _ -> let cty = transl_simple_type env ~closed:false sty in let ty = cty.ctyp_type in add_method loc env lab priv virt ty sign; Tctf_method (lab, priv, virt, cty)) | Pctf_constraint (sty, sty') -> mkctf_with_attrs (fun () -> let (cty, cty') = type_constraint env sty sty' ctf.pctf_loc in Tctf_constraint (cty, cty')) | Pctf_attribute x -> Builtin_attributes.warning_attribute x; mkctf (Tctf_attribute x) | Pctf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_signature virt env pcsig self_scope loc = let {pcsig_self=sty; pcsig_fields=psign} = pcsig in let sign = Ctype.new_class_signature () in (* Introduce a dummy method preventing self type from being closed. *) Ctype.add_dummy_method env ~scope:self_scope sign; let self_cty = transl_simple_type env ~closed:false sty in let self_type = self_cty.ctyp_type in begin try Ctype.unify env self_type sign.csig_self with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, env, Pattern_type_clash self_type)) end; (* Class type fields *) let fields = Builtin_attributes.warning_scope [] (fun () -> List.map (class_type_field env sign self_scope) psign) in check_virtual loc env virt Class_type sign; { csig_self = self_cty; csig_fields = fields; csig_type = sign; } and class_type env virt self_scope scty = Builtin_attributes.warning_scope scty.pcty_attributes (fun () -> class_type_aux env virt self_scope scty) and class_type_aux env virt self_scope scty = let cltyp desc typ = { cltyp_desc = desc; cltyp_type = typ; cltyp_loc = scty.pcty_loc; cltyp_env = env; cltyp_attributes = scty.pcty_attributes; } in match scty.pcty_desc with | Pcty_constr (lid, styl) -> let (path, decl) = Env.lookup_cltype ~loc:scty.pcty_loc lid.txt env in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, env, Unbound_class_type_2 lid.txt)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in (* Adding a dummy method to the self type prevents it from being closed / escaping. *) Ctype.add_dummy_method env ~scope:self_scope (Btype.signature_of_class_type clty); if List.length params <> List.length styl then raise(Error(scty.pcty_loc, env, Parameter_arity_mismatch (lid.txt, List.length params, List.length styl))); let ctys = List.map2 (fun sty ty -> let cty' = transl_simple_type env ~closed:false sty in let ty' = cty'.ctyp_type in begin try Ctype.unify env ty' ty with Ctype.Unify err -> raise(Error(sty.ptyp_loc, env, Parameter_mismatch err)) end; cty' ) styl params in let typ = Cty_constr (path, params, clty) in (* Check for unexpected virtual methods *) check_virtual_clty scty.pcty_loc env virt Class_type typ; cltyp (Tcty_constr ( path, lid , ctys)) typ | Pcty_signature pcsig -> let clsig = class_signature virt env pcsig self_scope scty.pcty_loc in let typ = Cty_signature clsig.csig_type in cltyp (Tcty_signature clsig) typ | Pcty_arrow (l, sty, scty) -> let cty = transl_simple_type env ~closed:false sty in let ty = cty.ctyp_type in let ty = if Btype.is_optional l then Ctype.newty (Tconstr(Predef.path_option,[ty], ref Mnil)) else ty in let clty = class_type env virt self_scope scty in let typ = Cty_arrow (l, ty, clty.cltyp_type) in cltyp (Tcty_arrow (l, cty, clty)) typ | Pcty_open (od, e) -> let (od, newenv) = !type_open_descr env od in let clty = class_type newenv virt self_scope e in cltyp (Tcty_open (od, clty)) clty.cltyp_type | Pcty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) let class_type env virt self_scope scty = delayed_meth_specs := []; let cty = class_type env virt self_scope scty in List.iter Lazy.force (List.rev !delayed_meth_specs); delayed_meth_specs := []; cty (*******************************) let enter_ancestor_val name val_env = Env.enter_unbound_value name Val_unbound_ancestor val_env let enter_self_val name val_env = Env.enter_unbound_value name Val_unbound_self val_env let enter_instance_var_val name val_env = Env.enter_unbound_value name Val_unbound_instance_variable val_env let enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env = let check s = Warnings.Unused_ancestor s in let kind = Val_anc (sign, meths, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.enter_value ~check name desc met_env let add_self_met loc id sign self_var_kind vars cl_num as_var ty attrs met_env = let check = if as_var then (fun s -> Warnings.Unused_var s) else (fun s -> Warnings.Unused_var_strict s) in let kind = Val_self (sign, self_var_kind, vars, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value ~check id desc met_env let add_instance_var_met loc label id sign cl_num attrs met_env = let mut, ty = match Vars.find label sign.csig_vars with | (mut, _, ty) -> mut, ty | exception Not_found -> assert false in let kind = Val_ivar (mut, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value id desc met_env let add_instance_vars_met loc vars sign cl_num met_env = List.fold_left (fun met_env (label, id) -> add_instance_var_met loc label id sign cl_num [] met_env) met_env vars type intermediate_class_field = | Inherit of { override : override_flag; parent : class_expr; super : string option; inherited_vars : (string * Ident.t) list; super_meths : (string * Ident.t) list; loc : Location.t; attributes : attribute list; } | Virtual_val of { label : string loc; mut : mutable_flag; id : Ident.t; cty : core_type; already_declared : bool; loc : Location.t; attributes : attribute list; } | Concrete_val of { label : string loc; mut : mutable_flag; id : Ident.t; override : override_flag; definition : expression; already_declared : bool; loc : Location.t; attributes : attribute list; } | Virtual_method of { label : string loc; priv : private_flag; cty : core_type; loc : Location.t; attributes : attribute list; } | Concrete_method of { label : string loc; priv : private_flag; override : override_flag; sdefinition : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Constraint of { cty1 : core_type; cty2 : core_type; loc : Location.t; attributes : attribute list; } | Initializer of { sexpr : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Attribute of { attribute : attribute; loc : Location.t; attributes : attribute list; } type first_pass_accummulater = { rev_fields : intermediate_class_field list; val_env : Env.t; par_env : Env.t; concrete_meths : MethSet.t; concrete_vals : VarSet.t; local_meths : MethSet.t; local_vals : VarSet.t; vars : Ident.t Vars.t; } let rec class_field_first_pass self_loc cl_num sign self_scope acc cf = let { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } = acc in let loc = cf.pcf_loc in let attributes = cf.pcf_attributes in let with_attrs f = Builtin_attributes.warning_scope attributes f in match cf.pcf_desc with | Pcf_inherit (override, sparent, super) -> with_attrs (fun () -> let parent = class_expr cl_num val_env par_env Virtual self_scope sparent in complete_class_type parent.cl_loc par_env Virtual Class parent.cl_type; inherit_class_type ~strict:true loc val_env sign parent.cl_type; let parent_sign = Btype.signature_of_class_type parent.cl_type in let new_concrete_meths = Btype.concrete_methods parent_sign in let new_concrete_vals = Btype.concrete_instance_vars parent_sign in let over_meths = MethSet.inter new_concrete_meths concrete_meths in let over_vals = VarSet.inter new_concrete_vals concrete_vals in begin match override with | Fresh -> let cname = match parent.cl_type with | Cty_constr (p, _, _) -> Path.name p | _ -> "inherited" in if not (MethSet.is_empty over_meths) then Location.prerr_warning loc (Warnings.Method_override (cname :: MethSet.elements over_meths)); if not (VarSet.is_empty over_vals) then Location.prerr_warning loc (Warnings.Instance_variable_override (cname :: VarSet.elements over_vals)); | Override -> if MethSet.is_empty over_meths && VarSet.is_empty over_vals then raise (Error(loc, val_env, No_overriding ("",""))) end; let concrete_vals = VarSet.union new_concrete_vals concrete_vals in let concrete_meths = MethSet.union new_concrete_meths concrete_meths in let val_env, par_env, inherited_vars, vars = Vars.fold (fun label _ (val_env, par_env, inherited_vars, vars) -> let val_env = enter_instance_var_val label val_env in let par_env = enter_instance_var_val label par_env in let id = Ident.create_local label in let inherited_vars = (label, id) :: inherited_vars in let vars = Vars.add label id vars in (val_env, par_env, inherited_vars, vars)) parent_sign.csig_vars (val_env, par_env, [], vars) in (* Methods available through super *) let super_meths = MethSet.fold (fun label acc -> (label, Ident.create_local label) :: acc) new_concrete_meths [] in Super let (val_env, par_env, super) = match super with | None -> (val_env, par_env, None) | Some {txt=name} -> let val_env = enter_ancestor_val name val_env in let par_env = enter_ancestor_val name par_env in (val_env, par_env, Some name) in let field = Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; concrete_meths; concrete_vals; vars }) | Pcf_val (label, mut, Cfk_virtual styp) -> with_attrs (fun () -> let cty = Ctype.with_local_level_if_principal (fun () -> Typetexp.transl_simple_type val_env ~closed:false styp) ~post:(fun cty -> Ctype.generalize_structure cty.ctyp_type) in add_instance_variable ~strict:true loc val_env label.txt mut Virtual cty.ctyp_type sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Virtual_val { label; mut; id; cty; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; vars }) | Pcf_val (label, mut, Cfk_concrete (override, sdefinition)) -> with_attrs (fun () -> if VarSet.mem label.txt local_vals then raise(Error(loc, val_env, Duplicate ("instance variable", label.txt))); if VarSet.mem label.txt concrete_vals then begin if override = Fresh then Location.prerr_warning label.loc (Warnings.Instance_variable_override[label.txt]) end else begin if override = Override then raise(Error(loc, val_env, No_overriding ("instance variable", label.txt))) end; let definition = Ctype.with_local_level_if_principal ~post:Typecore.generalize_structure_exp (fun () -> type_exp val_env sdefinition) in add_instance_variable ~strict:true loc val_env label.txt mut Concrete definition.exp_type sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_vals = VarSet.add label.txt concrete_vals in let local_vals = VarSet.add label.txt local_vals in { acc with rev_fields; val_env; par_env; concrete_vals; local_vals; vars }) | Pcf_method (label, priv, Cfk_virtual sty) -> with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in let cty = transl_simple_type val_env ~closed:false sty in let ty = cty.ctyp_type in add_method loc val_env label.txt priv Virtual ty sign; let field = Virtual_method { label; priv; cty; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_method (label, priv, Cfk_concrete (override, expr)) -> with_attrs (fun () -> if MethSet.mem label.txt local_meths then raise(Error(loc, val_env, Duplicate ("method", label.txt))); if MethSet.mem label.txt concrete_meths then begin if override = Fresh then begin Location.prerr_warning loc (Warnings.Method_override [label.txt]) end end else begin if override = Override then begin raise(Error(loc, val_env, No_overriding("method", label.txt))) end end; let expr = match expr.pexp_desc with | Pexp_poly _ -> expr | _ -> Ast_helper.Exp.poly ~loc:expr.pexp_loc expr None in let sbody, sty = match expr.pexp_desc with | Pexp_poly (sbody, sty) -> sbody, sty | _ -> assert false in let ty = match sty with | None -> Ctype.newvar () | Some sty -> let sty = Ast_helper.Typ.force_poly sty in let cty' = Typetexp.transl_simple_type val_env ~closed:false sty in cty'.ctyp_type in add_method loc val_env label.txt priv Concrete ty sign; begin try match get_desc ty with | Tvar _ -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty; Ctype.unify val_env (type_approx val_env sbody) ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in let ty2 = type_approx val_env sbody in Ctype.unify val_env ty2 ty1' | _ -> assert false with Ctype.Unify err -> raise(Error(loc, val_env, Field_type_mismatch ("method", label.txt, err))) end; let sdefinition = make_method self_loc cl_num expr in let warning_state = Warnings.backup () in let field = Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_meths = MethSet.add label.txt concrete_meths in let local_meths = MethSet.add label.txt local_meths in { acc with rev_fields; concrete_meths; local_meths }) | Pcf_constraint (sty1, sty2) -> with_attrs (fun () -> let (cty1, cty2) = type_constraint val_env sty1 sty2 loc in let field = Constraint { cty1; cty2; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_initializer sexpr -> with_attrs (fun () -> let sexpr = make_method self_loc cl_num sexpr in let warning_state = Warnings.backup () in let field = Initializer { sexpr; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_attribute attribute -> Builtin_attributes.warning_attribute attribute; let field = Attribute { attribute; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields } | Pcf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_fields_first_pass self_loc cl_num sign self_scope val_env par_env cfs = let rev_fields = [] in let concrete_meths = MethSet.empty in let concrete_vals = VarSet.empty in let local_meths = MethSet.empty in let local_vals = VarSet.empty in let vars = Vars.empty in let init_acc = { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } in let acc = Builtin_attributes.warning_scope [] (fun () -> List.fold_left (class_field_first_pass self_loc cl_num sign self_scope) init_acc cfs) in List.rev acc.rev_fields, acc.vars and class_field_second_pass cl_num sign met_env field = let mkcf desc loc attrs = { cf_desc = desc; cf_loc = loc; cf_attributes = attrs } in match field with | Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } -> let met_env = add_instance_vars_met loc inherited_vars sign cl_num met_env in let met_env = match super with | None -> met_env | Some name -> let meths = List.fold_left (fun acc (label, id) -> Meths.add label id acc) Meths.empty super_meths in let ty = Btype.self_type parent.cl_type in let attrs = [] in let _id, met_env = enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env in met_env in let desc = Tcf_inherit(override, parent, super, inherited_vars, super_meths) in met_env, mkcf desc loc attributes | Virtual_val { label; mut; id; cty; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_virtual cty in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_concrete(override, definition) in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Virtual_method { label; priv; cty; loc; attributes } -> let kind = Tcfk_virtual cty in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes | Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> let ty = Btype.method_type label.txt sign in let self_type = sign.Types.csig_self in let meth_type = mk_expected (Btype.newgenty (Tarrow(Nolabel, self_type, ty, commu_ok))) in let texp = Ctype.with_raised_nongen_level (fun () -> type_expect met_env sdefinition meth_type) in let kind = Tcfk_concrete (override, texp) in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes) | Constraint { cty1; cty2; loc; attributes } -> let desc = Tcf_constraint(cty1, cty2) in met_env, mkcf desc loc attributes | Initializer { sexpr; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> let unit_type = Ctype.instance Predef.type_unit in let self_type = sign.Types.csig_self in let meth_type = mk_expected (Ctype.newty (Tarrow (Nolabel, self_type, unit_type, commu_ok))) in let texp = Ctype.with_raised_nongen_level (fun () -> type_expect met_env sexpr meth_type) in let desc = Tcf_initializer texp in met_env, mkcf desc loc attributes) | Attribute { attribute; loc; attributes; } -> let desc = Tcf_attribute attribute in met_env, mkcf desc loc attributes and class_fields_second_pass cl_num sign met_env fields = let _, rev_cfs = List.fold_left (fun (met_env, cfs) field -> let met_env, cf = class_field_second_pass cl_num sign met_env field in met_env, cf :: cfs) (met_env, []) fields in List.rev rev_cfs (* N.B. the self type of a final object type doesn't contain a dummy method in the beginning. We only explicitly add a dummy method to class definitions (and class (type) declarations)), which are later removed (made absent) by [final_decl]. If we ever find a dummy method in a final object self type, it means that somehow we've unified the self type of the object with the self type of a not yet finished class. When this happens, we cannot close the object type and must error. *) and class_structure cl_num virt self_scope final val_env met_env loc { pcstr_self = spat; pcstr_fields = str } = (* Environment for substructures *) let par_env = met_env in (* Location of self. Used for locations of self arguments *) let self_loc = {spat.ppat_loc with Location.loc_ghost = true} in let sign = Ctype.new_class_signature () in (* Adding a dummy method to the signature prevents it from being closed / escaping. That isn't needed for objects though. *) begin match final with | Not_final -> Ctype.add_dummy_method val_env ~scope:self_scope sign; | Final -> () end; (* Self binder *) let (self_pat, self_pat_vars) = type_self_pattern val_env spat in let val_env, par_env = List.fold_right (fun {pv_id; _} (val_env, par_env) -> let name = Ident.name pv_id in let val_env = enter_self_val name val_env in let par_env = enter_self_val name par_env in val_env, par_env) self_pat_vars (val_env, par_env) in (* Check that the binder has a correct type *) begin try Ctype.unify val_env self_pat.pat_type sign.csig_self with Ctype.Unify _ -> raise(Error(spat.ppat_loc, val_env, Pattern_type_clash self_pat.pat_type)) end; (* Typing of class fields *) let (fields, vars) = class_fields_first_pass self_loc cl_num sign self_scope val_env par_env str in let kind = kind_of_final final in (* Check for unexpected virtual methods *) check_virtual loc val_env virt kind sign; (* Update the class signature *) update_class_signature loc val_env ~warn_implicit_public:false virt kind sign; let meths = Meths.fold (fun label _ meths -> Meths.add label (Ident.create_local label) meths) sign.csig_meths Meths.empty in (* Close the signature if it is final *) begin match final with | Not_final -> () | Final -> if not (Ctype.close_class_signature val_env sign) then raise(Error(loc, val_env, Closing_self_type sign)); end; (* Typing of method bodies *) Ctype.generalize_class_signature_spine val_env sign; let self_var_kind = match virt with | Virtual -> Self_virtual(ref meths) | Concrete -> Self_concrete meths in let met_env = List.fold_right (fun {pv_id; pv_type; pv_loc; pv_as_var; pv_attributes} met_env -> add_self_met pv_loc pv_id sign self_var_kind vars cl_num pv_as_var pv_type pv_attributes met_env) self_pat_vars met_env in let fields = class_fields_second_pass cl_num sign met_env fields in (* Update the class signature and warn about public methods made private *) update_class_signature loc val_env ~warn_implicit_public:true virt kind sign; let meths = match self_var_kind with | Self_virtual meths_ref -> !meths_ref | Self_concrete meths -> meths in { cstr_self = self_pat; cstr_fields = fields; cstr_type = sign; cstr_meths = meths; } and class_expr cl_num val_env met_env virt self_scope scl = Builtin_attributes.warning_scope scl.pcl_attributes (fun () -> class_expr_aux cl_num val_env met_env virt self_scope scl) and class_expr_aux cl_num val_env met_env virt self_scope scl = match scl.pcl_desc with | Pcl_constr (lid, styl) -> let (path, decl) = Env.lookup_class ~loc:scl.pcl_loc lid.txt val_env in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, val_env, Unbound_class_2 lid.txt)); let tyl = List.map (fun sty -> transl_simple_type val_env ~closed:false sty) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = Btype.abbreviate_class_type path params clty in (* Adding a dummy method to the self type prevents it from being closed / escaping. *) Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type clty'); if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, val_env, Parameter_arity_mismatch (lid.txt, List.length params, List.length tyl))); List.iter2 (fun cty' ty -> let ty' = cty'.ctyp_type in try Ctype.unify val_env ty' ty with Ctype.Unify err -> raise(Error(cty'.ctyp_loc, val_env, Parameter_mismatch err))) tyl params; (* Check for unexpected virtual methods *) check_virtual_clty scl.pcl_loc val_env virt Class clty'; let cl = rc {cl_desc = Tcl_ident (path, lid, tyl); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; cl_attributes = scl.pcl_attributes; } in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tcl_constraint (cl, None, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; cl_attributes = []; (* attributes are kept on the inner cl node *) } | Pcl_structure cl_str -> let desc = class_structure cl_num virt self_scope Not_final val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tcl_structure desc; cl_loc = scl.pcl_loc; cl_type = Cty_signature desc.cstr_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_fun (l, Some default, spat, sbody) -> let loc = default.pexp_loc in let open Ast_helper in let scases = [ Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "Some")))) (Some ([], Pat.var ~loc (mknoloc "*sth*")))) (Exp.ident ~loc (mknoloc (Longident.Lident "*sth*"))); Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "None")))) None) default; ] in let smatch = Exp.match_ ~loc (Exp.ident ~loc (mknoloc (Longident.Lident "*opt*"))) scases in let sfun = Cl.fun_ ~loc:scl.pcl_loc l None (Pat.var ~loc (mknoloc "*opt*")) (Cl.let_ ~loc:scl.pcl_loc Nonrecursive [Vb.mk spat smatch] sbody) Note : we do n't put the ' # default ' attribute , as it is not detected for class - level let bindings . See # 5975 . is not detected for class-level let bindings. See #5975.*) in class_expr cl_num val_env met_env virt self_scope sfun | Pcl_fun (l, None, spat, scl') -> let (pat, pv, val_env', met_env) = Ctype.with_local_level_if_principal (fun () -> Typecore.type_class_arg_pattern cl_num val_env met_env l spat) ~post: begin fun (pat, _, _, _) -> let gen {pat_type = ty} = Ctype.generalize_structure ty in iter_pattern gen pat end in let pv = List.map begin fun (id, id', _ty) -> let path = Pident id' in (* do not mark the value as being used *) let vd = Env.find_value path val_env' in (id, {exp_desc = Texp_ident(path, mknoloc (Longident.Lident (Ident.name id)), vd); exp_loc = Location.none; exp_extra = []; exp_type = Ctype.instance vd.val_type; exp_attributes = []; (* check *) exp_env = val_env'}) end pv in let rec not_nolabel_function = function | Cty_arrow(Nolabel, _, _) -> false | Cty_arrow(_, _, cty) -> not_nolabel_function cty | _ -> true in let partial = let dummy = type_exp val_env (Ast_helper.Exp.unreachable ()) in Typecore.check_partial val_env pat.pat_type pat.pat_loc [{c_lhs = pat; c_guard = None; c_rhs = dummy}] in let cl = Ctype.with_raised_nongen_level (fun () -> class_expr cl_num val_env' met_env virt self_scope scl') in if Btype.is_optional l && not_nolabel_function cl.cl_type then Location.prerr_warning pat.pat_loc Warnings.Unerasable_optional_argument; rc {cl_desc = Tcl_fun (l, pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Cty_arrow (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_apply (scl', sargs) -> assert (sargs <> []); let cl = Ctype.with_local_level_if_principal (fun () -> class_expr cl_num val_env met_env virt self_scope scl') ~post:(fun cl -> Ctype.generalize_class_type_structure cl.cl_type) in let rec nonopt_labels ls ty_fun = match ty_fun with | Cty_arrow (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = Nolabel) sargs && List.exists (fun l -> l <> Nolabel) labels && begin Location.prerr_warning cl.cl_loc (Warnings.Labels_omitted (List.map Printtyp.string_of_label (List.filter ((<>) Nolabel) labels))); true end in let rec type_args args omitted ty_fun ty_fun0 sargs = match ty_fun, ty_fun0 with | Cty_arrow (l, ty, ty_fun), Cty_arrow (_, ty0, ty_fun0) when sargs <> [] -> let name = Btype.label_name l and optional = Btype.is_optional l in let use_arg sarg l' = Some ( if not optional || Btype.is_optional l' then type_argument val_env sarg ty ty0 else let ty' = extract_option_type val_env ty and ty0' = extract_option_type val_env ty0 in let arg = type_argument val_env sarg ty' ty0' in option_some val_env arg ) in let eliminate_optional_arg () = Some (option_none val_env ty0 Location.none) in let remaining_sargs, arg = if ignore_labels then begin match sargs with | [] -> assert false | (l', sarg) :: remaining_sargs -> if name = Btype.label_name l' || (not optional && l' = Nolabel) then (remaining_sargs, use_arg sarg l') else if optional && not (List.exists (fun (l, _) -> name = Btype.label_name l) remaining_sargs) then (sargs, eliminate_optional_arg ()) else raise(Error(sarg.pexp_loc, val_env, Apply_wrong_label l')) end else match Btype.extract_label name sargs with | Some (l', sarg, _, remaining_sargs) -> if not optional && Btype.is_optional l' then Location.prerr_warning sarg.pexp_loc (Warnings.Nonoptional_label (Printtyp.string_of_label l)); remaining_sargs, use_arg sarg l' | None -> sargs, if Btype.is_optional l && List.mem_assoc Nolabel sargs then eliminate_optional_arg () else None in let omitted = if arg = None then (l,ty0) :: omitted else omitted in type_args ((l,arg)::args) omitted ty_fun ty_fun0 remaining_sargs | _ -> match sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, val_env, Apply_wrong_label l)) else raise(Error(cl.cl_loc, val_env, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Cty_arrow(l,ty,ty_fun)) ty_fun0 omitted) in let (args, cty) = let (_, ty_fun0) = Ctype.instance_class [] cl.cl_type in type_args [] [] cl.cl_type ty_fun0 sargs in rc {cl_desc = Tcl_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = Typecore.type_let In_class_def val_env rec_flag sdefs in let (vals, met_env) = List.fold_right (fun (id, _id_loc, _typ) (vals, met_env) -> let path = Pident id in (* do not mark the value as used *) let vd = Env.find_value path val_env in let ty = Ctype.with_local_level ~post:Ctype.generalize (fun () -> Ctype.instance vd.val_type) in let expr = {exp_desc = Texp_ident(path, mknoloc(Longident.Lident (Ident.name id)),vd); exp_loc = Location.none; exp_extra = []; exp_type = ty; exp_attributes = []; exp_env = val_env; } in let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num); val_attributes = []; Types.val_loc = vd.Types.val_loc; val_uid = vd.val_uid; } in let id' = Ident.create_local (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents_full defs) ([], met_env) in let cl = class_expr cl_num val_env met_env virt self_scope scl' in let () = if rec_flag = Recursive then check_recursive_bindings val_env defs in rc {cl_desc = Tcl_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_constraint (scl', scty) -> let cl, clty = Ctype.with_local_level_for_class begin fun () -> let cl = Typetexp.TyVarEnv.with_local_scope begin fun () -> let cl = class_expr cl_num val_env met_env virt self_scope scl' in complete_class_type cl.cl_loc val_env virt Class_type cl.cl_type; cl end and clty = Typetexp.TyVarEnv.with_local_scope begin fun () -> let clty = class_type val_env virt self_scope scty in complete_class_type clty.cltyp_loc val_env virt Class clty.cltyp_type; clty end in cl, clty end ~post: begin fun ({cl_type=cl}, {cltyp_type=clty}) -> Ctype.limited_generalize_class_type (Btype.self_type_row cl) cl; Ctype.limited_generalize_class_type (Btype.self_type_row clty) clty; end in begin match Includeclass.class_types val_env cl.cl_type clty.cltyp_type with [] -> () | error -> raise(Error(cl.cl_loc, val_env, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty.cltyp_type in let ty = snd (Ctype.instance_class [] clty.cltyp_type) in (* Adding a dummy method to the self type prevents it from being closed / escaping. *) Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type ty); rc {cl_desc = Tcl_constraint (cl, Some clty, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = ty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_open (pod, e) -> let used_slot = ref false in let (od, new_val_env) = !type_open_descr ~used_slot val_env pod in let ( _, new_met_env) = !type_open_descr ~used_slot met_env pod in let cl = class_expr cl_num new_val_env new_met_env virt self_scope e in rc {cl_desc = Tcl_open (od, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) (*******************************) (* Approximate the type of the constructor to allow recursive use *) (* of optional parameters *) let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_declaration cl, commu_ok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_arrow (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_description ct, commu_ok)) | _ -> Ctype.newvar () (*******************************) let temp_abbrev loc arity uid = let params = ref [] in for _i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let ty_td = {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = loc; or keep attrs from the class decl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = uid; } in (!params, ty, ty_td) let initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, uid) = (* Temporary abbreviations *) let arity = List.length cl.pci_params in let (obj_params, obj_ty, obj_td) = temp_abbrev cl.pci_loc arity uid in let env = Env.add_type ~check:true obj_id obj_td env in let (cl_params, cl_ty, cl_td) = temp_abbrev cl.pci_loc arity uid in (* Temporary type for the class constructor *) let constr_type = Ctype.with_local_level_if_principal (fun () -> approx cl.pci_expr) ~post:Ctype.generalize_structure in let dummy_cty = Cty_signature (Ctype.new_class_signature ()) in let dummy_class = {Types.cty_params = []; (* Dummy value *) cty_variance = []; cty_type = dummy_cty; (* Dummy value *) cty_path = unbound_class; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = Location.none; cty_attributes = []; cty_uid = uid; } in let env = Env.add_cltype ty_id {clty_params = []; (* Dummy value *) clty_variance = []; clty_type = dummy_cty; (* Dummy value *) clty_path = unbound_class; clty_hash_type = cl_td; (* Dummy value *) clty_loc = Location.none; clty_attributes = []; clty_uid = uid; } ( if define_class then Env.add_class id dummy_class env else env ) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class) (res, env) = let ci_params, params, coercion_locs, expr, typ, sign = Ctype.with_local_level_for_class begin fun () -> TyVarEnv.reset (); (* Introduce class parameters *) let ci_params = let make_param (sty, v) = try (transl_type_param env sty, v) with Already_bound -> raise(Error(sty.ptyp_loc, env, Repeated_parameter)) in List.map make_param cl.pci_params in let params = List.map (fun (cty, _) -> cty.ctyp_type) ci_params in (* Allow self coercions (only for class declarations) *) let coercion_locs = ref [] in (* Type the class expression *) let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_virt cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in let sign = Btype.signature_of_class_type typ in (ci_params, params, coercion_locs, expr, typ, sign) end ~post: begin fun (_, params, _, _, typ, sign) -> the row variable List.iter (Ctype.limited_generalize sign.csig_self_row) params; Ctype.limited_generalize_class_type sign.csig_self_row typ; end in (* Check the abbreviation for the object type *) let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let row = Btype.self_type_row obj_type in Ctype.unify env row (Ctype.newty Tnil); begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_parameters (obj_id, obj_params, obj_params'))) end; let ty = Btype.self_type obj_type in begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; Ctype.set_object_name obj_id params (Btype.self_type typ); (* Check the other temporary abbreviation (#-type) *) begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Btype.self_type cl_type in begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_class_type_parameters (ty_id, cl_params, cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let ty_expanded = Ctype.object_fields ty in raise(Error(cl.pci_loc, env, Abbrev_type_clash (ty, ty_expanded, cl_ty))) end end; (* Type of the class constructor *) begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Constructor_type_mismatch (cl.pci_name.txt, err))) end; (* Class and class type temporary definitions *) let cty_variance = Variance.unknown_signature ~injective:false ~arity:(List.length params) in let cltydef = {clty_params = params; clty_type = Btype.class_body typ; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_hash_type = cl_td; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } and clty = {cty_params = params; cty_type = typ; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in (* Misc. *) let arity = Btype.class_type_arity typ in let pub_meths = Btype.public_methods sign in (* Final definitions *) let (params', typ') = Ctype.instance_class params typ in let clty = {cty_params = params'; cty_type = typ'; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some (Ctype.instance constr_type) end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in let obj_abbr = let arity = List.length obj_params in { type_params = obj_params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some obj_ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = cl.pci_loc; or keep attrs from cl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = dummy_class.cty_uid; } in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Btype.self_type typ) in Ctype.set_object_name obj_id cl_params cl_ty; let cl_abbr = { cl_td with type_params = cl_params; type_manifest = Some cl_ty } in let cltydef = {clty_params = params'; clty_type = Btype.class_body typ'; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_hash_type = cl_abbr; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, ci_params, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, ci_params, arity, pub_meths, coe, expr) = let cl_abbr = cltydef.clty_hash_type in begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Non_collapsable_conjunction (id, clty, err))) end; List.iter Ctype.generalize clty.cty_params; Ctype.generalize_class_type clty.cty_type; Option.iter Ctype.generalize clty.cty_new; List.iter Ctype.generalize obj_abbr.type_params; Option.iter Ctype.generalize obj_abbr.type_manifest; List.iter Ctype.generalize cl_abbr.type_params; Option.iter Ctype.generalize cl_abbr.type_manifest; if Ctype.nongen_class_declaration clty then raise(Error(cl.pci_loc, env, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Btype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, env, Unbound_type_var(printer, reason))) end; { id; clty; ty_id; cltydef; obj_id; obj_abbr; arity; pub_meths; coe; id_loc = cl.pci_name; req = { ci_loc = cl.pci_loc; ci_virt = cl.pci_virt; ci_params = ci_params; (* TODO : check that we have the correct use of identifiers *) ci_id_name = cl.pci_name; ci_id_class = id; ci_id_class_type = ty_id; ci_id_object = obj_id; ci_expr = expr; ci_decl = clty; ci_type_decl = cltydef; ci_attributes = cl.pci_attributes; } } (* (cl.pci_variance, cl.pci_loc)) *) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class) (res, env) = Builtin_attributes.warning_scope cl.pci_attributes (fun () -> class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class) (res, env) ) let extract_type_decls { clty; cltydef; obj_id; obj_abbr; req} decls = (obj_id, obj_abbr, clty, cltydef, req) :: decls let merge_type_decls decl (obj_abbr, clty, cltydef) = {decl with obj_abbr; clty; cltydef} let final_env define_class env { id; clty; ty_id; cltydef; obj_id; obj_abbr; } = (* Add definitions after cleaning them *) Env.add_type ~check:true obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env)) (* Check that #c is coercible to c if there is a self-coercion *) let check_coercions env { id; id_loc; clty; ty_id; cltydef; obj_id; obj_abbr; arity; pub_meths; coe; req } = let cl_abbr = cltydef.clty_hash_type in begin match coe with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype err -> raise(Typecore.Error(loc, env, Typecore.Not_subtype err)) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, env, Cannot_coerce_self obj_ty)) end; {cls_id = id; cls_id_loc = id_loc; cls_decl = clty; cls_ty_id = ty_id; cls_ty_decl = cltydef; cls_obj_id = obj_id; cls_obj_abbr = obj_abbr; cls_abbr = cl_abbr; cls_arity = arity; cls_pub_methods = pub_meths; cls_info=req} (*******************************) let type_classes define_class approx kind env cls = let scope = Ctype.create_scope () in let cls = List.map (function cl -> (cl, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Uid.mk ~current_unit:(Env.get_unit_name ()) )) cls in let res, env = Ctype.with_local_level_for_class begin fun () -> let (res, env) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, env) = List.fold_right (class_infos define_class kind) res ([], env) in res, env end in let res = List.rev_map (final_decl env define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = try Typedecl_variance.update_class_decls env decls with Typedecl_variance.Error(loc, err) -> raise (Typedecl.Error(loc, Typedecl.Variance err)) in let res = List.map2 merge_type_decls res decls in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env virt sexpr = incr class_num; let self_scope = Ctype.get_current_level () in let expr = class_expr (Int.to_string !class_num) env env virt self_scope sexpr in complete_class_type expr.cl_loc env virt Class expr.cl_type; (expr, expr.cl_type) let class_description env virt sexpr = let self_scope = Ctype.get_current_level () in let expr = class_type env virt self_scope sexpr in complete_class_type expr.cltyp_loc env virt Class_type expr.cltyp_type; (expr, expr.cltyp_type) let class_declarations env cls = let info, env = type_classes true approx_declaration class_declaration env cls in let ids, exprs = List.split (List.map (fun ci -> ci.cls_id, ci.cls_info.ci_expr) info) in check_recursive_class_bindings env ids exprs; info, env let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decls, env) = type_classes false approx_description class_description env cls in (List.map (fun decl -> {clsty_ty_id = decl.cls_ty_id; clsty_id_loc = decl.cls_id_loc; clsty_ty_decl = decl.cls_ty_decl; clsty_obj_id = decl.cls_obj_id; clsty_obj_abbr = decl.cls_obj_abbr; clsty_abbr = decl.cls_abbr; clsty_info = decl.cls_info}) decls, env) let type_object env loc s = incr class_num; let desc = class_structure (Int.to_string !class_num) Concrete Btype.lowest_level Final env env loc s in complete_class_signature loc env Concrete Object desc.cstr_type; let meths = Btype.public_methods desc.cstr_type in (desc, meths) let () = Typecore.type_object := type_object (*******************************) Check that there is no references through recursive modules ( GPR#6491 ) let rec check_recmod_class_type env cty = match cty.pcty_desc with | Pcty_constr(lid, _) -> ignore (Env.lookup_cltype ~use:false ~loc:lid.loc lid.txt env) | Pcty_extension _ -> () | Pcty_arrow(_, _, cty) -> check_recmod_class_type env cty | Pcty_open(od, cty) -> let _, env = !type_open_descr env od in check_recmod_class_type env cty | Pcty_signature csig -> check_recmod_class_sig env csig and check_recmod_class_sig env csig = List.iter (fun ctf -> match ctf.pctf_desc with | Pctf_inherit cty -> check_recmod_class_type env cty | Pctf_val _ | Pctf_method _ | Pctf_constraint _ | Pctf_attribute _ | Pctf_extension _ -> ()) csig.pcsig_fields let check_recmod_decl env sdecl = check_recmod_class_type env sdecl.pci_expr (* Approximate the class declaration as class ['params] id = object end *) let approx_class sdecl = let open Ast_helper in let self' = Typ.any () in let clty' = Cty.signature ~loc:sdecl.pci_expr.pcty_loc (Csig.mk self' []) in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = let decls, env = class_type_declarations env (List.map approx_class sdecls) in List.iter (check_recmod_decl env) sdecls; decls (*******************************) (* Error report *) open Format let non_virtual_string_of_kind = function | Object -> "object" | Class -> "non-virtual class" | Class_type -> "non-virtual class type" let report_error env ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint err -> fprintf ppf "@[<v>The class constraints are not consistent.@ "; Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type"); fprintf ppf "@]" | Field_type_mismatch (k, m, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The %s %s@ has type" k m) (function ppf -> fprintf ppf "but is expected to have type") | Unexpected_field (ty, lab) -> fprintf ppf "@[@[<2>This object is expected to have type :@ %a@]\ @ This type does not have a method %s." Printtyp.type_expr ty lab | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply _ -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | Nolabel -> "out label" | l -> sprintf " label %s" (Btype.prefixed_label_name l) in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> (* XXX Trace *) XXX Revoir message | Improve error message fprintf ppf "@[%s@ %a@]" "This pattern cannot match self: it only matches values of type" Printtyp.type_expr ty | Unbound_class_2 cl -> fprintf ppf "@[The class@ %a@ is not yet completely defined@]" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "@[The class type@ %a@ is not yet completely defined@]" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> (* XXX Afficher une trace ? | Print a trace? *) Printtyp.prepare_for_printing [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" !Oprint.out_type (Printtyp.tree_of_typexp Type abbrev) !Oprint.out_type (Printtyp.tree_of_typexp Type actual) !Oprint.out_type (Printtyp.tree_of_typexp Type expected) | Constructor_type_mismatch (c, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (kind, mets, vals) -> let kind = non_virtual_string_of_kind kind in let missings = match mets, vals with [], _ -> "variables" | _, [] -> "methods" | _ -> "methods and variables" in fprintf ppf "@[This %s has virtual %s.@ \ @[<2>The following %s are virtual : %a@]@]" kind missings missings (pp_print_list ~pp_sep:pp_print_space pp_print_string) (mets @ vals) | Undeclared_methods(kind, mets) -> let kind = non_virtual_string_of_kind kind in fprintf ppf "@[This %s has undeclared virtual methods.@ \ @[<2>The following methods were not declared : %a@]@]" kind (pp_print_list ~pp_sep:pp_print_space pp_print_string) mets | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.prepare_for_printing (params @ cstrs); fprintf ppf "@[The abbreviation %a@ is used with parameter(s)@ %a@ \ which are incompatible with constraint(s)@ %a@]" Printtyp.ident id !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) params) !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) cstrs) | Bad_class_type_parameters (id, params, cstrs) -> Printtyp.prepare_for_printing (params @ cstrs); fprintf ppf "@[The class type #%a@ is used with parameter(s)@ %a,@ \ whereas the class type definition@ constrains@ \ those parameters to be@ %a@]" Printtyp.ident id !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) params) !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) cstrs) | Class_match_failure error -> Includeclass.report_error Type ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_reason ppf { Ctype.free_variable; meth; meth_ty; } = let (ty0, kind) = free_variable in let ty1 = match kind with | Type_variable -> ty0 | Row_variable -> Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.add_type_to_preparation meth_ty; Printtyp.add_type_to_preparation ty1; fprintf ppf "The method %s@ has type@;<1 2>%a@ where@ %a@ is unbound" meth !Oprint.out_type (Printtyp.tree_of_typexp Type meth_ty) !Oprint.out_type (Printtyp.tree_of_typexp Type ty0) in fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurrences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, err) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsible conjunctive types in constraints.@ %t@]" (Printtyp.class_declaration id) clty (fun ppf -> Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") ) | Self_clash err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but actually has type") | Mutability_mismatch (_lab, mut) -> let mut1, mut2 = if mut = Immutable then "mutable", "immutable" else "immutable", "mutable" in fprintf ppf "@[The instance variable is %s;@ it cannot be redefined as %s@]" mut1 mut2 | No_overriding (_, "") -> fprintf ppf "@[This inheritance does not override any method@ %s@]" "instance variable" | No_overriding (kind, name) -> fprintf ppf "@[The %s `%s'@ has no previous definition@]" kind name | Duplicate (kind, name) -> fprintf ppf "@[The %s `%s'@ has multiple definitions in this object@]" kind name | Closing_self_type sign -> fprintf ppf "@[Cannot close type of object literal:@ %a@,\ it has been unified with the self type of a class that is not yet@ \ completely defined.@]" Printtyp.type_scheme sign.csig_self let report_error env ppf err = Printtyp.wrap_printing_env ~error:true env (fun () -> report_error env ppf err) let () = Location.register_error_of_exn (function | Error (loc, env, err) -> Some (Location.error_of_printer ~loc (report_error env) err) | Error_forward err -> Some err | _ -> None )
null
https://raw.githubusercontent.com/ocaml/ocaml/7e5e7127ffcd688c27f683e048ade3a849b9a24f/typing/typeclass.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Path associated to the temporary class type of a class being typed (its constructor is not available). ********************************** Some operations on class types ********************************** Record a class type Return the constructor type associated to a class type ********************************* Primitives for typing classes ********************************* ***************************** Introduce a dummy method preventing self type from being closed. Class type fields Adding a dummy method to the self type prevents it from being closed / escaping. Check for unexpected virtual methods ***************************** Methods available through super N.B. the self type of a final object type doesn't contain a dummy method in the beginning. We only explicitly add a dummy method to class definitions (and class (type) declarations)), which are later removed (made absent) by [final_decl]. If we ever find a dummy method in a final object self type, it means that somehow we've unified the self type of the object with the self type of a not yet finished class. When this happens, we cannot close the object type and must error. Environment for substructures Location of self. Used for locations of self arguments Adding a dummy method to the signature prevents it from being closed / escaping. That isn't needed for objects though. Self binder Check that the binder has a correct type Typing of class fields Check for unexpected virtual methods Update the class signature Close the signature if it is final Typing of method bodies Update the class signature and warn about public methods made private Adding a dummy method to the self type prevents it from being closed / escaping. Check for unexpected virtual methods attributes are kept on the inner cl node do not mark the value as being used check do not mark the value as used Adding a dummy method to the self type prevents it from being closed / escaping. ***************************** Approximate the type of the constructor to allow recursive use of optional parameters ***************************** Temporary abbreviations Temporary type for the class constructor Dummy value Dummy value Dummy value Dummy value Dummy value Introduce class parameters Allow self coercions (only for class declarations) Type the class expression Check the abbreviation for the object type Check the other temporary abbreviation (#-type) Type of the class constructor Class and class type temporary definitions Misc. Final definitions TODO : check that we have the correct use of identifiers (cl.pci_variance, cl.pci_loc)) Add definitions after cleaning them Check that #c is coercible to c if there is a self-coercion ***************************** ***************************** Approximate the class declaration as class ['params] id = object end ***************************** Error report XXX Trace XXX Afficher une trace ? | Print a trace?
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Parsetree open Asttypes open Path open Types open Typecore open Typetexp open Format type 'a class_info = { cls_id : Ident.t; cls_id_loc : string loc; cls_decl : class_declaration; cls_ty_id : Ident.t; cls_ty_decl : class_type_declaration; cls_obj_id : Ident.t; cls_obj_abbr : type_declaration; cls_abbr : type_declaration; cls_arity : int; cls_pub_methods : string list; cls_info : 'a; } type class_type_info = { clsty_ty_id : Ident.t; clsty_id_loc : string loc; clsty_ty_decl : class_type_declaration; clsty_obj_id : Ident.t; clsty_obj_abbr : type_declaration; clsty_abbr : type_declaration; clsty_info : Typedtree.class_type_declaration; } type 'a full_class = { id : Ident.t; id_loc : tag loc; clty: class_declaration; ty_id: Ident.t; cltydef: class_type_declaration; obj_id: Ident.t; obj_abbr: type_declaration; arity: int; pub_meths: string list; coe: Warnings.loc list; req: 'a Typedtree.class_infos; } type kind = | Object | Class | Class_type type final = | Final | Not_final let kind_of_final = function | Final -> Object | Not_final -> Class type error = | Unconsistent_constraint of Errortrace.unification_error | Field_type_mismatch of string * string * Errortrace.unification_error | Unexpected_field of type_expr * string | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of arg_label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class_2 of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * Errortrace.unification_error | Virtual_class of kind * string list * string list | Undeclared_methods of kind * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of Errortrace.unification_error | Bad_parameters of Ident.t * type_expr list * type_expr list | Bad_class_type_parameters of Ident.t * type_expr list * type_expr list | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * Errortrace.unification_error | Self_clash of Errortrace.unification_error | Mutability_mismatch of string * mutable_flag | No_overriding of string * string | Duplicate of string * string | Closing_self_type of class_signature exception Error of Location.t * Env.t * error exception Error_forward of Location.error open Typedtree let type_open_descr : (?used_slot:bool ref -> Env.t -> Parsetree.open_description -> open_description * Env.t) ref = ref (fun ?used_slot:_ _ -> assert false) let ctyp desc typ env loc = { ctyp_desc = desc; ctyp_type = typ; ctyp_loc = loc; ctyp_env = env; ctyp_attributes = [] } let unbound_class = Path.Pident (Ident.create_local "*undef*") let extract_constraints cty = let sign = Btype.signature_of_class_type cty in (Btype.instance_vars sign, Btype.methods sign, Btype.concrete_methods sign) let rc node = Cmt_format.add_saved_type (Cmt_format.Partial_class_expr node); node let update_class_signature loc env ~warn_implicit_public virt kind sign = let implicit_public, implicit_declared = Ctype.update_class_signature env sign in if implicit_declared <> [] then begin match virt with Should perhaps emit warning 17 here | Concrete -> raise (Error(loc, env, Undeclared_methods(kind, implicit_declared))) end; if warn_implicit_public && implicit_public <> [] then begin Location.prerr_warning loc (Warnings.Implicit_public_methods implicit_public) end let complete_class_signature loc env virt kind sign = update_class_signature loc env ~warn_implicit_public:false virt kind sign; Ctype.hide_private_methods env sign let complete_class_type loc env virt kind typ = let sign = Btype.signature_of_class_type typ in complete_class_signature loc env virt kind sign let check_virtual loc env virt kind sign = match virt with | Virtual -> () | Concrete -> match Btype.virtual_methods sign, Btype.virtual_instance_vars sign with | [], [] -> () | meths, vars -> raise(Error(loc, env, Virtual_class(kind, meths, vars))) let rec check_virtual_clty loc env virt kind clty = match clty with | Cty_constr(_, _, clty) | Cty_arrow(_, _, clty) -> check_virtual_clty loc env virt kind clty | Cty_signature sign -> check_virtual loc env virt kind sign let rec constructor_type constr cty = match cty with Cty_constr (_, _, cty) -> constructor_type constr cty | Cty_signature _ -> constr | Cty_arrow (l, ty, cty) -> Ctype.newty (Tarrow (l, ty, constructor_type constr cty, commu_ok)) let raise_add_method_failure loc env label sign failure = match (failure : Ctype.add_method_failure) with | Ctype.Unexpected_method -> raise(Error(loc, env, Unexpected_field (sign.Types.csig_self, label))) | Ctype.Type_mismatch trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let raise_add_instance_variable_failure loc env label failure = match (failure : Ctype.add_instance_variable_failure) with | Ctype.Mutability_mismatch mut -> raise (Error(loc, env, Mutability_mismatch(label, mut))) | Ctype.Type_mismatch trace -> raise (Error(loc, env, Field_type_mismatch("instance variable", label, trace))) let raise_inherit_class_signature_failure loc env sign = function | Ctype.Self_type_mismatch trace -> raise(Error(loc, env, Self_clash trace)) | Ctype.Method(label, failure) -> raise_add_method_failure loc env label sign failure | Ctype.Instance_variable(label, failure) -> raise_add_instance_variable_failure loc env label failure let add_method loc env label priv virt ty sign = match Ctype.add_method env label priv virt ty sign with | () -> () | exception Ctype.Add_method_failed failure -> raise_add_method_failure loc env label sign failure let add_instance_variable ~strict loc env label mut virt ty sign = match Ctype.add_instance_variable ~strict env label mut virt ty sign with | () -> () | exception Ctype.Add_instance_variable_failed failure -> raise_add_instance_variable_failure loc env label failure let inherit_class_signature ~strict loc env sign1 sign2 = match Ctype.inherit_class_signature ~strict env sign1 sign2 with | () -> () | exception Ctype.Inherit_class_signature_failed failure -> raise_inherit_class_signature_failure loc env sign1 failure let inherit_class_type ~strict loc env sign1 cty2 = let sign2 = match Btype.scrape_class_type cty2 with | Cty_signature sign2 -> sign2 | _ -> raise(Error(loc, env, Structure_expected cty2)) in inherit_class_signature ~strict loc env sign1 sign2 let unify_delayed_method_type loc env label ty expected_ty= match Ctype.unify env ty expected_ty with | () -> () | exception Ctype.Unify trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let type_constraint val_env sty sty' loc = let cty = transl_simple_type val_env ~closed:false sty in let ty = cty.ctyp_type in let cty' = transl_simple_type val_env ~closed:false sty' in let ty' = cty'.ctyp_type in begin try Ctype.unify val_env ty ty' with Ctype.Unify err -> raise(Error(loc, val_env, Unconsistent_constraint err)); end; (cty, cty') let make_method loc cl_num expr = let open Ast_helper in let mkid s = mkloc s loc in Exp.fun_ ~loc:expr.pexp_loc Nolabel None (Pat.alias ~loc (Pat.var ~loc (mkid "self-*")) (mkid ("self-" ^ cl_num))) expr let delayed_meth_specs = ref [] let rec class_type_field env sign self_scope ctf = let loc = ctf.pctf_loc in let mkctf desc = { ctf_desc = desc; ctf_loc = loc; ctf_attributes = ctf.pctf_attributes } in let mkctf_with_attrs f = Builtin_attributes.warning_scope ctf.pctf_attributes (fun () -> mkctf (f ())) in match ctf.pctf_desc with | Pctf_inherit sparent -> mkctf_with_attrs (fun () -> let parent = class_type env Virtual self_scope sparent in complete_class_type parent.cltyp_loc env Virtual Class_type parent.cltyp_type; inherit_class_type ~strict:false loc env sign parent.cltyp_type; Tctf_inherit parent) | Pctf_val ({txt=lab}, mut, virt, sty) -> mkctf_with_attrs (fun () -> let cty = transl_simple_type env ~closed:false sty in let ty = cty.ctyp_type in add_instance_variable ~strict:false loc env lab mut virt ty sign; Tctf_val (lab, mut, virt, cty)) | Pctf_method ({txt=lab}, priv, virt, sty) -> mkctf_with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in match sty.ptyp_desc, priv with | Ptyp_poly ([],sty'), Public -> let expected_ty = Ctype.newvar () in add_method loc env lab priv virt expected_ty sign; let returned_cty = ctyp Ttyp_any (Ctype.newty Tnil) env loc in delayed_meth_specs := Warnings.mk_lazy (fun () -> let cty = transl_simple_type_univars env sty' in let ty = cty.ctyp_type in unify_delayed_method_type loc env lab ty expected_ty; returned_cty.ctyp_desc <- Ttyp_poly ([], cty); returned_cty.ctyp_type <- ty; ) :: !delayed_meth_specs; Tctf_method (lab, priv, virt, returned_cty) | _ -> let cty = transl_simple_type env ~closed:false sty in let ty = cty.ctyp_type in add_method loc env lab priv virt ty sign; Tctf_method (lab, priv, virt, cty)) | Pctf_constraint (sty, sty') -> mkctf_with_attrs (fun () -> let (cty, cty') = type_constraint env sty sty' ctf.pctf_loc in Tctf_constraint (cty, cty')) | Pctf_attribute x -> Builtin_attributes.warning_attribute x; mkctf (Tctf_attribute x) | Pctf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_signature virt env pcsig self_scope loc = let {pcsig_self=sty; pcsig_fields=psign} = pcsig in let sign = Ctype.new_class_signature () in Ctype.add_dummy_method env ~scope:self_scope sign; let self_cty = transl_simple_type env ~closed:false sty in let self_type = self_cty.ctyp_type in begin try Ctype.unify env self_type sign.csig_self with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, env, Pattern_type_clash self_type)) end; let fields = Builtin_attributes.warning_scope [] (fun () -> List.map (class_type_field env sign self_scope) psign) in check_virtual loc env virt Class_type sign; { csig_self = self_cty; csig_fields = fields; csig_type = sign; } and class_type env virt self_scope scty = Builtin_attributes.warning_scope scty.pcty_attributes (fun () -> class_type_aux env virt self_scope scty) and class_type_aux env virt self_scope scty = let cltyp desc typ = { cltyp_desc = desc; cltyp_type = typ; cltyp_loc = scty.pcty_loc; cltyp_env = env; cltyp_attributes = scty.pcty_attributes; } in match scty.pcty_desc with | Pcty_constr (lid, styl) -> let (path, decl) = Env.lookup_cltype ~loc:scty.pcty_loc lid.txt env in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, env, Unbound_class_type_2 lid.txt)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in Ctype.add_dummy_method env ~scope:self_scope (Btype.signature_of_class_type clty); if List.length params <> List.length styl then raise(Error(scty.pcty_loc, env, Parameter_arity_mismatch (lid.txt, List.length params, List.length styl))); let ctys = List.map2 (fun sty ty -> let cty' = transl_simple_type env ~closed:false sty in let ty' = cty'.ctyp_type in begin try Ctype.unify env ty' ty with Ctype.Unify err -> raise(Error(sty.ptyp_loc, env, Parameter_mismatch err)) end; cty' ) styl params in let typ = Cty_constr (path, params, clty) in check_virtual_clty scty.pcty_loc env virt Class_type typ; cltyp (Tcty_constr ( path, lid , ctys)) typ | Pcty_signature pcsig -> let clsig = class_signature virt env pcsig self_scope scty.pcty_loc in let typ = Cty_signature clsig.csig_type in cltyp (Tcty_signature clsig) typ | Pcty_arrow (l, sty, scty) -> let cty = transl_simple_type env ~closed:false sty in let ty = cty.ctyp_type in let ty = if Btype.is_optional l then Ctype.newty (Tconstr(Predef.path_option,[ty], ref Mnil)) else ty in let clty = class_type env virt self_scope scty in let typ = Cty_arrow (l, ty, clty.cltyp_type) in cltyp (Tcty_arrow (l, cty, clty)) typ | Pcty_open (od, e) -> let (od, newenv) = !type_open_descr env od in let clty = class_type newenv virt self_scope e in cltyp (Tcty_open (od, clty)) clty.cltyp_type | Pcty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) let class_type env virt self_scope scty = delayed_meth_specs := []; let cty = class_type env virt self_scope scty in List.iter Lazy.force (List.rev !delayed_meth_specs); delayed_meth_specs := []; cty let enter_ancestor_val name val_env = Env.enter_unbound_value name Val_unbound_ancestor val_env let enter_self_val name val_env = Env.enter_unbound_value name Val_unbound_self val_env let enter_instance_var_val name val_env = Env.enter_unbound_value name Val_unbound_instance_variable val_env let enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env = let check s = Warnings.Unused_ancestor s in let kind = Val_anc (sign, meths, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.enter_value ~check name desc met_env let add_self_met loc id sign self_var_kind vars cl_num as_var ty attrs met_env = let check = if as_var then (fun s -> Warnings.Unused_var s) else (fun s -> Warnings.Unused_var_strict s) in let kind = Val_self (sign, self_var_kind, vars, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value ~check id desc met_env let add_instance_var_met loc label id sign cl_num attrs met_env = let mut, ty = match Vars.find label sign.csig_vars with | (mut, _, ty) -> mut, ty | exception Not_found -> assert false in let kind = Val_ivar (mut, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value id desc met_env let add_instance_vars_met loc vars sign cl_num met_env = List.fold_left (fun met_env (label, id) -> add_instance_var_met loc label id sign cl_num [] met_env) met_env vars type intermediate_class_field = | Inherit of { override : override_flag; parent : class_expr; super : string option; inherited_vars : (string * Ident.t) list; super_meths : (string * Ident.t) list; loc : Location.t; attributes : attribute list; } | Virtual_val of { label : string loc; mut : mutable_flag; id : Ident.t; cty : core_type; already_declared : bool; loc : Location.t; attributes : attribute list; } | Concrete_val of { label : string loc; mut : mutable_flag; id : Ident.t; override : override_flag; definition : expression; already_declared : bool; loc : Location.t; attributes : attribute list; } | Virtual_method of { label : string loc; priv : private_flag; cty : core_type; loc : Location.t; attributes : attribute list; } | Concrete_method of { label : string loc; priv : private_flag; override : override_flag; sdefinition : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Constraint of { cty1 : core_type; cty2 : core_type; loc : Location.t; attributes : attribute list; } | Initializer of { sexpr : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Attribute of { attribute : attribute; loc : Location.t; attributes : attribute list; } type first_pass_accummulater = { rev_fields : intermediate_class_field list; val_env : Env.t; par_env : Env.t; concrete_meths : MethSet.t; concrete_vals : VarSet.t; local_meths : MethSet.t; local_vals : VarSet.t; vars : Ident.t Vars.t; } let rec class_field_first_pass self_loc cl_num sign self_scope acc cf = let { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } = acc in let loc = cf.pcf_loc in let attributes = cf.pcf_attributes in let with_attrs f = Builtin_attributes.warning_scope attributes f in match cf.pcf_desc with | Pcf_inherit (override, sparent, super) -> with_attrs (fun () -> let parent = class_expr cl_num val_env par_env Virtual self_scope sparent in complete_class_type parent.cl_loc par_env Virtual Class parent.cl_type; inherit_class_type ~strict:true loc val_env sign parent.cl_type; let parent_sign = Btype.signature_of_class_type parent.cl_type in let new_concrete_meths = Btype.concrete_methods parent_sign in let new_concrete_vals = Btype.concrete_instance_vars parent_sign in let over_meths = MethSet.inter new_concrete_meths concrete_meths in let over_vals = VarSet.inter new_concrete_vals concrete_vals in begin match override with | Fresh -> let cname = match parent.cl_type with | Cty_constr (p, _, _) -> Path.name p | _ -> "inherited" in if not (MethSet.is_empty over_meths) then Location.prerr_warning loc (Warnings.Method_override (cname :: MethSet.elements over_meths)); if not (VarSet.is_empty over_vals) then Location.prerr_warning loc (Warnings.Instance_variable_override (cname :: VarSet.elements over_vals)); | Override -> if MethSet.is_empty over_meths && VarSet.is_empty over_vals then raise (Error(loc, val_env, No_overriding ("",""))) end; let concrete_vals = VarSet.union new_concrete_vals concrete_vals in let concrete_meths = MethSet.union new_concrete_meths concrete_meths in let val_env, par_env, inherited_vars, vars = Vars.fold (fun label _ (val_env, par_env, inherited_vars, vars) -> let val_env = enter_instance_var_val label val_env in let par_env = enter_instance_var_val label par_env in let id = Ident.create_local label in let inherited_vars = (label, id) :: inherited_vars in let vars = Vars.add label id vars in (val_env, par_env, inherited_vars, vars)) parent_sign.csig_vars (val_env, par_env, [], vars) in let super_meths = MethSet.fold (fun label acc -> (label, Ident.create_local label) :: acc) new_concrete_meths [] in Super let (val_env, par_env, super) = match super with | None -> (val_env, par_env, None) | Some {txt=name} -> let val_env = enter_ancestor_val name val_env in let par_env = enter_ancestor_val name par_env in (val_env, par_env, Some name) in let field = Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; concrete_meths; concrete_vals; vars }) | Pcf_val (label, mut, Cfk_virtual styp) -> with_attrs (fun () -> let cty = Ctype.with_local_level_if_principal (fun () -> Typetexp.transl_simple_type val_env ~closed:false styp) ~post:(fun cty -> Ctype.generalize_structure cty.ctyp_type) in add_instance_variable ~strict:true loc val_env label.txt mut Virtual cty.ctyp_type sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Virtual_val { label; mut; id; cty; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; vars }) | Pcf_val (label, mut, Cfk_concrete (override, sdefinition)) -> with_attrs (fun () -> if VarSet.mem label.txt local_vals then raise(Error(loc, val_env, Duplicate ("instance variable", label.txt))); if VarSet.mem label.txt concrete_vals then begin if override = Fresh then Location.prerr_warning label.loc (Warnings.Instance_variable_override[label.txt]) end else begin if override = Override then raise(Error(loc, val_env, No_overriding ("instance variable", label.txt))) end; let definition = Ctype.with_local_level_if_principal ~post:Typecore.generalize_structure_exp (fun () -> type_exp val_env sdefinition) in add_instance_variable ~strict:true loc val_env label.txt mut Concrete definition.exp_type sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_vals = VarSet.add label.txt concrete_vals in let local_vals = VarSet.add label.txt local_vals in { acc with rev_fields; val_env; par_env; concrete_vals; local_vals; vars }) | Pcf_method (label, priv, Cfk_virtual sty) -> with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in let cty = transl_simple_type val_env ~closed:false sty in let ty = cty.ctyp_type in add_method loc val_env label.txt priv Virtual ty sign; let field = Virtual_method { label; priv; cty; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_method (label, priv, Cfk_concrete (override, expr)) -> with_attrs (fun () -> if MethSet.mem label.txt local_meths then raise(Error(loc, val_env, Duplicate ("method", label.txt))); if MethSet.mem label.txt concrete_meths then begin if override = Fresh then begin Location.prerr_warning loc (Warnings.Method_override [label.txt]) end end else begin if override = Override then begin raise(Error(loc, val_env, No_overriding("method", label.txt))) end end; let expr = match expr.pexp_desc with | Pexp_poly _ -> expr | _ -> Ast_helper.Exp.poly ~loc:expr.pexp_loc expr None in let sbody, sty = match expr.pexp_desc with | Pexp_poly (sbody, sty) -> sbody, sty | _ -> assert false in let ty = match sty with | None -> Ctype.newvar () | Some sty -> let sty = Ast_helper.Typ.force_poly sty in let cty' = Typetexp.transl_simple_type val_env ~closed:false sty in cty'.ctyp_type in add_method loc val_env label.txt priv Concrete ty sign; begin try match get_desc ty with | Tvar _ -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty; Ctype.unify val_env (type_approx val_env sbody) ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in let ty2 = type_approx val_env sbody in Ctype.unify val_env ty2 ty1' | _ -> assert false with Ctype.Unify err -> raise(Error(loc, val_env, Field_type_mismatch ("method", label.txt, err))) end; let sdefinition = make_method self_loc cl_num expr in let warning_state = Warnings.backup () in let field = Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_meths = MethSet.add label.txt concrete_meths in let local_meths = MethSet.add label.txt local_meths in { acc with rev_fields; concrete_meths; local_meths }) | Pcf_constraint (sty1, sty2) -> with_attrs (fun () -> let (cty1, cty2) = type_constraint val_env sty1 sty2 loc in let field = Constraint { cty1; cty2; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_initializer sexpr -> with_attrs (fun () -> let sexpr = make_method self_loc cl_num sexpr in let warning_state = Warnings.backup () in let field = Initializer { sexpr; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_attribute attribute -> Builtin_attributes.warning_attribute attribute; let field = Attribute { attribute; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields } | Pcf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_fields_first_pass self_loc cl_num sign self_scope val_env par_env cfs = let rev_fields = [] in let concrete_meths = MethSet.empty in let concrete_vals = VarSet.empty in let local_meths = MethSet.empty in let local_vals = VarSet.empty in let vars = Vars.empty in let init_acc = { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } in let acc = Builtin_attributes.warning_scope [] (fun () -> List.fold_left (class_field_first_pass self_loc cl_num sign self_scope) init_acc cfs) in List.rev acc.rev_fields, acc.vars and class_field_second_pass cl_num sign met_env field = let mkcf desc loc attrs = { cf_desc = desc; cf_loc = loc; cf_attributes = attrs } in match field with | Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } -> let met_env = add_instance_vars_met loc inherited_vars sign cl_num met_env in let met_env = match super with | None -> met_env | Some name -> let meths = List.fold_left (fun acc (label, id) -> Meths.add label id acc) Meths.empty super_meths in let ty = Btype.self_type parent.cl_type in let attrs = [] in let _id, met_env = enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env in met_env in let desc = Tcf_inherit(override, parent, super, inherited_vars, super_meths) in met_env, mkcf desc loc attributes | Virtual_val { label; mut; id; cty; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_virtual cty in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_concrete(override, definition) in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Virtual_method { label; priv; cty; loc; attributes } -> let kind = Tcfk_virtual cty in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes | Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> let ty = Btype.method_type label.txt sign in let self_type = sign.Types.csig_self in let meth_type = mk_expected (Btype.newgenty (Tarrow(Nolabel, self_type, ty, commu_ok))) in let texp = Ctype.with_raised_nongen_level (fun () -> type_expect met_env sdefinition meth_type) in let kind = Tcfk_concrete (override, texp) in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes) | Constraint { cty1; cty2; loc; attributes } -> let desc = Tcf_constraint(cty1, cty2) in met_env, mkcf desc loc attributes | Initializer { sexpr; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> let unit_type = Ctype.instance Predef.type_unit in let self_type = sign.Types.csig_self in let meth_type = mk_expected (Ctype.newty (Tarrow (Nolabel, self_type, unit_type, commu_ok))) in let texp = Ctype.with_raised_nongen_level (fun () -> type_expect met_env sexpr meth_type) in let desc = Tcf_initializer texp in met_env, mkcf desc loc attributes) | Attribute { attribute; loc; attributes; } -> let desc = Tcf_attribute attribute in met_env, mkcf desc loc attributes and class_fields_second_pass cl_num sign met_env fields = let _, rev_cfs = List.fold_left (fun (met_env, cfs) field -> let met_env, cf = class_field_second_pass cl_num sign met_env field in met_env, cf :: cfs) (met_env, []) fields in List.rev rev_cfs and class_structure cl_num virt self_scope final val_env met_env loc { pcstr_self = spat; pcstr_fields = str } = let par_env = met_env in let self_loc = {spat.ppat_loc with Location.loc_ghost = true} in let sign = Ctype.new_class_signature () in begin match final with | Not_final -> Ctype.add_dummy_method val_env ~scope:self_scope sign; | Final -> () end; let (self_pat, self_pat_vars) = type_self_pattern val_env spat in let val_env, par_env = List.fold_right (fun {pv_id; _} (val_env, par_env) -> let name = Ident.name pv_id in let val_env = enter_self_val name val_env in let par_env = enter_self_val name par_env in val_env, par_env) self_pat_vars (val_env, par_env) in begin try Ctype.unify val_env self_pat.pat_type sign.csig_self with Ctype.Unify _ -> raise(Error(spat.ppat_loc, val_env, Pattern_type_clash self_pat.pat_type)) end; let (fields, vars) = class_fields_first_pass self_loc cl_num sign self_scope val_env par_env str in let kind = kind_of_final final in check_virtual loc val_env virt kind sign; update_class_signature loc val_env ~warn_implicit_public:false virt kind sign; let meths = Meths.fold (fun label _ meths -> Meths.add label (Ident.create_local label) meths) sign.csig_meths Meths.empty in begin match final with | Not_final -> () | Final -> if not (Ctype.close_class_signature val_env sign) then raise(Error(loc, val_env, Closing_self_type sign)); end; Ctype.generalize_class_signature_spine val_env sign; let self_var_kind = match virt with | Virtual -> Self_virtual(ref meths) | Concrete -> Self_concrete meths in let met_env = List.fold_right (fun {pv_id; pv_type; pv_loc; pv_as_var; pv_attributes} met_env -> add_self_met pv_loc pv_id sign self_var_kind vars cl_num pv_as_var pv_type pv_attributes met_env) self_pat_vars met_env in let fields = class_fields_second_pass cl_num sign met_env fields in update_class_signature loc val_env ~warn_implicit_public:true virt kind sign; let meths = match self_var_kind with | Self_virtual meths_ref -> !meths_ref | Self_concrete meths -> meths in { cstr_self = self_pat; cstr_fields = fields; cstr_type = sign; cstr_meths = meths; } and class_expr cl_num val_env met_env virt self_scope scl = Builtin_attributes.warning_scope scl.pcl_attributes (fun () -> class_expr_aux cl_num val_env met_env virt self_scope scl) and class_expr_aux cl_num val_env met_env virt self_scope scl = match scl.pcl_desc with | Pcl_constr (lid, styl) -> let (path, decl) = Env.lookup_class ~loc:scl.pcl_loc lid.txt val_env in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, val_env, Unbound_class_2 lid.txt)); let tyl = List.map (fun sty -> transl_simple_type val_env ~closed:false sty) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = Btype.abbreviate_class_type path params clty in Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type clty'); if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, val_env, Parameter_arity_mismatch (lid.txt, List.length params, List.length tyl))); List.iter2 (fun cty' ty -> let ty' = cty'.ctyp_type in try Ctype.unify val_env ty' ty with Ctype.Unify err -> raise(Error(cty'.ctyp_loc, val_env, Parameter_mismatch err))) tyl params; check_virtual_clty scl.pcl_loc val_env virt Class clty'; let cl = rc {cl_desc = Tcl_ident (path, lid, tyl); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; cl_attributes = scl.pcl_attributes; } in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tcl_constraint (cl, None, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; } | Pcl_structure cl_str -> let desc = class_structure cl_num virt self_scope Not_final val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tcl_structure desc; cl_loc = scl.pcl_loc; cl_type = Cty_signature desc.cstr_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_fun (l, Some default, spat, sbody) -> let loc = default.pexp_loc in let open Ast_helper in let scases = [ Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "Some")))) (Some ([], Pat.var ~loc (mknoloc "*sth*")))) (Exp.ident ~loc (mknoloc (Longident.Lident "*sth*"))); Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "None")))) None) default; ] in let smatch = Exp.match_ ~loc (Exp.ident ~loc (mknoloc (Longident.Lident "*opt*"))) scases in let sfun = Cl.fun_ ~loc:scl.pcl_loc l None (Pat.var ~loc (mknoloc "*opt*")) (Cl.let_ ~loc:scl.pcl_loc Nonrecursive [Vb.mk spat smatch] sbody) Note : we do n't put the ' # default ' attribute , as it is not detected for class - level let bindings . See # 5975 . is not detected for class-level let bindings. See #5975.*) in class_expr cl_num val_env met_env virt self_scope sfun | Pcl_fun (l, None, spat, scl') -> let (pat, pv, val_env', met_env) = Ctype.with_local_level_if_principal (fun () -> Typecore.type_class_arg_pattern cl_num val_env met_env l spat) ~post: begin fun (pat, _, _, _) -> let gen {pat_type = ty} = Ctype.generalize_structure ty in iter_pattern gen pat end in let pv = List.map begin fun (id, id', _ty) -> let path = Pident id' in let vd = Env.find_value path val_env' in (id, {exp_desc = Texp_ident(path, mknoloc (Longident.Lident (Ident.name id)), vd); exp_loc = Location.none; exp_extra = []; exp_type = Ctype.instance vd.val_type; exp_env = val_env'}) end pv in let rec not_nolabel_function = function | Cty_arrow(Nolabel, _, _) -> false | Cty_arrow(_, _, cty) -> not_nolabel_function cty | _ -> true in let partial = let dummy = type_exp val_env (Ast_helper.Exp.unreachable ()) in Typecore.check_partial val_env pat.pat_type pat.pat_loc [{c_lhs = pat; c_guard = None; c_rhs = dummy}] in let cl = Ctype.with_raised_nongen_level (fun () -> class_expr cl_num val_env' met_env virt self_scope scl') in if Btype.is_optional l && not_nolabel_function cl.cl_type then Location.prerr_warning pat.pat_loc Warnings.Unerasable_optional_argument; rc {cl_desc = Tcl_fun (l, pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Cty_arrow (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_apply (scl', sargs) -> assert (sargs <> []); let cl = Ctype.with_local_level_if_principal (fun () -> class_expr cl_num val_env met_env virt self_scope scl') ~post:(fun cl -> Ctype.generalize_class_type_structure cl.cl_type) in let rec nonopt_labels ls ty_fun = match ty_fun with | Cty_arrow (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = Nolabel) sargs && List.exists (fun l -> l <> Nolabel) labels && begin Location.prerr_warning cl.cl_loc (Warnings.Labels_omitted (List.map Printtyp.string_of_label (List.filter ((<>) Nolabel) labels))); true end in let rec type_args args omitted ty_fun ty_fun0 sargs = match ty_fun, ty_fun0 with | Cty_arrow (l, ty, ty_fun), Cty_arrow (_, ty0, ty_fun0) when sargs <> [] -> let name = Btype.label_name l and optional = Btype.is_optional l in let use_arg sarg l' = Some ( if not optional || Btype.is_optional l' then type_argument val_env sarg ty ty0 else let ty' = extract_option_type val_env ty and ty0' = extract_option_type val_env ty0 in let arg = type_argument val_env sarg ty' ty0' in option_some val_env arg ) in let eliminate_optional_arg () = Some (option_none val_env ty0 Location.none) in let remaining_sargs, arg = if ignore_labels then begin match sargs with | [] -> assert false | (l', sarg) :: remaining_sargs -> if name = Btype.label_name l' || (not optional && l' = Nolabel) then (remaining_sargs, use_arg sarg l') else if optional && not (List.exists (fun (l, _) -> name = Btype.label_name l) remaining_sargs) then (sargs, eliminate_optional_arg ()) else raise(Error(sarg.pexp_loc, val_env, Apply_wrong_label l')) end else match Btype.extract_label name sargs with | Some (l', sarg, _, remaining_sargs) -> if not optional && Btype.is_optional l' then Location.prerr_warning sarg.pexp_loc (Warnings.Nonoptional_label (Printtyp.string_of_label l)); remaining_sargs, use_arg sarg l' | None -> sargs, if Btype.is_optional l && List.mem_assoc Nolabel sargs then eliminate_optional_arg () else None in let omitted = if arg = None then (l,ty0) :: omitted else omitted in type_args ((l,arg)::args) omitted ty_fun ty_fun0 remaining_sargs | _ -> match sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, val_env, Apply_wrong_label l)) else raise(Error(cl.cl_loc, val_env, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Cty_arrow(l,ty,ty_fun)) ty_fun0 omitted) in let (args, cty) = let (_, ty_fun0) = Ctype.instance_class [] cl.cl_type in type_args [] [] cl.cl_type ty_fun0 sargs in rc {cl_desc = Tcl_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = Typecore.type_let In_class_def val_env rec_flag sdefs in let (vals, met_env) = List.fold_right (fun (id, _id_loc, _typ) (vals, met_env) -> let path = Pident id in let vd = Env.find_value path val_env in let ty = Ctype.with_local_level ~post:Ctype.generalize (fun () -> Ctype.instance vd.val_type) in let expr = {exp_desc = Texp_ident(path, mknoloc(Longident.Lident (Ident.name id)),vd); exp_loc = Location.none; exp_extra = []; exp_type = ty; exp_attributes = []; exp_env = val_env; } in let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num); val_attributes = []; Types.val_loc = vd.Types.val_loc; val_uid = vd.val_uid; } in let id' = Ident.create_local (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents_full defs) ([], met_env) in let cl = class_expr cl_num val_env met_env virt self_scope scl' in let () = if rec_flag = Recursive then check_recursive_bindings val_env defs in rc {cl_desc = Tcl_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_constraint (scl', scty) -> let cl, clty = Ctype.with_local_level_for_class begin fun () -> let cl = Typetexp.TyVarEnv.with_local_scope begin fun () -> let cl = class_expr cl_num val_env met_env virt self_scope scl' in complete_class_type cl.cl_loc val_env virt Class_type cl.cl_type; cl end and clty = Typetexp.TyVarEnv.with_local_scope begin fun () -> let clty = class_type val_env virt self_scope scty in complete_class_type clty.cltyp_loc val_env virt Class clty.cltyp_type; clty end in cl, clty end ~post: begin fun ({cl_type=cl}, {cltyp_type=clty}) -> Ctype.limited_generalize_class_type (Btype.self_type_row cl) cl; Ctype.limited_generalize_class_type (Btype.self_type_row clty) clty; end in begin match Includeclass.class_types val_env cl.cl_type clty.cltyp_type with [] -> () | error -> raise(Error(cl.cl_loc, val_env, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty.cltyp_type in let ty = snd (Ctype.instance_class [] clty.cltyp_type) in Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type ty); rc {cl_desc = Tcl_constraint (cl, Some clty, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = ty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_open (pod, e) -> let used_slot = ref false in let (od, new_val_env) = !type_open_descr ~used_slot val_env pod in let ( _, new_met_env) = !type_open_descr ~used_slot met_env pod in let cl = class_expr cl_num new_val_env new_met_env virt self_scope e in rc {cl_desc = Tcl_open (od, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_declaration cl, commu_ok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_arrow (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_description ct, commu_ok)) | _ -> Ctype.newvar () let temp_abbrev loc arity uid = let params = ref [] in for _i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let ty_td = {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = loc; or keep attrs from the class decl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = uid; } in (!params, ty, ty_td) let initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, uid) = let arity = List.length cl.pci_params in let (obj_params, obj_ty, obj_td) = temp_abbrev cl.pci_loc arity uid in let env = Env.add_type ~check:true obj_id obj_td env in let (cl_params, cl_ty, cl_td) = temp_abbrev cl.pci_loc arity uid in let constr_type = Ctype.with_local_level_if_principal (fun () -> approx cl.pci_expr) ~post:Ctype.generalize_structure in let dummy_cty = Cty_signature (Ctype.new_class_signature ()) in let dummy_class = cty_variance = []; cty_path = unbound_class; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = Location.none; cty_attributes = []; cty_uid = uid; } in let env = Env.add_cltype ty_id clty_variance = []; clty_path = unbound_class; clty_loc = Location.none; clty_attributes = []; clty_uid = uid; } ( if define_class then Env.add_class id dummy_class env else env ) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class) (res, env) = let ci_params, params, coercion_locs, expr, typ, sign = Ctype.with_local_level_for_class begin fun () -> TyVarEnv.reset (); let ci_params = let make_param (sty, v) = try (transl_type_param env sty, v) with Already_bound -> raise(Error(sty.ptyp_loc, env, Repeated_parameter)) in List.map make_param cl.pci_params in let params = List.map (fun (cty, _) -> cty.ctyp_type) ci_params in let coercion_locs = ref [] in let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_virt cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in let sign = Btype.signature_of_class_type typ in (ci_params, params, coercion_locs, expr, typ, sign) end ~post: begin fun (_, params, _, _, typ, sign) -> the row variable List.iter (Ctype.limited_generalize sign.csig_self_row) params; Ctype.limited_generalize_class_type sign.csig_self_row typ; end in let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let row = Btype.self_type_row obj_type in Ctype.unify env row (Ctype.newty Tnil); begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_parameters (obj_id, obj_params, obj_params'))) end; let ty = Btype.self_type obj_type in begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; Ctype.set_object_name obj_id params (Btype.self_type typ); begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Btype.self_type cl_type in begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_class_type_parameters (ty_id, cl_params, cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let ty_expanded = Ctype.object_fields ty in raise(Error(cl.pci_loc, env, Abbrev_type_clash (ty, ty_expanded, cl_ty))) end end; begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Constructor_type_mismatch (cl.pci_name.txt, err))) end; let cty_variance = Variance.unknown_signature ~injective:false ~arity:(List.length params) in let cltydef = {clty_params = params; clty_type = Btype.class_body typ; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_hash_type = cl_td; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } and clty = {cty_params = params; cty_type = typ; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in let arity = Btype.class_type_arity typ in let pub_meths = Btype.public_methods sign in let (params', typ') = Ctype.instance_class params typ in let clty = {cty_params = params'; cty_type = typ'; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some (Ctype.instance constr_type) end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in let obj_abbr = let arity = List.length obj_params in { type_params = obj_params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some obj_ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = cl.pci_loc; or keep attrs from cl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = dummy_class.cty_uid; } in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Btype.self_type typ) in Ctype.set_object_name obj_id cl_params cl_ty; let cl_abbr = { cl_td with type_params = cl_params; type_manifest = Some cl_ty } in let cltydef = {clty_params = params'; clty_type = Btype.class_body typ'; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_hash_type = cl_abbr; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, ci_params, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, ci_params, arity, pub_meths, coe, expr) = let cl_abbr = cltydef.clty_hash_type in begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Non_collapsable_conjunction (id, clty, err))) end; List.iter Ctype.generalize clty.cty_params; Ctype.generalize_class_type clty.cty_type; Option.iter Ctype.generalize clty.cty_new; List.iter Ctype.generalize obj_abbr.type_params; Option.iter Ctype.generalize obj_abbr.type_manifest; List.iter Ctype.generalize cl_abbr.type_params; Option.iter Ctype.generalize cl_abbr.type_manifest; if Ctype.nongen_class_declaration clty then raise(Error(cl.pci_loc, env, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Btype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, env, Unbound_type_var(printer, reason))) end; { id; clty; ty_id; cltydef; obj_id; obj_abbr; arity; pub_meths; coe; id_loc = cl.pci_name; req = { ci_loc = cl.pci_loc; ci_virt = cl.pci_virt; ci_params = ci_params; ci_id_name = cl.pci_name; ci_id_class = id; ci_id_class_type = ty_id; ci_id_object = obj_id; ci_expr = expr; ci_decl = clty; ci_type_decl = cltydef; ci_attributes = cl.pci_attributes; } } let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class) (res, env) = Builtin_attributes.warning_scope cl.pci_attributes (fun () -> class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_params, cl_ty, cl_td, constr_type, dummy_class) (res, env) ) let extract_type_decls { clty; cltydef; obj_id; obj_abbr; req} decls = (obj_id, obj_abbr, clty, cltydef, req) :: decls let merge_type_decls decl (obj_abbr, clty, cltydef) = {decl with obj_abbr; clty; cltydef} let final_env define_class env { id; clty; ty_id; cltydef; obj_id; obj_abbr; } = Env.add_type ~check:true obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env)) let check_coercions env { id; id_loc; clty; ty_id; cltydef; obj_id; obj_abbr; arity; pub_meths; coe; req } = let cl_abbr = cltydef.clty_hash_type in begin match coe with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype err -> raise(Typecore.Error(loc, env, Typecore.Not_subtype err)) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, env, Cannot_coerce_self obj_ty)) end; {cls_id = id; cls_id_loc = id_loc; cls_decl = clty; cls_ty_id = ty_id; cls_ty_decl = cltydef; cls_obj_id = obj_id; cls_obj_abbr = obj_abbr; cls_abbr = cl_abbr; cls_arity = arity; cls_pub_methods = pub_meths; cls_info=req} let type_classes define_class approx kind env cls = let scope = Ctype.create_scope () in let cls = List.map (function cl -> (cl, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Uid.mk ~current_unit:(Env.get_unit_name ()) )) cls in let res, env = Ctype.with_local_level_for_class begin fun () -> let (res, env) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, env) = List.fold_right (class_infos define_class kind) res ([], env) in res, env end in let res = List.rev_map (final_decl env define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = try Typedecl_variance.update_class_decls env decls with Typedecl_variance.Error(loc, err) -> raise (Typedecl.Error(loc, Typedecl.Variance err)) in let res = List.map2 merge_type_decls res decls in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env virt sexpr = incr class_num; let self_scope = Ctype.get_current_level () in let expr = class_expr (Int.to_string !class_num) env env virt self_scope sexpr in complete_class_type expr.cl_loc env virt Class expr.cl_type; (expr, expr.cl_type) let class_description env virt sexpr = let self_scope = Ctype.get_current_level () in let expr = class_type env virt self_scope sexpr in complete_class_type expr.cltyp_loc env virt Class_type expr.cltyp_type; (expr, expr.cltyp_type) let class_declarations env cls = let info, env = type_classes true approx_declaration class_declaration env cls in let ids, exprs = List.split (List.map (fun ci -> ci.cls_id, ci.cls_info.ci_expr) info) in check_recursive_class_bindings env ids exprs; info, env let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decls, env) = type_classes false approx_description class_description env cls in (List.map (fun decl -> {clsty_ty_id = decl.cls_ty_id; clsty_id_loc = decl.cls_id_loc; clsty_ty_decl = decl.cls_ty_decl; clsty_obj_id = decl.cls_obj_id; clsty_obj_abbr = decl.cls_obj_abbr; clsty_abbr = decl.cls_abbr; clsty_info = decl.cls_info}) decls, env) let type_object env loc s = incr class_num; let desc = class_structure (Int.to_string !class_num) Concrete Btype.lowest_level Final env env loc s in complete_class_signature loc env Concrete Object desc.cstr_type; let meths = Btype.public_methods desc.cstr_type in (desc, meths) let () = Typecore.type_object := type_object Check that there is no references through recursive modules ( GPR#6491 ) let rec check_recmod_class_type env cty = match cty.pcty_desc with | Pcty_constr(lid, _) -> ignore (Env.lookup_cltype ~use:false ~loc:lid.loc lid.txt env) | Pcty_extension _ -> () | Pcty_arrow(_, _, cty) -> check_recmod_class_type env cty | Pcty_open(od, cty) -> let _, env = !type_open_descr env od in check_recmod_class_type env cty | Pcty_signature csig -> check_recmod_class_sig env csig and check_recmod_class_sig env csig = List.iter (fun ctf -> match ctf.pctf_desc with | Pctf_inherit cty -> check_recmod_class_type env cty | Pctf_val _ | Pctf_method _ | Pctf_constraint _ | Pctf_attribute _ | Pctf_extension _ -> ()) csig.pcsig_fields let check_recmod_decl env sdecl = check_recmod_class_type env sdecl.pci_expr let approx_class sdecl = let open Ast_helper in let self' = Typ.any () in let clty' = Cty.signature ~loc:sdecl.pci_expr.pcty_loc (Csig.mk self' []) in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = let decls, env = class_type_declarations env (List.map approx_class sdecls) in List.iter (check_recmod_decl env) sdecls; decls open Format let non_virtual_string_of_kind = function | Object -> "object" | Class -> "non-virtual class" | Class_type -> "non-virtual class type" let report_error env ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint err -> fprintf ppf "@[<v>The class constraints are not consistent.@ "; Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type"); fprintf ppf "@]" | Field_type_mismatch (k, m, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The %s %s@ has type" k m) (function ppf -> fprintf ppf "but is expected to have type") | Unexpected_field (ty, lab) -> fprintf ppf "@[@[<2>This object is expected to have type :@ %a@]\ @ This type does not have a method %s." Printtyp.type_expr ty lab | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply _ -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | Nolabel -> "out label" | l -> sprintf " label %s" (Btype.prefixed_label_name l) in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> XXX Revoir message | Improve error message fprintf ppf "@[%s@ %a@]" "This pattern cannot match self: it only matches values of type" Printtyp.type_expr ty | Unbound_class_2 cl -> fprintf ppf "@[The class@ %a@ is not yet completely defined@]" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "@[The class type@ %a@ is not yet completely defined@]" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> Printtyp.prepare_for_printing [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" !Oprint.out_type (Printtyp.tree_of_typexp Type abbrev) !Oprint.out_type (Printtyp.tree_of_typexp Type actual) !Oprint.out_type (Printtyp.tree_of_typexp Type expected) | Constructor_type_mismatch (c, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (kind, mets, vals) -> let kind = non_virtual_string_of_kind kind in let missings = match mets, vals with [], _ -> "variables" | _, [] -> "methods" | _ -> "methods and variables" in fprintf ppf "@[This %s has virtual %s.@ \ @[<2>The following %s are virtual : %a@]@]" kind missings missings (pp_print_list ~pp_sep:pp_print_space pp_print_string) (mets @ vals) | Undeclared_methods(kind, mets) -> let kind = non_virtual_string_of_kind kind in fprintf ppf "@[This %s has undeclared virtual methods.@ \ @[<2>The following methods were not declared : %a@]@]" kind (pp_print_list ~pp_sep:pp_print_space pp_print_string) mets | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.prepare_for_printing (params @ cstrs); fprintf ppf "@[The abbreviation %a@ is used with parameter(s)@ %a@ \ which are incompatible with constraint(s)@ %a@]" Printtyp.ident id !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) params) !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) cstrs) | Bad_class_type_parameters (id, params, cstrs) -> Printtyp.prepare_for_printing (params @ cstrs); fprintf ppf "@[The class type #%a@ is used with parameter(s)@ %a,@ \ whereas the class type definition@ constrains@ \ those parameters to be@ %a@]" Printtyp.ident id !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) params) !Oprint.out_type_args (List.map (Printtyp.tree_of_typexp Type) cstrs) | Class_match_failure error -> Includeclass.report_error Type ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_reason ppf { Ctype.free_variable; meth; meth_ty; } = let (ty0, kind) = free_variable in let ty1 = match kind with | Type_variable -> ty0 | Row_variable -> Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.add_type_to_preparation meth_ty; Printtyp.add_type_to_preparation ty1; fprintf ppf "The method %s@ has type@;<1 2>%a@ where@ %a@ is unbound" meth !Oprint.out_type (Printtyp.tree_of_typexp Type meth_ty) !Oprint.out_type (Printtyp.tree_of_typexp Type ty0) in fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurrences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, err) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsible conjunctive types in constraints.@ %t@]" (Printtyp.class_declaration id) clty (fun ppf -> Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") ) | Self_clash err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but actually has type") | Mutability_mismatch (_lab, mut) -> let mut1, mut2 = if mut = Immutable then "mutable", "immutable" else "immutable", "mutable" in fprintf ppf "@[The instance variable is %s;@ it cannot be redefined as %s@]" mut1 mut2 | No_overriding (_, "") -> fprintf ppf "@[This inheritance does not override any method@ %s@]" "instance variable" | No_overriding (kind, name) -> fprintf ppf "@[The %s `%s'@ has no previous definition@]" kind name | Duplicate (kind, name) -> fprintf ppf "@[The %s `%s'@ has multiple definitions in this object@]" kind name | Closing_self_type sign -> fprintf ppf "@[Cannot close type of object literal:@ %a@,\ it has been unified with the self type of a class that is not yet@ \ completely defined.@]" Printtyp.type_scheme sign.csig_self let report_error env ppf err = Printtyp.wrap_printing_env ~error:true env (fun () -> report_error env ppf err) let () = Location.register_error_of_exn (function | Error (loc, env, err) -> Some (Location.error_of_printer ~loc (report_error env) err) | Error_forward err -> Some err | _ -> None )
e0fe8ef731c58080d4336963d9aeec5a581f76b8776394d7fbffd2dd975f2d7a
HunterYIboHu/htdp2-solution
ex154-add-balloons.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex154-add-balloons) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) ; Graphic constants (define TEST (rectangle 20 40 "outline" "black")) (define WHITE (rectangle 0 0 "outline" "white")) A N is one of : ; - 0 ; - (add1 N) ; interpretation represents the natural numbers or counting numbers ; N Image -> Image produce a column of n copies of . (check-expect (col 3 TEST) (above TEST TEST TEST)) (check-expect (col 0 TEST) WHITE) (define (col n img) (cond [(zero? n) WHITE] [(positive? n) (above img (col (sub1 n) img))])) ; N Image -> Image produce a row of n copies of . (check-expect (row 3 TEST) (beside TEST TEST TEST)) (check-expect (row 0 TEST) WHITE) (define (row n img) (cond [(zero? n) WHITE] [(positive? n) (beside img (row (sub1 n) img))])) ; Physical constants (define COLS 18) (define ROWS 8) (define SIZE 10) (define BLOCK (rectangle SIZE SIZE "outline" "black")) (define L-HALL (place-image (row ROWS (col COLS BLOCK)) (/ (* ROWS SIZE) 2) (/ (* COLS SIZE) 2) (empty-scene (* ROWS SIZE) (* COLS SIZE)))) (define BALLOON (circle 5 "solid" "blue")) ; List-of-posns is one of: ; - '() ; - (cons Posn List-of-posns) ; the x coordinate is between 0 and 80 the y coordinate is between 0 and 180 ; examples: (define ZERO '()) (define TWO (cons (make-posn (* 3 SIZE) (* 12 SIZE)) (cons (make-posn (* 5 SIZE) (* 2 SIZE)) '()))) (define FIVE (cons (make-posn (* 3 SIZE) (* 12 SIZE)) (cons (make-posn (* 5 SIZE) (* 2 SIZE)) (cons (make-posn (* 7 SIZE) (* 7 SIZE)) (cons (make-posn (* 7 SIZE) (* 9 SIZE)) (cons (make-posn (* 2 SIZE) (* 10 SIZE)) '())))))) ; List-of-posns -> Image ; add balloons to the lecture hall according to the position in alop . (check-expect (add-balloons ZERO) L-HALL) (check-expect (add-balloons TWO) (place-images (make-list 2 BALLOON) (list (make-posn (* 3 SIZE) (* 12 SIZE)) (make-posn (* 5 SIZE) (* 2 SIZE))) L-HALL)) (check-expect (add-balloons FIVE) (place-images (make-list 5 BALLOON) (list (make-posn (* 3 SIZE) (* 12 SIZE)) (make-posn (* 5 SIZE) (* 2 SIZE)) (make-posn (* 7 SIZE) (* 7 SIZE)) (make-posn (* 7 SIZE) (* 9 SIZE)) (make-posn (* 2 SIZE) (* 10 SIZE))) L-HALL)) (define (add-balloons alop) (cond [(empty? alop) L-HALL] [(cons? alop) (place-image BALLOON (posn-x (first alop)) (posn-y (first alop)) (add-balloons (rest alop)))]))
null
https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter2/Section10-list-design-recipe/ex154-add-balloons.rkt
racket
about the language level of this file in a form that our tools can easily process. Graphic constants - 0 - (add1 N) interpretation represents the natural numbers or counting numbers N Image -> Image N Image -> Image Physical constants List-of-posns is one of: - '() - (cons Posn List-of-posns) the x coordinate is between 0 and 80 examples: List-of-posns -> Image add balloons to the lecture hall according to
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex154-add-balloons) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (define TEST (rectangle 20 40 "outline" "black")) (define WHITE (rectangle 0 0 "outline" "white")) A N is one of : produce a column of n copies of . (check-expect (col 3 TEST) (above TEST TEST TEST)) (check-expect (col 0 TEST) WHITE) (define (col n img) (cond [(zero? n) WHITE] [(positive? n) (above img (col (sub1 n) img))])) produce a row of n copies of . (check-expect (row 3 TEST) (beside TEST TEST TEST)) (check-expect (row 0 TEST) WHITE) (define (row n img) (cond [(zero? n) WHITE] [(positive? n) (beside img (row (sub1 n) img))])) (define COLS 18) (define ROWS 8) (define SIZE 10) (define BLOCK (rectangle SIZE SIZE "outline" "black")) (define L-HALL (place-image (row ROWS (col COLS BLOCK)) (/ (* ROWS SIZE) 2) (/ (* COLS SIZE) 2) (empty-scene (* ROWS SIZE) (* COLS SIZE)))) (define BALLOON (circle 5 "solid" "blue")) the y coordinate is between 0 and 180 (define ZERO '()) (define TWO (cons (make-posn (* 3 SIZE) (* 12 SIZE)) (cons (make-posn (* 5 SIZE) (* 2 SIZE)) '()))) (define FIVE (cons (make-posn (* 3 SIZE) (* 12 SIZE)) (cons (make-posn (* 5 SIZE) (* 2 SIZE)) (cons (make-posn (* 7 SIZE) (* 7 SIZE)) (cons (make-posn (* 7 SIZE) (* 9 SIZE)) (cons (make-posn (* 2 SIZE) (* 10 SIZE)) '())))))) the position in alop . (check-expect (add-balloons ZERO) L-HALL) (check-expect (add-balloons TWO) (place-images (make-list 2 BALLOON) (list (make-posn (* 3 SIZE) (* 12 SIZE)) (make-posn (* 5 SIZE) (* 2 SIZE))) L-HALL)) (check-expect (add-balloons FIVE) (place-images (make-list 5 BALLOON) (list (make-posn (* 3 SIZE) (* 12 SIZE)) (make-posn (* 5 SIZE) (* 2 SIZE)) (make-posn (* 7 SIZE) (* 7 SIZE)) (make-posn (* 7 SIZE) (* 9 SIZE)) (make-posn (* 2 SIZE) (* 10 SIZE))) L-HALL)) (define (add-balloons alop) (cond [(empty? alop) L-HALL] [(cons? alop) (place-image BALLOON (posn-x (first alop)) (posn-y (first alop)) (add-balloons (rest alop)))]))
b3d55225e277da6793101a93441d9900df532a5ac803ed1d8338c1ede37f2e4d
Verites/verigraph
Monad.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} module GrLang.Monad ( MonadGrLang(..) , ExceptT , importIfNeeded_ , makeVisible , Result , Error , prettyError , throwError , getOrError , addNew , reportAlreadyDefined , GrLangT , GrLangState(..) , emptyState , initState , runGrLangT , evalGrLangT , evalGrLang , getValueContext ) where import Control.Monad.Except (ExceptT (..), mapExceptT, runExceptT) import qualified Control.Monad.Except as ExceptT import Control.Monad.State import Data.DList (DList) import qualified Data.DList as DList import Data.Functor.Identity import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import Data.Text.Prettyprint.Doc (Doc, Pretty (..), (<+>)) import qualified Data.Text.Prettyprint.Doc as PP import qualified Data.Text.Prettyprint.Doc.Util as PP import Base.Annotation (Annotated (..), Located, locatedDoc, locationOf) import qualified Base.Annotation as Ann import Base.Location import qualified Data.Graphs as TypeGraph import Data.TypedGraph (Edge (..), EdgeId, Node (..), NodeId) import GrLang.Value type Error = DList (Located (Doc ())) type Result a = Either Error a prettyError :: Error -> Doc () prettyError = PP.vsep . map (PP.hang 2 . locatedDoc) . DList.toList throwError :: Monad m => Maybe Location -> Doc () -> ExceptT Error m a throwError loc msg = ExceptT.throwError $ DList.singleton (A loc msg) class Monad m => MonadGrLang m where -- | Given the path to a module and an action that imports it, executes the -- action unless the module was already imported. Makes the imported module -- visible, as well as its transitive imports. -- -- When running the import action, the only visible module will be the -- one being imported. importIfNeeded :: FilePath -> ExceptT Error m a -> ExceptT Error m (Maybe a) -- | Given the path to a module, check if it is was already imported. checkIfImported :: FilePath -> ExceptT Error m Bool -- | Given the path to a module, check if it is currently visible. checkIfVisible :: FilePath -> ExceptT Error m Bool -- | Given the path to a module, mark it as visible, _even when the path was not yet -- imported_. unsafeMakeVisible :: FilePath -> m () -- | Obtain the current type graph getTypeGraph :: ExceptT Error m TypeGraph -- | Look up the node type that has the given name getNodeType :: Located Text -> ExceptT Error m NodeType -- | Look up the edge type that has the given name, source type and id type. getEdgeType :: Located Text -> NodeType -> NodeType -> ExceptT Error m EdgeType -- | Create a new node type with given name, returning its id. If a node type -- with the same name already exists, returns an error. addNodeType :: Located Text -> ExceptT Error m () -- | Create a new edge type with given name, source type and target type, -- returning its id. If an edge type with the same name, source and target -- already exists, returns an error. addEdgeType :: Located Text -> Located Text -> Located Text -> ExceptT Error m () -- | Obtain the value associated to the given name, or return an error if -- there is none. getValue :: Located Text -> ExceptT Error m Value -- | Bind the given value to the given name. If the name is already bound, -- return an error. putValue :: Located Text -> Value -> ExceptT Error m () instance MonadGrLang m => MonadGrLang (StateT s m) where importIfNeeded path action = do st <- get result <- lift' . importIfNeeded path $ do result <- lift $ runStateT (runExceptT action) st case result of (Left errs, _) -> ExceptT.throwError errs (Right x, st') -> return (x, st') case result of Nothing -> return Nothing Just (x, st') -> put st' >> return (Just x) checkIfImported = lift' . checkIfImported checkIfVisible = lift' . checkIfVisible unsafeMakeVisible = lift . unsafeMakeVisible getTypeGraph = lift' getTypeGraph getNodeType = lift' . getNodeType getEdgeType name src = lift' . getEdgeType name src addNodeType = lift' . addNodeType addEdgeType name src = lift' . addEdgeType name src getValue = lift' . getValue putValue name = lift' . putValue name lift' :: Monad m => ExceptT Error m a -> ExceptT Error (StateT s m) a lift' = mapExceptT lift -- | Given the path to a module and an action that imports it, executes the -- action unless the module was already imported. Makes the imported module -- visible, as well as its transitive imports. -- -- When running the import action, the only visible module will be the -- one being imported. importIfNeeded_ :: MonadGrLang m => FilePath -> ExceptT Error m a -> ExceptT Error m () importIfNeeded_ path action = void $ importIfNeeded path action -- | Given the path to a module, mark it as visible. Fails when the path was not yet -- imported. makeVisible :: MonadGrLang m => Located FilePath -> ExceptT Error m () makeVisible (A loc srcPath) = do isImported <- checkIfImported srcPath if isImported then lift $ unsafeMakeVisible srcPath else throwError loc . PP.fillSep $ ["Cannot", "make", "unimported", "module", PP.squotes (pretty srcPath), "visible"] | A monad transformer for compiling or interpreting the GrLang . -- It allows the user to store local state of type @u@. newtype GrLangT m a = GrLangT { unGrLangT :: StateT GrLangState m a } deriving (Functor, Applicative, Monad, MonadTrans) data GrLangState = GrLangState { typeGraph :: TypeGraph , nodeTypes :: Map Text NodeId , edgeTypes :: Map (Text, NodeId, NodeId) EdgeId , valueContext :: Map Text (Located Value) , importedModules :: Set FilePath , visibleModules :: Set FilePath } emptyState :: GrLangState emptyState = GrLangState { typeGraph = TypeGraph.empty , nodeTypes = Map.empty , edgeTypes = Map.empty , valueContext = Map.empty , importedModules = Set.empty , visibleModules = Set.empty } initState :: TypeGraph -> GrLangState initState graph = emptyState { typeGraph = graph , nodeTypes = Map.fromList [ (nodeName n, nodeId n) | n <- TypeGraph.nodes graph ] , edgeTypes = Map.fromList [ ((edgeName e, sourceId e, targetId e), edgeId e) | e <- TypeGraph.edges graph ] } | Run a GrLang computation with the given initial state . runGrLangT :: Monad m => GrLangState -> GrLangT m a -> m (a, GrLangState) runGrLangT st (GrLangT action) = runStateT action st evalGrLangT :: Monad m => GrLangState -> ExceptT Error (GrLangT m) a -> m (Either Error a) evalGrLangT st action = evalStateT (unGrLangT $ runExceptT action) st evalGrLang :: GrLangState -> ExceptT Error (GrLangT Identity) a -> Either Error a evalGrLang st action = runIdentity $ evalGrLangT st action instance MonadIO m => MonadIO (GrLangT m) where liftIO = lift . liftIO instance Monad m => MonadGrLang (GrLangT m) where importIfNeeded path importAction = do isImported <- lift . GrLangT $ gets (Set.member path . importedModules) if isImported then do lift . GrLangT . modify $ \state -> state { visibleModules = Set.insert path (visibleModules state) } return Nothing else do outerVisible <- lift . GrLangT $ gets visibleModules lift . GrLangT . modify $ \state -> state { importedModules = Set.insert path (importedModules state) , visibleModules = Set.singleton path } result <- importAction lift . GrLangT . modify $ \state -> state { visibleModules = Set.union outerVisible (visibleModules state) } return (Just result) checkIfImported srcPath = lift . GrLangT $ gets (Set.member srcPath . importedModules) checkIfVisible srcPath = lift . GrLangT $ gets (Set.member srcPath . visibleModules) unsafeMakeVisible srcPath = GrLangT . modify $ \state -> state { visibleModules = Set.insert srcPath (visibleModules state) } getTypeGraph = lift . GrLangT $ gets typeGraph getNodeType (A loc name) = getOrError loc "node type" name (lookupNodeType name) nodeLocation getEdgeType (A loc name) srcType tgtType = getOrError loc "edge type" (showEdgeType name srcType tgtType) (lookupEdgeType name srcType tgtType) edgeLocation addNodeType (A loc name) = do existingType <- lift $ lookupNodeType name addNew' loc "Node type" name (nodeLocation <$> existingType) $ \state -> let newId:_ = TypeGraph.newNodes (typeGraph state) metadata = Metadata (Just name) loc in state { typeGraph = TypeGraph.insertNodeWithPayload newId (Just metadata) (typeGraph state) , nodeTypes = Map.insert name newId (nodeTypes state) } addEdgeType (A loc name) srcName tgtName = do srcType <- getNodeType srcName tgtType <- getNodeType tgtName existingType <- lift $ lookupEdgeType name srcType tgtType addNew' loc "Edge type" (showEdgeType name srcType tgtType) (edgeLocation <$> existingType) $ \state -> let newId:_ = TypeGraph.newEdges (typeGraph state) metadata = Metadata (Just name) loc (Node srcId _, Node tgtId _) = (srcType, tgtType) in state { typeGraph = TypeGraph.insertEdgeWithPayload newId srcId tgtId (Just metadata) (typeGraph state) , edgeTypes = Map.insert (name, srcId, tgtId) newId (edgeTypes state) } getValue (A loc name) = Ann.drop <$> getOrError loc "value" name (Map.lookup name <$> getValueContext) locationOf where getValueContext = GrLangT $ gets valueContext putValue (A loc name) val = do prevVal <- lift . GrLangT $ gets (Map.lookup name . valueContext) addNew' loc "Value" name (locationOf <$> prevVal) $ \state -> state { valueContext = Map.insert name (A loc val) (valueContext state) } lookupNodeType :: Monad m => Text -> GrLangT m (Maybe NodeType) lookupNodeType name = GrLangT $ do tgraph <- gets typeGraph ntypes <- gets nodeTypes return $ (`TypeGraph.lookupNode` tgraph) =<< Map.lookup name ntypes lookupEdgeType :: Monad m => Text -> NodeType -> NodeType -> GrLangT m (Maybe EdgeType) lookupEdgeType name srcType tgtType = GrLangT $ do tgraph <- gets typeGraph etypes <- gets edgeTypes return $ (`TypeGraph.lookupEdge` tgraph) =<< Map.lookup (name, nodeId srcType, nodeId tgtType) etypes getValueContext :: Monad m => ExceptT Error (GrLangT m) (Map Text (Located Value)) getValueContext = lift . GrLangT $ gets valueContext addNew' :: Monad m => Maybe Location -> String -> Text -> Maybe (Maybe Location) -> (GrLangState -> GrLangState) -> ExceptT Error (GrLangT m) () addNew' loc kind name existingLocation addToState = addNew loc kind name existingLocation . lift . GrLangT . modify $ \state -> let state' = addToState state tgraph = typeGraph state' in state' { valueContext = fmap (fmap $ updateTypeGraph tgraph) (valueContext state') } addNew :: Monad m => Maybe Location -> String -> Text -> Maybe (Maybe Location) -> ExceptT Error m a -> ExceptT Error m () addNew loc kind name existingLocation addToState = case existingLocation of Just loc' -> reportAlreadyDefined loc kind name loc' Nothing -> do _ <- addToState return () -- | Try to lookup a named element, throwing an error if there is none. -- -- Receives, in this order: the location which caused the lookup, a string -- describing the kind of value (e.g. "node or edge"), the name being looked up, -- an action that looks up the name, and a function that extracts locations from -- values of the kind being looked up. getOrError :: MonadGrLang m => Maybe Location -> String -> Text -> m (Maybe a) -> (a -> Maybe Location) -> ExceptT Error m a getOrError loc kind name getter getLocation = do result <- lift getter let undefError = PP.fillSep ["Undefined", pretty kind, PP.squotes (pretty name)] case result of Nothing -> throwError loc undefError Just x -> case getLocation x of Nothing -> return x Just (Location srcPath _) -> do isVisible <- checkIfVisible srcPath if isVisible then return x else throwError loc . PP.fillSep $ undefError : PP.words "(you must import" ++ [PP.squotes (pretty srcPath) <> ")"] showEdgeType :: Text -> GrNode -> GrNode -> Text showEdgeType e src tgt = formatEdgeType e (nodeName src) (nodeName tgt) reportAlreadyDefined :: Monad m => Maybe Location -> String -> Text -> Maybe Location -> ExceptT Error m a reportAlreadyDefined loc kind name prevLoc = throwError loc . PP.fillSep $ [ pretty kind, PP.squotes (pretty name), "was", "already", "defined" ] ++ case prevLoc of Nothing -> [] Just loc' -> ["at" <+> pretty loc']
null
https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/src/library/GrLang/Monad.hs
haskell
# LANGUAGE OverloadedStrings # | Given the path to a module and an action that imports it, executes the action unless the module was already imported. Makes the imported module visible, as well as its transitive imports. When running the import action, the only visible module will be the one being imported. | Given the path to a module, check if it is was already imported. | Given the path to a module, check if it is currently visible. | Given the path to a module, mark it as visible, _even when the path was not yet imported_. | Obtain the current type graph | Look up the node type that has the given name | Look up the edge type that has the given name, source type and id type. | Create a new node type with given name, returning its id. If a node type with the same name already exists, returns an error. | Create a new edge type with given name, source type and target type, returning its id. If an edge type with the same name, source and target already exists, returns an error. | Obtain the value associated to the given name, or return an error if there is none. | Bind the given value to the given name. If the name is already bound, return an error. | Given the path to a module and an action that imports it, executes the action unless the module was already imported. Makes the imported module visible, as well as its transitive imports. When running the import action, the only visible module will be the one being imported. | Given the path to a module, mark it as visible. Fails when the path was not yet imported. It allows the user to store local state of type @u@. | Try to lookup a named element, throwing an error if there is none. Receives, in this order: the location which caused the lookup, a string describing the kind of value (e.g. "node or edge"), the name being looked up, an action that looks up the name, and a function that extracts locations from values of the kind being looked up.
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # module GrLang.Monad ( MonadGrLang(..) , ExceptT , importIfNeeded_ , makeVisible , Result , Error , prettyError , throwError , getOrError , addNew , reportAlreadyDefined , GrLangT , GrLangState(..) , emptyState , initState , runGrLangT , evalGrLangT , evalGrLang , getValueContext ) where import Control.Monad.Except (ExceptT (..), mapExceptT, runExceptT) import qualified Control.Monad.Except as ExceptT import Control.Monad.State import Data.DList (DList) import qualified Data.DList as DList import Data.Functor.Identity import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import Data.Text.Prettyprint.Doc (Doc, Pretty (..), (<+>)) import qualified Data.Text.Prettyprint.Doc as PP import qualified Data.Text.Prettyprint.Doc.Util as PP import Base.Annotation (Annotated (..), Located, locatedDoc, locationOf) import qualified Base.Annotation as Ann import Base.Location import qualified Data.Graphs as TypeGraph import Data.TypedGraph (Edge (..), EdgeId, Node (..), NodeId) import GrLang.Value type Error = DList (Located (Doc ())) type Result a = Either Error a prettyError :: Error -> Doc () prettyError = PP.vsep . map (PP.hang 2 . locatedDoc) . DList.toList throwError :: Monad m => Maybe Location -> Doc () -> ExceptT Error m a throwError loc msg = ExceptT.throwError $ DList.singleton (A loc msg) class Monad m => MonadGrLang m where importIfNeeded :: FilePath -> ExceptT Error m a -> ExceptT Error m (Maybe a) checkIfImported :: FilePath -> ExceptT Error m Bool checkIfVisible :: FilePath -> ExceptT Error m Bool unsafeMakeVisible :: FilePath -> m () getTypeGraph :: ExceptT Error m TypeGraph getNodeType :: Located Text -> ExceptT Error m NodeType getEdgeType :: Located Text -> NodeType -> NodeType -> ExceptT Error m EdgeType addNodeType :: Located Text -> ExceptT Error m () addEdgeType :: Located Text -> Located Text -> Located Text -> ExceptT Error m () getValue :: Located Text -> ExceptT Error m Value putValue :: Located Text -> Value -> ExceptT Error m () instance MonadGrLang m => MonadGrLang (StateT s m) where importIfNeeded path action = do st <- get result <- lift' . importIfNeeded path $ do result <- lift $ runStateT (runExceptT action) st case result of (Left errs, _) -> ExceptT.throwError errs (Right x, st') -> return (x, st') case result of Nothing -> return Nothing Just (x, st') -> put st' >> return (Just x) checkIfImported = lift' . checkIfImported checkIfVisible = lift' . checkIfVisible unsafeMakeVisible = lift . unsafeMakeVisible getTypeGraph = lift' getTypeGraph getNodeType = lift' . getNodeType getEdgeType name src = lift' . getEdgeType name src addNodeType = lift' . addNodeType addEdgeType name src = lift' . addEdgeType name src getValue = lift' . getValue putValue name = lift' . putValue name lift' :: Monad m => ExceptT Error m a -> ExceptT Error (StateT s m) a lift' = mapExceptT lift importIfNeeded_ :: MonadGrLang m => FilePath -> ExceptT Error m a -> ExceptT Error m () importIfNeeded_ path action = void $ importIfNeeded path action makeVisible :: MonadGrLang m => Located FilePath -> ExceptT Error m () makeVisible (A loc srcPath) = do isImported <- checkIfImported srcPath if isImported then lift $ unsafeMakeVisible srcPath else throwError loc . PP.fillSep $ ["Cannot", "make", "unimported", "module", PP.squotes (pretty srcPath), "visible"] | A monad transformer for compiling or interpreting the GrLang . newtype GrLangT m a = GrLangT { unGrLangT :: StateT GrLangState m a } deriving (Functor, Applicative, Monad, MonadTrans) data GrLangState = GrLangState { typeGraph :: TypeGraph , nodeTypes :: Map Text NodeId , edgeTypes :: Map (Text, NodeId, NodeId) EdgeId , valueContext :: Map Text (Located Value) , importedModules :: Set FilePath , visibleModules :: Set FilePath } emptyState :: GrLangState emptyState = GrLangState { typeGraph = TypeGraph.empty , nodeTypes = Map.empty , edgeTypes = Map.empty , valueContext = Map.empty , importedModules = Set.empty , visibleModules = Set.empty } initState :: TypeGraph -> GrLangState initState graph = emptyState { typeGraph = graph , nodeTypes = Map.fromList [ (nodeName n, nodeId n) | n <- TypeGraph.nodes graph ] , edgeTypes = Map.fromList [ ((edgeName e, sourceId e, targetId e), edgeId e) | e <- TypeGraph.edges graph ] } | Run a GrLang computation with the given initial state . runGrLangT :: Monad m => GrLangState -> GrLangT m a -> m (a, GrLangState) runGrLangT st (GrLangT action) = runStateT action st evalGrLangT :: Monad m => GrLangState -> ExceptT Error (GrLangT m) a -> m (Either Error a) evalGrLangT st action = evalStateT (unGrLangT $ runExceptT action) st evalGrLang :: GrLangState -> ExceptT Error (GrLangT Identity) a -> Either Error a evalGrLang st action = runIdentity $ evalGrLangT st action instance MonadIO m => MonadIO (GrLangT m) where liftIO = lift . liftIO instance Monad m => MonadGrLang (GrLangT m) where importIfNeeded path importAction = do isImported <- lift . GrLangT $ gets (Set.member path . importedModules) if isImported then do lift . GrLangT . modify $ \state -> state { visibleModules = Set.insert path (visibleModules state) } return Nothing else do outerVisible <- lift . GrLangT $ gets visibleModules lift . GrLangT . modify $ \state -> state { importedModules = Set.insert path (importedModules state) , visibleModules = Set.singleton path } result <- importAction lift . GrLangT . modify $ \state -> state { visibleModules = Set.union outerVisible (visibleModules state) } return (Just result) checkIfImported srcPath = lift . GrLangT $ gets (Set.member srcPath . importedModules) checkIfVisible srcPath = lift . GrLangT $ gets (Set.member srcPath . visibleModules) unsafeMakeVisible srcPath = GrLangT . modify $ \state -> state { visibleModules = Set.insert srcPath (visibleModules state) } getTypeGraph = lift . GrLangT $ gets typeGraph getNodeType (A loc name) = getOrError loc "node type" name (lookupNodeType name) nodeLocation getEdgeType (A loc name) srcType tgtType = getOrError loc "edge type" (showEdgeType name srcType tgtType) (lookupEdgeType name srcType tgtType) edgeLocation addNodeType (A loc name) = do existingType <- lift $ lookupNodeType name addNew' loc "Node type" name (nodeLocation <$> existingType) $ \state -> let newId:_ = TypeGraph.newNodes (typeGraph state) metadata = Metadata (Just name) loc in state { typeGraph = TypeGraph.insertNodeWithPayload newId (Just metadata) (typeGraph state) , nodeTypes = Map.insert name newId (nodeTypes state) } addEdgeType (A loc name) srcName tgtName = do srcType <- getNodeType srcName tgtType <- getNodeType tgtName existingType <- lift $ lookupEdgeType name srcType tgtType addNew' loc "Edge type" (showEdgeType name srcType tgtType) (edgeLocation <$> existingType) $ \state -> let newId:_ = TypeGraph.newEdges (typeGraph state) metadata = Metadata (Just name) loc (Node srcId _, Node tgtId _) = (srcType, tgtType) in state { typeGraph = TypeGraph.insertEdgeWithPayload newId srcId tgtId (Just metadata) (typeGraph state) , edgeTypes = Map.insert (name, srcId, tgtId) newId (edgeTypes state) } getValue (A loc name) = Ann.drop <$> getOrError loc "value" name (Map.lookup name <$> getValueContext) locationOf where getValueContext = GrLangT $ gets valueContext putValue (A loc name) val = do prevVal <- lift . GrLangT $ gets (Map.lookup name . valueContext) addNew' loc "Value" name (locationOf <$> prevVal) $ \state -> state { valueContext = Map.insert name (A loc val) (valueContext state) } lookupNodeType :: Monad m => Text -> GrLangT m (Maybe NodeType) lookupNodeType name = GrLangT $ do tgraph <- gets typeGraph ntypes <- gets nodeTypes return $ (`TypeGraph.lookupNode` tgraph) =<< Map.lookup name ntypes lookupEdgeType :: Monad m => Text -> NodeType -> NodeType -> GrLangT m (Maybe EdgeType) lookupEdgeType name srcType tgtType = GrLangT $ do tgraph <- gets typeGraph etypes <- gets edgeTypes return $ (`TypeGraph.lookupEdge` tgraph) =<< Map.lookup (name, nodeId srcType, nodeId tgtType) etypes getValueContext :: Monad m => ExceptT Error (GrLangT m) (Map Text (Located Value)) getValueContext = lift . GrLangT $ gets valueContext addNew' :: Monad m => Maybe Location -> String -> Text -> Maybe (Maybe Location) -> (GrLangState -> GrLangState) -> ExceptT Error (GrLangT m) () addNew' loc kind name existingLocation addToState = addNew loc kind name existingLocation . lift . GrLangT . modify $ \state -> let state' = addToState state tgraph = typeGraph state' in state' { valueContext = fmap (fmap $ updateTypeGraph tgraph) (valueContext state') } addNew :: Monad m => Maybe Location -> String -> Text -> Maybe (Maybe Location) -> ExceptT Error m a -> ExceptT Error m () addNew loc kind name existingLocation addToState = case existingLocation of Just loc' -> reportAlreadyDefined loc kind name loc' Nothing -> do _ <- addToState return () getOrError :: MonadGrLang m => Maybe Location -> String -> Text -> m (Maybe a) -> (a -> Maybe Location) -> ExceptT Error m a getOrError loc kind name getter getLocation = do result <- lift getter let undefError = PP.fillSep ["Undefined", pretty kind, PP.squotes (pretty name)] case result of Nothing -> throwError loc undefError Just x -> case getLocation x of Nothing -> return x Just (Location srcPath _) -> do isVisible <- checkIfVisible srcPath if isVisible then return x else throwError loc . PP.fillSep $ undefError : PP.words "(you must import" ++ [PP.squotes (pretty srcPath) <> ")"] showEdgeType :: Text -> GrNode -> GrNode -> Text showEdgeType e src tgt = formatEdgeType e (nodeName src) (nodeName tgt) reportAlreadyDefined :: Monad m => Maybe Location -> String -> Text -> Maybe Location -> ExceptT Error m a reportAlreadyDefined loc kind name prevLoc = throwError loc . PP.fillSep $ [ pretty kind, PP.squotes (pretty name), "was", "already", "defined" ] ++ case prevLoc of Nothing -> [] Just loc' -> ["at" <+> pretty loc']
5c6f96808be40eddc41747734ece6b21ca4f08016492a323f4e55809758680c9
kazu-yamamoto/http2
Internal.hs
module Network.HTTP2.Client.Internal ( Request(..) , Response(..) ) where import Network.HTTP2.Client.Types
null
https://raw.githubusercontent.com/kazu-yamamoto/http2/3c29763be147a3d482eff28f427ad80f1d4df706/Network/HTTP2/Client/Internal.hs
haskell
module Network.HTTP2.Client.Internal ( Request(..) , Response(..) ) where import Network.HTTP2.Client.Types
6f20e4427bf20515b9bdfe1cbeeb0ec8b8df9d5237033e07cbbc99819abe78a5
mpickering/apply-refact
Monad2.hs
no = do foo ; mapM print a
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Monad2.hs
haskell
no = do foo ; mapM print a
a0c240ad9389c2cd49b06d59a9f9950e2611637e8eed3d1b2541ae30cf1d461a
janestreet/hardcaml_c
hardcaml_c.ml
include Simulator module Cyclesim = Cyclesim
null
https://raw.githubusercontent.com/janestreet/hardcaml_c/1bf2468801ba9f6a935ffcd08887d9da87bee3f1/lib/hardcaml_c.ml
ocaml
include Simulator module Cyclesim = Cyclesim
ea152613f70f379db188be5655cd028c7b1ac4ea73d7d5da89b2f438dfbd189f
haskell/ghcide
Logger.hs
Copyright ( c ) 2019 The DAML Authors . All rights reserved . SPDX - License - Identifier : Apache-2.0 {-# LANGUAGE RankNTypes #-} -- | This is a compatibility module that abstracts over the -- concrete choice of logging framework so users can plug in whatever -- framework they want to. module Development.IDE.Types.Logger ( Priority(..) , Logger(..) , logError, logWarning, logInfo, logDebug, logTelemetry , noLogging ) where import qualified Data.Text as T data Priority Do n't change the ordering of this type or you will mess up the Ord -- instance = Telemetry -- ^ Events that are useful for gathering user metrics. ^ Verbose debug logging . | Info -- ^ Useful information in case an error has to be understood. | Warning -- ^ These error messages should not occur in a expected usage, and -- should be investigated. | Error -- ^ Such log messages must never occur in expected usage. deriving (Eq, Show, Ord, Enum, Bounded) -- | Note that this is logging actions _of the program_, not of the user. -- You shouldn't call warning/error if the user has caused an error, only -- if our code has gone wrong and is itself erroneous (e.g. we threw an exception). data Logger = Logger {logPriority :: Priority -> T.Text -> IO ()} logError :: Logger -> T.Text -> IO () logError x = logPriority x Error logWarning :: Logger -> T.Text -> IO () logWarning x = logPriority x Warning logInfo :: Logger -> T.Text -> IO () logInfo x = logPriority x Info logDebug :: Logger -> T.Text -> IO () logDebug x = logPriority x Debug logTelemetry :: Logger -> T.Text -> IO () logTelemetry x = logPriority x Telemetry noLogging :: Logger noLogging = Logger $ \_ _ -> return ()
null
https://raw.githubusercontent.com/haskell/ghcide/3ef4ef99c4b9cde867d29180c32586947df64b9e/src/Development/IDE/Types/Logger.hs
haskell
# LANGUAGE RankNTypes # | This is a compatibility module that abstracts over the concrete choice of logging framework so users can plug in whatever framework they want to. instance ^ Events that are useful for gathering user metrics. ^ Useful information in case an error has to be understood. ^ These error messages should not occur in a expected usage, and should be investigated. ^ Such log messages must never occur in expected usage. | Note that this is logging actions _of the program_, not of the user. You shouldn't call warning/error if the user has caused an error, only if our code has gone wrong and is itself erroneous (e.g. we threw an exception).
Copyright ( c ) 2019 The DAML Authors . All rights reserved . SPDX - License - Identifier : Apache-2.0 module Development.IDE.Types.Logger ( Priority(..) , Logger(..) , logError, logWarning, logInfo, logDebug, logTelemetry , noLogging ) where import qualified Data.Text as T data Priority Do n't change the ordering of this type or you will mess up the Ord ^ Verbose debug logging . | Warning deriving (Eq, Show, Ord, Enum, Bounded) data Logger = Logger {logPriority :: Priority -> T.Text -> IO ()} logError :: Logger -> T.Text -> IO () logError x = logPriority x Error logWarning :: Logger -> T.Text -> IO () logWarning x = logPriority x Warning logInfo :: Logger -> T.Text -> IO () logInfo x = logPriority x Info logDebug :: Logger -> T.Text -> IO () logDebug x = logPriority x Debug logTelemetry :: Logger -> T.Text -> IO () logTelemetry x = logPriority x Telemetry noLogging :: Logger noLogging = Logger $ \_ _ -> return ()
fc74cc5c67ac319ef5823c4613d45a0f3d78aed116982d24afb6ac9cee690a39
francescoc/scalabilitywitherlangotp
bsc.erl
-module(bsc). -behaviour(application). -behaviour(supervisor). -export([start/2, stop/1, init/1]). %% Application callbacks start(_Type, _Args) -> {ok, _Pid} = supervisor:start_link({local,?MODULE}, ?MODULE, []). stop(_Data) -> ok. %% Supervisor callbacks init(_) -> ChildSpecList = [child(freq_overload), child(frequency), child(simple_phone_sup)], {ok,{{rest_for_one, 2, 3600}, ChildSpecList}}. child(Module) -> {Module, {Module, start_link, []}, permanent, 2000, worker, [Module]}.
null
https://raw.githubusercontent.com/francescoc/scalabilitywitherlangotp/961de968f034e55eba22eea9a368fe9f47c608cc/ch9/combining/bsc.erl
erlang
Application callbacks Supervisor callbacks
-module(bsc). -behaviour(application). -behaviour(supervisor). -export([start/2, stop/1, init/1]). start(_Type, _Args) -> {ok, _Pid} = supervisor:start_link({local,?MODULE}, ?MODULE, []). stop(_Data) -> ok. init(_) -> ChildSpecList = [child(freq_overload), child(frequency), child(simple_phone_sup)], {ok,{{rest_for_one, 2, 3600}, ChildSpecList}}. child(Module) -> {Module, {Module, start_link, []}, permanent, 2000, worker, [Module]}.
d2d75e824c6481bc45c9d1ec573a698eb0e41a960121c4288dc46fad5a5cbd74
johnwhitington/ocamli
if.ml
let _ = if 42 = 40 + 2 then 1 + 2 else 6 * 4
null
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/newtype/programs/if.ml
ocaml
let _ = if 42 = 40 + 2 then 1 + 2 else 6 * 4
48845c84787328bbabd7cfcebe567d3c9cf901a02d5023a002e1ff76925dc21c
missingfaktor/akar
core_test.clj
(ns akar-exceptions.core-test (:require [clojure.test :refer :all] [akar-exceptions.core :refer :all]) (:import [clojure.lang ExceptionInfo])) (deftest akar-exceptions-core-test (testing "attempt" (testing "returns value on successful computation" (is (= :ok (attempt (do (/ 0 2) :ok) :on-error ((:type Exception) :ko))))) (testing "skips exception handlers on successful computation" (let [handler-invoked (atom false) _ (attempt (do (/ 0 2)) :on-error (:_ (reset! handler-invoked true)))] (is (= false @handler-invoked))) (testing "runs finally on successful execution" (let [finally-invoked (atom false) _ (attempt (do (/ 0 2)) :on-error (:_ :ko) :ultimately (reset! finally-invoked true))] (is (= true @finally-invoked)))) (testing "handles exceptions using given handler" (is (= :ko (attempt (do (/ 2 0) :ok) :on-error ((:type Exception) :ko))))) (testing "uses super-class handlers if available" (is (= :arith (attempt (do (/ 2 0) :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format)))) (is (= :number-format (attempt (do (Integer/parseInt "not-really-a-number") :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format)))) (is (= :wut (attempt (do (count (count 1)) :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format (:type Exception) :wut))))) (testing "bubbles up throwable if a suitable handler is not found" (is (thrown? UnsupportedOperationException (attempt (do (count (count 1)) :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format))))) (testing "runs finally on failed execution" (let [finally-invoked (atom false) _ (attempt (do (/ 2 0)) :on-error (:_ :ko) :ultimately (reset! finally-invoked true))] (is (= true @finally-invoked)))) (testing "is okay with empty handler list" (is (attempt (/ 0 2) :on-error ()))))) (testing "raise" (testing "throws regular throwables" (is (thrown? NumberFormatException (raise (NumberFormatException.))))) (testing "throws map with the given message as ex-info" (is (thrown-with-msg? ExceptionInfo #"^hello$" (raise {:message "hello"})))) (testing "throws map with no specific message as ex-info" (is (thrown? ExceptionInfo (raise {:some-key :some-value})))) (testing "throws random values" (is (thrown? ExceptionInfo (raise :not-a-throwable-or-a-map))))) (testing "pattern functions" (let [exec (fn [block] (attempt (block) :on-error ([!ex-info {:occurrences n}] n [!ex-info :_] :ex-info-still [(!ex RuntimeException) e] (.getMessage e))))] (is (= 2 (exec (fn [] (raise {:occurrences 2}))))) (is (= :ex-info-still (exec (fn [] (raise 11))))) (is (= "Oops" (exec (fn [] (raise (RuntimeException. "Oops")))))) (is (thrown? Exception (exec (fn [] (raise (Exception.)))))))))
null
https://raw.githubusercontent.com/missingfaktor/akar/66403b735cafab4e9fb971b4bf56e899ee84962f/akar-exceptions/test/akar_exceptions/core_test.clj
clojure
(ns akar-exceptions.core-test (:require [clojure.test :refer :all] [akar-exceptions.core :refer :all]) (:import [clojure.lang ExceptionInfo])) (deftest akar-exceptions-core-test (testing "attempt" (testing "returns value on successful computation" (is (= :ok (attempt (do (/ 0 2) :ok) :on-error ((:type Exception) :ko))))) (testing "skips exception handlers on successful computation" (let [handler-invoked (atom false) _ (attempt (do (/ 0 2)) :on-error (:_ (reset! handler-invoked true)))] (is (= false @handler-invoked))) (testing "runs finally on successful execution" (let [finally-invoked (atom false) _ (attempt (do (/ 0 2)) :on-error (:_ :ko) :ultimately (reset! finally-invoked true))] (is (= true @finally-invoked)))) (testing "handles exceptions using given handler" (is (= :ko (attempt (do (/ 2 0) :ok) :on-error ((:type Exception) :ko))))) (testing "uses super-class handlers if available" (is (= :arith (attempt (do (/ 2 0) :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format)))) (is (= :number-format (attempt (do (Integer/parseInt "not-really-a-number") :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format)))) (is (= :wut (attempt (do (count (count 1)) :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format (:type Exception) :wut))))) (testing "bubbles up throwable if a suitable handler is not found" (is (thrown? UnsupportedOperationException (attempt (do (count (count 1)) :ok) :on-error ((:type ArithmeticException) :arith (:type NumberFormatException) :number-format))))) (testing "runs finally on failed execution" (let [finally-invoked (atom false) _ (attempt (do (/ 2 0)) :on-error (:_ :ko) :ultimately (reset! finally-invoked true))] (is (= true @finally-invoked)))) (testing "is okay with empty handler list" (is (attempt (/ 0 2) :on-error ()))))) (testing "raise" (testing "throws regular throwables" (is (thrown? NumberFormatException (raise (NumberFormatException.))))) (testing "throws map with the given message as ex-info" (is (thrown-with-msg? ExceptionInfo #"^hello$" (raise {:message "hello"})))) (testing "throws map with no specific message as ex-info" (is (thrown? ExceptionInfo (raise {:some-key :some-value})))) (testing "throws random values" (is (thrown? ExceptionInfo (raise :not-a-throwable-or-a-map))))) (testing "pattern functions" (let [exec (fn [block] (attempt (block) :on-error ([!ex-info {:occurrences n}] n [!ex-info :_] :ex-info-still [(!ex RuntimeException) e] (.getMessage e))))] (is (= 2 (exec (fn [] (raise {:occurrences 2}))))) (is (= :ex-info-still (exec (fn [] (raise 11))))) (is (= "Oops" (exec (fn [] (raise (RuntimeException. "Oops")))))) (is (thrown? Exception (exec (fn [] (raise (Exception.)))))))))
014472dd792d515ad1243c0711f7a91653903000b1f7cf501b05031a701faacb
bobzhang/ocaml-book
batch.ml
open Match module G = Mikmatch.Glob open BatPervasives let syscall cmd = let ic,oc = Unix.open_process cmd in let buf = Buffer.create 16 in (try while true do Buffer.add_channel buf ic 1 done with End_of_file -> () ); let _ = Unix.close_process (ic,oc) in Buffer.contents buf let _ = syscall "ls ../*/*.tex" |> flip BatString.nsplit "\n" |> List.filter (BatString.is_empty |- not) |> List.iter check
null
https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/util/batch.ml
ocaml
open Match module G = Mikmatch.Glob open BatPervasives let syscall cmd = let ic,oc = Unix.open_process cmd in let buf = Buffer.create 16 in (try while true do Buffer.add_channel buf ic 1 done with End_of_file -> () ); let _ = Unix.close_process (ic,oc) in Buffer.contents buf let _ = syscall "ls ../*/*.tex" |> flip BatString.nsplit "\n" |> List.filter (BatString.is_empty |- not) |> List.iter check
4aa297bbcf02f89d56a3a2f37c72ae0bf3153789aeff6ade4675c73269d4614c
lindig/lua-ml
luabaselib.ml
module Add (MakeParser : Luaparser.MAKER) (I : Luainterp.S) = struct module Parser = MakeParser (I.Ast) module P = Parser module V = I.Value let lex map buf = Luascanner.token buf map let do_lexbuf ~sourcename:filename g buf = let map = Luasrcmap.mk () in let _ = Luasrcmap.sync map 0 (filename, 1, 1) in try let chunks = P.chunks (lex map) buf in let pgm = I.compile ~srcdbg:(map, false) chunks g in match pgm () with | [] -> [I.Value.LuaValueBase.String "executed without errors"] | answers -> answers with | Parsing.Parse_error -> let file, line, _ = Luasrcmap.last map in let errmsg = Printf.sprintf "%s: Syntax error on line %d" file line in failwith errmsg | I.Error s -> failwith (Printf.sprintf "Runtime error: %s" s) | I.Value.Projection (_v, w) -> (failwith ("Error projecting to " ^ w)) let dostring ?(file="<string>") g s = let abbreviate s = if String.length s < 200 then s else String.sub s 0 60 ^ "..." in I.with_stack (V.srcloc ~file:("dostring('" ^ abbreviate s ^ "')") ~linedefined:0) g (do_lexbuf ~sourcename:file g) (Lexing.from_string s) let dofile g infile = try let f = match infile with "-" -> stdin | _ -> open_in infile in let close () = if infile <> "-" then close_in f else () in try let answer = I.with_stack (V.srcloc ~file:("dofile('" ^ infile ^ "')") ~linedefined:0) g (do_lexbuf ~sourcename:infile g) (Lexing.from_channel f) in (close(); answer) with e -> (close (); raise e) with Sys_error msg -> [V.LuaValueBase.Nil; V.LuaValueBase.String ("System error: " ^ msg)] let ( **-> ) = V.( **-> ) let ( **->> ) x y = x **-> V.result y let next t key = let k, v = try match key with | V.LuaValueBase.Nil -> V.Table.first t | _ -> V.Table.next t key with Not_found -> V.LuaValueBase.Nil, V.LuaValueBase.Nil in [k; v] let objname g v = let tail = [] in let ss = match V.objname g v with | Some (V.Fallback n) -> "`" :: n :: "' fallback" :: tail | Some (V.Global n) -> "function " :: n :: tail | Some (V.Element (t, V.LuaValueBase.String n)) -> "function " :: t :: "." :: n :: tail | Some (V.Element (t, v)) -> "function " :: t :: "[" :: V.to_string v :: "]" :: tail | None -> "unnamed " :: V.to_string v :: tail in String.concat "" ss let luabaselib g = [ "dofile", V.efunc (V.string **-> V.resultvs) (dofile g) ; "dostring", V.efunc (V.string **-> V.resultvs) (dostring g) should catch and turn into an error fallback ... ; "size", V.efunc (V.table **->> V.int) V.Luahash.length ; "next", V.efunc (V.table **-> V.value **-> V.resultvs) next ; "nextvar", V.efunc (V.value **-> V.resultvs) (fun x -> next g.V.globals x) ; "tostring", V.efunc (V.value **->> V.string) V.to_string ; "objname", V.efunc (V.value **->> V.string) (objname g) ; "print", V.caml_func (fun args -> List.iter (fun x -> print_endline (V.to_string x)) args; flush stdout; []) ; "tonumber", V.efunc (V.float **->> V.float) (fun x -> x) ; "type", V.efunc (V.value **->> V.string) (function | V.LuaValueBase.Nil -> "nil" | V.LuaValueBase.Number _ -> "number" | V.LuaValueBase.String _ -> "string" | V.LuaValueBase.Table _ -> "table" | V.LuaValueBase.Function (_,_) -> "function" | V.LuaValueBase.Userdata _ -> "userdata") ; "assert", V.efunc (V.value **-> V.default "" V.string **->> V.unit) (fun c msg -> match c with | V.LuaValueBase.Nil -> I.error ("assertion failed: " ^ msg) | _ -> ()) ; "error", V.efunc (V.string **->> V.unit) I.error ; "setglobal", V.efunc (V.value **-> V.value **->> V.unit) (fun k v -> V.Table.bind g.V.globals ~key:k ~data:v) ; "getglobal", V.efunc (V.value **->> V.value) (I.getglobal g) ; "setfallback", V.efunc (V.string **-> V.value **->> V.value) (I.setfallback g) ] include I let mk () = let g, init = I.pre_mk () in I.register_globals (luabaselib g) g; init (fun s -> ignore (dostring g s)); g end
null
https://raw.githubusercontent.com/lindig/lua-ml/c9fa490331ce22b9df03130be3fceac40a09877e/src/luabaselib.ml
ocaml
module Add (MakeParser : Luaparser.MAKER) (I : Luainterp.S) = struct module Parser = MakeParser (I.Ast) module P = Parser module V = I.Value let lex map buf = Luascanner.token buf map let do_lexbuf ~sourcename:filename g buf = let map = Luasrcmap.mk () in let _ = Luasrcmap.sync map 0 (filename, 1, 1) in try let chunks = P.chunks (lex map) buf in let pgm = I.compile ~srcdbg:(map, false) chunks g in match pgm () with | [] -> [I.Value.LuaValueBase.String "executed without errors"] | answers -> answers with | Parsing.Parse_error -> let file, line, _ = Luasrcmap.last map in let errmsg = Printf.sprintf "%s: Syntax error on line %d" file line in failwith errmsg | I.Error s -> failwith (Printf.sprintf "Runtime error: %s" s) | I.Value.Projection (_v, w) -> (failwith ("Error projecting to " ^ w)) let dostring ?(file="<string>") g s = let abbreviate s = if String.length s < 200 then s else String.sub s 0 60 ^ "..." in I.with_stack (V.srcloc ~file:("dostring('" ^ abbreviate s ^ "')") ~linedefined:0) g (do_lexbuf ~sourcename:file g) (Lexing.from_string s) let dofile g infile = try let f = match infile with "-" -> stdin | _ -> open_in infile in let close () = if infile <> "-" then close_in f else () in try let answer = I.with_stack (V.srcloc ~file:("dofile('" ^ infile ^ "')") ~linedefined:0) g (do_lexbuf ~sourcename:infile g) (Lexing.from_channel f) in (close(); answer) with e -> (close (); raise e) with Sys_error msg -> [V.LuaValueBase.Nil; V.LuaValueBase.String ("System error: " ^ msg)] let ( **-> ) = V.( **-> ) let ( **->> ) x y = x **-> V.result y let next t key = let k, v = try match key with | V.LuaValueBase.Nil -> V.Table.first t | _ -> V.Table.next t key with Not_found -> V.LuaValueBase.Nil, V.LuaValueBase.Nil in [k; v] let objname g v = let tail = [] in let ss = match V.objname g v with | Some (V.Fallback n) -> "`" :: n :: "' fallback" :: tail | Some (V.Global n) -> "function " :: n :: tail | Some (V.Element (t, V.LuaValueBase.String n)) -> "function " :: t :: "." :: n :: tail | Some (V.Element (t, v)) -> "function " :: t :: "[" :: V.to_string v :: "]" :: tail | None -> "unnamed " :: V.to_string v :: tail in String.concat "" ss let luabaselib g = [ "dofile", V.efunc (V.string **-> V.resultvs) (dofile g) ; "dostring", V.efunc (V.string **-> V.resultvs) (dostring g) should catch and turn into an error fallback ... ; "size", V.efunc (V.table **->> V.int) V.Luahash.length ; "next", V.efunc (V.table **-> V.value **-> V.resultvs) next ; "nextvar", V.efunc (V.value **-> V.resultvs) (fun x -> next g.V.globals x) ; "tostring", V.efunc (V.value **->> V.string) V.to_string ; "objname", V.efunc (V.value **->> V.string) (objname g) ; "print", V.caml_func (fun args -> List.iter (fun x -> print_endline (V.to_string x)) args; flush stdout; []) ; "tonumber", V.efunc (V.float **->> V.float) (fun x -> x) ; "type", V.efunc (V.value **->> V.string) (function | V.LuaValueBase.Nil -> "nil" | V.LuaValueBase.Number _ -> "number" | V.LuaValueBase.String _ -> "string" | V.LuaValueBase.Table _ -> "table" | V.LuaValueBase.Function (_,_) -> "function" | V.LuaValueBase.Userdata _ -> "userdata") ; "assert", V.efunc (V.value **-> V.default "" V.string **->> V.unit) (fun c msg -> match c with | V.LuaValueBase.Nil -> I.error ("assertion failed: " ^ msg) | _ -> ()) ; "error", V.efunc (V.string **->> V.unit) I.error ; "setglobal", V.efunc (V.value **-> V.value **->> V.unit) (fun k v -> V.Table.bind g.V.globals ~key:k ~data:v) ; "getglobal", V.efunc (V.value **->> V.value) (I.getglobal g) ; "setfallback", V.efunc (V.string **-> V.value **->> V.value) (I.setfallback g) ] include I let mk () = let g, init = I.pre_mk () in I.register_globals (luabaselib g) g; init (fun s -> ignore (dostring g s)); g end
b85339c3be0bce720830490bb88583947cd3c3b63cdfc0443573bddc083ecc5f
clojupyter/clojupyter
history_test.clj
(ns clojupyter.kernel.history-test (:require [clojupyter.kernel.history :as sut] [clojupyter.test-shared :as ts] [midje.sweet :refer [against-background after around before fact facts =>]] [clojure.java.io :as io]) (:import (java.nio.file Files Paths))) (def test-db (str (Files/createTempDirectory "test_data_" (into-array java.nio.file.attribute.FileAttribute [])) "/test.db")) (against-background [(around :facts (let [db (sut/init-history test-db)] ?form)) (after :facts (.delete (io/file test-db)))] (facts "history functions should works" (fact "history-init should create db file" (.exists (io/file test-db)) => true) (fact "session should start from 1" (let [session (sut/start-history-session db)] (:session-id session) ) => 1) (fact "session should increase from 1" (let [session_1 (sut/start-history-session db) session_2 (sut/start-history-session db) session_3 (sut/start-history-session db)] [(:session-id session_1) (:session-id session_2) (:session-id session_3)] ) => [1 2 3]) (fact "session should record command history" (let [session (sut/start-history-session db)] (-> session (sut/add-history 1 "t1") (sut/add-history 2 "t2")) (sut/get-history session) ) => [{:session 1 :line 1 :source "t1"} {:session 1 :line 2 :source "t2"}]) (fact "end ession should truncate history to max size" (let [session (sut/start-history-session db)] (-> session (sut/add-history 1 "t1") (sut/add-history 2 "t2") (sut/add-history 3 "t3") (sut/add-history 4 "t4") (sut/end-history-session 2) ) (sut/get-history session) ) => [{:session 1 :line 3 :source "t3"} {:session 1 :line 4 :source "t4"}]) ))
null
https://raw.githubusercontent.com/clojupyter/clojupyter/b54b30b5efa115937b7a85e708a7402bd9efa0ab/test/clojupyter/kernel/history_test.clj
clojure
(ns clojupyter.kernel.history-test (:require [clojupyter.kernel.history :as sut] [clojupyter.test-shared :as ts] [midje.sweet :refer [against-background after around before fact facts =>]] [clojure.java.io :as io]) (:import (java.nio.file Files Paths))) (def test-db (str (Files/createTempDirectory "test_data_" (into-array java.nio.file.attribute.FileAttribute [])) "/test.db")) (against-background [(around :facts (let [db (sut/init-history test-db)] ?form)) (after :facts (.delete (io/file test-db)))] (facts "history functions should works" (fact "history-init should create db file" (.exists (io/file test-db)) => true) (fact "session should start from 1" (let [session (sut/start-history-session db)] (:session-id session) ) => 1) (fact "session should increase from 1" (let [session_1 (sut/start-history-session db) session_2 (sut/start-history-session db) session_3 (sut/start-history-session db)] [(:session-id session_1) (:session-id session_2) (:session-id session_3)] ) => [1 2 3]) (fact "session should record command history" (let [session (sut/start-history-session db)] (-> session (sut/add-history 1 "t1") (sut/add-history 2 "t2")) (sut/get-history session) ) => [{:session 1 :line 1 :source "t1"} {:session 1 :line 2 :source "t2"}]) (fact "end ession should truncate history to max size" (let [session (sut/start-history-session db)] (-> session (sut/add-history 1 "t1") (sut/add-history 2 "t2") (sut/add-history 3 "t3") (sut/add-history 4 "t4") (sut/end-history-session 2) ) (sut/get-history session) ) => [{:session 1 :line 3 :source "t3"} {:session 1 :line 4 :source "t4"}]) ))
5ab581100bd7a69f90263620ee5217fb668905f1cc82a484d990c918afb9ff68
cedlemo/OCaml-GI-ctypes-bindings-generator
Tool_item_group.mli
open Ctypes type t val t_typ : t typ val create : string -> Widget.t ptr val get_collapsed : t -> bool val get_drop_item : t -> int32 -> int32 -> Tool_item.t ptr val get_ellipsize : t -> Ellipsize_mode.t val get_header_relief : t -> Relief_style.t val get_item_position : t -> Tool_item.t ptr -> int32 val get_label : t -> string option val get_label_widget : t -> Widget.t ptr val get_n_items : t -> Unsigned.uint32 val get_nth_item : t -> Unsigned.uint32 -> Tool_item.t ptr val insert : t -> Tool_item.t ptr -> int32 -> unit val set_collapsed : t -> bool -> unit val set_ellipsize : t -> Ellipsize_mode.t -> unit val set_header_relief : t -> Relief_style.t -> unit val set_item_position : t -> Tool_item.t ptr -> int32 -> unit val set_label : t -> string -> unit val set_label_widget : t -> Widget.t ptr -> unit
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Tool_item_group.mli
ocaml
open Ctypes type t val t_typ : t typ val create : string -> Widget.t ptr val get_collapsed : t -> bool val get_drop_item : t -> int32 -> int32 -> Tool_item.t ptr val get_ellipsize : t -> Ellipsize_mode.t val get_header_relief : t -> Relief_style.t val get_item_position : t -> Tool_item.t ptr -> int32 val get_label : t -> string option val get_label_widget : t -> Widget.t ptr val get_n_items : t -> Unsigned.uint32 val get_nth_item : t -> Unsigned.uint32 -> Tool_item.t ptr val insert : t -> Tool_item.t ptr -> int32 -> unit val set_collapsed : t -> bool -> unit val set_ellipsize : t -> Ellipsize_mode.t -> unit val set_header_relief : t -> Relief_style.t -> unit val set_item_position : t -> Tool_item.t ptr -> int32 -> unit val set_label : t -> string -> unit val set_label_widget : t -> Widget.t ptr -> unit
ea3e458952264519203916df1c6656828f7cc99f637f9425d32f74adbca6549b
Clojure2D/clojure2d
color_test.clj
(ns clojure2d.color-test (:require [clojure.test :refer [deftest is are]] [clojure2d.color :as c] [clojure2d.color.blend :as b] [fastmath.core :as m] [fastmath.random :as r] [fastmath.vector :as v])) ;; color protocol (def cv3 (v/vec3 245.0 245.0 220.0)) (def cv4 (v/vec4 245.0 245.0 220.0 255.0)) (def cc (java.awt.Color. 245 245 220)) ;; => "#f5f5dc" (deftest type-conversion-test = > 243.19577500000003 (is (m/approx-eq 243.195 (c/luma cv3))) (is (m/approx-eq 243.195 (c/luma cv4))) (is (m/approx-eq 243.195 (c/luma cc))) (is (= cv4 (c/to-color :beige))) (is (= cv4 (c/to-color cv3))) (is (= cv4 (c/to-color cc))) (is (= cc (c/to-awt-color :beige))) (is (= cc (c/to-awt-color cv3))) (is (= cc (c/to-awt-color cv4))) (is (= cv4 (c/to-color "#f5f5dc"))) (is (= cv4 (c/to-color "f5f5dc"))) (is (= cv4 (c/to-color "F5F5DC"))) (is (= cv4 (c/to-color "#f5f5dcff"))) (is (= cv4 (c/to-color 0xf5f5dc))) (is (= cv4 (c/to-color 0xfff5f5dc)))) (deftest alpha-test (is (= (c/color 245.0 245.0 220.0 100.0) (c/set-alpha cv4 100))) (is (= (c/color 245.0 245.0 220.0 100.0) (c/to-color (c/set-awt-alpha cc 100))))) (deftest make-color-test (is (= cc (c/awt-color cv3 255.0))) (is (= cc (c/awt-color 245.0 245.0 220.0))) (is (= cc (c/awt-color 245.0 245.0 220.0 255.0))) (is (= cv4 (c/color cv3 255))) (is (= cv4 (c/color 245.0 245.0 220.0))) (is (= cv4 (c/color 245.0 245.0 220.0 255.0)))) (deftest hue-test (is (= 60.0 (c/hue (c/color :beige))))) ;; (deftest numerical-operations (is (= (v/vec4 0.0 250.2 255.0 200.4) (c/clamp (v/vec4 -1.1 250.2 260.3 200.4)))) (is (= (v/vec4 0.0 250.0 255.0 200.0) (c/lclamp (v/vec4 -1.1 250.2 260.3 200.4)))) (is (= (v/vec4 255.0 255.0 255.0 255.0) (c/scale [1 1 1] 255.0))) (is (= (v/vec4 0.5 0.5 0.5 255.0) (c/scale [127.5 127.5 127.5] (/ 255.0))))) ;; test blends (deftest blend-test (is (== 255.0 (b/normal 100.0 255.0))) (is (== 0.0 (b/normal 200.0 0.0))) (is (== 255.0 (b/normal 0.0 255.0))) (is (== 0.0 (b/normal 1.0 0.0))) (is (== 255.0 (b/add 100.0 200.0))) (is (== 150.0 (b/add 50.0 100.0))) (is (== 255.0 (b/add 0.0 255.0))) (is (== 255.0 (b/add 255.0 0.0))) (is (== (mod 300 256.0) (b/madd 100.0 200.0))) (is (== 150.0 (b/madd 50.0 100.0))) (is (== 255.0 (b/madd 0.0 255.0))) (is (== 255.0 (b/madd 255.0 0.0))) (is (== 0.0 (b/subtract 100.0 200.0))) (is (== 50 (b/subtract 100.0 50.0))) (is (== 0.0 (b/subtract 0.0 255.0))) (is (== 255.0 (b/subtract 255.0 0.0))) (is (== (mod -100 256.0) (b/msubtract 100.0 200.0))) (is (== 50 (b/msubtract 100.0 50.0))) (is (== 1.0 (b/msubtract 0.0 255.0))) (is (== 255.0 (b/msubtract 255.0 0.0)))) ;; test color converters (def random-color-sequence (->> (concat (c/named-colors-list) (repeatedly 30000 #(v/generate-vec4 (fn [] (r/irand 256)))) (repeatedly 30000 #(v/generate-vec3 (fn [] (r/irand 256)))) (repeatedly 40000 r/irand) (repeatedly 40000 #(v/fmap (c/to-color (c/random-color)) (fn [^double v] (m/floor v))))) (mapv c/to-color))) (defn compare-colors [[to from] colors] (filter identity (map (fn [c] (not= c (v/fmap (from (to c)) #(m/round %)))) colors))) (defn compare-colors- [[to from] colors] (filter #(not= (first %) (second %)) (map (fn [c] [c (v/fmap (from (to c)) #(m/round %))]) colors))) (defn colorspace-validity "Test if colorspace conversion works properly" [cs cs-tab] (empty? (compare-colors (cs-tab cs) random-color-sequence))) (defmacro build-colorspace-reversibility-test [cs-tab] (let [cs-sym (symbol (str "reversibility-test-" (name cs-tab)))] `(deftest ~cs-sym ~@(for [cs (remove #{:Gray} (keys c/colorspaces))] `(is (colorspace-validity ~cs ~cs-tab)))))) (build-colorspace-reversibility-test c/colorspaces) (build-colorspace-reversibility-test c/colorspaces*) ;; color conversion (deftest conversion-examples (let [reference-color (c/from-XYZ [20.654008, 12.197225, 5.136952])] ;; #colour-models-colour-models (are [f res] (= res (v/approx (f reference-color))) c/to-Yxy (v/vec4 12.2 0.54 0.32 255.0) c/to-LAB (v/vec4 41.53 52.64 26.92 255.0) c/to-LUV (v/vec4 41.53 96.83 17.74 255.0) c/to-HunterLAB (v/vec4 34.92 47.05 14.36 255.0) c/to-IPT (v/vec4 0.38 0.38 0.19 255.0) c/to-IgPgTg (v/vec4 0.42 0.19 0.11 255.0) c/to-Oklab (v/vec4 0.52 0.15 0.06 255.0) c/to-OSA (v/vec4 -3.0 3.0 -9.67 255.0) c/to-UCS (v/vec4 0.14 0.12 0.11 255.0) c/to-UVW (v/vec4 94.55 11.56 40.55 255.0)) colorio , colour has different XYZ scaling (are [f res] (= res (v/approx (f reference-color) 4)) c/to-JAB (v/vec4 0.0747 0.0707 0.0472 255.0)) array ( [ 0.99603944 , 0.93246304 , 0.45620519 ] ) ( * 0.99603944 360.0 ) ; ; = > 358.5741984 (is (= (v/vec4 358.57 0.93 0.46 255.0) (-> [0.45620519, 0.03081071, 0.04091952] (c/scale 255.0) (c/to-HSV) (v/approx)))) (is (= (v/vec4 103 0 51 255) (c/lclamp (c/from-YCbCr* [36 136 175])))) (is (= (v/vec4 0.5625 -0.0625 0.125 255.0) (-> [0.75 0.5 0.5] (c/scale 255.0) (c/to-YCgCo) (c/scale (/ 255.0))))))) ;; chroma.js tests (deftest chroma-example (is "#ff6d93" (-> :pink (c/darken) (c/saturate 2.0) (c/format-hex)))) (deftest chroma-api (is "#ff69b4" (c/format-hex :hotpink)) (is "#ff3399" (c/format-hex "#ff3399")) (is "#ff3399" (c/format-hex "F39")) (is "#ff3399" (c/format-hex 0xff3399)) (is "#ff3399" (c/format-hex (c/color 0xff 0x33 0x99))) (is "#ff3399" (c/format-hex (c/color 255.0 51.0 153.0))) (is "#ff3399" (c/format-hex [255 51 153])) (is "#ff3399" (c/format-hex (c/from-HSL [330.0 1.0 0.6]))) (is "#80ff80" (c/format-hex (c/from-HSL [120 1 0.75]))) (is "#85d4d5" (c/format-hex (c/from-LCH [80 25 200]))) (is "#aad28c" (c/format-hex (c/from-LCH [80 40 130]))) (is "#b400b4" (c/format-hex (c/mix :red :blue 0.5))) (is "#dd0080" (c/format-hex (c/mix :red :blue 0.25))) (is "#8000dd" (c/format-hex (c/mix :red :blue 0.75))) (is "#800080" (c/format-hex (c/lerp :red :blue))) (is "#00ff00" (c/format-hex (c/lerp :red :blue :HSL 0.5))) ;; different than chroma, shortest path (is "#ca0088" (c/format-hex (c/lerp :red :blue :LAB 0.5)))) (def average-colors ["#ddd", :yellow, :red, :teal]) (deftest chroma-average (is "#b79757" (c/format-hex (c/average average-colors))) (is "#d3a96a" (c/format-hex (c/average average-colors :LAB)))) (deftest chroma-valid (is (c/valid-color? :red)) (is (not (c/valid-color? :bread))) (is (c/valid-color? "#F0000D")) (is (not (c/valid-color? "#FOOOOD")))) (deftest chroma-blend (is "#47af22" (c/format-hex (b/blend-colors b/multiply 0x4cbbfc 0xeeee22))) (is "#4cbb22" (c/format-hex (b/blend-colors b/darken 0x4cbbfc 0xeeee22))) (is "#eeeefc" (c/format-hex (b/blend-colors b/lighten 0x4cbbfc 0xeeee22)))) (deftest chroma-contrast (is 1.72 (m/approx (c/contrast-ratio :pink :hotpink))) (is 6.12 (m/approx (c/contrast-ratio :pink :purple)))) (deftest chroma-distance (is 96.95 (m/approx (c/delta-E* "fff" "ff0"))) (is 122.16 (m/approx (c/delta-E* "fff" "f0f"))) (is 255.0 (m/approx (c/delta-E*-euclidean "fff" "ff0" :RGB))) (is 255.0 (m/approx (c/delta-E*-euclidean "fff" "f0f" :RGB))) (is 1.64 (m/approx (c/delta-E*-CMC 0xededee 0xedeeed))) (is 3.15 (m/approx (c/delta-E*-CMC 0xececee 0xeceeec))) (is 7.36 (m/approx (c/delta-E*-CMC 0xe9e9ee 0xe9eee9))) (is 14.85 (m/approx (c/delta-E*-CMC 0xe4e4ee 0xe4eee4))) (is 21.33 (m/approx (c/delta-E*-CMC 0xe0e0ee 0xe0eee0)))) (deftest chroma-color (is "#ff000080" (c/format-hex (c/set-alpha :red 128))) (is 128.0 (c/alpha (c/color 255.0 0.0 0.0 128.0))) (is "#c93384" (c/format-hex (c/darken :hotpink))) (is "#930058" (c/format-hex (c/darken :hotpink 2.0))) (is "#74003f" (c/format-hex (c/darken :hotpink 2.6))) (is "#ff9ce6" (c/format-hex (c/brighten :hotpink))) (is "#ffd1ff" (c/format-hex (c/brighten :hotpink 2.0))) (is "#ffffff" (c/format-hex (c/brighten :hotpink 3.0))) (is "#4b83ae" (c/format-hex (c/saturate :slategray))) (is "#0087cd" (c/format-hex (c/saturate :slategray 2.0))) (is "#008bec" (c/format-hex (c/saturate :slategray 3.0))) (is "#e77dea" (c/format-hex (c/desaturate :hotpink))) (is "#cd8ca8" (c/format-hex (c/desaturate :hotpink 2.0))) (is "#b299a3" (c/format-hex (c/desaturate :hotpink 3.0))) ;; differs a little bit from original, due to rounding (is "#a10000" (c/format-hex (c/modulate :orangered :LAB 0 0.5))) (is "#63c56c" (c/format-hex (c/modulate :darkseagreen :LCH 1 2.0))) (is "#eb8787" (c/format-hex (c/set-channel :skyblue :HSL 0 0.0))) (is "#ce8ca9" (c/format-hex (c/set-channel :hotpink :LCH 1 30.0))) (is 57.57 (m/approx (c/get-channel :orangered :LAB 0))) (is 0.5 (m/approx (c/get-channel :orangered :HSL 2))) (is 69.0 (m/approx (c/get-channel :orangered 1))) (is 1.0 (/ (c/relative-luma :white) 255.0)) (is 0.81 (m/approx (/ (c/relative-luma :aquamarine) 255.0))) (is 0.35 (m/approx (/ (c/relative-luma :hotpink) 255.0))) (is 0.07 (m/approx (/ (c/relative-luma :darkslateblue) 255.0))) (is 0.0 (/ (c/relative-luma :black) 255.0))) ;; test iq palette generator test paletton generator ;; test nearest color distance
null
https://raw.githubusercontent.com/Clojure2D/clojure2d/608f646ff57d9c1d4146a246ba64dd1c424bf7cb/test/clojure2d/color_test.clj
clojure
color protocol => "#f5f5dc" test blends test color converters color conversion #colour-models-colour-models ; = > 358.5741984 chroma.js tests different than chroma, shortest path differs a little bit from original, due to rounding test iq palette generator test nearest color distance
(ns clojure2d.color-test (:require [clojure.test :refer [deftest is are]] [clojure2d.color :as c] [clojure2d.color.blend :as b] [fastmath.core :as m] [fastmath.random :as r] [fastmath.vector :as v])) (def cv3 (v/vec3 245.0 245.0 220.0)) (def cv4 (v/vec4 245.0 245.0 220.0 255.0)) (def cc (java.awt.Color. 245 245 220)) (deftest type-conversion-test = > 243.19577500000003 (is (m/approx-eq 243.195 (c/luma cv3))) (is (m/approx-eq 243.195 (c/luma cv4))) (is (m/approx-eq 243.195 (c/luma cc))) (is (= cv4 (c/to-color :beige))) (is (= cv4 (c/to-color cv3))) (is (= cv4 (c/to-color cc))) (is (= cc (c/to-awt-color :beige))) (is (= cc (c/to-awt-color cv3))) (is (= cc (c/to-awt-color cv4))) (is (= cv4 (c/to-color "#f5f5dc"))) (is (= cv4 (c/to-color "f5f5dc"))) (is (= cv4 (c/to-color "F5F5DC"))) (is (= cv4 (c/to-color "#f5f5dcff"))) (is (= cv4 (c/to-color 0xf5f5dc))) (is (= cv4 (c/to-color 0xfff5f5dc)))) (deftest alpha-test (is (= (c/color 245.0 245.0 220.0 100.0) (c/set-alpha cv4 100))) (is (= (c/color 245.0 245.0 220.0 100.0) (c/to-color (c/set-awt-alpha cc 100))))) (deftest make-color-test (is (= cc (c/awt-color cv3 255.0))) (is (= cc (c/awt-color 245.0 245.0 220.0))) (is (= cc (c/awt-color 245.0 245.0 220.0 255.0))) (is (= cv4 (c/color cv3 255))) (is (= cv4 (c/color 245.0 245.0 220.0))) (is (= cv4 (c/color 245.0 245.0 220.0 255.0)))) (deftest hue-test (is (= 60.0 (c/hue (c/color :beige))))) (deftest numerical-operations (is (= (v/vec4 0.0 250.2 255.0 200.4) (c/clamp (v/vec4 -1.1 250.2 260.3 200.4)))) (is (= (v/vec4 0.0 250.0 255.0 200.0) (c/lclamp (v/vec4 -1.1 250.2 260.3 200.4)))) (is (= (v/vec4 255.0 255.0 255.0 255.0) (c/scale [1 1 1] 255.0))) (is (= (v/vec4 0.5 0.5 0.5 255.0) (c/scale [127.5 127.5 127.5] (/ 255.0))))) (deftest blend-test (is (== 255.0 (b/normal 100.0 255.0))) (is (== 0.0 (b/normal 200.0 0.0))) (is (== 255.0 (b/normal 0.0 255.0))) (is (== 0.0 (b/normal 1.0 0.0))) (is (== 255.0 (b/add 100.0 200.0))) (is (== 150.0 (b/add 50.0 100.0))) (is (== 255.0 (b/add 0.0 255.0))) (is (== 255.0 (b/add 255.0 0.0))) (is (== (mod 300 256.0) (b/madd 100.0 200.0))) (is (== 150.0 (b/madd 50.0 100.0))) (is (== 255.0 (b/madd 0.0 255.0))) (is (== 255.0 (b/madd 255.0 0.0))) (is (== 0.0 (b/subtract 100.0 200.0))) (is (== 50 (b/subtract 100.0 50.0))) (is (== 0.0 (b/subtract 0.0 255.0))) (is (== 255.0 (b/subtract 255.0 0.0))) (is (== (mod -100 256.0) (b/msubtract 100.0 200.0))) (is (== 50 (b/msubtract 100.0 50.0))) (is (== 1.0 (b/msubtract 0.0 255.0))) (is (== 255.0 (b/msubtract 255.0 0.0)))) (def random-color-sequence (->> (concat (c/named-colors-list) (repeatedly 30000 #(v/generate-vec4 (fn [] (r/irand 256)))) (repeatedly 30000 #(v/generate-vec3 (fn [] (r/irand 256)))) (repeatedly 40000 r/irand) (repeatedly 40000 #(v/fmap (c/to-color (c/random-color)) (fn [^double v] (m/floor v))))) (mapv c/to-color))) (defn compare-colors [[to from] colors] (filter identity (map (fn [c] (not= c (v/fmap (from (to c)) #(m/round %)))) colors))) (defn compare-colors- [[to from] colors] (filter #(not= (first %) (second %)) (map (fn [c] [c (v/fmap (from (to c)) #(m/round %))]) colors))) (defn colorspace-validity "Test if colorspace conversion works properly" [cs cs-tab] (empty? (compare-colors (cs-tab cs) random-color-sequence))) (defmacro build-colorspace-reversibility-test [cs-tab] (let [cs-sym (symbol (str "reversibility-test-" (name cs-tab)))] `(deftest ~cs-sym ~@(for [cs (remove #{:Gray} (keys c/colorspaces))] `(is (colorspace-validity ~cs ~cs-tab)))))) (build-colorspace-reversibility-test c/colorspaces) (build-colorspace-reversibility-test c/colorspaces*) (deftest conversion-examples (let [reference-color (c/from-XYZ [20.654008, 12.197225, 5.136952])] (are [f res] (= res (v/approx (f reference-color))) c/to-Yxy (v/vec4 12.2 0.54 0.32 255.0) c/to-LAB (v/vec4 41.53 52.64 26.92 255.0) c/to-LUV (v/vec4 41.53 96.83 17.74 255.0) c/to-HunterLAB (v/vec4 34.92 47.05 14.36 255.0) c/to-IPT (v/vec4 0.38 0.38 0.19 255.0) c/to-IgPgTg (v/vec4 0.42 0.19 0.11 255.0) c/to-Oklab (v/vec4 0.52 0.15 0.06 255.0) c/to-OSA (v/vec4 -3.0 3.0 -9.67 255.0) c/to-UCS (v/vec4 0.14 0.12 0.11 255.0) c/to-UVW (v/vec4 94.55 11.56 40.55 255.0)) colorio , colour has different XYZ scaling (are [f res] (= res (v/approx (f reference-color) 4)) c/to-JAB (v/vec4 0.0747 0.0707 0.0472 255.0)) array ( [ 0.99603944 , 0.93246304 , 0.45620519 ] ) (is (= (v/vec4 358.57 0.93 0.46 255.0) (-> [0.45620519, 0.03081071, 0.04091952] (c/scale 255.0) (c/to-HSV) (v/approx)))) (is (= (v/vec4 103 0 51 255) (c/lclamp (c/from-YCbCr* [36 136 175])))) (is (= (v/vec4 0.5625 -0.0625 0.125 255.0) (-> [0.75 0.5 0.5] (c/scale 255.0) (c/to-YCgCo) (c/scale (/ 255.0))))))) (deftest chroma-example (is "#ff6d93" (-> :pink (c/darken) (c/saturate 2.0) (c/format-hex)))) (deftest chroma-api (is "#ff69b4" (c/format-hex :hotpink)) (is "#ff3399" (c/format-hex "#ff3399")) (is "#ff3399" (c/format-hex "F39")) (is "#ff3399" (c/format-hex 0xff3399)) (is "#ff3399" (c/format-hex (c/color 0xff 0x33 0x99))) (is "#ff3399" (c/format-hex (c/color 255.0 51.0 153.0))) (is "#ff3399" (c/format-hex [255 51 153])) (is "#ff3399" (c/format-hex (c/from-HSL [330.0 1.0 0.6]))) (is "#80ff80" (c/format-hex (c/from-HSL [120 1 0.75]))) (is "#85d4d5" (c/format-hex (c/from-LCH [80 25 200]))) (is "#aad28c" (c/format-hex (c/from-LCH [80 40 130]))) (is "#b400b4" (c/format-hex (c/mix :red :blue 0.5))) (is "#dd0080" (c/format-hex (c/mix :red :blue 0.25))) (is "#8000dd" (c/format-hex (c/mix :red :blue 0.75))) (is "#800080" (c/format-hex (c/lerp :red :blue))) (is "#ca0088" (c/format-hex (c/lerp :red :blue :LAB 0.5)))) (def average-colors ["#ddd", :yellow, :red, :teal]) (deftest chroma-average (is "#b79757" (c/format-hex (c/average average-colors))) (is "#d3a96a" (c/format-hex (c/average average-colors :LAB)))) (deftest chroma-valid (is (c/valid-color? :red)) (is (not (c/valid-color? :bread))) (is (c/valid-color? "#F0000D")) (is (not (c/valid-color? "#FOOOOD")))) (deftest chroma-blend (is "#47af22" (c/format-hex (b/blend-colors b/multiply 0x4cbbfc 0xeeee22))) (is "#4cbb22" (c/format-hex (b/blend-colors b/darken 0x4cbbfc 0xeeee22))) (is "#eeeefc" (c/format-hex (b/blend-colors b/lighten 0x4cbbfc 0xeeee22)))) (deftest chroma-contrast (is 1.72 (m/approx (c/contrast-ratio :pink :hotpink))) (is 6.12 (m/approx (c/contrast-ratio :pink :purple)))) (deftest chroma-distance (is 96.95 (m/approx (c/delta-E* "fff" "ff0"))) (is 122.16 (m/approx (c/delta-E* "fff" "f0f"))) (is 255.0 (m/approx (c/delta-E*-euclidean "fff" "ff0" :RGB))) (is 255.0 (m/approx (c/delta-E*-euclidean "fff" "f0f" :RGB))) (is 1.64 (m/approx (c/delta-E*-CMC 0xededee 0xedeeed))) (is 3.15 (m/approx (c/delta-E*-CMC 0xececee 0xeceeec))) (is 7.36 (m/approx (c/delta-E*-CMC 0xe9e9ee 0xe9eee9))) (is 14.85 (m/approx (c/delta-E*-CMC 0xe4e4ee 0xe4eee4))) (is 21.33 (m/approx (c/delta-E*-CMC 0xe0e0ee 0xe0eee0)))) (deftest chroma-color (is "#ff000080" (c/format-hex (c/set-alpha :red 128))) (is 128.0 (c/alpha (c/color 255.0 0.0 0.0 128.0))) (is "#c93384" (c/format-hex (c/darken :hotpink))) (is "#930058" (c/format-hex (c/darken :hotpink 2.0))) (is "#74003f" (c/format-hex (c/darken :hotpink 2.6))) (is "#ff9ce6" (c/format-hex (c/brighten :hotpink))) (is "#ffd1ff" (c/format-hex (c/brighten :hotpink 2.0))) (is "#ffffff" (c/format-hex (c/brighten :hotpink 3.0))) (is "#4b83ae" (c/format-hex (c/saturate :slategray))) (is "#0087cd" (c/format-hex (c/saturate :slategray 2.0))) (is "#008bec" (c/format-hex (c/saturate :slategray 3.0))) (is "#e77dea" (c/format-hex (c/desaturate :hotpink))) (is "#cd8ca8" (c/format-hex (c/desaturate :hotpink 2.0))) (is "#a10000" (c/format-hex (c/modulate :orangered :LAB 0 0.5))) (is "#63c56c" (c/format-hex (c/modulate :darkseagreen :LCH 1 2.0))) (is "#eb8787" (c/format-hex (c/set-channel :skyblue :HSL 0 0.0))) (is "#ce8ca9" (c/format-hex (c/set-channel :hotpink :LCH 1 30.0))) (is 57.57 (m/approx (c/get-channel :orangered :LAB 0))) (is 0.5 (m/approx (c/get-channel :orangered :HSL 2))) (is 69.0 (m/approx (c/get-channel :orangered 1))) (is 1.0 (/ (c/relative-luma :white) 255.0)) (is 0.81 (m/approx (/ (c/relative-luma :aquamarine) 255.0))) (is 0.35 (m/approx (/ (c/relative-luma :hotpink) 255.0))) (is 0.07 (m/approx (/ (c/relative-luma :darkslateblue) 255.0))) (is 0.0 (/ (c/relative-luma :black) 255.0))) test paletton generator
06b226fe663da70e22aac5861882d864b279a2428638fe203893e63450037a69
S8A/htdp-exercises
ex060.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex060) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) (define RADIUS 15) (define MARGIN (/ RADIUS 3)) (define HEIGHT (* 3 RADIUS)) (define WIDTH (* 2.5 HEIGHT)) (define FRAME (overlay (rectangle WIDTH HEIGHT "outline" "blue") (rectangle WIDTH HEIGHT "solid" "black"))) (define SPACER (rectangle MARGIN HEIGHT "solid" "transparent")) An N - TrafficLight is one of : ; – 0 interpretation the traffic light shows red – 1 interpretation the traffic light shows green – 2 interpretation the traffic light shows yellow ; N-TrafficLight -> N-TrafficLight ; yields the next state, given current state cs (define (tl-next-numeric cs) (modulo (+ cs 1) 3)) (check-expect (tl-next-numeric 0) 1) (check-expect (tl-next-numeric 1) 2) (check-expect (tl-next-numeric 2) 0) ; Q: Does the tl-next function convey its intention more clearly ; than the tl-next-numeric function? ; A: Yes, because using numbers is not as intuitive. ; N-TrafficLight Boolean -> Image ; draws a lightbulb of the given color (define (light-numeric color on?) (circle RADIUS (if on? "solid" "outline") (cond [(= color 0) "red"] [(= color 1) "green"] [(= color 2) "yellow"]))) (check-expect (light-numeric 0 #false) (circle RADIUS "outline" "red")) (check-expect (light-numeric 2 #true) (circle RADIUS "solid" "yellow")) (check-expect (light-numeric 1 #false) (circle RADIUS "outline" "green")) ; N-TrafficLight -> Image ; renders the current state cs as an image (define (tl-render-numeric cs) (overlay (beside SPACER (light-numeric 0 (= cs 0)) SPACER (light-numeric 2 (= cs 2)) SPACER (light-numeric 1 (= cs 1)) SPACER) FRAME)) (check-expect (tl-render-numeric 0) (overlay (beside SPACER (light-numeric 0 #t) SPACER (light-numeric 2 #f) SPACER (light-numeric 1 #f) SPACER) FRAME)) (check-expect (tl-render-numeric 2) (overlay (beside SPACER (light-numeric 0 #f) SPACER (light-numeric 2 #t) SPACER (light-numeric 1 #f) SPACER) FRAME)) (check-expect (tl-render-numeric 1) (overlay (beside SPACER (light-numeric 0 #f) SPACER (light-numeric 2 #f) SPACER (light-numeric 1 #t) SPACER) FRAME)) ; N-TrafficLight -> N-TrafficLight simulates a clock - based American traffic light (define (numeric-traffic-light-simulation initial-state) (big-bang initial-state [to-draw tl-render-numeric] [on-tick tl-next-numeric 1]))
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex060.rkt
racket
about the language level of this file in a form that our tools can easily process. – 0 interpretation the traffic light shows red N-TrafficLight -> N-TrafficLight yields the next state, given current state cs Q: Does the tl-next function convey its intention more clearly than the tl-next-numeric function? A: Yes, because using numbers is not as intuitive. N-TrafficLight Boolean -> Image draws a lightbulb of the given color N-TrafficLight -> Image renders the current state cs as an image N-TrafficLight -> N-TrafficLight
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex060) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) (define RADIUS 15) (define MARGIN (/ RADIUS 3)) (define HEIGHT (* 3 RADIUS)) (define WIDTH (* 2.5 HEIGHT)) (define FRAME (overlay (rectangle WIDTH HEIGHT "outline" "blue") (rectangle WIDTH HEIGHT "solid" "black"))) (define SPACER (rectangle MARGIN HEIGHT "solid" "transparent")) An N - TrafficLight is one of : – 1 interpretation the traffic light shows green – 2 interpretation the traffic light shows yellow (define (tl-next-numeric cs) (modulo (+ cs 1) 3)) (check-expect (tl-next-numeric 0) 1) (check-expect (tl-next-numeric 1) 2) (check-expect (tl-next-numeric 2) 0) (define (light-numeric color on?) (circle RADIUS (if on? "solid" "outline") (cond [(= color 0) "red"] [(= color 1) "green"] [(= color 2) "yellow"]))) (check-expect (light-numeric 0 #false) (circle RADIUS "outline" "red")) (check-expect (light-numeric 2 #true) (circle RADIUS "solid" "yellow")) (check-expect (light-numeric 1 #false) (circle RADIUS "outline" "green")) (define (tl-render-numeric cs) (overlay (beside SPACER (light-numeric 0 (= cs 0)) SPACER (light-numeric 2 (= cs 2)) SPACER (light-numeric 1 (= cs 1)) SPACER) FRAME)) (check-expect (tl-render-numeric 0) (overlay (beside SPACER (light-numeric 0 #t) SPACER (light-numeric 2 #f) SPACER (light-numeric 1 #f) SPACER) FRAME)) (check-expect (tl-render-numeric 2) (overlay (beside SPACER (light-numeric 0 #f) SPACER (light-numeric 2 #t) SPACER (light-numeric 1 #f) SPACER) FRAME)) (check-expect (tl-render-numeric 1) (overlay (beside SPACER (light-numeric 0 #f) SPACER (light-numeric 2 #f) SPACER (light-numeric 1 #t) SPACER) FRAME)) simulates a clock - based American traffic light (define (numeric-traffic-light-simulation initial-state) (big-bang initial-state [to-draw tl-render-numeric] [on-tick tl-next-numeric 1]))
505a5cc64b2f7f13344003641f8631f483a1224d5e2d0edd2cc4b74507cc8126
manuel-serrano/bigloo
tools.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / bdb / bdb / Gdb / tools.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : We d Jul 28 15:41:13 1999 * / * Last change : We d Aug 9 17:17:05 2000 ( serrano ) * / ;* ------------------------------------------------------------- */ * General parsing tools . This module implements small GDB * / ;* facilities to gather small informations about expressions. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module gdb_tools (import tools_tools) (export (gdb-typeof::bstring ::bstring) (gdb-current-scope)) (import gdb_invoke)) ;*---------------------------------------------------------------------*/ ;* gdb-typeof ... */ ;* ------------------------------------------------------------- */ * Ask for the type of a variable . Returns it as a string . * / ;*---------------------------------------------------------------------*/ (define (gdb-typeof::bstring var::bstring) (let* ((cmd (string-append "whatis " var)) (res (gdb-server->string cmd))) ;; whatis format is <TYPE> = <TYPE VALUE>. to fetch the type ;; value we skip everything until the = characters (string-from res #\= 2))) ;*---------------------------------------------------------------------*/ ;* gdb-current-scope ... */ ;* ------------------------------------------------------------- */ ;* Returns the current scope (this function does do any parsing, */ ;* it returns a plain string as produced by gdb). */ ;*---------------------------------------------------------------------*/ (define (gdb-current-scope) ;; we have to compute the current line number (let ((line (gdb-server->string "info line"))) (if (substring=? "Line " line 5) (let* ((lnum (string-until-at line 5 #\space 0)) (cmd (string-append "info scope " lnum))) (if (= (string->integer lnum) 0) ;; there is no line for that file #f ;; then we can request an "info scope" (gdb-server->string cmd))) #f)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/bdb/bdb/Gdb/tools.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * facilities to gather small informations about expressions. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * gdb-typeof ... */ * ------------------------------------------------------------- */ *---------------------------------------------------------------------*/ whatis format is <TYPE> = <TYPE VALUE>. to fetch the type value we skip everything until the = characters *---------------------------------------------------------------------*/ * gdb-current-scope ... */ * ------------------------------------------------------------- */ * Returns the current scope (this function does do any parsing, */ * it returns a plain string as produced by gdb). */ *---------------------------------------------------------------------*/ we have to compute the current line number there is no line for that file then we can request an "info scope"
* serrano / prgm / project / bigloo / bdb / bdb / Gdb / tools.scm * / * Author : * / * Creation : We d Jul 28 15:41:13 1999 * / * Last change : We d Aug 9 17:17:05 2000 ( serrano ) * / * General parsing tools . This module implements small GDB * / (module gdb_tools (import tools_tools) (export (gdb-typeof::bstring ::bstring) (gdb-current-scope)) (import gdb_invoke)) * Ask for the type of a variable . Returns it as a string . * / (define (gdb-typeof::bstring var::bstring) (let* ((cmd (string-append "whatis " var)) (res (gdb-server->string cmd))) (string-from res #\= 2))) (define (gdb-current-scope) (let ((line (gdb-server->string "info line"))) (if (substring=? "Line " line 5) (let* ((lnum (string-until-at line 5 #\space 0)) (cmd (string-append "info scope " lnum))) (if (= (string->integer lnum) 0) #f (gdb-server->string cmd))) #f)))
8da1a5ccec09e9eaf0f433c6c232a1b003590c3ae5df62ecc6eb0c5d2bad6507
clojupyter/clojupyter
core.clj
(ns clojupyter.kernel.core (:gen-class) (:require [clojupyter.kernel.cljsrv :as cljsrv] [clojupyter.kernel.comm-atom :as ca] [clojupyter.kernel.config :as config] [clojupyter.kernel.handle-event-process :as hep :refer [start-handle-event-process]] [clojupyter.kernel.init :as init] [clojupyter.kernel.jup-channels :refer [jup? make-jup]] [clojupyter.jupmsg-specs :as jsp] [clojupyter.log :as log] [clojupyter.messages :as msgs] [clojupyter.messages-specs :as msp] [clojupyter.shutdown :as shutdown] [clojupyter.state :as state] [clojupyter.util :as u] [clojupyter.util-actions :as u!] [clojupyter.zmq :as cjpzmq] [clojupyter.zmq.heartbeat-process :as hb] [clojure.core.async :as async :refer [<!! buffer chan]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :refer [instrument]] [clojure.walk :as walk] [io.simplect.compose :refer [def- curry c C p P >->> >>->]] )) (def- address (curry 2 (fn [config service] (let [svc (service config)] (assert svc (str "core/address: " service " not found")) (str (:transport config) "://" (:ip config) ":" svc))))) (defn run-kernel [jup term cljsrv] (state/ensure-initial-state!) (u!/with-exception-logging (let [proto-ctx {:cljsrv cljsrv, :jup jup, :term term}] (start-handle-event-process proto-ctx)))) (s/fdef run-kernel :args (s/cat :jup jup?, :term shutdown/terminator?, :cljsrv cljsrv/cljsrv?)) (instrument `run-kernel) ;;; ------------------------------------------------------------------------------------------------------------------------ ;;; CHANNEL TRANSDUCTION ;;; ------------------------------------------------------------------------------------------------------------------------ (defn extract-kernel-response-byte-arrays "Returns the result of extract any byte-arrays from messages with COMM state." [{:keys [rsp-content] :as kernel-rsp}] (let [state-path [:data :state] bufpath-path [:data :buffer_paths]] (if-let [state (get-in rsp-content state-path)] (let [[state' pathmap] (msgs/leaf-paths bytes? (constantly "replaced") state) paths (vec (keys pathmap)) buffers (mapv (p get pathmap) paths) rsp-content' (-> rsp-content (assoc-in state-path state') (assoc-in bufpath-path paths))] (assoc kernel-rsp :rsp-content rsp-content' :rsp-buffers buffers)) kernel-rsp))) (defn replace-comm-atoms-with-references [{:keys [rsp-content] :as kernel-rsp}] (let [[repl-content _] (msgs/leaf-paths ca/comm-atom? ca/model-ref rsp-content)] (assoc kernel-rsp :rsp-content repl-content))) (def- LOG-COUNTER "Enumerates all transducer output, showing the order of events." (atom 0)) (defn- logging-transducer [id] (fn [v] (when (config/log-traffic?) (log/debug (str "logxf." (swap! LOG-COUNTER inc) "(" id "):") (log/ppstr v))) v)) (defn- wrap-skip-shutdown-tokens [f] (fn [v] (if (shutdown/is-token? v) v (f v)))) (defn- inbound-channel-transducer [port checker] (u!/wrap-report-and-absorb-exceptions (msgs/transducer-error port) (C (wrap-skip-shutdown-tokens (C (p msgs/frames->jupmsg checker) (p msgs/jupmsg->kernelreq port))) (logging-transducer (str "INBOUND:" port))))) (defn- outbound-channel-transducer [port signer] (u!/wrap-report-and-absorb-exceptions (msgs/transducer-error port) (C (wrap-skip-shutdown-tokens (C (fn [krsp] (extract-kernel-response-byte-arrays krsp)) (fn [krsp] (replace-comm-atoms-with-references krsp)) (fn [krsp] (msgs/kernelrsp->jupmsg port krsp)))) (logging-transducer (str "OUTBOUND:" port)) (wrap-skip-shutdown-tokens (fn [jupmsg] (msgs/jupmsg->frames signer jupmsg)))))) (defn- start-zmq-socket-forwarding "Starts threads forwarding traffic between ZeroMQ sockets and core.async channels. Returns a 2-tuple of `jup` and `term` which respectively provide access to communicating with Jupyter and terminating Clojupyter." [ztx config] (u!/with-exception-logging (let [bufsize 25 ;; leave plenty of space - we don't want blocking on termination term (shutdown/make-terminator bufsize) get-shutdown (partial shutdown/notify-on-shutdown term) sess-key (s/assert ::msp/key (:key config)) [signer checker] (u/make-signer-checker sess-key) in-ch (fn [port] (get-shutdown (chan (buffer bufsize) (map (inbound-channel-transducer port checker))))) out-ch (fn [port] (get-shutdown (chan (buffer bufsize) (map (outbound-channel-transducer port signer)))))] (letfn [(start-fwd [port addr sock-type] (cjpzmq/start ztx port addr term {:inbound-ch (in-ch port), :outbound-ch (out-ch port), :zmq-socket-type sock-type}))] (let [[ctrl-in ctrl-out] (let [port :control_port] (start-fwd port (address config port) :router)) [shell-in shell-out] (let [port :shell_port] (start-fwd port (address config port) :router)) [iopub-in iopub-out] (let [port :iopub_port] (start-fwd port (address config port) :pub)) [stdin-in stdin-out] (let [port :stdin_port] (start-fwd port (address config port) :dealer)) jup (make-jup ctrl-in ctrl-out shell-in shell-out iopub-in iopub-out stdin-in stdin-out)] (hb/start-hb ztx (address config :hb_port) term) [jup term]))) (log/debug "start-zmq-socket-fwd returning"))) (defn- start-clojupyter "Starts Clojupyter including threads forwarding traffic between ZMQ sockets and core.async channels." [ztx config] (u!/with-exception-logging (do (log/info "Clojupyter config" (log/ppstr config)) (when-not (s/valid? ::msp/jupyter-config config) (log/error "Command-line arguments do not conform to specification.")) (init/ensure-init-global-state!) (let [[jup term] (start-zmq-socket-forwarding ztx config) wait-ch (shutdown/notify-on-shutdown term (chan 1))] (with-open [cljsrv (cljsrv/make-cljsrv)] (run-kernel jup term cljsrv) (<!! wait-ch) (log/debug "start-clojupyter: wait-signal received")))) (log/debug "start-clojupyter returning"))) (defn- finish-up [] (state/end-history-session)) (defn- parse-jupyter-arglist [arglist] (-> arglist first slurp u/parse-json-str walk/keywordize-keys)) (defn -main "Main entry point for Clojupyter when spawned by Jupyter. Creates the ZeroMQ context which lasts the entire life of the process." ;; When developing it is useful to be able to create the ZMQ context once and for all. This is the ;; key distinction between `-main` and `start-clojupyter` which assumes that the ZMQ context has ;; already been created. [& arglist] (init/ensure-init-global-state!) (log/debug "-main starting" (log/ppstr {:arglist arglist})) (try (let [ztx (state/zmq-context) config (parse-jupyter-arglist arglist)] (start-clojupyter ztx config)) (finish-up) (finally (log/info "Clojupyter terminating (sysexit)") (Thread/sleep 100) (System/exit 0)))) (instrument `run-kernel)
null
https://raw.githubusercontent.com/clojupyter/clojupyter/0bb113e467cbe607661a86809e52b459f1127e32/src/clojupyter/kernel/core.clj
clojure
------------------------------------------------------------------------------------------------------------------------ CHANNEL TRANSDUCTION ------------------------------------------------------------------------------------------------------------------------ leave plenty of space - we don't want blocking on termination When developing it is useful to be able to create the ZMQ context once and for all. This is the key distinction between `-main` and `start-clojupyter` which assumes that the ZMQ context has already been created.
(ns clojupyter.kernel.core (:gen-class) (:require [clojupyter.kernel.cljsrv :as cljsrv] [clojupyter.kernel.comm-atom :as ca] [clojupyter.kernel.config :as config] [clojupyter.kernel.handle-event-process :as hep :refer [start-handle-event-process]] [clojupyter.kernel.init :as init] [clojupyter.kernel.jup-channels :refer [jup? make-jup]] [clojupyter.jupmsg-specs :as jsp] [clojupyter.log :as log] [clojupyter.messages :as msgs] [clojupyter.messages-specs :as msp] [clojupyter.shutdown :as shutdown] [clojupyter.state :as state] [clojupyter.util :as u] [clojupyter.util-actions :as u!] [clojupyter.zmq :as cjpzmq] [clojupyter.zmq.heartbeat-process :as hb] [clojure.core.async :as async :refer [<!! buffer chan]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :refer [instrument]] [clojure.walk :as walk] [io.simplect.compose :refer [def- curry c C p P >->> >>->]] )) (def- address (curry 2 (fn [config service] (let [svc (service config)] (assert svc (str "core/address: " service " not found")) (str (:transport config) "://" (:ip config) ":" svc))))) (defn run-kernel [jup term cljsrv] (state/ensure-initial-state!) (u!/with-exception-logging (let [proto-ctx {:cljsrv cljsrv, :jup jup, :term term}] (start-handle-event-process proto-ctx)))) (s/fdef run-kernel :args (s/cat :jup jup?, :term shutdown/terminator?, :cljsrv cljsrv/cljsrv?)) (instrument `run-kernel) (defn extract-kernel-response-byte-arrays "Returns the result of extract any byte-arrays from messages with COMM state." [{:keys [rsp-content] :as kernel-rsp}] (let [state-path [:data :state] bufpath-path [:data :buffer_paths]] (if-let [state (get-in rsp-content state-path)] (let [[state' pathmap] (msgs/leaf-paths bytes? (constantly "replaced") state) paths (vec (keys pathmap)) buffers (mapv (p get pathmap) paths) rsp-content' (-> rsp-content (assoc-in state-path state') (assoc-in bufpath-path paths))] (assoc kernel-rsp :rsp-content rsp-content' :rsp-buffers buffers)) kernel-rsp))) (defn replace-comm-atoms-with-references [{:keys [rsp-content] :as kernel-rsp}] (let [[repl-content _] (msgs/leaf-paths ca/comm-atom? ca/model-ref rsp-content)] (assoc kernel-rsp :rsp-content repl-content))) (def- LOG-COUNTER "Enumerates all transducer output, showing the order of events." (atom 0)) (defn- logging-transducer [id] (fn [v] (when (config/log-traffic?) (log/debug (str "logxf." (swap! LOG-COUNTER inc) "(" id "):") (log/ppstr v))) v)) (defn- wrap-skip-shutdown-tokens [f] (fn [v] (if (shutdown/is-token? v) v (f v)))) (defn- inbound-channel-transducer [port checker] (u!/wrap-report-and-absorb-exceptions (msgs/transducer-error port) (C (wrap-skip-shutdown-tokens (C (p msgs/frames->jupmsg checker) (p msgs/jupmsg->kernelreq port))) (logging-transducer (str "INBOUND:" port))))) (defn- outbound-channel-transducer [port signer] (u!/wrap-report-and-absorb-exceptions (msgs/transducer-error port) (C (wrap-skip-shutdown-tokens (C (fn [krsp] (extract-kernel-response-byte-arrays krsp)) (fn [krsp] (replace-comm-atoms-with-references krsp)) (fn [krsp] (msgs/kernelrsp->jupmsg port krsp)))) (logging-transducer (str "OUTBOUND:" port)) (wrap-skip-shutdown-tokens (fn [jupmsg] (msgs/jupmsg->frames signer jupmsg)))))) (defn- start-zmq-socket-forwarding "Starts threads forwarding traffic between ZeroMQ sockets and core.async channels. Returns a 2-tuple of `jup` and `term` which respectively provide access to communicating with Jupyter and terminating Clojupyter." [ztx config] (u!/with-exception-logging term (shutdown/make-terminator bufsize) get-shutdown (partial shutdown/notify-on-shutdown term) sess-key (s/assert ::msp/key (:key config)) [signer checker] (u/make-signer-checker sess-key) in-ch (fn [port] (get-shutdown (chan (buffer bufsize) (map (inbound-channel-transducer port checker))))) out-ch (fn [port] (get-shutdown (chan (buffer bufsize) (map (outbound-channel-transducer port signer)))))] (letfn [(start-fwd [port addr sock-type] (cjpzmq/start ztx port addr term {:inbound-ch (in-ch port), :outbound-ch (out-ch port), :zmq-socket-type sock-type}))] (let [[ctrl-in ctrl-out] (let [port :control_port] (start-fwd port (address config port) :router)) [shell-in shell-out] (let [port :shell_port] (start-fwd port (address config port) :router)) [iopub-in iopub-out] (let [port :iopub_port] (start-fwd port (address config port) :pub)) [stdin-in stdin-out] (let [port :stdin_port] (start-fwd port (address config port) :dealer)) jup (make-jup ctrl-in ctrl-out shell-in shell-out iopub-in iopub-out stdin-in stdin-out)] (hb/start-hb ztx (address config :hb_port) term) [jup term]))) (log/debug "start-zmq-socket-fwd returning"))) (defn- start-clojupyter "Starts Clojupyter including threads forwarding traffic between ZMQ sockets and core.async channels." [ztx config] (u!/with-exception-logging (do (log/info "Clojupyter config" (log/ppstr config)) (when-not (s/valid? ::msp/jupyter-config config) (log/error "Command-line arguments do not conform to specification.")) (init/ensure-init-global-state!) (let [[jup term] (start-zmq-socket-forwarding ztx config) wait-ch (shutdown/notify-on-shutdown term (chan 1))] (with-open [cljsrv (cljsrv/make-cljsrv)] (run-kernel jup term cljsrv) (<!! wait-ch) (log/debug "start-clojupyter: wait-signal received")))) (log/debug "start-clojupyter returning"))) (defn- finish-up [] (state/end-history-session)) (defn- parse-jupyter-arglist [arglist] (-> arglist first slurp u/parse-json-str walk/keywordize-keys)) (defn -main "Main entry point for Clojupyter when spawned by Jupyter. Creates the ZeroMQ context which lasts the entire life of the process." [& arglist] (init/ensure-init-global-state!) (log/debug "-main starting" (log/ppstr {:arglist arglist})) (try (let [ztx (state/zmq-context) config (parse-jupyter-arglist arglist)] (start-clojupyter ztx config)) (finish-up) (finally (log/info "Clojupyter terminating (sysexit)") (Thread/sleep 100) (System/exit 0)))) (instrument `run-kernel)
7b57788f246b48e2a19062824f0830f9128a8a7f9d91e8ac66b0ef33131a639d
goblint/analyzer
setDomain.ml
(** Abstract domains representing sets. *) module Pretty = GoblintCil.Pretty open Pretty (* Exception raised when the set domain can not support the requested operation. * This will be raised, when trying to iterate a set that has been set to Top *) exception Unsupported of string let unsupported s = raise (Unsupported s) (** A set domain must support all the standard library set operations. They have been copied instead of included since our [empty] has a different signature. *) module type S = sig include Lattice.S type elt val empty: unit -> t val is_empty: t -> bool val mem: elt -> t -> bool val add: elt -> t -> t val singleton: elt -> t val remove: elt -> t -> t (** See {!Set.S.remove}. {b NB!} On set abstractions this is a {e strong} removal, i.e. all subsumed elements are also removed. @see <#discussion_r936336198> *) val union: t -> t -> t val inter: t -> t -> t val diff: t -> t -> t (** See {!Set.S.diff}. {b NB!} On set abstractions this is a {e strong} removal, i.e. all subsumed elements are also removed. @see <#discussion_r936336198> *) val subset: t -> t -> bool val disjoint: t -> t -> bool val iter: (elt -> unit) -> t -> unit (** See {!Set.S.iter}. On set abstractions this iterates only over canonical elements, not all subsumed elements. *) val map: (elt -> elt) -> t -> t (** See {!Set.S.map}. On set abstractions this maps only canonical elements, not all subsumed elements. *) val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a (** See {!Set.S.fold}. On set abstractions this folds only over canonical elements, not all subsumed elements. *) val for_all: (elt -> bool) -> t -> bool * See { ! Set . } . On set abstractions this checks only canonical elements , not all subsumed elements . On set abstractions this checks only canonical elements, not all subsumed elements. *) val exists: (elt -> bool) -> t -> bool (** See {!Set.S.exists}. On set abstractions this checks only canonical elements, not all subsumed elements. *) val filter: (elt -> bool) -> t -> t * See { ! } . On set abstractions this filters only canonical elements , not all subsumed elements . On set abstractions this filters only canonical elements, not all subsumed elements. *) val partition: (elt -> bool) -> t -> t * t (** See {!Set.S.partition}. On set abstractions this partitions only canonical elements, not all subsumed elements. *) val cardinal: t -> int (** See {!Set.S.cardinal}. On set abstractions this counts only canonical elements, not all subsumed elements. *) val elements: t -> elt list (** See {!Set.S.elements}. On set abstractions this lists only canonical elements, not all subsumed elements. *) val of_list: elt list -> t val min_elt: t -> elt (** See {!Set.S.min_elt}. On set abstractions this chooses only a canonical element, not any subsumed element. *) val max_elt: t -> elt (** See {!Set.S.max_elt}. On set abstractions this chooses only a canonical element, not any subsumed element. *) val choose: t -> elt (** See {!Set.S.choose}. On set abstractions this chooses only a canonical element, not any subsumed element. *) end (** Subsignature of {!S}, which is sufficient for {!Print}. *) module type Elements = sig type t type elt val elements: t -> elt list val iter: (elt -> unit) -> t -> unit end (** Reusable output definitions for sets. *) module Print (E: Printable.S) (S: Elements with type elt = E.t) = struct let pretty () x = let elts = S.elements x in let content = List.map (E.pretty ()) elts in let rec separate x = match x with | [] -> [] | [x] -> [x] | (x::xs) -> x ++ (text "," ++ break) :: separate xs in let separated = separate content in let content = List.fold_left (++) nil separated in (text "{" ++ align) ++ content ++ (unalign ++ text "}") (** Short summary for sets. *) let show x : string = let all_elems : string list = List.map E.show (S.elements x) in Printable.get_short_list "{" "}" all_elems let to_yojson x = [%to_yojson: E.t list] (S.elements x) let printXml f xs = BatPrintf.fprintf f "<value>\n<set>\n"; S.iter (E.printXml f) xs; BatPrintf.fprintf f "</set>\n</value>\n" end (** A functor for creating a simple set domain, there is no top element, and * calling [top ()] will raise an exception *) module Make (Base: Printable.S): S with type elt = Base.t and TODO : remove , only needed in VarEq for some reason ... struct include Printable.Blank include BatSet.Make(Base) let name () = "Set (" ^ Base.name () ^ ")" let empty _ = empty let leq = subset let join = union let widen = join let meet = inter let narrow = meet let bot = empty let is_bot = is_empty let top () = unsupported "Make.top" let is_top _ = false let map f s = let add_to_it x s = add (f x) s in fold add_to_it s (empty ()) include Print (Base) ( struct type nonrec t = t type nonrec elt = elt let elements = elements let iter = iter end ) let equal x y = cardinal x = cardinal y && for_all (fun e -> exists (Base.equal e) y) x let hash x = fold (fun x y -> y + Base.hash x) x 0 let relift x = map Base.relift x let pretty_diff () ((x:t),(y:t)): Pretty.doc = if leq x y then dprintf "%s: These are fine!" (name ()) else if is_bot y then dprintf "%s: %a instead of bot" (name ()) pretty x else begin let evil = choose (diff x y) in Pretty.dprintf "%s: %a not leq %a\n @[because %a@]" (name ()) pretty x pretty y Base.pretty evil end let arbitrary () = QCheck.map ~rev:elements of_list @@ QCheck.small_list (Base.arbitrary ()) end (** A functor for creating a path sensitive set domain, that joins the base * analysis whenever the user elements coincide. Just as above there is no top * element, and calling [top ()] will raise an exception *) TODO : unused module SensitiveConf (C: Printable.ProdConfiguration) (Base: Lattice.S) (User: Printable.S) = struct module Elt = Printable.ProdConf (C) (Base) (User) include Make(Elt) let name () = "Sensitive " ^ name () let leq s1 s2 = I want to check that forall e in x , the same key is in y with it 's base * domain element being leq of this one * domain element being leq of this one *) let p (b1,u1) = exists (fun (b2,u2) -> User.equal u1 u2 && Base.leq b1 b2) s2 in for_all p s1 let pretty_diff () ((x:t),(y:t)): Pretty.doc = Pretty.dprintf "%s: %a not leq %a" (name ()) pretty x pretty y let join s1 s2 = Ok , so for each element ( b2,u2 ) in s2 , we check in s1 for elements that have * equal user values ( there should be at most 1 ) and we either join with it , or * just add the element to our accumulator res and remove it from s1 * equal user values (there should be at most 1) and we either join with it, or * just add the element to our accumulator res and remove it from s1 *) let f (b2,u2) (s1,res) = let (s1_match, s1_rest) = partition (fun (b1,u1) -> User.equal u1 u2) s1 in let el = try let (b1,u1) = choose s1_match in (Base.join b1 b2, u2) with Not_found -> (b2,u2) in (s1_rest, add el res) in let (s1', res) = fold f s2 (s1, empty ()) in union s1' res let add e s = join (singleton e) s The meet operation is slightly different from the above , I think this is * the right thing , the intuition is from thinking of this as a MapBot * the right thing, the intuition is from thinking of this as a MapBot *) let meet s1 s2 = let f (b2,u2) (s1,res) = let (s1_match, s1_rest) = partition (fun (b1,u1) -> User.equal u1 u2) s1 in let res = try let (b1,u1) = choose s1_match in add (Base.meet b1 b2, u2) res with Not_found -> res in (s1_rest, res) in snd (fold f s2 (s1, empty ())) end [@@deprecated] (** Auxiliary signature for naming the top element *) module type ToppedSetNames = sig val topname: string end module LiftTop (S: S) (N: ToppedSetNames): S with type elt = S.elt and type t = [`Top | `Lifted of S.t] = (* Expose t for HoareDomain.Set_LiftTop *) struct include Printable.Std include Lattice.LiftTop (S) type elt = S.elt let empty () = `Lifted (S.empty ()) let is_empty x = match x with | `Top -> false | `Lifted x -> S.is_empty x let mem x s = match s with | `Top -> true | `Lifted s -> S.mem x s let add x s = match s with | `Top -> `Top | `Lifted s -> `Lifted (S.add x s) let singleton x = `Lifted (S.singleton x) let remove x s = match s with NB ! NB ! NB ! | `Lifted s -> `Lifted (S.remove x s) let union x y = match x, y with | `Top, _ -> `Top | _, `Top -> `Top | `Lifted x, `Lifted y -> `Lifted (S.union x y) let inter x y = match x, y with | `Top, y -> y | x, `Top -> x | `Lifted x, `Lifted y -> `Lifted (S.inter x y) let diff x y = match x, y with | x, `Top -> empty () NB ! NB ! NB ! | `Lifted x, `Lifted y -> `Lifted (S.diff x y) let subset x y = match x, y with | _, `Top -> true | `Top, _ -> false | `Lifted x, `Lifted y -> S.subset x y let disjoint x y = match x, y with | `Top, `Top -> false | `Lifted x, `Top | `Top, `Lifted x -> S.is_empty x | `Lifted x, `Lifted y -> S.disjoint x y let schema normal abnormal x = match x with | `Top -> unsupported abnormal | `Lifted t -> normal t let schema_default v f = function | `Top -> v | `Lifted x -> f x (* HACK! Map is an exception in that it doesn't throw an exception! *) let map f x = match x with | `Top -> `Top | `Lifted t -> `Lifted (S.map f t) let iter f = schema (S.iter f) "iter on `Top" (* let map f = schema (fun t -> `Lifted (S.map f t)) "map"*) let fold f x e = schema (fun t -> S.fold f t e) "fold on `Top" x let for_all f = schema_default false (S.for_all f) let exists f = schema_default true (S.exists f) let filter f = schema (fun t -> `Lifted (S.filter f t)) "filter on `Top" let elements = schema S.elements "elements on `Top" let of_list xs = `Lifted (S.of_list xs) let cardinal = schema S.cardinal "cardinal on `Top" let min_elt = schema S.min_elt "min_elt on `Top" let max_elt = schema S.max_elt "max_elt on `Top" let choose = schema S.choose "choose on `Top" let partition f = schema (fun t -> match S.partition f t with (a,b) -> (`Lifted a, `Lifted b)) "filter on `Top" (* The printable implementation *) (* Overrides `Top text *) let pretty () x = match x with | `Top -> text N.topname | `Lifted t -> S.pretty () t let show x : string = match x with | `Top -> N.topname | `Lifted t -> S.show t (* Lattice implementation *) (* Lift separately because lattice order might be different from subset order, e.g. after Reverse *) let bot () = `Lifted (S.bot ()) let is_bot x = match x with | `Top -> false | `Lifted x -> S.is_bot x let leq x y = match x, y with | _, `Top -> true | `Top, _ -> false | `Lifted x, `Lifted y -> S.leq x y let join x y = match x, y with | `Top, _ -> `Top | _, `Top -> `Top | `Lifted x, `Lifted y -> `Lifted (S.join x y) let widen x y = (* assumes y to be bigger than x *) match x, y with | `Top, _ | _, `Top -> `Top | `Lifted x, `Lifted y -> `Lifted (S.widen x y) let meet x y = match x, y with | `Top, y -> y | x, `Top -> x | `Lifted x, `Lifted y -> `Lifted (S.meet x y) let narrow x y = match x, y with | `Top, y -> y | x, `Top -> x | `Lifted x, `Lifted y -> `Lifted (S.narrow x y) let arbitrary () = QCheck.set_print show (arbitrary ()) end (** Functor for creating artificially topped set domains. *) module ToppedSet (Base: Printable.S) (N: ToppedSetNames): S with type elt = Base.t and type t = [`Top | `Lifted of Make (Base).t] = (* TODO: don't expose t *) struct module S = Make (Base) include LiftTop (S) (N) end (* This one just removes the extra "{" notation and also by always returning * false for the isSimple, the answer looks better, but this is essentially a * hack. All the pretty printing needs some rethinking. *) module HeadlessSet (Base: Printable.S) = struct include Make(Base) let name () = "Headless " ^ name () let pretty () x = let elts = elements x in let content = List.map (Base.pretty ()) elts in let rec separate x = match x with | [] -> [] | [x] -> [x] | (x::xs) -> x ++ (text ", ") ++ line :: separate xs in let separated = separate content in let content = List.fold_left (++) nil separated in content let pretty_diff () ((x:t),(y:t)): Pretty.doc = Pretty.dprintf "%s: %a not leq %a" (name ()) pretty x pretty y let printXml f xs = iter (Base.printXml f) xs end (** Reverses lattice order of a set domain while keeping the set operations same. *) module Reverse (Base: S) = struct include Base include Lattice.Reverse (Base) end module type FiniteSetElems = sig type t val elems: t list end TODO : put elems into E module FiniteSet (E:Printable.S) (Elems:FiniteSetElems with type t = E.t) = struct module E = struct include E let arbitrary () = QCheck.oneofl Elems.elems end include Make (E) let top () = of_list Elems.elems let is_top x = equal x (top ()) end (** Set abstracted by a single (joined) element. Element-wise {!S} operations only observe the single element. *) module Joined (E: Lattice.S): S with type elt = E.t = struct type elt = E.t include E let singleton e = e let of_list es = List.fold_left E.join (E.bot ()) es let exists p e = p e let for_all p e = p e let mem e e' = E.leq e e' let choose e = e let elements e = [e] let remove e e' = if E.leq e' e then NB ! strong removal else e' let map f e = f e let fold f e a = f e a let empty () = E.bot () let add e e' = E.join e e' let is_empty e = E.is_bot e let union e e' = E.join e e' NB ! strong removal let iter f e = f e let cardinal e = if is_empty e then 0 else 1 let inter e e' = E.meet e e' let subset e e' = E.leq e e' let filter p e = unsupported "Joined.filter" let partition p e = unsupported "Joined.partition" let min_elt e = unsupported "Joined.min_elt" let max_elt e = unsupported "Joined.max_elt" let disjoint e e' = is_empty (inter e e') end
null
https://raw.githubusercontent.com/goblint/analyzer/12276b68682f48bf540ae832fa8b7f27c1b8404a/src/domains/setDomain.ml
ocaml
* Abstract domains representing sets. Exception raised when the set domain can not support the requested operation. * This will be raised, when trying to iterate a set that has been set to Top * A set domain must support all the standard library set operations. They have been copied instead of included since our [empty] has a different signature. * See {!Set.S.remove}. {b NB!} On set abstractions this is a {e strong} removal, i.e. all subsumed elements are also removed. @see <#discussion_r936336198> * See {!Set.S.diff}. {b NB!} On set abstractions this is a {e strong} removal, i.e. all subsumed elements are also removed. @see <#discussion_r936336198> * See {!Set.S.iter}. On set abstractions this iterates only over canonical elements, not all subsumed elements. * See {!Set.S.map}. On set abstractions this maps only canonical elements, not all subsumed elements. * See {!Set.S.fold}. On set abstractions this folds only over canonical elements, not all subsumed elements. * See {!Set.S.exists}. On set abstractions this checks only canonical elements, not all subsumed elements. * See {!Set.S.partition}. On set abstractions this partitions only canonical elements, not all subsumed elements. * See {!Set.S.cardinal}. On set abstractions this counts only canonical elements, not all subsumed elements. * See {!Set.S.elements}. On set abstractions this lists only canonical elements, not all subsumed elements. * See {!Set.S.min_elt}. On set abstractions this chooses only a canonical element, not any subsumed element. * See {!Set.S.max_elt}. On set abstractions this chooses only a canonical element, not any subsumed element. * See {!Set.S.choose}. On set abstractions this chooses only a canonical element, not any subsumed element. * Subsignature of {!S}, which is sufficient for {!Print}. * Reusable output definitions for sets. * Short summary for sets. * A functor for creating a simple set domain, there is no top element, and * calling [top ()] will raise an exception * A functor for creating a path sensitive set domain, that joins the base * analysis whenever the user elements coincide. Just as above there is no top * element, and calling [top ()] will raise an exception * Auxiliary signature for naming the top element Expose t for HoareDomain.Set_LiftTop HACK! Map is an exception in that it doesn't throw an exception! let map f = schema (fun t -> `Lifted (S.map f t)) "map" The printable implementation Overrides `Top text Lattice implementation Lift separately because lattice order might be different from subset order, e.g. after Reverse assumes y to be bigger than x * Functor for creating artificially topped set domains. TODO: don't expose t This one just removes the extra "{" notation and also by always returning * false for the isSimple, the answer looks better, but this is essentially a * hack. All the pretty printing needs some rethinking. * Reverses lattice order of a set domain while keeping the set operations same. * Set abstracted by a single (joined) element. Element-wise {!S} operations only observe the single element.
module Pretty = GoblintCil.Pretty open Pretty exception Unsupported of string let unsupported s = raise (Unsupported s) module type S = sig include Lattice.S type elt val empty: unit -> t val is_empty: t -> bool val mem: elt -> t -> bool val add: elt -> t -> t val singleton: elt -> t val remove: elt -> t -> t val union: t -> t -> t val inter: t -> t -> t val diff: t -> t -> t val subset: t -> t -> bool val disjoint: t -> t -> bool val iter: (elt -> unit) -> t -> unit val map: (elt -> elt) -> t -> t val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all: (elt -> bool) -> t -> bool * See { ! Set . } . On set abstractions this checks only canonical elements , not all subsumed elements . On set abstractions this checks only canonical elements, not all subsumed elements. *) val exists: (elt -> bool) -> t -> bool val filter: (elt -> bool) -> t -> t * See { ! } . On set abstractions this filters only canonical elements , not all subsumed elements . On set abstractions this filters only canonical elements, not all subsumed elements. *) val partition: (elt -> bool) -> t -> t * t val cardinal: t -> int val elements: t -> elt list val of_list: elt list -> t val min_elt: t -> elt val max_elt: t -> elt val choose: t -> elt end module type Elements = sig type t type elt val elements: t -> elt list val iter: (elt -> unit) -> t -> unit end module Print (E: Printable.S) (S: Elements with type elt = E.t) = struct let pretty () x = let elts = S.elements x in let content = List.map (E.pretty ()) elts in let rec separate x = match x with | [] -> [] | [x] -> [x] | (x::xs) -> x ++ (text "," ++ break) :: separate xs in let separated = separate content in let content = List.fold_left (++) nil separated in (text "{" ++ align) ++ content ++ (unalign ++ text "}") let show x : string = let all_elems : string list = List.map E.show (S.elements x) in Printable.get_short_list "{" "}" all_elems let to_yojson x = [%to_yojson: E.t list] (S.elements x) let printXml f xs = BatPrintf.fprintf f "<value>\n<set>\n"; S.iter (E.printXml f) xs; BatPrintf.fprintf f "</set>\n</value>\n" end module Make (Base: Printable.S): S with type elt = Base.t and TODO : remove , only needed in VarEq for some reason ... struct include Printable.Blank include BatSet.Make(Base) let name () = "Set (" ^ Base.name () ^ ")" let empty _ = empty let leq = subset let join = union let widen = join let meet = inter let narrow = meet let bot = empty let is_bot = is_empty let top () = unsupported "Make.top" let is_top _ = false let map f s = let add_to_it x s = add (f x) s in fold add_to_it s (empty ()) include Print (Base) ( struct type nonrec t = t type nonrec elt = elt let elements = elements let iter = iter end ) let equal x y = cardinal x = cardinal y && for_all (fun e -> exists (Base.equal e) y) x let hash x = fold (fun x y -> y + Base.hash x) x 0 let relift x = map Base.relift x let pretty_diff () ((x:t),(y:t)): Pretty.doc = if leq x y then dprintf "%s: These are fine!" (name ()) else if is_bot y then dprintf "%s: %a instead of bot" (name ()) pretty x else begin let evil = choose (diff x y) in Pretty.dprintf "%s: %a not leq %a\n @[because %a@]" (name ()) pretty x pretty y Base.pretty evil end let arbitrary () = QCheck.map ~rev:elements of_list @@ QCheck.small_list (Base.arbitrary ()) end TODO : unused module SensitiveConf (C: Printable.ProdConfiguration) (Base: Lattice.S) (User: Printable.S) = struct module Elt = Printable.ProdConf (C) (Base) (User) include Make(Elt) let name () = "Sensitive " ^ name () let leq s1 s2 = I want to check that forall e in x , the same key is in y with it 's base * domain element being leq of this one * domain element being leq of this one *) let p (b1,u1) = exists (fun (b2,u2) -> User.equal u1 u2 && Base.leq b1 b2) s2 in for_all p s1 let pretty_diff () ((x:t),(y:t)): Pretty.doc = Pretty.dprintf "%s: %a not leq %a" (name ()) pretty x pretty y let join s1 s2 = Ok , so for each element ( b2,u2 ) in s2 , we check in s1 for elements that have * equal user values ( there should be at most 1 ) and we either join with it , or * just add the element to our accumulator res and remove it from s1 * equal user values (there should be at most 1) and we either join with it, or * just add the element to our accumulator res and remove it from s1 *) let f (b2,u2) (s1,res) = let (s1_match, s1_rest) = partition (fun (b1,u1) -> User.equal u1 u2) s1 in let el = try let (b1,u1) = choose s1_match in (Base.join b1 b2, u2) with Not_found -> (b2,u2) in (s1_rest, add el res) in let (s1', res) = fold f s2 (s1, empty ()) in union s1' res let add e s = join (singleton e) s The meet operation is slightly different from the above , I think this is * the right thing , the intuition is from thinking of this as a MapBot * the right thing, the intuition is from thinking of this as a MapBot *) let meet s1 s2 = let f (b2,u2) (s1,res) = let (s1_match, s1_rest) = partition (fun (b1,u1) -> User.equal u1 u2) s1 in let res = try let (b1,u1) = choose s1_match in add (Base.meet b1 b2, u2) res with Not_found -> res in (s1_rest, res) in snd (fold f s2 (s1, empty ())) end [@@deprecated] module type ToppedSetNames = sig val topname: string end module LiftTop (S: S) (N: ToppedSetNames): S with type elt = S.elt and struct include Printable.Std include Lattice.LiftTop (S) type elt = S.elt let empty () = `Lifted (S.empty ()) let is_empty x = match x with | `Top -> false | `Lifted x -> S.is_empty x let mem x s = match s with | `Top -> true | `Lifted s -> S.mem x s let add x s = match s with | `Top -> `Top | `Lifted s -> `Lifted (S.add x s) let singleton x = `Lifted (S.singleton x) let remove x s = match s with NB ! NB ! NB ! | `Lifted s -> `Lifted (S.remove x s) let union x y = match x, y with | `Top, _ -> `Top | _, `Top -> `Top | `Lifted x, `Lifted y -> `Lifted (S.union x y) let inter x y = match x, y with | `Top, y -> y | x, `Top -> x | `Lifted x, `Lifted y -> `Lifted (S.inter x y) let diff x y = match x, y with | x, `Top -> empty () NB ! NB ! NB ! | `Lifted x, `Lifted y -> `Lifted (S.diff x y) let subset x y = match x, y with | _, `Top -> true | `Top, _ -> false | `Lifted x, `Lifted y -> S.subset x y let disjoint x y = match x, y with | `Top, `Top -> false | `Lifted x, `Top | `Top, `Lifted x -> S.is_empty x | `Lifted x, `Lifted y -> S.disjoint x y let schema normal abnormal x = match x with | `Top -> unsupported abnormal | `Lifted t -> normal t let schema_default v f = function | `Top -> v | `Lifted x -> f x let map f x = match x with | `Top -> `Top | `Lifted t -> `Lifted (S.map f t) let iter f = schema (S.iter f) "iter on `Top" let fold f x e = schema (fun t -> S.fold f t e) "fold on `Top" x let for_all f = schema_default false (S.for_all f) let exists f = schema_default true (S.exists f) let filter f = schema (fun t -> `Lifted (S.filter f t)) "filter on `Top" let elements = schema S.elements "elements on `Top" let of_list xs = `Lifted (S.of_list xs) let cardinal = schema S.cardinal "cardinal on `Top" let min_elt = schema S.min_elt "min_elt on `Top" let max_elt = schema S.max_elt "max_elt on `Top" let choose = schema S.choose "choose on `Top" let partition f = schema (fun t -> match S.partition f t with (a,b) -> (`Lifted a, `Lifted b)) "filter on `Top" let pretty () x = match x with | `Top -> text N.topname | `Lifted t -> S.pretty () t let show x : string = match x with | `Top -> N.topname | `Lifted t -> S.show t let bot () = `Lifted (S.bot ()) let is_bot x = match x with | `Top -> false | `Lifted x -> S.is_bot x let leq x y = match x, y with | _, `Top -> true | `Top, _ -> false | `Lifted x, `Lifted y -> S.leq x y let join x y = match x, y with | `Top, _ -> `Top | _, `Top -> `Top | `Lifted x, `Lifted y -> `Lifted (S.join x y) match x, y with | `Top, _ | _, `Top -> `Top | `Lifted x, `Lifted y -> `Lifted (S.widen x y) let meet x y = match x, y with | `Top, y -> y | x, `Top -> x | `Lifted x, `Lifted y -> `Lifted (S.meet x y) let narrow x y = match x, y with | `Top, y -> y | x, `Top -> x | `Lifted x, `Lifted y -> `Lifted (S.narrow x y) let arbitrary () = QCheck.set_print show (arbitrary ()) end module ToppedSet (Base: Printable.S) (N: ToppedSetNames): S with type elt = Base.t and struct module S = Make (Base) include LiftTop (S) (N) end module HeadlessSet (Base: Printable.S) = struct include Make(Base) let name () = "Headless " ^ name () let pretty () x = let elts = elements x in let content = List.map (Base.pretty ()) elts in let rec separate x = match x with | [] -> [] | [x] -> [x] | (x::xs) -> x ++ (text ", ") ++ line :: separate xs in let separated = separate content in let content = List.fold_left (++) nil separated in content let pretty_diff () ((x:t),(y:t)): Pretty.doc = Pretty.dprintf "%s: %a not leq %a" (name ()) pretty x pretty y let printXml f xs = iter (Base.printXml f) xs end module Reverse (Base: S) = struct include Base include Lattice.Reverse (Base) end module type FiniteSetElems = sig type t val elems: t list end TODO : put elems into E module FiniteSet (E:Printable.S) (Elems:FiniteSetElems with type t = E.t) = struct module E = struct include E let arbitrary () = QCheck.oneofl Elems.elems end include Make (E) let top () = of_list Elems.elems let is_top x = equal x (top ()) end module Joined (E: Lattice.S): S with type elt = E.t = struct type elt = E.t include E let singleton e = e let of_list es = List.fold_left E.join (E.bot ()) es let exists p e = p e let for_all p e = p e let mem e e' = E.leq e e' let choose e = e let elements e = [e] let remove e e' = if E.leq e' e then NB ! strong removal else e' let map f e = f e let fold f e a = f e a let empty () = E.bot () let add e e' = E.join e e' let is_empty e = E.is_bot e let union e e' = E.join e e' NB ! strong removal let iter f e = f e let cardinal e = if is_empty e then 0 else 1 let inter e e' = E.meet e e' let subset e e' = E.leq e e' let filter p e = unsupported "Joined.filter" let partition p e = unsupported "Joined.partition" let min_elt e = unsupported "Joined.min_elt" let max_elt e = unsupported "Joined.max_elt" let disjoint e e' = is_empty (inter e e') end
2b1786cdb9e6769366cda51b2d960f1ac38da188d5208120e99d9378f23c4ba9
Kappa-Dev/KappaTools
tab_log.ml
(******************************************************************************) (* _ __ * The Kappa Language *) | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF (* | ' / *********************************************************************) (* | . \ * This file is distributed under the terms of the *) (* |_|\_\ * GNU Lesser General Public License Version 3 *) (******************************************************************************) module Html = Tyxml_js.Html5 open Lwt.Infix let tab_is_active, set_tab_is_active = React.S.create false let tab_was_active = ref false let line_count state = match state with | None -> 0 | Some state -> let open Api_types_t in state.simulation_info_output.simulation_output_log_messages let navli () = Ui_common.label_news tab_is_active (fun state -> (line_count state)) let dont_gc_me = ref [] let content () = let state_log , set_state_log = React.S.create ("" : string) in let () = dont_gc_me := [ Lwt_react.S.map_s (fun _ -> State_simulation.with_simulation_info ~label:__LOC__ ~ready: (fun manager _ -> manager#simulation_detail_log_message >>= (Api_common.result_bind_lwt ~ok:(fun (log_messages : Api_types_j.log_message) -> let () = set_state_log log_messages in Lwt.return (Result_util.ok ())) ) ) ~stopped:(fun _ -> let () = set_state_log "" in Lwt.return (Result_util.ok ())) () ) (React.S.on tab_is_active State_simulation.dummy_model State_simulation.model) ] in [ Html.div ~a:[Html.a_class ["panel-pre" ; "panel-scroll"]] [ Tyxml_js.R.Html.txt state_log ] ] let parent_hide () = set_tab_is_active false let parent_shown () = set_tab_is_active !tab_was_active let onload () = let () = Common.jquery_on "#navlog" "hide.bs.tab" (fun _ -> let () = tab_was_active := false in set_tab_is_active false) in let () = Common.jquery_on "#navlog" "shown.bs.tab" (fun _ -> let () = tab_was_active := true in set_tab_is_active true) in () let onresize () : unit = ()
null
https://raw.githubusercontent.com/Kappa-Dev/KappaTools/1e8c9c55e743510eb070ed8b6f2363a166936277/gui/tab_log.ml
ocaml
**************************************************************************** _ __ * The Kappa Language | ' / ******************************************************************** | . \ * This file is distributed under the terms of the |_|\_\ * GNU Lesser General Public License Version 3 ****************************************************************************
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF module Html = Tyxml_js.Html5 open Lwt.Infix let tab_is_active, set_tab_is_active = React.S.create false let tab_was_active = ref false let line_count state = match state with | None -> 0 | Some state -> let open Api_types_t in state.simulation_info_output.simulation_output_log_messages let navli () = Ui_common.label_news tab_is_active (fun state -> (line_count state)) let dont_gc_me = ref [] let content () = let state_log , set_state_log = React.S.create ("" : string) in let () = dont_gc_me := [ Lwt_react.S.map_s (fun _ -> State_simulation.with_simulation_info ~label:__LOC__ ~ready: (fun manager _ -> manager#simulation_detail_log_message >>= (Api_common.result_bind_lwt ~ok:(fun (log_messages : Api_types_j.log_message) -> let () = set_state_log log_messages in Lwt.return (Result_util.ok ())) ) ) ~stopped:(fun _ -> let () = set_state_log "" in Lwt.return (Result_util.ok ())) () ) (React.S.on tab_is_active State_simulation.dummy_model State_simulation.model) ] in [ Html.div ~a:[Html.a_class ["panel-pre" ; "panel-scroll"]] [ Tyxml_js.R.Html.txt state_log ] ] let parent_hide () = set_tab_is_active false let parent_shown () = set_tab_is_active !tab_was_active let onload () = let () = Common.jquery_on "#navlog" "hide.bs.tab" (fun _ -> let () = tab_was_active := false in set_tab_is_active false) in let () = Common.jquery_on "#navlog" "shown.bs.tab" (fun _ -> let () = tab_was_active := true in set_tab_is_active true) in () let onresize () : unit = ()
15bbd226132fbe65ab526989bc010953b40d63913a18b489bdd6d731953f3d28
parapluu/Concuerror
ets_heir.erl
-module(ets_heir). -compile(export_all). scenarios() -> [{T, inf, dpor} || T <- [?MODULE, test, test1, test2]]. ets_heir() -> Heir = spawn(fun() -> ok end), ets:new(table, [named_table, {heir, Heir, heir}]), spawn(fun() -> ets:lookup(table, x), throw(too_bad) end). test() -> P = self(), Q = spawn(fun() -> ets:new(foo, [named_table, {heir, P, fan}]) end), receive {'ETS-TRANSFER', foo, Q, fan} -> ok end. test1() -> P = self(), Q = spawn(fun() -> ets:new(foo, [named_table]), ets:give_away(foo, P, fan) end), receive {'ETS-TRANSFER', foo, Q, fan} -> ok end. test2() -> P = self(), ets:new(table, [named_table, {heir, P, bad}]), spawn(fun() -> ets:lookup(table, x) end).
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/basic_tests/src/ets_heir.erl
erlang
-module(ets_heir). -compile(export_all). scenarios() -> [{T, inf, dpor} || T <- [?MODULE, test, test1, test2]]. ets_heir() -> Heir = spawn(fun() -> ok end), ets:new(table, [named_table, {heir, Heir, heir}]), spawn(fun() -> ets:lookup(table, x), throw(too_bad) end). test() -> P = self(), Q = spawn(fun() -> ets:new(foo, [named_table, {heir, P, fan}]) end), receive {'ETS-TRANSFER', foo, Q, fan} -> ok end. test1() -> P = self(), Q = spawn(fun() -> ets:new(foo, [named_table]), ets:give_away(foo, P, fan) end), receive {'ETS-TRANSFER', foo, Q, fan} -> ok end. test2() -> P = self(), ets:new(table, [named_table, {heir, P, bad}]), spawn(fun() -> ets:lookup(table, x) end).
4c8f85047165ddf8a8aa20a6a582b094745a3925aea51dd3f87bfeefbe4a8a21
GaloisInc/semmc
Explicit.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE ScopedTypeVariables # module SemMC.Stochastic.IORelation.Explicit ( generateExplicitInstruction, classifyExplicitOperands ) where import qualified GHC.Err.Located as L import Control.Monad ( replicateM ) import Control.Monad.Trans ( liftIO ) import qualified Data.Foldable as F import qualified Data.Map.Strict as M import Data.Monoid import Data.Proxy ( Proxy(..) ) import qualified Data.Set as S import Text.Printf ( printf ) import qualified Data.Set.NonEmpty as NES import qualified Data.Parameterized.Classes as P import qualified Data.Parameterized.List as SL import Data.Parameterized.Some ( Some(..) ) import qualified Dismantle.Instruction as D import qualified Dismantle.Instruction.Random as D import qualified SemMC.Architecture as A import qualified SemMC.Architecture.Concrete as AC import qualified SemMC.Architecture.View as V import qualified SemMC.Concrete.Execution as CE import SemMC.Stochastic.IORelation.Shared import SemMC.Stochastic.IORelation.Types import Prelude -- | Make a random instruction that does not reference any implicit operands. -- -- This could be made more efficient - right now, it just tries to generate -- random instructions until it gets a match. generateExplicitInstruction :: (AC.ConcreteArchitecture arch, D.ArbitraryOperands (A.Opcode arch) (A.Operand arch)) => Proxy arch -> A.Opcode arch (A.Operand arch) sh -> [Some (V.View arch)] -> Learning arch (A.Instruction arch) generateExplicitInstruction proxy op implicitOperands = do g <- askGen insn <- liftIO $ D.randomInstruction g (NES.singleton (Some op)) case insn of D.Instruction _ ops -> case SL.ifoldr (matchesOperand proxy implicitOperands) (False, S.empty) ops of (False, sops) -- The operands are all distinct and no operands are implicit | S.size sops == length (instructionRegisterOperands proxy ops) -> return insn _ -> generateExplicitInstruction proxy op implicitOperands -- | Generate test cases and send them off to the remote runner. Collect and interpret the results to create an IORelation that describes the explicit -- operands of the instruction. classifyExplicitOperands :: (AC.ConcreteArchitecture arch, D.ArbitraryOperands (A.Opcode arch) (A.Operand arch)) => A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> Learning arch (IORelation arch sh) classifyExplicitOperands op explicitOperands = do t0 <- mkRandomTest tests <- generateExplicitTestVariants insn t0 tests' <- mapM (wrapTestBundle insn) tests results <- withTestResults op tests' computeIORelation op explicitOperands tests' results where insn = D.Instruction op explicitOperands -- | For all of the explicit operands, map the results of tests to deductions -- (forming an 'IORelation') computeIORelation :: (AC.ConcreteArchitecture arch) => A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> [TestBundle (TestCase arch) (ExplicitFact arch)] -> CE.ResultIndex (V.ConcreteState arch) -> Learning arch (IORelation arch sh) computeIORelation opcode operands bundles idx = F.foldlM (buildIORelation opcode operands idx) mempty bundles -- | Interpret the results of a test (by consulting the 'ResultIndex' based on nonces) -- 1 ) Look up the result of the concrete run of the original test -- ('tbTestOrig'). We'll learn information based on deviation of the other -- test cases from this one. -- 2 ) If any of the locations referenced by the instruction change , they are -- (explicit) output locations and the tagged location is an input. If no -- locations change due to the tagged location, it could be an output -- we -- don't know, so don't conclude anything. Future tests will figure out if -- it is an output. buildIORelation :: forall arch sh . (AC.ConcreteArchitecture arch) => A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> CE.ResultIndex (V.ConcreteState arch) -> IORelation arch sh -> TestBundle (TestCase arch) (ExplicitFact arch) -> Learning arch (IORelation arch sh) buildIORelation op explicitOperands ri iorel tb = do case tbResult tb of ExplicitFact { lIndex = alteredIndex, lOpcode = lop } | Just P.Refl <- P.testEquality op lop -> do explicitOutputLocs <- S.unions <$> mapM (collectExplicitLocations alteredIndex explicitOperands explicitLocs ri) (tbTestCases tb) case S.null explicitOutputLocs of True -> return iorel False -> -- If the set of explicit output locations discovered by this test -- bundle is non-empty, then the location mentioned in the learned -- fact is an input. let newRel = IORelation { inputs = S.singleton (OperandRef (Some alteredIndex)) , outputs = S.fromList $ map OperandRef (F.toList explicitOutputLocs) } in return (iorel <> newRel) | otherwise -> L.error (printf "Opcode mismatch; expected %s but got %s" (P.showF op) (P.showF lop)) where explicitLocs = instructionRegisterOperands (Proxy :: Proxy arch) explicitOperands -- | For the given test case, look up the results and compare them to the input -- -- If the test failed, return an empty set. collectExplicitLocations :: (AC.ConcreteArchitecture arch) => SL.Index sh tp -> SL.List (A.Operand arch) sh -> [IndexedSemanticView arch sh] -> CE.ResultIndex (V.ConcreteState arch) -> TestCase arch -> Learning arch (S.Set (Some (SL.Index sh))) collectExplicitLocations alteredIndex _opList explicitLocs ri tc = do case M.lookup (CE.testNonce tc) (CE.riSuccesses ri) of Nothing -> return S.empty Just res -> F.foldrM (addLocIfDifferent (CE.resultContext res)) S.empty explicitLocs where addLocIfDifferent resCtx (IndexedSemanticView idx (V.SemanticView { V.semvView = opView@(V.View {}) })) s | Just P.Refl <- P.testEquality alteredIndex idx = return s | output <- V.peekMS resCtx opView , input <- V.peekMS (CE.testContext tc) opView = do case input /= output of True -> return (S.insert (Some idx) s) False -> return s -- | Given an initial test state, generate all interesting variants on it. The -- idea is to see which outputs change when we tweak an input. -- -- We learn the *inputs* set by starting with an initial test t0 and tweaking -- each element in the state in turn. For each tweaked input, we examine the -- effects on the output states. We want to avoid tweaking the registers that -- are instantiated as operands to the instruction, as we expect those to cause -- changes. We really just need to learn which of the operands are inputs vs -- outputs, and if there are any implicit arguments. -- -- We learn the *outputs* set by comparing the tweaked input vs the output from -- that test vector: all modified registers are in the output set. generateExplicitTestVariants :: forall arch . (AC.ConcreteArchitecture arch) => A.Instruction arch -> V.ConcreteState arch -> Learning arch [TestBundle (V.ConcreteState arch) (ExplicitFact arch)] generateExplicitTestVariants i s0 = case i of D.Instruction opcode operands -> do mapM (genVar opcode) (instructionRegisterOperands (Proxy :: Proxy arch) operands) where genVar :: forall sh . A.Opcode arch (A.Operand arch) sh -> IndexedSemanticView arch sh -> Learning arch (TestBundle (V.ConcreteState arch) (ExplicitFact arch)) genVar opcode (IndexedSemanticView ix (V.SemanticView { V.semvView = view })) = do cases <- generateVariantsFor s0 opcode ix (Some view) return TestBundle { tbTestCases = cases , tbTestBase = s0 , tbResult = ExplicitFact { lOpcode = opcode , lIndex = ix , lLocation = view , lInstruction = i } } -- | Tweak the value in the 'ConcreteState' at the given location to a number of -- random values. -- This has to be in IO so that we can generate ' 's -- -- Right now, we only support generating random bitvectors. That will get more -- interesting once we start dealing with floats. Note that we could just -- generate random bitvectors for floats, too, but we would probably want to -- tweak the distribution to generate interesting types of floats. generateVariantsFor :: (AC.ConcreteArchitecture arch) => V.ConcreteState arch -> A.Opcode arch (A.Operand arch) sh -> SL.Index sh tp -> Some (V.View arch) -> Learning arch [V.ConcreteState arch] generateVariantsFor s0 _opcode _ix (Some v@(V.View {})) = do replicateM 20 (withGeneratedValueForLocation v (\x -> V.pokeMS s0 v x)) matchesOperand :: (AC.ConcreteArchitecture arch) => Proxy arch -> [Some (V.View arch)] -> SL.Index sh tp -> A.Operand arch tp -> (Bool, S.Set (Some (V.View arch))) -> (Bool, S.Set (Some (V.View arch))) matchesOperand proxy implicits _ix operand (matches, sops) = case AC.operandToSemanticView proxy operand of Nothing -> (matches, sops) Just (V.SemanticView { V.semvView = view }) -> (matches || any (== (Some view)) implicits, S.insert (Some view) sops) Note [ Test Form ] For each explicit operand in an instruction , we generate test cases with different values for that location . The ExplicitFact records the index of the operand so that we can generate appropriate entries in the IORelation later . If changing the location causes other locations to change after the test , it means the location was an input location . At the same time , the locations that change are output locations . Note that a location can be both an input and an output . For each explicit operand in an instruction, we generate test cases with different values for that location. The ExplicitFact records the index of the operand so that we can generate appropriate entries in the IORelation later. If changing the location causes other locations to change after the test, it means the location was an input location. At the same time, the locations that change are output locations. Note that a location can be both an input and an output. -}
null
https://raw.githubusercontent.com/GaloisInc/semmc/17f3ac6238377f833b04f291b07bc31d6266b1a1/semmc-learning/src/SemMC/Stochastic/IORelation/Explicit.hs
haskell
# LANGUAGE GADTs # | Make a random instruction that does not reference any implicit operands. This could be made more efficient - right now, it just tries to generate random instructions until it gets a match. The operands are all distinct and no operands are implicit | Generate test cases and send them off to the remote runner. Collect and operands of the instruction. | For all of the explicit operands, map the results of tests to deductions (forming an 'IORelation') | Interpret the results of a test (by consulting the 'ResultIndex' based on nonces) ('tbTestOrig'). We'll learn information based on deviation of the other test cases from this one. (explicit) output locations and the tagged location is an input. If no locations change due to the tagged location, it could be an output -- we don't know, so don't conclude anything. Future tests will figure out if it is an output. If the set of explicit output locations discovered by this test bundle is non-empty, then the location mentioned in the learned fact is an input. | For the given test case, look up the results and compare them to the input If the test failed, return an empty set. | Given an initial test state, generate all interesting variants on it. The idea is to see which outputs change when we tweak an input. We learn the *inputs* set by starting with an initial test t0 and tweaking each element in the state in turn. For each tweaked input, we examine the effects on the output states. We want to avoid tweaking the registers that are instantiated as operands to the instruction, as we expect those to cause changes. We really just need to learn which of the operands are inputs vs outputs, and if there are any implicit arguments. We learn the *outputs* set by comparing the tweaked input vs the output from that test vector: all modified registers are in the output set. | Tweak the value in the 'ConcreteState' at the given location to a number of random values. Right now, we only support generating random bitvectors. That will get more interesting once we start dealing with floats. Note that we could just generate random bitvectors for floats, too, but we would probably want to tweak the distribution to generate interesting types of floats.
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # module SemMC.Stochastic.IORelation.Explicit ( generateExplicitInstruction, classifyExplicitOperands ) where import qualified GHC.Err.Located as L import Control.Monad ( replicateM ) import Control.Monad.Trans ( liftIO ) import qualified Data.Foldable as F import qualified Data.Map.Strict as M import Data.Monoid import Data.Proxy ( Proxy(..) ) import qualified Data.Set as S import Text.Printf ( printf ) import qualified Data.Set.NonEmpty as NES import qualified Data.Parameterized.Classes as P import qualified Data.Parameterized.List as SL import Data.Parameterized.Some ( Some(..) ) import qualified Dismantle.Instruction as D import qualified Dismantle.Instruction.Random as D import qualified SemMC.Architecture as A import qualified SemMC.Architecture.Concrete as AC import qualified SemMC.Architecture.View as V import qualified SemMC.Concrete.Execution as CE import SemMC.Stochastic.IORelation.Shared import SemMC.Stochastic.IORelation.Types import Prelude generateExplicitInstruction :: (AC.ConcreteArchitecture arch, D.ArbitraryOperands (A.Opcode arch) (A.Operand arch)) => Proxy arch -> A.Opcode arch (A.Operand arch) sh -> [Some (V.View arch)] -> Learning arch (A.Instruction arch) generateExplicitInstruction proxy op implicitOperands = do g <- askGen insn <- liftIO $ D.randomInstruction g (NES.singleton (Some op)) case insn of D.Instruction _ ops -> case SL.ifoldr (matchesOperand proxy implicitOperands) (False, S.empty) ops of (False, sops) | S.size sops == length (instructionRegisterOperands proxy ops) -> return insn _ -> generateExplicitInstruction proxy op implicitOperands interpret the results to create an IORelation that describes the explicit classifyExplicitOperands :: (AC.ConcreteArchitecture arch, D.ArbitraryOperands (A.Opcode arch) (A.Operand arch)) => A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> Learning arch (IORelation arch sh) classifyExplicitOperands op explicitOperands = do t0 <- mkRandomTest tests <- generateExplicitTestVariants insn t0 tests' <- mapM (wrapTestBundle insn) tests results <- withTestResults op tests' computeIORelation op explicitOperands tests' results where insn = D.Instruction op explicitOperands computeIORelation :: (AC.ConcreteArchitecture arch) => A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> [TestBundle (TestCase arch) (ExplicitFact arch)] -> CE.ResultIndex (V.ConcreteState arch) -> Learning arch (IORelation arch sh) computeIORelation opcode operands bundles idx = F.foldlM (buildIORelation opcode operands idx) mempty bundles 1 ) Look up the result of the concrete run of the original test 2 ) If any of the locations referenced by the instruction change , they are buildIORelation :: forall arch sh . (AC.ConcreteArchitecture arch) => A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> CE.ResultIndex (V.ConcreteState arch) -> IORelation arch sh -> TestBundle (TestCase arch) (ExplicitFact arch) -> Learning arch (IORelation arch sh) buildIORelation op explicitOperands ri iorel tb = do case tbResult tb of ExplicitFact { lIndex = alteredIndex, lOpcode = lop } | Just P.Refl <- P.testEquality op lop -> do explicitOutputLocs <- S.unions <$> mapM (collectExplicitLocations alteredIndex explicitOperands explicitLocs ri) (tbTestCases tb) case S.null explicitOutputLocs of True -> return iorel False -> let newRel = IORelation { inputs = S.singleton (OperandRef (Some alteredIndex)) , outputs = S.fromList $ map OperandRef (F.toList explicitOutputLocs) } in return (iorel <> newRel) | otherwise -> L.error (printf "Opcode mismatch; expected %s but got %s" (P.showF op) (P.showF lop)) where explicitLocs = instructionRegisterOperands (Proxy :: Proxy arch) explicitOperands collectExplicitLocations :: (AC.ConcreteArchitecture arch) => SL.Index sh tp -> SL.List (A.Operand arch) sh -> [IndexedSemanticView arch sh] -> CE.ResultIndex (V.ConcreteState arch) -> TestCase arch -> Learning arch (S.Set (Some (SL.Index sh))) collectExplicitLocations alteredIndex _opList explicitLocs ri tc = do case M.lookup (CE.testNonce tc) (CE.riSuccesses ri) of Nothing -> return S.empty Just res -> F.foldrM (addLocIfDifferent (CE.resultContext res)) S.empty explicitLocs where addLocIfDifferent resCtx (IndexedSemanticView idx (V.SemanticView { V.semvView = opView@(V.View {}) })) s | Just P.Refl <- P.testEquality alteredIndex idx = return s | output <- V.peekMS resCtx opView , input <- V.peekMS (CE.testContext tc) opView = do case input /= output of True -> return (S.insert (Some idx) s) False -> return s generateExplicitTestVariants :: forall arch . (AC.ConcreteArchitecture arch) => A.Instruction arch -> V.ConcreteState arch -> Learning arch [TestBundle (V.ConcreteState arch) (ExplicitFact arch)] generateExplicitTestVariants i s0 = case i of D.Instruction opcode operands -> do mapM (genVar opcode) (instructionRegisterOperands (Proxy :: Proxy arch) operands) where genVar :: forall sh . A.Opcode arch (A.Operand arch) sh -> IndexedSemanticView arch sh -> Learning arch (TestBundle (V.ConcreteState arch) (ExplicitFact arch)) genVar opcode (IndexedSemanticView ix (V.SemanticView { V.semvView = view })) = do cases <- generateVariantsFor s0 opcode ix (Some view) return TestBundle { tbTestCases = cases , tbTestBase = s0 , tbResult = ExplicitFact { lOpcode = opcode , lIndex = ix , lLocation = view , lInstruction = i } } This has to be in IO so that we can generate ' 's generateVariantsFor :: (AC.ConcreteArchitecture arch) => V.ConcreteState arch -> A.Opcode arch (A.Operand arch) sh -> SL.Index sh tp -> Some (V.View arch) -> Learning arch [V.ConcreteState arch] generateVariantsFor s0 _opcode _ix (Some v@(V.View {})) = do replicateM 20 (withGeneratedValueForLocation v (\x -> V.pokeMS s0 v x)) matchesOperand :: (AC.ConcreteArchitecture arch) => Proxy arch -> [Some (V.View arch)] -> SL.Index sh tp -> A.Operand arch tp -> (Bool, S.Set (Some (V.View arch))) -> (Bool, S.Set (Some (V.View arch))) matchesOperand proxy implicits _ix operand (matches, sops) = case AC.operandToSemanticView proxy operand of Nothing -> (matches, sops) Just (V.SemanticView { V.semvView = view }) -> (matches || any (== (Some view)) implicits, S.insert (Some view) sops) Note [ Test Form ] For each explicit operand in an instruction , we generate test cases with different values for that location . The ExplicitFact records the index of the operand so that we can generate appropriate entries in the IORelation later . If changing the location causes other locations to change after the test , it means the location was an input location . At the same time , the locations that change are output locations . Note that a location can be both an input and an output . For each explicit operand in an instruction, we generate test cases with different values for that location. The ExplicitFact records the index of the operand so that we can generate appropriate entries in the IORelation later. If changing the location causes other locations to change after the test, it means the location was an input location. At the same time, the locations that change are output locations. Note that a location can be both an input and an output. -}
ecc69eff9e55028acbd708176008c66951c5c06172567aa10136dd9771b941cc
cmsc430/www
regexp-defun.rkt
#lang racket (provide accepts) type Regexp = | ' zero | ' one | ` ( char , ) | ` ( times , Regexp , Regexp ) | ` ( plus , Regexp , Regexp ) | ` ( star , Regexp ) ;; type K = ;; | '(k0) | ` ( k1 , Regexp , K ) | ` ( k2 , K , Regexp ) ;; Regexp String -> Boolean (define (accepts r s) (matcher r (string->list s) '(k0))) Regexp ( ) K - > Bool (define (matcher r cs k) (match r ['zero #f] ['one (apply-k k cs)] [`(char ,c) (match cs ['() #f] [(cons d cs) (and (char=? c d) (apply-k k cs))])] [`(plus ,r1 ,r2) (or (matcher r1 cs k) (matcher r2 cs k))] [`(times ,r1 ,r2) (matcher r1 cs `(k1 ,r2 ,k))] [`(star ,r) (apply-k `(k2 ,k ,r) cs)])) K ( ) - > Bool (define (apply-k k cs) (match k [`(k0) (empty? cs)] [`(k1 ,r2 ,k) (matcher r2 cs k)] [`(k2 ,k* ,r) (or (apply-k k* cs) (matcher r cs k))]))
null
https://raw.githubusercontent.com/cmsc430/www/fcc64c41d1b96cce6dbda49509d2f2ab8ee9f404/langs/loot/regexp-defun.rkt
racket
type K = | '(k0) Regexp String -> Boolean
#lang racket (provide accepts) type Regexp = | ' zero | ' one | ` ( char , ) | ` ( times , Regexp , Regexp ) | ` ( plus , Regexp , Regexp ) | ` ( star , Regexp ) | ` ( k1 , Regexp , K ) | ` ( k2 , K , Regexp ) (define (accepts r s) (matcher r (string->list s) '(k0))) Regexp ( ) K - > Bool (define (matcher r cs k) (match r ['zero #f] ['one (apply-k k cs)] [`(char ,c) (match cs ['() #f] [(cons d cs) (and (char=? c d) (apply-k k cs))])] [`(plus ,r1 ,r2) (or (matcher r1 cs k) (matcher r2 cs k))] [`(times ,r1 ,r2) (matcher r1 cs `(k1 ,r2 ,k))] [`(star ,r) (apply-k `(k2 ,k ,r) cs)])) K ( ) - > Bool (define (apply-k k cs) (match k [`(k0) (empty? cs)] [`(k1 ,r2 ,k) (matcher r2 cs k)] [`(k2 ,k* ,r) (or (apply-k k* cs) (matcher r cs k))]))
dd600c7c18470aacbb96b684ff94bdab5acb13e6bdfe226e03611b38cf6a30fe
GrammaTech/sel
clang-syntactic-contexts.lisp
clang-syntactic-contexts.lisp --- Clang syntactic contexts . (defpackage :software-evolution-library/test/clang-syntactic-contexts (:nicknames :sel/test/clang-syntactic-contexts) (:use :gt/full #+gt :testbot :software-evolution-library/test/util :software-evolution-library/test/util-clang :stefil+ :software-evolution-library :software-evolution-library/software/parseable :software-evolution-library/software/clang) (:export :test-clang-syntactic-contexts)) (in-package :software-evolution-library/test/clang-syntactic-contexts) (in-readtable :curry-compose-reader-macros) (defsuite test-clang-syntactic-contexts "Clang syntactic contexts." (clang-available-p)) (defvar *contexts* nil "Holds the syntactic-contexts software object.") (define-constant +contexts-dir+ (append +etc-dir+ (list "syntactic-contexts")) :test #'equalp :documentation "Path to the syntactic-contexts example.") (defun contexts-dir (filename) (make-pathname :name (pathname-name filename) :type (pathname-type filename) :directory +contexts-dir+)) (defixture contexts (:setup (setf *contexts* (from-file (make-instance 'clang :compiler "clang") (contexts-dir "contexts.c")))) (:teardown (setf *contexts* nil))) ;; Tests of basic clang mutation operators (defun count-matching-chars-in-stmt (char stmt) (let ((ast (if (listp stmt) (car stmt) stmt))) (count-if {eq char} (source-text ast)))) (defun find-function (obj name) (find-if [{string= name} #'ast-name] (functions obj))) (deftest cut-full-stmt-removes-semicolon () (with-fixture contexts (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,(stmt-with-text *contexts* "int x = 0;"))))) (is (eq 0 (count-matching-chars-in-stmt #\; (find-function *contexts* "full_stmt")))))) (deftest insert-full-stmt-adds-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (is (eq 2 (count-matching-chars-in-stmt #\; (find-function *contexts* "full_stmt")))))) (deftest insert-braced-full-stmt-does-not-add-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;")) (inserted (function-body (find-function *contexts* "list")))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,inserted))))) (is (eq 1 (count-matching-chars-in-stmt #\; (find-function *contexts* "full_stmt")))))) (deftest replace-full-stmt-does-not-add-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;")) (replacement (stmt-with-text *contexts* "int x = 1"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (eq 1 (count-matching-chars-in-stmt #\; (find-function *contexts* "full_stmt")))))) (deftest replace-full-stmt-with-braced-removes-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;")) (replacement (function-body (find-function *contexts* "list")))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (eq 0 (count-matching-chars-in-stmt #\; (find-function *contexts* "full_stmt")))))) (deftest insert-non-full-stmt-into-fullstmt-context-makes-full () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x")) (location (stmt-with-text *contexts* "if (1)" :at-start t))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,location) (:value1 . ,target)))) (is (not (ast-full-stmt target)))) (is (nest (ast-full-stmt) (first) (child-asts) (function-body) (find-function *contexts* "braced_body"))))) (deftest cut-list-elt-removes-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int b"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (starts-with-subseq "void list(int a, int c)" (source-text (find-function *contexts* "list")))))) (deftest insert-list-elt-adds-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int b"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (is (starts-with-subseq "void list(int a, int b,int b, int c)" (source-text (find-function *contexts* "list")))))) (deftest replace-list-elt-keeps-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int b")) (replacement (stmt-with-text *contexts* "int a"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (starts-with-subseq "void list(int a, int a, int c)" (source-text (find-function *contexts* "list")))))) (deftest cut-final-list-elt-removes-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int c"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (starts-with-subseq "void list(int a, int b)" (source-text (find-function *contexts* "list")))))) (deftest insert-final-list-elt-adds-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int c"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (is (starts-with-subseq "void list(int a, int b, int c,int c)" (source-text (find-function *contexts* "list")))))) (deftest replace-final-list-elt-keeps-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int c")) (replacement (stmt-with-text *contexts* "int a"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (starts-with-subseq "void list(int a, int b, int a)" (source-text (find-function *contexts* "list")))))) (deftest replace-braced-adds-braces-and-semicolon () (with-fixture contexts (let ((target (nest (second) (child-asts) (first) (child-asts) (function-body) (find-function *contexts* "braced_body"))) (replacement (stmt-with-text *contexts* "int x = 0"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (let ((function (find-function *contexts* "braced_body"))) (is (eq 2 (count-matching-chars-in-stmt #\{ function))) (is (eq 2 (count-matching-chars-in-stmt #\} function))) (is (eq 1 (count-matching-chars-in-stmt #\; function))) Braces should be part of a new CompoundStmt AST rather than ;; free-floating text. (is (eq 2 (count-if «and [{eq :CompoundStmt} #'ast-class] {ancestor-of *contexts* function}» (stmt-asts *contexts*))))))) (deftest (cut-unbraced-body-adds-nullstmt :long-running) () (with-fixture contexts (let ((target (stmt-with-text *contexts* "x = 2;"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) ;; Note -- this is no longer a good mutation, since there's a ; missing ;; Cutting statements from non-compound statement should introduce ;; a semicolon (or this should be fixed up) (is (eq 0 (count-matching-chars-in-stmt #\; (find-function *contexts* "unbraced_body")))) (is (eq :NullStmt (nest (ast-class) ; Was some->> (second) (child-asts) (stmt-with-text *contexts* "if (2)" :at-start t)))))) (deftest cut-braced-body-adds-nullstmt () (with-fixture contexts (let ((target (nest (get-parent-ast *contexts*) (stmt-with-text *contexts* "int x = 1;")))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (eq 1 (count-matching-chars-in-stmt #\; (find-function *contexts* "braced_body")))) (is (eq :NullStmt (nest (ast-class) ; Was some->> (second) (child-asts) (stmt-with-text *contexts* "if (1)" :at-start t)))))) (deftest replace-unbraced-body-keeps-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "x = 2;"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,target))))) (is (eq 1 (count-matching-chars-in-stmt #\; (find-function *contexts* "unbraced_body")))))) (deftest replace-unbraced-body-with-braced () (with-fixture contexts (let ((target (stmt-with-text *contexts* "x = 2;")) (replacement (function-body (find-function *contexts* "full_stmt")))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (let ((function (find-function *contexts* "unbraced_body"))) (is (eq 2 (count-matching-chars-in-stmt #\{ function))) (is (eq 2 (count-matching-chars-in-stmt #\} function))) (is (eq 1 (count-matching-chars-in-stmt #\; function)))))) (deftest cut-field-removes-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int f1;"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (let ((struct (stmt-with-text *contexts* "struct" :at-start t))) (is (eq 2 (count-matching-chars-in-stmt #\; struct)))))) (deftest insert-field-adds-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int f1;"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (let ((struct (stmt-with-text *contexts* "struct" :at-start t))) (is (eq 4 (count-matching-chars-in-stmt #\; struct)))))) (deftest replace-field-keeps-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int f1;")) (replacement (stmt-with-text *contexts* "int f2;"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (let ((struct (stmt-with-text *contexts* "struct" :at-start t))) (is (eq 3 (count-matching-chars-in-stmt #\; struct)))))) (deftest insert-toplevel-adds-semicolon () (with-fixture contexts (let ((location (stmt-with-text *contexts* "struct" :at-start t)) (inserted (stmt-with-text *contexts* "int x = 0;")) (semicolons (count-if {eq #\;} (genome-string *contexts*)))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,location) (:value1 . ,inserted)))) (is (eq (1+ semicolons) (count-if {eq #\;} (genome-string *contexts*))))))) (deftest insert-toplevel-braced () (with-fixture contexts (let ((location (stmt-with-text *contexts* "struct" :at-start t)) (inserted (stmt-with-text *contexts* "void list" :at-start t)) (semicolons (count-if {eq #\;} (genome-string *contexts*)))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,location) (:value1 . ,inserted)))) (is (eq semicolons (count-if {eq #\;} (genome-string *contexts*))))))) (deftest splice-asts-and-text () (with-fixture contexts (let ((location (stmt-with-text *contexts* "int x = 0;")) (inserted (list (format nil "/*comment 1*/~%") (stmt-with-text *contexts* "int x = 1" :at-start t) (format nil ";~%/*comment 2*/~%")))) (apply-mutation-ops *contexts* `((:splice (:stmt1 . ,location) (:value1 . ,inserted)))) (is (not (stmt-with-text *contexts* "int x = 0;" :no-error t))) (is (stmt-with-text *contexts* "int x = 1;" :no-error t)) (is (eq 1 (nest (length) (remove-if-not (function ast-full-stmt)) (child-asts) (function-body) (stmt-with-text *contexts* "void full_stmt" :at-start t)))) (is (search "comment 1" (genome-string *contexts*))) (is (search "comment 2" (genome-string *contexts*)))))) (deftest cut-initialization-list-preserves-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "{ 1, 2, 3 }"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (eq 1 (nest (count-matching-chars-in-stmt #\;) (find-function *contexts* "initialization_list")))))) (deftest replace-removes-trailing-semicolon-with-whitespace () (with-fixture contexts (let ((location (stmt-with-text *contexts* "MACRO" :at-start t)) (replacement (nest (first) (child-asts) (find-function *contexts* "unbraced_body")))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,location) (:value1 . ,replacement))))) (is (eq 0 (nest (count-matching-chars-in-stmt #\;) (find-function *contexts* "trailing_semi_with_whitespace"))))))
null
https://raw.githubusercontent.com/GrammaTech/sel/cd6975ad9f61a060e77d8aea0c8f74698cf8ff3e/test/clang-syntactic-contexts.lisp
lisp
Tests of basic clang mutation operators function))) free-floating text. Note -- this is no longer a good mutation, since there's a ; missing Cutting statements from non-compound statement should introduce a semicolon (or this should be fixed up) Was some->> Was some->> function)))))) struct)))))) struct)))))) struct)))))) } (genome-string *contexts*)))) } (genome-string *contexts*))))))) } (genome-string *contexts*)))) } (genome-string *contexts*))))))) ) )
clang-syntactic-contexts.lisp --- Clang syntactic contexts . (defpackage :software-evolution-library/test/clang-syntactic-contexts (:nicknames :sel/test/clang-syntactic-contexts) (:use :gt/full #+gt :testbot :software-evolution-library/test/util :software-evolution-library/test/util-clang :stefil+ :software-evolution-library :software-evolution-library/software/parseable :software-evolution-library/software/clang) (:export :test-clang-syntactic-contexts)) (in-package :software-evolution-library/test/clang-syntactic-contexts) (in-readtable :curry-compose-reader-macros) (defsuite test-clang-syntactic-contexts "Clang syntactic contexts." (clang-available-p)) (defvar *contexts* nil "Holds the syntactic-contexts software object.") (define-constant +contexts-dir+ (append +etc-dir+ (list "syntactic-contexts")) :test #'equalp :documentation "Path to the syntactic-contexts example.") (defun contexts-dir (filename) (make-pathname :name (pathname-name filename) :type (pathname-type filename) :directory +contexts-dir+)) (defixture contexts (:setup (setf *contexts* (from-file (make-instance 'clang :compiler "clang") (contexts-dir "contexts.c")))) (:teardown (setf *contexts* nil))) (defun count-matching-chars-in-stmt (char stmt) (let ((ast (if (listp stmt) (car stmt) stmt))) (count-if {eq char} (source-text ast)))) (defun find-function (obj name) (find-if [{string= name} #'ast-name] (functions obj))) (deftest cut-full-stmt-removes-semicolon () (with-fixture contexts (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,(stmt-with-text *contexts* "int x = 0;"))))) (is (eq 0 (count-matching-chars-in-stmt (find-function *contexts* "full_stmt")))))) (deftest insert-full-stmt-adds-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (is (eq 2 (count-matching-chars-in-stmt (find-function *contexts* "full_stmt")))))) (deftest insert-braced-full-stmt-does-not-add-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;")) (inserted (function-body (find-function *contexts* "list")))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,inserted))))) (is (eq 1 (count-matching-chars-in-stmt (find-function *contexts* "full_stmt")))))) (deftest replace-full-stmt-does-not-add-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;")) (replacement (stmt-with-text *contexts* "int x = 1"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (eq 1 (count-matching-chars-in-stmt (find-function *contexts* "full_stmt")))))) (deftest replace-full-stmt-with-braced-removes-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x = 0;")) (replacement (function-body (find-function *contexts* "list")))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (eq 0 (count-matching-chars-in-stmt (find-function *contexts* "full_stmt")))))) (deftest insert-non-full-stmt-into-fullstmt-context-makes-full () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int x")) (location (stmt-with-text *contexts* "if (1)" :at-start t))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,location) (:value1 . ,target)))) (is (not (ast-full-stmt target)))) (is (nest (ast-full-stmt) (first) (child-asts) (function-body) (find-function *contexts* "braced_body"))))) (deftest cut-list-elt-removes-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int b"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (starts-with-subseq "void list(int a, int c)" (source-text (find-function *contexts* "list")))))) (deftest insert-list-elt-adds-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int b"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (is (starts-with-subseq "void list(int a, int b,int b, int c)" (source-text (find-function *contexts* "list")))))) (deftest replace-list-elt-keeps-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int b")) (replacement (stmt-with-text *contexts* "int a"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (starts-with-subseq "void list(int a, int a, int c)" (source-text (find-function *contexts* "list")))))) (deftest cut-final-list-elt-removes-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int c"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (starts-with-subseq "void list(int a, int b)" (source-text (find-function *contexts* "list")))))) (deftest insert-final-list-elt-adds-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int c"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (is (starts-with-subseq "void list(int a, int b, int c,int c)" (source-text (find-function *contexts* "list")))))) (deftest replace-final-list-elt-keeps-comma () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int c")) (replacement (stmt-with-text *contexts* "int a"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (is (starts-with-subseq "void list(int a, int b, int a)" (source-text (find-function *contexts* "list")))))) (deftest replace-braced-adds-braces-and-semicolon () (with-fixture contexts (let ((target (nest (second) (child-asts) (first) (child-asts) (function-body) (find-function *contexts* "braced_body"))) (replacement (stmt-with-text *contexts* "int x = 0"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (let ((function (find-function *contexts* "braced_body"))) (is (eq 2 (count-matching-chars-in-stmt #\{ function))) (is (eq 2 (count-matching-chars-in-stmt #\} function))) Braces should be part of a new CompoundStmt AST rather than (is (eq 2 (count-if «and [{eq :CompoundStmt} #'ast-class] {ancestor-of *contexts* function}» (stmt-asts *contexts*))))))) (deftest (cut-unbraced-body-adds-nullstmt :long-running) () (with-fixture contexts (let ((target (stmt-with-text *contexts* "x = 2;"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (eq 0 (count-matching-chars-in-stmt (find-function *contexts* "unbraced_body")))) (is (eq :NullStmt (second) (child-asts) (stmt-with-text *contexts* "if (2)" :at-start t)))))) (deftest cut-braced-body-adds-nullstmt () (with-fixture contexts (let ((target (nest (get-parent-ast *contexts*) (stmt-with-text *contexts* "int x = 1;")))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (is (eq 1 (count-matching-chars-in-stmt (find-function *contexts* "braced_body")))) (is (eq :NullStmt (second) (child-asts) (stmt-with-text *contexts* "if (1)" :at-start t)))))) (deftest replace-unbraced-body-keeps-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "x = 2;"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,target))))) (is (eq 1 (count-matching-chars-in-stmt (find-function *contexts* "unbraced_body")))))) (deftest replace-unbraced-body-with-braced () (with-fixture contexts (let ((target (stmt-with-text *contexts* "x = 2;")) (replacement (function-body (find-function *contexts* "full_stmt")))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (let ((function (find-function *contexts* "unbraced_body"))) (is (eq 2 (count-matching-chars-in-stmt #\{ function))) (is (eq 2 (count-matching-chars-in-stmt #\} function))) (deftest cut-field-removes-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int f1;"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (let ((struct (stmt-with-text *contexts* "struct" :at-start t))) (is (eq 2 (deftest insert-field-adds-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int f1;"))) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,target) (:value1 . ,target))))) (let ((struct (stmt-with-text *contexts* "struct" :at-start t))) (is (eq 4 (deftest replace-field-keeps-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "int f1;")) (replacement (stmt-with-text *contexts* "int f2;"))) (apply-mutation-ops *contexts* `((:set (:stmt1 . ,target) (:value1 . ,replacement))))) (let ((struct (stmt-with-text *contexts* "struct" :at-start t))) (is (eq 3 (deftest insert-toplevel-adds-semicolon () (with-fixture contexts (let ((location (stmt-with-text *contexts* "struct" :at-start t)) (inserted (stmt-with-text *contexts* "int x = 0;")) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,location) (:value1 . ,inserted)))) (is (eq (1+ semicolons) (deftest insert-toplevel-braced () (with-fixture contexts (let ((location (stmt-with-text *contexts* "struct" :at-start t)) (inserted (stmt-with-text *contexts* "void list" :at-start t)) (apply-mutation-ops *contexts* `((:insert (:stmt1 . ,location) (:value1 . ,inserted)))) (is (eq semicolons (deftest splice-asts-and-text () (with-fixture contexts (let ((location (stmt-with-text *contexts* "int x = 0;")) (inserted (list (format nil "/*comment 1*/~%") (stmt-with-text *contexts* "int x = 1" :at-start t) (format nil ";~%/*comment 2*/~%")))) (apply-mutation-ops *contexts* `((:splice (:stmt1 . ,location) (:value1 . ,inserted)))) (is (not (stmt-with-text *contexts* "int x = 0;" :no-error t))) (is (stmt-with-text *contexts* "int x = 1;" :no-error t)) (is (eq 1 (nest (length) (remove-if-not (function ast-full-stmt)) (child-asts) (function-body) (stmt-with-text *contexts* "void full_stmt" :at-start t)))) (is (search "comment 1" (genome-string *contexts*))) (is (search "comment 2" (genome-string *contexts*)))))) (deftest cut-initialization-list-preserves-semicolon () (with-fixture contexts (let ((target (stmt-with-text *contexts* "{ 1, 2, 3 }"))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,target))))) (find-function *contexts* "initialization_list")))))) (deftest replace-removes-trailing-semicolon-with-whitespace () (with-fixture contexts (let ((location (stmt-with-text *contexts* "MACRO" :at-start t)) (replacement (nest (first) (child-asts) (find-function *contexts* "unbraced_body")))) (apply-mutation-ops *contexts* `((:cut (:stmt1 . ,location) (:value1 . ,replacement))))) (is (eq 0 (nest (find-function *contexts* "trailing_semi_with_whitespace"))))))
d6a219f413bbaa3cd628b797f0fd864d991c2b0545ed259b2284d872d14aaeaa
leandrosilva/cameron
eh_supervisor.erl
@author < > 2011 . %% @doc Utility functions to supervisor modules. -module(eh_supervisor). -author('Leandro Silva <>'). % public api -export([upgrade/1]). %% %% Public API ------------------------------------------------------------------------------------- %% ) - > ok %% @doc Remover and add processes if necessary. upgrade(Supervisor) -> {ok, {_, Specs}} = Supervisor:init([]), Old = sets:from_list([Name || {Name, _, _, _} <- supervisor:which_children(Supervisor)]), New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]), % kill children processes that doesn't exists anymore % I mean, they exist in the Old spec but no longer in the New spec Kill = sets:subtract(Old, New), sets:fold(fun (Id, ok) -> supervisor:terminate_child(Supervisor, Id), supervisor:delete_child(Supervisor, Id), ok end, ok, Kill), [supervisor:start_child(Supervisor, Spec) || Spec <- Specs], ok.
null
https://raw.githubusercontent.com/leandrosilva/cameron/34051395b620d2c3cb2cb63c854e65234786a176/deps/erl_helpers/src/eh_supervisor.erl
erlang
@doc Utility functions to supervisor modules. public api Public API ------------------------------------------------------------------------------------- @doc Remover and add processes if necessary. kill children processes that doesn't exists anymore I mean, they exist in the Old spec but no longer in the New spec
@author < > 2011 . -module(eh_supervisor). -author('Leandro Silva <>'). -export([upgrade/1]). ) - > ok upgrade(Supervisor) -> {ok, {_, Specs}} = Supervisor:init([]), Old = sets:from_list([Name || {Name, _, _, _} <- supervisor:which_children(Supervisor)]), New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]), Kill = sets:subtract(Old, New), sets:fold(fun (Id, ok) -> supervisor:terminate_child(Supervisor, Id), supervisor:delete_child(Supervisor, Id), ok end, ok, Kill), [supervisor:start_child(Supervisor, Spec) || Spec <- Specs], ok.
f41c8c09d39299d514907a11a5f1d79e79f430c6493759a51e0d6bee6b14cefe
funcool/promesa
util.cljc
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; Copyright ( c ) < > (ns promesa.util (:require [promesa.protocols :as pt]) #?(:clj (:import java.lang.reflect.Method java.time.Duration java.util.concurrent.CompletionException java.util.concurrent.CompletionStage java.util.concurrent.CountDownLatch java.util.concurrent.locks.ReentrantLock java.util.function . BiConsumer ;; java.util.function.BiFunction ;; java.util.function.Consumer ;; java.util.function.Function ;; java.util.function.Supplier ))) #?(:clj (set! *warn-on-reflection* true)) #?(:clj (extend-protocol clojure.core/Inst Duration (inst-ms* [v] (.toMillis ^Duration v)))) #?(:clj (deftype Supplier [f] java.util.function.Supplier (get [_] (f)))) #?(:clj (deftype Function [f] java.util.function.Function (apply [_ v] (f v)))) #?(:clj (def f-identity (->Function identity))) #?(:clj (defn unwrap-completion-stage {:no-doc true} [it] (.thenCompose ^CompletionStage it ^java.util.function.Function f-identity))) #?(:clj (defn unwrap-completion-exception {:no-doc true} [cause] (if (instance? CompletionException cause) (.getCause ^CompletionException cause) cause))) #?(:clj (deftype Function2 [f] java.util.function.BiFunction (apply [_ r e] (f r (unwrap-completion-exception e))))) #?(:clj (deftype Consumer2 [f] java.util.function.BiConsumer (accept [_ r e] (f r (unwrap-completion-exception e))))) (defn handler "Create a handler, mainly for combine two separate functions into a single callbale." [fv fc] (fn [v c] (if c (fc c) (fv v)))) (defn has-method? {:no-doc true} [klass name] (let [methods (into #{} (map (fn [method] (.getName ^Method method))) (.getDeclaredMethods ^Class klass))] (contains? methods name))) (defn maybe-deref {:no-doc true} [o] (if (delay? o) (deref o) o)) (defn mutex {:no-doc true} [] #?(:clj (let [m (ReentrantLock.)] (reify pt/ILock (-lock! [_] (.lock m)) (-unlock! [_] (.unlock m)))) :cljs (reify pt/ILock (-lock! [_]) (-unlock! [_])))) (defn try* {:no-doc true} [f on-error] (try (f) (catch #?(:clj Throwable :cljs :default) e (on-error e)))) -me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/ ;; Explains the use of ^:once metadata (defmacro ignoring [& exprs] `(try* (^:once fn* [] ~@exprs) (constantly nil))) (defmacro try! [& exprs] `(try* (^:once fn* [] ~@exprs) identity))
null
https://raw.githubusercontent.com/funcool/promesa/19491a4ea476f80ae741c6d8072c1a4612b1b654/src/promesa/util.cljc
clojure
java.util.function.BiFunction java.util.function.Consumer java.util.function.Function java.util.function.Supplier Explains the use of ^:once metadata
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) < > (ns promesa.util (:require [promesa.protocols :as pt]) #?(:clj (:import java.lang.reflect.Method java.time.Duration java.util.concurrent.CompletionException java.util.concurrent.CompletionStage java.util.concurrent.CountDownLatch java.util.concurrent.locks.ReentrantLock java.util.function . BiConsumer ))) #?(:clj (set! *warn-on-reflection* true)) #?(:clj (extend-protocol clojure.core/Inst Duration (inst-ms* [v] (.toMillis ^Duration v)))) #?(:clj (deftype Supplier [f] java.util.function.Supplier (get [_] (f)))) #?(:clj (deftype Function [f] java.util.function.Function (apply [_ v] (f v)))) #?(:clj (def f-identity (->Function identity))) #?(:clj (defn unwrap-completion-stage {:no-doc true} [it] (.thenCompose ^CompletionStage it ^java.util.function.Function f-identity))) #?(:clj (defn unwrap-completion-exception {:no-doc true} [cause] (if (instance? CompletionException cause) (.getCause ^CompletionException cause) cause))) #?(:clj (deftype Function2 [f] java.util.function.BiFunction (apply [_ r e] (f r (unwrap-completion-exception e))))) #?(:clj (deftype Consumer2 [f] java.util.function.BiConsumer (accept [_ r e] (f r (unwrap-completion-exception e))))) (defn handler "Create a handler, mainly for combine two separate functions into a single callbale." [fv fc] (fn [v c] (if c (fc c) (fv v)))) (defn has-method? {:no-doc true} [klass name] (let [methods (into #{} (map (fn [method] (.getName ^Method method))) (.getDeclaredMethods ^Class klass))] (contains? methods name))) (defn maybe-deref {:no-doc true} [o] (if (delay? o) (deref o) o)) (defn mutex {:no-doc true} [] #?(:clj (let [m (ReentrantLock.)] (reify pt/ILock (-lock! [_] (.lock m)) (-unlock! [_] (.unlock m)))) :cljs (reify pt/ILock (-lock! [_]) (-unlock! [_])))) (defn try* {:no-doc true} [f on-error] (try (f) (catch #?(:clj Throwable :cljs :default) e (on-error e)))) -me.cgrand.net/2013/09/11/macros-closures-and-unexpected-object-retention/ (defmacro ignoring [& exprs] `(try* (^:once fn* [] ~@exprs) (constantly nil))) (defmacro try! [& exprs] `(try* (^:once fn* [] ~@exprs) identity))
5f16df6f7b8d3fd8078147cafeda92792f5c3895b22d0b04411b7ca56800e2b3
pokepay/aws-sdk-lisp
api.lisp
;; DO NOT EDIT: File is generated by AWS-SDK/GENERATOR. (common-lisp:defpackage #:aws-sdk/services/codecommit/api (:use) (:nicknames #:aws/codecommit) (:import-from #:aws-sdk/generator/shape) (:import-from #:aws-sdk/generator/operation) (:import-from #:aws-sdk/api) (:import-from #:aws-sdk/request) (:import-from #:aws-sdk/error)) (common-lisp:in-package #:aws-sdk/services/codecommit/api) (common-lisp:progn (common-lisp:defclass codecommit-request (aws-sdk/request:request) common-lisp:nil (:default-initargs :service "codecommit")) (common-lisp:export 'codecommit-request)) (common-lisp:progn (common-lisp:define-condition codecommit-error (aws-sdk/error:aws-error) common-lisp:nil) (common-lisp:export 'codecommit-error)) (common-lisp:defvar *error-map* '(("BlobIdDoesNotExistException" . blob-id-does-not-exist-exception) ("BlobIdRequiredException" . blob-id-required-exception) ("BranchDoesNotExistException" . branch-does-not-exist-exception) ("BranchNameExistsException" . branch-name-exists-exception) ("BranchNameRequiredException" . branch-name-required-exception) ("CommitDoesNotExistException" . commit-does-not-exist-exception) ("CommitIdDoesNotExistException" . commit-id-does-not-exist-exception) ("CommitIdRequiredException" . commit-id-required-exception) ("CommitRequiredException" . commit-required-exception) ("EncryptionIntegrityChecksFailedException" . encryption-integrity-checks-failed-exception) ("EncryptionKeyAccessDeniedException" . encryption-key-access-denied-exception) ("EncryptionKeyDisabledException" . encryption-key-disabled-exception) ("EncryptionKeyNotFoundException" . encryption-key-not-found-exception) ("EncryptionKeyUnavailableException" . encryption-key-unavailable-exception) ("FileTooLargeException" . file-too-large-exception) ("InvalidBlobIdException" . invalid-blob-id-exception) ("InvalidBranchNameException" . invalid-branch-name-exception) ("InvalidCommitException" . invalid-commit-exception) ("InvalidCommitIdException" . invalid-commit-id-exception) ("InvalidContinuationTokenException" . invalid-continuation-token-exception) ("InvalidMaxResultsException" . invalid-max-results-exception) ("InvalidOrderException" . invalid-order-exception) ("InvalidPathException" . invalid-path-exception) ("InvalidRepositoryDescriptionException" . invalid-repository-description-exception) ("InvalidRepositoryNameException" . invalid-repository-name-exception) ("InvalidRepositoryTriggerBranchNameException" . invalid-repository-trigger-branch-name-exception) ("InvalidRepositoryTriggerCustomDataException" . invalid-repository-trigger-custom-data-exception) ("InvalidRepositoryTriggerDestinationArnException" . invalid-repository-trigger-destination-arn-exception) ("InvalidRepositoryTriggerEventsException" . invalid-repository-trigger-events-exception) ("InvalidRepositoryTriggerNameException" . invalid-repository-trigger-name-exception) ("InvalidRepositoryTriggerRegionException" . invalid-repository-trigger-region-exception) ("InvalidSortByException" . invalid-sort-by-exception) ("MaximumBranchesExceededException" . maximum-branches-exceeded-exception) ("MaximumRepositoryNamesExceededException" . maximum-repository-names-exceeded-exception) ("MaximumRepositoryTriggersExceededException" . maximum-repository-triggers-exceeded-exception) ("PathDoesNotExistException" . path-does-not-exist-exception) ("RepositoryDoesNotExistException" . repository-does-not-exist-exception) ("RepositoryLimitExceededException" . repository-limit-exceeded-exception) ("RepositoryNameExistsException" . repository-name-exists-exception) ("RepositoryNameRequiredException" . repository-name-required-exception) ("RepositoryNamesRequiredException" . repository-names-required-exception) ("RepositoryTriggerBranchNameListRequiredException" . repository-trigger-branch-name-list-required-exception) ("RepositoryTriggerDestinationArnRequiredException" . repository-trigger-destination-arn-required-exception) ("RepositoryTriggerEventsListRequiredException" . repository-trigger-events-list-required-exception) ("RepositoryTriggerNameRequiredException" . repository-trigger-name-required-exception) ("RepositoryTriggersListRequiredException" . repository-triggers-list-required-exception))) (common-lisp:deftype account-id () 'common-lisp:string) (common-lisp:deftype additional-data () 'common-lisp:string) (common-lisp:deftype arn () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (batch-get-repositories-input (:copier common-lisp:nil) (:conc-name "struct-shape-batch-get-repositories-input-")) (repository-names (common-lisp:error ":repositorynames is required") :type (common-lisp:or repository-name-list common-lisp:null))) (common-lisp:export (common-lisp:list 'batch-get-repositories-input 'make-batch-get-repositories-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input batch-get-repositories-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input batch-get-repositories-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-names)) (common-lisp:list (common-lisp:cons "repositoryNames" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input batch-get-repositories-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (batch-get-repositories-output (:copier common-lisp:nil) (:conc-name "struct-shape-batch-get-repositories-output-")) (repositories common-lisp:nil :type (common-lisp:or repository-metadata-list common-lisp:null)) (repositories-not-found common-lisp:nil :type (common-lisp:or repository-not-found-list common-lisp:null))) (common-lisp:export (common-lisp:list 'batch-get-repositories-output 'make-batch-get-repositories-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input batch-get-repositories-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input batch-get-repositories-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repositories)) (common-lisp:list (common-lisp:cons "repositories" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repositories-not-found)) (common-lisp:list (common-lisp:cons "repositoriesNotFound" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input batch-get-repositories-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition blob-id-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'blob-id-does-not-exist-exception))) (common-lisp:progn (common-lisp:define-condition blob-id-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'blob-id-required-exception))) (common-lisp:progn (common-lisp:defstruct (blob-metadata (:copier common-lisp:nil) (:conc-name "struct-shape-blob-metadata-")) (blob-id common-lisp:nil :type (common-lisp:or object-id common-lisp:null)) (path common-lisp:nil :type (common-lisp:or path common-lisp:null)) (mode common-lisp:nil :type (common-lisp:or mode common-lisp:null))) (common-lisp:export (common-lisp:list 'blob-metadata 'make-blob-metadata)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input blob-metadata)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input blob-metadata)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'blob-id)) (common-lisp:list (common-lisp:cons "blobId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'path)) (common-lisp:list (common-lisp:cons "path" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'mode)) (common-lisp:list (common-lisp:cons "mode" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input blob-metadata)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition branch-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'branch-does-not-exist-exception))) (common-lisp:progn (common-lisp:defstruct (branch-info (:copier common-lisp:nil) (:conc-name "struct-shape-branch-info-")) (branch-name common-lisp:nil :type (common-lisp:or branch-name common-lisp:null)) (commit-id common-lisp:nil :type (common-lisp:or commit-id common-lisp:null))) (common-lisp:export (common-lisp:list 'branch-info 'make-branch-info)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input branch-info)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input branch-info)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch-name)) (common-lisp:list (common-lisp:cons "branchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit-id)) (common-lisp:list (common-lisp:cons "commitId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input branch-info)) common-lisp:nil)) (common-lisp:deftype branch-name () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition branch-name-exists-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'branch-name-exists-exception))) (common-lisp:progn (common-lisp:deftype branch-name-list () '(trivial-types:proper-list branch-name)) (common-lisp:defun |make-branch-name-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list branch-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition branch-name-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'branch-name-required-exception))) (common-lisp:deftype change-type-enum () 'common-lisp:string) (common-lisp:deftype clone-url-http () 'common-lisp:string) (common-lisp:deftype clone-url-ssh () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (commit (:copier common-lisp:nil) (:conc-name "struct-shape-commit-")) (tree-id common-lisp:nil :type (common-lisp:or object-id common-lisp:null)) (parents common-lisp:nil :type (common-lisp:or parent-list common-lisp:null)) (message common-lisp:nil :type (common-lisp:or message common-lisp:null)) (author common-lisp:nil :type (common-lisp:or user-info common-lisp:null)) (committer common-lisp:nil :type (common-lisp:or user-info common-lisp:null)) (additional-data common-lisp:nil :type (common-lisp:or additional-data common-lisp:null))) (common-lisp:export (common-lisp:list 'commit 'make-commit)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input commit)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input commit)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'tree-id)) (common-lisp:list (common-lisp:cons "treeId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'parents)) (common-lisp:list (common-lisp:cons "parents" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'message)) (common-lisp:list (common-lisp:cons "message" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'author)) (common-lisp:list (common-lisp:cons "author" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'committer)) (common-lisp:list (common-lisp:cons "committer" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'additional-data)) (common-lisp:list (common-lisp:cons "additionalData" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input commit)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition commit-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-does-not-exist-exception))) (common-lisp:deftype commit-id () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition commit-id-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-id-does-not-exist-exception))) (common-lisp:progn (common-lisp:define-condition commit-id-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-id-required-exception))) (common-lisp:deftype commit-name () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition commit-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-required-exception))) (common-lisp:progn (common-lisp:defstruct (create-branch-input (:copier common-lisp:nil) (:conc-name "struct-shape-create-branch-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (branch-name (common-lisp:error ":branchname is required") :type (common-lisp:or branch-name common-lisp:null)) (commit-id (common-lisp:error ":commitid is required") :type (common-lisp:or commit-id common-lisp:null))) (common-lisp:export (common-lisp:list 'create-branch-input 'make-create-branch-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input create-branch-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input create-branch-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch-name)) (common-lisp:list (common-lisp:cons "branchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit-id)) (common-lisp:list (common-lisp:cons "commitId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input create-branch-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (create-repository-input (:copier common-lisp:nil) (:conc-name "struct-shape-create-repository-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (repository-description common-lisp:nil :type (common-lisp:or repository-description common-lisp:null))) (common-lisp:export (common-lisp:list 'create-repository-input 'make-create-repository-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input create-repository-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input create-repository-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-description)) (common-lisp:list (common-lisp:cons "repositoryDescription" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input create-repository-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (create-repository-output (:copier common-lisp:nil) (:conc-name "struct-shape-create-repository-output-")) (repository-metadata common-lisp:nil :type (common-lisp:or repository-metadata common-lisp:null))) (common-lisp:export (common-lisp:list 'create-repository-output 'make-create-repository-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input create-repository-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input create-repository-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-metadata)) (common-lisp:list (common-lisp:cons "repositoryMetadata" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input create-repository-output)) common-lisp:nil)) (common-lisp:deftype creation-date () 'common-lisp:string) (common-lisp:deftype date () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (delete-repository-input (:copier common-lisp:nil) (:conc-name "struct-shape-delete-repository-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'delete-repository-input 'make-delete-repository-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input delete-repository-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input delete-repository-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input delete-repository-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (delete-repository-output (:copier common-lisp:nil) (:conc-name "struct-shape-delete-repository-output-")) (repository-id common-lisp:nil :type (common-lisp:or repository-id common-lisp:null))) (common-lisp:export (common-lisp:list 'delete-repository-output 'make-delete-repository-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input delete-repository-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input delete-repository-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-id)) (common-lisp:list (common-lisp:cons "repositoryId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input delete-repository-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (difference (:copier common-lisp:nil) (:conc-name "struct-shape-difference-")) (before-blob common-lisp:nil :type (common-lisp:or blob-metadata common-lisp:null)) (after-blob common-lisp:nil :type (common-lisp:or blob-metadata common-lisp:null)) (change-type common-lisp:nil :type (common-lisp:or change-type-enum common-lisp:null))) (common-lisp:export (common-lisp:list 'difference 'make-difference)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input difference)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input difference)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'before-blob)) (common-lisp:list (common-lisp:cons "beforeBlob" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'after-blob)) (common-lisp:list (common-lisp:cons "afterBlob" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'change-type)) (common-lisp:list (common-lisp:cons "changeType" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input difference)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype difference-list () '(trivial-types:proper-list difference)) (common-lisp:defun |make-difference-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list difference)) aws-sdk/generator/shape::members)) (common-lisp:deftype email () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition encryption-integrity-checks-failed-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-integrity-checks-failed-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-access-denied-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-access-denied-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-disabled-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-disabled-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-not-found-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-not-found-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-unavailable-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-unavailable-exception))) (common-lisp:progn (common-lisp:define-condition file-too-large-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'file-too-large-exception))) (common-lisp:progn (common-lisp:defstruct (get-blob-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-blob-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (blob-id (common-lisp:error ":blobid is required") :type (common-lisp:or object-id common-lisp:null))) (common-lisp:export (common-lisp:list 'get-blob-input 'make-get-blob-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-blob-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-blob-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'blob-id)) (common-lisp:list (common-lisp:cons "blobId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-blob-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-blob-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-blob-output-")) (content (common-lisp:error ":content is required") :type (common-lisp:or (common-lisp:simple-array (common-lisp:unsigned-byte 8) (common-lisp:*)) common-lisp:null))) (common-lisp:export (common-lisp:list 'get-blob-output 'make-get-blob-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-blob-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-blob-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'content)) (common-lisp:list (common-lisp:cons "content" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-blob-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-branch-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-branch-input-")) (repository-name common-lisp:nil :type (common-lisp:or repository-name common-lisp:null)) (branch-name common-lisp:nil :type (common-lisp:or branch-name common-lisp:null))) (common-lisp:export (common-lisp:list 'get-branch-input 'make-get-branch-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-branch-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-branch-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch-name)) (common-lisp:list (common-lisp:cons "branchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-branch-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-branch-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-branch-output-")) (branch common-lisp:nil :type (common-lisp:or branch-info common-lisp:null))) (common-lisp:export (common-lisp:list 'get-branch-output 'make-get-branch-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-branch-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-branch-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch)) (common-lisp:list (common-lisp:cons "branch" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-branch-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-commit-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-commit-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (commit-id (common-lisp:error ":commitid is required") :type (common-lisp:or object-id common-lisp:null))) (common-lisp:export (common-lisp:list 'get-commit-input 'make-get-commit-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-commit-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-commit-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit-id)) (common-lisp:list (common-lisp:cons "commitId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-commit-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-commit-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-commit-output-")) (commit (common-lisp:error ":commit is required") :type (common-lisp:or commit common-lisp:null))) (common-lisp:export (common-lisp:list 'get-commit-output 'make-get-commit-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-commit-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-commit-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit)) (common-lisp:list (common-lisp:cons "commit" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-commit-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-differences-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-differences-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (before-commit-specifier common-lisp:nil :type (common-lisp:or commit-name common-lisp:null)) (after-commit-specifier (common-lisp:error ":aftercommitspecifier is required") :type (common-lisp:or commit-name common-lisp:null)) (before-path common-lisp:nil :type (common-lisp:or path common-lisp:null)) (after-path common-lisp:nil :type (common-lisp:or path common-lisp:null)) (max-results common-lisp:nil :type (common-lisp:or limit common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'get-differences-input 'make-get-differences-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-differences-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-differences-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'before-commit-specifier)) (common-lisp:list (common-lisp:cons "beforeCommitSpecifier" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'after-commit-specifier)) (common-lisp:list (common-lisp:cons "afterCommitSpecifier" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'before-path)) (common-lisp:list (common-lisp:cons "beforePath" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'after-path)) (common-lisp:list (common-lisp:cons "afterPath" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'max-results)) (common-lisp:list (common-lisp:cons "MaxResults" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "NextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-differences-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-differences-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-differences-output-")) (differences common-lisp:nil :type (common-lisp:or difference-list common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'get-differences-output 'make-get-differences-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-differences-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-differences-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'differences)) (common-lisp:list (common-lisp:cons "differences" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "NextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-differences-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-input 'make-get-repository-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-repository-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-repository-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-repository-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-output-")) (repository-metadata common-lisp:nil :type (common-lisp:or repository-metadata common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-output 'make-get-repository-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-repository-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-repository-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-metadata)) (common-lisp:list (common-lisp:cons "repositoryMetadata" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-repository-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-triggers-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-triggers-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-triggers-input 'make-get-repository-triggers-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-repository-triggers-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-repository-triggers-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-repository-triggers-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-triggers-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-triggers-output-")) (configuration-id common-lisp:nil :type (common-lisp:or repository-triggers-configuration-id common-lisp:null)) (triggers common-lisp:nil :type (common-lisp:or repository-triggers-list common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-triggers-output 'make-get-repository-triggers-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-repository-triggers-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-repository-triggers-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'configuration-id)) (common-lisp:list (common-lisp:cons "configurationId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'triggers)) (common-lisp:list (common-lisp:cons "triggers" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-repository-triggers-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition invalid-blob-id-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-blob-id-exception))) (common-lisp:progn (common-lisp:define-condition invalid-branch-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-branch-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-commit-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-commit-exception))) (common-lisp:progn (common-lisp:define-condition invalid-commit-id-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-commit-id-exception))) (common-lisp:progn (common-lisp:define-condition invalid-continuation-token-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-continuation-token-exception))) (common-lisp:progn (common-lisp:define-condition invalid-max-results-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-max-results-exception))) (common-lisp:progn (common-lisp:define-condition invalid-order-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-order-exception))) (common-lisp:progn (common-lisp:define-condition invalid-path-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-path-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-description-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-description-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-branch-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-branch-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-custom-data-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-custom-data-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-destination-arn-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-destination-arn-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-events-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-events-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-region-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-region-exception))) (common-lisp:progn (common-lisp:define-condition invalid-sort-by-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-sort-by-exception))) (common-lisp:deftype last-modified-date () 'common-lisp:string) (common-lisp:deftype limit () 'common-lisp:integer) (common-lisp:progn (common-lisp:defstruct (list-branches-input (:copier common-lisp:nil) (:conc-name "struct-shape-list-branches-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'list-branches-input 'make-list-branches-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input list-branches-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input list-branches-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input list-branches-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (list-branches-output (:copier common-lisp:nil) (:conc-name "struct-shape-list-branches-output-")) (branches common-lisp:nil :type (common-lisp:or branch-name-list common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'list-branches-output 'make-list-branches-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input list-branches-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input list-branches-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branches)) (common-lisp:list (common-lisp:cons "branches" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input list-branches-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (list-repositories-input (:copier common-lisp:nil) (:conc-name "struct-shape-list-repositories-input-")) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null)) (sort-by common-lisp:nil :type (common-lisp:or sort-by-enum common-lisp:null)) (order common-lisp:nil :type (common-lisp:or order-enum common-lisp:null))) (common-lisp:export (common-lisp:list 'list-repositories-input 'make-list-repositories-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input list-repositories-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input list-repositories-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'sort-by)) (common-lisp:list (common-lisp:cons "sortBy" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'order)) (common-lisp:list (common-lisp:cons "order" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input list-repositories-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (list-repositories-output (:copier common-lisp:nil) (:conc-name "struct-shape-list-repositories-output-")) (repositories common-lisp:nil :type (common-lisp:or repository-name-id-pair-list common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'list-repositories-output 'make-list-repositories-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input list-repositories-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input list-repositories-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repositories)) (common-lisp:list (common-lisp:cons "repositories" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input list-repositories-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition maximum-branches-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'maximum-branches-exceeded-exception))) (common-lisp:progn (common-lisp:define-condition maximum-repository-names-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'maximum-repository-names-exceeded-exception))) (common-lisp:progn (common-lisp:define-condition maximum-repository-triggers-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'maximum-repository-triggers-exceeded-exception))) (common-lisp:deftype message () 'common-lisp:string) (common-lisp:deftype mode () 'common-lisp:string) (common-lisp:deftype name () 'common-lisp:string) (common-lisp:deftype next-token () 'common-lisp:string) (common-lisp:deftype object-id () 'common-lisp:string) (common-lisp:deftype order-enum () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype parent-list () '(trivial-types:proper-list object-id)) (common-lisp:defun |make-parent-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list object-id)) aws-sdk/generator/shape::members)) (common-lisp:deftype path () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition path-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'path-does-not-exist-exception))) (common-lisp:progn (common-lisp:defstruct (put-repository-triggers-input (:copier common-lisp:nil) (:conc-name "struct-shape-put-repository-triggers-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (triggers (common-lisp:error ":triggers is required") :type (common-lisp:or repository-triggers-list common-lisp:null))) (common-lisp:export (common-lisp:list 'put-repository-triggers-input 'make-put-repository-triggers-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input put-repository-triggers-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input put-repository-triggers-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'triggers)) (common-lisp:list (common-lisp:cons "triggers" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input put-repository-triggers-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (put-repository-triggers-output (:copier common-lisp:nil) (:conc-name "struct-shape-put-repository-triggers-output-")) (configuration-id common-lisp:nil :type (common-lisp:or repository-triggers-configuration-id common-lisp:null))) (common-lisp:export (common-lisp:list 'put-repository-triggers-output 'make-put-repository-triggers-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input put-repository-triggers-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input put-repository-triggers-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'configuration-id)) (common-lisp:list (common-lisp:cons "configurationId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input put-repository-triggers-output)) common-lisp:nil)) (common-lisp:deftype repository-description () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-does-not-exist-exception))) (common-lisp:deftype repository-id () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-limit-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-limit-exceeded-exception))) (common-lisp:progn (common-lisp:defstruct (repository-metadata (:copier common-lisp:nil) (:conc-name "struct-shape-repository-metadata-")) (account-id common-lisp:nil :type (common-lisp:or account-id common-lisp:null)) (repository-id common-lisp:nil :type (common-lisp:or repository-id common-lisp:null)) (repository-name common-lisp:nil :type (common-lisp:or repository-name common-lisp:null)) (repository-description common-lisp:nil :type (common-lisp:or repository-description common-lisp:null)) (default-branch common-lisp:nil :type (common-lisp:or branch-name common-lisp:null)) (last-modified-date common-lisp:nil :type (common-lisp:or last-modified-date common-lisp:null)) (creation-date common-lisp:nil :type (common-lisp:or creation-date common-lisp:null)) (clone-url-http common-lisp:nil :type (common-lisp:or clone-url-http common-lisp:null)) (clone-url-ssh common-lisp:nil :type (common-lisp:or clone-url-ssh common-lisp:null)) (arn common-lisp:nil :type (common-lisp:or arn common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-metadata 'make-repository-metadata)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input repository-metadata)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input repository-metadata)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'account-id)) (common-lisp:list (common-lisp:cons "accountId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-id)) (common-lisp:list (common-lisp:cons "repositoryId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-description)) (common-lisp:list (common-lisp:cons "repositoryDescription" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'default-branch)) (common-lisp:list (common-lisp:cons "defaultBranch" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'last-modified-date)) (common-lisp:list (common-lisp:cons "lastModifiedDate" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'creation-date)) (common-lisp:list (common-lisp:cons "creationDate" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'clone-url-http)) (common-lisp:list (common-lisp:cons "cloneUrlHttp" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'clone-url-ssh)) (common-lisp:list (common-lisp:cons "cloneUrlSsh" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'arn)) (common-lisp:list (common-lisp:cons "Arn" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input repository-metadata)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype repository-metadata-list () '(trivial-types:proper-list repository-metadata)) (common-lisp:defun |make-repository-metadata-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-metadata)) aws-sdk/generator/shape::members)) (common-lisp:deftype repository-name () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-name-exists-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-name-exists-exception))) (common-lisp:progn (common-lisp:defstruct (repository-name-id-pair (:copier common-lisp:nil) (:conc-name "struct-shape-repository-name-id-pair-")) (repository-name common-lisp:nil :type (common-lisp:or repository-name common-lisp:null)) (repository-id common-lisp:nil :type (common-lisp:or repository-id common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-name-id-pair 'make-repository-name-id-pair)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input repository-name-id-pair)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input repository-name-id-pair)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-id)) (common-lisp:list (common-lisp:cons "repositoryId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input repository-name-id-pair)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype repository-name-id-pair-list () '(trivial-types:proper-list repository-name-id-pair)) (common-lisp:defun |make-repository-name-id-pair-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-name-id-pair)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:deftype repository-name-list () '(trivial-types:proper-list repository-name)) (common-lisp:defun |make-repository-name-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-name-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-name-required-exception))) (common-lisp:progn (common-lisp:define-condition repository-names-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-names-required-exception))) (common-lisp:progn (common-lisp:deftype repository-not-found-list () '(trivial-types:proper-list repository-name)) (common-lisp:defun |make-repository-not-found-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:defstruct (repository-trigger (:copier common-lisp:nil) (:conc-name "struct-shape-repository-trigger-")) (name (common-lisp:error ":name is required") :type (common-lisp:or repository-trigger-name common-lisp:null)) (destination-arn (common-lisp:error ":destinationarn is required") :type (common-lisp:or arn common-lisp:null)) (custom-data common-lisp:nil :type (common-lisp:or repository-trigger-custom-data common-lisp:null)) (branches common-lisp:nil :type (common-lisp:or branch-name-list common-lisp:null)) (events (common-lisp:error ":events is required") :type (common-lisp:or repository-trigger-event-list common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-trigger 'make-repository-trigger)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input repository-trigger)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input repository-trigger)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'name)) (common-lisp:list (common-lisp:cons "name" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'destination-arn)) (common-lisp:list (common-lisp:cons "destinationArn" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'custom-data)) (common-lisp:list (common-lisp:cons "customData" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branches)) (common-lisp:list (common-lisp:cons "branches" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'events)) (common-lisp:list (common-lisp:cons "events" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input repository-trigger)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition repository-trigger-branch-name-list-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-branch-name-list-required-exception))) (common-lisp:deftype repository-trigger-custom-data () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-trigger-destination-arn-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-destination-arn-required-exception))) (common-lisp:deftype repository-trigger-event-enum () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype repository-trigger-event-list () '(trivial-types:proper-list repository-trigger-event-enum)) (common-lisp:defun |make-repository-trigger-event-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger-event-enum)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-trigger-events-list-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-events-list-required-exception))) (common-lisp:progn (common-lisp:defstruct (repository-trigger-execution-failure (:copier common-lisp:nil) (:conc-name "struct-shape-repository-trigger-execution-failure-")) (trigger common-lisp:nil :type (common-lisp:or repository-trigger-name common-lisp:null)) (failure-message common-lisp:nil :type (common-lisp:or repository-trigger-execution-failure-message common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-trigger-execution-failure 'make-repository-trigger-execution-failure)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input repository-trigger-execution-failure)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input repository-trigger-execution-failure)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'trigger)) (common-lisp:list (common-lisp:cons "trigger" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'failure-message)) (common-lisp:list (common-lisp:cons "failureMessage" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input repository-trigger-execution-failure)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype repository-trigger-execution-failure-list () '(trivial-types:proper-list repository-trigger-execution-failure)) (common-lisp:defun |make-repository-trigger-execution-failure-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger-execution-failure)) aws-sdk/generator/shape::members)) (common-lisp:deftype repository-trigger-execution-failure-message () 'common-lisp:string) (common-lisp:deftype repository-trigger-name () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype repository-trigger-name-list () '(trivial-types:proper-list repository-trigger-name)) (common-lisp:defun |make-repository-trigger-name-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-trigger-name-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-name-required-exception))) (common-lisp:deftype repository-triggers-configuration-id () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype repository-triggers-list () '(trivial-types:proper-list repository-trigger)) (common-lisp:defun |make-repository-triggers-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-triggers-list-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-triggers-list-required-exception))) (common-lisp:deftype sort-by-enum () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (test-repository-triggers-input (:copier common-lisp:nil) (:conc-name "struct-shape-test-repository-triggers-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (triggers (common-lisp:error ":triggers is required") :type (common-lisp:or repository-triggers-list common-lisp:null))) (common-lisp:export (common-lisp:list 'test-repository-triggers-input 'make-test-repository-triggers-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input test-repository-triggers-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input test-repository-triggers-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'triggers)) (common-lisp:list (common-lisp:cons "triggers" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input test-repository-triggers-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (test-repository-triggers-output (:copier common-lisp:nil) (:conc-name "struct-shape-test-repository-triggers-output-")) (successful-executions common-lisp:nil :type (common-lisp:or repository-trigger-name-list common-lisp:null)) (failed-executions common-lisp:nil :type (common-lisp:or repository-trigger-execution-failure-list common-lisp:null))) (common-lisp:export (common-lisp:list 'test-repository-triggers-output 'make-test-repository-triggers-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input test-repository-triggers-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input test-repository-triggers-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'successful-executions)) (common-lisp:list (common-lisp:cons "successfulExecutions" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'failed-executions)) (common-lisp:list (common-lisp:cons "failedExecutions" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input test-repository-triggers-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (update-default-branch-input (:copier common-lisp:nil) (:conc-name "struct-shape-update-default-branch-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (default-branch-name (common-lisp:error ":defaultbranchname is required") :type (common-lisp:or branch-name common-lisp:null))) (common-lisp:export (common-lisp:list 'update-default-branch-input 'make-update-default-branch-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input update-default-branch-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input update-default-branch-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'default-branch-name)) (common-lisp:list (common-lisp:cons "defaultBranchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input update-default-branch-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (update-repository-description-input (:copier common-lisp:nil) (:conc-name "struct-shape-update-repository-description-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (repository-description common-lisp:nil :type (common-lisp:or repository-description common-lisp:null))) (common-lisp:export (common-lisp:list 'update-repository-description-input 'make-update-repository-description-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input update-repository-description-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input update-repository-description-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-description)) (common-lisp:list (common-lisp:cons "repositoryDescription" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input update-repository-description-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (update-repository-name-input (:copier common-lisp:nil) (:conc-name "struct-shape-update-repository-name-input-")) (old-name (common-lisp:error ":oldname is required") :type (common-lisp:or repository-name common-lisp:null)) (new-name (common-lisp:error ":newname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'update-repository-name-input 'make-update-repository-name-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input update-repository-name-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input update-repository-name-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'old-name)) (common-lisp:list (common-lisp:cons "oldName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'new-name)) (common-lisp:list (common-lisp:cons "newName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input update-repository-name-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (user-info (:copier common-lisp:nil) (:conc-name "struct-shape-user-info-")) (name common-lisp:nil :type (common-lisp:or name common-lisp:null)) (email common-lisp:nil :type (common-lisp:or email common-lisp:null)) (date common-lisp:nil :type (common-lisp:or date common-lisp:null))) (common-lisp:export (common-lisp:list 'user-info 'make-user-info)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input user-info)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input user-info)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'name)) (common-lisp:list (common-lisp:cons "name" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'email)) (common-lisp:list (common-lisp:cons "email" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'date)) (common-lisp:list (common-lisp:cons "date" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input user-info)) common-lisp:nil)) common-lisp:nil (common-lisp:progn (common-lisp:defun batch-get-repositories ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-names) (common-lisp:declare (common-lisp:ignorable repository-names)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-batch-get-repositories-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "BatchGetRepositories" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'batch-get-repositories)) (common-lisp:progn (common-lisp:defun create-branch ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name branch-name commit-id) (common-lisp:declare (common-lisp:ignorable repository-name branch-name commit-id)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-create-branch-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "CreateBranch" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'create-branch)) (common-lisp:progn (common-lisp:defun create-repository ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name repository-description) (common-lisp:declare (common-lisp:ignorable repository-name repository-description)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-create-repository-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "CreateRepository" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'create-repository)) (common-lisp:progn (common-lisp:defun delete-repository ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name) (common-lisp:declare (common-lisp:ignorable repository-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-delete-repository-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "DeleteRepository" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'delete-repository)) (common-lisp:progn (common-lisp:defun get-blob ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name blob-id) (common-lisp:declare (common-lisp:ignorable repository-name blob-id)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-blob-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetBlob" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-blob)) (common-lisp:progn (common-lisp:defun get-branch ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name branch-name) (common-lisp:declare (common-lisp:ignorable repository-name branch-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-branch-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetBranch" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-branch)) (common-lisp:progn (common-lisp:defun get-commit ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name commit-id) (common-lisp:declare (common-lisp:ignorable repository-name commit-id)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-commit-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetCommit" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-commit)) (common-lisp:progn (common-lisp:defun get-differences ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name before-commit-specifier after-commit-specifier before-path after-path max-results next-token) (common-lisp:declare (common-lisp:ignorable repository-name before-commit-specifier after-commit-specifier before-path after-path max-results next-token)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-differences-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetDifferences" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-differences)) (common-lisp:progn (common-lisp:defun get-repository ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name) (common-lisp:declare (common-lisp:ignorable repository-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-repository-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetRepository" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-repository)) (common-lisp:progn (common-lisp:defun get-repository-triggers ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name) (common-lisp:declare (common-lisp:ignorable repository-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-repository-triggers-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetRepositoryTriggers" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-repository-triggers)) (common-lisp:progn (common-lisp:defun list-branches ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name next-token) (common-lisp:declare (common-lisp:ignorable repository-name next-token)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-list-branches-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "ListBranches" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'list-branches)) (common-lisp:progn (common-lisp:defun list-repositories ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key next-token sort-by order) (common-lisp:declare (common-lisp:ignorable next-token sort-by order)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-list-repositories-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "ListRepositories" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'list-repositories)) (common-lisp:progn (common-lisp:defun put-repository-triggers ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name triggers) (common-lisp:declare (common-lisp:ignorable repository-name triggers)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-put-repository-triggers-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "PutRepositoryTriggers" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'put-repository-triggers)) (common-lisp:progn (common-lisp:defun test-repository-triggers ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name triggers) (common-lisp:declare (common-lisp:ignorable repository-name triggers)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-test-repository-triggers-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "TestRepositoryTriggers" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'test-repository-triggers)) (common-lisp:progn (common-lisp:defun update-default-branch ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name default-branch-name) (common-lisp:declare (common-lisp:ignorable repository-name default-branch-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-update-default-branch-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "UpdateDefaultBranch" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'update-default-branch)) (common-lisp:progn (common-lisp:defun update-repository-description ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name repository-description) (common-lisp:declare (common-lisp:ignorable repository-name repository-description)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-update-repository-description-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "UpdateRepositoryDescription" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'update-repository-description)) (common-lisp:progn (common-lisp:defun update-repository-name ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key old-name new-name) (common-lisp:declare (common-lisp:ignorable old-name new-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-update-repository-name-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "UpdateRepositoryName" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'update-repository-name))
null
https://raw.githubusercontent.com/pokepay/aws-sdk-lisp/ad9a8f9294a9799cef5f4d85e0cd34eca418be24/services/codecommit/api.lisp
lisp
DO NOT EDIT: File is generated by AWS-SDK/GENERATOR.
(common-lisp:defpackage #:aws-sdk/services/codecommit/api (:use) (:nicknames #:aws/codecommit) (:import-from #:aws-sdk/generator/shape) (:import-from #:aws-sdk/generator/operation) (:import-from #:aws-sdk/api) (:import-from #:aws-sdk/request) (:import-from #:aws-sdk/error)) (common-lisp:in-package #:aws-sdk/services/codecommit/api) (common-lisp:progn (common-lisp:defclass codecommit-request (aws-sdk/request:request) common-lisp:nil (:default-initargs :service "codecommit")) (common-lisp:export 'codecommit-request)) (common-lisp:progn (common-lisp:define-condition codecommit-error (aws-sdk/error:aws-error) common-lisp:nil) (common-lisp:export 'codecommit-error)) (common-lisp:defvar *error-map* '(("BlobIdDoesNotExistException" . blob-id-does-not-exist-exception) ("BlobIdRequiredException" . blob-id-required-exception) ("BranchDoesNotExistException" . branch-does-not-exist-exception) ("BranchNameExistsException" . branch-name-exists-exception) ("BranchNameRequiredException" . branch-name-required-exception) ("CommitDoesNotExistException" . commit-does-not-exist-exception) ("CommitIdDoesNotExistException" . commit-id-does-not-exist-exception) ("CommitIdRequiredException" . commit-id-required-exception) ("CommitRequiredException" . commit-required-exception) ("EncryptionIntegrityChecksFailedException" . encryption-integrity-checks-failed-exception) ("EncryptionKeyAccessDeniedException" . encryption-key-access-denied-exception) ("EncryptionKeyDisabledException" . encryption-key-disabled-exception) ("EncryptionKeyNotFoundException" . encryption-key-not-found-exception) ("EncryptionKeyUnavailableException" . encryption-key-unavailable-exception) ("FileTooLargeException" . file-too-large-exception) ("InvalidBlobIdException" . invalid-blob-id-exception) ("InvalidBranchNameException" . invalid-branch-name-exception) ("InvalidCommitException" . invalid-commit-exception) ("InvalidCommitIdException" . invalid-commit-id-exception) ("InvalidContinuationTokenException" . invalid-continuation-token-exception) ("InvalidMaxResultsException" . invalid-max-results-exception) ("InvalidOrderException" . invalid-order-exception) ("InvalidPathException" . invalid-path-exception) ("InvalidRepositoryDescriptionException" . invalid-repository-description-exception) ("InvalidRepositoryNameException" . invalid-repository-name-exception) ("InvalidRepositoryTriggerBranchNameException" . invalid-repository-trigger-branch-name-exception) ("InvalidRepositoryTriggerCustomDataException" . invalid-repository-trigger-custom-data-exception) ("InvalidRepositoryTriggerDestinationArnException" . invalid-repository-trigger-destination-arn-exception) ("InvalidRepositoryTriggerEventsException" . invalid-repository-trigger-events-exception) ("InvalidRepositoryTriggerNameException" . invalid-repository-trigger-name-exception) ("InvalidRepositoryTriggerRegionException" . invalid-repository-trigger-region-exception) ("InvalidSortByException" . invalid-sort-by-exception) ("MaximumBranchesExceededException" . maximum-branches-exceeded-exception) ("MaximumRepositoryNamesExceededException" . maximum-repository-names-exceeded-exception) ("MaximumRepositoryTriggersExceededException" . maximum-repository-triggers-exceeded-exception) ("PathDoesNotExistException" . path-does-not-exist-exception) ("RepositoryDoesNotExistException" . repository-does-not-exist-exception) ("RepositoryLimitExceededException" . repository-limit-exceeded-exception) ("RepositoryNameExistsException" . repository-name-exists-exception) ("RepositoryNameRequiredException" . repository-name-required-exception) ("RepositoryNamesRequiredException" . repository-names-required-exception) ("RepositoryTriggerBranchNameListRequiredException" . repository-trigger-branch-name-list-required-exception) ("RepositoryTriggerDestinationArnRequiredException" . repository-trigger-destination-arn-required-exception) ("RepositoryTriggerEventsListRequiredException" . repository-trigger-events-list-required-exception) ("RepositoryTriggerNameRequiredException" . repository-trigger-name-required-exception) ("RepositoryTriggersListRequiredException" . repository-triggers-list-required-exception))) (common-lisp:deftype account-id () 'common-lisp:string) (common-lisp:deftype additional-data () 'common-lisp:string) (common-lisp:deftype arn () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (batch-get-repositories-input (:copier common-lisp:nil) (:conc-name "struct-shape-batch-get-repositories-input-")) (repository-names (common-lisp:error ":repositorynames is required") :type (common-lisp:or repository-name-list common-lisp:null))) (common-lisp:export (common-lisp:list 'batch-get-repositories-input 'make-batch-get-repositories-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input batch-get-repositories-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input batch-get-repositories-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-names)) (common-lisp:list (common-lisp:cons "repositoryNames" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input batch-get-repositories-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (batch-get-repositories-output (:copier common-lisp:nil) (:conc-name "struct-shape-batch-get-repositories-output-")) (repositories common-lisp:nil :type (common-lisp:or repository-metadata-list common-lisp:null)) (repositories-not-found common-lisp:nil :type (common-lisp:or repository-not-found-list common-lisp:null))) (common-lisp:export (common-lisp:list 'batch-get-repositories-output 'make-batch-get-repositories-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input batch-get-repositories-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input batch-get-repositories-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repositories)) (common-lisp:list (common-lisp:cons "repositories" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repositories-not-found)) (common-lisp:list (common-lisp:cons "repositoriesNotFound" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input batch-get-repositories-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition blob-id-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'blob-id-does-not-exist-exception))) (common-lisp:progn (common-lisp:define-condition blob-id-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'blob-id-required-exception))) (common-lisp:progn (common-lisp:defstruct (blob-metadata (:copier common-lisp:nil) (:conc-name "struct-shape-blob-metadata-")) (blob-id common-lisp:nil :type (common-lisp:or object-id common-lisp:null)) (path common-lisp:nil :type (common-lisp:or path common-lisp:null)) (mode common-lisp:nil :type (common-lisp:or mode common-lisp:null))) (common-lisp:export (common-lisp:list 'blob-metadata 'make-blob-metadata)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input blob-metadata)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input blob-metadata)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'blob-id)) (common-lisp:list (common-lisp:cons "blobId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'path)) (common-lisp:list (common-lisp:cons "path" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'mode)) (common-lisp:list (common-lisp:cons "mode" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input blob-metadata)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition branch-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'branch-does-not-exist-exception))) (common-lisp:progn (common-lisp:defstruct (branch-info (:copier common-lisp:nil) (:conc-name "struct-shape-branch-info-")) (branch-name common-lisp:nil :type (common-lisp:or branch-name common-lisp:null)) (commit-id common-lisp:nil :type (common-lisp:or commit-id common-lisp:null))) (common-lisp:export (common-lisp:list 'branch-info 'make-branch-info)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input branch-info)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input branch-info)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch-name)) (common-lisp:list (common-lisp:cons "branchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit-id)) (common-lisp:list (common-lisp:cons "commitId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input branch-info)) common-lisp:nil)) (common-lisp:deftype branch-name () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition branch-name-exists-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'branch-name-exists-exception))) (common-lisp:progn (common-lisp:deftype branch-name-list () '(trivial-types:proper-list branch-name)) (common-lisp:defun |make-branch-name-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list branch-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition branch-name-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'branch-name-required-exception))) (common-lisp:deftype change-type-enum () 'common-lisp:string) (common-lisp:deftype clone-url-http () 'common-lisp:string) (common-lisp:deftype clone-url-ssh () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (commit (:copier common-lisp:nil) (:conc-name "struct-shape-commit-")) (tree-id common-lisp:nil :type (common-lisp:or object-id common-lisp:null)) (parents common-lisp:nil :type (common-lisp:or parent-list common-lisp:null)) (message common-lisp:nil :type (common-lisp:or message common-lisp:null)) (author common-lisp:nil :type (common-lisp:or user-info common-lisp:null)) (committer common-lisp:nil :type (common-lisp:or user-info common-lisp:null)) (additional-data common-lisp:nil :type (common-lisp:or additional-data common-lisp:null))) (common-lisp:export (common-lisp:list 'commit 'make-commit)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input commit)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input commit)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'tree-id)) (common-lisp:list (common-lisp:cons "treeId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'parents)) (common-lisp:list (common-lisp:cons "parents" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'message)) (common-lisp:list (common-lisp:cons "message" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'author)) (common-lisp:list (common-lisp:cons "author" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'committer)) (common-lisp:list (common-lisp:cons "committer" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'additional-data)) (common-lisp:list (common-lisp:cons "additionalData" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input commit)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition commit-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-does-not-exist-exception))) (common-lisp:deftype commit-id () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition commit-id-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-id-does-not-exist-exception))) (common-lisp:progn (common-lisp:define-condition commit-id-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-id-required-exception))) (common-lisp:deftype commit-name () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition commit-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'commit-required-exception))) (common-lisp:progn (common-lisp:defstruct (create-branch-input (:copier common-lisp:nil) (:conc-name "struct-shape-create-branch-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (branch-name (common-lisp:error ":branchname is required") :type (common-lisp:or branch-name common-lisp:null)) (commit-id (common-lisp:error ":commitid is required") :type (common-lisp:or commit-id common-lisp:null))) (common-lisp:export (common-lisp:list 'create-branch-input 'make-create-branch-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input create-branch-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input create-branch-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch-name)) (common-lisp:list (common-lisp:cons "branchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit-id)) (common-lisp:list (common-lisp:cons "commitId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input create-branch-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (create-repository-input (:copier common-lisp:nil) (:conc-name "struct-shape-create-repository-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (repository-description common-lisp:nil :type (common-lisp:or repository-description common-lisp:null))) (common-lisp:export (common-lisp:list 'create-repository-input 'make-create-repository-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input create-repository-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input create-repository-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-description)) (common-lisp:list (common-lisp:cons "repositoryDescription" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input create-repository-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (create-repository-output (:copier common-lisp:nil) (:conc-name "struct-shape-create-repository-output-")) (repository-metadata common-lisp:nil :type (common-lisp:or repository-metadata common-lisp:null))) (common-lisp:export (common-lisp:list 'create-repository-output 'make-create-repository-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input create-repository-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input create-repository-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-metadata)) (common-lisp:list (common-lisp:cons "repositoryMetadata" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input create-repository-output)) common-lisp:nil)) (common-lisp:deftype creation-date () 'common-lisp:string) (common-lisp:deftype date () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (delete-repository-input (:copier common-lisp:nil) (:conc-name "struct-shape-delete-repository-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'delete-repository-input 'make-delete-repository-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input delete-repository-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input delete-repository-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input delete-repository-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (delete-repository-output (:copier common-lisp:nil) (:conc-name "struct-shape-delete-repository-output-")) (repository-id common-lisp:nil :type (common-lisp:or repository-id common-lisp:null))) (common-lisp:export (common-lisp:list 'delete-repository-output 'make-delete-repository-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input delete-repository-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input delete-repository-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-id)) (common-lisp:list (common-lisp:cons "repositoryId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input delete-repository-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (difference (:copier common-lisp:nil) (:conc-name "struct-shape-difference-")) (before-blob common-lisp:nil :type (common-lisp:or blob-metadata common-lisp:null)) (after-blob common-lisp:nil :type (common-lisp:or blob-metadata common-lisp:null)) (change-type common-lisp:nil :type (common-lisp:or change-type-enum common-lisp:null))) (common-lisp:export (common-lisp:list 'difference 'make-difference)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input difference)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input difference)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'before-blob)) (common-lisp:list (common-lisp:cons "beforeBlob" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'after-blob)) (common-lisp:list (common-lisp:cons "afterBlob" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'change-type)) (common-lisp:list (common-lisp:cons "changeType" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input difference)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype difference-list () '(trivial-types:proper-list difference)) (common-lisp:defun |make-difference-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list difference)) aws-sdk/generator/shape::members)) (common-lisp:deftype email () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition encryption-integrity-checks-failed-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-integrity-checks-failed-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-access-denied-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-access-denied-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-disabled-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-disabled-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-not-found-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-not-found-exception))) (common-lisp:progn (common-lisp:define-condition encryption-key-unavailable-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'encryption-key-unavailable-exception))) (common-lisp:progn (common-lisp:define-condition file-too-large-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'file-too-large-exception))) (common-lisp:progn (common-lisp:defstruct (get-blob-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-blob-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (blob-id (common-lisp:error ":blobid is required") :type (common-lisp:or object-id common-lisp:null))) (common-lisp:export (common-lisp:list 'get-blob-input 'make-get-blob-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-blob-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-blob-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'blob-id)) (common-lisp:list (common-lisp:cons "blobId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-blob-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-blob-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-blob-output-")) (content (common-lisp:error ":content is required") :type (common-lisp:or (common-lisp:simple-array (common-lisp:unsigned-byte 8) (common-lisp:*)) common-lisp:null))) (common-lisp:export (common-lisp:list 'get-blob-output 'make-get-blob-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-blob-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-blob-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'content)) (common-lisp:list (common-lisp:cons "content" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-blob-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-branch-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-branch-input-")) (repository-name common-lisp:nil :type (common-lisp:or repository-name common-lisp:null)) (branch-name common-lisp:nil :type (common-lisp:or branch-name common-lisp:null))) (common-lisp:export (common-lisp:list 'get-branch-input 'make-get-branch-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-branch-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-branch-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch-name)) (common-lisp:list (common-lisp:cons "branchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-branch-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-branch-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-branch-output-")) (branch common-lisp:nil :type (common-lisp:or branch-info common-lisp:null))) (common-lisp:export (common-lisp:list 'get-branch-output 'make-get-branch-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-branch-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-branch-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branch)) (common-lisp:list (common-lisp:cons "branch" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-branch-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-commit-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-commit-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (commit-id (common-lisp:error ":commitid is required") :type (common-lisp:or object-id common-lisp:null))) (common-lisp:export (common-lisp:list 'get-commit-input 'make-get-commit-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-commit-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-commit-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit-id)) (common-lisp:list (common-lisp:cons "commitId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-commit-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-commit-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-commit-output-")) (commit (common-lisp:error ":commit is required") :type (common-lisp:or commit common-lisp:null))) (common-lisp:export (common-lisp:list 'get-commit-output 'make-get-commit-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-commit-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-commit-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'commit)) (common-lisp:list (common-lisp:cons "commit" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-commit-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-differences-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-differences-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (before-commit-specifier common-lisp:nil :type (common-lisp:or commit-name common-lisp:null)) (after-commit-specifier (common-lisp:error ":aftercommitspecifier is required") :type (common-lisp:or commit-name common-lisp:null)) (before-path common-lisp:nil :type (common-lisp:or path common-lisp:null)) (after-path common-lisp:nil :type (common-lisp:or path common-lisp:null)) (max-results common-lisp:nil :type (common-lisp:or limit common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'get-differences-input 'make-get-differences-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-differences-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-differences-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'before-commit-specifier)) (common-lisp:list (common-lisp:cons "beforeCommitSpecifier" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'after-commit-specifier)) (common-lisp:list (common-lisp:cons "afterCommitSpecifier" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'before-path)) (common-lisp:list (common-lisp:cons "beforePath" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'after-path)) (common-lisp:list (common-lisp:cons "afterPath" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'max-results)) (common-lisp:list (common-lisp:cons "MaxResults" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "NextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-differences-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-differences-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-differences-output-")) (differences common-lisp:nil :type (common-lisp:or difference-list common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'get-differences-output 'make-get-differences-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-differences-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-differences-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'differences)) (common-lisp:list (common-lisp:cons "differences" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "NextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-differences-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-input 'make-get-repository-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input get-repository-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input get-repository-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input get-repository-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-output-")) (repository-metadata common-lisp:nil :type (common-lisp:or repository-metadata common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-output 'make-get-repository-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-repository-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-repository-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-metadata)) (common-lisp:list (common-lisp:cons "repositoryMetadata" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-repository-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-triggers-input (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-triggers-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-triggers-input 'make-get-repository-triggers-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-repository-triggers-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-repository-triggers-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-repository-triggers-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (get-repository-triggers-output (:copier common-lisp:nil) (:conc-name "struct-shape-get-repository-triggers-output-")) (configuration-id common-lisp:nil :type (common-lisp:or repository-triggers-configuration-id common-lisp:null)) (triggers common-lisp:nil :type (common-lisp:or repository-triggers-list common-lisp:null))) (common-lisp:export (common-lisp:list 'get-repository-triggers-output 'make-get-repository-triggers-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input get-repository-triggers-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input get-repository-triggers-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'configuration-id)) (common-lisp:list (common-lisp:cons "configurationId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'triggers)) (common-lisp:list (common-lisp:cons "triggers" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input get-repository-triggers-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition invalid-blob-id-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-blob-id-exception))) (common-lisp:progn (common-lisp:define-condition invalid-branch-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-branch-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-commit-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-commit-exception))) (common-lisp:progn (common-lisp:define-condition invalid-commit-id-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-commit-id-exception))) (common-lisp:progn (common-lisp:define-condition invalid-continuation-token-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-continuation-token-exception))) (common-lisp:progn (common-lisp:define-condition invalid-max-results-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-max-results-exception))) (common-lisp:progn (common-lisp:define-condition invalid-order-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-order-exception))) (common-lisp:progn (common-lisp:define-condition invalid-path-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-path-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-description-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-description-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-branch-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-branch-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-custom-data-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-custom-data-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-destination-arn-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-destination-arn-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-events-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-events-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-name-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-name-exception))) (common-lisp:progn (common-lisp:define-condition invalid-repository-trigger-region-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-repository-trigger-region-exception))) (common-lisp:progn (common-lisp:define-condition invalid-sort-by-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'invalid-sort-by-exception))) (common-lisp:deftype last-modified-date () 'common-lisp:string) (common-lisp:deftype limit () 'common-lisp:integer) (common-lisp:progn (common-lisp:defstruct (list-branches-input (:copier common-lisp:nil) (:conc-name "struct-shape-list-branches-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'list-branches-input 'make-list-branches-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input list-branches-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input list-branches-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input list-branches-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (list-branches-output (:copier common-lisp:nil) (:conc-name "struct-shape-list-branches-output-")) (branches common-lisp:nil :type (common-lisp:or branch-name-list common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'list-branches-output 'make-list-branches-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input list-branches-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input list-branches-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branches)) (common-lisp:list (common-lisp:cons "branches" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input list-branches-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (list-repositories-input (:copier common-lisp:nil) (:conc-name "struct-shape-list-repositories-input-")) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null)) (sort-by common-lisp:nil :type (common-lisp:or sort-by-enum common-lisp:null)) (order common-lisp:nil :type (common-lisp:or order-enum common-lisp:null))) (common-lisp:export (common-lisp:list 'list-repositories-input 'make-list-repositories-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input list-repositories-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input list-repositories-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'sort-by)) (common-lisp:list (common-lisp:cons "sortBy" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'order)) (common-lisp:list (common-lisp:cons "order" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input list-repositories-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (list-repositories-output (:copier common-lisp:nil) (:conc-name "struct-shape-list-repositories-output-")) (repositories common-lisp:nil :type (common-lisp:or repository-name-id-pair-list common-lisp:null)) (next-token common-lisp:nil :type (common-lisp:or next-token common-lisp:null))) (common-lisp:export (common-lisp:list 'list-repositories-output 'make-list-repositories-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input list-repositories-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input list-repositories-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repositories)) (common-lisp:list (common-lisp:cons "repositories" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'next-token)) (common-lisp:list (common-lisp:cons "nextToken" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input list-repositories-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition maximum-branches-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'maximum-branches-exceeded-exception))) (common-lisp:progn (common-lisp:define-condition maximum-repository-names-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'maximum-repository-names-exceeded-exception))) (common-lisp:progn (common-lisp:define-condition maximum-repository-triggers-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'maximum-repository-triggers-exceeded-exception))) (common-lisp:deftype message () 'common-lisp:string) (common-lisp:deftype mode () 'common-lisp:string) (common-lisp:deftype name () 'common-lisp:string) (common-lisp:deftype next-token () 'common-lisp:string) (common-lisp:deftype object-id () 'common-lisp:string) (common-lisp:deftype order-enum () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype parent-list () '(trivial-types:proper-list object-id)) (common-lisp:defun |make-parent-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list object-id)) aws-sdk/generator/shape::members)) (common-lisp:deftype path () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition path-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'path-does-not-exist-exception))) (common-lisp:progn (common-lisp:defstruct (put-repository-triggers-input (:copier common-lisp:nil) (:conc-name "struct-shape-put-repository-triggers-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (triggers (common-lisp:error ":triggers is required") :type (common-lisp:or repository-triggers-list common-lisp:null))) (common-lisp:export (common-lisp:list 'put-repository-triggers-input 'make-put-repository-triggers-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input put-repository-triggers-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input put-repository-triggers-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'triggers)) (common-lisp:list (common-lisp:cons "triggers" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input put-repository-triggers-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (put-repository-triggers-output (:copier common-lisp:nil) (:conc-name "struct-shape-put-repository-triggers-output-")) (configuration-id common-lisp:nil :type (common-lisp:or repository-triggers-configuration-id common-lisp:null))) (common-lisp:export (common-lisp:list 'put-repository-triggers-output 'make-put-repository-triggers-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input put-repository-triggers-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input put-repository-triggers-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'configuration-id)) (common-lisp:list (common-lisp:cons "configurationId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input put-repository-triggers-output)) common-lisp:nil)) (common-lisp:deftype repository-description () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-does-not-exist-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-does-not-exist-exception))) (common-lisp:deftype repository-id () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-limit-exceeded-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-limit-exceeded-exception))) (common-lisp:progn (common-lisp:defstruct (repository-metadata (:copier common-lisp:nil) (:conc-name "struct-shape-repository-metadata-")) (account-id common-lisp:nil :type (common-lisp:or account-id common-lisp:null)) (repository-id common-lisp:nil :type (common-lisp:or repository-id common-lisp:null)) (repository-name common-lisp:nil :type (common-lisp:or repository-name common-lisp:null)) (repository-description common-lisp:nil :type (common-lisp:or repository-description common-lisp:null)) (default-branch common-lisp:nil :type (common-lisp:or branch-name common-lisp:null)) (last-modified-date common-lisp:nil :type (common-lisp:or last-modified-date common-lisp:null)) (creation-date common-lisp:nil :type (common-lisp:or creation-date common-lisp:null)) (clone-url-http common-lisp:nil :type (common-lisp:or clone-url-http common-lisp:null)) (clone-url-ssh common-lisp:nil :type (common-lisp:or clone-url-ssh common-lisp:null)) (arn common-lisp:nil :type (common-lisp:or arn common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-metadata 'make-repository-metadata)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input repository-metadata)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input repository-metadata)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'account-id)) (common-lisp:list (common-lisp:cons "accountId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-id)) (common-lisp:list (common-lisp:cons "repositoryId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-description)) (common-lisp:list (common-lisp:cons "repositoryDescription" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'default-branch)) (common-lisp:list (common-lisp:cons "defaultBranch" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'last-modified-date)) (common-lisp:list (common-lisp:cons "lastModifiedDate" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'creation-date)) (common-lisp:list (common-lisp:cons "creationDate" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'clone-url-http)) (common-lisp:list (common-lisp:cons "cloneUrlHttp" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'clone-url-ssh)) (common-lisp:list (common-lisp:cons "cloneUrlSsh" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'arn)) (common-lisp:list (common-lisp:cons "Arn" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input repository-metadata)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype repository-metadata-list () '(trivial-types:proper-list repository-metadata)) (common-lisp:defun |make-repository-metadata-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-metadata)) aws-sdk/generator/shape::members)) (common-lisp:deftype repository-name () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-name-exists-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-name-exists-exception))) (common-lisp:progn (common-lisp:defstruct (repository-name-id-pair (:copier common-lisp:nil) (:conc-name "struct-shape-repository-name-id-pair-")) (repository-name common-lisp:nil :type (common-lisp:or repository-name common-lisp:null)) (repository-id common-lisp:nil :type (common-lisp:or repository-id common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-name-id-pair 'make-repository-name-id-pair)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input repository-name-id-pair)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input repository-name-id-pair)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-id)) (common-lisp:list (common-lisp:cons "repositoryId" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input repository-name-id-pair)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype repository-name-id-pair-list () '(trivial-types:proper-list repository-name-id-pair)) (common-lisp:defun |make-repository-name-id-pair-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-name-id-pair)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:deftype repository-name-list () '(trivial-types:proper-list repository-name)) (common-lisp:defun |make-repository-name-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-name-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-name-required-exception))) (common-lisp:progn (common-lisp:define-condition repository-names-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-names-required-exception))) (common-lisp:progn (common-lisp:deftype repository-not-found-list () '(trivial-types:proper-list repository-name)) (common-lisp:defun |make-repository-not-found-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:defstruct (repository-trigger (:copier common-lisp:nil) (:conc-name "struct-shape-repository-trigger-")) (name (common-lisp:error ":name is required") :type (common-lisp:or repository-trigger-name common-lisp:null)) (destination-arn (common-lisp:error ":destinationarn is required") :type (common-lisp:or arn common-lisp:null)) (custom-data common-lisp:nil :type (common-lisp:or repository-trigger-custom-data common-lisp:null)) (branches common-lisp:nil :type (common-lisp:or branch-name-list common-lisp:null)) (events (common-lisp:error ":events is required") :type (common-lisp:or repository-trigger-event-list common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-trigger 'make-repository-trigger)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input repository-trigger)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input repository-trigger)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'name)) (common-lisp:list (common-lisp:cons "name" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'destination-arn)) (common-lisp:list (common-lisp:cons "destinationArn" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'custom-data)) (common-lisp:list (common-lisp:cons "customData" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'branches)) (common-lisp:list (common-lisp:cons "branches" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'events)) (common-lisp:list (common-lisp:cons "events" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input repository-trigger)) common-lisp:nil)) (common-lisp:progn (common-lisp:define-condition repository-trigger-branch-name-list-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-branch-name-list-required-exception))) (common-lisp:deftype repository-trigger-custom-data () 'common-lisp:string) (common-lisp:progn (common-lisp:define-condition repository-trigger-destination-arn-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-destination-arn-required-exception))) (common-lisp:deftype repository-trigger-event-enum () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype repository-trigger-event-list () '(trivial-types:proper-list repository-trigger-event-enum)) (common-lisp:defun |make-repository-trigger-event-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger-event-enum)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-trigger-events-list-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-events-list-required-exception))) (common-lisp:progn (common-lisp:defstruct (repository-trigger-execution-failure (:copier common-lisp:nil) (:conc-name "struct-shape-repository-trigger-execution-failure-")) (trigger common-lisp:nil :type (common-lisp:or repository-trigger-name common-lisp:null)) (failure-message common-lisp:nil :type (common-lisp:or repository-trigger-execution-failure-message common-lisp:null))) (common-lisp:export (common-lisp:list 'repository-trigger-execution-failure 'make-repository-trigger-execution-failure)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input repository-trigger-execution-failure)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input repository-trigger-execution-failure)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'trigger)) (common-lisp:list (common-lisp:cons "trigger" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'failure-message)) (common-lisp:list (common-lisp:cons "failureMessage" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input repository-trigger-execution-failure)) common-lisp:nil)) (common-lisp:progn (common-lisp:deftype repository-trigger-execution-failure-list () '(trivial-types:proper-list repository-trigger-execution-failure)) (common-lisp:defun |make-repository-trigger-execution-failure-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger-execution-failure)) aws-sdk/generator/shape::members)) (common-lisp:deftype repository-trigger-execution-failure-message () 'common-lisp:string) (common-lisp:deftype repository-trigger-name () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype repository-trigger-name-list () '(trivial-types:proper-list repository-trigger-name)) (common-lisp:defun |make-repository-trigger-name-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger-name)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-trigger-name-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-trigger-name-required-exception))) (common-lisp:deftype repository-triggers-configuration-id () 'common-lisp:string) (common-lisp:progn (common-lisp:deftype repository-triggers-list () '(trivial-types:proper-list repository-trigger)) (common-lisp:defun |make-repository-triggers-list| (common-lisp:&rest aws-sdk/generator/shape::members) (common-lisp:check-type aws-sdk/generator/shape::members (trivial-types:proper-list repository-trigger)) aws-sdk/generator/shape::members)) (common-lisp:progn (common-lisp:define-condition repository-triggers-list-required-exception (codecommit-error) common-lisp:nil) (common-lisp:export (common-lisp:list 'repository-triggers-list-required-exception))) (common-lisp:deftype sort-by-enum () 'common-lisp:string) (common-lisp:progn (common-lisp:defstruct (test-repository-triggers-input (:copier common-lisp:nil) (:conc-name "struct-shape-test-repository-triggers-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (triggers (common-lisp:error ":triggers is required") :type (common-lisp:or repository-triggers-list common-lisp:null))) (common-lisp:export (common-lisp:list 'test-repository-triggers-input 'make-test-repository-triggers-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input test-repository-triggers-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input test-repository-triggers-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'triggers)) (common-lisp:list (common-lisp:cons "triggers" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input test-repository-triggers-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (test-repository-triggers-output (:copier common-lisp:nil) (:conc-name "struct-shape-test-repository-triggers-output-")) (successful-executions common-lisp:nil :type (common-lisp:or repository-trigger-name-list common-lisp:null)) (failed-executions common-lisp:nil :type (common-lisp:or repository-trigger-execution-failure-list common-lisp:null))) (common-lisp:export (common-lisp:list 'test-repository-triggers-output 'make-test-repository-triggers-output)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input test-repository-triggers-output)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input test-repository-triggers-output)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'successful-executions)) (common-lisp:list (common-lisp:cons "successfulExecutions" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'failed-executions)) (common-lisp:list (common-lisp:cons "failedExecutions" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input test-repository-triggers-output)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (update-default-branch-input (:copier common-lisp:nil) (:conc-name "struct-shape-update-default-branch-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (default-branch-name (common-lisp:error ":defaultbranchname is required") :type (common-lisp:or branch-name common-lisp:null))) (common-lisp:export (common-lisp:list 'update-default-branch-input 'make-update-default-branch-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input update-default-branch-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input update-default-branch-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'default-branch-name)) (common-lisp:list (common-lisp:cons "defaultBranchName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input update-default-branch-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (update-repository-description-input (:copier common-lisp:nil) (:conc-name "struct-shape-update-repository-description-input-")) (repository-name (common-lisp:error ":repositoryname is required") :type (common-lisp:or repository-name common-lisp:null)) (repository-description common-lisp:nil :type (common-lisp:or repository-description common-lisp:null))) (common-lisp:export (common-lisp:list 'update-repository-description-input 'make-update-repository-description-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input update-repository-description-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input update-repository-description-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-name)) (common-lisp:list (common-lisp:cons "repositoryName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'repository-description)) (common-lisp:list (common-lisp:cons "repositoryDescription" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input update-repository-description-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (update-repository-name-input (:copier common-lisp:nil) (:conc-name "struct-shape-update-repository-name-input-")) (old-name (common-lisp:error ":oldname is required") :type (common-lisp:or repository-name common-lisp:null)) (new-name (common-lisp:error ":newname is required") :type (common-lisp:or repository-name common-lisp:null))) (common-lisp:export (common-lisp:list 'update-repository-name-input 'make-update-repository-name-input)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ( (aws-sdk/generator/shape::input update-repository-name-input)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ( (aws-sdk/generator/shape::input update-repository-name-input)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'old-name)) (common-lisp:list (common-lisp:cons "oldName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'new-name)) (common-lisp:list (common-lisp:cons "newName" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ( (aws-sdk/generator/shape::input update-repository-name-input)) common-lisp:nil)) (common-lisp:progn (common-lisp:defstruct (user-info (:copier common-lisp:nil) (:conc-name "struct-shape-user-info-")) (name common-lisp:nil :type (common-lisp:or name common-lisp:null)) (email common-lisp:nil :type (common-lisp:or email common-lisp:null)) (date common-lisp:nil :type (common-lisp:or date common-lisp:null))) (common-lisp:export (common-lisp:list 'user-info 'make-user-info)) (common-lisp:defmethod aws-sdk/generator/shape::input-headers ((aws-sdk/generator/shape::input user-info)) (common-lisp:append)) (common-lisp:defmethod aws-sdk/generator/shape::input-params ((aws-sdk/generator/shape::input user-info)) (common-lisp:append (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'name)) (common-lisp:list (common-lisp:cons "name" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'email)) (common-lisp:list (common-lisp:cons "email" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))) (alexandria:when-let (aws-sdk/generator/shape::value (common-lisp:slot-value aws-sdk/generator/shape::input 'date)) (common-lisp:list (common-lisp:cons "date" (aws-sdk/generator/shape::input-params aws-sdk/generator/shape::value)))))) (common-lisp:defmethod aws-sdk/generator/shape::input-payload ((aws-sdk/generator/shape::input user-info)) common-lisp:nil)) common-lisp:nil (common-lisp:progn (common-lisp:defun batch-get-repositories ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-names) (common-lisp:declare (common-lisp:ignorable repository-names)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-batch-get-repositories-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "BatchGetRepositories" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'batch-get-repositories)) (common-lisp:progn (common-lisp:defun create-branch ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name branch-name commit-id) (common-lisp:declare (common-lisp:ignorable repository-name branch-name commit-id)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-create-branch-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "CreateBranch" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'create-branch)) (common-lisp:progn (common-lisp:defun create-repository ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name repository-description) (common-lisp:declare (common-lisp:ignorable repository-name repository-description)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-create-repository-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "CreateRepository" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'create-repository)) (common-lisp:progn (common-lisp:defun delete-repository ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name) (common-lisp:declare (common-lisp:ignorable repository-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-delete-repository-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "DeleteRepository" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'delete-repository)) (common-lisp:progn (common-lisp:defun get-blob ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name blob-id) (common-lisp:declare (common-lisp:ignorable repository-name blob-id)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-blob-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetBlob" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-blob)) (common-lisp:progn (common-lisp:defun get-branch ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name branch-name) (common-lisp:declare (common-lisp:ignorable repository-name branch-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-branch-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetBranch" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-branch)) (common-lisp:progn (common-lisp:defun get-commit ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name commit-id) (common-lisp:declare (common-lisp:ignorable repository-name commit-id)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-commit-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetCommit" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-commit)) (common-lisp:progn (common-lisp:defun get-differences ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name before-commit-specifier after-commit-specifier before-path after-path max-results next-token) (common-lisp:declare (common-lisp:ignorable repository-name before-commit-specifier after-commit-specifier before-path after-path max-results next-token)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-differences-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetDifferences" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-differences)) (common-lisp:progn (common-lisp:defun get-repository ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name) (common-lisp:declare (common-lisp:ignorable repository-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-repository-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetRepository" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-repository)) (common-lisp:progn (common-lisp:defun get-repository-triggers ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name) (common-lisp:declare (common-lisp:ignorable repository-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-get-repository-triggers-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "GetRepositoryTriggers" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'get-repository-triggers)) (common-lisp:progn (common-lisp:defun list-branches ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name next-token) (common-lisp:declare (common-lisp:ignorable repository-name next-token)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-list-branches-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "ListBranches" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'list-branches)) (common-lisp:progn (common-lisp:defun list-repositories ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key next-token sort-by order) (common-lisp:declare (common-lisp:ignorable next-token sort-by order)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-list-repositories-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "ListRepositories" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'list-repositories)) (common-lisp:progn (common-lisp:defun put-repository-triggers ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name triggers) (common-lisp:declare (common-lisp:ignorable repository-name triggers)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-put-repository-triggers-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "PutRepositoryTriggers" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'put-repository-triggers)) (common-lisp:progn (common-lisp:defun test-repository-triggers ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name triggers) (common-lisp:declare (common-lisp:ignorable repository-name triggers)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-test-repository-triggers-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "TestRepositoryTriggers" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'test-repository-triggers)) (common-lisp:progn (common-lisp:defun update-default-branch ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name default-branch-name) (common-lisp:declare (common-lisp:ignorable repository-name default-branch-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-update-default-branch-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "UpdateDefaultBranch" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'update-default-branch)) (common-lisp:progn (common-lisp:defun update-repository-description ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key repository-name repository-description) (common-lisp:declare (common-lisp:ignorable repository-name repository-description)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-update-repository-description-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "UpdateRepositoryDescription" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'update-repository-description)) (common-lisp:progn (common-lisp:defun update-repository-name ( common-lisp:&rest aws-sdk/generator/operation::args common-lisp:&key old-name new-name) (common-lisp:declare (common-lisp:ignorable old-name new-name)) (common-lisp:let ((aws-sdk/generator/operation::input (common-lisp:apply 'make-update-repository-name-input aws-sdk/generator/operation::args))) (aws-sdk/generator/operation::parse-response (aws-sdk/api:aws-request (aws-sdk/generator/shape:make-request-with-input 'codecommit-request aws-sdk/generator/operation::input "POST" "/" "UpdateRepositoryName" "2015-04-13")) common-lisp:nil common-lisp:nil *error-map*))) (common-lisp:export 'update-repository-name))
54f41a6eaaab06f991bb09bc36bdbe8cc289e12aac157404e497f2c7f211ea29
chenyukang/eopl
define-datatype.scm
;; define-datatype.scm this line must be within 8 lines of the top of the file ( let ( ( time - stamp " Time - stamp : < 2002 - 01 - 02 10:55:10 dfried > " ) ) ;; (display (string-append " define-datatype.scm version J3 " ( substring time - stamp 13 29 ) ;; (string #\newline)))) ;;; This is an r5rs-compliant datatype system. ;;; exports define-datatype, isa, cases, list-of?, always? ;;; test with (define-datatype:test-all) ;;; All other procedures are prefixed with define-datatype: ;;; Any other exports are unintentional. ;;; (define-datatype name ;;; (variant-name (field-name predicate-exp) ...) ;;; ...) ;;; * variant-names become constructors ;;; * The field-names are used only for debugging. writes ( 4/2000 ): ; * Fixed bug in DEFINE-DATATYPE. ; (It was generating code of the form (begin <expression> <definition> ...), ; which is illegal in R5RS Scheme.) * Removed tests ERR20 , ERR22 , and ERR27 from DO - ALL - TESTS because : ; * Test ERR20 contains an undefined variable UUU? ; * Test ERR22 contains an undefined variable ? and also calls a ; non-procedure. * Test ERR27 contained an illegal syntax 5 ? , which I changed to 5 , ; creating a call to a non-procedure. ; ; Several things should be fixed but haven't been: ; * The banner's date is extracted in a fragile way. ; * Several test cases are of the form (begin <definition> ... <expression>), ; which is illegal in R5RS Scheme. This version goes back to , I think . ;;; A consequence of this design is that if someone decides to have a ;;; variant named `else', they cannot use it in the last clause of ;;; cases. Another consequence is that lexically binding the ;;; identifier `else', a la (lambda (else) (cases ... (else ...))), ;;; causes else-clauses to break, so don't do that. ;;; Representation of raw data: ;;; variant-registry: '((variant-name . type-name) ...) ;;; type-registry: '(type-name ...) ;;; type-name is '(variant-names . ((variant-name field-name ...) ...)) ;;; variant-name is a procedure for constructing the variant. ;;; All error messages are as they should be, except for when a ;;; datatype expression is given a non-symbol as a type or ;;; any constructor is a non-symbol. This is because define has ;;; its own error message in that case. We could, of course, solve ;;; these problems with (eval '---). ;;; The global names created by the test suite are all preceded ;;; by define-datatype:test: new error reporting system added by mw Mon Apr 24 14:49:03 2000 . (define define-datatype:report-error eopl:error) ;; (lambda (symbol format . data) ;; ;; print the message ;; (eopl:printf "Error in ~s: " symbol) ;; (apply eopl:printf (cons format data)) ;; (newline) ;; (eopl:error-stop)) (define define-datatype:reset-registries 'ignored) (define define-datatype:is-a-type? 'ignored) (define define-datatype:datatype-checker&registry-updater 'ignored) (define define-datatype:case-checker 'ignored) (let ((define-datatype:type-registry '()) (define-datatype:variant-registry '())) (set! define-datatype:reset-registries (lambda () (set! define-datatype:type-registry '()) (set! define-datatype:variant-registry '()) #t)) (set! define-datatype:is-a-type? (lambda (type-name) (memq type-name define-datatype:type-registry))) (set! define-datatype:datatype-checker&registry-updater (letrec ((set? (lambda (s) (if (null? s) #t (and (not (memq (car s) (cdr s))) (set? (cdr s))))))) (lambda (Type-name Variants) (if (not (symbol? Type-name)) (define-datatype:report-error 'define-datatype "~nThe data type name ~s is not an identifier." Type-name)) (for-each (lambda (variant) (if (not (symbol? (car variant))) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a datatype)~n" " The variant-name ~s is not an identifier.") Type-name (car variant)))) Variants) (let ((variant-names (map car Variants))) (if (not (set? variant-names)) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a datatype)~n" " Some of the variant-names are repeated: ~s.") Type-name variant-names)) (for-each (lambda (v) (cond ;;; This assq cannot be changed. ((assq v define-datatype:variant-registry) => (lambda (pair) (if (not (eq? (cdr pair) Type-name)) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " The variant-name ~s has already been~n" " used as a variant name in ~s.") Type-name v (cdr pair))))))) variant-names) (cond ;;; This assq could be a memq over variant names, only. but would require a third local registry . ((assq Type-name define-datatype:variant-registry) => (lambda (pair) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " The type name ~s has already been~n" " used as a variant name ~s in the~n" " data type ~s.") Type-name Type-name (car pair) (cdr pair)))) ((memq Type-name variant-names) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " Variant name is the same as the data type name.") Type-name))) (for-each (lambda (variant-name) (cond ((memq variant-name define-datatype:type-registry) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " The variant name ~s has already been~n" " used as a type name.") Type-name variant-name)))) variant-names) (set! define-datatype:variant-registry (append (map (lambda (v) (cons v Type-name)) variant-names) define-datatype:variant-registry)) (cond ((memq Type-name define-datatype:type-registry) => (lambda (pair) (set-car! pair Type-name))) (else (set! define-datatype:type-registry (cons Type-name define-datatype:type-registry)))))))) (set! define-datatype:case-checker (let ((remq-or-false (lambda (sym ls) (call-with-current-continuation (lambda (k) (let f ((ls ls)) (cond ((null? ls) (k #f)) ((eq? (car ls) sym) (cdr ls)) (else (cons (car ls) (f (cdr ls))))))))))) (lambda (Type-value Type-name Expression clauses) (cond ((assq Type-name define-datatype:variant-registry) => (lambda (variant-namextype-name) (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases (string-append "The data type ~s should not be a variant name.~n") Type-name))) (else (if (eq? Type-name Expression) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases (string-append "The data type ~s should not be the same~n" " as a lexical variable.") Type-name)) (let ((variant-table (cdr Type-value))) (let f ((clauses* clauses) (unused-variants (map car variant-table))) (if (null? clauses*) (if (not (null? unused-variants)) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses*)))) (define-datatype:report-error 'cases "Missing variant clauses for ~s." unused-variants))) (let* ((head-clause (car clauses*)) (tail-clauses (cdr clauses*)) (purported-variant (car head-clause))) (if (eq? purported-variant Expression) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases (string-append "The variant name ~s should not be the same~n" " as a lexical variable.") Expression)) (cond ((and (null? tail-clauses) (eq? purported-variant 'else)) ; do nothing, we're fine ) ((assq purported-variant variant-table) => (lambda (p) (let ((fields (cdr p)) (purported-fields (cadr head-clause)) (new-unused-variants-or-false (remq-or-false purported-variant unused-variants))) (if (not (= (length fields) (length purported-fields))) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases "Bad fields in ~s." head-clause))) (if (not new-unused-variants-or-false) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases "Duplicate variant clause: ~s." head-clause))) (f tail-clauses new-unused-variants-or-false)))) (else (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases "Bad clause: ~s." head-clause))))))))) )) )))) (define-syntax isa (syntax-rules () ((_) (define-datatype:report-error 'isa "isa expects 1 argument, not 0.")) ((_ type-name) (if (symbol? 'type-name) (lambda args (if (null? args) (define-datatype:report-error 'isa "(isa ~s) expects 1 argument, not 0." 'type-name) (if (null? (cdr args)) (let ((variant (car args))) (let ((type-info type-name)) (if (and (pair? type-info) (list? (car type-info))) (and (pair? variant) (memq (car variant) (car type-info)) #t) (define-datatype:report-error 'isa (string-append "(isa ~s) did not get a data type bound to an~n" " appropriate structure: ~s.~n" " This tends to happen when the type name is~n" " bound to a lexical variable.") 'type-name type-info)))) (define-datatype:report-error 'isa (string-append "(isa ~s) expects 1 argument, not ~s.~n" " With argument list = ~s.") 'type-name (length args) args)))) (define-datatype:report-error 'isa "Type name is not a symbol: ~s." 'type-name))) ((_ type-name other ...) (define-datatype:report-error 'isa "(isa ~s) expects 1 argument, not ~s with ~s." 'type-name (add1 (length '(other ...))) (cons 'isa '(type-name other ...)))))) (define-syntax define-datatype (syntax-rules () ((_ Type-name) (define-datatype:report-error 'define-datatype (string-append "~n There are no variants: ~n ~s.") '(define-datatype Type-name))) ((_ Type-name Type-name?) (define-datatype:report-error 'define-datatype (string-append "~n There are no variants: ~n ~s.") '(define-datatype Type-name Type-name?))) ((_ Type-name Type-name? (Variant-name (Field-name Pred?) ...) ...) (begin [ wdc ] (define ignored (define-datatype:datatype-checker&registry-updater 'Type-name '((Variant-name (Field-name Pred?) ...) ...))) ;[\wdc] (define Type-name (cons '(Variant-name ...) '((Variant-name Field-name ...) ...))) (define Type-name? (if (symbol? 'Type-name) (lambda args (if (null? args) (define-datatype:report-error 'Type-name? "expects 1 argument, not 0.") (if (null? (cdr args)) (let ((variant (car args))) (let ((type-info Type-name)) (if (and (pair? type-info) (list? (car type-info))) (and (pair? variant) (memq (car variant) (car type-info)) #t) (define-datatype:report-error 'Type-name? (string-append "did not get a data type bound to an~n" " appropriate structure: ~s.~n" " This tends to happen when the type name is~n" " bound to a lexical variable.") 'type-name type-info)))) (define-datatype:report-error 'Type-name? (string-append "expects 1 argument, not ~s.~n" " With argument list = ~s.") (length args) args)))) (define-datatype:report-error 'Type-name "Type name is not a symbol: ~s." 'type-name))) (define Variant-name (let ((expected-length (length '(Field-name ...))) (field-names '(Field-name ...)) (pred-names '(Pred? ...)) (preds (list (lambda (x) (Pred? x)) ...))) (lambda args (if (not (= (length args) expected-length)) (define-datatype:report-error 'Variant-name (string-append "Expected ~s arguments but got ~s arguments." "~n Fields are: ~s ~n Args are: ~s.") expected-length (length args) '(Field-name ...) args)) (for-each (lambda (a f p pname) (if (not (p a)) (define-datatype:report-error 'Variant-name "~n Bad ~a field (~s ~s) ==> #f." f pname a))) args field-names preds pred-names) (cons 'Variant-name args)))) ...)))) (define-syntax cases (syntax-rules () ((_ Type-name Expression . Clauses) (let ((type-predicate? (isa Type-name))) (define-datatype:case-checker Type-name 'Type-name 'Expression 'Clauses) (let ((x Expression)) (if (type-predicate? x) (define-datatype:case-helper x . Clauses) (begin (define-datatype:pretty-print (cons 'cases (cons 'Type-name (cons 'Expression 'Clauses)))) (define-datatype:report-error 'cases "~n Not a ~a variant: ~s." 'Type-name x)))))))) ;;; this only works because no-variant datatypes are invalid. (define-syntax define-datatype:case-helper (syntax-rules (else) ((_ Variant (else Body0 Body1 ...)) (begin Body0 Body1 ...)) ((_ Variant (Purported-variant-name (Purported-field-name ...) Body0 Body1 ...)) (apply (lambda (Purported-field-name ...) Body0 Body1 ...) (cdr Variant))) ((_ Variant (Purported-variant-name (Purported-field-name ...) Body0 Body1 ...) Clause ...) (if (eq? (car Variant) 'Purported-variant-name) (apply (lambda (Purported-field-name ...) Body0 Body1 ...) (cdr Variant)) (define-datatype:case-helper Variant Clause ...))) ((_ Variant Neither-an-else-nor-clause ...) (define-datatype:report-error 'cases "~n Not a ~a clause: ~s." 'Type-name (list Neither-an-else-nor-clause ...))))) ;;; ------------------------------ ;;; general helpers (define always? (lambda (x) #t)) (define list-of (lambda (pred . l) (let ((all-preds (cons pred l))) (lambda (obj) (let loop ((obj obj) (preds '())) (or if list is empty , should be , too (and (null? obj) (null? preds)) (if (null? preds) if is empty , but list is n't , then recycle (loop obj all-preds) ;; otherwise check and element and recur. (and (pair? obj) ((car preds) (car obj)) (loop (cdr obj) (cdr preds)))))))))) ;;; ------------------------------ ;;; examples (define-datatype define-datatype:test:btree define-datatype:test:btree? (define-datatype:test:empty-btree) (define-datatype:test:btree-node (left define-datatype:test:btree?) (key integer?) (right define-datatype:test:btree?))) (define sort-intlist (letrec ((flatten-btree (lambda (bt acc) (cases define-datatype:test:btree bt (define-datatype:test:empty-btree () acc) (define-datatype:test:btree-node (left key right) (flatten-btree left (cons key (flatten-btree right acc))))))) (insert-list (lambda (ls bt) (if (null? ls) bt (insert-list (cdr ls) (insert (car ls) bt))))) (insert (lambda (n bt) (cases define-datatype:test:btree bt (define-datatype:test:empty-btree () (define-datatype:test:btree-node (define-datatype:test:empty-btree) n (define-datatype:test:empty-btree))) (define-datatype:test:btree-node (left key right) (cond ((equal? n key) bt) ((< n key) (define-datatype:test:btree-node (insert n left) key right)) (else (define-datatype:test:btree-node left key (insert n right))))))))) (lambda (ls) (flatten-btree (insert-list ls (define-datatype:test:empty-btree)) '())))) (define define-datatype:test0 '(sort-intlist '(8 6 7 5 3 0 9))) ;;; ------------------------------ (define-datatype define-datatype:test:lyst define-datatype:test:lyst? (define-datatype:test:nil) (define-datatype:test:pair (head always?) (tail define-datatype:test:lyst?))) (define list->lyst (lambda (ls) (if (null? ls) (define-datatype:test:nil) (define-datatype:test:pair (car ls) (list->lyst (cdr ls)))))) (define lyst->list ; this tests hygiene (lambda (pr) (cases define-datatype:test:lyst pr (define-datatype:test:nil () '()) (define-datatype:test:pair (head tail) (cons head (lyst->list tail)))))) (define define-datatype:test1 '(lyst->list (list->lyst '(this is a weird form of identity)))) (define lyst-nil? ; this tests else-ability (lambda (pr) (cases define-datatype:test:lyst pr (define-datatype:test:nil () #t) (else #f)))) (define define-datatype:test2 '(list (lyst-nil? (define-datatype:test:nil)) (lyst-nil? (define-datatype:test:pair 3 (define-datatype:test:nil))))) (define define-datatype:test3 '(begin (define-datatype define-datatype:test:alist define-datatype:test:alist? (define-datatype:test:anil) (define-datatype:test:apair (head always?) (tail blist?))) (define-datatype define-datatype:test:blist define-datatype:test:blist? (define-datatype:test:bnil) (define-datatype:test:bpair (head always?) (tail define-datatype:test:alist?))) (define-datatype:test:apair 5 (define-datatype:test:bpair 4 (define-datatype:test:anil))))) (define define-datatype:test4 '(begin (define-datatype define-datatype:test:fff define-datatype:test:fff? (define-datatype:test:wu) (define-datatype:test:bu (define-datatype:test:fff define-datatype:test:fff?))) (let ((define-datatype:test:fff 3)) (define-datatype:test:fff? (define-datatype:test:bu (define-datatype:test:wu)))))) ;;; ------------------------------ ;;; error tests (define define-datatype:err0 ; wrong # args to a constructor '(define-datatype:test:pair)) (define define-datatype:err1 ; wrong type args to a constructor '(define-datatype:test:pair 3 4)) (define define-datatype:err2 ; unlisted variant in cases '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:nil () 3))) (define define-datatype:err3 ; wrong type argument to case '(cases define-datatype:test:lyst 5 (define-datatype:test:pair (x y) 3) (define-datatype:test:nil () 8))) (define define-datatype:err4 ; wrong # fields in cases '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:pair (y z) 4) (define-datatype:test:nil (x) 3) (else 5))) (define define-datatype:err5 ; misspelled variant in cases '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:ppair (y z) 4) (define-datatype:test:nil () 8) (else 5))) (define define-datatype:err10 ; non-symbol used for variant name '(define-datatype define-datatype:test:x define-datatype:test:x? ((define-datatype:test:r) (a b)))) (define define-datatype:err11 ; duplicate variant names '(define-datatype define-datatype:test:x define-datatype:test:x? (define-datatype:test:r (zoo goo?)) (define-datatype:test:r (foo goo?)) (define-datatype:test:s (joo goo?)))) (define define-datatype:err14 ; only type name '(define-datatype define-datatype:test:a define-datatype:test:a?)) (define define-datatype:err18 ; duplicate variant clauses '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:nil () 3) (define-datatype:test:nil () 4))) (define define-datatype:err19 ; repeated variant name. '(begin (define-datatype define-datatype:test:www define-datatype:test:www? (define-datatype:test:foo (man define-datatype:test:www?))) (define-datatype define-datatype:test:zzz define-datatype:test:zzz? (define-datatype:test:foo (harry define-datatype:test:zzz?))))) ;; uuu? is undefined. Should it be uu? (define define-datatype:err20 ; isa's symbol arg is not a type name '(begin (define-datatype define-datatype:test:uu define-datatype:test:uu? (define-datatype:test:goo (man number?))) (define-datatype:pretty-print (define-datatype:test:uu? (define-datatype:test:goo 5))) (define-datatype:test:uu? (define-datatype:test:goo 6)))) (define define-datatype:err21 ; Too many args to uuuu? '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu))) 5))) ;; what is the "?" on the last line?? (define define-datatype:err22 ; Too few args to isa '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) ( (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))?))) (define define-datatype:err23 ; Too many args to isa '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) (uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define define-datatype:err24 ; type name cannot be chosen '(begin ; from existing variant name (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) (define-datatype define-datatype:test:gu define-datatype:test:gu? (hood)) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define define-datatype:err25 ; type name and constructor name '(begin ; cannot be the same. (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:uuuu (foo define-datatype:test:uuuu?))) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define define-datatype:err26 ; variantr name cannot be chosen '(begin ; from existing type name (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:uuuu^ (foo define-datatype:test:uuuu?))) (define-datatype define-datatype:test:gru define-datatype:test:gru? (define-datatype:test:uuuu)) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) wdc : what is this 5 ? isa 's arg is not a symbol . '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:uuuu^ (foo define-datatype:test:uuuu?))) (5 (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define define-datatype:err28 ; 1st & 2nd arg of cases should not '(begin ; be the same. (define-datatype define-datatype:test:uuuu** define-datatype:test:uuuu**? (define-datatype:test:gud) (define-datatype:test:uuuu^^ (foo define-datatype:test:uuuu**?))) (let ((define-datatype:test:uuuu** (define-datatype:test:uuuu^^ (define-datatype:test:uuuu^^ (define-datatype:test:gud))))) (cases define-datatype:test:uuuu** define-datatype:test:uuuu** (define-datatype:test:gud () "Hello") (define-datatype:test:uuuu^^ (foo) "Goodbye"))))) 2nd arg of cases should not '(begin ; be the same as any variant name. (define-datatype define-datatype:test:uuuu** define-datatype:test:uuuu**? (define-datatype:test:gud) (define-datatype:test:uuuu^^ (foo define-datatype:test:uuuu**?))) (let ((define-datatype:test:uuuu^^ (define-datatype:test:uuuu^^ (define-datatype:test:uuuu^^ (define-datatype:test:gud))))) (cases define-datatype:test:uuuu** define-datatype:test:uuuu^^ (define-datatype:test:gud () "Hello") (define-datatype:test:uuuu^^ (foo) "Goodbye"))))) (define do-all-tests (let ((tests (list define-datatype:test0 define-datatype:test1 define-datatype:test2 define-datatype:test3 define-datatype:test4 define-datatype:err0 define-datatype:err1 define-datatype:err2 define-datatype:err3 define-datatype:err4 define-datatype:err5 define-datatype:err10 define-datatype:err11 define-datatype:err14 define-datatype:err18 define-datatype:err19 define-datatype:err21 define-datatype:err23 define-datatype:err24 define-datatype:err25 define-datatype:err26 define-datatype:err28 define-datatype:err29))) (lambda (chezer) (for-each chezer tests)))) ; mw added dynamic-wind around rebinding of eopl:error-stop (define define-datatype:tester (lambda (example) (display "------------------------------") (newline) (sllgen:pretty-print example) (display "-->") (newline) (call-with-current-continuation (lambda (k) (let ((alpha (lambda () (k #f)))) (let ((swap (lambda () (let ((temp eopl:error-stop)) (set! eopl:error-stop alpha) (set! alpha temp))))) (dynamic-wind swap (lambda () (write (eval example (interaction-environment))) (newline) #t) swap))))))) (define define-datatype:test-all (lambda () (do-all-tests define-datatype:tester) (define-datatype:reset-registries)))
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/libs/define-datatype.scm
scheme
define-datatype.scm (display (string-append (string #\newline)))) This is an r5rs-compliant datatype system. exports define-datatype, isa, cases, list-of?, always? test with (define-datatype:test-all) All other procedures are prefixed with define-datatype: Any other exports are unintentional. (define-datatype name (variant-name (field-name predicate-exp) ...) ...) * variant-names become constructors * The field-names are used only for debugging. * Fixed bug in DEFINE-DATATYPE. (It was generating code of the form (begin <expression> <definition> ...), which is illegal in R5RS Scheme.) * Test ERR20 contains an undefined variable UUU? * Test ERR22 contains an undefined variable ? and also calls a non-procedure. creating a call to a non-procedure. Several things should be fixed but haven't been: * The banner's date is extracted in a fragile way. * Several test cases are of the form (begin <definition> ... <expression>), which is illegal in R5RS Scheme. A consequence of this design is that if someone decides to have a variant named `else', they cannot use it in the last clause of cases. Another consequence is that lexically binding the identifier `else', a la (lambda (else) (cases ... (else ...))), causes else-clauses to break, so don't do that. Representation of raw data: variant-registry: '((variant-name . type-name) ...) type-registry: '(type-name ...) type-name is '(variant-names . ((variant-name field-name ...) ...)) variant-name is a procedure for constructing the variant. All error messages are as they should be, except for when a datatype expression is given a non-symbol as a type or any constructor is a non-symbol. This is because define has its own error message in that case. We could, of course, solve these problems with (eval '---). The global names created by the test suite are all preceded by define-datatype:test: (lambda (symbol format . data) ;; print the message (eopl:printf "Error in ~s: " symbol) (apply eopl:printf (cons format data)) (newline) (eopl:error-stop)) This assq cannot be changed. This assq could be a memq over variant names, only. do nothing, we're fine [\wdc] this only works because no-variant datatypes are invalid. ------------------------------ general helpers otherwise check and element and recur. ------------------------------ examples ------------------------------ this tests hygiene this tests else-ability ------------------------------ error tests wrong # args to a constructor wrong type args to a constructor unlisted variant in cases wrong type argument to case wrong # fields in cases misspelled variant in cases non-symbol used for variant name duplicate variant names only type name duplicate variant clauses repeated variant name. uuu? is undefined. Should it be uu? isa's symbol arg is not a type name Too many args to uuuu? what is the "?" on the last line?? Too few args to isa Too many args to isa type name cannot be chosen from existing variant name type name and constructor name cannot be the same. variantr name cannot be chosen from existing type name 1st & 2nd arg of cases should not be the same. be the same as any variant name. mw added dynamic-wind around rebinding of eopl:error-stop
this line must be within 8 lines of the top of the file ( let ( ( time - stamp " Time - stamp : < 2002 - 01 - 02 10:55:10 dfried > " ) ) " define-datatype.scm version J3 " ( substring time - stamp 13 29 ) writes ( 4/2000 ): * Removed tests ERR20 , ERR22 , and ERR27 from DO - ALL - TESTS because : * Test ERR27 contained an illegal syntax 5 ? , which I changed to 5 , This version goes back to , I think . new error reporting system added by mw Mon Apr 24 14:49:03 2000 . (define define-datatype:report-error eopl:error) (define define-datatype:reset-registries 'ignored) (define define-datatype:is-a-type? 'ignored) (define define-datatype:datatype-checker&registry-updater 'ignored) (define define-datatype:case-checker 'ignored) (let ((define-datatype:type-registry '()) (define-datatype:variant-registry '())) (set! define-datatype:reset-registries (lambda () (set! define-datatype:type-registry '()) (set! define-datatype:variant-registry '()) #t)) (set! define-datatype:is-a-type? (lambda (type-name) (memq type-name define-datatype:type-registry))) (set! define-datatype:datatype-checker&registry-updater (letrec ((set? (lambda (s) (if (null? s) #t (and (not (memq (car s) (cdr s))) (set? (cdr s))))))) (lambda (Type-name Variants) (if (not (symbol? Type-name)) (define-datatype:report-error 'define-datatype "~nThe data type name ~s is not an identifier." Type-name)) (for-each (lambda (variant) (if (not (symbol? (car variant))) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a datatype)~n" " The variant-name ~s is not an identifier.") Type-name (car variant)))) Variants) (let ((variant-names (map car Variants))) (if (not (set? variant-names)) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a datatype)~n" " Some of the variant-names are repeated: ~s.") Type-name variant-names)) (for-each (lambda (v) ((assq v define-datatype:variant-registry) => (lambda (pair) (if (not (eq? (cdr pair) Type-name)) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " The variant-name ~s has already been~n" " used as a variant name in ~s.") Type-name v (cdr pair))))))) variant-names) but would require a third local registry . ((assq Type-name define-datatype:variant-registry) => (lambda (pair) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " The type name ~s has already been~n" " used as a variant name ~s in the~n" " data type ~s.") Type-name Type-name (car pair) (cdr pair)))) ((memq Type-name variant-names) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " Variant name is the same as the data type name.") Type-name))) (for-each (lambda (variant-name) (cond ((memq variant-name define-datatype:type-registry) (define-datatype:report-error 'define-datatype (string-append "(While defining the ~a data type)~n" " The variant name ~s has already been~n" " used as a type name.") Type-name variant-name)))) variant-names) (set! define-datatype:variant-registry (append (map (lambda (v) (cons v Type-name)) variant-names) define-datatype:variant-registry)) (cond ((memq Type-name define-datatype:type-registry) => (lambda (pair) (set-car! pair Type-name))) (else (set! define-datatype:type-registry (cons Type-name define-datatype:type-registry)))))))) (set! define-datatype:case-checker (let ((remq-or-false (lambda (sym ls) (call-with-current-continuation (lambda (k) (let f ((ls ls)) (cond ((null? ls) (k #f)) ((eq? (car ls) sym) (cdr ls)) (else (cons (car ls) (f (cdr ls))))))))))) (lambda (Type-value Type-name Expression clauses) (cond ((assq Type-name define-datatype:variant-registry) => (lambda (variant-namextype-name) (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases (string-append "The data type ~s should not be a variant name.~n") Type-name))) (else (if (eq? Type-name Expression) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases (string-append "The data type ~s should not be the same~n" " as a lexical variable.") Type-name)) (let ((variant-table (cdr Type-value))) (let f ((clauses* clauses) (unused-variants (map car variant-table))) (if (null? clauses*) (if (not (null? unused-variants)) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses*)))) (define-datatype:report-error 'cases "Missing variant clauses for ~s." unused-variants))) (let* ((head-clause (car clauses*)) (tail-clauses (cdr clauses*)) (purported-variant (car head-clause))) (if (eq? purported-variant Expression) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases (string-append "The variant name ~s should not be the same~n" " as a lexical variable.") Expression)) (cond ((and (null? tail-clauses) (eq? purported-variant 'else)) ) ((assq purported-variant variant-table) => (lambda (p) (let ((fields (cdr p)) (purported-fields (cadr head-clause)) (new-unused-variants-or-false (remq-or-false purported-variant unused-variants))) (if (not (= (length fields) (length purported-fields))) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases "Bad fields in ~s." head-clause))) (if (not new-unused-variants-or-false) (begin (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases "Duplicate variant clause: ~s." head-clause))) (f tail-clauses new-unused-variants-or-false)))) (else (define-datatype:pretty-print (cons 'cases (cons Type-name (cons Expression clauses)))) (define-datatype:report-error 'cases "Bad clause: ~s." head-clause))))))))) )) )))) (define-syntax isa (syntax-rules () ((_) (define-datatype:report-error 'isa "isa expects 1 argument, not 0.")) ((_ type-name) (if (symbol? 'type-name) (lambda args (if (null? args) (define-datatype:report-error 'isa "(isa ~s) expects 1 argument, not 0." 'type-name) (if (null? (cdr args)) (let ((variant (car args))) (let ((type-info type-name)) (if (and (pair? type-info) (list? (car type-info))) (and (pair? variant) (memq (car variant) (car type-info)) #t) (define-datatype:report-error 'isa (string-append "(isa ~s) did not get a data type bound to an~n" " appropriate structure: ~s.~n" " This tends to happen when the type name is~n" " bound to a lexical variable.") 'type-name type-info)))) (define-datatype:report-error 'isa (string-append "(isa ~s) expects 1 argument, not ~s.~n" " With argument list = ~s.") 'type-name (length args) args)))) (define-datatype:report-error 'isa "Type name is not a symbol: ~s." 'type-name))) ((_ type-name other ...) (define-datatype:report-error 'isa "(isa ~s) expects 1 argument, not ~s with ~s." 'type-name (add1 (length '(other ...))) (cons 'isa '(type-name other ...)))))) (define-syntax define-datatype (syntax-rules () ((_ Type-name) (define-datatype:report-error 'define-datatype (string-append "~n There are no variants: ~n ~s.") '(define-datatype Type-name))) ((_ Type-name Type-name?) (define-datatype:report-error 'define-datatype (string-append "~n There are no variants: ~n ~s.") '(define-datatype Type-name Type-name?))) ((_ Type-name Type-name? (Variant-name (Field-name Pred?) ...) ...) (begin [ wdc ] (define ignored (define-datatype:datatype-checker&registry-updater 'Type-name '((Variant-name (Field-name Pred?) ...) ...))) (define Type-name (cons '(Variant-name ...) '((Variant-name Field-name ...) ...))) (define Type-name? (if (symbol? 'Type-name) (lambda args (if (null? args) (define-datatype:report-error 'Type-name? "expects 1 argument, not 0.") (if (null? (cdr args)) (let ((variant (car args))) (let ((type-info Type-name)) (if (and (pair? type-info) (list? (car type-info))) (and (pair? variant) (memq (car variant) (car type-info)) #t) (define-datatype:report-error 'Type-name? (string-append "did not get a data type bound to an~n" " appropriate structure: ~s.~n" " This tends to happen when the type name is~n" " bound to a lexical variable.") 'type-name type-info)))) (define-datatype:report-error 'Type-name? (string-append "expects 1 argument, not ~s.~n" " With argument list = ~s.") (length args) args)))) (define-datatype:report-error 'Type-name "Type name is not a symbol: ~s." 'type-name))) (define Variant-name (let ((expected-length (length '(Field-name ...))) (field-names '(Field-name ...)) (pred-names '(Pred? ...)) (preds (list (lambda (x) (Pred? x)) ...))) (lambda args (if (not (= (length args) expected-length)) (define-datatype:report-error 'Variant-name (string-append "Expected ~s arguments but got ~s arguments." "~n Fields are: ~s ~n Args are: ~s.") expected-length (length args) '(Field-name ...) args)) (for-each (lambda (a f p pname) (if (not (p a)) (define-datatype:report-error 'Variant-name "~n Bad ~a field (~s ~s) ==> #f." f pname a))) args field-names preds pred-names) (cons 'Variant-name args)))) ...)))) (define-syntax cases (syntax-rules () ((_ Type-name Expression . Clauses) (let ((type-predicate? (isa Type-name))) (define-datatype:case-checker Type-name 'Type-name 'Expression 'Clauses) (let ((x Expression)) (if (type-predicate? x) (define-datatype:case-helper x . Clauses) (begin (define-datatype:pretty-print (cons 'cases (cons 'Type-name (cons 'Expression 'Clauses)))) (define-datatype:report-error 'cases "~n Not a ~a variant: ~s." 'Type-name x)))))))) (define-syntax define-datatype:case-helper (syntax-rules (else) ((_ Variant (else Body0 Body1 ...)) (begin Body0 Body1 ...)) ((_ Variant (Purported-variant-name (Purported-field-name ...) Body0 Body1 ...)) (apply (lambda (Purported-field-name ...) Body0 Body1 ...) (cdr Variant))) ((_ Variant (Purported-variant-name (Purported-field-name ...) Body0 Body1 ...) Clause ...) (if (eq? (car Variant) 'Purported-variant-name) (apply (lambda (Purported-field-name ...) Body0 Body1 ...) (cdr Variant)) (define-datatype:case-helper Variant Clause ...))) ((_ Variant Neither-an-else-nor-clause ...) (define-datatype:report-error 'cases "~n Not a ~a clause: ~s." 'Type-name (list Neither-an-else-nor-clause ...))))) (define always? (lambda (x) #t)) (define list-of (lambda (pred . l) (let ((all-preds (cons pred l))) (lambda (obj) (let loop ((obj obj) (preds '())) (or if list is empty , should be , too (and (null? obj) (null? preds)) (if (null? preds) if is empty , but list is n't , then recycle (loop obj all-preds) (and (pair? obj) ((car preds) (car obj)) (loop (cdr obj) (cdr preds)))))))))) (define-datatype define-datatype:test:btree define-datatype:test:btree? (define-datatype:test:empty-btree) (define-datatype:test:btree-node (left define-datatype:test:btree?) (key integer?) (right define-datatype:test:btree?))) (define sort-intlist (letrec ((flatten-btree (lambda (bt acc) (cases define-datatype:test:btree bt (define-datatype:test:empty-btree () acc) (define-datatype:test:btree-node (left key right) (flatten-btree left (cons key (flatten-btree right acc))))))) (insert-list (lambda (ls bt) (if (null? ls) bt (insert-list (cdr ls) (insert (car ls) bt))))) (insert (lambda (n bt) (cases define-datatype:test:btree bt (define-datatype:test:empty-btree () (define-datatype:test:btree-node (define-datatype:test:empty-btree) n (define-datatype:test:empty-btree))) (define-datatype:test:btree-node (left key right) (cond ((equal? n key) bt) ((< n key) (define-datatype:test:btree-node (insert n left) key right)) (else (define-datatype:test:btree-node left key (insert n right))))))))) (lambda (ls) (flatten-btree (insert-list ls (define-datatype:test:empty-btree)) '())))) (define define-datatype:test0 '(sort-intlist '(8 6 7 5 3 0 9))) (define-datatype define-datatype:test:lyst define-datatype:test:lyst? (define-datatype:test:nil) (define-datatype:test:pair (head always?) (tail define-datatype:test:lyst?))) (define list->lyst (lambda (ls) (if (null? ls) (define-datatype:test:nil) (define-datatype:test:pair (car ls) (list->lyst (cdr ls)))))) (lambda (pr) (cases define-datatype:test:lyst pr (define-datatype:test:nil () '()) (define-datatype:test:pair (head tail) (cons head (lyst->list tail)))))) (define define-datatype:test1 '(lyst->list (list->lyst '(this is a weird form of identity)))) (lambda (pr) (cases define-datatype:test:lyst pr (define-datatype:test:nil () #t) (else #f)))) (define define-datatype:test2 '(list (lyst-nil? (define-datatype:test:nil)) (lyst-nil? (define-datatype:test:pair 3 (define-datatype:test:nil))))) (define define-datatype:test3 '(begin (define-datatype define-datatype:test:alist define-datatype:test:alist? (define-datatype:test:anil) (define-datatype:test:apair (head always?) (tail blist?))) (define-datatype define-datatype:test:blist define-datatype:test:blist? (define-datatype:test:bnil) (define-datatype:test:bpair (head always?) (tail define-datatype:test:alist?))) (define-datatype:test:apair 5 (define-datatype:test:bpair 4 (define-datatype:test:anil))))) (define define-datatype:test4 '(begin (define-datatype define-datatype:test:fff define-datatype:test:fff? (define-datatype:test:wu) (define-datatype:test:bu (define-datatype:test:fff define-datatype:test:fff?))) (let ((define-datatype:test:fff 3)) (define-datatype:test:fff? (define-datatype:test:bu (define-datatype:test:wu)))))) '(define-datatype:test:pair)) '(define-datatype:test:pair 3 4)) '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:nil () 3))) '(cases define-datatype:test:lyst 5 (define-datatype:test:pair (x y) 3) (define-datatype:test:nil () 8))) '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:pair (y z) 4) (define-datatype:test:nil (x) 3) (else 5))) '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:ppair (y z) 4) (define-datatype:test:nil () 8) (else 5))) '(define-datatype define-datatype:test:x define-datatype:test:x? ((define-datatype:test:r) (a b)))) '(define-datatype define-datatype:test:x define-datatype:test:x? (define-datatype:test:r (zoo goo?)) (define-datatype:test:r (foo goo?)) (define-datatype:test:s (joo goo?)))) '(define-datatype define-datatype:test:a define-datatype:test:a?)) '(cases define-datatype:test:lyst (define-datatype:test:nil) (define-datatype:test:nil () 3) (define-datatype:test:nil () 4))) '(begin (define-datatype define-datatype:test:www define-datatype:test:www? (define-datatype:test:foo (man define-datatype:test:www?))) (define-datatype define-datatype:test:zzz define-datatype:test:zzz? (define-datatype:test:foo (harry define-datatype:test:zzz?))))) '(begin (define-datatype define-datatype:test:uu define-datatype:test:uu? (define-datatype:test:goo (man number?))) (define-datatype:pretty-print (define-datatype:test:uu? (define-datatype:test:goo 5))) (define-datatype:test:uu? (define-datatype:test:goo 6)))) '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu))) 5))) '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) ( (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))?))) '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) (uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:zu (foo define-datatype:test:uuuu?))) (define-datatype define-datatype:test:gu define-datatype:test:gu? (hood)) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:uuuu (foo define-datatype:test:uuuu?))) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:uuuu^ (foo define-datatype:test:uuuu?))) (define-datatype define-datatype:test:gru define-datatype:test:gru? (define-datatype:test:uuuu)) (define-datatype:test:uuuu? (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) wdc : what is this 5 ? isa 's arg is not a symbol . '(begin (define-datatype define-datatype:test:uuuu define-datatype:test:uuuu? (define-datatype:test:gu) (define-datatype:test:uuuu^ (foo define-datatype:test:uuuu?))) (5 (define-datatype:test:zu (define-datatype:test:zu (define-datatype:test:gu)))))) (define-datatype define-datatype:test:uuuu** define-datatype:test:uuuu**? (define-datatype:test:gud) (define-datatype:test:uuuu^^ (foo define-datatype:test:uuuu**?))) (let ((define-datatype:test:uuuu** (define-datatype:test:uuuu^^ (define-datatype:test:uuuu^^ (define-datatype:test:gud))))) (cases define-datatype:test:uuuu** define-datatype:test:uuuu** (define-datatype:test:gud () "Hello") (define-datatype:test:uuuu^^ (foo) "Goodbye"))))) 2nd arg of cases should not (define-datatype define-datatype:test:uuuu** define-datatype:test:uuuu**? (define-datatype:test:gud) (define-datatype:test:uuuu^^ (foo define-datatype:test:uuuu**?))) (let ((define-datatype:test:uuuu^^ (define-datatype:test:uuuu^^ (define-datatype:test:uuuu^^ (define-datatype:test:gud))))) (cases define-datatype:test:uuuu** define-datatype:test:uuuu^^ (define-datatype:test:gud () "Hello") (define-datatype:test:uuuu^^ (foo) "Goodbye"))))) (define do-all-tests (let ((tests (list define-datatype:test0 define-datatype:test1 define-datatype:test2 define-datatype:test3 define-datatype:test4 define-datatype:err0 define-datatype:err1 define-datatype:err2 define-datatype:err3 define-datatype:err4 define-datatype:err5 define-datatype:err10 define-datatype:err11 define-datatype:err14 define-datatype:err18 define-datatype:err19 define-datatype:err21 define-datatype:err23 define-datatype:err24 define-datatype:err25 define-datatype:err26 define-datatype:err28 define-datatype:err29))) (lambda (chezer) (for-each chezer tests)))) (define define-datatype:tester (lambda (example) (display "------------------------------") (newline) (sllgen:pretty-print example) (display "-->") (newline) (call-with-current-continuation (lambda (k) (let ((alpha (lambda () (k #f)))) (let ((swap (lambda () (let ((temp eopl:error-stop)) (set! eopl:error-stop alpha) (set! alpha temp))))) (dynamic-wind swap (lambda () (write (eval example (interaction-environment))) (newline) #t) swap))))))) (define define-datatype:test-all (lambda () (do-all-tests define-datatype:tester) (define-datatype:reset-registries)))
b94a3c895a2bd938c6727e369c459d509a97234d3f7c718e1d745a6fd1921a8c
bennn/trivial
regexp-fail.rkt
#lang racket/base (require trivial/private/test-common (only-in typed/racket/base ann : -> String Listof List U Bytes)) ;; Ill-typed `regexp:` expressions TODO why ca n't I catch errors for ( ... ( List String ) ) ? WhydoI need # f ? (module+ test (test-compile-error #:require trivial/regexp trivial/define #:exn #rx"Type Checker" (ann (regexp-match "hi" "hi") (U #f (List String String String))) (ann (regexp-match #rx"(h)(i)" "hi") (U #f (List String String))) (ann (regexp-match #px"(?<=h)(?=i)" "hi") (U #f (List String String String))) ;;bg; ill-typed in untyped Racket (byte-regexp #rx#"yolo") (ann (regexp-match #rx#"hi" "hi") (U #f (List String String))) (ann (regexp-match #px#"hi" "hi") (U #f (List Bytes Bytes))) ;; --- Can't handle |, yet (ann (regexp-match "this(group)|that" "that") (U #f (List String String))) ;; --- can't handle starred groups (ann (regexp-match "(a)*(b)" "b") (U #f (List String String String))) ) (test-compile-error #:require trivial/regexp racket/port trivial/define #:exn #rx"Type Checker" ;; -- expected String, given Bytes (with-input-from-string "hello" (lambda () (define m (regexp-match #rx#"lang" (current-input-port))) (and m (string=? (car m) "lang")))) ---- is raising a type error , which is GOOD , but throwing during test ;; -- return type assumed to be String, but really is Bytes ;; (ugly, but at least we catch it statically) ;(with-input-from-file "test/regexp-fail.rkt" ; (lambda () ; (define m (regexp-match #rx"lang" (current-input-port))) ( and m ( string= ? ( car m ) # " lang " ) ) ) ) ) 2016 - 06 - 13 : these really should be errors , just no - opts ;(test-compile-error ; #:require trivial/regexp trivial/define ; #:exn #rx"mutation not allowed" ; ;; -- set! problems ( ( let ( [ a # rx"(b)(B ) " ] ) ( set ! a # rx " " ) ; (regexp-match a "hai")) ; (List String String String)) ; (let () ; (define a #rx"h(i)") ; (set! a #rx"hi") ; (regexp-match a "hi")) ; ; (let ([a #rx"h(i)"]) ; (set! a #rx"(h)(i)") ; (regexp-match a "hi")) ;) )
null
https://raw.githubusercontent.com/bennn/trivial/c8fb9dcc377d1bf40ca167e34072bec90d2651e1/test/regexp-fail.rkt
racket
Ill-typed `regexp:` expressions bg; ill-typed in untyped Racket --- Can't handle |, yet --- can't handle starred groups -- expected String, given Bytes -- return type assumed to be String, but really is Bytes (ugly, but at least we catch it statically) (with-input-from-file "test/regexp-fail.rkt" (lambda () (define m (regexp-match #rx"lang" (current-input-port))) (test-compile-error #:require trivial/regexp trivial/define #:exn #rx"mutation not allowed" ;; -- set! problems (regexp-match a "hai")) (List String String String)) (let () (define a #rx"h(i)") (set! a #rx"hi") (regexp-match a "hi")) (let ([a #rx"h(i)"]) (set! a #rx"(h)(i)") (regexp-match a "hi")) )
#lang racket/base (require trivial/private/test-common (only-in typed/racket/base ann : -> String Listof List U Bytes)) TODO why ca n't I catch errors for ( ... ( List String ) ) ? WhydoI need # f ? (module+ test (test-compile-error #:require trivial/regexp trivial/define #:exn #rx"Type Checker" (ann (regexp-match "hi" "hi") (U #f (List String String String))) (ann (regexp-match #rx"(h)(i)" "hi") (U #f (List String String))) (ann (regexp-match #px"(?<=h)(?=i)" "hi") (U #f (List String String String))) (byte-regexp #rx#"yolo") (ann (regexp-match #rx#"hi" "hi") (U #f (List String String))) (ann (regexp-match #px#"hi" "hi") (U #f (List Bytes Bytes))) (ann (regexp-match "this(group)|that" "that") (U #f (List String String))) (ann (regexp-match "(a)*(b)" "b") (U #f (List String String String))) ) (test-compile-error #:require trivial/regexp racket/port trivial/define #:exn #rx"Type Checker" (with-input-from-string "hello" (lambda () (define m (regexp-match #rx#"lang" (current-input-port))) (and m (string=? (car m) "lang")))) ---- is raising a type error , which is GOOD , but throwing during test ( and m ( string= ? ( car m ) # " lang " ) ) ) ) ) 2016 - 06 - 13 : these really should be errors , just no - opts ( ( let ( [ a # rx"(b)(B ) " ] ) ( set ! a # rx " " ) )
baacf27aa5aa41a111fc524afa12d3e5d44de73dbf0462ea43233f051d92948b
smallmelon/sdzmmo
lib_send.erl
%%%----------------------------------- %%% @Module : lib_send @Author : xyao %%% @Email : @Created : 2010.05.05 @Description : %%%----------------------------------- -module(lib_send). -include("record.hrl"). -include("common.hrl"). -export([ send_one/2, send_to_sid/2, send_to_all/1, send_to_local_all/1, send_to_nick/2, send_to_uid/2, send_to_scene/2, send_to_area_scene/4, send_to_guild/2, send_to_team/3, rand_to_process/1 ]). %%发送信息给指定socket玩家. Pid : : . send_one(S, Bin) -> gen_tcp:send(S, Bin). 发送信息给指定sid玩家 . : : . send_to_sid(S, Bin) -> rand_to_process(S) ! {send, Bin}. 发送信息给指定玩家名 . : 名称 : . send_to_nick(Nick, Bin) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', nickname = Nick, _='_'}), do_broadcast(L, Bin). %%发送信息给指定玩家ID. %%Uid:玩家ID : . send_to_uid(Uid, Bin) -> case ets:lookup(?ETS_ONLINE, Uid) of [] -> skip; [Player] -> send_to_sid(Player#ets_online.sid, Bin) end. %%发送信息到情景 %%Q:场景ID : 数据 send_to_scene(Q, Bin) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', scene = Q, _='_'}), do_broadcast(L, Bin). %%Q:帮派ID : 数据 send_to_guild(Q, Bin) -> if (Q > 0) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', guild_id= Q, _='_'}), do_broadcast(L, Bin); true -> void end. 发送信息到组队 : %%TeamId:组队ID : 数据 send_to_team(Sid, TeamId, Bin) -> if (TeamId > 0) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', pid_team=TeamId, _='_'}), do_broadcast(L, Bin); true -> send_to_sid(Sid, Bin) end. 发送信息到情景(9宫格区域,不是整个场景 ) %%Q:场景ID %%X,Y坐标 : 数据 send_to_area_scene(Q, X2, Y2, Bin) -> AllUser = ets:match(?ETS_ONLINE, #ets_online{sid = '$1',x = '$2', y='$3', scene = Q, _='_'}), XY2 = lib_scene:get_xy(X2, Y2), F = fun([Sid, X, Y]) -> XY = lib_scene:get_xy(X, Y), if XY == XY2 orelse XY == XY2 + 1 orelse XY == XY2 -1 orelse XY == XY2 -8 orelse XY == XY2 +8 orelse XY == XY2 -9 orelse XY == XY2 +9 orelse XY == XY2 -7 orelse XY == XY2+7 -> send_to_sid(Sid, Bin); true-> ok end end, [F([Sid, X, Y]) || [Sid, X, Y] <- AllUser]. %% 发送信息到世界 send_to_all(Bin) -> send_to_local_all(Bin), mod_disperse:broadcast_to_world(ets:tab2list(?ETS_SERVER), Bin). send_to_local_all(Bin) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', _='_'}), do_broadcast(L, Bin). %% 对列表中的所有socket进行广播 do_broadcast(L, Bin) -> F = fun([S]) -> send_to_sid(S, Bin) end, [F(D) || D <- L]. rand_to_process(S) -> {_,_,R} = erlang:now(), Rand = R div 1000 rem ?SEND_MSG + 1, lists:nth(Rand, S).
null
https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/lib/lib_send.erl
erlang
----------------------------------- @Module : lib_send @Email : ----------------------------------- 发送信息给指定socket玩家. 发送信息给指定玩家ID. Uid:玩家ID 发送信息到情景 Q:场景ID Q:帮派ID TeamId:组队ID Q:场景ID X,Y坐标 发送信息到世界 对列表中的所有socket进行广播
@Author : xyao @Created : 2010.05.05 @Description : -module(lib_send). -include("record.hrl"). -include("common.hrl"). -export([ send_one/2, send_to_sid/2, send_to_all/1, send_to_local_all/1, send_to_nick/2, send_to_uid/2, send_to_scene/2, send_to_area_scene/4, send_to_guild/2, send_to_team/3, rand_to_process/1 ]). Pid : : . send_one(S, Bin) -> gen_tcp:send(S, Bin). 发送信息给指定sid玩家 . : : . send_to_sid(S, Bin) -> rand_to_process(S) ! {send, Bin}. 发送信息给指定玩家名 . : 名称 : . send_to_nick(Nick, Bin) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', nickname = Nick, _='_'}), do_broadcast(L, Bin). : . send_to_uid(Uid, Bin) -> case ets:lookup(?ETS_ONLINE, Uid) of [] -> skip; [Player] -> send_to_sid(Player#ets_online.sid, Bin) end. : 数据 send_to_scene(Q, Bin) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', scene = Q, _='_'}), do_broadcast(L, Bin). : 数据 send_to_guild(Q, Bin) -> if (Q > 0) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', guild_id= Q, _='_'}), do_broadcast(L, Bin); true -> void end. 发送信息到组队 : : 数据 send_to_team(Sid, TeamId, Bin) -> if (TeamId > 0) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', pid_team=TeamId, _='_'}), do_broadcast(L, Bin); true -> send_to_sid(Sid, Bin) end. 发送信息到情景(9宫格区域,不是整个场景 ) : 数据 send_to_area_scene(Q, X2, Y2, Bin) -> AllUser = ets:match(?ETS_ONLINE, #ets_online{sid = '$1',x = '$2', y='$3', scene = Q, _='_'}), XY2 = lib_scene:get_xy(X2, Y2), F = fun([Sid, X, Y]) -> XY = lib_scene:get_xy(X, Y), if XY == XY2 orelse XY == XY2 + 1 orelse XY == XY2 -1 orelse XY == XY2 -8 orelse XY == XY2 +8 orelse XY == XY2 -9 orelse XY == XY2 +9 orelse XY == XY2 -7 orelse XY == XY2+7 -> send_to_sid(Sid, Bin); true-> ok end end, [F([Sid, X, Y]) || [Sid, X, Y] <- AllUser]. send_to_all(Bin) -> send_to_local_all(Bin), mod_disperse:broadcast_to_world(ets:tab2list(?ETS_SERVER), Bin). send_to_local_all(Bin) -> L = ets:match(?ETS_ONLINE, #ets_online{sid='$1', _='_'}), do_broadcast(L, Bin). do_broadcast(L, Bin) -> F = fun([S]) -> send_to_sid(S, Bin) end, [F(D) || D <- L]. rand_to_process(S) -> {_,_,R} = erlang:now(), Rand = R div 1000 rem ?SEND_MSG + 1, lists:nth(Rand, S).
0cf10a168d19ceb61407a3894ac308227dc49bc2934069cafe92df291de95512
yesodweb/wai
Buffer.hs
{-# LANGUAGE BangPatterns #-} module Network.Wai.Handler.Warp.Buffer ( createWriteBuffer , allocateBuffer , freeBuffer , toBuilderBuffer , bufferIO ) where import Data.IORef (IORef, readIORef) import qualified Data.Streaming.ByteString.Builder.Buffer as B (Buffer (..)) import Foreign.ForeignPtr import Foreign.Marshal.Alloc (mallocBytes, free) import Foreign.Ptr (plusPtr) import Network.Socket.BufferPool import Network.Wai.Handler.Warp.Imports import Network.Wai.Handler.Warp.Types ---------------------------------------------------------------- -- | Allocate a buffer of the given size and wrap it in a 'WriteBuffer' -- containing that size and a finalizer. createWriteBuffer :: BufSize -> IO WriteBuffer createWriteBuffer size = do bytes <- allocateBuffer size return WriteBuffer { bufBuffer = bytes, bufSize = size, bufFree = freeBuffer bytes } ---------------------------------------------------------------- -- | Allocating a buffer with malloc(). allocateBuffer :: Int -> IO Buffer allocateBuffer = mallocBytes -- | Releasing a buffer with free(). freeBuffer :: Buffer -> IO () freeBuffer = free ---------------------------------------------------------------- -- Utilities -- toBuilderBuffer :: IORef WriteBuffer -> IO B.Buffer toBuilderBuffer writeBufferRef = do writeBuffer <- readIORef writeBufferRef let ptr = bufBuffer writeBuffer size = bufSize writeBuffer fptr <- newForeignPtr_ ptr return $ B.Buffer fptr ptr ptr (ptr `plusPtr` size) bufferIO :: Buffer -> Int -> (ByteString -> IO ()) -> IO () bufferIO ptr siz io = do fptr <- newForeignPtr_ ptr io $ PS fptr 0 siz
null
https://raw.githubusercontent.com/yesodweb/wai/549be57fe0e088c895eeda0309accc8eb9503227/warp/Network/Wai/Handler/Warp/Buffer.hs
haskell
# LANGUAGE BangPatterns # -------------------------------------------------------------- | Allocate a buffer of the given size and wrap it in a 'WriteBuffer' containing that size and a finalizer. -------------------------------------------------------------- | Allocating a buffer with malloc(). | Releasing a buffer with free(). --------------------------------------------------------------
module Network.Wai.Handler.Warp.Buffer ( createWriteBuffer , allocateBuffer , freeBuffer , toBuilderBuffer , bufferIO ) where import Data.IORef (IORef, readIORef) import qualified Data.Streaming.ByteString.Builder.Buffer as B (Buffer (..)) import Foreign.ForeignPtr import Foreign.Marshal.Alloc (mallocBytes, free) import Foreign.Ptr (plusPtr) import Network.Socket.BufferPool import Network.Wai.Handler.Warp.Imports import Network.Wai.Handler.Warp.Types createWriteBuffer :: BufSize -> IO WriteBuffer createWriteBuffer size = do bytes <- allocateBuffer size return WriteBuffer { bufBuffer = bytes, bufSize = size, bufFree = freeBuffer bytes } allocateBuffer :: Int -> IO Buffer allocateBuffer = mallocBytes freeBuffer :: Buffer -> IO () freeBuffer = free Utilities toBuilderBuffer :: IORef WriteBuffer -> IO B.Buffer toBuilderBuffer writeBufferRef = do writeBuffer <- readIORef writeBufferRef let ptr = bufBuffer writeBuffer size = bufSize writeBuffer fptr <- newForeignPtr_ ptr return $ B.Buffer fptr ptr ptr (ptr `plusPtr` size) bufferIO :: Buffer -> Int -> (ByteString -> IO ()) -> IO () bufferIO ptr siz io = do fptr <- newForeignPtr_ ptr io $ PS fptr 0 siz
1807dc2ea63a6d0a42f614dc987891662c4247431487ea28212d4110c61de15e
adventuring/tootsville.net
http-status-messages.lisp
;;;; -*- lisp -*- ;;; src / http - status - messages.lisp is part of ;;; Copyright © 2008 - 2017 Bruce - Robert Pocock ; © 2018 - 2021 The Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) . ;;; This program is Free Software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;;; ;;; This program is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Affero General Public License for more details. ;;; You should have received a copy of the GNU Affero General Public ;;; License along with this program. If not, see ;;; </>. ;;; ;;; You can reach CIWTA at /, or write to us at: ;;; PO Box 23095 Oakland Park , FL 33307 - 3095 USA (in-package :Tootsville) (defvar *http-status-message* (make-hash-table)) (macrolet ((def-http-status (code phrase) `(setf (gethash ,code *http-status-message*) ,phrase))) (def-http-status 100 "Continue, please. I'd like to hear more.") (def-http-status 101 "Switching Protocols") (def-http-status 200 "Okie-dokie, here you go!") (def-http-status 201 "Look at what I've made now") (def-http-status 202 "I'll take that, sure") (def-http-status 203 "I'm not really sure, but …") (def-http-status 204 "Here's the nothing you wanted") (def-http-status 205 "Reset Content") (def-http-status 206 "Partial Content") (def-http-status 207 "Multi-Status") (def-http-status 300 "Multiple Choices") (def-http-status 301 "Moved Permanently") (def-http-status 302 "Moved Temporarily") (def-http-status 303 "See Other") (def-http-status 304 "Not Modified") (def-http-status 305 "Use Proxy") (def-http-status 307 "Temporary Redirect") (def-http-status 400 "Bad Request") (def-http-status 401 "Authorization Required") (def-http-status 402 "Payment Required") (def-http-status 403 "Forbidden") (def-http-status 404 "Not Found") (def-http-status 405 "Method Not Allowed") (def-http-status 406 "Not Acceptable") (def-http-status 407 "Proxy Authentication Required") (def-http-status 408 "Request Time-out") (def-http-status 409 "Conflict") (def-http-status 410 "Gone") (def-http-status 411 "Length Required") (def-http-status 412 "Precondition Failed") (def-http-status 413 "Request Entity Too Large") (def-http-status 414 "Request-URI Too Large") (def-http-status 415 "Unsupported Media Type") (def-http-status 416 "Requested range not satisfiable") (def-http-status 417 "Expectation Failed") (def-http-status 422 "Unprocessable Entity") (def-http-status 424 "Failed Dependency") (def-http-status 500 "Internal Server Error") (def-http-status 501 "Not Implemented") (def-http-status 502 "Bad Gateway") (def-http-status 503 "Service Unavailable") (def-http-status 504 "Gateway Time-out") (def-http-status 505 "Version not supported"))
null
https://raw.githubusercontent.com/adventuring/tootsville.net/985c11a91dd1a21b77d7378362d86cf1c031b22c/src/http-status-messages.lisp
lisp
-*- lisp -*- © 2018 - 2021 The either version 3 of This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. License along with this program. If not, see </>. You can reach CIWTA at /, or write to us at:
src / http - status - messages.lisp is part of Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) . This program is Free Software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License the License , or ( at your option ) any later version . You should have received a copy of the GNU Affero General Public PO Box 23095 Oakland Park , FL 33307 - 3095 USA (in-package :Tootsville) (defvar *http-status-message* (make-hash-table)) (macrolet ((def-http-status (code phrase) `(setf (gethash ,code *http-status-message*) ,phrase))) (def-http-status 100 "Continue, please. I'd like to hear more.") (def-http-status 101 "Switching Protocols") (def-http-status 200 "Okie-dokie, here you go!") (def-http-status 201 "Look at what I've made now") (def-http-status 202 "I'll take that, sure") (def-http-status 203 "I'm not really sure, but …") (def-http-status 204 "Here's the nothing you wanted") (def-http-status 205 "Reset Content") (def-http-status 206 "Partial Content") (def-http-status 207 "Multi-Status") (def-http-status 300 "Multiple Choices") (def-http-status 301 "Moved Permanently") (def-http-status 302 "Moved Temporarily") (def-http-status 303 "See Other") (def-http-status 304 "Not Modified") (def-http-status 305 "Use Proxy") (def-http-status 307 "Temporary Redirect") (def-http-status 400 "Bad Request") (def-http-status 401 "Authorization Required") (def-http-status 402 "Payment Required") (def-http-status 403 "Forbidden") (def-http-status 404 "Not Found") (def-http-status 405 "Method Not Allowed") (def-http-status 406 "Not Acceptable") (def-http-status 407 "Proxy Authentication Required") (def-http-status 408 "Request Time-out") (def-http-status 409 "Conflict") (def-http-status 410 "Gone") (def-http-status 411 "Length Required") (def-http-status 412 "Precondition Failed") (def-http-status 413 "Request Entity Too Large") (def-http-status 414 "Request-URI Too Large") (def-http-status 415 "Unsupported Media Type") (def-http-status 416 "Requested range not satisfiable") (def-http-status 417 "Expectation Failed") (def-http-status 422 "Unprocessable Entity") (def-http-status 424 "Failed Dependency") (def-http-status 500 "Internal Server Error") (def-http-status 501 "Not Implemented") (def-http-status 502 "Bad Gateway") (def-http-status 503 "Service Unavailable") (def-http-status 504 "Gateway Time-out") (def-http-status 505 "Version not supported"))
7b05a0c8c91239ccf3fc94391597a8fb8dc4f38e3064b26a0e7ba41e2ccf1014
hellonico/origami-sources
test_seq.clj
(ns origami.test-seq (:require [origami.lazyseqs :as lazy] [clojure.test :refer [deftest is]])) (deftest zip-test (let [zip (lazy/zip-seq "resources-dev/photos.zip")] (is (not (nil? (first zip)))))) (deftest github-test (let [url "-fun/tree/master/resources/cat_photos" zip (lazy/github-seq url)] (is (not (nil? (first zip)))))) (deftest webcam-test (let [cam (lazy/webcam-seq)] (is (not (nil? (first cam)))))) (deftest webpage-test (let [ws (lazy/webpage-seq "-phrases-help-connect-global-teams/")] (is (not (nil? (first ws)))))) (deftest dropbox-test (let [ws (lazy/dropbox-seq)] (is (not (nil? (first ws)))))) (deftest folder-test (let [ws (lazy/folder-seq "resources-dev/")] (is (not (nil? (first ws)))))) (deftest flickr-test (let [ws (lazy/flickr-seq ["cat"])] (is (not (nil? (first ws)))))) (comment ;(def ws (lazy/dropbox-seq)) ( u / imshow ( first ws ) ) ) ;; (->> ["猫"] ;; (flickr-seq) ( map - indexed ( fn [ idx itm ] ( cv / imwrite itm ( str " flickr/ " idx " .jpg " ) ) ) ) ) )
null
https://raw.githubusercontent.com/hellonico/origami-sources/923db398f90521f7692e4c5655972b7b0d5a9c2f/test/origami/test_seq.clj
clojure
(def ws (lazy/dropbox-seq)) (->> ["猫"] (flickr-seq)
(ns origami.test-seq (:require [origami.lazyseqs :as lazy] [clojure.test :refer [deftest is]])) (deftest zip-test (let [zip (lazy/zip-seq "resources-dev/photos.zip")] (is (not (nil? (first zip)))))) (deftest github-test (let [url "-fun/tree/master/resources/cat_photos" zip (lazy/github-seq url)] (is (not (nil? (first zip)))))) (deftest webcam-test (let [cam (lazy/webcam-seq)] (is (not (nil? (first cam)))))) (deftest webpage-test (let [ws (lazy/webpage-seq "-phrases-help-connect-global-teams/")] (is (not (nil? (first ws)))))) (deftest dropbox-test (let [ws (lazy/dropbox-seq)] (is (not (nil? (first ws)))))) (deftest folder-test (let [ws (lazy/folder-seq "resources-dev/")] (is (not (nil? (first ws)))))) (deftest flickr-test (let [ws (lazy/flickr-seq ["cat"])] (is (not (nil? (first ws)))))) (comment ( u / imshow ( first ws ) ) ) ( map - indexed ( fn [ idx itm ] ( cv / imwrite itm ( str " flickr/ " idx " .jpg " ) ) ) ) ) )
e58470e5d989490f669195580014a3bbf5820067f4c2119a2f3bc5418f76004a
morpheusgraphql/morpheus-graphql
Resolution.hs
{-# LANGUAGE DeriveLift #-} {-# LANGUAGE DeriveTraversable #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE NoImplicitPrelude # module Data.Mergeable.Internal.Resolution ( Indexed (..), indexed, fromListT, resolveWith, runResolutionT, ResolutionT, ) where import qualified Data.HashMap.Lazy as HM import Language.Haskell.TH.Syntax (Lift) import Relude sortedEntries :: [Indexed k a] -> [(k, a)] sortedEntries = fmap f . sortOn index where f a = (indexedKey a, indexedValue a) fromListT :: (Monad m, Eq k, Hashable k) => [(k, a)] -> ResolutionT k a coll m coll fromListT = traverse resolveDuplicatesM . fromListDuplicates >=> fromNoDuplicatesM resolveWith :: Monad m => (a -> a -> m a) -> NonEmpty a -> m a resolveWith f (x :| xs) = foldlM f x xs data Indexed k a = Indexed { index :: Int, indexedKey :: k, indexedValue :: a } deriving ( Show, Eq, Functor, Traversable, Foldable, Lift ) fromListDuplicates :: (Eq k, Hashable k) => [(k, a)] -> [(k, NonEmpty a)] fromListDuplicates xs = sortedEntries $ HM.elems $ clusterDuplicates (indexed xs) HM.empty indexed :: [(k, a)] -> [Indexed k a] indexed = __indexed 0 where __indexed :: Int -> [(k, a)] -> [Indexed k a] __indexed _ [] = [] __indexed i ((k, x) : xs) = Indexed i k x : __indexed (i + 1) xs resolveDuplicatesM :: Monad m => (k, NonEmpty a) -> ResolutionT k a coll m (k, a) resolveDuplicatesM (k, xs) = asks resolveDuplicates >>= lift . fmap (k,) . (xs &) fromNoDuplicatesM :: Monad m => [(k, a)] -> ResolutionT k a coll m coll fromNoDuplicatesM xs = asks ((xs &) . fromNoDuplicates) insertWithList :: (Eq k, Hashable k) => Indexed k (NonEmpty a) -> HashMap k (Indexed k (NonEmpty a)) -> HashMap k (Indexed k (NonEmpty a)) insertWithList (Indexed i1 key value) = HM.alter (Just . updater) key where updater Nothing = Indexed i1 key value updater (Just (Indexed i2 _ x)) = Indexed i2 key (x <> value) clusterDuplicates :: (Eq k, Hashable k) => [Indexed k a] -> HashMap k (Indexed k (NonEmpty a)) -> HashMap k (Indexed k (NonEmpty a)) clusterDuplicates [] = id clusterDuplicates xs = flip (foldl' (\coll x -> insertWithList (fmap (:| []) x) coll)) xs data Resolution k a coll m = Resolution { resolveDuplicates :: NonEmpty a -> m a, fromNoDuplicates :: [(k, a)] -> coll } runResolutionT :: ResolutionT k a coll m b -> ([(k, a)] -> coll) -> (NonEmpty a -> m a) -> m b runResolutionT (ResolutionT x) fromNoDuplicates resolveDuplicates = runReaderT x Resolution {..} newtype ResolutionT k a coll m x = ResolutionT { _runResolutionT :: ReaderT (Resolution k a coll m) m x } deriving ( Functor, Monad, Applicative, MonadReader (Resolution k a coll m) ) instance MonadTrans (ResolutionT k a coll) where lift = ResolutionT . lift
null
https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/3ffec58dfb7a53cee018bc4a3fb5a7192c672acd/morpheus-graphql-core/src/Data/Mergeable/Internal/Resolution.hs
haskell
# LANGUAGE DeriveLift # # LANGUAGE DeriveTraversable #
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE NoImplicitPrelude # module Data.Mergeable.Internal.Resolution ( Indexed (..), indexed, fromListT, resolveWith, runResolutionT, ResolutionT, ) where import qualified Data.HashMap.Lazy as HM import Language.Haskell.TH.Syntax (Lift) import Relude sortedEntries :: [Indexed k a] -> [(k, a)] sortedEntries = fmap f . sortOn index where f a = (indexedKey a, indexedValue a) fromListT :: (Monad m, Eq k, Hashable k) => [(k, a)] -> ResolutionT k a coll m coll fromListT = traverse resolveDuplicatesM . fromListDuplicates >=> fromNoDuplicatesM resolveWith :: Monad m => (a -> a -> m a) -> NonEmpty a -> m a resolveWith f (x :| xs) = foldlM f x xs data Indexed k a = Indexed { index :: Int, indexedKey :: k, indexedValue :: a } deriving ( Show, Eq, Functor, Traversable, Foldable, Lift ) fromListDuplicates :: (Eq k, Hashable k) => [(k, a)] -> [(k, NonEmpty a)] fromListDuplicates xs = sortedEntries $ HM.elems $ clusterDuplicates (indexed xs) HM.empty indexed :: [(k, a)] -> [Indexed k a] indexed = __indexed 0 where __indexed :: Int -> [(k, a)] -> [Indexed k a] __indexed _ [] = [] __indexed i ((k, x) : xs) = Indexed i k x : __indexed (i + 1) xs resolveDuplicatesM :: Monad m => (k, NonEmpty a) -> ResolutionT k a coll m (k, a) resolveDuplicatesM (k, xs) = asks resolveDuplicates >>= lift . fmap (k,) . (xs &) fromNoDuplicatesM :: Monad m => [(k, a)] -> ResolutionT k a coll m coll fromNoDuplicatesM xs = asks ((xs &) . fromNoDuplicates) insertWithList :: (Eq k, Hashable k) => Indexed k (NonEmpty a) -> HashMap k (Indexed k (NonEmpty a)) -> HashMap k (Indexed k (NonEmpty a)) insertWithList (Indexed i1 key value) = HM.alter (Just . updater) key where updater Nothing = Indexed i1 key value updater (Just (Indexed i2 _ x)) = Indexed i2 key (x <> value) clusterDuplicates :: (Eq k, Hashable k) => [Indexed k a] -> HashMap k (Indexed k (NonEmpty a)) -> HashMap k (Indexed k (NonEmpty a)) clusterDuplicates [] = id clusterDuplicates xs = flip (foldl' (\coll x -> insertWithList (fmap (:| []) x) coll)) xs data Resolution k a coll m = Resolution { resolveDuplicates :: NonEmpty a -> m a, fromNoDuplicates :: [(k, a)] -> coll } runResolutionT :: ResolutionT k a coll m b -> ([(k, a)] -> coll) -> (NonEmpty a -> m a) -> m b runResolutionT (ResolutionT x) fromNoDuplicates resolveDuplicates = runReaderT x Resolution {..} newtype ResolutionT k a coll m x = ResolutionT { _runResolutionT :: ReaderT (Resolution k a coll m) m x } deriving ( Functor, Monad, Applicative, MonadReader (Resolution k a coll m) ) instance MonadTrans (ResolutionT k a coll) where lift = ResolutionT . lift
2156c469e5d48061eef09f12bae7d725c79334567bd878e349809e2295aee1ef
vereis/jarlang
re.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2017 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(re). -export([grun/3,urun/3,ucompile/2,replace/3,replace/4,split/2,split/3]). -type mp() :: {re_pattern, _, _, _, _}. -type nl_spec() :: cr | crlf | lf | anycrlf | any. -type compile_option() :: unicode | anchored | caseless | dollar_endonly | dotall | extended | firstline | multiline | no_auto_capture | dupnames | ungreedy | {newline, nl_spec()} | bsr_anycrlf | bsr_unicode | no_start_optimize | ucp | never_utf. %%% BIFs -export([version/0, compile/1, compile/2, run/2, run/3, inspect/2]). -spec version() -> binary(). version() -> erlang:nif_error(undef). -spec compile(Regexp) -> {ok, MP} | {error, ErrSpec} when Regexp :: iodata(), MP :: mp(), ErrSpec :: {ErrString :: string(), Position :: non_neg_integer()}. compile(_) -> erlang:nif_error(undef). -spec compile(Regexp, Options) -> {ok, MP} | {error, ErrSpec} when Regexp :: iodata() | unicode:charlist(), Options :: [Option], Option :: compile_option(), MP :: mp(), ErrSpec :: {ErrString :: string(), Position :: non_neg_integer()}. compile(_, _) -> erlang:nif_error(undef). -spec run(Subject, RE) -> {match, Captured} | nomatch when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata(), Captured :: [CaptureData], CaptureData :: {integer(), integer()}. run(_, _) -> erlang:nif_error(undef). -spec run(Subject, RE, Options) -> {match, Captured} | match | nomatch | {error, ErrType} when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata() | unicode:charlist(), Options :: [Option], Option :: anchored | global | notbol | noteol | notempty | notempty_atstart | report_errors | {offset, non_neg_integer()} | {match_limit, non_neg_integer()} | {match_limit_recursion, non_neg_integer()} | {newline, NLSpec :: nl_spec()} | bsr_anycrlf | bsr_unicode | {capture, ValueSpec} | {capture, ValueSpec, Type} | CompileOpt, Type :: index | list | binary, ValueSpec :: all | all_but_first | all_names | first | none | ValueList, ValueList :: [ValueID], ValueID :: integer() | string() | atom(), CompileOpt :: compile_option(), Captured :: [CaptureData] | [[CaptureData]], CaptureData :: {integer(), integer()} | ListConversionData | binary(), ListConversionData :: string() | {error, string(), binary()} | {incomplete, string(), binary()}, ErrType :: match_limit | match_limit_recursion | {compile, CompileErr}, CompileErr :: {ErrString :: string(), Position :: non_neg_integer()}. run(_, _, _) -> erlang:nif_error(undef). -spec inspect(MP,Item) -> {namelist, [ binary() ]} when MP :: mp(), Item :: namelist. inspect(_,_) -> erlang:nif_error(undef). %%% End of BIFs -spec split(Subject, RE) -> SplitList when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata(), SplitList :: [iodata() | unicode:charlist()]. split(Subject,RE) -> split(Subject,RE,[]). -spec split(Subject, RE, Options) -> SplitList when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata() | unicode:charlist(), Options :: [ Option ], Option :: anchored | notbol | noteol | notempty | notempty_atstart | {offset, non_neg_integer()} | {newline, nl_spec()} | {match_limit, non_neg_integer()} | {match_limit_recursion, non_neg_integer()} | bsr_anycrlf | bsr_unicode | {return, ReturnType} | {parts, NumParts} | group | trim | CompileOpt, NumParts :: non_neg_integer() | infinity, ReturnType :: iodata | list | binary, CompileOpt :: compile_option(), SplitList :: [RetData] | [GroupedRetData], GroupedRetData :: [RetData], RetData :: iodata() | unicode:charlist() | binary() | list(). split(Subject,RE,Options) -> try {NewOpt,Convert,Limit,Strip,Group} = process_split_params(Options,iodata,-1,false,false), Unicode = check_for_unicode(RE, Options), FlatSubject = to_binary(Subject, Unicode), case compile_split(RE,NewOpt) of {error,_Err} -> throw(badre); {PreCompiled, NumSub, RunOpt} -> %% OK, lets run case re:run(FlatSubject,PreCompiled,RunOpt ++ [global]) of nomatch -> case Group of true -> convert_any_split_result([[FlatSubject]], Convert, Unicode, true); false -> convert_any_split_result([FlatSubject], Convert, Unicode, false) end; {match, Matches} -> Res = do_split(FlatSubject, 0, Matches, NumSub, Limit, Group), Stripped = case Strip of true -> backstrip_empty(Res,Group); false -> Res end, convert_any_split_result(Stripped, Convert, Unicode, Group) end end catch throw:badopt -> erlang:error(badarg,[Subject,RE,Options]); throw:badre -> erlang:error(badarg,[Subject,RE,Options]); error:badarg -> erlang:error(badarg,[Subject,RE,Options]) end. backstrip_empty(List, false) -> do_backstrip_empty(List); backstrip_empty(List, true) -> do_backstrip_empty_g(List). do_backstrip_empty_g([]) -> []; do_backstrip_empty_g([H]) -> case do_backstrip_empty(H) of [] -> []; _ -> [H] end; do_backstrip_empty_g([H|T]) -> case do_backstrip_empty_g(T) of [] -> case do_backstrip_empty(H) of [] -> []; _ -> [H] end; Other -> [H|Other] end. do_backstrip_empty([]) -> []; do_backstrip_empty([<<>>]) -> []; do_backstrip_empty([<<>>|T]) -> case do_backstrip_empty(T) of [] -> []; Other -> [<<>>|Other] end; do_backstrip_empty([H|T]) -> [H|do_backstrip_empty(T)]. convert_any_split_result(List,Type,Uni,true) -> [ convert_split_result(Part,Type,Uni) || Part <- List ]; convert_any_split_result(List,Type,Uni, false) -> convert_split_result(List,Type,Uni). convert_split_result(List, iodata, _Unicode) -> List; convert_split_result(List, binary, _Unicode) -> As it happens , the iodata is actually binaries List; convert_split_result(List, list, true) -> [unicode:characters_to_list(Element,unicode) || Element <- List]; convert_split_result(List, list, false) -> [binary_to_list(Element) || Element <- List]. do_split(Subj, Off, _, _, 0, false) -> <<_:Off/binary,Rest/binary>> = Subj, [Rest]; do_split(Subj, Off, [], _, _, false) -> <<_:Off/binary,Rest/binary>> = Subj, [Rest]; do_split(Subj, Off, _, _, _,false) when byte_size(Subj) =< Off -> [<<>>]; do_split(Subj, Off, _, _, 0, true) -> <<_:Off/binary,Rest/binary>> = Subj, [[Rest]]; do_split(Subj, Off, [], _, _, true) -> <<_:Off/binary,Rest/binary>> = Subj, [[Rest]]; do_split(Subj, Off, _, _, _,true) when byte_size(Subj) =< Off -> [[<<>>]]; do_split(Subj, Offset, [[{MainI,MainL}|Sub]|T], NumSub, Limit, Group) -> NewOffset = MainI+MainL, KeptLen = MainI - Offset, case {KeptLen,empty_sub(Sub),MainL} of {0,true,0} -> do_split(Subj,NewOffset,T,NumSub,Limit,Group); _ -> <<_:Offset/binary,Keep:KeptLen/binary,_/binary>> = Subj, ESub = extend_subpatterns(Sub,NumSub), Tail = do_split(Subj, NewOffset, T, NumSub, Limit - 1,Group), case Group of false -> [Keep | dig_subpatterns(Subj,lists:reverse(ESub),Tail)]; true -> [[Keep | dig_subpatterns(Subj,lists:reverse(ESub),[])]| Tail] end end. empty_sub([]) -> true; empty_sub([{_,0}|T]) -> empty_sub(T); empty_sub(_) -> false. dig_subpatterns(_,[],Acc) -> Acc; dig_subpatterns(Subj,[{-1,0}|T],Acc) -> dig_subpatterns(Subj,T,[<<>>|Acc]); dig_subpatterns(Subj,[{I,L}|T],Acc) -> <<_:I/binary,Part:L/binary,_/binary>> = Subj, dig_subpatterns(Subj,T,[Part|Acc]). extend_subpatterns(_,0) -> []; extend_subpatterns([],N) -> [{0,0} | extend_subpatterns([],N-1)]; extend_subpatterns([H|T],N) -> [H | extend_subpatterns(T,N-1)]. compile_split({re_pattern,N,_,_,_} = Comp, Options) -> {Comp,N,Options}; compile_split(Pat,Options0) when not is_tuple(Pat) -> Options = lists:filter(fun(O) -> (not runopt(O)) end, Options0), case re:compile(Pat,Options) of {error,Err} -> {error,Err}; {ok, {re_pattern,N,_,_,_} = Comp} -> NewOpt = lists:filter(fun(OO) -> (not copt(OO)) end, Options0), {Comp,N,NewOpt} end; compile_split(_,_) -> throw(badre). -spec replace(Subject, RE, Replacement) -> iodata() | unicode:charlist() when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata(), Replacement :: iodata() | unicode:charlist(). replace(Subject,RE,Replacement) -> replace(Subject,RE,Replacement,[]). -spec replace(Subject, RE, Replacement, Options) -> iodata() | unicode:charlist() when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata() | unicode:charlist(), Replacement :: iodata() | unicode:charlist(), Options :: [Option], Option :: anchored | global | notbol | noteol | notempty | notempty_atstart | {offset, non_neg_integer()} | {newline, NLSpec} | bsr_anycrlf | {match_limit, non_neg_integer()} | {match_limit_recursion, non_neg_integer()} | bsr_unicode | {return, ReturnType} | CompileOpt, ReturnType :: iodata | list | binary, CompileOpt :: compile_option(), NLSpec :: cr | crlf | lf | anycrlf | any. replace(Subject,RE,Replacement,Options) -> try {NewOpt,Convert} = process_repl_params(Options,iodata), Unicode = check_for_unicode(RE, Options), FlatSubject = to_binary(Subject, Unicode), FlatReplacement = to_binary(Replacement, Unicode), IoList = do_replace(FlatSubject,Subject,RE,FlatReplacement,NewOpt), case Convert of iodata -> IoList; binary -> case Unicode of false -> iolist_to_binary(IoList); true -> unicode:characters_to_binary(IoList,unicode) end; list -> case Unicode of false -> binary_to_list(iolist_to_binary(IoList)); true -> unicode:characters_to_list(IoList,unicode) end end catch throw:badopt -> erlang:error(badarg,[Subject,RE,Replacement,Options]); throw:badre -> erlang:error(badarg,[Subject,RE,Replacement,Options]); error:badarg -> erlang:error(badarg,[Subject,RE,Replacement,Options]) end. do_replace(FlatSubject,Subject,RE,Replacement,Options) -> case re:run(FlatSubject,RE,Options) of nomatch -> Subject; {match,[Mlist|T]} when is_list(Mlist) -> apply_mlist(FlatSubject,Replacement,[Mlist|T]); {match,Slist} -> apply_mlist(FlatSubject,Replacement,[Slist]) end. process_repl_params([],Convert) -> {[],Convert}; process_repl_params([report_errors|_],_) -> throw(badopt); process_repl_params([{capture,_,_}|_],_) -> throw(badopt); process_repl_params([{capture,_}|_],_) -> throw(badopt); process_repl_params([{return,iodata}|T],_C) -> process_repl_params(T,iodata); process_repl_params([{return,list}|T],_C) -> process_repl_params(T,list); process_repl_params([{return,binary}|T],_C) -> process_repl_params(T,binary); process_repl_params([{return,_}|_],_) -> throw(badopt); process_repl_params([H|T],C) -> {NT,NC} = process_repl_params(T,C), {[H|NT],NC}. process_split_params([],Convert,Limit,Strip,Group) -> {[],Convert,Limit,Strip,Group}; process_split_params([trim|T],C,_L,_S,G) -> process_split_params(T,C,-1,true,G); process_split_params([{parts,0}|T],C,_L,_S,G) -> process_split_params(T,C,-1,true,G); process_split_params([{parts,N}|T],C,_L,_S,G) when is_integer(N), N >= 1 -> process_split_params(T,C,N-1,false,G); process_split_params([{parts,infinity}|T],C,_L,_S,G) -> process_split_params(T,C,-1,false,G); process_split_params([{parts,_}|_],_,_,_,_) -> throw(badopt); process_split_params([group|T],C,L,S,_G) -> process_split_params(T,C,L,S,true); process_split_params([global|_],_,_,_,_) -> throw(badopt); process_split_params([report_errors|_],_,_,_,_) -> throw(badopt); process_split_params([{capture,_,_}|_],_,_,_,_) -> throw(badopt); process_split_params([{capture,_}|_],_,_,_,_) -> throw(badopt); process_split_params([{return,iodata}|T],_C,L,S,G) -> process_split_params(T,iodata,L,S,G); process_split_params([{return,list}|T],_C,L,S,G) -> process_split_params(T,list,L,S,G); process_split_params([{return,binary}|T],_C,L,S,G) -> process_split_params(T,binary,L,S,G); process_split_params([{return,_}|_],_,_,_,_) -> throw(badopt); process_split_params([H|T],C,L,S,G) -> {NT,NC,NL,NS,NG} = process_split_params(T,C,L,S,G), {[H|NT],NC,NL,NS,NG}. apply_mlist(Subject,Replacement,Mlist) -> do_mlist(Subject,Subject,0,precomp_repl(Replacement), Mlist). precomp_repl(<<>>) -> []; precomp_repl(<<$\\,$g,${,Rest/binary>>) when byte_size(Rest) > 0 -> {NS, <<$},NRest/binary>>} = pick_int(Rest), [list_to_integer(NS) | precomp_repl(NRest)]; precomp_repl(<<$\\,$g,Rest/binary>>) when byte_size(Rest) > 0 -> {NS,NRest} = pick_int(Rest), [list_to_integer(NS) | precomp_repl(NRest)]; precomp_repl(<<$\\,X,Rest/binary>>) when X < $1 ; X > $9 -> %% Escaped character case precomp_repl(Rest) of [BHead | T0] when is_binary(BHead) -> [<<X,BHead/binary>> | T0]; Other -> [<<X>> | Other] end; precomp_repl(<<$\\,Rest/binary>>) when byte_size(Rest) > 0-> {NS,NRest} = pick_int(Rest), [list_to_integer(NS) | precomp_repl(NRest)]; precomp_repl(<<$&,Rest/binary>>) -> [0 | precomp_repl(Rest)]; precomp_repl(<<X,Rest/binary>>) -> case precomp_repl(Rest) of [BHead | T0] when is_binary(BHead) -> [<<X,BHead/binary>> | T0]; Other -> [<<X>> | Other] end. pick_int(<<X,R/binary>>) when X >= $0, X =< $9 -> {Found,Rest} = pick_int(R), {[X|Found],Rest}; pick_int(Bin) -> {[],Bin}. do_mlist(_,<<>>,_,_,[]) -> []; %Avoid empty binary tail do_mlist(_,Subject,_,_,[]) -> Subject; do_mlist(Whole,Subject,Pos,Repl,[[{MPos,Count} | Sub] | Tail]) when MPos > Pos -> EatLength = MPos - Pos, <<Untouched:EatLength/binary, Rest/binary>> = Subject, [Untouched | do_mlist(Whole,Rest, MPos, Repl, [[{MPos,Count} | Sub] | Tail])]; do_mlist(Whole,Subject,Pos,Repl,[[{MPos,Count} | Sub] | Tail]) when MPos =:= Pos -> EatLength = Count, <<_:EatLength/binary,Rest/binary>> = Subject, NewData = do_replace(Whole,Repl,[{MPos,Count} | Sub]), [NewData | do_mlist(Whole,Rest,Pos+EatLength,Repl,Tail)]. do_replace(_,[Bin],_) when is_binary(Bin) -> Bin; do_replace(Subject,Repl,SubExprs0) -> SubExprs = list_to_tuple(SubExprs0), [ case Part of N when is_integer(N) -> if tuple_size(SubExprs) =< N -> <<>>; true -> {SPos,SLen} = element(N+1,SubExprs), if SPos < 0 -> <<>>; true -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Subject, Res end end; Other -> Other end || Part <- Repl ]. check_for_unicode({re_pattern,_,1,_,_},_) -> true; check_for_unicode({re_pattern,_,0,_,_},_) -> false; check_for_unicode(_,L) -> lists:member(unicode,L). check_for_crlf({re_pattern,_,_,1,_},_) -> true; check_for_crlf({re_pattern,_,_,0,_},_) -> false; check_for_crlf(_,L) -> case lists:keysearch(newline,1,L) of {value,{newline,any}} -> true; {value,{newline,crlf}} -> true; {value,{newline,anycrlf}} -> true; _ -> false end. % SelectReturn = false | all | stirpfirst | none ConvertReturn = index | list | binary % {capture, all} -> all (untouchded) % {capture, all_names} -> if names are present: treated as a name {capture, [...]} % else: same as {capture, []} { capture , first } - > kept in argument list and Select all { capture , all_but_first } - > removed from argument list and selects stripfirst % {capture, none} -> removed from argument list and selects none % {capture, []} -> removed from argument list and selects none { capture , [ ... ] } - > 0 added to selection list and selects stripfirst SelectReturn false is same as all in the end . Call as process_parameters([],0,false , index , NeedClean ) process_parameters([],InitialOffset, SelectReturn, ConvertReturn,_,_) -> {[], InitialOffset, SelectReturn, ConvertReturn}; process_parameters([{offset, N} | T],_Init0,Select0,Return0,CC,RE) -> process_parameters(T,N,Select0,Return0,CC,RE); process_parameters([global | T],Init0,Select0,Return0,CC,RE) -> process_parameters(T,Init0,Select0,Return0,CC,RE); process_parameters([{capture,Values,Type}|T],Init0,Select0,_Return0,CC,RE) -> process_parameters([{capture,Values}|T],Init0,Select0,Type,CC,RE); process_parameters([{capture,Values}|T],Init0,Select0,Return0,CC,RE) -> First process the rest to see if capture was already present {NewTail, Init1, Select1, Return1} = process_parameters(T,Init0,Select0,Return0,CC,RE), case Select1 of false -> case Values of all -> {[{capture,all} | NewTail], Init1, all, Return0}; all_names -> case re:inspect(RE,namelist) of {namelist, []} -> {[{capture,first} | NewTail], Init1, none, Return0}; {namelist, List} -> {[{capture,[0|List]} | NewTail], Init1, stripfirst, Return0} end; first -> {[{capture,first} | NewTail], Init1, all, Return0}; all_but_first -> {[{capture,all} | NewTail], Init1, stripfirst, Return0}; none -> {[{capture,first} | NewTail], Init1, none, Return0}; [] -> {[{capture,first} | NewTail], Init1, none, Return0}; List when is_list(List) -> {[{capture,[0|List]} | NewTail], Init1, stripfirst, Return0}; _ -> throw(badlist) end; _ -> Found overriding further down list , ignore this one {NewTail, Init1, Select1, Return1} end; process_parameters([H|T],Init0,Select0,Return0,true,RE) -> case copt(H) of true -> process_parameters(T,Init0,Select0,Return0,true,RE); false -> {NewT,Init,Select,Return} = process_parameters(T,Init0,Select0,Return0,true,RE), {[H|NewT],Init,Select,Return} end; process_parameters([H|T],Init0,Select0,Return0,false,RE) -> {NewT,Init,Select,Return} = process_parameters(T,Init0,Select0,Return0,false,RE), {[H|NewT],Init,Select,Return}; process_parameters(_,_,_,_,_,_) -> throw(badlist). postprocess({match,[]},_,_,_,_) -> nomatch; postprocess({match,_},none,_,_,_) -> match; postprocess({match,M},Any,binary,Flat,Uni) -> binarify(postprocess({match,M},Any,index,Flat,Uni),Flat); postprocess({match,M},Any,list,Flat,Uni) -> listify(postprocess({match,M},Any,index,Flat,Uni),Flat,Uni); postprocess({match,M},all,index,_,_) -> {match,M}; postprocess({match,M},false,index,_,_) -> {match,M}; postprocess({match,M},stripfirst,index,_,_) -> {match, [ T || [_|T] <- M ]}. binarify({match,M},Flat) -> {match, [ [ case {I,L} of {-1,0} -> <<>>; {SPos,SLen} -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, Res end || {I,L} <- One ] || One <- M ]}. listify({match,M},Flat,Uni) -> {match, [ [ case {I,L} of {_,0} -> []; {SPos,SLen} -> case Uni of true -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, unicode:characters_to_list(Res,unicode); false -> Start = SPos + 1, End = SPos + SLen, binary_to_list(Flat,Start,End) end end || {I,L} <- One ] || One <- M ]}. ubinarify({match,M},Flat) -> {match, [ case {I,L} of {-1,0} -> <<>>; {SPos,SLen} -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, Res end || {I,L} <- M ]}; ubinarify(Else,_) -> Else. ulistify({match,M},Flat) -> {match, [ case {I,L} of {_,0} -> []; {SPos,SLen} -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, unicode:characters_to_list(Res,unicode) end || {I,L} <- M ]}; ulistify(Else,_) -> Else. process_uparams([global|_T],_RetType) -> throw(false); process_uparams([{capture,Values,Type}|T],_OldType) -> process_uparams([{capture,Values}|T],Type); process_uparams([H|T],Type) -> {NL,NType} = process_uparams(T,Type), {[H|NL],NType}; process_uparams([],Type) -> {[],Type}. ucompile(RE,Options) -> try re:compile(unicode:characters_to_binary(RE,unicode),Options) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [RE,Options])), erlang:raise(error,AnyError,[{Mod,compile,L,Loc}|Rest]) end. urun(Subject,RE,Options) -> try urun2(Subject,RE,Options) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [Subject,RE,Options])), erlang:raise(error,AnyError,[{Mod,run,L,Loc}|Rest]) end. urun2(Subject0,RE0,Options0) -> {Options,RetType} = case (catch process_uparams(Options0,index)) of {A,B} -> {A,B}; _ -> {Options0,false} end, Subject = unicode:characters_to_binary(Subject0,unicode), RE = case RE0 of BinRE when is_binary(BinRE) -> BinRE; {re_pattern,_,_,_,_} = ReCompiled -> ReCompiled; ListRE -> unicode:characters_to_binary(ListRE,unicode) end, Ret = re:run(Subject,RE,Options), case RetType of binary -> ubinarify(Ret,Subject); list -> ulistify(Ret,Subject); _ -> Ret end. Might be called either with two - tuple ( if regexp was already compiled ) or with 3 - tuple ( saving original RE for exceptions grun(Subject,RE,{Options,NeedClean}) -> try grun2(Subject,RE,{Options,NeedClean}) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [Subject,RE,Options])), erlang:raise(error,AnyError,[{Mod,run,L,Loc}|Rest]) end; grun(Subject,RE,{Options,NeedClean,OrigRE}) -> try grun2(Subject,RE,{Options,NeedClean}) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [Subject,OrigRE,Options])), erlang:raise(error,AnyError,[{Mod,run,L,Loc}|Rest]) end. grun2(Subject,RE,{Options,NeedClean}) -> Unicode = check_for_unicode(RE,Options), CRLF = check_for_crlf(RE,Options), FlatSubject = to_binary(Subject, Unicode), do_grun(FlatSubject,Subject,Unicode,CRLF,RE,{Options,NeedClean}). do_grun(FlatSubject,Subject,Unicode,CRLF,RE,{Options0,NeedClean}) -> {StrippedOptions, InitialOffset, SelectReturn, ConvertReturn} = case (catch process_parameters(Options0, 0, false, index, NeedClean,RE)) of badlist -> erlang:error(badarg,[Subject,RE,Options0]); CorrectReturn -> CorrectReturn end, try postprocess(loopexec(FlatSubject,RE,InitialOffset, byte_size(FlatSubject), Unicode,CRLF,StrippedOptions), SelectReturn,ConvertReturn,FlatSubject,Unicode) catch throw:ErrTuple -> ErrTuple end. loopexec(_,_,X,Y,_,_,_) when X > Y -> {match,[]}; loopexec(Subject,RE,X,Y,Unicode,CRLF,Options) -> case re:run(Subject,RE,[{offset,X}]++Options) of {error, Err} -> throw({error,Err}); nomatch -> {match,[]}; {match,[{A,B}|More]} -> {match,Rest} = case B>0 of true -> loopexec(Subject,RE,A+B,Y,Unicode,CRLF,Options); false -> {match,M} = case re:run(Subject,RE,[{offset,X},notempty_atstart, anchored]++Options) of nomatch -> {match,[]}; {match,Other} -> {match,Other} end, NewA = case M of [{_,NStep}|_] when NStep > 0 -> A+NStep; _ -> forward(Subject,A,1,Unicode,CRLF) end, {match,MM} = loopexec(Subject,RE,NewA,Y, Unicode,CRLF,Options), case M of [] -> {match,MM}; _ -> {match,[M | MM]} end end, {match,[[{A,B}|More] | Rest]} end. forward(_Chal,A,0,_,_) -> A; forward(Chal,A,N,U,true) -> <<_:A/binary,Tl/binary>> = Chal, case Tl of <<$\r,$\n,_/binary>> -> forward(Chal,A+2,N-1,U,true); _ -> forward2(Chal,A,N,U,true) end; forward(Chal,A,N,U,false) -> forward2(Chal,A,N,U,false). forward2(Chal,A,N,false,CRLF) -> forward(Chal,A+1,N-1,false,CRLF); forward2(Chal,A,N,true,CRLF) -> <<_:A/binary,Tl/binary>> = Chal, Forw = case Tl of <<1:1,1:1,0:1,_:5,_/binary>> -> 2; <<1:1,1:1,1:1,0:1,_:4,_/binary>> -> 3; <<1:1,1:1,1:1,1:1,0:1,_:3,_/binary>> -> 4; _ -> 1 end, forward(Chal,A+Forw,N-1,true,CRLF). copt(caseless) -> true; copt(no_start_optimize) -> true; copt(never_utf) -> true; copt(ucp) -> true; copt(dollar_endonly) -> true; copt(dotall) -> true; copt(extended) -> true; copt(firstline) -> true; copt(multiline) -> true; copt(no_auto_capture) -> true; copt(dupnames) -> true; copt(ungreedy) -> true; copt(unicode) -> true; copt(_) -> false. %bothopt({newline,_}) -> % true; %bothopt(anchored) -> % true; ( _ ) - > % false. runopt(notempty) -> true; runopt(notempty_atstart) -> true; runopt(notbol) -> true; runopt(noteol) -> true; runopt({offset,_}) -> true; runopt({capture,_,_}) -> true; runopt({capture,_}) -> true; runopt(global) -> true; runopt({match_limit,_}) -> true; runopt({match_limit_recursion,_}) -> true; runopt(_) -> false. to_binary(Bin, _IsUnicode) when is_binary(Bin) -> Bin; to_binary(Data, true) -> unicode:characters_to_binary(Data,unicode); to_binary(Data, false) -> iolist_to_binary(Data).
null
https://raw.githubusercontent.com/vereis/jarlang/72105b79c1861aa6c4f51c3b50ba695338aafba4/src/erl/lib/stdlib/re.erl
erlang
%CopyrightBegin% 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. %CopyrightEnd% BIFs End of BIFs OK, lets run Escaped character Avoid empty binary tail SelectReturn = false | all | stirpfirst | none {capture, all} -> all (untouchded) {capture, all_names} -> if names are present: treated as a name {capture, [...]} else: same as {capture, []} {capture, none} -> removed from argument list and selects none {capture, []} -> removed from argument list and selects none bothopt({newline,_}) -> true; bothopt(anchored) -> true; false.
Copyright Ericsson AB 2008 - 2017 . 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(re). -export([grun/3,urun/3,ucompile/2,replace/3,replace/4,split/2,split/3]). -type mp() :: {re_pattern, _, _, _, _}. -type nl_spec() :: cr | crlf | lf | anycrlf | any. -type compile_option() :: unicode | anchored | caseless | dollar_endonly | dotall | extended | firstline | multiline | no_auto_capture | dupnames | ungreedy | {newline, nl_spec()} | bsr_anycrlf | bsr_unicode | no_start_optimize | ucp | never_utf. -export([version/0, compile/1, compile/2, run/2, run/3, inspect/2]). -spec version() -> binary(). version() -> erlang:nif_error(undef). -spec compile(Regexp) -> {ok, MP} | {error, ErrSpec} when Regexp :: iodata(), MP :: mp(), ErrSpec :: {ErrString :: string(), Position :: non_neg_integer()}. compile(_) -> erlang:nif_error(undef). -spec compile(Regexp, Options) -> {ok, MP} | {error, ErrSpec} when Regexp :: iodata() | unicode:charlist(), Options :: [Option], Option :: compile_option(), MP :: mp(), ErrSpec :: {ErrString :: string(), Position :: non_neg_integer()}. compile(_, _) -> erlang:nif_error(undef). -spec run(Subject, RE) -> {match, Captured} | nomatch when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata(), Captured :: [CaptureData], CaptureData :: {integer(), integer()}. run(_, _) -> erlang:nif_error(undef). -spec run(Subject, RE, Options) -> {match, Captured} | match | nomatch | {error, ErrType} when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata() | unicode:charlist(), Options :: [Option], Option :: anchored | global | notbol | noteol | notempty | notempty_atstart | report_errors | {offset, non_neg_integer()} | {match_limit, non_neg_integer()} | {match_limit_recursion, non_neg_integer()} | {newline, NLSpec :: nl_spec()} | bsr_anycrlf | bsr_unicode | {capture, ValueSpec} | {capture, ValueSpec, Type} | CompileOpt, Type :: index | list | binary, ValueSpec :: all | all_but_first | all_names | first | none | ValueList, ValueList :: [ValueID], ValueID :: integer() | string() | atom(), CompileOpt :: compile_option(), Captured :: [CaptureData] | [[CaptureData]], CaptureData :: {integer(), integer()} | ListConversionData | binary(), ListConversionData :: string() | {error, string(), binary()} | {incomplete, string(), binary()}, ErrType :: match_limit | match_limit_recursion | {compile, CompileErr}, CompileErr :: {ErrString :: string(), Position :: non_neg_integer()}. run(_, _, _) -> erlang:nif_error(undef). -spec inspect(MP,Item) -> {namelist, [ binary() ]} when MP :: mp(), Item :: namelist. inspect(_,_) -> erlang:nif_error(undef). -spec split(Subject, RE) -> SplitList when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata(), SplitList :: [iodata() | unicode:charlist()]. split(Subject,RE) -> split(Subject,RE,[]). -spec split(Subject, RE, Options) -> SplitList when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata() | unicode:charlist(), Options :: [ Option ], Option :: anchored | notbol | noteol | notempty | notempty_atstart | {offset, non_neg_integer()} | {newline, nl_spec()} | {match_limit, non_neg_integer()} | {match_limit_recursion, non_neg_integer()} | bsr_anycrlf | bsr_unicode | {return, ReturnType} | {parts, NumParts} | group | trim | CompileOpt, NumParts :: non_neg_integer() | infinity, ReturnType :: iodata | list | binary, CompileOpt :: compile_option(), SplitList :: [RetData] | [GroupedRetData], GroupedRetData :: [RetData], RetData :: iodata() | unicode:charlist() | binary() | list(). split(Subject,RE,Options) -> try {NewOpt,Convert,Limit,Strip,Group} = process_split_params(Options,iodata,-1,false,false), Unicode = check_for_unicode(RE, Options), FlatSubject = to_binary(Subject, Unicode), case compile_split(RE,NewOpt) of {error,_Err} -> throw(badre); {PreCompiled, NumSub, RunOpt} -> case re:run(FlatSubject,PreCompiled,RunOpt ++ [global]) of nomatch -> case Group of true -> convert_any_split_result([[FlatSubject]], Convert, Unicode, true); false -> convert_any_split_result([FlatSubject], Convert, Unicode, false) end; {match, Matches} -> Res = do_split(FlatSubject, 0, Matches, NumSub, Limit, Group), Stripped = case Strip of true -> backstrip_empty(Res,Group); false -> Res end, convert_any_split_result(Stripped, Convert, Unicode, Group) end end catch throw:badopt -> erlang:error(badarg,[Subject,RE,Options]); throw:badre -> erlang:error(badarg,[Subject,RE,Options]); error:badarg -> erlang:error(badarg,[Subject,RE,Options]) end. backstrip_empty(List, false) -> do_backstrip_empty(List); backstrip_empty(List, true) -> do_backstrip_empty_g(List). do_backstrip_empty_g([]) -> []; do_backstrip_empty_g([H]) -> case do_backstrip_empty(H) of [] -> []; _ -> [H] end; do_backstrip_empty_g([H|T]) -> case do_backstrip_empty_g(T) of [] -> case do_backstrip_empty(H) of [] -> []; _ -> [H] end; Other -> [H|Other] end. do_backstrip_empty([]) -> []; do_backstrip_empty([<<>>]) -> []; do_backstrip_empty([<<>>|T]) -> case do_backstrip_empty(T) of [] -> []; Other -> [<<>>|Other] end; do_backstrip_empty([H|T]) -> [H|do_backstrip_empty(T)]. convert_any_split_result(List,Type,Uni,true) -> [ convert_split_result(Part,Type,Uni) || Part <- List ]; convert_any_split_result(List,Type,Uni, false) -> convert_split_result(List,Type,Uni). convert_split_result(List, iodata, _Unicode) -> List; convert_split_result(List, binary, _Unicode) -> As it happens , the iodata is actually binaries List; convert_split_result(List, list, true) -> [unicode:characters_to_list(Element,unicode) || Element <- List]; convert_split_result(List, list, false) -> [binary_to_list(Element) || Element <- List]. do_split(Subj, Off, _, _, 0, false) -> <<_:Off/binary,Rest/binary>> = Subj, [Rest]; do_split(Subj, Off, [], _, _, false) -> <<_:Off/binary,Rest/binary>> = Subj, [Rest]; do_split(Subj, Off, _, _, _,false) when byte_size(Subj) =< Off -> [<<>>]; do_split(Subj, Off, _, _, 0, true) -> <<_:Off/binary,Rest/binary>> = Subj, [[Rest]]; do_split(Subj, Off, [], _, _, true) -> <<_:Off/binary,Rest/binary>> = Subj, [[Rest]]; do_split(Subj, Off, _, _, _,true) when byte_size(Subj) =< Off -> [[<<>>]]; do_split(Subj, Offset, [[{MainI,MainL}|Sub]|T], NumSub, Limit, Group) -> NewOffset = MainI+MainL, KeptLen = MainI - Offset, case {KeptLen,empty_sub(Sub),MainL} of {0,true,0} -> do_split(Subj,NewOffset,T,NumSub,Limit,Group); _ -> <<_:Offset/binary,Keep:KeptLen/binary,_/binary>> = Subj, ESub = extend_subpatterns(Sub,NumSub), Tail = do_split(Subj, NewOffset, T, NumSub, Limit - 1,Group), case Group of false -> [Keep | dig_subpatterns(Subj,lists:reverse(ESub),Tail)]; true -> [[Keep | dig_subpatterns(Subj,lists:reverse(ESub),[])]| Tail] end end. empty_sub([]) -> true; empty_sub([{_,0}|T]) -> empty_sub(T); empty_sub(_) -> false. dig_subpatterns(_,[],Acc) -> Acc; dig_subpatterns(Subj,[{-1,0}|T],Acc) -> dig_subpatterns(Subj,T,[<<>>|Acc]); dig_subpatterns(Subj,[{I,L}|T],Acc) -> <<_:I/binary,Part:L/binary,_/binary>> = Subj, dig_subpatterns(Subj,T,[Part|Acc]). extend_subpatterns(_,0) -> []; extend_subpatterns([],N) -> [{0,0} | extend_subpatterns([],N-1)]; extend_subpatterns([H|T],N) -> [H | extend_subpatterns(T,N-1)]. compile_split({re_pattern,N,_,_,_} = Comp, Options) -> {Comp,N,Options}; compile_split(Pat,Options0) when not is_tuple(Pat) -> Options = lists:filter(fun(O) -> (not runopt(O)) end, Options0), case re:compile(Pat,Options) of {error,Err} -> {error,Err}; {ok, {re_pattern,N,_,_,_} = Comp} -> NewOpt = lists:filter(fun(OO) -> (not copt(OO)) end, Options0), {Comp,N,NewOpt} end; compile_split(_,_) -> throw(badre). -spec replace(Subject, RE, Replacement) -> iodata() | unicode:charlist() when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata(), Replacement :: iodata() | unicode:charlist(). replace(Subject,RE,Replacement) -> replace(Subject,RE,Replacement,[]). -spec replace(Subject, RE, Replacement, Options) -> iodata() | unicode:charlist() when Subject :: iodata() | unicode:charlist(), RE :: mp() | iodata() | unicode:charlist(), Replacement :: iodata() | unicode:charlist(), Options :: [Option], Option :: anchored | global | notbol | noteol | notempty | notempty_atstart | {offset, non_neg_integer()} | {newline, NLSpec} | bsr_anycrlf | {match_limit, non_neg_integer()} | {match_limit_recursion, non_neg_integer()} | bsr_unicode | {return, ReturnType} | CompileOpt, ReturnType :: iodata | list | binary, CompileOpt :: compile_option(), NLSpec :: cr | crlf | lf | anycrlf | any. replace(Subject,RE,Replacement,Options) -> try {NewOpt,Convert} = process_repl_params(Options,iodata), Unicode = check_for_unicode(RE, Options), FlatSubject = to_binary(Subject, Unicode), FlatReplacement = to_binary(Replacement, Unicode), IoList = do_replace(FlatSubject,Subject,RE,FlatReplacement,NewOpt), case Convert of iodata -> IoList; binary -> case Unicode of false -> iolist_to_binary(IoList); true -> unicode:characters_to_binary(IoList,unicode) end; list -> case Unicode of false -> binary_to_list(iolist_to_binary(IoList)); true -> unicode:characters_to_list(IoList,unicode) end end catch throw:badopt -> erlang:error(badarg,[Subject,RE,Replacement,Options]); throw:badre -> erlang:error(badarg,[Subject,RE,Replacement,Options]); error:badarg -> erlang:error(badarg,[Subject,RE,Replacement,Options]) end. do_replace(FlatSubject,Subject,RE,Replacement,Options) -> case re:run(FlatSubject,RE,Options) of nomatch -> Subject; {match,[Mlist|T]} when is_list(Mlist) -> apply_mlist(FlatSubject,Replacement,[Mlist|T]); {match,Slist} -> apply_mlist(FlatSubject,Replacement,[Slist]) end. process_repl_params([],Convert) -> {[],Convert}; process_repl_params([report_errors|_],_) -> throw(badopt); process_repl_params([{capture,_,_}|_],_) -> throw(badopt); process_repl_params([{capture,_}|_],_) -> throw(badopt); process_repl_params([{return,iodata}|T],_C) -> process_repl_params(T,iodata); process_repl_params([{return,list}|T],_C) -> process_repl_params(T,list); process_repl_params([{return,binary}|T],_C) -> process_repl_params(T,binary); process_repl_params([{return,_}|_],_) -> throw(badopt); process_repl_params([H|T],C) -> {NT,NC} = process_repl_params(T,C), {[H|NT],NC}. process_split_params([],Convert,Limit,Strip,Group) -> {[],Convert,Limit,Strip,Group}; process_split_params([trim|T],C,_L,_S,G) -> process_split_params(T,C,-1,true,G); process_split_params([{parts,0}|T],C,_L,_S,G) -> process_split_params(T,C,-1,true,G); process_split_params([{parts,N}|T],C,_L,_S,G) when is_integer(N), N >= 1 -> process_split_params(T,C,N-1,false,G); process_split_params([{parts,infinity}|T],C,_L,_S,G) -> process_split_params(T,C,-1,false,G); process_split_params([{parts,_}|_],_,_,_,_) -> throw(badopt); process_split_params([group|T],C,L,S,_G) -> process_split_params(T,C,L,S,true); process_split_params([global|_],_,_,_,_) -> throw(badopt); process_split_params([report_errors|_],_,_,_,_) -> throw(badopt); process_split_params([{capture,_,_}|_],_,_,_,_) -> throw(badopt); process_split_params([{capture,_}|_],_,_,_,_) -> throw(badopt); process_split_params([{return,iodata}|T],_C,L,S,G) -> process_split_params(T,iodata,L,S,G); process_split_params([{return,list}|T],_C,L,S,G) -> process_split_params(T,list,L,S,G); process_split_params([{return,binary}|T],_C,L,S,G) -> process_split_params(T,binary,L,S,G); process_split_params([{return,_}|_],_,_,_,_) -> throw(badopt); process_split_params([H|T],C,L,S,G) -> {NT,NC,NL,NS,NG} = process_split_params(T,C,L,S,G), {[H|NT],NC,NL,NS,NG}. apply_mlist(Subject,Replacement,Mlist) -> do_mlist(Subject,Subject,0,precomp_repl(Replacement), Mlist). precomp_repl(<<>>) -> []; precomp_repl(<<$\\,$g,${,Rest/binary>>) when byte_size(Rest) > 0 -> {NS, <<$},NRest/binary>>} = pick_int(Rest), [list_to_integer(NS) | precomp_repl(NRest)]; precomp_repl(<<$\\,$g,Rest/binary>>) when byte_size(Rest) > 0 -> {NS,NRest} = pick_int(Rest), [list_to_integer(NS) | precomp_repl(NRest)]; precomp_repl(<<$\\,X,Rest/binary>>) when X < $1 ; X > $9 -> case precomp_repl(Rest) of [BHead | T0] when is_binary(BHead) -> [<<X,BHead/binary>> | T0]; Other -> [<<X>> | Other] end; precomp_repl(<<$\\,Rest/binary>>) when byte_size(Rest) > 0-> {NS,NRest} = pick_int(Rest), [list_to_integer(NS) | precomp_repl(NRest)]; precomp_repl(<<$&,Rest/binary>>) -> [0 | precomp_repl(Rest)]; precomp_repl(<<X,Rest/binary>>) -> case precomp_repl(Rest) of [BHead | T0] when is_binary(BHead) -> [<<X,BHead/binary>> | T0]; Other -> [<<X>> | Other] end. pick_int(<<X,R/binary>>) when X >= $0, X =< $9 -> {Found,Rest} = pick_int(R), {[X|Found],Rest}; pick_int(Bin) -> {[],Bin}. do_mlist(_,<<>>,_,_,[]) -> do_mlist(_,Subject,_,_,[]) -> Subject; do_mlist(Whole,Subject,Pos,Repl,[[{MPos,Count} | Sub] | Tail]) when MPos > Pos -> EatLength = MPos - Pos, <<Untouched:EatLength/binary, Rest/binary>> = Subject, [Untouched | do_mlist(Whole,Rest, MPos, Repl, [[{MPos,Count} | Sub] | Tail])]; do_mlist(Whole,Subject,Pos,Repl,[[{MPos,Count} | Sub] | Tail]) when MPos =:= Pos -> EatLength = Count, <<_:EatLength/binary,Rest/binary>> = Subject, NewData = do_replace(Whole,Repl,[{MPos,Count} | Sub]), [NewData | do_mlist(Whole,Rest,Pos+EatLength,Repl,Tail)]. do_replace(_,[Bin],_) when is_binary(Bin) -> Bin; do_replace(Subject,Repl,SubExprs0) -> SubExprs = list_to_tuple(SubExprs0), [ case Part of N when is_integer(N) -> if tuple_size(SubExprs) =< N -> <<>>; true -> {SPos,SLen} = element(N+1,SubExprs), if SPos < 0 -> <<>>; true -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Subject, Res end end; Other -> Other end || Part <- Repl ]. check_for_unicode({re_pattern,_,1,_,_},_) -> true; check_for_unicode({re_pattern,_,0,_,_},_) -> false; check_for_unicode(_,L) -> lists:member(unicode,L). check_for_crlf({re_pattern,_,_,1,_},_) -> true; check_for_crlf({re_pattern,_,_,0,_},_) -> false; check_for_crlf(_,L) -> case lists:keysearch(newline,1,L) of {value,{newline,any}} -> true; {value,{newline,crlf}} -> true; {value,{newline,anycrlf}} -> true; _ -> false end. ConvertReturn = index | list | binary { capture , first } - > kept in argument list and Select all { capture , all_but_first } - > removed from argument list and selects stripfirst { capture , [ ... ] } - > 0 added to selection list and selects stripfirst SelectReturn false is same as all in the end . Call as process_parameters([],0,false , index , NeedClean ) process_parameters([],InitialOffset, SelectReturn, ConvertReturn,_,_) -> {[], InitialOffset, SelectReturn, ConvertReturn}; process_parameters([{offset, N} | T],_Init0,Select0,Return0,CC,RE) -> process_parameters(T,N,Select0,Return0,CC,RE); process_parameters([global | T],Init0,Select0,Return0,CC,RE) -> process_parameters(T,Init0,Select0,Return0,CC,RE); process_parameters([{capture,Values,Type}|T],Init0,Select0,_Return0,CC,RE) -> process_parameters([{capture,Values}|T],Init0,Select0,Type,CC,RE); process_parameters([{capture,Values}|T],Init0,Select0,Return0,CC,RE) -> First process the rest to see if capture was already present {NewTail, Init1, Select1, Return1} = process_parameters(T,Init0,Select0,Return0,CC,RE), case Select1 of false -> case Values of all -> {[{capture,all} | NewTail], Init1, all, Return0}; all_names -> case re:inspect(RE,namelist) of {namelist, []} -> {[{capture,first} | NewTail], Init1, none, Return0}; {namelist, List} -> {[{capture,[0|List]} | NewTail], Init1, stripfirst, Return0} end; first -> {[{capture,first} | NewTail], Init1, all, Return0}; all_but_first -> {[{capture,all} | NewTail], Init1, stripfirst, Return0}; none -> {[{capture,first} | NewTail], Init1, none, Return0}; [] -> {[{capture,first} | NewTail], Init1, none, Return0}; List when is_list(List) -> {[{capture,[0|List]} | NewTail], Init1, stripfirst, Return0}; _ -> throw(badlist) end; _ -> Found overriding further down list , ignore this one {NewTail, Init1, Select1, Return1} end; process_parameters([H|T],Init0,Select0,Return0,true,RE) -> case copt(H) of true -> process_parameters(T,Init0,Select0,Return0,true,RE); false -> {NewT,Init,Select,Return} = process_parameters(T,Init0,Select0,Return0,true,RE), {[H|NewT],Init,Select,Return} end; process_parameters([H|T],Init0,Select0,Return0,false,RE) -> {NewT,Init,Select,Return} = process_parameters(T,Init0,Select0,Return0,false,RE), {[H|NewT],Init,Select,Return}; process_parameters(_,_,_,_,_,_) -> throw(badlist). postprocess({match,[]},_,_,_,_) -> nomatch; postprocess({match,_},none,_,_,_) -> match; postprocess({match,M},Any,binary,Flat,Uni) -> binarify(postprocess({match,M},Any,index,Flat,Uni),Flat); postprocess({match,M},Any,list,Flat,Uni) -> listify(postprocess({match,M},Any,index,Flat,Uni),Flat,Uni); postprocess({match,M},all,index,_,_) -> {match,M}; postprocess({match,M},false,index,_,_) -> {match,M}; postprocess({match,M},stripfirst,index,_,_) -> {match, [ T || [_|T] <- M ]}. binarify({match,M},Flat) -> {match, [ [ case {I,L} of {-1,0} -> <<>>; {SPos,SLen} -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, Res end || {I,L} <- One ] || One <- M ]}. listify({match,M},Flat,Uni) -> {match, [ [ case {I,L} of {_,0} -> []; {SPos,SLen} -> case Uni of true -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, unicode:characters_to_list(Res,unicode); false -> Start = SPos + 1, End = SPos + SLen, binary_to_list(Flat,Start,End) end end || {I,L} <- One ] || One <- M ]}. ubinarify({match,M},Flat) -> {match, [ case {I,L} of {-1,0} -> <<>>; {SPos,SLen} -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, Res end || {I,L} <- M ]}; ubinarify(Else,_) -> Else. ulistify({match,M},Flat) -> {match, [ case {I,L} of {_,0} -> []; {SPos,SLen} -> <<_:SPos/binary,Res:SLen/binary,_/binary>> = Flat, unicode:characters_to_list(Res,unicode) end || {I,L} <- M ]}; ulistify(Else,_) -> Else. process_uparams([global|_T],_RetType) -> throw(false); process_uparams([{capture,Values,Type}|T],_OldType) -> process_uparams([{capture,Values}|T],Type); process_uparams([H|T],Type) -> {NL,NType} = process_uparams(T,Type), {[H|NL],NType}; process_uparams([],Type) -> {[],Type}. ucompile(RE,Options) -> try re:compile(unicode:characters_to_binary(RE,unicode),Options) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [RE,Options])), erlang:raise(error,AnyError,[{Mod,compile,L,Loc}|Rest]) end. urun(Subject,RE,Options) -> try urun2(Subject,RE,Options) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [Subject,RE,Options])), erlang:raise(error,AnyError,[{Mod,run,L,Loc}|Rest]) end. urun2(Subject0,RE0,Options0) -> {Options,RetType} = case (catch process_uparams(Options0,index)) of {A,B} -> {A,B}; _ -> {Options0,false} end, Subject = unicode:characters_to_binary(Subject0,unicode), RE = case RE0 of BinRE when is_binary(BinRE) -> BinRE; {re_pattern,_,_,_,_} = ReCompiled -> ReCompiled; ListRE -> unicode:characters_to_binary(ListRE,unicode) end, Ret = re:run(Subject,RE,Options), case RetType of binary -> ubinarify(Ret,Subject); list -> ulistify(Ret,Subject); _ -> Ret end. Might be called either with two - tuple ( if regexp was already compiled ) or with 3 - tuple ( saving original RE for exceptions grun(Subject,RE,{Options,NeedClean}) -> try grun2(Subject,RE,{Options,NeedClean}) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [Subject,RE,Options])), erlang:raise(error,AnyError,[{Mod,run,L,Loc}|Rest]) end; grun(Subject,RE,{Options,NeedClean,OrigRE}) -> try grun2(Subject,RE,{Options,NeedClean}) catch error:AnyError -> {'EXIT',{new_stacktrace,[{Mod,_,L,Loc}|Rest]}} = (catch erlang:error(new_stacktrace, [Subject,OrigRE,Options])), erlang:raise(error,AnyError,[{Mod,run,L,Loc}|Rest]) end. grun2(Subject,RE,{Options,NeedClean}) -> Unicode = check_for_unicode(RE,Options), CRLF = check_for_crlf(RE,Options), FlatSubject = to_binary(Subject, Unicode), do_grun(FlatSubject,Subject,Unicode,CRLF,RE,{Options,NeedClean}). do_grun(FlatSubject,Subject,Unicode,CRLF,RE,{Options0,NeedClean}) -> {StrippedOptions, InitialOffset, SelectReturn, ConvertReturn} = case (catch process_parameters(Options0, 0, false, index, NeedClean,RE)) of badlist -> erlang:error(badarg,[Subject,RE,Options0]); CorrectReturn -> CorrectReturn end, try postprocess(loopexec(FlatSubject,RE,InitialOffset, byte_size(FlatSubject), Unicode,CRLF,StrippedOptions), SelectReturn,ConvertReturn,FlatSubject,Unicode) catch throw:ErrTuple -> ErrTuple end. loopexec(_,_,X,Y,_,_,_) when X > Y -> {match,[]}; loopexec(Subject,RE,X,Y,Unicode,CRLF,Options) -> case re:run(Subject,RE,[{offset,X}]++Options) of {error, Err} -> throw({error,Err}); nomatch -> {match,[]}; {match,[{A,B}|More]} -> {match,Rest} = case B>0 of true -> loopexec(Subject,RE,A+B,Y,Unicode,CRLF,Options); false -> {match,M} = case re:run(Subject,RE,[{offset,X},notempty_atstart, anchored]++Options) of nomatch -> {match,[]}; {match,Other} -> {match,Other} end, NewA = case M of [{_,NStep}|_] when NStep > 0 -> A+NStep; _ -> forward(Subject,A,1,Unicode,CRLF) end, {match,MM} = loopexec(Subject,RE,NewA,Y, Unicode,CRLF,Options), case M of [] -> {match,MM}; _ -> {match,[M | MM]} end end, {match,[[{A,B}|More] | Rest]} end. forward(_Chal,A,0,_,_) -> A; forward(Chal,A,N,U,true) -> <<_:A/binary,Tl/binary>> = Chal, case Tl of <<$\r,$\n,_/binary>> -> forward(Chal,A+2,N-1,U,true); _ -> forward2(Chal,A,N,U,true) end; forward(Chal,A,N,U,false) -> forward2(Chal,A,N,U,false). forward2(Chal,A,N,false,CRLF) -> forward(Chal,A+1,N-1,false,CRLF); forward2(Chal,A,N,true,CRLF) -> <<_:A/binary,Tl/binary>> = Chal, Forw = case Tl of <<1:1,1:1,0:1,_:5,_/binary>> -> 2; <<1:1,1:1,1:1,0:1,_:4,_/binary>> -> 3; <<1:1,1:1,1:1,1:1,0:1,_:3,_/binary>> -> 4; _ -> 1 end, forward(Chal,A+Forw,N-1,true,CRLF). copt(caseless) -> true; copt(no_start_optimize) -> true; copt(never_utf) -> true; copt(ucp) -> true; copt(dollar_endonly) -> true; copt(dotall) -> true; copt(extended) -> true; copt(firstline) -> true; copt(multiline) -> true; copt(no_auto_capture) -> true; copt(dupnames) -> true; copt(ungreedy) -> true; copt(unicode) -> true; copt(_) -> false. ( _ ) - > runopt(notempty) -> true; runopt(notempty_atstart) -> true; runopt(notbol) -> true; runopt(noteol) -> true; runopt({offset,_}) -> true; runopt({capture,_,_}) -> true; runopt({capture,_}) -> true; runopt(global) -> true; runopt({match_limit,_}) -> true; runopt({match_limit_recursion,_}) -> true; runopt(_) -> false. to_binary(Bin, _IsUnicode) when is_binary(Bin) -> Bin; to_binary(Data, true) -> unicode:characters_to_binary(Data,unicode); to_binary(Data, false) -> iolist_to_binary(Data).
75817eb065078ee146ffdb61cc16fcbbb04c70517013b3ce3ef474d9716eaed9
lixiangqi/medic
debug.rkt
#lang racket (require medic/core) (medic "src5-medic.rkt") (debug "src5.rkt")
null
https://raw.githubusercontent.com/lixiangqi/medic/0920090d3c77d6873b8481841622a5f2d13a732c/demos/demo5/debug.rkt
racket
#lang racket (require medic/core) (medic "src5-medic.rkt") (debug "src5.rkt")
3f483bcae97ef4c071ddf2d5b746be2ad831b42780a0531c2d07258ff26f32b0
seantempesta/cljs-react-navigation
base.cljs
(ns cljs-react-navigation.base (:require [cljs.spec.alpha :as s :include-macros true] [goog.object :as gobj] [reagent.core :as r] [reagent.impl.component :as ric])) (defonce React (js/require "react")) (defonce ReactNavigation (js/require "react-navigation")) (defonce isValidElement (gobj/get React #js ["isValidElement"])) Core (defonce createNavigationContainer (gobj/get ReactNavigation #js ["createNavigationContainer"])) (defonce StateUtils (gobj/get ReactNavigation #js ["StateUtils"])) (defonce addNavigationHelpers (gobj/get ReactNavigation #js ["addNavigationHelpers"])) (defonce NavigationActions (gobj/get ReactNavigation #js ["NavigationActions"])) (defonce NavigationActionsMap {"Navigation/INIT" (gobj/get NavigationActions #js ["init"]) "Navigation/URI" (gobj/get NavigationActions #js ["uri"]) "Navigation/NAVIGATE" (gobj/get NavigationActions #js ["navigate"]) "Navigation/BACK" (gobj/get NavigationActions #js ["back"]) "Navigation/RESET" (gobj/get NavigationActions #js ["reset"]) "Navigation/SET_PARAMS" (gobj/get NavigationActions #js ["setParams"])}) ;; Navigators (defonce createNavigator (gobj/get ReactNavigation #js ["createNavigator"])) (defonce StackNavigator (gobj/get ReactNavigation #js ["StackNavigator"])) (defonce TabNavigator (gobj/get ReactNavigation #js ["TabNavigator"])) (defonce DrawerNavigator (gobj/get ReactNavigation #js ["DrawerNavigator"])) (defonce SwitchNavigator (gobj/get ReactNavigation #js ["SwitchNavigator"])) Routers (defonce StackRouter (gobj/get ReactNavigation #js ["StackRouter"])) (defonce TabRouter (gobj/get ReactNavigation #js ["TabRouter"])) ;; Views (defonce Transitioner (gobj/get ReactNavigation #js ["Transitioner"])) (defonce CardStack (gobj/get ReactNavigation #js ["CardStack"])) (defonce DrawerView (gobj/get ReactNavigation #js ["DrawerView"])) (defonce TabView (gobj/get ReactNavigation #js ["TabView"])) (assert (and React ReactNavigation) "React and React Navigation must be installed. Maybe NPM install them and restart the packager?") Spec conforming functions ;; (defn react-component? "Spec conforming function. Accepts a react class or returns :cljs.spec.alpha/invalid." [c] (cond (ric/react-class? c) c :else :cljs.spec.alpha/invalid)) (defn react-element? "Spec conforming function. Accepts either a react element, conforms a react class to an element, or returns :cljs.spec.alpha/invalid." [e] (cond (isValidElement e) e (ric/react-class? e) (r/create-element e) :else :cljs.spec.alpha/invalid)) (defn string-or-react-component? "Accepts either a string, react component, or a fn that returns a react component. If it's a fn, props will automatically convert (js->clj) when the fn is called." [s-or-c] (cond (ric/react-class? s-or-c) s-or-c (string? s-or-c) s-or-c (fn? s-or-c) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (s-or-c clj-props children)] react-c)) :else :cljs.spec.alpha/invalid)) (defn string-or-react-element? [s-or-e] (cond (isValidElement s-or-e) s-or-e (ric/react-class? s-or-e) (r/create-element s-or-e) (fn? s-or-e) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (s-or-e clj-props children) react-e (r/create-element react-c)] react-e)) (string? s-or-e) s-or-e :else :cljs.spec.alpha/invalid)) (defn fn-or-react-component? "Confirms either a valid react component was passed in or a function that returns a react component. If it's a function, props will be converted to clojure structures with keywords. Expects the fn to return a valid component" [fn-or-c] (cond (ric/react-class? fn-or-c) fn-or-c (fn? fn-or-c) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (fn-or-c clj-props children)] react-c)) :else :cljs.spec.alpha/invalid)) (defn fn-or-react-element? "Confirms either a valid react element was passed in or a function that returns a react element. If it's a function, props will be converted to clojure structures with keywords. Expects the fn to return a valid component" [fn-or-e] (cond (isValidElement fn-or-e) fn-or-e (ric/react-class? fn-or-e) (r/create-element fn-or-e) (fn? fn-or-e) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (fn-or-e clj-props children) react-e (r/create-element react-c)] react-e)) :else :cljs.spec.alpha/invalid)) (defn navigation-options? "Conforms a clj map (or a function that returns a clj map) to a js object" [map-or-fn] (cond (map? map-or-fn) (s/conform :react-navigation.navigationOptions/all map-or-fn) (fn? map-or-fn) (fn [props] (let [clj-props (js->clj props :keywordize-keys true) fn-output (map-or-fn clj-props) conformed (s/conform :react-navigation.navigationOptions/all fn-output) conformed-js (clj->js conformed)] conformed-js)) :else :cljs.spec.alpha/invalid)) ;; React (s/def :react/component (s/conformer react-component?)) (s/def :react/element (s/conformer react-element?)) navigationOptions ( merged both Screen and Tabs for my sanity ) (s/def :react-navigation.navigationOptions/title string?) (s/def :react-navigation.navigationOptions/headerVisible boolean?) (s/def :react-navigation.navigationOptions/headerTitle (s/conformer string-or-react-element?)) (s/def :react-navigation.navigationOptions/headerBackTitle string?) (s/def :react-navigation.navigationOptions/headerRight (s/conformer string-or-react-element?)) (s/def :react-navigation.navigationOptions/headerLeft (s/conformer string-or-react-element?)) (s/def :react-navigation.navigationOptions/headerStyle map?) (s/def :react-navigation.navigationOptions/headerTitleStyle map?) (s/def :react-navigation.navigationOptions/headerTintColor string?) (s/def :react-navigation.navigationOptions/headerPressColorAndroid string?) (s/def :react-navigation.navigationOptions/gesturesEnabled boolean?) (s/def :react-navigation.navigationOptions/tabBarVisible boolean?) (s/def :react-navigation.navigationOptions/tabBarIcon (s/conformer fn-or-react-element?)) (s/def :react-navigation.navigationOptions/tabBarLabel string?) (s/def :react-navigation.navigationOptions/all (s/keys :opt-un [:react-navigation.navigationOptions/title :react-navigation.navigationOptions/headerVisible :react-navigation.navigationOptions/headerTitle :react-navigation.navigationOptions/headerBackTitle :react-navigation.navigationOptions/headerRight :react-navigation.navigationOptions/headerLeft :react-navigation.navigationOptions/headerStyle :react-navigation.navigationOptions/headerTitleStyle :react-navigation.navigationOptions/headerTintColor :react-navigation.navigationOptions/headerPressColorAndroid :react-navigation.navigationOptions/gesturesEnabled :react-navigation.navigationOptions/tabBarVisible :react-navigation.navigationOptions/tabBarIcon :react-navigation.navigationOptions/tabBarLabel])) (s/def :react-navigation/navigationOptions (s/nilable (s/conformer navigation-options?))) ;; RouteConfigs (s/def :react-navigation.RouteConfigs.route/screen (s/conformer fn-or-react-component?)) (s/def :react-navigation.RouteConfigs.route/path string?) (s/def :react-navigation.RouteConfigs/route (s/keys :req-un [:react-navigation.RouteConfigs.route/screen] :opt-un [:react-navigation.RouteConfigs.route/path :react-navigation/navigationOptions])) (s/def :react-navigation/RouteConfigs (s/map-of keyword? :react-navigation.RouteConfigs/route)) StackNavigator StackNavigatorConfig (s/def :react-navigation.StackNavigator.StackNavigatorConfig/initialRouteName string?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/initialRouteParams map?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/paths map?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/mode #{"modal" "card"}) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/headerMode #{"float" "screen" "none"}) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/cardStyle map?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionStart fn?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionEnd fn?) (s/def :react-navigation.StackNavigator/StackNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.StackNavigator.StackNavigatorConfig/initialRouteName :react-navigation.StackNavigator.StackNavigatorConfig/initialRouteParams :react-navigation/navigationOptions :react-navigation.StackNavigator.StackNavigatorConfig/paths :react-navigation.StackNavigator.StackNavigatorConfig/mode :react-navigation.StackNavigator.StackNavigatorConfig/headerMode :react-navigation.StackNavigator.StackNavigatorConfig/cardStyle :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionStart :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionEnd]))) TabNavigator TabNavigatorConfig (s/def :react-navigation.TabNavigator.TabNavigatorConfig/tabBarComponent (s/conformer fn-or-react-component?)) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/tabBarPosition #{"top" "bottom"}) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/swipeEnabled boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/animationEnabled boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/lazyLoad boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/initialRouteName string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/order (s/coll-of string?)) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/paths map?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/backBehavior #{"initialroute" "none"}) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeTintColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeBackgroundColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveTintColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveBackgroundColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/showLabel boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/style map?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/labelStyle map?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/tabBarOptions (s/nilable (s/keys :opt-un [:react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeTintColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeBackgroundColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveTintColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveBackgroundColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/showLabel :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/style :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/labelStyle]))) (s/def :react-navigation.TabNavigator/TabNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.TabNavigator.TabNavigatorConfig/tabBarComponent :react-navigation.TabNavigator.TabNavigatorConfig/tabBarPosition :react-navigation.TabNavigator.TabNavigatorConfig/swipeEnabled :react-navigation.TabNavigator.TabNavigatorConfig/animationEnabled :react-navigation.TabNavigator.TabNavigatorConfig/lazyLoad :react-navigation.TabNavigator.TabNavigatorConfig/initialRouteName :react-navigation.TabNavigator.TabNavigatorConfig/order :react-navigation.TabNavigator.TabNavigatorConfig/paths :react-navigation.TabNavigator.TabNavigatorConfig/backBehavior :react-navigation.TabNavigator.TabNavigatorConfig/tabBarOptions]))) ;; DrawerNavigator DrawerNavigatorConfig (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerWidth number?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerPosition #{"left" "right"}) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentComponent (s/conformer fn-or-react-component?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/useNativeAnimations boolean?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerBackgroundColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/initialRouteName string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/order (s/coll-of string?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/paths map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/backBehavior #{"initialroute" "none"}) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeTintColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeBackgroundColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveTintColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveBackgroundColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/onItemPress (s/conformer fn-or-react-component?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemsContainerStyle map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/iconContainerStyle map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/labelStyle map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemStyle (s/conformer string-or-react-element?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentOptions (s/nilable (s/keys :opt-un [:react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeTintColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeBackgroundColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveTintColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveBackgroundColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/onItemPress :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemsContainerStyle :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/iconContainerStyle :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/labelStyle :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemStyle]))) (s/def :react-navigation.DrawerNavigator/DrawerNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerWidth :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerPosition :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentComponent :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentOptions :react-navigation.DrawerNavigator.DrawerNavigatorConfig/useNativeAnimations :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerBackgroundColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig/initialRouteName :react-navigation.DrawerNavigator.DrawerNavigatorConfig/order :react-navigation.DrawerNavigator.DrawerNavigatorConfig/paths :react-navigation.DrawerNavigator.DrawerNavigatorConfig/backBehavior]))) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/initialRouteName string?) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/resetOnBlur boolean?) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/paths map?) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/backBehavior #{"initialroute" "none"}) (s/def :react-navigation.SwitchNavigator/SwitchNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.SwitchNavigator.SwitchNavigatorConfig/initialRouteName :react-navigation.SwitchNavigator.SwitchNavigatorConfig/resetOnBlur :react-navigation.SwitchNavigator.SwitchNavigatorConfig/paths :react-navigation.SwitchNavigator.SwitchNavigatorConfig/backBehavior]))) (defn append-navigationOptions "If navigationOptions are specified append to the react-component" [react-component navigationOptions] (when (and navigationOptions (not= navigationOptions :cljs.spec.alpha/invalid)) (aset react-component "navigationOptions" (clj->js navigationOptions))) react-component) (s/fdef append-navigationOptions :args (s/tuple :react/component :react-navigation/navigationOptions) :ret #(ric/react-class? %)) (defn stack-screen [react-component navigationOptions] (let [react-component-conformed (s/conform :react/component react-component) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= react-component-conformed :cljs.spec.alpha/invalid) "Invalid react component.") (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid) "Invalid navigationOptions.") (append-navigationOptions react-component-conformed navigationOptions-conformed))) (defn tab-screen [react-component navigationOptions] (let [react-component-conformed (s/conform :react/component react-component) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= react-component-conformed :cljs.spec.alpha/invalid) "Invalid react component.") (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid) "Invalid navigationOptions.") (append-navigationOptions react-component-conformed navigationOptions-conformed))) (defn drawer-component [react-component navigationOptions] (let [react-component-conformed (s/conform :react/component react-component) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= react-component-conformed :cljs.spec.alpha/invalid) "Invalid react component.") (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid) "Invalid navigationOptions.") (append-navigationOptions react-component-conformed navigationOptions-conformed))) ;; Navigators ;; (defn stack-navigator [routeConfigs stackNavigatorConfig] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) StackNavigatorConfig-conformed (s/conform :react-navigation.StackNavigator/StackNavigatorConfig stackNavigatorConfig)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= StackNavigatorConfig-conformed :cljs.spec.alpha/invalid)) (if StackNavigatorConfig-conformed (StackNavigator (clj->js routeConfigs-conformed) (clj->js StackNavigatorConfig-conformed)) (StackNavigator (clj->js routeConfigs-conformed))))) (defn tab-navigator [routeConfigs navigationOptions] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid)) (TabNavigator (clj->js routeConfigs-conformed) (clj->js navigationOptions-conformed)))) (defn drawer-navigator [routeConfigs drawerNavigatorConfig] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) drawerNavigatorConfig-conformed (s/conform :react-navigation.DrawerNavigator/DrawerNavigatorConfig drawerNavigatorConfig)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= drawerNavigatorConfig-conformed :cljs.spec.alpha/invalid)) (if drawerNavigatorConfig-conformed (DrawerNavigator (clj->js routeConfigs-conformed) (clj->js drawerNavigatorConfig-conformed)) (DrawerNavigator (clj->js routeConfigs-conformed))))) (defn switch-navigator [routeConfigs switchNavigatorConfig] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) switchNavigatorConfig-conformed (s/conform :react-navigation.SwitchNavigator/SwitchNavigatorConfig switchNavigatorConfig)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= switchNavigatorConfig-conformed :cljs.spec.alpha/invalid)) (if switchNavigatorConfig-conformed (SwitchNavigator (clj->js routeConfigs-conformed) (clj->js switchNavigatorConfig-conformed)) (SwitchNavigator (clj->js routeConfigs-conformed)))))
null
https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/src/cljs_react_navigation/base.cljs
clojure
Navigators Views React RouteConfigs DrawerNavigator DrawerNavigatorConfig Navigators
(ns cljs-react-navigation.base (:require [cljs.spec.alpha :as s :include-macros true] [goog.object :as gobj] [reagent.core :as r] [reagent.impl.component :as ric])) (defonce React (js/require "react")) (defonce ReactNavigation (js/require "react-navigation")) (defonce isValidElement (gobj/get React #js ["isValidElement"])) Core (defonce createNavigationContainer (gobj/get ReactNavigation #js ["createNavigationContainer"])) (defonce StateUtils (gobj/get ReactNavigation #js ["StateUtils"])) (defonce addNavigationHelpers (gobj/get ReactNavigation #js ["addNavigationHelpers"])) (defonce NavigationActions (gobj/get ReactNavigation #js ["NavigationActions"])) (defonce NavigationActionsMap {"Navigation/INIT" (gobj/get NavigationActions #js ["init"]) "Navigation/URI" (gobj/get NavigationActions #js ["uri"]) "Navigation/NAVIGATE" (gobj/get NavigationActions #js ["navigate"]) "Navigation/BACK" (gobj/get NavigationActions #js ["back"]) "Navigation/RESET" (gobj/get NavigationActions #js ["reset"]) "Navigation/SET_PARAMS" (gobj/get NavigationActions #js ["setParams"])}) (defonce createNavigator (gobj/get ReactNavigation #js ["createNavigator"])) (defonce StackNavigator (gobj/get ReactNavigation #js ["StackNavigator"])) (defonce TabNavigator (gobj/get ReactNavigation #js ["TabNavigator"])) (defonce DrawerNavigator (gobj/get ReactNavigation #js ["DrawerNavigator"])) (defonce SwitchNavigator (gobj/get ReactNavigation #js ["SwitchNavigator"])) Routers (defonce StackRouter (gobj/get ReactNavigation #js ["StackRouter"])) (defonce TabRouter (gobj/get ReactNavigation #js ["TabRouter"])) (defonce Transitioner (gobj/get ReactNavigation #js ["Transitioner"])) (defonce CardStack (gobj/get ReactNavigation #js ["CardStack"])) (defonce DrawerView (gobj/get ReactNavigation #js ["DrawerView"])) (defonce TabView (gobj/get ReactNavigation #js ["TabView"])) (assert (and React ReactNavigation) "React and React Navigation must be installed. Maybe NPM install them and restart the packager?") Spec conforming functions (defn react-component? "Spec conforming function. Accepts a react class or returns :cljs.spec.alpha/invalid." [c] (cond (ric/react-class? c) c :else :cljs.spec.alpha/invalid)) (defn react-element? "Spec conforming function. Accepts either a react element, conforms a react class to an element, or returns :cljs.spec.alpha/invalid." [e] (cond (isValidElement e) e (ric/react-class? e) (r/create-element e) :else :cljs.spec.alpha/invalid)) (defn string-or-react-component? "Accepts either a string, react component, or a fn that returns a react component. If it's a fn, props will automatically convert (js->clj) when the fn is called." [s-or-c] (cond (ric/react-class? s-or-c) s-or-c (string? s-or-c) s-or-c (fn? s-or-c) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (s-or-c clj-props children)] react-c)) :else :cljs.spec.alpha/invalid)) (defn string-or-react-element? [s-or-e] (cond (isValidElement s-or-e) s-or-e (ric/react-class? s-or-e) (r/create-element s-or-e) (fn? s-or-e) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (s-or-e clj-props children) react-e (r/create-element react-c)] react-e)) (string? s-or-e) s-or-e :else :cljs.spec.alpha/invalid)) (defn fn-or-react-component? "Confirms either a valid react component was passed in or a function that returns a react component. If it's a function, props will be converted to clojure structures with keywords. Expects the fn to return a valid component" [fn-or-c] (cond (ric/react-class? fn-or-c) fn-or-c (fn? fn-or-c) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (fn-or-c clj-props children)] react-c)) :else :cljs.spec.alpha/invalid)) (defn fn-or-react-element? "Confirms either a valid react element was passed in or a function that returns a react element. If it's a function, props will be converted to clojure structures with keywords. Expects the fn to return a valid component" [fn-or-e] (cond (isValidElement fn-or-e) fn-or-e (ric/react-class? fn-or-e) (r/create-element fn-or-e) (fn? fn-or-e) (fn [props & children] (let [clj-props (js->clj props :keywordize-keys true) react-c (fn-or-e clj-props children) react-e (r/create-element react-c)] react-e)) :else :cljs.spec.alpha/invalid)) (defn navigation-options? "Conforms a clj map (or a function that returns a clj map) to a js object" [map-or-fn] (cond (map? map-or-fn) (s/conform :react-navigation.navigationOptions/all map-or-fn) (fn? map-or-fn) (fn [props] (let [clj-props (js->clj props :keywordize-keys true) fn-output (map-or-fn clj-props) conformed (s/conform :react-navigation.navigationOptions/all fn-output) conformed-js (clj->js conformed)] conformed-js)) :else :cljs.spec.alpha/invalid)) (s/def :react/component (s/conformer react-component?)) (s/def :react/element (s/conformer react-element?)) navigationOptions ( merged both Screen and Tabs for my sanity ) (s/def :react-navigation.navigationOptions/title string?) (s/def :react-navigation.navigationOptions/headerVisible boolean?) (s/def :react-navigation.navigationOptions/headerTitle (s/conformer string-or-react-element?)) (s/def :react-navigation.navigationOptions/headerBackTitle string?) (s/def :react-navigation.navigationOptions/headerRight (s/conformer string-or-react-element?)) (s/def :react-navigation.navigationOptions/headerLeft (s/conformer string-or-react-element?)) (s/def :react-navigation.navigationOptions/headerStyle map?) (s/def :react-navigation.navigationOptions/headerTitleStyle map?) (s/def :react-navigation.navigationOptions/headerTintColor string?) (s/def :react-navigation.navigationOptions/headerPressColorAndroid string?) (s/def :react-navigation.navigationOptions/gesturesEnabled boolean?) (s/def :react-navigation.navigationOptions/tabBarVisible boolean?) (s/def :react-navigation.navigationOptions/tabBarIcon (s/conformer fn-or-react-element?)) (s/def :react-navigation.navigationOptions/tabBarLabel string?) (s/def :react-navigation.navigationOptions/all (s/keys :opt-un [:react-navigation.navigationOptions/title :react-navigation.navigationOptions/headerVisible :react-navigation.navigationOptions/headerTitle :react-navigation.navigationOptions/headerBackTitle :react-navigation.navigationOptions/headerRight :react-navigation.navigationOptions/headerLeft :react-navigation.navigationOptions/headerStyle :react-navigation.navigationOptions/headerTitleStyle :react-navigation.navigationOptions/headerTintColor :react-navigation.navigationOptions/headerPressColorAndroid :react-navigation.navigationOptions/gesturesEnabled :react-navigation.navigationOptions/tabBarVisible :react-navigation.navigationOptions/tabBarIcon :react-navigation.navigationOptions/tabBarLabel])) (s/def :react-navigation/navigationOptions (s/nilable (s/conformer navigation-options?))) (s/def :react-navigation.RouteConfigs.route/screen (s/conformer fn-or-react-component?)) (s/def :react-navigation.RouteConfigs.route/path string?) (s/def :react-navigation.RouteConfigs/route (s/keys :req-un [:react-navigation.RouteConfigs.route/screen] :opt-un [:react-navigation.RouteConfigs.route/path :react-navigation/navigationOptions])) (s/def :react-navigation/RouteConfigs (s/map-of keyword? :react-navigation.RouteConfigs/route)) StackNavigator StackNavigatorConfig (s/def :react-navigation.StackNavigator.StackNavigatorConfig/initialRouteName string?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/initialRouteParams map?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/paths map?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/mode #{"modal" "card"}) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/headerMode #{"float" "screen" "none"}) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/cardStyle map?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionStart fn?) (s/def :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionEnd fn?) (s/def :react-navigation.StackNavigator/StackNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.StackNavigator.StackNavigatorConfig/initialRouteName :react-navigation.StackNavigator.StackNavigatorConfig/initialRouteParams :react-navigation/navigationOptions :react-navigation.StackNavigator.StackNavigatorConfig/paths :react-navigation.StackNavigator.StackNavigatorConfig/mode :react-navigation.StackNavigator.StackNavigatorConfig/headerMode :react-navigation.StackNavigator.StackNavigatorConfig/cardStyle :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionStart :react-navigation.StackNavigator.StackNavigatorConfig/onTransitionEnd]))) TabNavigator TabNavigatorConfig (s/def :react-navigation.TabNavigator.TabNavigatorConfig/tabBarComponent (s/conformer fn-or-react-component?)) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/tabBarPosition #{"top" "bottom"}) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/swipeEnabled boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/animationEnabled boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/lazyLoad boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/initialRouteName string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/order (s/coll-of string?)) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/paths map?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/backBehavior #{"initialroute" "none"}) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeTintColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeBackgroundColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveTintColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveBackgroundColor string?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/showLabel boolean?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/style map?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/labelStyle map?) (s/def :react-navigation.TabNavigator.TabNavigatorConfig/tabBarOptions (s/nilable (s/keys :opt-un [:react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeTintColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/activeBackgroundColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveTintColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/inactiveBackgroundColor :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/showLabel :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/style :react-navigation.TabNavigator.TabNavigatorConfig.tabBarOptions/labelStyle]))) (s/def :react-navigation.TabNavigator/TabNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.TabNavigator.TabNavigatorConfig/tabBarComponent :react-navigation.TabNavigator.TabNavigatorConfig/tabBarPosition :react-navigation.TabNavigator.TabNavigatorConfig/swipeEnabled :react-navigation.TabNavigator.TabNavigatorConfig/animationEnabled :react-navigation.TabNavigator.TabNavigatorConfig/lazyLoad :react-navigation.TabNavigator.TabNavigatorConfig/initialRouteName :react-navigation.TabNavigator.TabNavigatorConfig/order :react-navigation.TabNavigator.TabNavigatorConfig/paths :react-navigation.TabNavigator.TabNavigatorConfig/backBehavior :react-navigation.TabNavigator.TabNavigatorConfig/tabBarOptions]))) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerWidth number?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerPosition #{"left" "right"}) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentComponent (s/conformer fn-or-react-component?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/useNativeAnimations boolean?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerBackgroundColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/initialRouteName string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/order (s/coll-of string?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/paths map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/backBehavior #{"initialroute" "none"}) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeTintColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeBackgroundColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveTintColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveBackgroundColor string?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/onItemPress (s/conformer fn-or-react-component?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemsContainerStyle map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/iconContainerStyle map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/labelStyle map?) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemStyle (s/conformer string-or-react-element?)) (s/def :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentOptions (s/nilable (s/keys :opt-un [:react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeTintColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/activeBackgroundColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveTintColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/inactiveBackgroundColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/onItemPress :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemsContainerStyle :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/iconContainerStyle :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/labelStyle :react-navigation.DrawerNavigator.DrawerNavigatorConfig.contentOptions/itemStyle]))) (s/def :react-navigation.DrawerNavigator/DrawerNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerWidth :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerPosition :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentComponent :react-navigation.DrawerNavigator.DrawerNavigatorConfig/contentOptions :react-navigation.DrawerNavigator.DrawerNavigatorConfig/useNativeAnimations :react-navigation.DrawerNavigator.DrawerNavigatorConfig/drawerBackgroundColor :react-navigation.DrawerNavigator.DrawerNavigatorConfig/initialRouteName :react-navigation.DrawerNavigator.DrawerNavigatorConfig/order :react-navigation.DrawerNavigator.DrawerNavigatorConfig/paths :react-navigation.DrawerNavigator.DrawerNavigatorConfig/backBehavior]))) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/initialRouteName string?) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/resetOnBlur boolean?) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/paths map?) (s/def :react-navigation.SwitchNavigator.SwitchNavigatorConfig/backBehavior #{"initialroute" "none"}) (s/def :react-navigation.SwitchNavigator/SwitchNavigatorConfig (s/nilable (s/keys :opt-un [:react-navigation.SwitchNavigator.SwitchNavigatorConfig/initialRouteName :react-navigation.SwitchNavigator.SwitchNavigatorConfig/resetOnBlur :react-navigation.SwitchNavigator.SwitchNavigatorConfig/paths :react-navigation.SwitchNavigator.SwitchNavigatorConfig/backBehavior]))) (defn append-navigationOptions "If navigationOptions are specified append to the react-component" [react-component navigationOptions] (when (and navigationOptions (not= navigationOptions :cljs.spec.alpha/invalid)) (aset react-component "navigationOptions" (clj->js navigationOptions))) react-component) (s/fdef append-navigationOptions :args (s/tuple :react/component :react-navigation/navigationOptions) :ret #(ric/react-class? %)) (defn stack-screen [react-component navigationOptions] (let [react-component-conformed (s/conform :react/component react-component) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= react-component-conformed :cljs.spec.alpha/invalid) "Invalid react component.") (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid) "Invalid navigationOptions.") (append-navigationOptions react-component-conformed navigationOptions-conformed))) (defn tab-screen [react-component navigationOptions] (let [react-component-conformed (s/conform :react/component react-component) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= react-component-conformed :cljs.spec.alpha/invalid) "Invalid react component.") (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid) "Invalid navigationOptions.") (append-navigationOptions react-component-conformed navigationOptions-conformed))) (defn drawer-component [react-component navigationOptions] (let [react-component-conformed (s/conform :react/component react-component) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= react-component-conformed :cljs.spec.alpha/invalid) "Invalid react component.") (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid) "Invalid navigationOptions.") (append-navigationOptions react-component-conformed navigationOptions-conformed))) (defn stack-navigator [routeConfigs stackNavigatorConfig] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) StackNavigatorConfig-conformed (s/conform :react-navigation.StackNavigator/StackNavigatorConfig stackNavigatorConfig)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= StackNavigatorConfig-conformed :cljs.spec.alpha/invalid)) (if StackNavigatorConfig-conformed (StackNavigator (clj->js routeConfigs-conformed) (clj->js StackNavigatorConfig-conformed)) (StackNavigator (clj->js routeConfigs-conformed))))) (defn tab-navigator [routeConfigs navigationOptions] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) navigationOptions-conformed (s/conform :react-navigation/navigationOptions navigationOptions)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= navigationOptions-conformed :cljs.spec.alpha/invalid)) (TabNavigator (clj->js routeConfigs-conformed) (clj->js navigationOptions-conformed)))) (defn drawer-navigator [routeConfigs drawerNavigatorConfig] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) drawerNavigatorConfig-conformed (s/conform :react-navigation.DrawerNavigator/DrawerNavigatorConfig drawerNavigatorConfig)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= drawerNavigatorConfig-conformed :cljs.spec.alpha/invalid)) (if drawerNavigatorConfig-conformed (DrawerNavigator (clj->js routeConfigs-conformed) (clj->js drawerNavigatorConfig-conformed)) (DrawerNavigator (clj->js routeConfigs-conformed))))) (defn switch-navigator [routeConfigs switchNavigatorConfig] (let [routeConfigs-conformed (s/conform :react-navigation/RouteConfigs routeConfigs) switchNavigatorConfig-conformed (s/conform :react-navigation.SwitchNavigator/SwitchNavigatorConfig switchNavigatorConfig)] (assert (not= routeConfigs-conformed :cljs.spec.alpha/invalid)) (assert (not= switchNavigatorConfig-conformed :cljs.spec.alpha/invalid)) (if switchNavigatorConfig-conformed (SwitchNavigator (clj->js routeConfigs-conformed) (clj->js switchNavigatorConfig-conformed)) (SwitchNavigator (clj->js routeConfigs-conformed)))))
141a38074217ac5622463f1e26adfb0d0d9876d5e071e98c40e4e04a78285f13
jimpil/annotator-clj
core.clj
(ns PAnnotator.core #^{:author "Dimitrios Piliouras 2012 ()" :doc "PAnnotator's core namespace. Strings in this namespace know how to stem themselves (Porter's stemmer), allign themselves (Smith-Waterman) with other strings and also compare compute the edit-distance (Levenshtein) between themselves and other strings."} (:use [clojure.tools.cli :only [cli]] [clojure.set :only [union]] [clojure.pprint :only [pprint]] [clojure.string :only [split-lines split blank?]] #_[re-rand :only [re-rand]]) (:require [clojure.core.reducers :as r] [clojure.java.io :as io] [PAnnotator.allignment :as alli] [PAnnotator.util :as ut] #_[PAnnotator.scrapper :as scra]) (:import [java.io File FileFilter] [java.util.regex Pattern PatternSyntaxException] [org.apache.pdfbox.pdmodel PDDocument] [org.apache.pdfbox.util PDFTextStripper] [java.util.concurrent Executors ExecutorCompletionService] [org.tartarus.snowball.ext EnglishStemmer DanishStemmer DutchStemmer FinnishStemmer FrenchStemmer German2Stemmer GermanStemmer HungarianStemmer ItalianStemmer KpStemmer LovinsStemmer NorwegianStemmer PorterStemmer PortugueseStemmer RomanianStemmer RussianStemmer SpanishStemmer SwedishStemmer TurkishStemmer] [org.tartarus.snowball SnowballProgram]) (:gen-class :name Annotator :main true :methods [^:static [process [java.util.Map] void] ^:static [process [String String java.util.List] String]]) ) (def ^:dynamic *cpu-no* (.. Runtime getRuntime availableProcessors)) (def fj-chunk-size (atom 5)) (def global-dic (atom nil)) (def sentence-segmentation-regex #"(?<=[.!?]|[.!?][\\'\"])(?<!e\.g\.|i\.e\.|vs\.|p\.m\.|a\.m\.|Mr\.|Mrs\.|Ms\.|St\.|Fig\.|fig\.|Jr\.|Dr\.|Prof\.|Sr\.|\s[A-Z]\.)\s+") (def token-regex #"[\w\d/]+|[\-\,\.\?\!\(\)]") match 0 or more vowels + 1 or more consonants at the start of the word match 1 or more vowels + 1 or more consonants inside a word match 1 or more vowels + 0 or more consonants at the end of a word (defn- un-capitalize ^String [^String s] (if (every? #(Character/isUpperCase ^Character %) s) s (let [Cfirst (subs s 0 1) Crest (subs s 1) ] (str (.toLowerCase Cfirst) Crest)))) (def normaliser (comp (fn [untrimmed] (mapv #(un-capitalize (.trim ^String %)) untrimmed)) split-lines slurp)) (defn singleton? [s] (< (count (split s #"(\s|\-|\(|\))")) 2)) (def drugbank-singletons (doall (filter singleton? (normaliser (io/resource "DRUGBANK/DRUGBANK-TERMS.txt"))))) (defprotocol Stemmable (getRoot [this] [this lang])) (defprotocol Levenshtein (getDistance [this other])) (defprotocol Allignable (allignSW [this other])) (defn- porter-stemmer ^SnowballProgram [^String lang] (case lang "danish" (DanishStemmer.) "dutch" (DutchStemmer.) "english" (EnglishStemmer.) "finnish" (FinnishStemmer.) "french" (FrenchStemmer.) "german2" (German2Stemmer.) "german" (GermanStemmer.) "hungarian" (HungarianStemmer.) "italian" (ItalianStemmer.) "kp" (KpStemmer.) "lovins" (LovinsStemmer.) "norwegian" (NorwegianStemmer.) "porter" (PorterStemmer.) "postugese" (PortugueseStemmer.) "romanian" (RomanianStemmer.) "russian" (RussianStemmer.) "spanish" (SpanishStemmer.) "swedish" (SwedishStemmer.) "turskish" (TurkishStemmer.) (throw (IllegalArgumentException. "Language NOT supported...Stemming cannot continue!")))) (declare levenshtein-distance*) (extend-type String Stemmable (getRoot ([this] (getRoot this "english")) ([this lang] (let [stemmer (porter-stemmer lang)] (doto stemmer (.setCurrent this) (.stem)) (.getCurrent stemmer)))) Levenshtein (getDistance [this other] (levenshtein-distance* this other)) Allignable (allignSW [this other] (alli/smith_waterman this other))) (extend-type clojure.lang.IPersistentCollection Stemmable (getRoot ([this] (getRoot this "english")) ([this lang] (let [stemmer (porter-stemmer lang)] (map #(do (doto stemmer (.setCurrent %) (.stem)) (.getCurrent stemmer)) this))))) (extend-type nil Stemmable (getRoot ([_] nil) ([_ _] nil))) (defn name-parts [names] ;;get some basic syllable statistics (let [lead (transient []) inner (transient []) trail (transient [])] (doseq [n names] (when-let [pat1 (re-find _LEAD n)] (conj! lead pat1)) (when-let [pats (re-seq _INNER n)] (doseq [p pats] (conj! inner p))) (when-let [pat2 (re-find _TRAIL n)] (conj! trail pat2))) [(frequencies (persistent! lead)) (frequencies (persistent! inner)) a vector of 3 maps ( keep the ones with at least five occurences ) (mapv first (take-while #(> (second %) 5) (sort-by second > freqs)))) (defn- namegen [nparts & {:keys [alt-lead alt-trail]}] (let [[leads inners trails] (mapv freq-desc nparts) random-int (rand-int 3) syllables (if (> (rand) 0.85) (+ 2 random-int) (inc random-int))] (loop [name (or alt-lead (rand-nth leads)) ss syllables] (if (zero? ss) (str name (or alt-trail (rand-nth trails))) (recur (str name (rand-nth inners)) (dec ss)))))) (def drugen (partial namegen (name-parts drugbank-singletons))) ;; (drugen :alt-trail "ine") (drugen :alt-lead "card") (declare fold-into-vec) (defn randrugs ([] (repeatedly drugen)) ([t] (repeatedly t drugen)) ([t pred] do n't bother folding for less than 11 elements (fold-into-vec 15 (r/remove pred (vec (randrugs t)))))) ([t pred & more] (let [ress (repeatedly t #(apply drugen more))] (if (< t 11) (remove pred ress) (fold-into-vec 15 (r/remove pred (vec ress))))))) EXAMPLE USAGE of pred ( fn close ? [ x ] ( some # ( < ( ) 4 ) ) ) (defn pdf->txt [^String src & {:keys [s-page e-page dest] :or {s-page 1 dest (str (first (split src #"\.")) ".txt")}}] {:pre [(< 0 s-page) (.endsWith src ".pdf")]} (println " \u001B[31mYOU ARE PERFORMING A POTENTIALLY ILLEGAL OPERATION...\n\t PROCEED AT YOUR OWN RISK!!!\u001B[m \n Proceed? (y/n):") (when (-> *in* (java.util.Scanner.) .next (.charAt 0) (= \y)) (with-open [pd (PDDocument/load (File. src)) wr (io/writer dest)] (let [page-no (.getNumberOfPages pd) stripper (doto (PDFTextStripper.) (.setStartPage s-page) (.setEndPage (or e-page page-no)))] (println " #Total pages =" page-no "\n" "#Selected pages =" (- (or e-page page-no) (dec s-page))) (.writeText stripper pd wr) (println "Raw content extracted and written to" dest "..."))))) (def openNLP-NER-tags {:opening "<START:" :closing " <END>" :middle "> " :order [:entity :token]}) for TOKEN in ` cat some-file.txt ` ; do echo $ TOKEN ; done for TOKEN in ` cat ; do echo -e $ TOKEN ' \tO ' > > some-file.txt.tok ; done (def stanfordNLP-NER-tags {:opening "" :middle "" :closing "\t" :order [:token :entity] }) (def custom-NER-tags (atom {})) (def plain-NER-tags {:opening "__" :middle ": " :closing "__" :order [:token :entity] }) (definline dist-step [pred d index] `(let [[i# j#] ~index] (assoc ~d ~index (cond (zero? (min i# j#)) (max i# j#) (~pred i# j#) (get ~d [(dec i#) (dec j#)]) :else (min (inc (get ~d [(dec i#) j#])) ;+1 cost for deletion (inc (get ~d [i# (dec j#)])) ;+1 cost for insertion +2 cost for substitution ( per Juramfky 's lecture - slides ) (defn- levenshtein-distance* "Calculates the amount of difference between two strings." [s1 s2] (let [m (inc (count s1)) ; do not skip tha last character n (inc (count s2)) ; do not skip tha last character pred (fn [i j] (= (get s1 (dec i)) (get s2 (dec j)))) step #(dist-step pred %1 %2) distance-matrix (reduce step {} (ut/matrix m n))] (get distance-matrix [(dec m) (dec n)]))) (def edit-distance levenshtein-distance*) ;;very quick already but maybe some memoization? (defn s-split "Segments the given string into distinct sentences delimited by a newline." [^String s] (ut/segment (split s sentence-segmentation-regex))) (defn split-sentences [file] (s-split (slurp file))) (defn simple-tokenize "An extremely simple tokenizer that splits on any non-alphanumeric character. Inline punctuation is mostly preserved. Returns a lazy-seq of whole-word tokens. Optionally, you can apply stemming to all the returned tokens. Strings know how to stem themselves. Simply use the 'getRoot' fn. usage: (simple-tokenize \"the fox jumped over the lazy dog\" :stemmer getRoot) OR (simple-tokenize \"Wir besuchen meine Tante in Berlin.\" :stemmer #(getRoot % \"german\")) in case you want to specify a language other than English." [sentence & {:keys [rgx stemmer] :or {rgx token-regex}}] (let [tokens (re-seq rgx sentence)] (if stemmer (stemmer tokens) tokens))) (defn n-grams-count "Used to create n-grams with the specified numbers A seq of numbers for the ngrams to create. The documents to process with the ngrams *returns* A map of the ngrams" [numbers documents] (reduce (fn [counts number] (reduce (fn [counts document] (reduce (fn [counts freqs] (let [ngram (first freqs)] (if-let [val (counts ngram)] (assoc counts ngram (+ val (second freqs))) (assoc counts ngram (second freqs))))) counts (frequencies (ut/ngrams document number)))) counts documents)) {} (if (sequential? numbers) numbers (list numbers)))) (defn add-ngrams-to-document "Used to add ngrams to the document. *numbers* The number of ngrams to create. <br /> *document* The document to process. <br /> *processed-document* The processed-document to add the ngrams too. <br /> *ngrams-count* The ngrams map. <br /> *return* The processed document with the added ngrams" [numbers document processed-document ngrams-count] (reduce (fn [processed-document ngram] (if (contains? ngrams-count (first ngram)) (assoc processed-document :counts (assoc (:counts processed-document) (first ngram) (second ngram)) :number-of-words (+ (:number-of-words processed-document) (second ngram))) processed-document)) processed-document (n-grams-count numbers (list document)))) (defmulti format-tag keyword) (defmethod format-tag :plain-NER [_] #(str (:opening plain-NER-tags) % (:middle plain-NER-tags) %2 (:closing plain-NER-tags))) (defmethod format-tag :openNLP-NER [_] #(str (:opening openNLP-NER-tags) % (:middle openNLP-NER-tags) %2 (:closing openNLP-NER-tags))) (defmethod format-tag :stanfordNLP-NER [_] #(str %2 \tab %)) (defmethod format-tag :custom-NER [o] (if (= (first (:order @custom-NER-tags)) :token) #(str (:opening @custom-NER-tags) %2 (:middle @custom-NER-tags) % (:closing @custom-NER-tags)) #(str (:opening @custom-NER-tags) % (:middle @custom-NER-tags) %2 (:closing @custom-NER-tags)))) (defn pool-map "A saner, more disciplined version of pmap. Submits jobs eagerly but polls for results lazily. Don't use if original ordering of 'coll' matters." ([f coll threads] (let [exec (Executors/newFixedThreadPool threads) pool (ExecutorCompletionService. exec) futures (try (mapv (fn [x] (.submit pool #(f x))) coll) (finally (.shutdown exec)))] (repeatedly (count futures) #(.. pool take get)))) ([f coll] (pool-map f coll (+ 2 cpu-no)))) (defn fold-into-vec [chunk coll] "Provided a reducer, concatenate into a vector. Same as (into [] coll), but parallel." (r/fold chunk (r/monoid into vector) conj coll)) (defn rmap "A high-performance, fork-join based mapping function that uses ArrayList underneath." ([f coll fj-chunk-size shuffle?] (r/fold fj-chunk-size r/cat r/append! (r/map f (cond-> coll shuffle? shuffle (not shuffle?) vec)))) ([f coll fj-chunk-size] (rhmap f coll fj-chunk-size false)) ([f coll] (rhmap f coll 1)) ) (defn mapr "A pretty basic map-reduce style mapping function. Will partition the data according to p-size and assign a future to each partition (per pmap)." ([f coll p-size shuffle?] (->> (cond-> coll shuffle? shuffle) (partition-all p-size) (pmap #(mapv f %) ) (apply concat)) ) ;;concat the inner vectors that represent the partitions ([f coll p-size] (mapr f coll p-size false)) ([f coll] (mapr f coll (+ 2 cpu-no)))) (defn- file->data "Read the file f back on memory safely. Contents of f should be a clojure data-structure. Not allowed to execute arbitrary code (per #=)." [f] (binding [*read-eval* false] (read-string (slurp f)))) (defn- combine-dicts "Takes a seq of dictionaries (seqs) and produces a united set of all entries (no duplicates)." [ds] (if (< 1 (count ds)) (let [set-views (map set ds)] (apply union set-views)) (first ds))) (defn- space-out "Given some text, find all the openNLP sgml tags that are not surrounded by spaces and put spaces around them." ^String [^String text t-scheme] (when-not (or (blank? (:opening t-scheme)) (blank? (:closing t-scheme))) " ( ? < ! ) < STA " ) (-> (re-matcher (re-pattern (str (apply str (next (:closing t-scheme))) "(?! )")) text) ;"END>(?! )" (.replaceAll "$0 "))) (.replaceAll " $0")))) (defn- create-folder! "Creates a folder at the specified path." [^String path] (.mkdir (File. path))) (defn- mapping-fn "Returns a fn that will take care mapping with this stratefy. Supported options include :serial, :lazy, :lazy-parallel, :pool-parallel, :map-reduce & :fork-join." [strategy] (case strategy :serial mapv :lazy map :lazy-parallel pmap :pool-parallel pool-map :map-reduce mapr :fork-join rmap)) (defn- file-write-mode "Returns a fn that will take care writing files in this mode. Supported options include :merge-all, :per-file & :on-screen." [mode target-f] (case mode :merge-all (fn [target content] (do (spit target content :append true) (spit target "\n\n" :append true))) :per-file (fn [target content] (let [fname (str target-f "/" target ".pann")] (spit fname content))) :on-screen (fn [_ content] (print content "\n\n")) )) (defn file-filter [filter] (reify FileFilter (accept [this f] (boolean (re-find (re-pattern (str ".*" filter)) (.getName ^File f)))))) (defn- sort-input [data-s ffilter] (let [data-seq (-> data-s slurp read-string) fitem (first data-seq)] (if (sequential? fitem) data-s ;;the usual happens (let [directory (io/file fitem) ;;the whole directory f-seq (if-let [ff ffilter] (.listFiles ^File directory ^FileFilter (file-filter ff)) (.listFiles ^File directory)) f-seq-names (for [f f-seq :when #(.isFile ^File f)] (.getPath ^File f))] (reset! global-dic (combine-dicts (mapv normaliser (next data-seq)))) build the new 2d vector (defn- annotate "Overloaded function. First one takes a filename f, an entity-type (e.g. \"person\") and some dictionaries and annotates the text in f with openNLP compatible sgml tags for that entity-type using the provided dictionaries. Second one takes a map with 3 keys. The :files+dics key should point to a (2d) seq that contains other seqs where the 1st item is the file we want to annotate and the rest are the available dictionaries. The :target key specifies the file to write the resulting annotated text and :entity-type describes the entities (nil falls-back to \"default\"). Unless you have a single file to process, you should start with the 2nd overload as in the example below. The output file will contain new-line delimiters per processed document. e.g. (annotate {:entity-type \"drug\" :target \"test.txt\" ;;resulting sgml: <START:drug> ... <END> :file+dics [[\"train/invitro_train-raw.txt\" \"train/invitro-train-names-distinct.txt\"] [\"train/invivo_train-raw.txt\" \"train/invivo-train-names-distinct.txt\"]]})" (^String [^String f ^String entity-type dics lib] (let [dic (if-let [gb @global-dic] gb (combine-dicts (mapv normaliser dics))) file-name (.getName (java.io.File. f)) format-fn (format-tag lib)] (println (str "Processing document: " f)) (loop [text (slurp f) names dic] (if-let [name1 (first names)] (recur (try (.replaceAll (re-matcher (re-pattern (str "(?i)\\b+" (Pattern/quote name1) "+\\b")) text) (format-fn entity-type name1)) (catch PatternSyntaxException _ (do (println (str "--- COULD NOT BE PROCESSED! --->" name1)) text))) (next names)) [file-name (s-split text)])) )) ([{:keys [files+dics entity-type target target-folder consumer-lib strategy write-mode file-filter] :or {entity-type "default" target "target-file.txt" target-folder "ANNOTATED" consumer-lib "openNLP-NER" strategy "lazy-parallel" write-mode "merge-all" file-filter "txt"}}] (let [f+ds (sort-input files+dics file-filter) annotations ((mapping-fn (keyword strategy)) ;;will return a mapping function #(let [[f a] (annotate (first %) entity-type (next %) (keyword consumer-lib))] (vector f (space-out a (var-get (ns-resolve 'PAnnotator.core (symbol (str consumer-lib "-tags"))))))) (cond (string? f+ds) (file->data f+ds) (vector? f+ds) f+ds :else (throw (IllegalArgumentException. "Weird data-format encountered! Cannot proceed..."))) ) wfn (do (when (= write-mode "per-file") (create-folder! target-folder)) (file-write-mode (keyword write-mode) target-folder)) ;will return a writing function wmd (if (= write-mode "merge-all") (constantly target) identity)] (doseq [[f a] annotations] (wfn (wmd f) a)))) ) (def -process annotate) (def HELP_MESSAGE "\nINSTRUCTIONS: java -cp PAnnotator-uberjar.jar Annotator -d <DATA-FILE>* -t <TARGET-FILE>** -e <ENTITY-TYPE>*** -par serial OR lazy OR lazy-parallel OR pool-parallel OR fork-join**** -wm merge-all OR per-file OR on-screen***** -fl \"openNLP-NER\" OR \"stanfordNLP-NER\" OR \"plain-NER\" -ct \"{:opening \"_\" :closing \"_\" :middle \":\"}\" -chu an integer value typically from 2 to 6 \n *must be a file with a 2D clojure seqable of the form: [[input1 dic1 dic2 dic3 dic4] [input2 dic5 dic6 dic7] [input3 dic8 dic9]] *defaults to 'data-file.txt' **defaults to 'target-file.txt' ***optional argument - defaults to \"default\" ****optional argument - defaults to 'lazy-parallel' *****optional argument - defaults to 'merge-all'") (defn -main [& args] ;(pos-tag "target-file.txt" true) (let [[opts argus banner] (cli args ["-h" "--help" "Show help/instructions." :flag true :default false] ["-d" "--data" "REQUIRED: The data-file (e.g. \"data.txt\")" :default "data-file.txt"] ["-e" "--entity-type" "REQUIRED: The type of entity in question (e.g. \"river\")" :default "default"] ["-t" "--target" "REQUIRED: The target-file (e.g. \"target.txt\")" :default "target-file.txt"] ["-tfo" "--target-folder" "Specify a target folder. Only useful if write-mode is set 'to per-file' (defaults to ANNOTATED/)." :default "ANNOTATED"] ["-ct" "--custom-tags" "Specify your own tags. (e.g \"{:opening \"_\" :closing \"_\" :middle \":\" :order [:token :entity]}\")"] ["-par" "--parallelism" "Set a parallelisation strategy (other options are: serial, lazy, pool-parallel & fork-join)." :default "lazy-parallel"] ["-chu" "--chunking" "Specify the number where recursive tree splitting should stop in a fork-join task (defaults to 4)." :default 4] ["-wm" "--write-mode" "Set file-write-mode (other options are: per-file & on-screen)." :default "merge-all"] ["-ff" "--file-filter" "Specify a file-filter when processing an entire folder (there is NO default - all files will be processed)."] ["-fl" "--for-lib" "Apply a predefined tagging format (other options are: stanfordNLP-NER, plain-NER & custom-NER)." :default "openNLP-NER"] ["-tok" "--tokens" "Extracts (and optionally stems) tokens from the supplied string or file. Activate stemming with the -ste flag."] ["-ste" "--stemming" "Activates porter-stemming. Only useful when paired with the -tok switch which returns the tokens." :flag true :default false] ["-lang" "--language" "Set the stemming language. Only useful when paired with the -tok and -ste switches." :default "english"] ["-allign" "--allignment" "Perform local allignement (Smith-Waterman) between 2 sequences."] ["-dist" "--edit-distance" "Calculate the edit-distance (Levenshtein) between 2 words."] ["-rpdf" "--ripdf" "Extract the contents from a pdf file and write them to a plain txt file."] ["-dname" "--drugname" "Generate a finite list (you provide how many) of randomly assembled name(s) that look like drugs (orthographically)."] )] (when (:help opts) (println HELP_MESSAGE "\n\n" banner) (System/exit 0)) (when-let [source (:ripdf opts)] (pdf->txt source) (System/exit 0)) (when-let [how-many (:drugname opts)] (let [n (Integer/parseInt how-many)] (println (apply randrugs n (drop 2 args))) (System/exit 0))) (when (:allignment opts) (if (> 3 (count args)) (do (println "Less than 2 arguments detected! Please provide 2 sequences to allign...") (System/exit 0)) (do (println (allignSW (second args) (nth args 2))) (System/exit 0)))) (when (:edit-distance opts) (if (> 3 (count args)) (do (println "Less than 2 arguments detected! Please provide 2 words to compare...") (System/exit 0)) (do (println "\nLevenshtein distance =" (getDistance (second args) (nth args 2))) (System/exit 0)))) (when-let [ss (:tokens opts)] (if (:stemming opts) (pprint (simple-tokenize (if (string? ss) ss (slurp ss)) :stemmer #(getRoot % (:language opts)))) (pprint (simple-tokenize (if (string? ss) ss (slurp ss))))) (System/exit 0)) (when-let [cs (:chunking opts)] (reset! fj-chunk-size (Integer/valueOf ^Integer cs))) (do (println "\n\t\t====> \u001B[35mPAnnotator\u001B[m \u001B[32mv0.3.4\u001B[m <====\t\t\n\t\t-----------------------------\n\n") (println "\tRun settings:" "\n\n--Entity-Type:" (:entity-type opts) "\n--Target-File:" (:target opts) "\n--Target-Folder:" (:target-folder opts) "\n--Data-File:" (:data opts) "\n--Mapping strategy:" (:parallelism opts) "\n--Fork-join tree leaf-size:" @fj-chunk-size "(potentially irrelevant for this run)" "\n--Consumer library:" (:for-lib opts) "(potentially irrelevant for this run)" "\n--Write-Mode:" (:write-mode opts) "\n--Custom-tags:" (:custom-tags opts) "\n\n") (-process {:entity-type (:entity-type opts) :target (:target opts) :target-folder (:target-folder opts) :files+dics (:data opts) :file-filter (:file-filter opts) :strategy (:parallelism opts) :write-mode (:write-mode opts) :consumer-lib (if-let [cu (:custom-tags opts)] (do (swap! custom-NER-tags merge (read-string cu)) "custom-NER") (:for-lib opts))}) (case (:write-mode opts) "merge-all" (println "--------------------------------------------------------\n" "SUCCESS! Look for a file called" (str "'" (:target opts) "'. \n")) "per-file" (println "--------------------------------------------------------\n" "SUCCESS! Look for the file(s) under folder" (str (or (:target-folder opts) "ANNOTATED") "/ at the root of your classpath. \n")) "on-screen" (println "-----------------------------------------------------\n\n => THAT WAS IT...!\n") (println "write-mode can be either 'merge-all' or 'per-file' or 'on-screen'...")) (shutdown-agents) (System/exit 0)) ))
null
https://raw.githubusercontent.com/jimpil/annotator-clj/40390d46e9da83d1a4b4296c9f84263ce3afa501/src/PAnnotator/core.clj
clojure
get some basic syllable statistics (drugen :alt-trail "ine") (drugen :alt-lead "card") do echo $ TOKEN ; done do echo -e $ TOKEN ' \tO ' > > some-file.txt.tok ; done +1 cost for deletion +1 cost for insertion do not skip tha last character do not skip tha last character very quick already but maybe some memoization? concat the inner vectors that represent the partitions "END>(?! )" the usual happens the whole directory resulting sgml: <START:drug> ... <END> will return a mapping function will return a writing function (pos-tag "target-file.txt" true)
(ns PAnnotator.core #^{:author "Dimitrios Piliouras 2012 ()" :doc "PAnnotator's core namespace. Strings in this namespace know how to stem themselves (Porter's stemmer), allign themselves (Smith-Waterman) with other strings and also compare compute the edit-distance (Levenshtein) between themselves and other strings."} (:use [clojure.tools.cli :only [cli]] [clojure.set :only [union]] [clojure.pprint :only [pprint]] [clojure.string :only [split-lines split blank?]] #_[re-rand :only [re-rand]]) (:require [clojure.core.reducers :as r] [clojure.java.io :as io] [PAnnotator.allignment :as alli] [PAnnotator.util :as ut] #_[PAnnotator.scrapper :as scra]) (:import [java.io File FileFilter] [java.util.regex Pattern PatternSyntaxException] [org.apache.pdfbox.pdmodel PDDocument] [org.apache.pdfbox.util PDFTextStripper] [java.util.concurrent Executors ExecutorCompletionService] [org.tartarus.snowball.ext EnglishStemmer DanishStemmer DutchStemmer FinnishStemmer FrenchStemmer German2Stemmer GermanStemmer HungarianStemmer ItalianStemmer KpStemmer LovinsStemmer NorwegianStemmer PorterStemmer PortugueseStemmer RomanianStemmer RussianStemmer SpanishStemmer SwedishStemmer TurkishStemmer] [org.tartarus.snowball SnowballProgram]) (:gen-class :name Annotator :main true :methods [^:static [process [java.util.Map] void] ^:static [process [String String java.util.List] String]]) ) (def ^:dynamic *cpu-no* (.. Runtime getRuntime availableProcessors)) (def fj-chunk-size (atom 5)) (def global-dic (atom nil)) (def sentence-segmentation-regex #"(?<=[.!?]|[.!?][\\'\"])(?<!e\.g\.|i\.e\.|vs\.|p\.m\.|a\.m\.|Mr\.|Mrs\.|Ms\.|St\.|Fig\.|fig\.|Jr\.|Dr\.|Prof\.|Sr\.|\s[A-Z]\.)\s+") (def token-regex #"[\w\d/]+|[\-\,\.\?\!\(\)]") match 0 or more vowels + 1 or more consonants at the start of the word match 1 or more vowels + 1 or more consonants inside a word match 1 or more vowels + 0 or more consonants at the end of a word (defn- un-capitalize ^String [^String s] (if (every? #(Character/isUpperCase ^Character %) s) s (let [Cfirst (subs s 0 1) Crest (subs s 1) ] (str (.toLowerCase Cfirst) Crest)))) (def normaliser (comp (fn [untrimmed] (mapv #(un-capitalize (.trim ^String %)) untrimmed)) split-lines slurp)) (defn singleton? [s] (< (count (split s #"(\s|\-|\(|\))")) 2)) (def drugbank-singletons (doall (filter singleton? (normaliser (io/resource "DRUGBANK/DRUGBANK-TERMS.txt"))))) (defprotocol Stemmable (getRoot [this] [this lang])) (defprotocol Levenshtein (getDistance [this other])) (defprotocol Allignable (allignSW [this other])) (defn- porter-stemmer ^SnowballProgram [^String lang] (case lang "danish" (DanishStemmer.) "dutch" (DutchStemmer.) "english" (EnglishStemmer.) "finnish" (FinnishStemmer.) "french" (FrenchStemmer.) "german2" (German2Stemmer.) "german" (GermanStemmer.) "hungarian" (HungarianStemmer.) "italian" (ItalianStemmer.) "kp" (KpStemmer.) "lovins" (LovinsStemmer.) "norwegian" (NorwegianStemmer.) "porter" (PorterStemmer.) "postugese" (PortugueseStemmer.) "romanian" (RomanianStemmer.) "russian" (RussianStemmer.) "spanish" (SpanishStemmer.) "swedish" (SwedishStemmer.) "turskish" (TurkishStemmer.) (throw (IllegalArgumentException. "Language NOT supported...Stemming cannot continue!")))) (declare levenshtein-distance*) (extend-type String Stemmable (getRoot ([this] (getRoot this "english")) ([this lang] (let [stemmer (porter-stemmer lang)] (doto stemmer (.setCurrent this) (.stem)) (.getCurrent stemmer)))) Levenshtein (getDistance [this other] (levenshtein-distance* this other)) Allignable (allignSW [this other] (alli/smith_waterman this other))) (extend-type clojure.lang.IPersistentCollection Stemmable (getRoot ([this] (getRoot this "english")) ([this lang] (let [stemmer (porter-stemmer lang)] (map #(do (doto stemmer (.setCurrent %) (.stem)) (.getCurrent stemmer)) this))))) (extend-type nil Stemmable (getRoot ([_] nil) ([_ _] nil))) (let [lead (transient []) inner (transient []) trail (transient [])] (doseq [n names] (when-let [pat1 (re-find _LEAD n)] (conj! lead pat1)) (when-let [pats (re-seq _INNER n)] (doseq [p pats] (conj! inner p))) (when-let [pat2 (re-find _TRAIL n)] (conj! trail pat2))) [(frequencies (persistent! lead)) (frequencies (persistent! inner)) a vector of 3 maps ( keep the ones with at least five occurences ) (mapv first (take-while #(> (second %) 5) (sort-by second > freqs)))) (defn- namegen [nparts & {:keys [alt-lead alt-trail]}] (let [[leads inners trails] (mapv freq-desc nparts) random-int (rand-int 3) syllables (if (> (rand) 0.85) (+ 2 random-int) (inc random-int))] (loop [name (or alt-lead (rand-nth leads)) ss syllables] (if (zero? ss) (str name (or alt-trail (rand-nth trails))) (recur (str name (rand-nth inners)) (dec ss)))))) (declare fold-into-vec) (defn randrugs ([] (repeatedly drugen)) ([t] (repeatedly t drugen)) ([t pred] do n't bother folding for less than 11 elements (fold-into-vec 15 (r/remove pred (vec (randrugs t)))))) ([t pred & more] (let [ress (repeatedly t #(apply drugen more))] (if (< t 11) (remove pred ress) (fold-into-vec 15 (r/remove pred (vec ress))))))) EXAMPLE USAGE of pred ( fn close ? [ x ] ( some # ( < ( ) 4 ) ) ) (defn pdf->txt [^String src & {:keys [s-page e-page dest] :or {s-page 1 dest (str (first (split src #"\.")) ".txt")}}] {:pre [(< 0 s-page) (.endsWith src ".pdf")]} (println " \u001B[31mYOU ARE PERFORMING A POTENTIALLY ILLEGAL OPERATION...\n\t PROCEED AT YOUR OWN RISK!!!\u001B[m \n Proceed? (y/n):") (when (-> *in* (java.util.Scanner.) .next (.charAt 0) (= \y)) (with-open [pd (PDDocument/load (File. src)) wr (io/writer dest)] (let [page-no (.getNumberOfPages pd) stripper (doto (PDFTextStripper.) (.setStartPage s-page) (.setEndPage (or e-page page-no)))] (println " #Total pages =" page-no "\n" "#Selected pages =" (- (or e-page page-no) (dec s-page))) (.writeText stripper pd wr) (println "Raw content extracted and written to" dest "..."))))) (def openNLP-NER-tags {:opening "<START:" :closing " <END>" :middle "> " :order [:entity :token]}) (def stanfordNLP-NER-tags {:opening "" :middle "" :closing "\t" :order [:token :entity] }) (def custom-NER-tags (atom {})) (def plain-NER-tags {:opening "__" :middle ": " :closing "__" :order [:token :entity] }) (definline dist-step [pred d index] `(let [[i# j#] ~index] (assoc ~d ~index (cond (zero? (min i# j#)) (max i# j#) (~pred i# j#) (get ~d [(dec i#) (dec j#)]) :else (min +2 cost for substitution ( per Juramfky 's lecture - slides ) (defn- levenshtein-distance* "Calculates the amount of difference between two strings." [s1 s2] pred (fn [i j] (= (get s1 (dec i)) (get s2 (dec j)))) step #(dist-step pred %1 %2) distance-matrix (reduce step {} (ut/matrix m n))] (get distance-matrix [(dec m) (dec n)]))) (defn s-split "Segments the given string into distinct sentences delimited by a newline." [^String s] (ut/segment (split s sentence-segmentation-regex))) (defn split-sentences [file] (s-split (slurp file))) (defn simple-tokenize "An extremely simple tokenizer that splits on any non-alphanumeric character. Inline punctuation is mostly preserved. Returns a lazy-seq of whole-word tokens. Optionally, you can apply stemming to all the returned tokens. Strings know how to stem themselves. Simply use the 'getRoot' fn. usage: (simple-tokenize \"the fox jumped over the lazy dog\" :stemmer getRoot) OR (simple-tokenize \"Wir besuchen meine Tante in Berlin.\" :stemmer #(getRoot % \"german\")) in case you want to specify a language other than English." [sentence & {:keys [rgx stemmer] :or {rgx token-regex}}] (let [tokens (re-seq rgx sentence)] (if stemmer (stemmer tokens) tokens))) (defn n-grams-count "Used to create n-grams with the specified numbers A seq of numbers for the ngrams to create. The documents to process with the ngrams *returns* A map of the ngrams" [numbers documents] (reduce (fn [counts number] (reduce (fn [counts document] (reduce (fn [counts freqs] (let [ngram (first freqs)] (if-let [val (counts ngram)] (assoc counts ngram (+ val (second freqs))) (assoc counts ngram (second freqs))))) counts (frequencies (ut/ngrams document number)))) counts documents)) {} (if (sequential? numbers) numbers (list numbers)))) (defn add-ngrams-to-document "Used to add ngrams to the document. *numbers* The number of ngrams to create. <br /> *document* The document to process. <br /> *processed-document* The processed-document to add the ngrams too. <br /> *ngrams-count* The ngrams map. <br /> *return* The processed document with the added ngrams" [numbers document processed-document ngrams-count] (reduce (fn [processed-document ngram] (if (contains? ngrams-count (first ngram)) (assoc processed-document :counts (assoc (:counts processed-document) (first ngram) (second ngram)) :number-of-words (+ (:number-of-words processed-document) (second ngram))) processed-document)) processed-document (n-grams-count numbers (list document)))) (defmulti format-tag keyword) (defmethod format-tag :plain-NER [_] #(str (:opening plain-NER-tags) % (:middle plain-NER-tags) %2 (:closing plain-NER-tags))) (defmethod format-tag :openNLP-NER [_] #(str (:opening openNLP-NER-tags) % (:middle openNLP-NER-tags) %2 (:closing openNLP-NER-tags))) (defmethod format-tag :stanfordNLP-NER [_] #(str %2 \tab %)) (defmethod format-tag :custom-NER [o] (if (= (first (:order @custom-NER-tags)) :token) #(str (:opening @custom-NER-tags) %2 (:middle @custom-NER-tags) % (:closing @custom-NER-tags)) #(str (:opening @custom-NER-tags) % (:middle @custom-NER-tags) %2 (:closing @custom-NER-tags)))) (defn pool-map "A saner, more disciplined version of pmap. Submits jobs eagerly but polls for results lazily. Don't use if original ordering of 'coll' matters." ([f coll threads] (let [exec (Executors/newFixedThreadPool threads) pool (ExecutorCompletionService. exec) futures (try (mapv (fn [x] (.submit pool #(f x))) coll) (finally (.shutdown exec)))] (repeatedly (count futures) #(.. pool take get)))) ([f coll] (pool-map f coll (+ 2 cpu-no)))) (defn fold-into-vec [chunk coll] "Provided a reducer, concatenate into a vector. Same as (into [] coll), but parallel." (r/fold chunk (r/monoid into vector) conj coll)) (defn rmap "A high-performance, fork-join based mapping function that uses ArrayList underneath." ([f coll fj-chunk-size shuffle?] (r/fold fj-chunk-size r/cat r/append! (r/map f (cond-> coll shuffle? shuffle (not shuffle?) vec)))) ([f coll fj-chunk-size] (rhmap f coll fj-chunk-size false)) ([f coll] (rhmap f coll 1)) ) (defn mapr "A pretty basic map-reduce style mapping function. Will partition the data according to p-size and assign a future to each partition (per pmap)." ([f coll p-size shuffle?] (->> (cond-> coll shuffle? shuffle) (partition-all p-size) (pmap #(mapv f %) ) ([f coll p-size] (mapr f coll p-size false)) ([f coll] (mapr f coll (+ 2 cpu-no)))) (defn- file->data "Read the file f back on memory safely. Contents of f should be a clojure data-structure. Not allowed to execute arbitrary code (per #=)." [f] (binding [*read-eval* false] (read-string (slurp f)))) (defn- combine-dicts "Takes a seq of dictionaries (seqs) and produces a united set of all entries (no duplicates)." [ds] (if (< 1 (count ds)) (let [set-views (map set ds)] (apply union set-views)) (first ds))) (defn- space-out "Given some text, find all the openNLP sgml tags that are not surrounded by spaces and put spaces around them." ^String [^String text t-scheme] (when-not (or (blank? (:opening t-scheme)) (blank? (:closing t-scheme))) " ( ? < ! ) < STA " ) (.replaceAll "$0 "))) (.replaceAll " $0")))) (defn- create-folder! "Creates a folder at the specified path." [^String path] (.mkdir (File. path))) (defn- mapping-fn "Returns a fn that will take care mapping with this stratefy. Supported options include :serial, :lazy, :lazy-parallel, :pool-parallel, :map-reduce & :fork-join." [strategy] (case strategy :serial mapv :lazy map :lazy-parallel pmap :pool-parallel pool-map :map-reduce mapr :fork-join rmap)) (defn- file-write-mode "Returns a fn that will take care writing files in this mode. Supported options include :merge-all, :per-file & :on-screen." [mode target-f] (case mode :merge-all (fn [target content] (do (spit target content :append true) (spit target "\n\n" :append true))) :per-file (fn [target content] (let [fname (str target-f "/" target ".pann")] (spit fname content))) :on-screen (fn [_ content] (print content "\n\n")) )) (defn file-filter [filter] (reify FileFilter (accept [this f] (boolean (re-find (re-pattern (str ".*" filter)) (.getName ^File f)))))) (defn- sort-input [data-s ffilter] (let [data-seq (-> data-s slurp read-string) fitem (first data-seq)] f-seq (if-let [ff ffilter] (.listFiles ^File directory ^FileFilter (file-filter ff)) (.listFiles ^File directory)) f-seq-names (for [f f-seq :when #(.isFile ^File f)] (.getPath ^File f))] (reset! global-dic (combine-dicts (mapv normaliser (next data-seq)))) build the new 2d vector (defn- annotate "Overloaded function. First one takes a filename f, an entity-type (e.g. \"person\") and some dictionaries and annotates the text in f with openNLP compatible sgml tags for that entity-type using the provided dictionaries. Second one takes a map with 3 keys. The :files+dics key should point to a (2d) seq that contains other seqs where the 1st item is the file we want to annotate and the rest are the available dictionaries. The :target key specifies the file to write the resulting annotated text and :entity-type describes the entities (nil falls-back to \"default\"). Unless you have a single file to process, you should start with the 2nd overload as in the example below. The output file will contain new-line delimiters per processed document. e.g. :file+dics [[\"train/invitro_train-raw.txt\" \"train/invitro-train-names-distinct.txt\"] [\"train/invivo_train-raw.txt\" \"train/invivo-train-names-distinct.txt\"]]})" (^String [^String f ^String entity-type dics lib] (let [dic (if-let [gb @global-dic] gb (combine-dicts (mapv normaliser dics))) file-name (.getName (java.io.File. f)) format-fn (format-tag lib)] (println (str "Processing document: " f)) (loop [text (slurp f) names dic] (if-let [name1 (first names)] (recur (try (.replaceAll (re-matcher (re-pattern (str "(?i)\\b+" (Pattern/quote name1) "+\\b")) text) (format-fn entity-type name1)) (catch PatternSyntaxException _ (do (println (str "--- COULD NOT BE PROCESSED! --->" name1)) text))) (next names)) [file-name (s-split text)])) )) ([{:keys [files+dics entity-type target target-folder consumer-lib strategy write-mode file-filter] :or {entity-type "default" target "target-file.txt" target-folder "ANNOTATED" consumer-lib "openNLP-NER" strategy "lazy-parallel" write-mode "merge-all" file-filter "txt"}}] (let [f+ds (sort-input files+dics file-filter) #(let [[f a] (annotate (first %) entity-type (next %) (keyword consumer-lib))] (vector f (space-out a (var-get (ns-resolve 'PAnnotator.core (symbol (str consumer-lib "-tags"))))))) (cond (string? f+ds) (file->data f+ds) (vector? f+ds) f+ds :else (throw (IllegalArgumentException. "Weird data-format encountered! Cannot proceed..."))) ) wfn (do (when (= write-mode "per-file") (create-folder! target-folder)) wmd (if (= write-mode "merge-all") (constantly target) identity)] (doseq [[f a] annotations] (wfn (wmd f) a)))) ) (def -process annotate) (def HELP_MESSAGE "\nINSTRUCTIONS: java -cp PAnnotator-uberjar.jar Annotator -d <DATA-FILE>* -t <TARGET-FILE>** -e <ENTITY-TYPE>*** -par serial OR lazy OR lazy-parallel OR pool-parallel OR fork-join**** -wm merge-all OR per-file OR on-screen***** -fl \"openNLP-NER\" OR \"stanfordNLP-NER\" OR \"plain-NER\" -ct \"{:opening \"_\" :closing \"_\" :middle \":\"}\" -chu an integer value typically from 2 to 6 \n *must be a file with a 2D clojure seqable of the form: [[input1 dic1 dic2 dic3 dic4] [input2 dic5 dic6 dic7] [input3 dic8 dic9]] *defaults to 'data-file.txt' **defaults to 'target-file.txt' ***optional argument - defaults to \"default\" ****optional argument - defaults to 'lazy-parallel' *****optional argument - defaults to 'merge-all'") (defn -main [& args] (let [[opts argus banner] (cli args ["-h" "--help" "Show help/instructions." :flag true :default false] ["-d" "--data" "REQUIRED: The data-file (e.g. \"data.txt\")" :default "data-file.txt"] ["-e" "--entity-type" "REQUIRED: The type of entity in question (e.g. \"river\")" :default "default"] ["-t" "--target" "REQUIRED: The target-file (e.g. \"target.txt\")" :default "target-file.txt"] ["-tfo" "--target-folder" "Specify a target folder. Only useful if write-mode is set 'to per-file' (defaults to ANNOTATED/)." :default "ANNOTATED"] ["-ct" "--custom-tags" "Specify your own tags. (e.g \"{:opening \"_\" :closing \"_\" :middle \":\" :order [:token :entity]}\")"] ["-par" "--parallelism" "Set a parallelisation strategy (other options are: serial, lazy, pool-parallel & fork-join)." :default "lazy-parallel"] ["-chu" "--chunking" "Specify the number where recursive tree splitting should stop in a fork-join task (defaults to 4)." :default 4] ["-wm" "--write-mode" "Set file-write-mode (other options are: per-file & on-screen)." :default "merge-all"] ["-ff" "--file-filter" "Specify a file-filter when processing an entire folder (there is NO default - all files will be processed)."] ["-fl" "--for-lib" "Apply a predefined tagging format (other options are: stanfordNLP-NER, plain-NER & custom-NER)." :default "openNLP-NER"] ["-tok" "--tokens" "Extracts (and optionally stems) tokens from the supplied string or file. Activate stemming with the -ste flag."] ["-ste" "--stemming" "Activates porter-stemming. Only useful when paired with the -tok switch which returns the tokens." :flag true :default false] ["-lang" "--language" "Set the stemming language. Only useful when paired with the -tok and -ste switches." :default "english"] ["-allign" "--allignment" "Perform local allignement (Smith-Waterman) between 2 sequences."] ["-dist" "--edit-distance" "Calculate the edit-distance (Levenshtein) between 2 words."] ["-rpdf" "--ripdf" "Extract the contents from a pdf file and write them to a plain txt file."] ["-dname" "--drugname" "Generate a finite list (you provide how many) of randomly assembled name(s) that look like drugs (orthographically)."] )] (when (:help opts) (println HELP_MESSAGE "\n\n" banner) (System/exit 0)) (when-let [source (:ripdf opts)] (pdf->txt source) (System/exit 0)) (when-let [how-many (:drugname opts)] (let [n (Integer/parseInt how-many)] (println (apply randrugs n (drop 2 args))) (System/exit 0))) (when (:allignment opts) (if (> 3 (count args)) (do (println "Less than 2 arguments detected! Please provide 2 sequences to allign...") (System/exit 0)) (do (println (allignSW (second args) (nth args 2))) (System/exit 0)))) (when (:edit-distance opts) (if (> 3 (count args)) (do (println "Less than 2 arguments detected! Please provide 2 words to compare...") (System/exit 0)) (do (println "\nLevenshtein distance =" (getDistance (second args) (nth args 2))) (System/exit 0)))) (when-let [ss (:tokens opts)] (if (:stemming opts) (pprint (simple-tokenize (if (string? ss) ss (slurp ss)) :stemmer #(getRoot % (:language opts)))) (pprint (simple-tokenize (if (string? ss) ss (slurp ss))))) (System/exit 0)) (when-let [cs (:chunking opts)] (reset! fj-chunk-size (Integer/valueOf ^Integer cs))) (do (println "\n\t\t====> \u001B[35mPAnnotator\u001B[m \u001B[32mv0.3.4\u001B[m <====\t\t\n\t\t-----------------------------\n\n") (println "\tRun settings:" "\n\n--Entity-Type:" (:entity-type opts) "\n--Target-File:" (:target opts) "\n--Target-Folder:" (:target-folder opts) "\n--Data-File:" (:data opts) "\n--Mapping strategy:" (:parallelism opts) "\n--Fork-join tree leaf-size:" @fj-chunk-size "(potentially irrelevant for this run)" "\n--Consumer library:" (:for-lib opts) "(potentially irrelevant for this run)" "\n--Write-Mode:" (:write-mode opts) "\n--Custom-tags:" (:custom-tags opts) "\n\n") (-process {:entity-type (:entity-type opts) :target (:target opts) :target-folder (:target-folder opts) :files+dics (:data opts) :file-filter (:file-filter opts) :strategy (:parallelism opts) :write-mode (:write-mode opts) :consumer-lib (if-let [cu (:custom-tags opts)] (do (swap! custom-NER-tags merge (read-string cu)) "custom-NER") (:for-lib opts))}) (case (:write-mode opts) "merge-all" (println "--------------------------------------------------------\n" "SUCCESS! Look for a file called" (str "'" (:target opts) "'. \n")) "per-file" (println "--------------------------------------------------------\n" "SUCCESS! Look for the file(s) under folder" (str (or (:target-folder opts) "ANNOTATED") "/ at the root of your classpath. \n")) "on-screen" (println "-----------------------------------------------------\n\n => THAT WAS IT...!\n") (println "write-mode can be either 'merge-all' or 'per-file' or 'on-screen'...")) (shutdown-agents) (System/exit 0)) ))
609e7c1b363d52ffa93e8d3a43f2c681ca28fc4d8ad6cd04dd36a3b3b04c7def
berke/jsure
minefield.ml
(* Minefield *) module SS = Set.Make(String);; module SM = Map.Make(String);; type t = { mutable mf_words : int SM.t; } module L = Levenshtein.Levenshtein_string;; let create () = { mf_words = SM.empty };; let add_word mf u = mf.mf_words <- SM.add u 0 mf.mf_words;; let check_proximity mf u = if SM.mem u mf.mf_words then None else begin let min_dist = ref max_float in let nearest_word = ref None in SM.iter begin fun v _ -> let d = L.distance u v in if d < !min_dist then begin min_dist := d; nearest_word := Some v end end mf.mf_words; match !nearest_word with | None -> None | Some v -> Some(!min_dist, v) end ;;
null
https://raw.githubusercontent.com/berke/jsure/f7c32e21602cd8d8f18e90a608cfc59b1172be57/minefield.ml
ocaml
Minefield
module SS = Set.Make(String);; module SM = Map.Make(String);; type t = { mutable mf_words : int SM.t; } module L = Levenshtein.Levenshtein_string;; let create () = { mf_words = SM.empty };; let add_word mf u = mf.mf_words <- SM.add u 0 mf.mf_words;; let check_proximity mf u = if SM.mem u mf.mf_words then None else begin let min_dist = ref max_float in let nearest_word = ref None in SM.iter begin fun v _ -> let d = L.distance u v in if d < !min_dist then begin min_dist := d; nearest_word := Some v end end mf.mf_words; match !nearest_word with | None -> None | Some v -> Some(!min_dist, v) end ;;
2508052157a48b2a35eb4fe9527d7c987e2191a004a28a84584775ecfc0b4539
gonzojive/sbcl
arith.lisp
;;;; the VM definition of arithmetic VOPs for the x86 This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!VM") ;;;; unary operations (define-vop (fast-safe-arith-op) (:policy :fast-safe) (:effects) (:affected)) (define-vop (fixnum-unop fast-safe-arith-op) (:args (x :scs (any-reg) :target res)) (:results (res :scs (any-reg))) (:note "inline fixnum arithmetic") (:arg-types tagged-num) (:result-types tagged-num)) (define-vop (signed-unop fast-safe-arith-op) (:args (x :scs (signed-reg) :target res)) (:results (res :scs (signed-reg))) (:note "inline (signed-byte 32) arithmetic") (:arg-types signed-num) (:result-types signed-num)) (define-vop (fast-negate/fixnum fixnum-unop) (:translate %negate) (:generator 1 (move res x) (inst neg res))) (define-vop (fast-negate/signed signed-unop) (:translate %negate) (:generator 2 (move res x) (inst neg res))) (define-vop (fast-lognot/fixnum fixnum-unop) (:translate lognot) (:generator 1 (move res x) (inst xor res (fixnumize -1)))) (define-vop (fast-lognot/signed signed-unop) (:translate lognot) (:generator 2 (move res x) (inst not res))) ;;;; binary fixnum operations Assume that any constant operand is the second arg ... (define-vop (fast-fixnum-binop fast-safe-arith-op) (:args (x :target r :scs (any-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg) :from (:argument 0) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r))))) (:result-types tagged-num) (:note "inline fixnum arithmetic")) (define-vop (fast-unsigned-binop fast-safe-arith-op) (:args (x :target r :scs (unsigned-reg) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:results (r :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r))))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic")) (define-vop (fast-signed-binop fast-safe-arith-op) (:args (x :target r :scs (signed-reg) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (sc-is r signed-stack) (location= x r)))) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg) :from (:argument 0) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (sc-is r signed-stack) (location= x r))))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic")) (define-vop (fast-fixnum-binop-c fast-safe-arith-op) (:args (x :target r :scs (any-reg control-stack))) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:results (r :scs (any-reg) :load-if (not (location= x r)))) (:result-types tagged-num) (:note "inline fixnum arithmetic")) (define-vop (fast-unsigned-binop-c fast-safe-arith-op) (:args (x :target r :scs (unsigned-reg unsigned-stack))) (:info y) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:results (r :scs (unsigned-reg) :load-if (not (location= x r)))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic")) (define-vop (fast-signed-binop-c fast-safe-arith-op) (:args (x :target r :scs (signed-reg signed-stack))) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:results (r :scs (signed-reg) :load-if (not (location= x r)))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic")) (macrolet ((define-binop (translate untagged-penalty op) `(progn (define-vop (,(symbolicate "FAST-" translate "/FIXNUM=>FIXNUM") fast-fixnum-binop) (:translate ,translate) (:generator 2 (move r x) (inst ,op r y))) (define-vop (,(symbolicate 'fast- translate '-c/fixnum=>fixnum) fast-fixnum-binop-c) (:translate ,translate) (:generator 1 (move r x) (inst ,op r (fixnumize y)))) (define-vop (,(symbolicate "FAST-" translate "/SIGNED=>SIGNED") fast-signed-binop) (:translate ,translate) (:generator ,(1+ untagged-penalty) (move r x) (inst ,op r y))) (define-vop (,(symbolicate 'fast- translate '-c/signed=>signed) fast-signed-binop-c) (:translate ,translate) (:generator ,untagged-penalty (move r x) (inst ,op r y))) (define-vop (,(symbolicate "FAST-" translate "/UNSIGNED=>UNSIGNED") fast-unsigned-binop) (:translate ,translate) (:generator ,(1+ untagged-penalty) (move r x) (inst ,op r y))) (define-vop (,(symbolicate 'fast- translate '-c/unsigned=>unsigned) fast-unsigned-binop-c) (:translate ,translate) (:generator ,untagged-penalty (move r x) ,(if (eq translate 'logand) for the -C / UNSIGNED=>UNSIGNED VOP , this case ;; is optimized away as an identity somewhere along the lines . However , this VOP is used in ;; -C/SIGNED=>UNSIGNED, below, when the ;; higher-level lisp code can't optimize away the ;; non-trivial identity. `(unless (= y #.(1- (ash 1 n-word-bits))) (inst ,op r y)) `(inst ,op r y))))))) (define-binop - 4 sub) (define-binop logand 2 and) (define-binop logior 2 or) (define-binop logxor 2 xor)) Special handling of add on the x86 ; can use to avoid a ;;; register load, otherwise it uses add. (define-vop (fast-+/fixnum=>fixnum fast-safe-arith-op) (:translate +) (:args (x :scs (any-reg) :target r :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg) :from (:argument 0) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r))))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 2 (cond ((and (sc-is x any-reg) (sc-is y any-reg) (sc-is r any-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :index y :scale 1))) (t (move r x) (inst add r y))))) (define-vop (fast-+-c/fixnum=>fixnum fast-safe-arith-op) (:translate +) (:args (x :target r :scs (any-reg control-stack))) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:results (r :scs (any-reg) :load-if (not (location= x r)))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 1 (cond ((and (sc-is x any-reg) (sc-is r any-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :disp (fixnumize y)))) (t (move r x) (inst add r (fixnumize y)))))) (define-vop (fast-+/signed=>signed fast-safe-arith-op) (:translate +) (:args (x :scs (signed-reg) :target r :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (sc-is r signed-stack) (location= x r)))) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg) :from (:argument 0) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (location= x r))))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 5 (cond ((and (sc-is x signed-reg) (sc-is y signed-reg) (sc-is r signed-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :index y :scale 1))) (t (move r x) (inst add r y))))) ;;;; Special logand cases: (logand signed unsigned) => unsigned (define-vop (fast-logand/signed-unsigned=>unsigned fast-logand/unsigned=>unsigned) (:args (x :target r :scs (signed-reg) :load-if (not (and (sc-is x signed-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types signed-num unsigned-num)) (define-vop (fast-logand-c/signed-unsigned=>unsigned fast-logand-c/unsigned=>unsigned) (:args (x :target r :scs (signed-reg signed-stack))) (:arg-types signed-num (:constant (unsigned-byte 32)))) (define-vop (fast-logand/unsigned-signed=>unsigned fast-logand/unsigned=>unsigned) (:args (x :target r :scs (unsigned-reg) :load-if (not (and (sc-is x unsigned-stack) (sc-is y signed-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (signed-reg signed-stack))) (:arg-types unsigned-num signed-num)) (define-vop (fast-+-c/signed=>signed fast-safe-arith-op) (:translate +) (:args (x :target r :scs (signed-reg signed-stack))) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:results (r :scs (signed-reg) :load-if (not (location= x r)))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 4 (cond ((and (sc-is x signed-reg) (sc-is r signed-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :disp y))) (t (move r x) (if (= y 1) (inst inc r) (inst add r y)))))) (define-vop (fast-+/unsigned=>unsigned fast-safe-arith-op) (:translate +) (:args (x :scs (unsigned-reg) :target r :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:results (r :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r))))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:generator 5 (cond ((and (sc-is x unsigned-reg) (sc-is y unsigned-reg) (sc-is r unsigned-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :index y :scale 1))) (t (move r x) (inst add r y))))) (define-vop (fast-+-c/unsigned=>unsigned fast-safe-arith-op) (:translate +) (:args (x :target r :scs (unsigned-reg unsigned-stack))) (:info y) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:results (r :scs (unsigned-reg) :load-if (not (location= x r)))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:generator 4 (cond ((and (sc-is x unsigned-reg) (sc-is r unsigned-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :disp y))) (t (move r x) (if (= y 1) (inst inc r) (inst add r y)))))) ;;;; multiplication and division (define-vop (fast-*/fixnum=>fixnum fast-safe-arith-op) (:translate *) ;; We need different loading characteristics. (:args (x :scs (any-reg) :target r) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg) :from (:argument 0))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 4 (move r x) (inst sar r n-fixnum-tag-bits) (inst imul r y))) (define-vop (fast-*-c/fixnum=>fixnum fast-safe-arith-op) (:translate *) ;; We need different loading characteristics. (:args (x :scs (any-reg control-stack))) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:results (r :scs (any-reg))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 3 (inst imul r x y))) (define-vop (fast-*/signed=>signed fast-safe-arith-op) (:translate *) ;; We need different loading characteristics. (:args (x :scs (signed-reg) :target r) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg) :from (:argument 0))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 5 (move r x) (inst imul r y))) (define-vop (fast-*-c/signed=>signed fast-safe-arith-op) (:translate *) ;; We need different loading characteristics. (:args (x :scs (signed-reg signed-stack))) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:results (r :scs (signed-reg))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 4 (inst imul r x y))) (define-vop (fast-*/unsigned=>unsigned fast-safe-arith-op) (:translate *) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :target r :from (:argument 0) :to :result) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from :eval :to :result) edx) (:ignore edx) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 6 (move eax x) (inst mul eax y) (move r eax))) (define-vop (fast-truncate/fixnum=>fixnum fast-safe-arith-op) (:translate truncate) (:args (x :scs (any-reg) :target eax) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:temporary (:sc signed-reg :offset eax-offset :target quo :from (:argument 0) :to (:result 0)) eax) (:temporary (:sc unsigned-reg :offset edx-offset :target rem :from (:argument 0) :to (:result 1)) edx) (:results (quo :scs (any-reg)) (rem :scs (any-reg))) (:result-types tagged-num tagged-num) (:note "inline fixnum arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 31 (let ((zero (generate-error-code vop 'division-by-zero-error x y))) (if (sc-is y any-reg) (inst test y y) ; smaller instruction (inst cmp y 0)) (inst jmp :eq zero)) (move eax x) (inst cdq) (inst idiv eax y) (if (location= quo eax) (inst shl eax n-fixnum-tag-bits) (inst lea quo (make-ea :dword :index eax :scale (ash 1 n-fixnum-tag-bits)))) (move rem edx))) (define-vop (fast-truncate-c/fixnum=>fixnum fast-safe-arith-op) (:translate truncate) (:args (x :scs (any-reg) :target eax)) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:temporary (:sc signed-reg :offset eax-offset :target quo :from :argument :to (:result 0)) eax) (:temporary (:sc any-reg :offset edx-offset :target rem :from :eval :to (:result 1)) edx) (:temporary (:sc any-reg :from :eval :to :result) y-arg) (:results (quo :scs (any-reg)) (rem :scs (any-reg))) (:result-types tagged-num tagged-num) (:note "inline fixnum arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 30 (move eax x) (inst cdq) (inst mov y-arg (fixnumize y)) (inst idiv eax y-arg) (if (location= quo eax) (inst shl eax n-fixnum-tag-bits) (inst lea quo (make-ea :dword :index eax :scale (ash 1 n-fixnum-tag-bits)))) (move rem edx))) (define-vop (fast-truncate/unsigned=>unsigned fast-safe-arith-op) (:translate truncate) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg signed-stack))) (:arg-types unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :target quo :from (:argument 0) :to (:result 0)) eax) (:temporary (:sc unsigned-reg :offset edx-offset :target rem :from (:argument 0) :to (:result 1)) edx) (:results (quo :scs (unsigned-reg)) (rem :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 33 (let ((zero (generate-error-code vop 'division-by-zero-error x y))) (if (sc-is y unsigned-reg) (inst test y y) ; smaller instruction (inst cmp y 0)) (inst jmp :eq zero)) (move eax x) (inst xor edx edx) (inst div eax y) (move quo eax) (move rem edx))) (define-vop (fast-truncate-c/unsigned=>unsigned fast-safe-arith-op) (:translate truncate) (:args (x :scs (unsigned-reg) :target eax)) (:info y) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:temporary (:sc unsigned-reg :offset eax-offset :target quo :from :argument :to (:result 0)) eax) (:temporary (:sc unsigned-reg :offset edx-offset :target rem :from :eval :to (:result 1)) edx) (:temporary (:sc unsigned-reg :from :eval :to :result) y-arg) (:results (quo :scs (unsigned-reg)) (rem :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 32 (move eax x) (inst xor edx edx) (inst mov y-arg y) (inst div eax y-arg) (move quo eax) (move rem edx))) (define-vop (fast-truncate/signed=>signed fast-safe-arith-op) (:translate truncate) (:args (x :scs (signed-reg) :target eax) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:temporary (:sc signed-reg :offset eax-offset :target quo :from (:argument 0) :to (:result 0)) eax) (:temporary (:sc signed-reg :offset edx-offset :target rem :from (:argument 0) :to (:result 1)) edx) (:results (quo :scs (signed-reg)) (rem :scs (signed-reg))) (:result-types signed-num signed-num) (:note "inline (signed-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 33 (let ((zero (generate-error-code vop 'division-by-zero-error x y))) (if (sc-is y signed-reg) (inst test y y) ; smaller instruction (inst cmp y 0)) (inst jmp :eq zero)) (move eax x) (inst cdq) (inst idiv eax y) (move quo eax) (move rem edx))) (define-vop (fast-truncate-c/signed=>signed fast-safe-arith-op) (:translate truncate) (:args (x :scs (signed-reg) :target eax)) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:temporary (:sc signed-reg :offset eax-offset :target quo :from :argument :to (:result 0)) eax) (:temporary (:sc signed-reg :offset edx-offset :target rem :from :eval :to (:result 1)) edx) (:temporary (:sc signed-reg :from :eval :to :result) y-arg) (:results (quo :scs (signed-reg)) (rem :scs (signed-reg))) (:result-types signed-num signed-num) (:note "inline (signed-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 32 (move eax x) (inst cdq) (inst mov y-arg y) (inst idiv eax y-arg) (move quo eax) (move rem edx))) ;;;; Shifting (define-vop (fast-ash-c/fixnum=>fixnum) (:translate ash) (:policy :fast-safe) (:args (number :scs (any-reg) :target result :load-if (not (and (sc-is number any-reg control-stack) (sc-is result any-reg control-stack) (location= number result))))) (:info amount) (:arg-types tagged-num (:constant integer)) (:results (result :scs (any-reg) :load-if (not (and (sc-is number control-stack) (sc-is result control-stack) (location= number result))))) (:result-types tagged-num) (:note "inline ASH") (:generator 2 (cond ((and (= amount 1) (not (location= number result))) (inst lea result (make-ea :dword :base number :index number))) ((and (= amount 2) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 4))) ((and (= amount 3) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 8))) (t (move result number) (cond ((< -32 amount 32) this code is used both in ASH and ASH - SMOD30 , so ;; be careful (if (plusp amount) (inst shl result amount) (progn (inst sar result (- amount)) (inst and result (lognot fixnum-tag-mask))))) ((plusp amount) (if (sc-is result any-reg) (inst xor result result) (inst mov result 0))) (t (inst sar result 31) (inst and result (lognot fixnum-tag-mask)))))))) (define-vop (fast-ash-left/fixnum=>fixnum) (:translate ash) (:args (number :scs (any-reg) :target result :load-if (not (and (sc-is number control-stack) (sc-is result control-stack) (location= number result)))) (amount :scs (unsigned-reg) :target ecx)) (:arg-types tagged-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (any-reg) :from (:argument 0) :load-if (not (and (sc-is number control-stack) (sc-is result control-stack) (location= number result))))) (:result-types tagged-num) (:policy :fast-safe) (:note "inline ASH") (:generator 3 (move result number) (move ecx amount) ;; The result-type ensures us that this shift will not overflow. (inst shl result :cl))) (define-vop (fast-ash-c/signed=>signed) (:translate ash) (:policy :fast-safe) (:args (number :scs (signed-reg) :target result :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result))))) (:info amount) (:arg-types signed-num (:constant integer)) (:results (result :scs (signed-reg) :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result))))) (:result-types signed-num) (:note "inline ASH") (:generator 3 (cond ((and (= amount 1) (not (location= number result))) (inst lea result (make-ea :dword :base number :index number))) ((and (= amount 2) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 4))) ((and (= amount 3) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 8))) (t (move result number) (cond ((plusp amount) (inst shl result amount)) (t (inst sar result (min 31 (- amount))))))))) (define-vop (fast-ash-c/unsigned=>unsigned) (:translate ash) (:policy :fast-safe) (:args (number :scs (unsigned-reg) :target result :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result))))) (:info amount) (:arg-types unsigned-num (:constant integer)) (:results (result :scs (unsigned-reg) :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result))))) (:result-types unsigned-num) (:note "inline ASH") (:generator 3 (cond ((and (= amount 1) (not (location= number result))) (inst lea result (make-ea :dword :base number :index number))) ((and (= amount 2) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 4))) ((and (= amount 3) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 8))) (t (move result number) (cond ((< -32 amount 32) this code is used both in ASH and ASH - MOD32 , so ;; be careful (if (plusp amount) (inst shl result amount) (inst shr result (- amount)))) (t (if (sc-is result unsigned-reg) (inst xor result result) (inst mov result 0)))))))) (define-vop (fast-ash-left/signed=>signed) (:translate ash) (:args (number :scs (signed-reg) :target result :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result)))) (amount :scs (unsigned-reg) :target ecx)) (:arg-types signed-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (signed-reg) :from (:argument 0) :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result))))) (:result-types signed-num) (:policy :fast-safe) (:note "inline ASH") (:generator 4 (move result number) (move ecx amount) (inst shl result :cl))) (define-vop (fast-ash-left/unsigned=>unsigned) (:translate ash) (:args (number :scs (unsigned-reg) :target result :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result)))) (amount :scs (unsigned-reg) :target ecx)) (:arg-types unsigned-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result))))) (:result-types unsigned-num) (:policy :fast-safe) (:note "inline ASH") (:generator 4 (move result number) (move ecx amount) (inst shl result :cl))) (define-vop (fast-ash/signed=>signed) (:translate ash) (:policy :fast-safe) (:args (number :scs (signed-reg) :target result) (amount :scs (signed-reg) :target ecx)) (:arg-types signed-num signed-num) (:results (result :scs (signed-reg) :from (:argument 0))) (:result-types signed-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:note "inline ASH") (:generator 5 (move result number) (move ecx amount) (inst or ecx ecx) (inst jmp :ns positive) (inst neg ecx) (inst cmp ecx 31) (inst jmp :be okay) (inst mov ecx 31) OKAY (inst sar result :cl) (inst jmp done) POSITIVE ;; The result-type ensures us that this shift will not overflow. (inst shl result :cl) DONE)) (define-vop (fast-ash/unsigned=>unsigned) (:translate ash) (:policy :fast-safe) (:args (number :scs (unsigned-reg) :target result) (amount :scs (signed-reg) :target ecx)) (:arg-types unsigned-num signed-num) (:results (result :scs (unsigned-reg) :from (:argument 0))) (:result-types unsigned-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:note "inline ASH") (:generator 5 (move result number) (move ecx amount) (inst or ecx ecx) (inst jmp :ns positive) (inst neg ecx) (inst cmp ecx 31) (inst jmp :be okay) (inst xor result result) (inst jmp done) OKAY (inst shr result :cl) (inst jmp done) POSITIVE ;; The result-type ensures us that this shift will not overflow. (inst shl result :cl) DONE)) (in-package "SB!C") (defknown %lea (integer integer (member 1 2 4 8) (signed-byte 32)) integer (foldable flushable movable)) (defoptimizer (%lea derive-type) ((base index scale disp)) (when (and (constant-lvar-p scale) (constant-lvar-p disp)) (let ((scale (lvar-value scale)) (disp (lvar-value disp)) (base-type (lvar-type base)) (index-type (lvar-type index))) (when (and (numeric-type-p base-type) (numeric-type-p index-type)) (let ((base-lo (numeric-type-low base-type)) (base-hi (numeric-type-high base-type)) (index-lo (numeric-type-low index-type)) (index-hi (numeric-type-high index-type))) (make-numeric-type :class 'integer :complexp :real :low (when (and base-lo index-lo) (+ base-lo (* index-lo scale) disp)) :high (when (and base-hi index-hi) (+ base-hi (* index-hi scale) disp)))))))) (defun %lea (base index scale disp) (+ base (* index scale) disp)) (in-package "SB!VM") (define-vop (%lea/unsigned=>unsigned) (:translate %lea) (:policy :fast-safe) (:args (base :scs (unsigned-reg)) (index :scs (unsigned-reg))) (:info scale disp) (:arg-types unsigned-num unsigned-num (:constant (member 1 2 4 8)) (:constant (signed-byte 32))) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 5 (inst lea r (make-ea :dword :base base :index index :scale scale :disp disp)))) (define-vop (%lea/signed=>signed) (:translate %lea) (:policy :fast-safe) (:args (base :scs (signed-reg)) (index :scs (signed-reg))) (:info scale disp) (:arg-types signed-num signed-num (:constant (member 1 2 4 8)) (:constant (signed-byte 32))) (:results (r :scs (signed-reg))) (:result-types signed-num) (:generator 4 (inst lea r (make-ea :dword :base base :index index :scale scale :disp disp)))) (define-vop (%lea/fixnum=>fixnum) (:translate %lea) (:policy :fast-safe) (:args (base :scs (any-reg)) (index :scs (any-reg))) (:info scale disp) (:arg-types tagged-num tagged-num (:constant (member 1 2 4 8)) (:constant (signed-byte 32))) (:results (r :scs (any-reg))) (:result-types tagged-num) (:generator 3 (inst lea r (make-ea :dword :base base :index index :scale scale :disp disp)))) ;;; FIXME: before making knowledge of this too public, it needs to be ;;; fixed so that it's actually _faster_ than the non-CMOV version; at least on my Celeron - XXX laptop , this version is marginally slower than the above version with branches . -- CSR , 2003 - 09 - 04 (define-vop (fast-cmov-ash/unsigned=>unsigned) (:translate ash) (:policy :fast-safe) (:args (number :scs (unsigned-reg) :target result) (amount :scs (signed-reg) :target ecx)) (:arg-types unsigned-num signed-num) (:results (result :scs (unsigned-reg) :from (:argument 0))) (:result-types unsigned-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:temporary (:sc any-reg :from (:eval 0) :to (:eval 1)) zero) (:note "inline ASH") (:guard (member :cmov *backend-subfeatures*)) (:generator 4 (move result number) (move ecx amount) (inst or ecx ecx) (inst jmp :ns positive) (inst neg ecx) (inst xor zero zero) (inst shr result :cl) (inst cmp ecx 31) (inst cmov :nbe result zero) (inst jmp done) POSITIVE ;; The result-type ensures us that this shift will not overflow. (inst shl result :cl) DONE)) (define-vop (signed-byte-32-len) (:translate integer-length) (:note "inline (signed-byte 32) integer-length") (:policy :fast-safe) (:args (arg :scs (signed-reg) :target res)) (:arg-types signed-num) (:results (res :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 28 (move res arg) (if (sc-is res unsigned-reg) (inst test res res) (inst cmp res 0)) (inst jmp :ge POS) (inst not res) POS (inst bsr res res) (inst jmp :z zero) (inst inc res) (inst jmp done) ZERO (inst xor res res) DONE)) (define-vop (unsigned-byte-32-len) (:translate integer-length) (:note "inline (unsigned-byte 32) integer-length") (:policy :fast-safe) (:args (arg :scs (unsigned-reg))) (:arg-types unsigned-num) (:results (res :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 26 (inst bsr res arg) (inst jmp :z zero) (inst inc res) (inst jmp done) ZERO (inst xor res res) DONE)) (define-vop (unsigned-byte-32-count) (:translate logcount) (:note "inline (unsigned-byte 32) logcount") (:policy :fast-safe) (:args (arg :scs (unsigned-reg) :target result)) (:arg-types unsigned-num) (:results (result :scs (unsigned-reg))) (:result-types positive-fixnum) (:temporary (:sc unsigned-reg) temp) (:generator 14 ;; See the comments below for how the algorithm works. The tricks used can be found for example in AMD 's software optimization guide or at " " in the ;; function "pop1". Calculate 2 - bit sums . Note that the value of a two - digit binary ;; number is the sum of the right digit and twice the left digit. Thus we can calculate the sum of the two digits by shifting the left digit to the right position and doing a two - bit subtraction . ;; This subtraction will never create a borrow and thus can be made on all 16 2 - digit numbers at once . (move result arg) (move temp arg) (inst shr result 1) (inst and result #x55555555) (inst sub temp result) Calculate 4 - bit sums by straightforward shift , mask and add . Note that we shift the source operand of the MOV and not its destination so that the SHR and the MOV can execute in the same ;; clock cycle. (inst mov result temp) (inst shr temp 2) (inst and result #x33333333) (inst and temp #x33333333) (inst add result temp) Calculate 8 - bit sums . Since each sum is at most 8 , which fits into 4 bits , we can apply the mask after the addition , saving one ;; instruction. (inst mov temp result) (inst shr result 4) (inst add result temp) (inst and result #x0f0f0f0f) Calculate the two 16 - bit sums and the 32 - bit sum . No masking is ;; necessary inbetween since the final sum is at most 32 which fits into 6 bits . (inst mov temp result) (inst shr result 8) (inst add result temp) (inst mov temp result) (inst shr result 16) (inst add result temp) (inst and result #xff))) ;;;; binary conditional VOPs (define-vop (fast-conditional) (:conditional :e) (:effects) (:affected) (:policy :fast-safe)) (define-vop (fast-conditional/fixnum fast-conditional) (:args (x :scs (any-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison")) (define-vop (fast-conditional-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg control-stack))) (:arg-types tagged-num (:constant (signed-byte 30))) (:info y)) (define-vop (fast-conditional/signed fast-conditional) (:args (x :scs (signed-reg) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg)))) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:note "inline (signed-byte 32) comparison")) (define-vop (fast-conditional-c/signed fast-conditional/signed) (:args (x :scs (signed-reg signed-stack))) (:arg-types signed-num (:constant (signed-byte 32))) (:info y)) (define-vop (fast-conditional/unsigned fast-conditional) (:args (x :scs (unsigned-reg) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) comparison")) (define-vop (fast-conditional-c/unsigned fast-conditional/unsigned) (:args (x :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:info y)) (macrolet ((define-logtest-vops () `(progn ,@(loop for suffix in '(/fixnum -c/fixnum /signed -c/signed /unsigned -c/unsigned) for cost in '(4 3 6 5 6 5) collect `(define-vop (,(symbolicate "FAST-LOGTEST" suffix) ,(symbolicate "FAST-CONDITIONAL" suffix)) (:translate logtest) (:conditional :ne) (:generator ,cost (emit-optimized-test-inst x ,(if (eq suffix '-c/fixnum) '(fixnumize y) 'y)))))))) (define-logtest-vops)) (defknown %logbitp (integer unsigned-byte) boolean (movable foldable flushable always-translatable)) ;;; only for constant folding within the compiler (defun %logbitp (integer index) (logbitp index integer)) ;;; too much work to do the non-constant case (maybe?) (define-vop (fast-logbitp-c/fixnum fast-conditional-c/fixnum) (:translate %logbitp) (:conditional :c) (:arg-types tagged-num (:constant (integer 0 29))) (:generator 4 (inst bt x (+ y n-fixnum-tag-bits)))) (define-vop (fast-logbitp/signed fast-conditional/signed) (:args (x :scs (signed-reg signed-stack)) (y :scs (signed-reg))) (:translate %logbitp) (:conditional :c) (:generator 6 (inst bt x y))) (define-vop (fast-logbitp-c/signed fast-conditional-c/signed) (:translate %logbitp) (:conditional :c) (:arg-types signed-num (:constant (integer 0 31))) (:generator 5 (inst bt x y))) (define-vop (fast-logbitp/unsigned fast-conditional/unsigned) (:args (x :scs (unsigned-reg unsigned-stack)) (y :scs (unsigned-reg))) (:translate %logbitp) (:conditional :c) (:generator 6 (inst bt x y))) (define-vop (fast-logbitp-c/unsigned fast-conditional-c/unsigned) (:translate %logbitp) (:conditional :c) (:arg-types unsigned-num (:constant (integer 0 31))) (:generator 5 (inst bt x y))) (macrolet ((define-conditional-vop (tran cond unsigned) `(progn ,@(mapcar (lambda (suffix cost signed) `(define-vop (;; FIXME: These could be done more ;; cleanly with SYMBOLICATE. ,(intern (format nil "~:@(FAST-IF-~A~A~)" tran suffix)) ,(intern (format nil "~:@(FAST-CONDITIONAL~A~)" suffix))) (:translate ,tran) (:conditional ,(if signed cond unsigned)) (:generator ,cost (inst cmp x ,(if (eq suffix '-c/fixnum) '(fixnumize y) 'y))))) '(/fixnum -c/fixnum /signed -c/signed /unsigned -c/unsigned) '(4 3 6 5 6 5) '(t t t t nil nil))))) (define-conditional-vop < :l :b) (define-conditional-vop > :g :a)) (define-vop (fast-if-eql/signed fast-conditional/signed) (:translate eql) (:generator 6 (inst cmp x y))) (define-vop (fast-if-eql-c/signed fast-conditional-c/signed) (:translate eql) (:generator 5 (cond ((and (sc-is x signed-reg) (zerop y)) (inst test x x)) ; smaller instruction (t (inst cmp x y))))) (define-vop (fast-if-eql/unsigned fast-conditional/unsigned) (:translate eql) (:generator 6 (inst cmp x y))) (define-vop (fast-if-eql-c/unsigned fast-conditional-c/unsigned) (:translate eql) (:generator 5 (cond ((and (sc-is x unsigned-reg) (zerop y)) (inst test x x)) ; smaller instruction (t (inst cmp x y))))) EQL / FIXNUM is funny because the first arg can be of any type , not just a ;;; known fixnum. These versions specify a fixnum restriction on their first arg . We have ;;; also generic-eql/fixnum VOPs which are the same, but have no restriction on the first arg and a higher cost . The reason for doing this is to prevent ;;; fixnum specific operations from being used on word integers, spuriously ;;; consing the argument. (define-vop (fast-eql/fixnum fast-conditional) (:args (x :scs (any-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison") (:translate eql) (:generator 4 (inst cmp x y))) (define-vop (generic-eql/fixnum fast-eql/fixnum) (:args (x :scs (any-reg descriptor-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg)))) (y :scs (any-reg control-stack))) (:arg-types * tagged-num) (:variant-cost 7)) (define-vop (fast-eql-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg control-stack))) (:arg-types tagged-num (:constant (signed-byte 30))) (:info y) (:translate eql) (:generator 2 (cond ((and (sc-is x any-reg) (zerop y)) (inst test x x)) ; smaller instruction (t (inst cmp x (fixnumize y)))))) (define-vop (generic-eql-c/fixnum fast-eql-c/fixnum) (:args (x :scs (any-reg descriptor-reg control-stack))) (:arg-types * (:constant (signed-byte 30))) (:variant-cost 6)) 32 - bit logical operations Only the lower 5 bits of the shift amount are significant . (define-vop (shift-towards-someplace) (:policy :fast-safe) (:args (num :scs (unsigned-reg) :target r) (amount :scs (signed-reg) :target ecx)) (:arg-types unsigned-num tagged-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (r :scs (unsigned-reg) :from (:argument 0))) (:result-types unsigned-num)) (define-vop (shift-towards-start shift-towards-someplace) (:translate shift-towards-start) (:note "SHIFT-TOWARDS-START") (:generator 1 (move r num) (move ecx amount) (inst shr r :cl))) (define-vop (shift-towards-end shift-towards-someplace) (:translate shift-towards-end) (:note "SHIFT-TOWARDS-END") (:generator 1 (move r num) (move ecx amount) (inst shl r :cl))) Modular functions (defmacro define-mod-binop ((name prototype) function) `(define-vop (,name ,prototype) (:args (x :target r :scs (unsigned-reg signed-reg) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is y unsigned-reg) (sc-is y signed-reg)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (location= x r)))) (y :scs (unsigned-reg signed-reg unsigned-stack signed-stack))) (:arg-types untagged-num untagged-num) (:results (r :scs (unsigned-reg signed-reg) :from (:argument 0) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is y unsigned-reg) (sc-is y unsigned-reg)) (or (sc-is r unsigned-stack) (sc-is r unsigned-stack)) (location= x r))))) (:result-types unsigned-num) (:translate ,function))) (defmacro define-mod-binop-c ((name prototype) function) `(define-vop (,name ,prototype) (:args (x :target r :scs (unsigned-reg signed-reg) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (location= x r))))) (:info y) (:arg-types untagged-num (:constant (or (unsigned-byte 32) (signed-byte 32)))) (:results (r :scs (unsigned-reg signed-reg) :from (:argument 0) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r unsigned-stack)) (location= x r))))) (:result-types unsigned-num) (:translate ,function))) (macrolet ((def (name -c-p) (let ((fun32 (intern (format nil "~S-MOD32" name))) (vopu (intern (format nil "FAST-~S/UNSIGNED=>UNSIGNED" name))) (vopcu (intern (format nil "FAST-~S-C/UNSIGNED=>UNSIGNED" name))) (vopf (intern (format nil "FAST-~S/FIXNUM=>FIXNUM" name))) (vopcf (intern (format nil "FAST-~S-C/FIXNUM=>FIXNUM" name))) (vop32u (intern (format nil "FAST-~S-MOD32/WORD=>UNSIGNED" name))) (vop32f (intern (format nil "FAST-~S-MOD32/FIXNUM=>FIXNUM" name))) (vop32cu (intern (format nil "FAST-~S-MOD32-C/WORD=>UNSIGNED" name))) (vop32cf (intern (format nil "FAST-~S-MOD32-C/FIXNUM=>FIXNUM" name))) (sfun30 (intern (format nil "~S-SMOD30" name))) (svop30f (intern (format nil "FAST-~S-SMOD30/FIXNUM=>FIXNUM" name))) (svop30cf (intern (format nil "FAST-~S-SMOD30-C/FIXNUM=>FIXNUM" name)))) `(progn (define-modular-fun ,fun32 (x y) ,name :untagged nil 32) (define-modular-fun ,sfun30 (x y) ,name :tagged t 30) (define-mod-binop (,vop32u ,vopu) ,fun32) (define-vop (,vop32f ,vopf) (:translate ,fun32)) (define-vop (,svop30f ,vopf) (:translate ,sfun30)) ,@(when -c-p `((define-mod-binop-c (,vop32cu ,vopcu) ,fun32) (define-vop (,svop30cf ,vopcf) (:translate ,sfun30)))))))) (def + t) (def - t) ;; (no -C variant as x86 MUL instruction doesn't take an immediate) (def * nil)) (define-vop (fast-ash-left-mod32-c/unsigned=>unsigned fast-ash-c/unsigned=>unsigned) (:translate ash-left-mod32)) (define-vop (fast-ash-left-mod32/unsigned=>unsigned fast-ash-left/unsigned=>unsigned)) (deftransform ash-left-mod32 ((integer count) ((unsigned-byte 32) (unsigned-byte 5))) (when (sb!c::constant-lvar-p count) (sb!c::give-up-ir1-transform)) '(%primitive fast-ash-left-mod32/unsigned=>unsigned integer count)) (define-vop (fast-ash-left-smod30-c/fixnum=>fixnum fast-ash-c/fixnum=>fixnum) (:translate ash-left-smod30)) (define-vop (fast-ash-left-smod30/fixnum=>fixnum fast-ash-left/fixnum=>fixnum)) (deftransform ash-left-smod30 ((integer count) ((signed-byte 30) (unsigned-byte 5))) (when (sb!c::constant-lvar-p count) (sb!c::give-up-ir1-transform)) '(%primitive fast-ash-left-smod30/fixnum=>fixnum integer count)) (in-package "SB!C") (defknown sb!vm::%lea-mod32 (integer integer (member 1 2 4 8) (signed-byte 32)) (unsigned-byte 32) (foldable flushable movable)) (defknown sb!vm::%lea-smod30 (integer integer (member 1 2 4 8) (signed-byte 32)) (signed-byte 30) (foldable flushable movable)) (define-modular-fun-optimizer %lea ((base index scale disp) :untagged nil :width width) (when (and (<= width 32) (constant-lvar-p scale) (constant-lvar-p disp)) (cut-to-width base :untagged width nil) (cut-to-width index :untagged width nil) 'sb!vm::%lea-mod32)) (define-modular-fun-optimizer %lea ((base index scale disp) :tagged t :width width) (when (and (<= width 30) (constant-lvar-p scale) (constant-lvar-p disp)) (cut-to-width base :tagged width t) (cut-to-width index :tagged width t) 'sb!vm::%lea-smod30)) #+sb-xc-host (progn (defun sb!vm::%lea-mod32 (base index scale disp) (ldb (byte 32 0) (%lea base index scale disp))) (defun sb!vm::%lea-smod30 (base index scale disp) (mask-signed-field 30 (%lea base index scale disp)))) #-sb-xc-host (progn (defun sb!vm::%lea-mod32 (base index scale disp) (let ((base (logand base #xffffffff)) (index (logand index #xffffffff))) ca n't use modular version of % , as we only have VOPs for constant SCALE and DISP . (ldb (byte 32 0) (+ base (* index scale) disp)))) (defun sb!vm::%lea-smod30 (base index scale disp) (let ((base (mask-signed-field 30 base)) (index (mask-signed-field 30 index))) ca n't use modular version of % , as we only have VOPs for constant SCALE and DISP . (mask-signed-field 30 (+ base (* index scale) disp))))) (in-package "SB!VM") (define-vop (%lea-mod32/unsigned=>unsigned %lea/unsigned=>unsigned) (:translate %lea-mod32)) (define-vop (%lea-smod30/fixnum=>fixnum %lea/fixnum=>fixnum) (:translate %lea-smod30)) ;;; logical operations (define-modular-fun lognot-mod32 (x) lognot :untagged nil 32) (define-vop (lognot-mod32/word=>unsigned) (:translate lognot-mod32) (:args (x :scs (unsigned-reg signed-reg unsigned-stack signed-stack) :target r :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (location= x r))))) (:arg-types unsigned-num) (:results (r :scs (unsigned-reg) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (sc-is r unsigned-stack) (location= x r))))) (:result-types unsigned-num) (:policy :fast-safe) (:generator 1 (move r x) (inst not r))) (define-source-transform logeqv (&rest args) (if (oddp (length args)) `(logxor ,@args) `(lognot (logxor ,@args)))) (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y)) (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y))) (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y)) (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y))) (define-source-transform lognor (x y) `(lognot (logior ,x ,y))) (define-source-transform lognand (x y) `(lognot (logand ,x ,y))) ;;;; bignum stuff (define-vop (bignum-length get-header-data) (:translate sb!bignum:%bignum-length) (:policy :fast-safe)) (define-vop (bignum-set-length set-header-data) (:translate sb!bignum:%bignum-set-length) (:policy :fast-safe)) (define-full-reffer bignum-ref * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-ref) (define-full-reffer+offset bignum-ref-with-offset * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-ref-with-offset) (define-full-setter bignum-set * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-set) (define-vop (digit-0-or-plus) (:translate sb!bignum:%digit-0-or-plusp) (:policy :fast-safe) (:args (digit :scs (unsigned-reg))) (:arg-types unsigned-num) (:conditional :ns) (:generator 3 (inst or digit digit))) ;;; For add and sub with carry the sc of carry argument is any-reg so that it may be passed as a fixnum or word and thus may be 0 , 1 , or 4 . This is easy to deal with and may save a fixnum - word ;;; conversion. (define-vop (add-w/carry) (:translate sb!bignum:%add-with-carry) (:policy :fast-safe) (:args (a :scs (unsigned-reg) :target result) (b :scs (unsigned-reg unsigned-stack) :to :eval) (c :scs (any-reg) :target temp)) (:arg-types unsigned-num unsigned-num positive-fixnum) (:temporary (:sc any-reg :from (:argument 2) :to :eval) temp) (:results (result :scs (unsigned-reg) :from (:argument 0)) (carry :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 4 (move result a) (move temp c) Set the carry flag to 0 if c=0 else to 1 (inst adc result b) (inst mov carry 0) (inst adc carry carry))) Note : the borrow is 1 for no borrow and 0 for a borrow , the opposite ;;; of the x86 convention. (define-vop (sub-w/borrow) (:translate sb!bignum:%subtract-with-borrow) (:policy :fast-safe) (:args (a :scs (unsigned-reg) :to :eval :target result) (b :scs (unsigned-reg unsigned-stack) :to :result) (c :scs (any-reg control-stack))) (:arg-types unsigned-num unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg) :from :eval) (borrow :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 5 Set the carry flag to 1 if c=0 else to 0 (move result a) (inst sbb result b) (inst mov borrow 1) (inst sbb borrow 0))) (define-vop (bignum-mult-and-add-3-arg) (:translate sb!bignum:%multiply-and-add) (:policy :fast-safe) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack)) (carry-in :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 0) :to (:result 1) :target lo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 1) :to (:result 0) :target hi) edx) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 20 (move eax x) (inst mul eax y) (inst add eax carry-in) (inst adc edx 0) (move hi edx) (move lo eax))) (define-vop (bignum-mult-and-add-4-arg) (:translate sb!bignum:%multiply-and-add) (:policy :fast-safe) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack)) (prev :scs (unsigned-reg unsigned-stack)) (carry-in :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 0) :to (:result 1) :target lo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 1) :to (:result 0) :target hi) edx) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 20 (move eax x) (inst mul eax y) (inst add eax prev) (inst adc edx 0) (inst add eax carry-in) (inst adc edx 0) (move hi edx) (move lo eax))) (define-vop (bignum-mult) (:translate sb!bignum:%multiply) (:policy :fast-safe) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 0) :to (:result 1) :target lo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 1) :to (:result 0) :target hi) edx) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 20 (move eax x) (inst mul eax y) (move hi edx) (move lo eax))) (define-vop (bignum-lognot lognot-mod32/word=>unsigned) (:translate sb!bignum:%lognot)) (define-vop (fixnum-to-digit) (:translate sb!bignum:%fixnum-to-digit) (:policy :fast-safe) (:args (fixnum :scs (any-reg control-stack) :target digit)) (:arg-types tagged-num) (:results (digit :scs (unsigned-reg) :load-if (not (and (sc-is fixnum control-stack) (sc-is digit unsigned-stack) (location= fixnum digit))))) (:result-types unsigned-num) (:generator 1 (move digit fixnum) (inst sar digit n-fixnum-tag-bits))) (define-vop (bignum-floor) (:translate sb!bignum:%floor) (:policy :fast-safe) (:args (div-high :scs (unsigned-reg) :target edx) (div-low :scs (unsigned-reg) :target eax) (divisor :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 1) :to (:result 0) :target quo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 0) :to (:result 1) :target rem) edx) (:results (quo :scs (unsigned-reg)) (rem :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 300 (move edx div-high) (move eax div-low) (inst div eax divisor) (move quo eax) (move rem edx))) (define-vop (signify-digit) (:translate sb!bignum:%fixnum-digit-with-correct-sign) (:policy :fast-safe) (:args (digit :scs (unsigned-reg unsigned-stack) :target res)) (:arg-types unsigned-num) (:results (res :scs (any-reg signed-reg) :load-if (not (and (sc-is digit unsigned-stack) (sc-is res control-stack signed-stack) (location= digit res))))) (:result-types signed-num) (:generator 1 (move res digit) (when (sc-is res any-reg control-stack) (inst shl res n-fixnum-tag-bits)))) (define-vop (digit-ashr) (:translate sb!bignum:%ashr) (:policy :fast-safe) (:args (digit :scs (unsigned-reg unsigned-stack) :target result) (count :scs (unsigned-reg) :target ecx)) (:arg-types unsigned-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is result unsigned-stack) (location= digit result))))) (:result-types unsigned-num) (:generator 2 (move result digit) (move ecx count) (inst sar result :cl))) (define-vop (digit-ashr/c) (:translate sb!bignum:%ashr) (:policy :fast-safe) (:args (digit :scs (unsigned-reg unsigned-stack) :target result)) (:arg-types unsigned-num (:constant (integer 0 31))) (:info count) (:results (result :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is result unsigned-stack) (location= digit result))))) (:result-types unsigned-num) (:generator 1 (move result digit) (inst sar result count))) (define-vop (digit-lshr digit-ashr) (:translate sb!bignum:%digit-logical-shift-right) (:generator 1 (move result digit) (move ecx count) (inst shr result :cl))) (define-vop (digit-ashl digit-ashr) (:translate sb!bignum:%ashl) (:generator 1 (move result digit) (move ecx count) (inst shl result :cl))) ;;;; static functions (define-static-fun two-arg-/ (x y) :translate /) (define-static-fun two-arg-gcd (x y) :translate gcd) (define-static-fun two-arg-lcm (x y) :translate lcm) (define-static-fun two-arg-and (x y) :translate logand) (define-static-fun two-arg-ior (x y) :translate logior) (define-static-fun two-arg-xor (x y) :translate logxor) ;;; Support for the Mersenne Twister, MT19937, random number generator due to and Nishimura . ;;; and , " Mersenne twister : A 623 - dimensionally equidistributed uniform pseudorandom number generator . " , ACM Transactions on Modeling and Computer Simulation , 1997 , to appear . ;;; State : 0 - 1 : Constant matrix A. [ 0 , # x9908b0df ] ( not used here ) 2 : Index ; init . to 1 . 3 - 626 : State . (defknown random-mt19937 ((simple-array (unsigned-byte 32) (*))) (unsigned-byte 32) ()) (define-vop (random-mt19937) (:policy :fast-safe) (:translate random-mt19937) (:args (state :scs (descriptor-reg) :to :result)) (:arg-types simple-array-unsigned-byte-32) (:temporary (:sc unsigned-reg :from (:eval 0) :to :result) k) (:temporary (:sc unsigned-reg :offset eax-offset :from (:eval 0) :to :result) tmp) (:results (y :scs (unsigned-reg) :from (:eval 0))) (:result-types unsigned-num) (:generator 50 (loadw k state (+ 2 vector-data-offset) other-pointer-lowtag) (inst cmp k 624) (inst jmp :ne no-update) The state is passed in EAX . (inst call (make-fixup 'random-mt19937-update :assembly-routine)) Restore k , and set to 0 . (inst xor k k) NO-UPDATE ;; y = ptgfsr[k++]; (inst mov y (make-ea-for-vector-data state :index k :offset 3)) y ^= ( y > > 11 ) ; (inst shr y 11) (inst xor y (make-ea-for-vector-data state :index k :offset 3)) y ^= ( y < < 7 ) & # x9d2c5680 (inst mov tmp y) (inst inc k) (inst shl tmp 7) (storew k state (+ 2 vector-data-offset) other-pointer-lowtag) (inst and tmp #x9d2c5680) (inst xor y tmp) y ^= ( y < < 15 ) & # xefc60000 (inst mov tmp y) (inst shl tmp 15) (inst and tmp #xefc60000) (inst xor y tmp) y ^= ( y > > 18 ) ; (inst mov tmp y) (inst shr tmp 18) (inst xor y tmp))) (in-package "SB!C") (defun mask-result (class width result) (ecase class (:unsigned `(logand ,result ,(1- (ash 1 width)))) (:signed `(mask-signed-field ,width ,result)))) ;;; This is essentially a straight implementation of the algorithm in " Strength Reduction of Multiplications by Integer Constants " , , ACM SIGPLAN Notices , Vol . 30 , No.2 , February 1995 . (defun basic-decompose-multiplication (class width arg num n-bits condensed) (case (aref condensed 0) (0 (let ((tmp (min 3 (aref condensed 1)))) (decf (aref condensed 1) tmp) (mask-result class width `(%lea ,arg ,(decompose-multiplication class width arg (ash (1- num) (- tmp)) (1- n-bits) (subseq condensed 1)) ,(ash 1 tmp) 0)))) ((1 2 3) (let ((r0 (aref condensed 0))) (incf (aref condensed 1) r0) (mask-result class width `(%lea ,(decompose-multiplication class width arg (- num (ash 1 r0)) (1- n-bits) (subseq condensed 1)) ,arg ,(ash 1 r0) 0)))) (t (let ((r0 (aref condensed 0))) (setf (aref condensed 0) 0) (mask-result class width `(ash ,(decompose-multiplication class width arg (ash num (- r0)) n-bits condensed) ,r0)))))) (defun decompose-multiplication (class width arg num n-bits condensed) (cond ((= n-bits 0) 0) ((= num 1) arg) ((= n-bits 1) (mask-result class width `(ash ,arg ,(1- (integer-length num))))) ((let ((max 0) (end 0)) (loop for i from 2 to (length condensed) for j = (reduce #'+ (subseq condensed 0 i)) when (and (> (- (* 2 i) 3 j) max) (< (+ (ash 1 (1+ j)) (ash (ldb (byte (- 32 (1+ j)) (1+ j)) num) (1+ j))) (ash 1 32))) do (setq max (- (* 2 i) 3 j) end i)) (when (> max 0) (let ((j (reduce #'+ (subseq condensed 0 end)))) (let ((n2 (+ (ash 1 (1+ j)) (ash (ldb (byte (- 32 (1+ j)) (1+ j)) num) (1+ j)))) (n1 (1+ (ldb (byte (1+ j) 0) (lognot num))))) (mask-result class width `(- ,(optimize-multiply class width arg n2) ,(optimize-multiply class width arg n1)))))))) ((dolist (i '(9 5 3)) (when (integerp (/ num i)) (when (< (logcount (/ num i)) (logcount num)) (let ((x (gensym))) (return `(let ((,x ,(optimize-multiply class width arg (/ num i)))) ,(mask-result class width `(%lea ,x ,x (1- ,i) 0))))))))) (t (basic-decompose-multiplication class width arg num n-bits condensed)))) (defun optimize-multiply (class width arg x) (let* ((n-bits (logcount x)) (condensed (make-array n-bits))) (let ((count 0) (bit 0)) (dotimes (i 32) (cond ((logbitp i x) (setf (aref condensed bit) count) (setf count 1) (incf bit)) (t (incf count))))) (decompose-multiplication class width arg x n-bits condensed))) (defun *-transformer (class width y) (cond ((= y (ash 1 (integer-length y))) there 's a generic transform for y = 2^k (give-up-ir1-transform)) ((member y '(3 5 9)) we can do these multiplications directly using LEA `(%lea x x ,(1- y) 0)) ((member :pentium4 *backend-subfeatures*) the pentium4 's multiply unit is reportedly very good (give-up-ir1-transform)) ;; FIXME: should make this more fine-grained. If nothing else, there should probably be a cutoff of about 9 instructions on ;; pentium-class machines. (t (optimize-multiply class width 'x y)))) (deftransform * ((x y) ((unsigned-byte 32) (constant-arg (unsigned-byte 32))) (unsigned-byte 32)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :unsigned 32 y))) (deftransform sb!vm::*-mod32 ((x y) ((unsigned-byte 32) (constant-arg (unsigned-byte 32))) (unsigned-byte 32)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :unsigned 32 y))) (deftransform * ((x y) ((signed-byte 30) (constant-arg (unsigned-byte 32))) (signed-byte 30)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :signed 30 y))) (deftransform sb!vm::*-smod30 ((x y) ((signed-byte 30) (constant-arg (unsigned-byte 32))) (signed-byte 30)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :signed 30 y))) FIXME : we should also be able to write an optimizer or two to convert ( + ( * x 2 ) 17 ) , ( - ( * x 9 ) 5 ) to a % LEA .
null
https://raw.githubusercontent.com/gonzojive/sbcl/3210d8ed721541d5bba85cbf51831238990e33f1/src/compiler/x86/arith.lisp
lisp
the VM definition of arithmetic VOPs for the x86 more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. unary operations binary fixnum operations is optimized away as an identity somewhere -C/SIGNED=>UNSIGNED, below, when the higher-level lisp code can't optimize away the non-trivial identity. can use to avoid a register load, otherwise it uses add. Special logand cases: (logand signed unsigned) => unsigned multiplication and division We need different loading characteristics. We need different loading characteristics. We need different loading characteristics. We need different loading characteristics. smaller instruction smaller instruction smaller instruction Shifting be careful The result-type ensures us that this shift will not overflow. be careful The result-type ensures us that this shift will not overflow. The result-type ensures us that this shift will not overflow. FIXME: before making knowledge of this too public, it needs to be fixed so that it's actually _faster_ than the non-CMOV version; at The result-type ensures us that this shift will not overflow. See the comments below for how the algorithm works. The tricks function "pop1". number is the sum of the right digit and twice the left digit. This subtraction will never create a borrow and thus can be made clock cycle. instruction. necessary inbetween since the final sum is at most 32 which fits binary conditional VOPs only for constant folding within the compiler too much work to do the non-constant case (maybe?) FIXME: These could be done more cleanly with SYMBOLICATE. smaller instruction smaller instruction known fixnum. also generic-eql/fixnum VOPs which are the same, but have no restriction on fixnum specific operations from being used on word integers, spuriously consing the argument. smaller instruction (no -C variant as x86 MUL instruction doesn't take an immediate) logical operations bignum stuff For add and sub with carry the sc of carry argument is any-reg so conversion. of the x86 convention. static functions Support for the Mersenne Twister, MT19937, random number generator init . to 1 . y = ptgfsr[k++]; This is essentially a straight implementation of the algorithm in FIXME: should make this more fine-grained. If nothing else, pentium-class machines.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!VM") (define-vop (fast-safe-arith-op) (:policy :fast-safe) (:effects) (:affected)) (define-vop (fixnum-unop fast-safe-arith-op) (:args (x :scs (any-reg) :target res)) (:results (res :scs (any-reg))) (:note "inline fixnum arithmetic") (:arg-types tagged-num) (:result-types tagged-num)) (define-vop (signed-unop fast-safe-arith-op) (:args (x :scs (signed-reg) :target res)) (:results (res :scs (signed-reg))) (:note "inline (signed-byte 32) arithmetic") (:arg-types signed-num) (:result-types signed-num)) (define-vop (fast-negate/fixnum fixnum-unop) (:translate %negate) (:generator 1 (move res x) (inst neg res))) (define-vop (fast-negate/signed signed-unop) (:translate %negate) (:generator 2 (move res x) (inst neg res))) (define-vop (fast-lognot/fixnum fixnum-unop) (:translate lognot) (:generator 1 (move res x) (inst xor res (fixnumize -1)))) (define-vop (fast-lognot/signed signed-unop) (:translate lognot) (:generator 2 (move res x) (inst not res))) Assume that any constant operand is the second arg ... (define-vop (fast-fixnum-binop fast-safe-arith-op) (:args (x :target r :scs (any-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg) :from (:argument 0) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r))))) (:result-types tagged-num) (:note "inline fixnum arithmetic")) (define-vop (fast-unsigned-binop fast-safe-arith-op) (:args (x :target r :scs (unsigned-reg) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:results (r :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r))))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic")) (define-vop (fast-signed-binop fast-safe-arith-op) (:args (x :target r :scs (signed-reg) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (sc-is r signed-stack) (location= x r)))) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg) :from (:argument 0) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (sc-is r signed-stack) (location= x r))))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic")) (define-vop (fast-fixnum-binop-c fast-safe-arith-op) (:args (x :target r :scs (any-reg control-stack))) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:results (r :scs (any-reg) :load-if (not (location= x r)))) (:result-types tagged-num) (:note "inline fixnum arithmetic")) (define-vop (fast-unsigned-binop-c fast-safe-arith-op) (:args (x :target r :scs (unsigned-reg unsigned-stack))) (:info y) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:results (r :scs (unsigned-reg) :load-if (not (location= x r)))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic")) (define-vop (fast-signed-binop-c fast-safe-arith-op) (:args (x :target r :scs (signed-reg signed-stack))) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:results (r :scs (signed-reg) :load-if (not (location= x r)))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic")) (macrolet ((define-binop (translate untagged-penalty op) `(progn (define-vop (,(symbolicate "FAST-" translate "/FIXNUM=>FIXNUM") fast-fixnum-binop) (:translate ,translate) (:generator 2 (move r x) (inst ,op r y))) (define-vop (,(symbolicate 'fast- translate '-c/fixnum=>fixnum) fast-fixnum-binop-c) (:translate ,translate) (:generator 1 (move r x) (inst ,op r (fixnumize y)))) (define-vop (,(symbolicate "FAST-" translate "/SIGNED=>SIGNED") fast-signed-binop) (:translate ,translate) (:generator ,(1+ untagged-penalty) (move r x) (inst ,op r y))) (define-vop (,(symbolicate 'fast- translate '-c/signed=>signed) fast-signed-binop-c) (:translate ,translate) (:generator ,untagged-penalty (move r x) (inst ,op r y))) (define-vop (,(symbolicate "FAST-" translate "/UNSIGNED=>UNSIGNED") fast-unsigned-binop) (:translate ,translate) (:generator ,(1+ untagged-penalty) (move r x) (inst ,op r y))) (define-vop (,(symbolicate 'fast- translate '-c/unsigned=>unsigned) fast-unsigned-binop-c) (:translate ,translate) (:generator ,untagged-penalty (move r x) ,(if (eq translate 'logand) for the -C / UNSIGNED=>UNSIGNED VOP , this case along the lines . However , this VOP is used in `(unless (= y #.(1- (ash 1 n-word-bits))) (inst ,op r y)) `(inst ,op r y))))))) (define-binop - 4 sub) (define-binop logand 2 and) (define-binop logior 2 or) (define-binop logxor 2 xor)) (define-vop (fast-+/fixnum=>fixnum fast-safe-arith-op) (:translate +) (:args (x :scs (any-reg) :target r :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg) :from (:argument 0) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg) (sc-is r control-stack) (location= x r))))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 2 (cond ((and (sc-is x any-reg) (sc-is y any-reg) (sc-is r any-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :index y :scale 1))) (t (move r x) (inst add r y))))) (define-vop (fast-+-c/fixnum=>fixnum fast-safe-arith-op) (:translate +) (:args (x :target r :scs (any-reg control-stack))) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:results (r :scs (any-reg) :load-if (not (location= x r)))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 1 (cond ((and (sc-is x any-reg) (sc-is r any-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :disp (fixnumize y)))) (t (move r x) (inst add r (fixnumize y)))))) (define-vop (fast-+/signed=>signed fast-safe-arith-op) (:translate +) (:args (x :scs (signed-reg) :target r :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (sc-is r signed-stack) (location= x r)))) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg) :from (:argument 0) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg) (location= x r))))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 5 (cond ((and (sc-is x signed-reg) (sc-is y signed-reg) (sc-is r signed-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :index y :scale 1))) (t (move r x) (inst add r y))))) (define-vop (fast-logand/signed-unsigned=>unsigned fast-logand/unsigned=>unsigned) (:args (x :target r :scs (signed-reg) :load-if (not (and (sc-is x signed-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types signed-num unsigned-num)) (define-vop (fast-logand-c/signed-unsigned=>unsigned fast-logand-c/unsigned=>unsigned) (:args (x :target r :scs (signed-reg signed-stack))) (:arg-types signed-num (:constant (unsigned-byte 32)))) (define-vop (fast-logand/unsigned-signed=>unsigned fast-logand/unsigned=>unsigned) (:args (x :target r :scs (unsigned-reg) :load-if (not (and (sc-is x unsigned-stack) (sc-is y signed-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (signed-reg signed-stack))) (:arg-types unsigned-num signed-num)) (define-vop (fast-+-c/signed=>signed fast-safe-arith-op) (:translate +) (:args (x :target r :scs (signed-reg signed-stack))) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:results (r :scs (signed-reg) :load-if (not (location= x r)))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 4 (cond ((and (sc-is x signed-reg) (sc-is r signed-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :disp y))) (t (move r x) (if (= y 1) (inst inc r) (inst add r y)))))) (define-vop (fast-+/unsigned=>unsigned fast-safe-arith-op) (:translate +) (:args (x :scs (unsigned-reg) :target r :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:results (r :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg) (sc-is r unsigned-stack) (location= x r))))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:generator 5 (cond ((and (sc-is x unsigned-reg) (sc-is y unsigned-reg) (sc-is r unsigned-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :index y :scale 1))) (t (move r x) (inst add r y))))) (define-vop (fast-+-c/unsigned=>unsigned fast-safe-arith-op) (:translate +) (:args (x :target r :scs (unsigned-reg unsigned-stack))) (:info y) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:results (r :scs (unsigned-reg) :load-if (not (location= x r)))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:generator 4 (cond ((and (sc-is x unsigned-reg) (sc-is r unsigned-reg) (not (location= x r))) (inst lea r (make-ea :dword :base x :disp y))) (t (move r x) (if (= y 1) (inst inc r) (inst add r y)))))) (define-vop (fast-*/fixnum=>fixnum fast-safe-arith-op) (:translate *) (:args (x :scs (any-reg) :target r) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg) :from (:argument 0))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 4 (move r x) (inst sar r n-fixnum-tag-bits) (inst imul r y))) (define-vop (fast-*-c/fixnum=>fixnum fast-safe-arith-op) (:translate *) (:args (x :scs (any-reg control-stack))) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:results (r :scs (any-reg))) (:result-types tagged-num) (:note "inline fixnum arithmetic") (:generator 3 (inst imul r x y))) (define-vop (fast-*/signed=>signed fast-safe-arith-op) (:translate *) (:args (x :scs (signed-reg) :target r) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg) :from (:argument 0))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 5 (move r x) (inst imul r y))) (define-vop (fast-*-c/signed=>signed fast-safe-arith-op) (:translate *) (:args (x :scs (signed-reg signed-stack))) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:results (r :scs (signed-reg))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic") (:generator 4 (inst imul r x y))) (define-vop (fast-*/unsigned=>unsigned fast-safe-arith-op) (:translate *) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :target r :from (:argument 0) :to :result) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from :eval :to :result) edx) (:ignore edx) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 6 (move eax x) (inst mul eax y) (move r eax))) (define-vop (fast-truncate/fixnum=>fixnum fast-safe-arith-op) (:translate truncate) (:args (x :scs (any-reg) :target eax) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:temporary (:sc signed-reg :offset eax-offset :target quo :from (:argument 0) :to (:result 0)) eax) (:temporary (:sc unsigned-reg :offset edx-offset :target rem :from (:argument 0) :to (:result 1)) edx) (:results (quo :scs (any-reg)) (rem :scs (any-reg))) (:result-types tagged-num tagged-num) (:note "inline fixnum arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 31 (let ((zero (generate-error-code vop 'division-by-zero-error x y))) (if (sc-is y any-reg) (inst cmp y 0)) (inst jmp :eq zero)) (move eax x) (inst cdq) (inst idiv eax y) (if (location= quo eax) (inst shl eax n-fixnum-tag-bits) (inst lea quo (make-ea :dword :index eax :scale (ash 1 n-fixnum-tag-bits)))) (move rem edx))) (define-vop (fast-truncate-c/fixnum=>fixnum fast-safe-arith-op) (:translate truncate) (:args (x :scs (any-reg) :target eax)) (:info y) (:arg-types tagged-num (:constant (signed-byte 30))) (:temporary (:sc signed-reg :offset eax-offset :target quo :from :argument :to (:result 0)) eax) (:temporary (:sc any-reg :offset edx-offset :target rem :from :eval :to (:result 1)) edx) (:temporary (:sc any-reg :from :eval :to :result) y-arg) (:results (quo :scs (any-reg)) (rem :scs (any-reg))) (:result-types tagged-num tagged-num) (:note "inline fixnum arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 30 (move eax x) (inst cdq) (inst mov y-arg (fixnumize y)) (inst idiv eax y-arg) (if (location= quo eax) (inst shl eax n-fixnum-tag-bits) (inst lea quo (make-ea :dword :index eax :scale (ash 1 n-fixnum-tag-bits)))) (move rem edx))) (define-vop (fast-truncate/unsigned=>unsigned fast-safe-arith-op) (:translate truncate) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg signed-stack))) (:arg-types unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :target quo :from (:argument 0) :to (:result 0)) eax) (:temporary (:sc unsigned-reg :offset edx-offset :target rem :from (:argument 0) :to (:result 1)) edx) (:results (quo :scs (unsigned-reg)) (rem :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 33 (let ((zero (generate-error-code vop 'division-by-zero-error x y))) (if (sc-is y unsigned-reg) (inst cmp y 0)) (inst jmp :eq zero)) (move eax x) (inst xor edx edx) (inst div eax y) (move quo eax) (move rem edx))) (define-vop (fast-truncate-c/unsigned=>unsigned fast-safe-arith-op) (:translate truncate) (:args (x :scs (unsigned-reg) :target eax)) (:info y) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:temporary (:sc unsigned-reg :offset eax-offset :target quo :from :argument :to (:result 0)) eax) (:temporary (:sc unsigned-reg :offset edx-offset :target rem :from :eval :to (:result 1)) edx) (:temporary (:sc unsigned-reg :from :eval :to :result) y-arg) (:results (quo :scs (unsigned-reg)) (rem :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 32 (move eax x) (inst xor edx edx) (inst mov y-arg y) (inst div eax y-arg) (move quo eax) (move rem edx))) (define-vop (fast-truncate/signed=>signed fast-safe-arith-op) (:translate truncate) (:args (x :scs (signed-reg) :target eax) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:temporary (:sc signed-reg :offset eax-offset :target quo :from (:argument 0) :to (:result 0)) eax) (:temporary (:sc signed-reg :offset edx-offset :target rem :from (:argument 0) :to (:result 1)) edx) (:results (quo :scs (signed-reg)) (rem :scs (signed-reg))) (:result-types signed-num signed-num) (:note "inline (signed-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 33 (let ((zero (generate-error-code vop 'division-by-zero-error x y))) (if (sc-is y signed-reg) (inst cmp y 0)) (inst jmp :eq zero)) (move eax x) (inst cdq) (inst idiv eax y) (move quo eax) (move rem edx))) (define-vop (fast-truncate-c/signed=>signed fast-safe-arith-op) (:translate truncate) (:args (x :scs (signed-reg) :target eax)) (:info y) (:arg-types signed-num (:constant (signed-byte 32))) (:temporary (:sc signed-reg :offset eax-offset :target quo :from :argument :to (:result 0)) eax) (:temporary (:sc signed-reg :offset edx-offset :target rem :from :eval :to (:result 1)) edx) (:temporary (:sc signed-reg :from :eval :to :result) y-arg) (:results (quo :scs (signed-reg)) (rem :scs (signed-reg))) (:result-types signed-num signed-num) (:note "inline (signed-byte 32) arithmetic") (:vop-var vop) (:save-p :compute-only) (:generator 32 (move eax x) (inst cdq) (inst mov y-arg y) (inst idiv eax y-arg) (move quo eax) (move rem edx))) (define-vop (fast-ash-c/fixnum=>fixnum) (:translate ash) (:policy :fast-safe) (:args (number :scs (any-reg) :target result :load-if (not (and (sc-is number any-reg control-stack) (sc-is result any-reg control-stack) (location= number result))))) (:info amount) (:arg-types tagged-num (:constant integer)) (:results (result :scs (any-reg) :load-if (not (and (sc-is number control-stack) (sc-is result control-stack) (location= number result))))) (:result-types tagged-num) (:note "inline ASH") (:generator 2 (cond ((and (= amount 1) (not (location= number result))) (inst lea result (make-ea :dword :base number :index number))) ((and (= amount 2) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 4))) ((and (= amount 3) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 8))) (t (move result number) (cond ((< -32 amount 32) this code is used both in ASH and ASH - SMOD30 , so (if (plusp amount) (inst shl result amount) (progn (inst sar result (- amount)) (inst and result (lognot fixnum-tag-mask))))) ((plusp amount) (if (sc-is result any-reg) (inst xor result result) (inst mov result 0))) (t (inst sar result 31) (inst and result (lognot fixnum-tag-mask)))))))) (define-vop (fast-ash-left/fixnum=>fixnum) (:translate ash) (:args (number :scs (any-reg) :target result :load-if (not (and (sc-is number control-stack) (sc-is result control-stack) (location= number result)))) (amount :scs (unsigned-reg) :target ecx)) (:arg-types tagged-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (any-reg) :from (:argument 0) :load-if (not (and (sc-is number control-stack) (sc-is result control-stack) (location= number result))))) (:result-types tagged-num) (:policy :fast-safe) (:note "inline ASH") (:generator 3 (move result number) (move ecx amount) (inst shl result :cl))) (define-vop (fast-ash-c/signed=>signed) (:translate ash) (:policy :fast-safe) (:args (number :scs (signed-reg) :target result :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result))))) (:info amount) (:arg-types signed-num (:constant integer)) (:results (result :scs (signed-reg) :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result))))) (:result-types signed-num) (:note "inline ASH") (:generator 3 (cond ((and (= amount 1) (not (location= number result))) (inst lea result (make-ea :dword :base number :index number))) ((and (= amount 2) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 4))) ((and (= amount 3) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 8))) (t (move result number) (cond ((plusp amount) (inst shl result amount)) (t (inst sar result (min 31 (- amount))))))))) (define-vop (fast-ash-c/unsigned=>unsigned) (:translate ash) (:policy :fast-safe) (:args (number :scs (unsigned-reg) :target result :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result))))) (:info amount) (:arg-types unsigned-num (:constant integer)) (:results (result :scs (unsigned-reg) :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result))))) (:result-types unsigned-num) (:note "inline ASH") (:generator 3 (cond ((and (= amount 1) (not (location= number result))) (inst lea result (make-ea :dword :base number :index number))) ((and (= amount 2) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 4))) ((and (= amount 3) (not (location= number result))) (inst lea result (make-ea :dword :index number :scale 8))) (t (move result number) (cond ((< -32 amount 32) this code is used both in ASH and ASH - MOD32 , so (if (plusp amount) (inst shl result amount) (inst shr result (- amount)))) (t (if (sc-is result unsigned-reg) (inst xor result result) (inst mov result 0)))))))) (define-vop (fast-ash-left/signed=>signed) (:translate ash) (:args (number :scs (signed-reg) :target result :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result)))) (amount :scs (unsigned-reg) :target ecx)) (:arg-types signed-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (signed-reg) :from (:argument 0) :load-if (not (and (sc-is number signed-stack) (sc-is result signed-stack) (location= number result))))) (:result-types signed-num) (:policy :fast-safe) (:note "inline ASH") (:generator 4 (move result number) (move ecx amount) (inst shl result :cl))) (define-vop (fast-ash-left/unsigned=>unsigned) (:translate ash) (:args (number :scs (unsigned-reg) :target result :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result)))) (amount :scs (unsigned-reg) :target ecx)) (:arg-types unsigned-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is number unsigned-stack) (sc-is result unsigned-stack) (location= number result))))) (:result-types unsigned-num) (:policy :fast-safe) (:note "inline ASH") (:generator 4 (move result number) (move ecx amount) (inst shl result :cl))) (define-vop (fast-ash/signed=>signed) (:translate ash) (:policy :fast-safe) (:args (number :scs (signed-reg) :target result) (amount :scs (signed-reg) :target ecx)) (:arg-types signed-num signed-num) (:results (result :scs (signed-reg) :from (:argument 0))) (:result-types signed-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:note "inline ASH") (:generator 5 (move result number) (move ecx amount) (inst or ecx ecx) (inst jmp :ns positive) (inst neg ecx) (inst cmp ecx 31) (inst jmp :be okay) (inst mov ecx 31) OKAY (inst sar result :cl) (inst jmp done) POSITIVE (inst shl result :cl) DONE)) (define-vop (fast-ash/unsigned=>unsigned) (:translate ash) (:policy :fast-safe) (:args (number :scs (unsigned-reg) :target result) (amount :scs (signed-reg) :target ecx)) (:arg-types unsigned-num signed-num) (:results (result :scs (unsigned-reg) :from (:argument 0))) (:result-types unsigned-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:note "inline ASH") (:generator 5 (move result number) (move ecx amount) (inst or ecx ecx) (inst jmp :ns positive) (inst neg ecx) (inst cmp ecx 31) (inst jmp :be okay) (inst xor result result) (inst jmp done) OKAY (inst shr result :cl) (inst jmp done) POSITIVE (inst shl result :cl) DONE)) (in-package "SB!C") (defknown %lea (integer integer (member 1 2 4 8) (signed-byte 32)) integer (foldable flushable movable)) (defoptimizer (%lea derive-type) ((base index scale disp)) (when (and (constant-lvar-p scale) (constant-lvar-p disp)) (let ((scale (lvar-value scale)) (disp (lvar-value disp)) (base-type (lvar-type base)) (index-type (lvar-type index))) (when (and (numeric-type-p base-type) (numeric-type-p index-type)) (let ((base-lo (numeric-type-low base-type)) (base-hi (numeric-type-high base-type)) (index-lo (numeric-type-low index-type)) (index-hi (numeric-type-high index-type))) (make-numeric-type :class 'integer :complexp :real :low (when (and base-lo index-lo) (+ base-lo (* index-lo scale) disp)) :high (when (and base-hi index-hi) (+ base-hi (* index-hi scale) disp)))))))) (defun %lea (base index scale disp) (+ base (* index scale) disp)) (in-package "SB!VM") (define-vop (%lea/unsigned=>unsigned) (:translate %lea) (:policy :fast-safe) (:args (base :scs (unsigned-reg)) (index :scs (unsigned-reg))) (:info scale disp) (:arg-types unsigned-num unsigned-num (:constant (member 1 2 4 8)) (:constant (signed-byte 32))) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 5 (inst lea r (make-ea :dword :base base :index index :scale scale :disp disp)))) (define-vop (%lea/signed=>signed) (:translate %lea) (:policy :fast-safe) (:args (base :scs (signed-reg)) (index :scs (signed-reg))) (:info scale disp) (:arg-types signed-num signed-num (:constant (member 1 2 4 8)) (:constant (signed-byte 32))) (:results (r :scs (signed-reg))) (:result-types signed-num) (:generator 4 (inst lea r (make-ea :dword :base base :index index :scale scale :disp disp)))) (define-vop (%lea/fixnum=>fixnum) (:translate %lea) (:policy :fast-safe) (:args (base :scs (any-reg)) (index :scs (any-reg))) (:info scale disp) (:arg-types tagged-num tagged-num (:constant (member 1 2 4 8)) (:constant (signed-byte 32))) (:results (r :scs (any-reg))) (:result-types tagged-num) (:generator 3 (inst lea r (make-ea :dword :base base :index index :scale scale :disp disp)))) least on my Celeron - XXX laptop , this version is marginally slower than the above version with branches . -- CSR , 2003 - 09 - 04 (define-vop (fast-cmov-ash/unsigned=>unsigned) (:translate ash) (:policy :fast-safe) (:args (number :scs (unsigned-reg) :target result) (amount :scs (signed-reg) :target ecx)) (:arg-types unsigned-num signed-num) (:results (result :scs (unsigned-reg) :from (:argument 0))) (:result-types unsigned-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:temporary (:sc any-reg :from (:eval 0) :to (:eval 1)) zero) (:note "inline ASH") (:guard (member :cmov *backend-subfeatures*)) (:generator 4 (move result number) (move ecx amount) (inst or ecx ecx) (inst jmp :ns positive) (inst neg ecx) (inst xor zero zero) (inst shr result :cl) (inst cmp ecx 31) (inst cmov :nbe result zero) (inst jmp done) POSITIVE (inst shl result :cl) DONE)) (define-vop (signed-byte-32-len) (:translate integer-length) (:note "inline (signed-byte 32) integer-length") (:policy :fast-safe) (:args (arg :scs (signed-reg) :target res)) (:arg-types signed-num) (:results (res :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 28 (move res arg) (if (sc-is res unsigned-reg) (inst test res res) (inst cmp res 0)) (inst jmp :ge POS) (inst not res) POS (inst bsr res res) (inst jmp :z zero) (inst inc res) (inst jmp done) ZERO (inst xor res res) DONE)) (define-vop (unsigned-byte-32-len) (:translate integer-length) (:note "inline (unsigned-byte 32) integer-length") (:policy :fast-safe) (:args (arg :scs (unsigned-reg))) (:arg-types unsigned-num) (:results (res :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 26 (inst bsr res arg) (inst jmp :z zero) (inst inc res) (inst jmp done) ZERO (inst xor res res) DONE)) (define-vop (unsigned-byte-32-count) (:translate logcount) (:note "inline (unsigned-byte 32) logcount") (:policy :fast-safe) (:args (arg :scs (unsigned-reg) :target result)) (:arg-types unsigned-num) (:results (result :scs (unsigned-reg))) (:result-types positive-fixnum) (:temporary (:sc unsigned-reg) temp) (:generator 14 used can be found for example in AMD 's software optimization guide or at " " in the Calculate 2 - bit sums . Note that the value of a two - digit binary Thus we can calculate the sum of the two digits by shifting the left digit to the right position and doing a two - bit subtraction . on all 16 2 - digit numbers at once . (move result arg) (move temp arg) (inst shr result 1) (inst and result #x55555555) (inst sub temp result) Calculate 4 - bit sums by straightforward shift , mask and add . Note that we shift the source operand of the MOV and not its destination so that the SHR and the MOV can execute in the same (inst mov result temp) (inst shr temp 2) (inst and result #x33333333) (inst and temp #x33333333) (inst add result temp) Calculate 8 - bit sums . Since each sum is at most 8 , which fits into 4 bits , we can apply the mask after the addition , saving one (inst mov temp result) (inst shr result 4) (inst add result temp) (inst and result #x0f0f0f0f) Calculate the two 16 - bit sums and the 32 - bit sum . No masking is into 6 bits . (inst mov temp result) (inst shr result 8) (inst add result temp) (inst mov temp result) (inst shr result 16) (inst add result temp) (inst and result #xff))) (define-vop (fast-conditional) (:conditional :e) (:effects) (:affected) (:policy :fast-safe)) (define-vop (fast-conditional/fixnum fast-conditional) (:args (x :scs (any-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison")) (define-vop (fast-conditional-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg control-stack))) (:arg-types tagged-num (:constant (signed-byte 30))) (:info y)) (define-vop (fast-conditional/signed fast-conditional) (:args (x :scs (signed-reg) :load-if (not (and (sc-is x signed-stack) (sc-is y signed-reg)))) (y :scs (signed-reg signed-stack))) (:arg-types signed-num signed-num) (:note "inline (signed-byte 32) comparison")) (define-vop (fast-conditional-c/signed fast-conditional/signed) (:args (x :scs (signed-reg signed-stack))) (:arg-types signed-num (:constant (signed-byte 32))) (:info y)) (define-vop (fast-conditional/unsigned fast-conditional) (:args (x :scs (unsigned-reg) :load-if (not (and (sc-is x unsigned-stack) (sc-is y unsigned-reg)))) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) comparison")) (define-vop (fast-conditional-c/unsigned fast-conditional/unsigned) (:args (x :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num (:constant (unsigned-byte 32))) (:info y)) (macrolet ((define-logtest-vops () `(progn ,@(loop for suffix in '(/fixnum -c/fixnum /signed -c/signed /unsigned -c/unsigned) for cost in '(4 3 6 5 6 5) collect `(define-vop (,(symbolicate "FAST-LOGTEST" suffix) ,(symbolicate "FAST-CONDITIONAL" suffix)) (:translate logtest) (:conditional :ne) (:generator ,cost (emit-optimized-test-inst x ,(if (eq suffix '-c/fixnum) '(fixnumize y) 'y)))))))) (define-logtest-vops)) (defknown %logbitp (integer unsigned-byte) boolean (movable foldable flushable always-translatable)) (defun %logbitp (integer index) (logbitp index integer)) (define-vop (fast-logbitp-c/fixnum fast-conditional-c/fixnum) (:translate %logbitp) (:conditional :c) (:arg-types tagged-num (:constant (integer 0 29))) (:generator 4 (inst bt x (+ y n-fixnum-tag-bits)))) (define-vop (fast-logbitp/signed fast-conditional/signed) (:args (x :scs (signed-reg signed-stack)) (y :scs (signed-reg))) (:translate %logbitp) (:conditional :c) (:generator 6 (inst bt x y))) (define-vop (fast-logbitp-c/signed fast-conditional-c/signed) (:translate %logbitp) (:conditional :c) (:arg-types signed-num (:constant (integer 0 31))) (:generator 5 (inst bt x y))) (define-vop (fast-logbitp/unsigned fast-conditional/unsigned) (:args (x :scs (unsigned-reg unsigned-stack)) (y :scs (unsigned-reg))) (:translate %logbitp) (:conditional :c) (:generator 6 (inst bt x y))) (define-vop (fast-logbitp-c/unsigned fast-conditional-c/unsigned) (:translate %logbitp) (:conditional :c) (:arg-types unsigned-num (:constant (integer 0 31))) (:generator 5 (inst bt x y))) (macrolet ((define-conditional-vop (tran cond unsigned) `(progn ,@(mapcar (lambda (suffix cost signed) ,(intern (format nil "~:@(FAST-IF-~A~A~)" tran suffix)) ,(intern (format nil "~:@(FAST-CONDITIONAL~A~)" suffix))) (:translate ,tran) (:conditional ,(if signed cond unsigned)) (:generator ,cost (inst cmp x ,(if (eq suffix '-c/fixnum) '(fixnumize y) 'y))))) '(/fixnum -c/fixnum /signed -c/signed /unsigned -c/unsigned) '(4 3 6 5 6 5) '(t t t t nil nil))))) (define-conditional-vop < :l :b) (define-conditional-vop > :g :a)) (define-vop (fast-if-eql/signed fast-conditional/signed) (:translate eql) (:generator 6 (inst cmp x y))) (define-vop (fast-if-eql-c/signed fast-conditional-c/signed) (:translate eql) (:generator 5 (cond ((and (sc-is x signed-reg) (zerop y)) (t (inst cmp x y))))) (define-vop (fast-if-eql/unsigned fast-conditional/unsigned) (:translate eql) (:generator 6 (inst cmp x y))) (define-vop (fast-if-eql-c/unsigned fast-conditional-c/unsigned) (:translate eql) (:generator 5 (cond ((and (sc-is x unsigned-reg) (zerop y)) (t (inst cmp x y))))) EQL / FIXNUM is funny because the first arg can be of any type , not just a These versions specify a fixnum restriction on their first arg . We have the first arg and a higher cost . The reason for doing this is to prevent (define-vop (fast-eql/fixnum fast-conditional) (:args (x :scs (any-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg)))) (y :scs (any-reg control-stack))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison") (:translate eql) (:generator 4 (inst cmp x y))) (define-vop (generic-eql/fixnum fast-eql/fixnum) (:args (x :scs (any-reg descriptor-reg) :load-if (not (and (sc-is x control-stack) (sc-is y any-reg)))) (y :scs (any-reg control-stack))) (:arg-types * tagged-num) (:variant-cost 7)) (define-vop (fast-eql-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg control-stack))) (:arg-types tagged-num (:constant (signed-byte 30))) (:info y) (:translate eql) (:generator 2 (cond ((and (sc-is x any-reg) (zerop y)) (t (inst cmp x (fixnumize y)))))) (define-vop (generic-eql-c/fixnum fast-eql-c/fixnum) (:args (x :scs (any-reg descriptor-reg control-stack))) (:arg-types * (:constant (signed-byte 30))) (:variant-cost 6)) 32 - bit logical operations Only the lower 5 bits of the shift amount are significant . (define-vop (shift-towards-someplace) (:policy :fast-safe) (:args (num :scs (unsigned-reg) :target r) (amount :scs (signed-reg) :target ecx)) (:arg-types unsigned-num tagged-num) (:temporary (:sc signed-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (r :scs (unsigned-reg) :from (:argument 0))) (:result-types unsigned-num)) (define-vop (shift-towards-start shift-towards-someplace) (:translate shift-towards-start) (:note "SHIFT-TOWARDS-START") (:generator 1 (move r num) (move ecx amount) (inst shr r :cl))) (define-vop (shift-towards-end shift-towards-someplace) (:translate shift-towards-end) (:note "SHIFT-TOWARDS-END") (:generator 1 (move r num) (move ecx amount) (inst shl r :cl))) Modular functions (defmacro define-mod-binop ((name prototype) function) `(define-vop (,name ,prototype) (:args (x :target r :scs (unsigned-reg signed-reg) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is y unsigned-reg) (sc-is y signed-reg)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (location= x r)))) (y :scs (unsigned-reg signed-reg unsigned-stack signed-stack))) (:arg-types untagged-num untagged-num) (:results (r :scs (unsigned-reg signed-reg) :from (:argument 0) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is y unsigned-reg) (sc-is y unsigned-reg)) (or (sc-is r unsigned-stack) (sc-is r unsigned-stack)) (location= x r))))) (:result-types unsigned-num) (:translate ,function))) (defmacro define-mod-binop-c ((name prototype) function) `(define-vop (,name ,prototype) (:args (x :target r :scs (unsigned-reg signed-reg) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (location= x r))))) (:info y) (:arg-types untagged-num (:constant (or (unsigned-byte 32) (signed-byte 32)))) (:results (r :scs (unsigned-reg signed-reg) :from (:argument 0) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r unsigned-stack)) (location= x r))))) (:result-types unsigned-num) (:translate ,function))) (macrolet ((def (name -c-p) (let ((fun32 (intern (format nil "~S-MOD32" name))) (vopu (intern (format nil "FAST-~S/UNSIGNED=>UNSIGNED" name))) (vopcu (intern (format nil "FAST-~S-C/UNSIGNED=>UNSIGNED" name))) (vopf (intern (format nil "FAST-~S/FIXNUM=>FIXNUM" name))) (vopcf (intern (format nil "FAST-~S-C/FIXNUM=>FIXNUM" name))) (vop32u (intern (format nil "FAST-~S-MOD32/WORD=>UNSIGNED" name))) (vop32f (intern (format nil "FAST-~S-MOD32/FIXNUM=>FIXNUM" name))) (vop32cu (intern (format nil "FAST-~S-MOD32-C/WORD=>UNSIGNED" name))) (vop32cf (intern (format nil "FAST-~S-MOD32-C/FIXNUM=>FIXNUM" name))) (sfun30 (intern (format nil "~S-SMOD30" name))) (svop30f (intern (format nil "FAST-~S-SMOD30/FIXNUM=>FIXNUM" name))) (svop30cf (intern (format nil "FAST-~S-SMOD30-C/FIXNUM=>FIXNUM" name)))) `(progn (define-modular-fun ,fun32 (x y) ,name :untagged nil 32) (define-modular-fun ,sfun30 (x y) ,name :tagged t 30) (define-mod-binop (,vop32u ,vopu) ,fun32) (define-vop (,vop32f ,vopf) (:translate ,fun32)) (define-vop (,svop30f ,vopf) (:translate ,sfun30)) ,@(when -c-p `((define-mod-binop-c (,vop32cu ,vopcu) ,fun32) (define-vop (,svop30cf ,vopcf) (:translate ,sfun30)))))))) (def + t) (def - t) (def * nil)) (define-vop (fast-ash-left-mod32-c/unsigned=>unsigned fast-ash-c/unsigned=>unsigned) (:translate ash-left-mod32)) (define-vop (fast-ash-left-mod32/unsigned=>unsigned fast-ash-left/unsigned=>unsigned)) (deftransform ash-left-mod32 ((integer count) ((unsigned-byte 32) (unsigned-byte 5))) (when (sb!c::constant-lvar-p count) (sb!c::give-up-ir1-transform)) '(%primitive fast-ash-left-mod32/unsigned=>unsigned integer count)) (define-vop (fast-ash-left-smod30-c/fixnum=>fixnum fast-ash-c/fixnum=>fixnum) (:translate ash-left-smod30)) (define-vop (fast-ash-left-smod30/fixnum=>fixnum fast-ash-left/fixnum=>fixnum)) (deftransform ash-left-smod30 ((integer count) ((signed-byte 30) (unsigned-byte 5))) (when (sb!c::constant-lvar-p count) (sb!c::give-up-ir1-transform)) '(%primitive fast-ash-left-smod30/fixnum=>fixnum integer count)) (in-package "SB!C") (defknown sb!vm::%lea-mod32 (integer integer (member 1 2 4 8) (signed-byte 32)) (unsigned-byte 32) (foldable flushable movable)) (defknown sb!vm::%lea-smod30 (integer integer (member 1 2 4 8) (signed-byte 32)) (signed-byte 30) (foldable flushable movable)) (define-modular-fun-optimizer %lea ((base index scale disp) :untagged nil :width width) (when (and (<= width 32) (constant-lvar-p scale) (constant-lvar-p disp)) (cut-to-width base :untagged width nil) (cut-to-width index :untagged width nil) 'sb!vm::%lea-mod32)) (define-modular-fun-optimizer %lea ((base index scale disp) :tagged t :width width) (when (and (<= width 30) (constant-lvar-p scale) (constant-lvar-p disp)) (cut-to-width base :tagged width t) (cut-to-width index :tagged width t) 'sb!vm::%lea-smod30)) #+sb-xc-host (progn (defun sb!vm::%lea-mod32 (base index scale disp) (ldb (byte 32 0) (%lea base index scale disp))) (defun sb!vm::%lea-smod30 (base index scale disp) (mask-signed-field 30 (%lea base index scale disp)))) #-sb-xc-host (progn (defun sb!vm::%lea-mod32 (base index scale disp) (let ((base (logand base #xffffffff)) (index (logand index #xffffffff))) ca n't use modular version of % , as we only have VOPs for constant SCALE and DISP . (ldb (byte 32 0) (+ base (* index scale) disp)))) (defun sb!vm::%lea-smod30 (base index scale disp) (let ((base (mask-signed-field 30 base)) (index (mask-signed-field 30 index))) ca n't use modular version of % , as we only have VOPs for constant SCALE and DISP . (mask-signed-field 30 (+ base (* index scale) disp))))) (in-package "SB!VM") (define-vop (%lea-mod32/unsigned=>unsigned %lea/unsigned=>unsigned) (:translate %lea-mod32)) (define-vop (%lea-smod30/fixnum=>fixnum %lea/fixnum=>fixnum) (:translate %lea-smod30)) (define-modular-fun lognot-mod32 (x) lognot :untagged nil 32) (define-vop (lognot-mod32/word=>unsigned) (:translate lognot-mod32) (:args (x :scs (unsigned-reg signed-reg unsigned-stack signed-stack) :target r :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (location= x r))))) (:arg-types unsigned-num) (:results (r :scs (unsigned-reg) :load-if (not (and (or (sc-is x unsigned-stack) (sc-is x signed-stack)) (or (sc-is r unsigned-stack) (sc-is r signed-stack)) (sc-is r unsigned-stack) (location= x r))))) (:result-types unsigned-num) (:policy :fast-safe) (:generator 1 (move r x) (inst not r))) (define-source-transform logeqv (&rest args) (if (oddp (length args)) `(logxor ,@args) `(lognot (logxor ,@args)))) (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y)) (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y))) (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y)) (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y))) (define-source-transform lognor (x y) `(lognot (logior ,x ,y))) (define-source-transform lognand (x y) `(lognot (logand ,x ,y))) (define-vop (bignum-length get-header-data) (:translate sb!bignum:%bignum-length) (:policy :fast-safe)) (define-vop (bignum-set-length set-header-data) (:translate sb!bignum:%bignum-set-length) (:policy :fast-safe)) (define-full-reffer bignum-ref * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-ref) (define-full-reffer+offset bignum-ref-with-offset * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-ref-with-offset) (define-full-setter bignum-set * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-set) (define-vop (digit-0-or-plus) (:translate sb!bignum:%digit-0-or-plusp) (:policy :fast-safe) (:args (digit :scs (unsigned-reg))) (:arg-types unsigned-num) (:conditional :ns) (:generator 3 (inst or digit digit))) that it may be passed as a fixnum or word and thus may be 0 , 1 , or 4 . This is easy to deal with and may save a fixnum - word (define-vop (add-w/carry) (:translate sb!bignum:%add-with-carry) (:policy :fast-safe) (:args (a :scs (unsigned-reg) :target result) (b :scs (unsigned-reg unsigned-stack) :to :eval) (c :scs (any-reg) :target temp)) (:arg-types unsigned-num unsigned-num positive-fixnum) (:temporary (:sc any-reg :from (:argument 2) :to :eval) temp) (:results (result :scs (unsigned-reg) :from (:argument 0)) (carry :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 4 (move result a) (move temp c) Set the carry flag to 0 if c=0 else to 1 (inst adc result b) (inst mov carry 0) (inst adc carry carry))) Note : the borrow is 1 for no borrow and 0 for a borrow , the opposite (define-vop (sub-w/borrow) (:translate sb!bignum:%subtract-with-borrow) (:policy :fast-safe) (:args (a :scs (unsigned-reg) :to :eval :target result) (b :scs (unsigned-reg unsigned-stack) :to :result) (c :scs (any-reg control-stack))) (:arg-types unsigned-num unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg) :from :eval) (borrow :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 5 Set the carry flag to 1 if c=0 else to 0 (move result a) (inst sbb result b) (inst mov borrow 1) (inst sbb borrow 0))) (define-vop (bignum-mult-and-add-3-arg) (:translate sb!bignum:%multiply-and-add) (:policy :fast-safe) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack)) (carry-in :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 0) :to (:result 1) :target lo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 1) :to (:result 0) :target hi) edx) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 20 (move eax x) (inst mul eax y) (inst add eax carry-in) (inst adc edx 0) (move hi edx) (move lo eax))) (define-vop (bignum-mult-and-add-4-arg) (:translate sb!bignum:%multiply-and-add) (:policy :fast-safe) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack)) (prev :scs (unsigned-reg unsigned-stack)) (carry-in :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 0) :to (:result 1) :target lo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 1) :to (:result 0) :target hi) edx) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 20 (move eax x) (inst mul eax y) (inst add eax prev) (inst adc edx 0) (inst add eax carry-in) (inst adc edx 0) (move hi edx) (move lo eax))) (define-vop (bignum-mult) (:translate sb!bignum:%multiply) (:policy :fast-safe) (:args (x :scs (unsigned-reg) :target eax) (y :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 0) :to (:result 1) :target lo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 1) :to (:result 0) :target hi) edx) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 20 (move eax x) (inst mul eax y) (move hi edx) (move lo eax))) (define-vop (bignum-lognot lognot-mod32/word=>unsigned) (:translate sb!bignum:%lognot)) (define-vop (fixnum-to-digit) (:translate sb!bignum:%fixnum-to-digit) (:policy :fast-safe) (:args (fixnum :scs (any-reg control-stack) :target digit)) (:arg-types tagged-num) (:results (digit :scs (unsigned-reg) :load-if (not (and (sc-is fixnum control-stack) (sc-is digit unsigned-stack) (location= fixnum digit))))) (:result-types unsigned-num) (:generator 1 (move digit fixnum) (inst sar digit n-fixnum-tag-bits))) (define-vop (bignum-floor) (:translate sb!bignum:%floor) (:policy :fast-safe) (:args (div-high :scs (unsigned-reg) :target edx) (div-low :scs (unsigned-reg) :target eax) (divisor :scs (unsigned-reg unsigned-stack))) (:arg-types unsigned-num unsigned-num unsigned-num) (:temporary (:sc unsigned-reg :offset eax-offset :from (:argument 1) :to (:result 0) :target quo) eax) (:temporary (:sc unsigned-reg :offset edx-offset :from (:argument 0) :to (:result 1) :target rem) edx) (:results (quo :scs (unsigned-reg)) (rem :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 300 (move edx div-high) (move eax div-low) (inst div eax divisor) (move quo eax) (move rem edx))) (define-vop (signify-digit) (:translate sb!bignum:%fixnum-digit-with-correct-sign) (:policy :fast-safe) (:args (digit :scs (unsigned-reg unsigned-stack) :target res)) (:arg-types unsigned-num) (:results (res :scs (any-reg signed-reg) :load-if (not (and (sc-is digit unsigned-stack) (sc-is res control-stack signed-stack) (location= digit res))))) (:result-types signed-num) (:generator 1 (move res digit) (when (sc-is res any-reg control-stack) (inst shl res n-fixnum-tag-bits)))) (define-vop (digit-ashr) (:translate sb!bignum:%ashr) (:policy :fast-safe) (:args (digit :scs (unsigned-reg unsigned-stack) :target result) (count :scs (unsigned-reg) :target ecx)) (:arg-types unsigned-num positive-fixnum) (:temporary (:sc unsigned-reg :offset ecx-offset :from (:argument 1)) ecx) (:results (result :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is result unsigned-stack) (location= digit result))))) (:result-types unsigned-num) (:generator 2 (move result digit) (move ecx count) (inst sar result :cl))) (define-vop (digit-ashr/c) (:translate sb!bignum:%ashr) (:policy :fast-safe) (:args (digit :scs (unsigned-reg unsigned-stack) :target result)) (:arg-types unsigned-num (:constant (integer 0 31))) (:info count) (:results (result :scs (unsigned-reg) :from (:argument 0) :load-if (not (and (sc-is result unsigned-stack) (location= digit result))))) (:result-types unsigned-num) (:generator 1 (move result digit) (inst sar result count))) (define-vop (digit-lshr digit-ashr) (:translate sb!bignum:%digit-logical-shift-right) (:generator 1 (move result digit) (move ecx count) (inst shr result :cl))) (define-vop (digit-ashl digit-ashr) (:translate sb!bignum:%ashl) (:generator 1 (move result digit) (move ecx count) (inst shl result :cl))) (define-static-fun two-arg-/ (x y) :translate /) (define-static-fun two-arg-gcd (x y) :translate gcd) (define-static-fun two-arg-lcm (x y) :translate lcm) (define-static-fun two-arg-and (x y) :translate logand) (define-static-fun two-arg-ior (x y) :translate logior) (define-static-fun two-arg-xor (x y) :translate logxor) due to and Nishimura . and , " Mersenne twister : A 623 - dimensionally equidistributed uniform pseudorandom number generator . " , ACM Transactions on Modeling and Computer Simulation , 1997 , to appear . State : 0 - 1 : Constant matrix A. [ 0 , # x9908b0df ] ( not used here ) 3 - 626 : State . (defknown random-mt19937 ((simple-array (unsigned-byte 32) (*))) (unsigned-byte 32) ()) (define-vop (random-mt19937) (:policy :fast-safe) (:translate random-mt19937) (:args (state :scs (descriptor-reg) :to :result)) (:arg-types simple-array-unsigned-byte-32) (:temporary (:sc unsigned-reg :from (:eval 0) :to :result) k) (:temporary (:sc unsigned-reg :offset eax-offset :from (:eval 0) :to :result) tmp) (:results (y :scs (unsigned-reg) :from (:eval 0))) (:result-types unsigned-num) (:generator 50 (loadw k state (+ 2 vector-data-offset) other-pointer-lowtag) (inst cmp k 624) (inst jmp :ne no-update) The state is passed in EAX . (inst call (make-fixup 'random-mt19937-update :assembly-routine)) Restore k , and set to 0 . (inst xor k k) NO-UPDATE (inst mov y (make-ea-for-vector-data state :index k :offset 3)) (inst shr y 11) (inst xor y (make-ea-for-vector-data state :index k :offset 3)) y ^= ( y < < 7 ) & # x9d2c5680 (inst mov tmp y) (inst inc k) (inst shl tmp 7) (storew k state (+ 2 vector-data-offset) other-pointer-lowtag) (inst and tmp #x9d2c5680) (inst xor y tmp) y ^= ( y < < 15 ) & # xefc60000 (inst mov tmp y) (inst shl tmp 15) (inst and tmp #xefc60000) (inst xor y tmp) (inst mov tmp y) (inst shr tmp 18) (inst xor y tmp))) (in-package "SB!C") (defun mask-result (class width result) (ecase class (:unsigned `(logand ,result ,(1- (ash 1 width)))) (:signed `(mask-signed-field ,width ,result)))) " Strength Reduction of Multiplications by Integer Constants " , , ACM SIGPLAN Notices , Vol . 30 , No.2 , February 1995 . (defun basic-decompose-multiplication (class width arg num n-bits condensed) (case (aref condensed 0) (0 (let ((tmp (min 3 (aref condensed 1)))) (decf (aref condensed 1) tmp) (mask-result class width `(%lea ,arg ,(decompose-multiplication class width arg (ash (1- num) (- tmp)) (1- n-bits) (subseq condensed 1)) ,(ash 1 tmp) 0)))) ((1 2 3) (let ((r0 (aref condensed 0))) (incf (aref condensed 1) r0) (mask-result class width `(%lea ,(decompose-multiplication class width arg (- num (ash 1 r0)) (1- n-bits) (subseq condensed 1)) ,arg ,(ash 1 r0) 0)))) (t (let ((r0 (aref condensed 0))) (setf (aref condensed 0) 0) (mask-result class width `(ash ,(decompose-multiplication class width arg (ash num (- r0)) n-bits condensed) ,r0)))))) (defun decompose-multiplication (class width arg num n-bits condensed) (cond ((= n-bits 0) 0) ((= num 1) arg) ((= n-bits 1) (mask-result class width `(ash ,arg ,(1- (integer-length num))))) ((let ((max 0) (end 0)) (loop for i from 2 to (length condensed) for j = (reduce #'+ (subseq condensed 0 i)) when (and (> (- (* 2 i) 3 j) max) (< (+ (ash 1 (1+ j)) (ash (ldb (byte (- 32 (1+ j)) (1+ j)) num) (1+ j))) (ash 1 32))) do (setq max (- (* 2 i) 3 j) end i)) (when (> max 0) (let ((j (reduce #'+ (subseq condensed 0 end)))) (let ((n2 (+ (ash 1 (1+ j)) (ash (ldb (byte (- 32 (1+ j)) (1+ j)) num) (1+ j)))) (n1 (1+ (ldb (byte (1+ j) 0) (lognot num))))) (mask-result class width `(- ,(optimize-multiply class width arg n2) ,(optimize-multiply class width arg n1)))))))) ((dolist (i '(9 5 3)) (when (integerp (/ num i)) (when (< (logcount (/ num i)) (logcount num)) (let ((x (gensym))) (return `(let ((,x ,(optimize-multiply class width arg (/ num i)))) ,(mask-result class width `(%lea ,x ,x (1- ,i) 0))))))))) (t (basic-decompose-multiplication class width arg num n-bits condensed)))) (defun optimize-multiply (class width arg x) (let* ((n-bits (logcount x)) (condensed (make-array n-bits))) (let ((count 0) (bit 0)) (dotimes (i 32) (cond ((logbitp i x) (setf (aref condensed bit) count) (setf count 1) (incf bit)) (t (incf count))))) (decompose-multiplication class width arg x n-bits condensed))) (defun *-transformer (class width y) (cond ((= y (ash 1 (integer-length y))) there 's a generic transform for y = 2^k (give-up-ir1-transform)) ((member y '(3 5 9)) we can do these multiplications directly using LEA `(%lea x x ,(1- y) 0)) ((member :pentium4 *backend-subfeatures*) the pentium4 's multiply unit is reportedly very good (give-up-ir1-transform)) there should probably be a cutoff of about 9 instructions on (t (optimize-multiply class width 'x y)))) (deftransform * ((x y) ((unsigned-byte 32) (constant-arg (unsigned-byte 32))) (unsigned-byte 32)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :unsigned 32 y))) (deftransform sb!vm::*-mod32 ((x y) ((unsigned-byte 32) (constant-arg (unsigned-byte 32))) (unsigned-byte 32)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :unsigned 32 y))) (deftransform * ((x y) ((signed-byte 30) (constant-arg (unsigned-byte 32))) (signed-byte 30)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :signed 30 y))) (deftransform sb!vm::*-smod30 ((x y) ((signed-byte 30) (constant-arg (unsigned-byte 32))) (signed-byte 30)) "recode as leas, shifts and adds" (let ((y (lvar-value y))) (*-transformer :signed 30 y))) FIXME : we should also be able to write an optimizer or two to convert ( + ( * x 2 ) 17 ) , ( - ( * x 9 ) 5 ) to a % LEA .
b43d31beb31b6b2f9896b8768968581cd32b3dbcf252347fdc11ac15c1bbcbd9
ssadler/piped
Compose.hs
-- | Pipe composition can be supply or demand driven, which refers to how the pipeline is initiated . Supply driven initiates the left side first . -- When a pipe terminates , one side must return a value . Unless the pipeline is run -- in resumable mode, the other sides may never "complete" in that they do not return a value . If they allocate resources , MonadResource or similar should be used to handle cleanup ( see ' Piped . Extras.bracketPipe ' ) . -- -- Right hand termination works by indicating that no more values are available. -- -- In a mode where either side can return a value, no special termination logic is invoked, execution ends the first time a side returns . -- -- Left termination is not provided; since there is no way to indicate to the left side -- that the right has terminated, and potential solutions involve discarding values. -- However, the "either" modes are also suitable for left termination. -- module Piped.Compose ( -- ** Operators -- (.|) , (|.) -- ** Demand driven -- | The right hand side is run first . The left hand side is only -- invoked by calling `await`. -- , composeDemand , composeDemandEither -- ** Supply driven -- | The left hand side is run first . If it returns immediately , the right -- hand side is invoked only in the case of `composeSupply`. -- , composeSupply , composeSupplyEither ) where import Piped.Internal -- | Demand driven; same as 'composeDemand -- (.|) :: Monad m => Pipe i e m () -> Pipe e o m b -> Pipe i o m b (.|) = composeDemand # INLINE ( .| ) # -- | Supply driven; same as 'composeSupplyEither -- (|.) :: Monad m => Pipe i e m a -> Pipe e o m a -> Pipe i o m a (|.) = composeSupplyEither {-# INLINE (|.) #-} | The right side is run first , only the right side may return a value . -- composeDemand :: Monad m => Pipe i e m () -> Pipe e o m b -> Pipe i o m b composeDemand (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f2 (\_ -> rest termLeft) (Await $ f1 (\_ r _ -> terminate r) l) r # INLINE composeDemand # | The right side is run first , either side may return a value . -- composeDemandEither :: Monad m => Pipe i e m a -> Pipe e o m a -> Pipe i o m a composeDemandEither (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f2 (\_ -> rest termLeft) (Await $ f1 (\l -> rest l . termRight) l) r # INLINE composeDemandEither # | The left side is run first , only the right side may return a value . -- composeSupply :: Monad m => Pipe i e m () -> Pipe e o m b -> Pipe i o m b composeSupply (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f1 (\_ r _ -> terminate r) l $ Yield ( f2 (\_ -> rest termLeft) termLeft r) (\i left -> f2 (\_ -> rest termLeft) (addLeftover i left) r) # INLINE composeSupply # | The left side is run first , either side may return a value . -- composeSupplyEither :: Monad m => Pipe i e m a -> Pipe e o m a -> Pipe i o m a composeSupplyEither (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f1 (\l r -> rest l $ termRight r) l $ Yield ( f2 (\_ -> rest termLeft) termLeft r) (\i left -> f2 (\_ -> rest termLeft) (addLeftover i left) r) # INLINE composeSupplyEither #
null
https://raw.githubusercontent.com/ssadler/piped/036c064d93f3d37f834c522a6e59c5baf44fdb6e/piped/src/Piped/Compose.hs
haskell
| Pipe composition can be supply or demand driven, which refers to how the pipeline is in resumable mode, the other sides may never "complete" in that they do not Right hand termination works by indicating that no more values are available. In a mode where either side can return a value, no special termination logic is invoked, Left termination is not provided; since there is no way to indicate to the left side that the right has terminated, and potential solutions involve discarding values. However, the "either" modes are also suitable for left termination. ** Operators ** Demand driven invoked by calling `await`. ** Supply driven hand side is invoked only in the case of `composeSupply`. | Demand driven; same as 'composeDemand | Supply driven; same as 'composeSupplyEither # INLINE (|.) #
initiated . Supply driven initiates the left side first . When a pipe terminates , one side must return a value . Unless the pipeline is run return a value . If they allocate resources , MonadResource or similar should be used to handle cleanup ( see ' Piped . Extras.bracketPipe ' ) . execution ends the first time a side returns . module Piped.Compose ( (.|) , (|.) | The right hand side is run first . The left hand side is only , composeDemand , composeDemandEither | The left hand side is run first . If it returns immediately , the right , composeSupply , composeSupplyEither ) where import Piped.Internal (.|) :: Monad m => Pipe i e m () -> Pipe e o m b -> Pipe i o m b (.|) = composeDemand # INLINE ( .| ) # (|.) :: Monad m => Pipe i e m a -> Pipe e o m a -> Pipe i o m a (|.) = composeSupplyEither | The right side is run first , only the right side may return a value . composeDemand :: Monad m => Pipe i e m () -> Pipe e o m b -> Pipe i o m b composeDemand (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f2 (\_ -> rest termLeft) (Await $ f1 (\_ r _ -> terminate r) l) r # INLINE composeDemand # | The right side is run first , either side may return a value . composeDemandEither :: Monad m => Pipe i e m a -> Pipe e o m a -> Pipe i o m a composeDemandEither (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f2 (\_ -> rest termLeft) (Await $ f1 (\l -> rest l . termRight) l) r # INLINE composeDemandEither # | The left side is run first , only the right side may return a value . composeSupply :: Monad m => Pipe i e m () -> Pipe e o m b -> Pipe i o m b composeSupply (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f1 (\_ r _ -> terminate r) l $ Yield ( f2 (\_ -> rest termLeft) termLeft r) (\i left -> f2 (\_ -> rest termLeft) (addLeftover i left) r) # INLINE composeSupply # | The left side is run first , either side may return a value . composeSupplyEither :: Monad m => Pipe i e m a -> Pipe e o m a -> Pipe i o m a composeSupplyEither (Pipe f1) (Pipe f2) = Pipe $ \rest l r -> f1 (\l r -> rest l $ termRight r) l $ Yield ( f2 (\_ -> rest termLeft) termLeft r) (\i left -> f2 (\_ -> rest termLeft) (addLeftover i left) r) # INLINE composeSupplyEither #
5ed733cec8b43e03709a289da92ef693b206a3a98fa18b0b58624d482818475a
mbuczko/revolt
task.clj
(ns revolt.task "A home namespace for built-in tasks along with initialization functions." (:require [io.aviso.ansi] [revolt.context :as context] [revolt.tasks.aot :as aot] [revolt.tasks.jar :as jar] [revolt.tasks.cljs :as cljs] [revolt.tasks.sass :as sass] [revolt.tasks.test :as test] [revolt.tasks.info :as info] [revolt.tasks.codox :as codox] [revolt.tasks.clean :as clean] [revolt.tasks.assets :as assets] [revolt.tasks.capsule :as capsule] [revolt.utils :as utils] [clojure.tools.logging :as log] [clojure.string :as str])) (defprotocol Task (invoke [this input ctx] "Runs task with provided input data and pipelined context.") (notify [this path ctx] "Handles notification with java.nio.file.Path typed argument.") (describe [this] "Returns human readable task description.")) (defmulti create-task (fn [id opts classpaths target] id)) (defn create-task-with-args "A helper function to load a namespace denoted by namespace-part of provided qualified keyword, and create a task." [kw opts classpaths target] (if (qualified-keyword? kw) (let [ns (namespace kw)] (log/debug "initializing task" kw) (try (require (symbol ns)) (create-task kw opts classpaths target) (catch Exception ex (log/errorf "Cannot initialize task %s: %s" kw (.getMessage ex))))) (log/errorf "Wrong keyword %s. Qualified keyword required." kw))) (defn require-task* "Creates a task instance from qualified keyword. Loads a corresponding namespace from qualified keyword and invokes `create-task` multi-method with keyword as a dispatch value, passing task options, project classpaths and project target building directory as arguments." [kw] (context/with-context ctx (let [task (create-task-with-args kw (.config-val ctx kw) (.classpaths ctx) (.target-dir ctx))] (fn [& [input context]] as we operate on 2 optional parameter , 3 cases may happen : ;; 1 . we will get an input only , like ( info { : version 0.0.2 } ) ;; this is a case where no context was given, and it should ;; be created automatically. ;; 2 . we will get both : input and context . ;; this is a case where context was given either directly ;; along with input, eg. `(info {:version} app-ctx)` or task has ;; partially defined input, like: ;; ;; (partial capsule {:version 0.0.2}) ;; ;; and has been composed with other tasks: ;; ;; (def composed-task (comp capsule info)) ;; invocation of composed task will pass a context from one task ;; to the other. tasks having input partially defined will get an input as a first parameter and context as a second one . ;; 3 . we will get a context only . this a slight variation of case 2 . and may happen when task is ;; composed together with others and has no partially defined input parameter . in this case task will be called with one parameter ;; only - with an updated context. ;; to differentiate between case 1 and 3 a type check on first argument ;; is applied. a ::ContextMap type indicates that argument is a context ( case 3 ) , otherwise it is an input argument ( case 1 ) . (let [context-as-input? (= (type input) ::ContextMap) context-map (or context (when context-as-input? input) ^{:type ::ContextMap} {}) input-argument (when-not context-as-input? input)] (cond ;; handle special arguments (keywords) (keyword? input-argument) (condp = input-argument :help (println (io.aviso.ansi/yellow (.describe task))) (throw (Exception. "Keyword parameter not recognized by task."))) ;; handle notifications (instance? java.nio.file.Path input-argument) (.notify task input-argument context-map) :else (.invoke task input-argument context-map))))))) (def require-task-cached (memoize require-task*)) (defmacro require-task [kw & [opt arg]] `(when-let [task# (require-task-cached ~kw)] (intern *ns* (or (and (= ~opt :as) '~arg) '~(symbol (name kw))) task#))) (defmacro require-all [kws] `(when (coll? ~kws) [~@(map #(list `require-task %) kws)])) (defn run-tasks-from-string "Decomposes given input string into collection of [task options] tuples and sequentially runs them one after another. `tasks-str` is a comma-separated list of tasks to run, along with their optional parameters given as \"parameter=value\" expressions, like: clean,info:env=test:version=1.2,aot,capsule Returns resulting context map." [tasks-str] (when-let [required-tasks (seq (utils/make-params-coll tasks-str "revolt.task"))] (loop [tasks required-tasks context {}] (if-let [[task opts] (first tasks)] (recur (rest tasks) (or (when-let [task-fn (require-task-cached (keyword task))] (task-fn opts context)) context)) context)))) (defn make-description "Composes a task information based on title, description and list of parameters." [title description & params] (let [pstr (for [[k d] (partition 2 params)] (format " %-20s | %s", k d))] (str title "\n\n" description "\n\n" (str/join "\n" pstr) "\n"))) ;; built-in tasks (defmethod create-task ::clean [_ opts classpaths target] (reify Task (invoke [this input ctx] (clean/invoke ctx (merge opts input) target)) (describe [this] (make-description "Target directory cleaner" "Cleans target directory." :extra-paths "additional paths to clean")))) (defmethod create-task ::sass [_ opts classpaths target] (reify Task (invoke [this input ctx] (let [in (if (map? input) (merge opts input) (assoc opts :file input))] (sass/invoke ctx in classpaths target))) (notify [this path ctx] (.invoke this path ctx)) (describe [this] (make-description "CSS preprocessor" "Takes Sass/Scss files and turns them into CSS ones." :source-path "relative directory with sass/scss resources to transform" :output-path "relative directory where to store generated CSSes" :sass-options "sass compiler options")))) (defmethod create-task ::assets [_ opts classpaths target] (let [default-opts {:update-with-exts ["js" "css" "html"]} options (merge default-opts opts)] (reify Task (invoke [this input ctx] (assets/invoke ctx (merge options input) classpaths target)) (notify [this path ctx] (log/warn "Notification is not handled by \"assets\" task.") ctx) (describe [this] (make-description "Static assets fingerprinter" "Fingerprints static assets like images, scripts or styles" :assets-paths "collection of paths with assets to fingerprint" :exclude-paths "collection of paths to exclude from fingerprinting" :update-with-exts "extensions of files to update with new references to fingerprinted assets"))))) (defmethod create-task ::aot [_ opts classpaths target] (reify Task (invoke [this input ctx] (aot/invoke ctx (merge opts input) classpaths target)) (describe [this] (make-description "Ahead-Of-Time compilation" "Compiles project namespaces." :extra-namespaces "collection of additional namespaces to compile")))) (defmethod create-task ::cljs [_ opts classpaths target] (require 'cljs.build.api) (let [cljs-api (find-ns 'cljs.build.api) build-fn (ns-resolve cljs-api 'build) inputs-fn (ns-resolve cljs-api 'inputs)] (when (and build-fn inputs-fn) (reify Task (invoke [this input ctx] (let [options (merge-with merge opts input)] (cljs/invoke ctx options classpaths target inputs-fn build-fn))) (notify [this path ctx] (.invoke this nil ctx)) (describe [this] (make-description "CLJS compilation" "Turns clojurescripts into javascripts with help of ClojureScript compiler." :compiler "global clojurescript compiler options used for all builds" :builds "collection of builds, where each build consists of:\n :id - build identifier\n :source-paths - project-relative path of clojurescript files to compile\n :compiler - clojurescript compiler options (-options)")))))) (defmethod create-task ::test [_ opts classpaths targetf] (System/setProperty "java.awt.headless" "true") (let [options (merge test/default-options opts)] (reify Task (invoke [this input ctx] (test/invoke ctx (merge options input))) (notify [this path ctx] (.invoke this nil ctx)) (describe [this] (make-description "Clojure tests runner" "Test runner based on bat-test (-test)." :notify "sound notification? (defaults to true)" :test-matcher "regex used to select test namespaces (defaults to #\".*test\")" :parallel "run tests in parallel? (defaults to false)" :report "reporting function (:pretty, :progress or :junit)" :filter "function to filter the test vars" :on-start "function to call before running tests (after reloading namespaces)" :on-end "function to be call after running tests" :cloverage "enable Cloverage coverage report? (defaults to false)" :cloverage-opts "Cloverage options (defaults to nil)"))))) (defmethod create-task ::codox [_ opts classpaths target] (reify Task (invoke [this input ctx] (codox/invoke ctx (merge opts input) target)) (describe [this] (make-description "API documentation generator" "Codox based API documentation." :name "project name, eg. \"edge\"" :package "symbol describing project package, eg. defunkt.edge" :version "project version, eg. \"1.2.0\"" :description "project description to be shown" :namespaces "collection of namespaces to document (by default all namespaces are taken)")))) (defmethod create-task ::info [_ opts classpaths target] (reify Task (invoke [this input ctx] (info/invoke ctx (merge opts input) target)) (describe [this] (make-description "Project info generator" "Generates map of project-specific information used by other tasks." :name "project name, eg. \"edge\"" :package "symbol describing project package, eg defunkt.edge" :version "project version" :description "project description to be shown")))) (defmethod create-task ::jar [_ opts classpaths target] (reify Task (invoke [this input ctx] (jar/invoke ctx (merge opts input) target)) (describe [this] (make-description "Jar packager" "Generates a jar package." :exclude-paths "collection of project paths to exclude from jar package" :output-jar "project related path of output jar, eg. dist/foo.jar")))) (defmethod create-task ::capsule [_ opts classpaths target] (reify Task (invoke [this input ctx] (capsule/invoke ctx (merge opts input) target)) (describe [this] (make-description "Capsule packager" "Generates an uberjar-like capsule ()." :capsule-type "type of capsule, one of :empty, :thin or :fat (defaults to :fat)" :exclude-paths "collection of project paths to exclude from capsule" :output-jar "project related path of output jar, eg. dist/foo.jar" :main "main class to be run" :min-java-version "" :min-update-version "" :java-version "" :jdk-required? "" :jvm-args "" :environment-variables "" :system-properties "" :security-manager "" :security-policy "" :security-policy-appended "" :java-agents "" :native-agents "" :native-dependencies "" :capsule-log-level ""))))
null
https://raw.githubusercontent.com/mbuczko/revolt/65ef8de68d7aa77d1ced40e7d669ebcbba8a340e/src/revolt/task.clj
clojure
this is a case where no context was given, and it should be created automatically. this is a case where context was given either directly along with input, eg. `(info {:version} app-ctx)` or task has partially defined input, like: (partial capsule {:version 0.0.2}) and has been composed with other tasks: (def composed-task (comp capsule info)) to the other. tasks having input partially defined will get composed together with others and has no partially defined input only - with an updated context. is applied. a ::ContextMap type indicates that argument is a context handle special arguments (keywords) handle notifications built-in tasks
(ns revolt.task "A home namespace for built-in tasks along with initialization functions." (:require [io.aviso.ansi] [revolt.context :as context] [revolt.tasks.aot :as aot] [revolt.tasks.jar :as jar] [revolt.tasks.cljs :as cljs] [revolt.tasks.sass :as sass] [revolt.tasks.test :as test] [revolt.tasks.info :as info] [revolt.tasks.codox :as codox] [revolt.tasks.clean :as clean] [revolt.tasks.assets :as assets] [revolt.tasks.capsule :as capsule] [revolt.utils :as utils] [clojure.tools.logging :as log] [clojure.string :as str])) (defprotocol Task (invoke [this input ctx] "Runs task with provided input data and pipelined context.") (notify [this path ctx] "Handles notification with java.nio.file.Path typed argument.") (describe [this] "Returns human readable task description.")) (defmulti create-task (fn [id opts classpaths target] id)) (defn create-task-with-args "A helper function to load a namespace denoted by namespace-part of provided qualified keyword, and create a task." [kw opts classpaths target] (if (qualified-keyword? kw) (let [ns (namespace kw)] (log/debug "initializing task" kw) (try (require (symbol ns)) (create-task kw opts classpaths target) (catch Exception ex (log/errorf "Cannot initialize task %s: %s" kw (.getMessage ex))))) (log/errorf "Wrong keyword %s. Qualified keyword required." kw))) (defn require-task* "Creates a task instance from qualified keyword. Loads a corresponding namespace from qualified keyword and invokes `create-task` multi-method with keyword as a dispatch value, passing task options, project classpaths and project target building directory as arguments." [kw] (context/with-context ctx (let [task (create-task-with-args kw (.config-val ctx kw) (.classpaths ctx) (.target-dir ctx))] (fn [& [input context]] as we operate on 2 optional parameter , 3 cases may happen : 1 . we will get an input only , like ( info { : version 0.0.2 } ) 2 . we will get both : input and context . invocation of composed task will pass a context from one task an input as a first parameter and context as a second one . 3 . we will get a context only . this a slight variation of case 2 . and may happen when task is parameter . in this case task will be called with one parameter to differentiate between case 1 and 3 a type check on first argument ( case 3 ) , otherwise it is an input argument ( case 1 ) . (let [context-as-input? (= (type input) ::ContextMap) context-map (or context (when context-as-input? input) ^{:type ::ContextMap} {}) input-argument (when-not context-as-input? input)] (cond (keyword? input-argument) (condp = input-argument :help (println (io.aviso.ansi/yellow (.describe task))) (throw (Exception. "Keyword parameter not recognized by task."))) (instance? java.nio.file.Path input-argument) (.notify task input-argument context-map) :else (.invoke task input-argument context-map))))))) (def require-task-cached (memoize require-task*)) (defmacro require-task [kw & [opt arg]] `(when-let [task# (require-task-cached ~kw)] (intern *ns* (or (and (= ~opt :as) '~arg) '~(symbol (name kw))) task#))) (defmacro require-all [kws] `(when (coll? ~kws) [~@(map #(list `require-task %) kws)])) (defn run-tasks-from-string "Decomposes given input string into collection of [task options] tuples and sequentially runs them one after another. `tasks-str` is a comma-separated list of tasks to run, along with their optional parameters given as \"parameter=value\" expressions, like: clean,info:env=test:version=1.2,aot,capsule Returns resulting context map." [tasks-str] (when-let [required-tasks (seq (utils/make-params-coll tasks-str "revolt.task"))] (loop [tasks required-tasks context {}] (if-let [[task opts] (first tasks)] (recur (rest tasks) (or (when-let [task-fn (require-task-cached (keyword task))] (task-fn opts context)) context)) context)))) (defn make-description "Composes a task information based on title, description and list of parameters." [title description & params] (let [pstr (for [[k d] (partition 2 params)] (format " %-20s | %s", k d))] (str title "\n\n" description "\n\n" (str/join "\n" pstr) "\n"))) (defmethod create-task ::clean [_ opts classpaths target] (reify Task (invoke [this input ctx] (clean/invoke ctx (merge opts input) target)) (describe [this] (make-description "Target directory cleaner" "Cleans target directory." :extra-paths "additional paths to clean")))) (defmethod create-task ::sass [_ opts classpaths target] (reify Task (invoke [this input ctx] (let [in (if (map? input) (merge opts input) (assoc opts :file input))] (sass/invoke ctx in classpaths target))) (notify [this path ctx] (.invoke this path ctx)) (describe [this] (make-description "CSS preprocessor" "Takes Sass/Scss files and turns them into CSS ones." :source-path "relative directory with sass/scss resources to transform" :output-path "relative directory where to store generated CSSes" :sass-options "sass compiler options")))) (defmethod create-task ::assets [_ opts classpaths target] (let [default-opts {:update-with-exts ["js" "css" "html"]} options (merge default-opts opts)] (reify Task (invoke [this input ctx] (assets/invoke ctx (merge options input) classpaths target)) (notify [this path ctx] (log/warn "Notification is not handled by \"assets\" task.") ctx) (describe [this] (make-description "Static assets fingerprinter" "Fingerprints static assets like images, scripts or styles" :assets-paths "collection of paths with assets to fingerprint" :exclude-paths "collection of paths to exclude from fingerprinting" :update-with-exts "extensions of files to update with new references to fingerprinted assets"))))) (defmethod create-task ::aot [_ opts classpaths target] (reify Task (invoke [this input ctx] (aot/invoke ctx (merge opts input) classpaths target)) (describe [this] (make-description "Ahead-Of-Time compilation" "Compiles project namespaces." :extra-namespaces "collection of additional namespaces to compile")))) (defmethod create-task ::cljs [_ opts classpaths target] (require 'cljs.build.api) (let [cljs-api (find-ns 'cljs.build.api) build-fn (ns-resolve cljs-api 'build) inputs-fn (ns-resolve cljs-api 'inputs)] (when (and build-fn inputs-fn) (reify Task (invoke [this input ctx] (let [options (merge-with merge opts input)] (cljs/invoke ctx options classpaths target inputs-fn build-fn))) (notify [this path ctx] (.invoke this nil ctx)) (describe [this] (make-description "CLJS compilation" "Turns clojurescripts into javascripts with help of ClojureScript compiler." :compiler "global clojurescript compiler options used for all builds" :builds "collection of builds, where each build consists of:\n :id - build identifier\n :source-paths - project-relative path of clojurescript files to compile\n :compiler - clojurescript compiler options (-options)")))))) (defmethod create-task ::test [_ opts classpaths targetf] (System/setProperty "java.awt.headless" "true") (let [options (merge test/default-options opts)] (reify Task (invoke [this input ctx] (test/invoke ctx (merge options input))) (notify [this path ctx] (.invoke this nil ctx)) (describe [this] (make-description "Clojure tests runner" "Test runner based on bat-test (-test)." :notify "sound notification? (defaults to true)" :test-matcher "regex used to select test namespaces (defaults to #\".*test\")" :parallel "run tests in parallel? (defaults to false)" :report "reporting function (:pretty, :progress or :junit)" :filter "function to filter the test vars" :on-start "function to call before running tests (after reloading namespaces)" :on-end "function to be call after running tests" :cloverage "enable Cloverage coverage report? (defaults to false)" :cloverage-opts "Cloverage options (defaults to nil)"))))) (defmethod create-task ::codox [_ opts classpaths target] (reify Task (invoke [this input ctx] (codox/invoke ctx (merge opts input) target)) (describe [this] (make-description "API documentation generator" "Codox based API documentation." :name "project name, eg. \"edge\"" :package "symbol describing project package, eg. defunkt.edge" :version "project version, eg. \"1.2.0\"" :description "project description to be shown" :namespaces "collection of namespaces to document (by default all namespaces are taken)")))) (defmethod create-task ::info [_ opts classpaths target] (reify Task (invoke [this input ctx] (info/invoke ctx (merge opts input) target)) (describe [this] (make-description "Project info generator" "Generates map of project-specific information used by other tasks." :name "project name, eg. \"edge\"" :package "symbol describing project package, eg defunkt.edge" :version "project version" :description "project description to be shown")))) (defmethod create-task ::jar [_ opts classpaths target] (reify Task (invoke [this input ctx] (jar/invoke ctx (merge opts input) target)) (describe [this] (make-description "Jar packager" "Generates a jar package." :exclude-paths "collection of project paths to exclude from jar package" :output-jar "project related path of output jar, eg. dist/foo.jar")))) (defmethod create-task ::capsule [_ opts classpaths target] (reify Task (invoke [this input ctx] (capsule/invoke ctx (merge opts input) target)) (describe [this] (make-description "Capsule packager" "Generates an uberjar-like capsule ()." :capsule-type "type of capsule, one of :empty, :thin or :fat (defaults to :fat)" :exclude-paths "collection of project paths to exclude from capsule" :output-jar "project related path of output jar, eg. dist/foo.jar" :main "main class to be run" :min-java-version "" :min-update-version "" :java-version "" :jdk-required? "" :jvm-args "" :environment-variables "" :system-properties "" :security-manager "" :security-policy "" :security-policy-appended "" :java-agents "" :native-agents "" :native-dependencies "" :capsule-log-level ""))))
56e0850a5f3cba0a044996ddb13a31045e76e828456c94468938dee34f0889e1
alanb2718/wallingford
always-dynamic-tests.rkt
#lang s-exp rosette (require rackunit rackunit/text-ui rosette/lib/roseunit) (require "../core/wallingford.rkt") (provide always-dynamic-tests) ;; Additional tests of always constraints -- dynamically re-assign something (define (assign-always-test) (test-case "test reassiging a variable using always (constraint should apply to new binding)" (define c (new thing%)) (define-symbolic x y integer?) (always (equal? x 3) #:priority low #:owner c) (always (equal? y 4) #:priority high #:owner c) (send c solve) (check-equal? (send c wally-evaluate x) 3) (check-equal? (send c wally-evaluate y) 4) (set! y x) (send c solve) the ( always ( equal ? y 4 ) constraint applies to the current binding for y , ; so we should get x=y=4 at this point (check-equal? (send c wally-evaluate x) 4) (check-equal? (send c wally-evaluate y) 4) )) (define (assign-always-required-test) (test-case "test reassiging a variable using a required always (mostly to test the optional priority parameter)" (define c (new thing%)) (define-symbolic x y integer?) (always (equal? x 3) #:priority low #:owner c) (always (equal? y 4) #:owner c) (send c solve) (check-equal? (send c wally-evaluate x) 3) (check-equal? (send c wally-evaluate y) 4) (set! y x) (send c solve) the ( always ( equal ? y 4 ) constraint applies to the current binding for y , ; so we should get x=y=4 at this point (check-equal? (send c wally-evaluate x) 4) (check-equal? (send c wally-evaluate y) 4) )) (struct test-struct (fld) #:transparent #:mutable) (define (struct-always-set-test) (test-case "test setting a field of a mutable struct" (define c (new thing%)) (define-symbolic x y integer?) (define s (test-struct x)) (always (equal? x 3) #:priority low #:owner c) (always (equal? y 4) #:priority low #:owner c) (always (equal? (test-struct-fld s) 10) #:priority high #:owner c) (send c solve) (check-equal? (send c wally-evaluate (test-struct-fld s)) 10) (check-equal? (send c wally-evaluate x) 10) (check-equal? (send c wally-evaluate y) 4) (set-test-struct-fld! s y) (send c solve) ; the always constraint on the struct applies to the current contents of fld (check-equal? (send c wally-evaluate (test-struct-fld s)) 10) (check-equal? (send c wally-evaluate x) 3) (check-equal? (send c wally-evaluate y) 10) )) (define (explicit-required-priority-test) (test-case "test providing an explicit priority of required" (define c (new thing%)) (define-symbolic x integer?) (always (equal? x 2) #:priority required #:owner c) (always (equal? x 3) #:priority required #:owner c) (check-exn exn:fail? (lambda () (send c solve))) ; clear assertions, since they are in an unsatisfiable state at this point (clear-asserts!))) (define always-dynamic-tests (test-suite+ "unit tests for dynamic always constraints" (assign-always-test) (assign-always-required-test) (struct-always-set-test) (explicit-required-priority-test) )) (time (run-tests always-dynamic-tests))
null
https://raw.githubusercontent.com/alanb2718/wallingford/9dd436c29f737d210c5b87dc1b86b2924c0c5970/tests/always-dynamic-tests.rkt
racket
Additional tests of always constraints -- dynamically re-assign something so we should get x=y=4 at this point so we should get x=y=4 at this point the always constraint on the struct applies to the current contents of fld clear assertions, since they are in an unsatisfiable state at this point
#lang s-exp rosette (require rackunit rackunit/text-ui rosette/lib/roseunit) (require "../core/wallingford.rkt") (provide always-dynamic-tests) (define (assign-always-test) (test-case "test reassiging a variable using always (constraint should apply to new binding)" (define c (new thing%)) (define-symbolic x y integer?) (always (equal? x 3) #:priority low #:owner c) (always (equal? y 4) #:priority high #:owner c) (send c solve) (check-equal? (send c wally-evaluate x) 3) (check-equal? (send c wally-evaluate y) 4) (set! y x) (send c solve) the ( always ( equal ? y 4 ) constraint applies to the current binding for y , (check-equal? (send c wally-evaluate x) 4) (check-equal? (send c wally-evaluate y) 4) )) (define (assign-always-required-test) (test-case "test reassiging a variable using a required always (mostly to test the optional priority parameter)" (define c (new thing%)) (define-symbolic x y integer?) (always (equal? x 3) #:priority low #:owner c) (always (equal? y 4) #:owner c) (send c solve) (check-equal? (send c wally-evaluate x) 3) (check-equal? (send c wally-evaluate y) 4) (set! y x) (send c solve) the ( always ( equal ? y 4 ) constraint applies to the current binding for y , (check-equal? (send c wally-evaluate x) 4) (check-equal? (send c wally-evaluate y) 4) )) (struct test-struct (fld) #:transparent #:mutable) (define (struct-always-set-test) (test-case "test setting a field of a mutable struct" (define c (new thing%)) (define-symbolic x y integer?) (define s (test-struct x)) (always (equal? x 3) #:priority low #:owner c) (always (equal? y 4) #:priority low #:owner c) (always (equal? (test-struct-fld s) 10) #:priority high #:owner c) (send c solve) (check-equal? (send c wally-evaluate (test-struct-fld s)) 10) (check-equal? (send c wally-evaluate x) 10) (check-equal? (send c wally-evaluate y) 4) (set-test-struct-fld! s y) (send c solve) (check-equal? (send c wally-evaluate (test-struct-fld s)) 10) (check-equal? (send c wally-evaluate x) 3) (check-equal? (send c wally-evaluate y) 10) )) (define (explicit-required-priority-test) (test-case "test providing an explicit priority of required" (define c (new thing%)) (define-symbolic x integer?) (always (equal? x 2) #:priority required #:owner c) (always (equal? x 3) #:priority required #:owner c) (check-exn exn:fail? (lambda () (send c solve))) (clear-asserts!))) (define always-dynamic-tests (test-suite+ "unit tests for dynamic always constraints" (assign-always-test) (assign-always-required-test) (struct-always-set-test) (explicit-required-priority-test) )) (time (run-tests always-dynamic-tests))
5cb4eba05a262532aa44008d45c3bc31367d4dd163c474d2d44725b558521491
0x0f0f0f/gobba
typecheck.ml
open Types open Errors let terr e f = traise ("expected a value of type: " ^ e ^ ", found a value of type: " ^ f ) let typeof e = match e with | EvtVect (t, a) -> TVect ((Array.length a), t) | EvtUnit -> TUnit | EvtInt _ -> TInt | EvtFloat _ -> TFloat | EvtComplex _ -> TComplex | EvtBool _ -> TBool | EvtString _ -> TString | EvtList _ -> TList | EvtDict _ -> TDict | EvtChar _ -> TChar | Closure (_, _, _, _) -> TLambda | LazyExpression _ -> TUnit (** Get the lowest (most inclusive set) number type from a list of numbers *) let rec level_number_list low ls = match ls with | [] -> low | (EvtComplex _)::_ -> TComplex | (EvtInt _)::xs -> level_number_list low xs | (EvtFloat _)::xs -> level_number_list TFloat xs | (_)::_ -> traise "value is not a number in arithmetical operator" let cast_numbert lowerto num = match lowerto with | TInt -> num | TFloat -> (match num with | EvtInt x -> EvtFloat(float_of_int x) | EvtFloat x -> EvtFloat x | EvtComplex x -> EvtComplex x | _ -> traise "not a number") | TComplex -> (match num with | EvtInt x -> EvtComplex {re = float_of_int x; im = 0.} | EvtFloat x -> EvtComplex {re = x; im = 0.} | EvtComplex x -> EvtComplex x | _ -> traise "not a number") | _ -> traise "cannot cast to a non-numerical type" (** Accept a list of numbers and flatten out their kind on the numerical tower hierarchy *) let flatten_numbert_list l = let found = level_number_list TInt l in (found, List.map (cast_numbert found) l) (* Dynamic typechecking *) let dyncheck (f: typeinfo) (e: typeinfo) = let rterr () = terr (show_typeinfo e) (show_typeinfo f) in match e with | TNumber -> (match f with | TInt | TFloat | TComplex | TNumber -> () | _ -> rterr () ) | _ -> if e = f then () else rterr() (** Unpacking functions: extract a value or throw an err *) let unpack_int x = (match x with EvtInt i -> i | e -> terr "int" (show_typeinfo (typeof e))) let unpack_float x = (match x with EvtFloat i -> i | e -> terr "float" (show_typeinfo (typeof e))) let unpack_complex x = (match x with EvtComplex i -> i | e -> terr "complex" (show_typeinfo (typeof e))) let unpack_bool x = (match x with EvtBool i -> i | e -> terr "bool" (show_typeinfo (typeof e))) let unpack_char x = (match x with EvtChar i -> i | e -> terr "char" (show_typeinfo (typeof e))) let unpack_string x = (match x with EvtString i -> i | e -> terr "string" (show_typeinfo (typeof e))) let unpack_list x = (match x with EvtList i -> i | e -> terr "list" (show_typeinfo (typeof e))) let unpack_dict x = (match x with EvtDict i -> i | e -> terr "dict" (show_typeinfo (typeof e))) let unpack_closure x = (match x with Closure (n, p, b, e) -> (n, p,b,e) | e -> terr "fun" (show_typeinfo (typeof e)))
null
https://raw.githubusercontent.com/0x0f0f0f/gobba/61092207438fb102e36245c46c27a711b8f357cb/lib/typecheck.ml
ocaml
* Get the lowest (most inclusive set) number type from a list of numbers * Accept a list of numbers and flatten out their kind on the numerical tower hierarchy Dynamic typechecking * Unpacking functions: extract a value or throw an err
open Types open Errors let terr e f = traise ("expected a value of type: " ^ e ^ ", found a value of type: " ^ f ) let typeof e = match e with | EvtVect (t, a) -> TVect ((Array.length a), t) | EvtUnit -> TUnit | EvtInt _ -> TInt | EvtFloat _ -> TFloat | EvtComplex _ -> TComplex | EvtBool _ -> TBool | EvtString _ -> TString | EvtList _ -> TList | EvtDict _ -> TDict | EvtChar _ -> TChar | Closure (_, _, _, _) -> TLambda | LazyExpression _ -> TUnit let rec level_number_list low ls = match ls with | [] -> low | (EvtComplex _)::_ -> TComplex | (EvtInt _)::xs -> level_number_list low xs | (EvtFloat _)::xs -> level_number_list TFloat xs | (_)::_ -> traise "value is not a number in arithmetical operator" let cast_numbert lowerto num = match lowerto with | TInt -> num | TFloat -> (match num with | EvtInt x -> EvtFloat(float_of_int x) | EvtFloat x -> EvtFloat x | EvtComplex x -> EvtComplex x | _ -> traise "not a number") | TComplex -> (match num with | EvtInt x -> EvtComplex {re = float_of_int x; im = 0.} | EvtFloat x -> EvtComplex {re = x; im = 0.} | EvtComplex x -> EvtComplex x | _ -> traise "not a number") | _ -> traise "cannot cast to a non-numerical type" let flatten_numbert_list l = let found = level_number_list TInt l in (found, List.map (cast_numbert found) l) let dyncheck (f: typeinfo) (e: typeinfo) = let rterr () = terr (show_typeinfo e) (show_typeinfo f) in match e with | TNumber -> (match f with | TInt | TFloat | TComplex | TNumber -> () | _ -> rterr () ) | _ -> if e = f then () else rterr() let unpack_int x = (match x with EvtInt i -> i | e -> terr "int" (show_typeinfo (typeof e))) let unpack_float x = (match x with EvtFloat i -> i | e -> terr "float" (show_typeinfo (typeof e))) let unpack_complex x = (match x with EvtComplex i -> i | e -> terr "complex" (show_typeinfo (typeof e))) let unpack_bool x = (match x with EvtBool i -> i | e -> terr "bool" (show_typeinfo (typeof e))) let unpack_char x = (match x with EvtChar i -> i | e -> terr "char" (show_typeinfo (typeof e))) let unpack_string x = (match x with EvtString i -> i | e -> terr "string" (show_typeinfo (typeof e))) let unpack_list x = (match x with EvtList i -> i | e -> terr "list" (show_typeinfo (typeof e))) let unpack_dict x = (match x with EvtDict i -> i | e -> terr "dict" (show_typeinfo (typeof e))) let unpack_closure x = (match x with Closure (n, p, b, e) -> (n, p,b,e) | e -> terr "fun" (show_typeinfo (typeof e)))
239e8cd98e02a626997a115302fd641e980d9a575a3bc6fe28de428a9f40d2a2
discljord/discljord
snowflakes.clj
(ns discljord.snowflakes "Contains utility functions to parse, deconstruct and create [snowflake ids](#snowflakes)." (:require [discljord.util :refer [parse-if-str]])) (def ^:const discord-epoch "The Discord epoch - the number of milliseconds that had passed since January 1, 1970, on January 1, 2015." 1420070400000) (defn timestamp "Returns the UNIX timestamp (ms) for when this id was generated. Takes either a string or a number representing the snowflake." [snowflake] (+ (bit-shift-right (parse-if-str snowflake) 22) discord-epoch)) (defn internal-worker-id "Returns the internal id of the worker that generated this id. Takes either a string or a number representing the snowflake." [snowflake] (bit-shift-right (bit-and (parse-if-str snowflake) 0x3E0000) 17)) (defn internal-process-id "Returns the internal id of the process this id was generated on. Takes either a string or a number representing the snowflake." [snowflake] (bit-shift-right (bit-and (parse-if-str snowflake) 0x1F000) 15)) (defn increment "Returns the increment of this id, i.e. the number of ids that had been generated before on its process. Takes either a string or a number representing the snowflake." [snowflake] (bit-and (parse-if-str snowflake) 0xFFF)) (defn parse-snowflake "Extracts all information from the given id and returns it as a map. The map has the following keys: `:id` - The input snowflake as a number `:timestamp` - See [[timestamp]] `:internal-worker-id` - See [[internal-worker-id]] `:internal-process-id` - See [[internal-process-id]] `:increment` - See [[increment]]" [snowflake] (let [snowflake (parse-if-str snowflake)] {:id snowflake :timestamp (timestamp snowflake) :internal-worker-id (internal-worker-id snowflake) :internal-process-id (internal-process-id snowflake) :increment (increment snowflake)})) (defn timestamp->snowflake "Takes a UNIX milliseconds timestamp (like from `(System/currentTimeMillis)`) and returns it as a Discord snowflake id. This can be used for paginated endpoints where ids are used to represent bounds like 'before' and 'after' to get results before, after or between timestamps." [timestamp] (bit-shift-left (- timestamp discord-epoch) 22))
null
https://raw.githubusercontent.com/discljord/discljord/2e321cee59d8a627dedc0c460c3266698e018b34/src/discljord/snowflakes.clj
clojure
(ns discljord.snowflakes "Contains utility functions to parse, deconstruct and create [snowflake ids](#snowflakes)." (:require [discljord.util :refer [parse-if-str]])) (def ^:const discord-epoch "The Discord epoch - the number of milliseconds that had passed since January 1, 1970, on January 1, 2015." 1420070400000) (defn timestamp "Returns the UNIX timestamp (ms) for when this id was generated. Takes either a string or a number representing the snowflake." [snowflake] (+ (bit-shift-right (parse-if-str snowflake) 22) discord-epoch)) (defn internal-worker-id "Returns the internal id of the worker that generated this id. Takes either a string or a number representing the snowflake." [snowflake] (bit-shift-right (bit-and (parse-if-str snowflake) 0x3E0000) 17)) (defn internal-process-id "Returns the internal id of the process this id was generated on. Takes either a string or a number representing the snowflake." [snowflake] (bit-shift-right (bit-and (parse-if-str snowflake) 0x1F000) 15)) (defn increment "Returns the increment of this id, i.e. the number of ids that had been generated before on its process. Takes either a string or a number representing the snowflake." [snowflake] (bit-and (parse-if-str snowflake) 0xFFF)) (defn parse-snowflake "Extracts all information from the given id and returns it as a map. The map has the following keys: `:id` - The input snowflake as a number `:timestamp` - See [[timestamp]] `:internal-worker-id` - See [[internal-worker-id]] `:internal-process-id` - See [[internal-process-id]] `:increment` - See [[increment]]" [snowflake] (let [snowflake (parse-if-str snowflake)] {:id snowflake :timestamp (timestamp snowflake) :internal-worker-id (internal-worker-id snowflake) :internal-process-id (internal-process-id snowflake) :increment (increment snowflake)})) (defn timestamp->snowflake "Takes a UNIX milliseconds timestamp (like from `(System/currentTimeMillis)`) and returns it as a Discord snowflake id. This can be used for paginated endpoints where ids are used to represent bounds like 'before' and 'after' to get results before, after or between timestamps." [timestamp] (bit-shift-left (- timestamp discord-epoch) 22))
0e68efbbbd2aba95b1fd5b8ed476b3690443d279f9cd71811908b946b65788c5
ghcjs/ghcjs-dom
WebGLContextEvent.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.WebGLContextEvent (js_newWebGLContextEvent, newWebGLContextEvent, js_getStatusMessage, getStatusMessage, WebGLContextEvent(..), gTypeWebGLContextEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"WebGLContextEvent\"]($1,\n$2)" js_newWebGLContextEvent :: JSString -> Optional WebGLContextEventInit -> IO WebGLContextEvent | < -US/docs/Web/API/WebGLContextEvent Mozilla WebGLContextEvent documentation > newWebGLContextEvent :: (MonadIO m, ToJSString type') => type' -> Maybe WebGLContextEventInit -> m WebGLContextEvent newWebGLContextEvent type' eventInit = liftIO (js_newWebGLContextEvent (toJSString type') (maybeToOptional eventInit)) foreign import javascript unsafe "$1[\"statusMessage\"]" js_getStatusMessage :: WebGLContextEvent -> IO JSString | < -US/docs/Web/API/WebGLContextEvent.statusMessage Mozilla WebGLContextEvent.statusMessage documentation > getStatusMessage :: (MonadIO m, FromJSString result) => WebGLContextEvent -> m result getStatusMessage self = liftIO (fromJSString <$> (js_getStatusMessage self))
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/WebGLContextEvent.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.WebGLContextEvent (js_newWebGLContextEvent, newWebGLContextEvent, js_getStatusMessage, getStatusMessage, WebGLContextEvent(..), gTypeWebGLContextEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"WebGLContextEvent\"]($1,\n$2)" js_newWebGLContextEvent :: JSString -> Optional WebGLContextEventInit -> IO WebGLContextEvent | < -US/docs/Web/API/WebGLContextEvent Mozilla WebGLContextEvent documentation > newWebGLContextEvent :: (MonadIO m, ToJSString type') => type' -> Maybe WebGLContextEventInit -> m WebGLContextEvent newWebGLContextEvent type' eventInit = liftIO (js_newWebGLContextEvent (toJSString type') (maybeToOptional eventInit)) foreign import javascript unsafe "$1[\"statusMessage\"]" js_getStatusMessage :: WebGLContextEvent -> IO JSString | < -US/docs/Web/API/WebGLContextEvent.statusMessage Mozilla WebGLContextEvent.statusMessage documentation > getStatusMessage :: (MonadIO m, FromJSString result) => WebGLContextEvent -> m result getStatusMessage self = liftIO (fromJSString <$> (js_getStatusMessage self))
2aaa5331ebdb82e78acc95e0db55275293e6ccf12d288140b26b6407a8e8f9b8
sbcl/sbcl
unix.lisp
This file contains Unix support that SBCL needs to implement itself . It 's derived from unix-glibc2.lisp for CMU CL , which was derived from CMU CL unix.lisp 1.56 . But those ;;;; files aspired to be complete Unix interfaces exported to the end ;;;; user, while this file aims to be as simple as possible and is not ;;;; intended for the end user. ;;;; FIXME : The old CMU CL unix.lisp code was implemented as hand ;;;; transcriptions from Unix headers into Lisp. It appears that this was as ;;;; unmaintainable in practice as you'd expect in theory, so I really really ;;;; don't want to do that. It'd be good to implement the various system calls ;;;; as C code implemented using the Unix header files, and have their interface back to SBCL code be characterized by things like " 32 - bit - wide ;;;; int" which are already in the interface between the runtime executable and the SBCL lisp code . This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB-UNIX") (/show0 "unix.lisp 21") Given a C - level zero - terminated array of C strings , return a ;;; corresponding Lisp-level list of SIMPLE-STRINGs. (defun c-strings->string-list (c-strings) (declare (type (alien (* c-string)) c-strings)) (let ((reversed-result nil)) (dotimes (i most-positive-fixnum) (declare (type index i)) (let ((c-string (deref c-strings i))) (if c-string (push c-string reversed-result) (return (nreverse reversed-result))))))) ;;;; Lisp types used by syscalls (deftype unix-pathname () 'simple-string) (deftype unix-fd () `(integer 0 ,most-positive-fixnum)) (deftype unix-file-mode () '(unsigned-byte 32)) (deftype unix-pid () '(unsigned-byte 32)) (deftype unix-uid () '(unsigned-byte 32)) (deftype unix-gid () '(unsigned-byte 32)) ;;;; system calls (/show0 "unix.lisp 74") (eval-when (:compile-toplevel :load-toplevel :execute) (defun libc-name-for (x) (assert (stringp x)) ;; This function takes a possibly-wrapped C name and strips off "sb_" ;; if it doesn't need a wrapper. The list of functions that can be ;; called directly is listed explicitly, because there are also others ;; that might want to be wrapped even if they don't need to be, like and sb_closedir . Why are those wrapped in fact ? #+netbsd x #-netbsd (if (member x '("sb_getrusage" ; syscall* "sb_gettimeofday" ;syscall* "sb_select" ; int-syscall "sb_getitimer" ; syscall* "sb_setitimer" ; syscall* "sb_clock_gettime" ; alien-funcall "sb_utimes") ; posix :test #'string=) (subseq x 3) x))) (defmacro syscall ((name &rest arg-types) success-form &rest args) (when (eql 3 (mismatch "[_]" name)) (setf name (concatenate 'string #+win32 "_" (subseq name 3)))) `(locally (declare (optimize (sb-c::float-accuracy 0))) (let ((result (alien-funcall (extern-alien ,(libc-name-for name) (function int ,@arg-types)) ,@args))) (if (minusp result) (values nil (get-errno)) ,success-form)))) ;;; This is like SYSCALL, but if it fails, signal an error instead of ;;; returning error codes. Should only be used for syscalls that will ;;; never really get an error. (defmacro syscall* ((name &rest arg-types) success-form &rest args) `(locally (declare (optimize (sb-c::float-accuracy 0))) (let ((result (alien-funcall (extern-alien ,(libc-name-for name) (function int ,@arg-types)) ,@args))) (if (minusp result) (error "Syscall ~A failed: ~A" ,name (strerror)) ,success-form)))) (defmacro int-syscall ((name &rest arg-types) &rest args) `(syscall (,(libc-name-for name) ,@arg-types) (values result 0) ,@args)) (defmacro with-restarted-syscall ((&optional (value (gensym)) (errno (gensym))) syscall-form &rest body) "Evaluate BODY with VALUE and ERRNO bound to the return values of SYSCALL-FORM. Repeat evaluation of SYSCALL-FORM if it is interrupted." `(let (,value ,errno) (loop (multiple-value-setq (,value ,errno) ,syscall-form) (unless #-win32 (eql ,errno eintr) #+win32 nil (return (values ,value ,errno)))) ,@body)) (defmacro void-syscall ((name &rest arg-types) &rest args) `(syscall (,name ,@arg-types) (values t 0) ,@args)) #+win32 (progn (defconstant espipe 29)) ;;;; hacking the Unix environment #-win32 (define-alien-routine ("getenv" posix-getenv) c-string "Return the \"value\" part of the environment string \"name=value\" which corresponds to NAME, or NIL if there is none." (name (c-string :not-null t))) from stdio.h Rename the file with string NAME1 to the string . NIL and an ;;; error code is returned if an error occurs. #-win32 (defun unix-rename (name1 name2) (declare (type unix-pathname name1 name2)) (void-syscall ("rename" (c-string :not-null t) (c-string :not-null t)) name1 name2)) from sys / types.h and gnu / types.h (/show0 "unix.lisp 220") ;;; FIXME: We shouldn't hand-copy types from header files into Lisp ;;; like this unless we have extreme provocation. Reading directories ;;; is not extreme enough, since it doesn't need to be blindingly ;;; fast: we can just implement those functions in C as a wrapper ;;; layer. (define-alien-type fd-mask unsigned) (define-alien-type nil (struct fd-set (fds-bits (array fd-mask #.(/ fd-setsize sb-vm:n-machine-word-bits))))) (/show0 "unix.lisp 304") ;;;; fcntl.h ;;;; POSIX Standard : 6.5 File Control Operations < fcntl.h > ;;; Open the file whose pathname is specified by PATH for reading and/or writing as specified by the argument . Various ;;; masks (O_RDONLY etc.) are defined in fcntlbits.h. ;;; If the flag is specified , then the file is created with a ;;; permission of argument MODE if the file doesn't exist. An integer file descriptor is returned by UNIX - OPEN . (defun unix-open (path flags mode &key #+win32 overlapped) (declare (type unix-pathname path) (type fixnum flags) (type unix-file-mode mode) #+win32 (ignore mode)) #+win32 (sb-win32:unixlike-open path flags :overlapped overlapped) #-win32 (with-restarted-syscall (value errno) (locally (declare (optimize (sb-c::float-accuracy 0))) (let ((result (alien-funcall (extern-alien "open" (function int c-string int &optional int)) path (logior flags #+largefile o_largefile) mode))) (if (minusp result) (values nil (get-errno)) (values result 0)))))) ;;; UNIX-CLOSE accepts a file descriptor and attempts to close the file ;;; associated with it. (/show0 "unix.lisp 391") (defun unix-close (fd) #+win32 (sb-win32:unixlike-close fd) #-win32 (declare (type unix-fd fd)) #-win32 (void-syscall ("close" int) fd)) ;;;; stdlib.h ;;; There are good reasons to implement some OPEN options with an ;;; mkstemp(3)-like routine, but we don't do that yet. Instead, this ;;; function is used only to make a temporary file for RUN-PROGRAM. sb_mkstemp ( ) is a wrapper that lives in src / runtime / wrap.c . Since ;;; SUSv3 mkstemp() doesn't specify the mode of the created file and since we have to implement most of this ourselves for Windows anyway , it seems worthwhile to depart from the ( ) ;;; specification by taking a mode to use when creating the new file. (defun sb-mkstemp (template-string mode) (declare (type string template-string) (type unix-file-mode mode)) (let ((template-buffer (string-to-octets template-string :null-terminate t))) (with-pinned-objects (template-buffer) (let ((fd (alien-funcall (extern-alien "sb_mkstemp" (function int (* char) int)) (vector-sap template-buffer) mode))) (if (minusp fd) (values nil (get-errno)) (values #-win32 fd #+win32 (sb-win32::duplicate-and-unwrap-fd fd) (octets-to-string template-buffer))))))) ;;;; resourcebits.h (defconstant rusage_self 0) ; the calling process (defconstant rusage_children -1) ; terminated child processes (defconstant rusage_both -2) (define-alien-type nil (struct rusage (ru-utime (struct timeval)) ; user time used (ru-stime (struct timeval)) ; system time used. (ru-maxrss long) ; maximum resident set size (in kilobytes) (ru-ixrss long) ; integral shared memory size (ru-idrss long) ; integral unshared data size (ru-isrss long) ; integral unshared stack size (ru-minflt long) ; page reclaims (ru-majflt long) ; page faults (ru-nswap long) ; swaps (ru-inblock long) ; block input operations (ru-oublock long) ; block output operations (ru-msgsnd long) ; messages sent (ru-msgrcv long) ; messages received (ru-nsignals long) ; signals received (ru-nvcsw long) ; voluntary context switches (ru-nivcsw long))) ; involuntary context switches ;;;; unistd.h Given a file path ( a string ) and one of four constant modes , ;;; return T if the file is accessible with that mode and NIL if not. When NIL , also return an errno value with NIL which tells why the ;;; file was not accessible. ;;; ;;; The access modes are: ;;; r_ok Read permission. ;;; w_ok Write permission. ;;; x_ok Execute permission. ;;; f_ok Presence of file. In Windows , the MODE argument to access is defined in terms of literal magic numbers --- there are no constants to grovel . ;;; is not defined. #+win32 (progn (defconstant f_ok 0) (defconstant w_ok 2) (defconstant r_ok 4)) (defun unix-access (path mode) (declare (type unix-pathname path) (type (mod 8) mode)) (void-syscall ("[_]access" c-string int) path mode)) values for the second argument to UNIX - LSEEK Note that nowadays these are called SEEK_SET , SEEK_CUR , and SEEK_END (defconstant l_set 0) ; to set the file pointer (defconstant l_incr 1) ; to increment the file pointer (defconstant l_xtnd 2) ; to extend the file size off_t is 32 bit on Windows , yet our functions support 64 bit seeks . (define-alien-type unix-offset #-win32 off-t #+win32 (signed 64)) ;;; Is a stream interactive? (defun unix-isatty (fd) (declare (type unix-fd fd)) #-win32 (int-syscall ("isatty" int) fd) #+win32 (sb-win32::windows-isatty fd)) (defun unix-lseek (fd offset whence) "Unix-lseek accepts a file descriptor and moves the file pointer by OFFSET octets. Whence can be any of the following: L_SET Set the file pointer. L_INCR Increment the file pointer. L_XTND Extend the file size. " (declare (type unix-fd fd) (type (integer 0 2) whence)) (let ((result #-win32 (alien-funcall (extern-alien #-largefile "lseek" #+largefile "lseek_largefile" (function off-t int off-t int)) fd offset whence) #+win32 (sb-win32:lseeki64 fd offset whence))) (if (minusp result) (values nil (get-errno)) (values result 0)))) ;;; UNIX-READ accepts a file descriptor, a buffer, and the length to read. ;;; It attempts to read len bytes from the device associated with fd ;;; and store them into the buffer. It returns the actual number of ;;; bytes read. (declaim (maybe-inline unix-read)) (defun unix-read (fd buf len) (declare (type unix-fd fd) (type (unsigned-byte 32) len)) (int-syscall (#-win32 "read" #+win32 "win32_unix_read" int (* char) int) fd buf len)) ;;; UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the ;;; length to write. It attempts to write len bytes to the device ;;; associated with fd from the buffer starting at offset. It returns ;;; the actual number of bytes written. (defun unix-write (fd buf offset len) : change 60fa88b187e438cc made this function unusable in cold - init if compiled with # + sb - show ( which increases DEBUG to 2 ) because of full calls to SB - ALIEN - INTERNALS : DEPORT - ALLOC and DEPORT . (declare (optimize (debug 1))) (declare (type unix-fd fd) (type (unsigned-byte 32) offset len)) (flet ((%write (sap) (declare (system-area-pointer sap)) (int-syscall (#-win32 "write" #+win32 "win32_unix_write" int (* char) int) fd (with-alien ((ptr (* char) sap)) (addr (deref ptr offset))) len))) (etypecase buf ((simple-array * (*)) (with-pinned-objects (buf) (%write (vector-sap buf)))) (system-area-pointer (%write buf))))) ;;; Set up a unix-piping mechanism consisting of an input pipe and an output pipe . Return two values : if no error occurred the first value is the pipe to be read from and the second is can be written to . If an error occurred the first value is NIL and the second the ;;; unix error code. #-win32 (defun unix-pipe () (with-alien ((fds (array int 2))) (syscall ("pipe" (* int)) (values (deref fds 0) (deref fds 1)) (cast fds (* int))))) #+win32 (defun unix-pipe () (sb-win32::windows-pipe)) Windows mkdir ( ) does n't take the mode argument . It 's cdecl , so we could ;; actually call it passing the mode argument, but some sharp-eyed reader would put five and twenty - seven together and ask us about it , so ... -- AB , 2005 - 12 - 27 #-win32 (defun unix-mkdir (name mode) (declare (type unix-pathname name) (type unix-file-mode mode)) (void-syscall ("mkdir" c-string int) name mode)) ;;; Given a C char* pointer allocated by malloc(), free it and return a ;;; corresponding Lisp string (or return NIL if the pointer is a C NULL). (defun newcharstar-string (newcharstar) (declare (type (alien (* char)) newcharstar)) (if (null-alien newcharstar) nil (prog1 (cast newcharstar c-string) (free-alien newcharstar)))) ;;; Return the Unix current directory as a SIMPLE-STRING, in the style returned by ( ) ( no trailing slash character ) . #-win32 (defun posix-getcwd () This implementation relies on a BSD / Linux extension to getcwd ( ) ;; behavior, automatically allocating memory when a null buffer ;; pointer is used. On a system which doesn't support that ;; extension, it'll have to be rewritten somehow. ;; ;; SunOS and OSF/1 provide almost as useful an extension: if given a null ;; buffer pointer, it will automatically allocate size space. The ;; KLUDGE in this solution arises because we have just read off PATH_MAX+1 from the Solaris header files and stuck it in here as ;; a constant. Going the grovel_headers route doesn't seem to be helpful , either , as Solaris does n't export PATH_MAX from ;; unistd.h. ;; Signal an error at compile - time , since it 's needed for the ;; runtime to start up #-(or android linux openbsd freebsd netbsd sunos darwin dragonfly haiku) #.(error "POSIX-GETCWD is not implemented.") (or #+(or linux openbsd freebsd netbsd sunos darwin dragonfly haiku) (newcharstar-string (alien-funcall (extern-alien "getcwd" (function (* char) (* char) size-t)) nil #+(or linux openbsd freebsd netbsd darwin dragonfly haiku) 0 #+(or sunos) 1025)) #+android (with-alien ((ptr (array char #.path-max))) ;; Older bionic versions do not have the above feature. (alien-funcall (extern-alien "getcwd" (function c-string (array char #.path-max) int)) ptr path-max)) (simple-perror "getcwd"))) ;;; Return the Unix current directory as a SIMPLE-STRING terminated ;;; by a slash character. (defun posix-getcwd/ () (concatenate 'string (posix-getcwd) "/")) Duplicate an existing file descriptor ( given as the argument ) and return it . If FD is not a valid file descriptor , NIL and an error ;;; number are returned. #-win32 (defun unix-dup (fd) (declare (type unix-fd fd)) (int-syscall ("dup" int) fd)) ;;; Terminate the current process with an optional error code. If ;;; successful, the call doesn't return. If unsuccessful, the call returns NIL and an error number . (deftype exit-code () `(signed-byte 32)) (defun os-exit (code &key abort) "Exit the process with CODE. If ABORT is true, exit is performed using _exit(2), avoiding atexit(3) hooks, etc. Otherwise exit(2) is called." (unless (typep code 'exit-code) (setf code (if abort 1 0))) (if abort (void-syscall ("_exit" int) code) (void-syscall ("exit" int) code))) (define-deprecated-function :early "1.0.56.55" unix-exit os-exit (code) (os-exit code)) ;;; Return the process id of the current process. (define-alien-routine (#+win32 "_getpid" #-win32 "getpid" unix-getpid) int) ;;; Return the real user id associated with the current process. #-win32 (define-alien-routine ("getuid" unix-getuid) int) ;;; Translate a user id into a login name. #-win32 (defun uid-username (uid) (or (newcharstar-string (alien-funcall (extern-alien "uid_username" (function (* char) int)) uid)) (error "found no match for Unix uid=~S" uid))) ;;; Return the namestring of the home directory, being careful to include a trailing # \/ #-win32 (progn (defun uid-homedir (uid) (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir" (function (* char) int)) uid)) (error "failed to resolve home directory for Unix uid=~S" uid))) (defun user-homedir (uid) (or (newcharstar-string (alien-funcall (extern-alien "user_homedir" (function (* char) c-string)) uid)) (error "failed to resolve home directory for Unix uid=~S" uid)))) ;;; Invoke readlink(2) on the file name specified by PATH. Return ;;; (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on ;;; failure. #-win32 (defun unix-readlink (path) (declare (type unix-pathname path)) (with-alien ((ptr (* char) (alien-funcall (extern-alien "wrapped_readlink" (function (* char) c-string)) path))) (if (null-alien ptr) (values nil (get-errno)) (multiple-value-prog1 (values (with-alien ((c-string c-string ptr)) c-string) nil) (free-alien ptr))))) #+win32 ;; Win32 doesn't do links, but something likes to call this anyway. Something in this file , no less . But it only takes one result , so ... (defun unix-readlink (path) (declare (ignore path)) nil) (defun unix-realpath (path) (declare (type unix-pathname path)) (with-alien ((ptr (* char) (alien-funcall (extern-alien "sb_realpath" (function (* char) c-string)) path))) (if (null-alien ptr) (values nil (get-errno)) (multiple-value-prog1 (values (with-alien ((c-string c-string ptr)) c-string) nil) (free-alien ptr))))) ;;; UNIX-UNLINK accepts a name and deletes the directory entry for that ;;; name and the file if this is the last link. (defun unix-unlink (name) (declare (type unix-pathname name)) (void-syscall ("[_]unlink" c-string) name)) ;;; Return the name of the host machine as a string. #-win32 (defun unix-gethostname () (with-alien ((buf (array char 256))) (syscall ("gethostname" (* char) int) (cast buf c-string) (cast buf (* char)) 256))) #-win32 (defun unix-setsid () (int-syscall ("setsid"))) ;;;; sys/ioctl.h ;;; UNIX-IOCTL performs a variety of operations on open i/o descriptors . See the UNIX Programmer 's Manual for more ;;; information. #-win32 (defun unix-ioctl (fd cmd arg) (declare (type unix-fd fd) (type word cmd)) (void-syscall ("ioctl" int unsigned-long (* char)) fd cmd arg)) sys / resource.h ;;; Return information about the resource usage of the process specified by WHO . WHO can be either the current process ;;; (rusage_self) or all of the terminated child processes ;;; (rusage_children). NIL and an error number is returned if the call ;;; fails. #-win32 (defun unix-getrusage (who) (with-alien ((usage (struct rusage))) (syscall ("sb_getrusage" int (* (struct rusage))) (values t (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000) (slot (slot usage 'ru-utime) 'tv-usec)) (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000) (slot (slot usage 'ru-stime) 'tv-usec)) (slot usage 'ru-maxrss) (slot usage 'ru-ixrss) (slot usage 'ru-idrss) (slot usage 'ru-isrss) (slot usage 'ru-minflt) (slot usage 'ru-majflt) (slot usage 'ru-nswap) (slot usage 'ru-inblock) (slot usage 'ru-oublock) (slot usage 'ru-msgsnd) (slot usage 'ru-msgrcv) (slot usage 'ru-nsignals) (slot usage 'ru-nvcsw) (slot usage 'ru-nivcsw)) who (addr usage)))) (defvar *on-dangerous-wait* :warn) ;;; Calling select in a bad place can hang in a nasty manner, so it's better ;;; to have some way to detect these. (defun note-dangerous-wait (type) (let ((action *on-dangerous-wait*) (*on-dangerous-wait* nil)) (case action (:warn (warn "Starting a ~A without a timeout while interrupts are ~ disabled." type)) (:error (error "Starting a ~A without a timeout while interrupts are ~ disabled." type)) (:backtrace (format *debug-io* "~&=== Starting a ~A without a timeout while interrupts are disabled. ===~%" type) (sb-debug:print-backtrace))) nil)) ;;;; poll.h #+os-provides-poll (progn (define-alien-type nil (struct pollfd (fd int) (events short) ; requested events (revents short))) ; returned events (declaim (inline unix-poll)) (defun unix-poll (pollfds nfds to-msec) (declare (fixnum nfds to-msec)) (when (and (minusp to-msec) (not *interrupts-enabled*)) (note-dangerous-wait "poll(2)")) ;; FAST-SELECT doesn't use WITH-RESTARTED-SYSCALL so this doesn't either (int-syscall ("poll" (* (struct pollfd)) int int) (alien-sap pollfds) nfds to-msec)) ;; "simple" poll operates on a single descriptor only (defun unix-simple-poll (fd direction to-msec) (declare (fixnum fd to-msec)) (when (and (minusp to-msec) (not *interrupts-enabled*)) (note-dangerous-wait "poll(2)")) (let ((events (ecase direction (:input (logior pollin pollpri)) (:output pollout)))) (with-alien ((fds (struct pollfd))) (with-restarted-syscall (count errno) (progn (setf (slot fds 'fd) fd (slot fds 'events) events (slot fds 'revents) 0) (int-syscall ("poll" (* (struct pollfd)) int int) (addr fds) 1 to-msec)) (if (zerop errno) (let ((revents (slot fds 'revents))) (or (and (eql 1 count) (logtest events revents)) (logtest pollhup revents))) (error "Syscall poll(2) failed: ~A" (strerror)))))))) ;;;; sys/select.h (defmacro with-fd-setsize ((n) &body body) `(let ((,n (if (< 0 ,n fd-setsize) ,n (error "Cannot select(2) on ~D: above FD_SETSIZE limit." (1- ,n))))) (declare (type (integer 0 #.fd-setsize) ,n)) ,@body)) ;;; Perform the UNIX select(2) system call. (declaim (inline unix-fast-select)) (defun unix-fast-select (num-descriptors read-fds write-fds exception-fds timeout-secs timeout-usecs) (declare (type integer num-descriptors) (type (or (alien (* (struct fd-set))) null) read-fds write-fds exception-fds) (type (or null (unsigned-byte 31)) timeout-secs timeout-usecs)) (with-fd-setsize (num-descriptors) (flet ((select (tv-sap) (int-syscall ("sb_select" int (* (struct fd-set)) (* (struct fd-set)) (* (struct fd-set)) (* (struct timeval))) num-descriptors read-fds write-fds exception-fds tv-sap))) (cond ((or timeout-secs timeout-usecs) (with-alien ((tv (struct timeval))) (setf (slot tv 'tv-sec) (or timeout-secs 0)) (setf (slot tv 'tv-usec) (or timeout-usecs 0)) (select (alien-sap (addr tv))))) (t (unless *interrupts-enabled* (note-dangerous-wait "select(2)")) (select (int-sap 0))))))) ;;; Lisp-side implementations of FD_FOO macros. (declaim (inline fd-set fd-clr fd-isset fd-zero)) (defun fd-set (offset fd-set) (multiple-value-bind (word bit) (floor offset sb-vm:n-machine-word-bits) (setf (deref (slot fd-set 'fds-bits) word) (logior (truly-the (unsigned-byte #.sb-vm:n-machine-word-bits) (ash 1 bit)) (deref (slot fd-set 'fds-bits) word))))) (defun fd-clr (offset fd-set) (multiple-value-bind (word bit) (floor offset sb-vm:n-machine-word-bits) (setf (deref (slot fd-set 'fds-bits) word) (logand (deref (slot fd-set 'fds-bits) word) (sb-kernel:word-logical-not (truly-the (unsigned-byte #.sb-vm:n-machine-word-bits) (ash 1 bit))))))) (defun fd-isset (offset fd-set) (multiple-value-bind (word bit) (floor offset sb-vm:n-machine-word-bits) (logbitp bit (deref (slot fd-set 'fds-bits) word)))) (defun fd-zero (fd-set) (loop for index below (/ fd-setsize sb-vm:n-machine-word-bits) do (setf (deref (slot fd-set 'fds-bits) index) 0))) #-os-provides-poll (defun unix-simple-poll (fd direction to-msec) (multiple-value-bind (to-sec to-usec) (if (minusp to-msec) (values nil nil) (multiple-value-bind (to-sec to-msec2) (truncate to-msec 1000) (values to-sec (* to-msec2 1000)))) (with-restarted-syscall (count errno) (with-alien ((fds (struct fd-set))) (fd-zero fds) (fd-set fd fds) (multiple-value-bind (read-fds write-fds) (ecase direction (:input (values (addr fds) nil)) (:output (values nil (addr fds)))) (unix-fast-select (1+ fd) read-fds write-fds nil to-sec to-usec))) (case count ((1) t) ((0) nil) (otherwise (error "Syscall select(2) failed on fd ~D: ~A" fd (strerror))))))) ;;;; sys/stat.h This is a structure defined in src / runtime / wrap.c , to look ;;; basically like "struct stat" according to stat(2). It may not ;;; actually correspond to the real in-memory stat structure that the ;;; syscall uses, and that's OK. Linux in particular is packed full of ;;; stat macros, and trying to keep Lisp code in correspondence with ;;; it is more pain than it's worth, so we just let our C runtime ;;; synthesize a nice consistent structure for us. ;;; Note that st - dev is a long , not a dev - t. This is because dev - t on linux 32 bit is a 64 bit quantity , but alien does n't support ;;; those. We don't actually access that field anywhere, though, so until we can get 64 bit alien support it 'll do . Also note that st_size is a long , not an off - t , because off - t is a 64 - bit quantity on Alpha . And FIXME : " No one would want a file length longer than 32 bits anyway , right?":-| ;;; The comment about alien and 64 - bit quantities has not been kept in ;;; sync with the comment now in wrap.h (formerly wrap.c), but it's not clear whether either comment is correct . -- RMK 2007 - 11 - 14 . (define-alien-type nil (struct wrapped_stat (st-dev wst-dev-t) (st-ino wst-ino-t) (st-mode mode-t) (st-nlink wst-nlink-t) (st-uid wst-uid-t) (st-gid wst-gid-t) (st-rdev wst-dev-t) (st-size wst-off-t) (st-blksize wst-blksize-t) (st-blocks wst-blkcnt-t) (st-atime time-t) (st-mtime time-t) (st-ctime time-t))) ;;; shared C-struct-to-multiple-VALUES conversion for the stat(2) ;;; family of Unix system calls ;;; ;;; FIXME: I think this should probably not be INLINE. However, when ;;; this was not inline, it seemed to cause memory corruption problems . My first guess is that it 's a bug in the FFI code , where ;;; the WITH-ALIEN expansion doesn't deal well with being wrapped around a call to a function returning > 10 values . But I did n't try ;;; to figure it out, just inlined it as a quick fix. Perhaps someone who 's motivated to debug the FFI code can go over the DISASSEMBLE ;;; output in the not-inlined case and see whether there's a problem, ;;; and maybe even find a fix.. (declaim (inline %extract-stat-results)) (defun %extract-stat-results (wrapped-stat) (declare (type (alien (* (struct wrapped_stat))) wrapped-stat)) (values t (slot wrapped-stat 'st-dev) (slot wrapped-stat 'st-ino) (slot wrapped-stat 'st-mode) (slot wrapped-stat 'st-nlink) (slot wrapped-stat 'st-uid) (slot wrapped-stat 'st-gid) (slot wrapped-stat 'st-rdev) (slot wrapped-stat 'st-size) (slot wrapped-stat 'st-atime) (slot wrapped-stat 'st-mtime) (slot wrapped-stat 'st-ctime) (slot wrapped-stat 'st-blksize) (slot wrapped-stat 'st-blocks))) ;;; Unix system calls in the stat(2) family are handled by calls to ;;; C-level wrapper functions which copy all the raw "struct stat" ;;; slots into the system-independent wrapped_stat format. ;;; stat(2) <-> stat_wrapper() ;;; fstat(2) <-> fstat_wrapper() ;;; lstat(2) <-> lstat_wrapper() (defun unix-stat (name) (declare (type unix-pathname name)) (with-alien ((buf (struct wrapped_stat))) (syscall ("stat_wrapper" c-string (* (struct wrapped_stat))) (%extract-stat-results (addr buf)) name (addr buf)))) (defun unix-lstat (name) (declare (type unix-pathname name)) (with-alien ((buf (struct wrapped_stat))) (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat))) (%extract-stat-results (addr buf)) name (addr buf)))) (defun unix-fstat (fd) #-win32 (declare (type unix-fd fd)) (#-win32 funcall #+win32 sb-win32::call-with-crt-fd (lambda (fd) (with-alien ((buf (struct wrapped_stat))) (syscall ("fstat_wrapper" int (* (struct wrapped_stat))) (%extract-stat-results (addr buf)) fd (addr buf)))) fd)) #-win32 (defun fd-type (fd) (declare (type unix-fd fd)) (let ((mode (or (with-alien ((buf (struct wrapped_stat))) (syscall ("fstat_wrapper" int (* (struct wrapped_stat))) (slot buf 'st-mode) fd (addr buf))) 0))) (case (logand mode s-ifmt) (#.s-ifchr :character) (#.s-ifdir :directory) (#.s-ifblk :block) (#.s-ifreg :regular) (#.s-ifsock :socket) (#.s-iflnk :link) (#.s-ififo :fifo) (t :unknown)))) ;;;; time.h ;; used by other time functions (define-alien-type nil (struct tm Seconds . [ 0 - 60 ] ( 1 leap second ) Minutes . [ 0 - 59 ] Hours . [ 0 - 23 ] Day . [ 1 - 31 ] Month . [ 0 - 11 ] Year - 1900 . Day of week . [ 0 - 6 ] Days in year . [ 0 - 365 ] DST . [ -1/0/1 ] (tm-gmtoff long) ; Seconds east of UTC. Timezone abbreviation . (define-alien-routine get-timezone int (when time-t) : the runtime ` boolean ' is defined as ` int ' , but the alien ;; type is N-WORD-BITS wide. (daylight-savings-p (boolean 32) :out)) #-win32 (defun nanosleep (secs nsecs) (alien-funcall (extern-alien "sb_nanosleep" (function int time-t int)) secs nsecs) nil) #-win32 (defun nanosleep-double (seconds) (alien-funcall (extern-alien "sb_nanosleep_double" (function (values) double)) seconds) nil) #-win32 (defun nanosleep-float (seconds) (alien-funcall (extern-alien "sb_nanosleep_float" (function (values) float)) seconds) nil) ;;;; sys/time.h Structure crudely representing a timezone . : This is ;;; obsolete and should never be used. (define-alien-type nil (struct timezone minutes west of Greenwich (tz-dsttime int))) ; type of dst correction Type of the second argument to ` getitimer ' and the second and third arguments ` setitimer ' . (define-alien-type nil (struct itimerval (it-interval (struct timeval)) ; timer interval (it-value (struct timeval)))) ; current value (defconstant itimer-real 0) (defconstant itimer-virtual 1) (defconstant itimer-prof 2) #-win32 (defun unix-getitimer (which) "UNIX-GETITIMER returns the INTERVAL and VALUE slots of one of three system timers (:real :virtual or :profile). On success, unix-getitimer returns 5 values, T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec." (declare (type (member :real :virtual :profile) which) (values t unsigned-byte (mod 1000000) unsigned-byte (mod 1000000))) (let ((which (ecase which (:real itimer-real) (:virtual itimer-virtual) (:profile itimer-prof)))) (with-alien ((itv (struct itimerval))) (syscall* ("sb_getitimer" int (* (struct itimerval))) (values t (slot (slot itv 'it-interval) 'tv-sec) (slot (slot itv 'it-interval) 'tv-usec) (slot (slot itv 'it-value) 'tv-sec) (slot (slot itv 'it-value) 'tv-usec)) which (alien-sap (addr itv)))))) #-win32 (defun unix-setitimer (which int-secs int-usec val-secs val-usec) "UNIX-SETITIMER sets the INTERVAL and VALUE slots of one of three system timers (:real :virtual or :profile). A SIGALRM, SIGVTALRM, or SIGPROF respectively will be delivered in VALUE <seconds+microseconds> from now. INTERVAL, when non-zero, is reloaded into the timer on each expiration. Setting VALUE to zero disables the timer. See the Unix man page for more details. On success, unix-setitimer returns the old contents of the INTERVAL and VALUE slots as in unix-getitimer." (declare (type (member :real :virtual :profile) which) (type unsigned-byte int-secs val-secs) (type (integer 0 (1000000)) int-usec val-usec) (values t unsigned-byte (mod 1000000) unsigned-byte (mod 1000000))) (let ((which (ecase which (:real itimer-real) (:virtual itimer-virtual) (:profile itimer-prof)))) (with-alien ((itvn (struct itimerval)) (itvo (struct itimerval))) (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs (slot (slot itvn 'it-interval) 'tv-usec) int-usec (slot (slot itvn 'it-value ) 'tv-sec ) val-secs (slot (slot itvn 'it-value ) 'tv-usec) val-usec) (syscall* ("sb_setitimer" int (* (struct timeval)) (* (struct timeval))) (values t (slot (slot itvo 'it-interval) 'tv-sec) (slot (slot itvo 'it-interval) 'tv-usec) (slot (slot itvo 'it-value) 'tv-sec) (slot (slot itvo 'it-value) 'tv-usec)) which (alien-sap (addr itvn)) (alien-sap (addr itvo)))))) ;;; FIXME: Many Unix error code definitions were deleted from the old CMU CL source code here , but not in the exports of SB - UNIX . I ( WHN ) hope that someday I 'll figure out an automatic way to detect ;;; unused symbols in package exports, but if I don't, there are enough of them all in one place here that they should probably be ;;; removed by hand. (defconstant microseconds-per-internal-time-unit (/ 1000000 internal-time-units-per-second)) (defconstant nanoseconds-per-internal-time-unit (* microseconds-per-internal-time-unit 1000)) UNIX specific code , that has been cleanly separated from the Windows build . #-win32 (progn (declaim (inline clock-gettime)) (defun clock-gettime (clockid) (declare (type (signed-byte 32) clockid)) (with-alien ((ts (struct timespec))) (alien-funcall (extern-alien #.(libc-name-for "sb_clock_gettime") (function int int (* (struct timespec)))) clockid (addr ts)) ' seconds ' is definitely a fixnum for 64 - bit , because most - positive - fixnum can express 1E11 years in seconds . (values #+64-bit (truly-the fixnum (slot ts 'tv-sec)) #-64-bit (slot ts 'tv-sec) (truly-the (integer 0 #.(expt 10 9)) (slot ts 'tv-nsec))))) (declaim (inline get-time-of-day)) (defun get-time-of-day () "Return the number of seconds and microseconds since the beginning of the UNIX epoch (January 1st 1970.)" (with-alien ((tv (struct timeval))) (syscall* ("sb_gettimeofday" (* (struct timeval)) system-area-pointer) (values (slot tv 'tv-sec) (slot tv 'tv-usec)) (addr tv) (int-sap 0)))) The " optimizations that actually matter " do n't actually matter for 64 - bit . Microseconds can express at least 1E5 years of uptime : ( float ( / most - positive - fixnum ( * 1000000 60 60 24 ( + 365 1/4 ) ) ) ) ;; = microseconds-per-second * seconds-per-minute * minutes-per-hour ;; * hours-per-day * days-per-year (defun get-internal-real-time () (with-alien ((base (struct timespec) :extern "lisp_init_time")) (multiple-value-bind (c-sec c-nsec) ;; By scaling down we end up with far less resolution than clock-realtime offers , and COARSE is about twice as fast , so use that , but only for linux . BSD has something similar . (clock-gettime #+linux clock-monotonic-coarse #-linux clock-monotonic) I know that my math is valid for 64 - bit . (declare (optimize (sb-c::type-check 0))) #+64-bit (let ((delta-sec (the fixnum (- c-sec (the fixnum (slot base 'tv-sec))))) (delta-nsec (the fixnum (- c-nsec (the fixnum (slot base 'tv-nsec)))))) (the sb-kernel:internal-time (+ (the fixnum (* delta-sec internal-time-units-per-second)) (truncate delta-nsec nanoseconds-per-internal-time-unit)))) There are two optimizations here that actually matter on 32 - bit systems : ( 1 ) subtract the epoch from seconds and milliseconds separately , ( 2 ) avoid consing a new bignum if the result is unchanged . ;; Thanks to for the optimization hint . ;; ;; Yes, it is possible to a computation to be GET-INTERNAL-REAL-TIME ;; bound. ;; ;; --NS 2007-04-05 #-64-bit (symbol-macrolet ((observed-sec (sb-thread::thread-observed-internal-real-time-delta-sec thr)) (observed-msec (sb-thread::thread-observed-internal-real-time-delta-millisec thr)) (time (sb-thread::thread-internal-real-time thr))) (let* ((delta-sec (- c-sec (slot base 'tv-sec))) ;; I inadvertently had too many THE casts in here, so I'd prefer to err on the side of caution rather than cause GC lossage ( which I accidentally did ) . So assert that nanoseconds are < = 10 ^ 9 ;; and the compiler will do as best it can with that information. (delta-nsec (- c-nsec (the (integer 0 #.(expt 10 9)) (slot base 'tv-nsec)))) ;; ROUND, FLOOR? Who cares, it's a number that's going to change. ;; More math = more self-induced jitter. (delta-millisec (floor delta-nsec 1000000)) (thr sb-thread:*current-thread*)) (if (and (= delta-sec observed-sec) (= delta-millisec observed-msec)) time (let ((current (+ (* delta-sec internal-time-units-per-second) ASSUMPTION : delta - millisec = delta-millisec))) (setf time current observed-msec delta-millisec observed-sec delta-sec) current))))))) (declaim (inline system-internal-run-time)) #-sunos ; defined in sunos-os (defun system-internal-run-time () (multiple-value-bind (sec nsec) (clock-gettime clock-process-cputime-id) (+ (* sec internal-time-units-per-second) (floor (+ nsec (floor nanoseconds-per-internal-time-unit 2)) nanoseconds-per-internal-time-unit))))) FIXME , : GET - TIME - OF - DAY used to be UNIX - GETTIMEOFDAY , and had a ;;; primary return value indicating sucess, and also returned timezone information -- though the timezone data was not there on . Now we have GET - TIME - OF - DAY , but it turns out that despite SB - UNIX being ;;; an implementation package UNIX-GETTIMEOFDAY has users in the wild. ;;; So we're stuck with it for a while -- maybe delete it towards the end of 2009 . (defun unix-gettimeofday () #+win32 (declare (notinline get-time-of-day)) ; forward ref (multiple-value-bind (sec usec) (get-time-of-day) (values t sec usec nil nil))) opendir , , and dirent - name (declaim (inline unix-opendir)) (defun unix-opendir (namestring &optional (errorp t)) (let ((dir (alien-funcall (extern-alien "sb_opendir" (function system-area-pointer c-string)) namestring))) (if (zerop (sap-int dir)) (when errorp (simple-perror (format nil "Error opening directory ~S" namestring))) dir))) (declaim (inline unix-readdir)) (defun unix-readdir (dir &optional (errorp t) namestring) (let ((ent (alien-funcall (extern-alien "sb_readdir" (function system-area-pointer system-area-pointer)) dir)) errno) (if (zerop (sap-int ent)) (when (and errorp (not (zerop (setf errno (get-errno))))) (simple-perror (format nil "Error reading directory entry~@[ from ~S~]" namestring) :errno errno)) ent))) (declaim (inline unix-closedir)) (defun unix-closedir (dir &optional (errorp t) namestring) (let ((r (alien-funcall (extern-alien "sb_closedir" (function int system-area-pointer)) dir))) (if (minusp r) (when errorp (simple-perror (format nil "Error closing directory~@[ ~S~]" namestring))) r))) (declaim (inline unix-dirent-name)) (defun unix-dirent-name (ent) (alien-funcall (extern-alien "sb_dirent_name" (function c-string system-area-pointer)) ent))
null
https://raw.githubusercontent.com/sbcl/sbcl/22398b178e11533aeeb38c3c1253a75d62cde103/src/code/unix.lisp
lisp
files aspired to be complete Unix interfaces exported to the end user, while this file aims to be as simple as possible and is not intended for the end user. transcriptions from Unix headers into Lisp. It appears that this was as unmaintainable in practice as you'd expect in theory, so I really really don't want to do that. It'd be good to implement the various system calls as C code implemented using the Unix header files, and have their int" which are already in the interface between the runtime more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. corresponding Lisp-level list of SIMPLE-STRINGs. Lisp types used by syscalls system calls This function takes a possibly-wrapped C name and strips off "sb_" if it doesn't need a wrapper. The list of functions that can be called directly is listed explicitly, because there are also others that might want to be wrapped even if they don't need to be, syscall* syscall* int-syscall syscall* syscall* alien-funcall posix This is like SYSCALL, but if it fails, signal an error instead of returning error codes. Should only be used for syscalls that will never really get an error. hacking the Unix environment error code is returned if an error occurs. FIXME: We shouldn't hand-copy types from header files into Lisp like this unless we have extreme provocation. Reading directories is not extreme enough, since it doesn't need to be blindingly fast: we can just implement those functions in C as a wrapper layer. fcntl.h Open the file whose pathname is specified by PATH for reading masks (O_RDONLY etc.) are defined in fcntlbits.h. permission of argument MODE if the file doesn't exist. An integer UNIX-CLOSE accepts a file descriptor and attempts to close the file associated with it. stdlib.h There are good reasons to implement some OPEN options with an mkstemp(3)-like routine, but we don't do that yet. Instead, this function is used only to make a temporary file for RUN-PROGRAM. SUSv3 mkstemp() doesn't specify the mode of the created file and specification by taking a mode to use when creating the new file. resourcebits.h the calling process terminated child processes user time used system time used. maximum resident set size (in kilobytes) integral shared memory size integral unshared data size integral unshared stack size page reclaims page faults swaps block input operations block output operations messages sent messages received signals received voluntary context switches involuntary context switches unistd.h return T if the file is accessible with that mode and NIL if not. file was not accessible. The access modes are: r_ok Read permission. w_ok Write permission. x_ok Execute permission. f_ok Presence of file. is not defined. to set the file pointer to increment the file pointer to extend the file size Is a stream interactive? UNIX-READ accepts a file descriptor, a buffer, and the length to read. It attempts to read len bytes from the device associated with fd and store them into the buffer. It returns the actual number of bytes read. UNIX-WRITE accepts a file descriptor, a buffer, an offset, and the length to write. It attempts to write len bytes to the device associated with fd from the buffer starting at offset. It returns the actual number of bytes written. Set up a unix-piping mechanism consisting of an input pipe and an unix error code. actually call it passing the mode argument, but some sharp-eyed reader Given a C char* pointer allocated by malloc(), free it and return a corresponding Lisp string (or return NIL if the pointer is a C NULL). Return the Unix current directory as a SIMPLE-STRING, in the behavior, automatically allocating memory when a null buffer pointer is used. On a system which doesn't support that extension, it'll have to be rewritten somehow. SunOS and OSF/1 provide almost as useful an extension: if given a null buffer pointer, it will automatically allocate size space. The KLUDGE in this solution arises because we have just read off a constant. Going the grovel_headers route doesn't seem to be unistd.h. runtime to start up Older bionic versions do not have the above feature. Return the Unix current directory as a SIMPLE-STRING terminated by a slash character. number are returned. Terminate the current process with an optional error code. If successful, the call doesn't return. If unsuccessful, the call Return the process id of the current process. Return the real user id associated with the current process. Translate a user id into a login name. Return the namestring of the home directory, being careful to Invoke readlink(2) on the file name specified by PATH. Return (VALUES LINKSTRING NIL) on success, or (VALUES NIL ERRNO) on failure. Win32 doesn't do links, but something likes to call this anyway. UNIX-UNLINK accepts a name and deletes the directory entry for that name and the file if this is the last link. Return the name of the host machine as a string. sys/ioctl.h UNIX-IOCTL performs a variety of operations on open i/o information. Return information about the resource usage of the process (rusage_self) or all of the terminated child processes (rusage_children). NIL and an error number is returned if the call fails. Calling select in a bad place can hang in a nasty manner, so it's better to have some way to detect these. poll.h requested events returned events FAST-SELECT doesn't use WITH-RESTARTED-SYSCALL so this doesn't either "simple" poll operates on a single descriptor only sys/select.h Perform the UNIX select(2) system call. Lisp-side implementations of FD_FOO macros. sys/stat.h basically like "struct stat" according to stat(2). It may not actually correspond to the real in-memory stat structure that the syscall uses, and that's OK. Linux in particular is packed full of stat macros, and trying to keep Lisp code in correspondence with it is more pain than it's worth, so we just let our C runtime synthesize a nice consistent structure for us. those. We don't actually access that field anywhere, though, so sync with the comment now in wrap.h (formerly wrap.c), but it's shared C-struct-to-multiple-VALUES conversion for the stat(2) family of Unix system calls FIXME: I think this should probably not be INLINE. However, when this was not inline, it seemed to cause memory corruption the WITH-ALIEN expansion doesn't deal well with being wrapped to figure it out, just inlined it as a quick fix. Perhaps someone output in the not-inlined case and see whether there's a problem, and maybe even find a fix.. Unix system calls in the stat(2) family are handled by calls to C-level wrapper functions which copy all the raw "struct stat" slots into the system-independent wrapped_stat format. stat(2) <-> stat_wrapper() fstat(2) <-> fstat_wrapper() lstat(2) <-> lstat_wrapper() time.h used by other time functions Seconds east of UTC. type is N-WORD-BITS wide. sys/time.h obsolete and should never be used. type of dst correction timer interval current value FIXME: Many Unix error code definitions were deleted from the old unused symbols in package exports, but if I don't, there are removed by hand. = microseconds-per-second * seconds-per-minute * minutes-per-hour * hours-per-day * days-per-year By scaling down we end up with far less resolution than clock-realtime Yes, it is possible to a computation to be GET-INTERNAL-REAL-TIME bound. --NS 2007-04-05 I inadvertently had too many THE casts in here, so I'd prefer and the compiler will do as best it can with that information. ROUND, FLOOR? Who cares, it's a number that's going to change. More math = more self-induced jitter. defined in sunos-os primary return value indicating sucess, and also returned timezone an implementation package UNIX-GETTIMEOFDAY has users in the wild. So we're stuck with it for a while -- maybe delete it towards the end forward ref
This file contains Unix support that SBCL needs to implement itself . It 's derived from unix-glibc2.lisp for CMU CL , which was derived from CMU CL unix.lisp 1.56 . But those FIXME : The old CMU CL unix.lisp code was implemented as hand interface back to SBCL code be characterized by things like " 32 - bit - wide executable and the SBCL lisp code . This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB-UNIX") (/show0 "unix.lisp 21") Given a C - level zero - terminated array of C strings , return a (defun c-strings->string-list (c-strings) (declare (type (alien (* c-string)) c-strings)) (let ((reversed-result nil)) (dotimes (i most-positive-fixnum) (declare (type index i)) (let ((c-string (deref c-strings i))) (if c-string (push c-string reversed-result) (return (nreverse reversed-result))))))) (deftype unix-pathname () 'simple-string) (deftype unix-fd () `(integer 0 ,most-positive-fixnum)) (deftype unix-file-mode () '(unsigned-byte 32)) (deftype unix-pid () '(unsigned-byte 32)) (deftype unix-uid () '(unsigned-byte 32)) (deftype unix-gid () '(unsigned-byte 32)) (/show0 "unix.lisp 74") (eval-when (:compile-toplevel :load-toplevel :execute) (defun libc-name-for (x) (assert (stringp x)) like and sb_closedir . Why are those wrapped in fact ? #+netbsd x :test #'string=) (subseq x 3) x))) (defmacro syscall ((name &rest arg-types) success-form &rest args) (when (eql 3 (mismatch "[_]" name)) (setf name (concatenate 'string #+win32 "_" (subseq name 3)))) `(locally (declare (optimize (sb-c::float-accuracy 0))) (let ((result (alien-funcall (extern-alien ,(libc-name-for name) (function int ,@arg-types)) ,@args))) (if (minusp result) (values nil (get-errno)) ,success-form)))) (defmacro syscall* ((name &rest arg-types) success-form &rest args) `(locally (declare (optimize (sb-c::float-accuracy 0))) (let ((result (alien-funcall (extern-alien ,(libc-name-for name) (function int ,@arg-types)) ,@args))) (if (minusp result) (error "Syscall ~A failed: ~A" ,name (strerror)) ,success-form)))) (defmacro int-syscall ((name &rest arg-types) &rest args) `(syscall (,(libc-name-for name) ,@arg-types) (values result 0) ,@args)) (defmacro with-restarted-syscall ((&optional (value (gensym)) (errno (gensym))) syscall-form &rest body) "Evaluate BODY with VALUE and ERRNO bound to the return values of SYSCALL-FORM. Repeat evaluation of SYSCALL-FORM if it is interrupted." `(let (,value ,errno) (loop (multiple-value-setq (,value ,errno) ,syscall-form) (unless #-win32 (eql ,errno eintr) #+win32 nil (return (values ,value ,errno)))) ,@body)) (defmacro void-syscall ((name &rest arg-types) &rest args) `(syscall (,name ,@arg-types) (values t 0) ,@args)) #+win32 (progn (defconstant espipe 29)) #-win32 (define-alien-routine ("getenv" posix-getenv) c-string "Return the \"value\" part of the environment string \"name=value\" which corresponds to NAME, or NIL if there is none." (name (c-string :not-null t))) from stdio.h Rename the file with string NAME1 to the string . NIL and an #-win32 (defun unix-rename (name1 name2) (declare (type unix-pathname name1 name2)) (void-syscall ("rename" (c-string :not-null t) (c-string :not-null t)) name1 name2)) from sys / types.h and gnu / types.h (/show0 "unix.lisp 220") (define-alien-type fd-mask unsigned) (define-alien-type nil (struct fd-set (fds-bits (array fd-mask #.(/ fd-setsize sb-vm:n-machine-word-bits))))) (/show0 "unix.lisp 304") POSIX Standard : 6.5 File Control Operations < fcntl.h > and/or writing as specified by the argument . Various If the flag is specified , then the file is created with a file descriptor is returned by UNIX - OPEN . (defun unix-open (path flags mode &key #+win32 overlapped) (declare (type unix-pathname path) (type fixnum flags) (type unix-file-mode mode) #+win32 (ignore mode)) #+win32 (sb-win32:unixlike-open path flags :overlapped overlapped) #-win32 (with-restarted-syscall (value errno) (locally (declare (optimize (sb-c::float-accuracy 0))) (let ((result (alien-funcall (extern-alien "open" (function int c-string int &optional int)) path (logior flags #+largefile o_largefile) mode))) (if (minusp result) (values nil (get-errno)) (values result 0)))))) (/show0 "unix.lisp 391") (defun unix-close (fd) #+win32 (sb-win32:unixlike-close fd) #-win32 (declare (type unix-fd fd)) #-win32 (void-syscall ("close" int) fd)) sb_mkstemp ( ) is a wrapper that lives in src / runtime / wrap.c . Since since we have to implement most of this ourselves for Windows anyway , it seems worthwhile to depart from the ( ) (defun sb-mkstemp (template-string mode) (declare (type string template-string) (type unix-file-mode mode)) (let ((template-buffer (string-to-octets template-string :null-terminate t))) (with-pinned-objects (template-buffer) (let ((fd (alien-funcall (extern-alien "sb_mkstemp" (function int (* char) int)) (vector-sap template-buffer) mode))) (if (minusp fd) (values nil (get-errno)) (values #-win32 fd #+win32 (sb-win32::duplicate-and-unwrap-fd fd) (octets-to-string template-buffer))))))) (defconstant rusage_both -2) (define-alien-type nil (struct rusage Given a file path ( a string ) and one of four constant modes , When NIL , also return an errno value with NIL which tells why the In Windows , the MODE argument to access is defined in terms of literal magic numbers --- there are no constants to grovel . #+win32 (progn (defconstant f_ok 0) (defconstant w_ok 2) (defconstant r_ok 4)) (defun unix-access (path mode) (declare (type unix-pathname path) (type (mod 8) mode)) (void-syscall ("[_]access" c-string int) path mode)) values for the second argument to UNIX - LSEEK Note that nowadays these are called SEEK_SET , SEEK_CUR , and SEEK_END off_t is 32 bit on Windows , yet our functions support 64 bit seeks . (define-alien-type unix-offset #-win32 off-t #+win32 (signed 64)) (defun unix-isatty (fd) (declare (type unix-fd fd)) #-win32 (int-syscall ("isatty" int) fd) #+win32 (sb-win32::windows-isatty fd)) (defun unix-lseek (fd offset whence) "Unix-lseek accepts a file descriptor and moves the file pointer by OFFSET octets. Whence can be any of the following: L_SET Set the file pointer. L_INCR Increment the file pointer. L_XTND Extend the file size. " (declare (type unix-fd fd) (type (integer 0 2) whence)) (let ((result #-win32 (alien-funcall (extern-alien #-largefile "lseek" #+largefile "lseek_largefile" (function off-t int off-t int)) fd offset whence) #+win32 (sb-win32:lseeki64 fd offset whence))) (if (minusp result) (values nil (get-errno)) (values result 0)))) (declaim (maybe-inline unix-read)) (defun unix-read (fd buf len) (declare (type unix-fd fd) (type (unsigned-byte 32) len)) (int-syscall (#-win32 "read" #+win32 "win32_unix_read" int (* char) int) fd buf len)) (defun unix-write (fd buf offset len) : change 60fa88b187e438cc made this function unusable in cold - init if compiled with # + sb - show ( which increases DEBUG to 2 ) because of full calls to SB - ALIEN - INTERNALS : DEPORT - ALLOC and DEPORT . (declare (optimize (debug 1))) (declare (type unix-fd fd) (type (unsigned-byte 32) offset len)) (flet ((%write (sap) (declare (system-area-pointer sap)) (int-syscall (#-win32 "write" #+win32 "win32_unix_write" int (* char) int) fd (with-alien ((ptr (* char) sap)) (addr (deref ptr offset))) len))) (etypecase buf ((simple-array * (*)) (with-pinned-objects (buf) (%write (vector-sap buf)))) (system-area-pointer (%write buf))))) output pipe . Return two values : if no error occurred the first value is the pipe to be read from and the second is can be written to . If an error occurred the first value is NIL and the second the #-win32 (defun unix-pipe () (with-alien ((fds (array int 2))) (syscall ("pipe" (* int)) (values (deref fds 0) (deref fds 1)) (cast fds (* int))))) #+win32 (defun unix-pipe () (sb-win32::windows-pipe)) Windows mkdir ( ) does n't take the mode argument . It 's cdecl , so we could would put five and twenty - seven together and ask us about it , so ... -- AB , 2005 - 12 - 27 #-win32 (defun unix-mkdir (name mode) (declare (type unix-pathname name) (type unix-file-mode mode)) (void-syscall ("mkdir" c-string int) name mode)) (defun newcharstar-string (newcharstar) (declare (type (alien (* char)) newcharstar)) (if (null-alien newcharstar) nil (prog1 (cast newcharstar c-string) (free-alien newcharstar)))) style returned by ( ) ( no trailing slash character ) . #-win32 (defun posix-getcwd () This implementation relies on a BSD / Linux extension to getcwd ( ) PATH_MAX+1 from the Solaris header files and stuck it in here as helpful , either , as Solaris does n't export PATH_MAX from Signal an error at compile - time , since it 's needed for the #-(or android linux openbsd freebsd netbsd sunos darwin dragonfly haiku) #.(error "POSIX-GETCWD is not implemented.") (or #+(or linux openbsd freebsd netbsd sunos darwin dragonfly haiku) (newcharstar-string (alien-funcall (extern-alien "getcwd" (function (* char) (* char) size-t)) nil #+(or linux openbsd freebsd netbsd darwin dragonfly haiku) 0 #+(or sunos) 1025)) #+android (with-alien ((ptr (array char #.path-max))) (alien-funcall (extern-alien "getcwd" (function c-string (array char #.path-max) int)) ptr path-max)) (simple-perror "getcwd"))) (defun posix-getcwd/ () (concatenate 'string (posix-getcwd) "/")) Duplicate an existing file descriptor ( given as the argument ) and return it . If FD is not a valid file descriptor , NIL and an error #-win32 (defun unix-dup (fd) (declare (type unix-fd fd)) (int-syscall ("dup" int) fd)) returns NIL and an error number . (deftype exit-code () `(signed-byte 32)) (defun os-exit (code &key abort) "Exit the process with CODE. If ABORT is true, exit is performed using _exit(2), avoiding atexit(3) hooks, etc. Otherwise exit(2) is called." (unless (typep code 'exit-code) (setf code (if abort 1 0))) (if abort (void-syscall ("_exit" int) code) (void-syscall ("exit" int) code))) (define-deprecated-function :early "1.0.56.55" unix-exit os-exit (code) (os-exit code)) (define-alien-routine (#+win32 "_getpid" #-win32 "getpid" unix-getpid) int) #-win32 (define-alien-routine ("getuid" unix-getuid) int) #-win32 (defun uid-username (uid) (or (newcharstar-string (alien-funcall (extern-alien "uid_username" (function (* char) int)) uid)) (error "found no match for Unix uid=~S" uid))) include a trailing # \/ #-win32 (progn (defun uid-homedir (uid) (or (newcharstar-string (alien-funcall (extern-alien "uid_homedir" (function (* char) int)) uid)) (error "failed to resolve home directory for Unix uid=~S" uid))) (defun user-homedir (uid) (or (newcharstar-string (alien-funcall (extern-alien "user_homedir" (function (* char) c-string)) uid)) (error "failed to resolve home directory for Unix uid=~S" uid)))) #-win32 (defun unix-readlink (path) (declare (type unix-pathname path)) (with-alien ((ptr (* char) (alien-funcall (extern-alien "wrapped_readlink" (function (* char) c-string)) path))) (if (null-alien ptr) (values nil (get-errno)) (multiple-value-prog1 (values (with-alien ((c-string c-string ptr)) c-string) nil) (free-alien ptr))))) #+win32 Something in this file , no less . But it only takes one result , so ... (defun unix-readlink (path) (declare (ignore path)) nil) (defun unix-realpath (path) (declare (type unix-pathname path)) (with-alien ((ptr (* char) (alien-funcall (extern-alien "sb_realpath" (function (* char) c-string)) path))) (if (null-alien ptr) (values nil (get-errno)) (multiple-value-prog1 (values (with-alien ((c-string c-string ptr)) c-string) nil) (free-alien ptr))))) (defun unix-unlink (name) (declare (type unix-pathname name)) (void-syscall ("[_]unlink" c-string) name)) #-win32 (defun unix-gethostname () (with-alien ((buf (array char 256))) (syscall ("gethostname" (* char) int) (cast buf c-string) (cast buf (* char)) 256))) #-win32 (defun unix-setsid () (int-syscall ("setsid"))) descriptors . See the UNIX Programmer 's Manual for more #-win32 (defun unix-ioctl (fd cmd arg) (declare (type unix-fd fd) (type word cmd)) (void-syscall ("ioctl" int unsigned-long (* char)) fd cmd arg)) sys / resource.h specified by WHO . WHO can be either the current process #-win32 (defun unix-getrusage (who) (with-alien ((usage (struct rusage))) (syscall ("sb_getrusage" int (* (struct rusage))) (values t (+ (* (slot (slot usage 'ru-utime) 'tv-sec) 1000000) (slot (slot usage 'ru-utime) 'tv-usec)) (+ (* (slot (slot usage 'ru-stime) 'tv-sec) 1000000) (slot (slot usage 'ru-stime) 'tv-usec)) (slot usage 'ru-maxrss) (slot usage 'ru-ixrss) (slot usage 'ru-idrss) (slot usage 'ru-isrss) (slot usage 'ru-minflt) (slot usage 'ru-majflt) (slot usage 'ru-nswap) (slot usage 'ru-inblock) (slot usage 'ru-oublock) (slot usage 'ru-msgsnd) (slot usage 'ru-msgrcv) (slot usage 'ru-nsignals) (slot usage 'ru-nvcsw) (slot usage 'ru-nivcsw)) who (addr usage)))) (defvar *on-dangerous-wait* :warn) (defun note-dangerous-wait (type) (let ((action *on-dangerous-wait*) (*on-dangerous-wait* nil)) (case action (:warn (warn "Starting a ~A without a timeout while interrupts are ~ disabled." type)) (:error (error "Starting a ~A without a timeout while interrupts are ~ disabled." type)) (:backtrace (format *debug-io* "~&=== Starting a ~A without a timeout while interrupts are disabled. ===~%" type) (sb-debug:print-backtrace))) nil)) #+os-provides-poll (progn (define-alien-type nil (struct pollfd (fd int) (declaim (inline unix-poll)) (defun unix-poll (pollfds nfds to-msec) (declare (fixnum nfds to-msec)) (when (and (minusp to-msec) (not *interrupts-enabled*)) (note-dangerous-wait "poll(2)")) (int-syscall ("poll" (* (struct pollfd)) int int) (alien-sap pollfds) nfds to-msec)) (defun unix-simple-poll (fd direction to-msec) (declare (fixnum fd to-msec)) (when (and (minusp to-msec) (not *interrupts-enabled*)) (note-dangerous-wait "poll(2)")) (let ((events (ecase direction (:input (logior pollin pollpri)) (:output pollout)))) (with-alien ((fds (struct pollfd))) (with-restarted-syscall (count errno) (progn (setf (slot fds 'fd) fd (slot fds 'events) events (slot fds 'revents) 0) (int-syscall ("poll" (* (struct pollfd)) int int) (addr fds) 1 to-msec)) (if (zerop errno) (let ((revents (slot fds 'revents))) (or (and (eql 1 count) (logtest events revents)) (logtest pollhup revents))) (error "Syscall poll(2) failed: ~A" (strerror)))))))) (defmacro with-fd-setsize ((n) &body body) `(let ((,n (if (< 0 ,n fd-setsize) ,n (error "Cannot select(2) on ~D: above FD_SETSIZE limit." (1- ,n))))) (declare (type (integer 0 #.fd-setsize) ,n)) ,@body)) (declaim (inline unix-fast-select)) (defun unix-fast-select (num-descriptors read-fds write-fds exception-fds timeout-secs timeout-usecs) (declare (type integer num-descriptors) (type (or (alien (* (struct fd-set))) null) read-fds write-fds exception-fds) (type (or null (unsigned-byte 31)) timeout-secs timeout-usecs)) (with-fd-setsize (num-descriptors) (flet ((select (tv-sap) (int-syscall ("sb_select" int (* (struct fd-set)) (* (struct fd-set)) (* (struct fd-set)) (* (struct timeval))) num-descriptors read-fds write-fds exception-fds tv-sap))) (cond ((or timeout-secs timeout-usecs) (with-alien ((tv (struct timeval))) (setf (slot tv 'tv-sec) (or timeout-secs 0)) (setf (slot tv 'tv-usec) (or timeout-usecs 0)) (select (alien-sap (addr tv))))) (t (unless *interrupts-enabled* (note-dangerous-wait "select(2)")) (select (int-sap 0))))))) (declaim (inline fd-set fd-clr fd-isset fd-zero)) (defun fd-set (offset fd-set) (multiple-value-bind (word bit) (floor offset sb-vm:n-machine-word-bits) (setf (deref (slot fd-set 'fds-bits) word) (logior (truly-the (unsigned-byte #.sb-vm:n-machine-word-bits) (ash 1 bit)) (deref (slot fd-set 'fds-bits) word))))) (defun fd-clr (offset fd-set) (multiple-value-bind (word bit) (floor offset sb-vm:n-machine-word-bits) (setf (deref (slot fd-set 'fds-bits) word) (logand (deref (slot fd-set 'fds-bits) word) (sb-kernel:word-logical-not (truly-the (unsigned-byte #.sb-vm:n-machine-word-bits) (ash 1 bit))))))) (defun fd-isset (offset fd-set) (multiple-value-bind (word bit) (floor offset sb-vm:n-machine-word-bits) (logbitp bit (deref (slot fd-set 'fds-bits) word)))) (defun fd-zero (fd-set) (loop for index below (/ fd-setsize sb-vm:n-machine-word-bits) do (setf (deref (slot fd-set 'fds-bits) index) 0))) #-os-provides-poll (defun unix-simple-poll (fd direction to-msec) (multiple-value-bind (to-sec to-usec) (if (minusp to-msec) (values nil nil) (multiple-value-bind (to-sec to-msec2) (truncate to-msec 1000) (values to-sec (* to-msec2 1000)))) (with-restarted-syscall (count errno) (with-alien ((fds (struct fd-set))) (fd-zero fds) (fd-set fd fds) (multiple-value-bind (read-fds write-fds) (ecase direction (:input (values (addr fds) nil)) (:output (values nil (addr fds)))) (unix-fast-select (1+ fd) read-fds write-fds nil to-sec to-usec))) (case count ((1) t) ((0) nil) (otherwise (error "Syscall select(2) failed on fd ~D: ~A" fd (strerror))))))) This is a structure defined in src / runtime / wrap.c , to look Note that st - dev is a long , not a dev - t. This is because dev - t on linux 32 bit is a 64 bit quantity , but alien does n't support until we can get 64 bit alien support it 'll do . Also note that st_size is a long , not an off - t , because off - t is a 64 - bit quantity on Alpha . And FIXME : " No one would want a file length longer than 32 bits anyway , right?":-| The comment about alien and 64 - bit quantities has not been kept in not clear whether either comment is correct . -- RMK 2007 - 11 - 14 . (define-alien-type nil (struct wrapped_stat (st-dev wst-dev-t) (st-ino wst-ino-t) (st-mode mode-t) (st-nlink wst-nlink-t) (st-uid wst-uid-t) (st-gid wst-gid-t) (st-rdev wst-dev-t) (st-size wst-off-t) (st-blksize wst-blksize-t) (st-blocks wst-blkcnt-t) (st-atime time-t) (st-mtime time-t) (st-ctime time-t))) problems . My first guess is that it 's a bug in the FFI code , where around a call to a function returning > 10 values . But I did n't try who 's motivated to debug the FFI code can go over the DISASSEMBLE (declaim (inline %extract-stat-results)) (defun %extract-stat-results (wrapped-stat) (declare (type (alien (* (struct wrapped_stat))) wrapped-stat)) (values t (slot wrapped-stat 'st-dev) (slot wrapped-stat 'st-ino) (slot wrapped-stat 'st-mode) (slot wrapped-stat 'st-nlink) (slot wrapped-stat 'st-uid) (slot wrapped-stat 'st-gid) (slot wrapped-stat 'st-rdev) (slot wrapped-stat 'st-size) (slot wrapped-stat 'st-atime) (slot wrapped-stat 'st-mtime) (slot wrapped-stat 'st-ctime) (slot wrapped-stat 'st-blksize) (slot wrapped-stat 'st-blocks))) (defun unix-stat (name) (declare (type unix-pathname name)) (with-alien ((buf (struct wrapped_stat))) (syscall ("stat_wrapper" c-string (* (struct wrapped_stat))) (%extract-stat-results (addr buf)) name (addr buf)))) (defun unix-lstat (name) (declare (type unix-pathname name)) (with-alien ((buf (struct wrapped_stat))) (syscall ("lstat_wrapper" c-string (* (struct wrapped_stat))) (%extract-stat-results (addr buf)) name (addr buf)))) (defun unix-fstat (fd) #-win32 (declare (type unix-fd fd)) (#-win32 funcall #+win32 sb-win32::call-with-crt-fd (lambda (fd) (with-alien ((buf (struct wrapped_stat))) (syscall ("fstat_wrapper" int (* (struct wrapped_stat))) (%extract-stat-results (addr buf)) fd (addr buf)))) fd)) #-win32 (defun fd-type (fd) (declare (type unix-fd fd)) (let ((mode (or (with-alien ((buf (struct wrapped_stat))) (syscall ("fstat_wrapper" int (* (struct wrapped_stat))) (slot buf 'st-mode) fd (addr buf))) 0))) (case (logand mode s-ifmt) (#.s-ifchr :character) (#.s-ifdir :directory) (#.s-ifblk :block) (#.s-ifreg :regular) (#.s-ifsock :socket) (#.s-iflnk :link) (#.s-ififo :fifo) (t :unknown)))) (define-alien-type nil (struct tm Seconds . [ 0 - 60 ] ( 1 leap second ) Minutes . [ 0 - 59 ] Hours . [ 0 - 23 ] Day . [ 1 - 31 ] Month . [ 0 - 11 ] Year - 1900 . Day of week . [ 0 - 6 ] Days in year . [ 0 - 365 ] DST . [ -1/0/1 ] Timezone abbreviation . (define-alien-routine get-timezone int (when time-t) : the runtime ` boolean ' is defined as ` int ' , but the alien (daylight-savings-p (boolean 32) :out)) #-win32 (defun nanosleep (secs nsecs) (alien-funcall (extern-alien "sb_nanosleep" (function int time-t int)) secs nsecs) nil) #-win32 (defun nanosleep-double (seconds) (alien-funcall (extern-alien "sb_nanosleep_double" (function (values) double)) seconds) nil) #-win32 (defun nanosleep-float (seconds) (alien-funcall (extern-alien "sb_nanosleep_float" (function (values) float)) seconds) nil) Structure crudely representing a timezone . : This is (define-alien-type nil (struct timezone minutes west of Greenwich Type of the second argument to ` getitimer ' and the second and third arguments ` setitimer ' . (define-alien-type nil (struct itimerval (defconstant itimer-real 0) (defconstant itimer-virtual 1) (defconstant itimer-prof 2) #-win32 (defun unix-getitimer (which) "UNIX-GETITIMER returns the INTERVAL and VALUE slots of one of three system timers (:real :virtual or :profile). On success, unix-getitimer returns 5 values, T, it-interval-secs, it-interval-usec, it-value-secs, it-value-usec." (declare (type (member :real :virtual :profile) which) (values t unsigned-byte (mod 1000000) unsigned-byte (mod 1000000))) (let ((which (ecase which (:real itimer-real) (:virtual itimer-virtual) (:profile itimer-prof)))) (with-alien ((itv (struct itimerval))) (syscall* ("sb_getitimer" int (* (struct itimerval))) (values t (slot (slot itv 'it-interval) 'tv-sec) (slot (slot itv 'it-interval) 'tv-usec) (slot (slot itv 'it-value) 'tv-sec) (slot (slot itv 'it-value) 'tv-usec)) which (alien-sap (addr itv)))))) #-win32 (defun unix-setitimer (which int-secs int-usec val-secs val-usec) "UNIX-SETITIMER sets the INTERVAL and VALUE slots of one of three system timers (:real :virtual or :profile). A SIGALRM, SIGVTALRM, or SIGPROF respectively will be delivered in VALUE <seconds+microseconds> from now. INTERVAL, when non-zero, is reloaded into the timer on each expiration. Setting VALUE to zero disables the timer. See the Unix man page for more details. On success, unix-setitimer returns the old contents of the INTERVAL and VALUE slots as in unix-getitimer." (declare (type (member :real :virtual :profile) which) (type unsigned-byte int-secs val-secs) (type (integer 0 (1000000)) int-usec val-usec) (values t unsigned-byte (mod 1000000) unsigned-byte (mod 1000000))) (let ((which (ecase which (:real itimer-real) (:virtual itimer-virtual) (:profile itimer-prof)))) (with-alien ((itvn (struct itimerval)) (itvo (struct itimerval))) (setf (slot (slot itvn 'it-interval) 'tv-sec ) int-secs (slot (slot itvn 'it-interval) 'tv-usec) int-usec (slot (slot itvn 'it-value ) 'tv-sec ) val-secs (slot (slot itvn 'it-value ) 'tv-usec) val-usec) (syscall* ("sb_setitimer" int (* (struct timeval)) (* (struct timeval))) (values t (slot (slot itvo 'it-interval) 'tv-sec) (slot (slot itvo 'it-interval) 'tv-usec) (slot (slot itvo 'it-value) 'tv-sec) (slot (slot itvo 'it-value) 'tv-usec)) which (alien-sap (addr itvn)) (alien-sap (addr itvo)))))) CMU CL source code here , but not in the exports of SB - UNIX . I ( WHN ) hope that someday I 'll figure out an automatic way to detect enough of them all in one place here that they should probably be (defconstant microseconds-per-internal-time-unit (/ 1000000 internal-time-units-per-second)) (defconstant nanoseconds-per-internal-time-unit (* microseconds-per-internal-time-unit 1000)) UNIX specific code , that has been cleanly separated from the Windows build . #-win32 (progn (declaim (inline clock-gettime)) (defun clock-gettime (clockid) (declare (type (signed-byte 32) clockid)) (with-alien ((ts (struct timespec))) (alien-funcall (extern-alien #.(libc-name-for "sb_clock_gettime") (function int int (* (struct timespec)))) clockid (addr ts)) ' seconds ' is definitely a fixnum for 64 - bit , because most - positive - fixnum can express 1E11 years in seconds . (values #+64-bit (truly-the fixnum (slot ts 'tv-sec)) #-64-bit (slot ts 'tv-sec) (truly-the (integer 0 #.(expt 10 9)) (slot ts 'tv-nsec))))) (declaim (inline get-time-of-day)) (defun get-time-of-day () "Return the number of seconds and microseconds since the beginning of the UNIX epoch (January 1st 1970.)" (with-alien ((tv (struct timeval))) (syscall* ("sb_gettimeofday" (* (struct timeval)) system-area-pointer) (values (slot tv 'tv-sec) (slot tv 'tv-usec)) (addr tv) (int-sap 0)))) The " optimizations that actually matter " do n't actually matter for 64 - bit . Microseconds can express at least 1E5 years of uptime : ( float ( / most - positive - fixnum ( * 1000000 60 60 24 ( + 365 1/4 ) ) ) ) (defun get-internal-real-time () (with-alien ((base (struct timespec) :extern "lisp_init_time")) (multiple-value-bind (c-sec c-nsec) offers , and COARSE is about twice as fast , so use that , but only for linux . BSD has something similar . (clock-gettime #+linux clock-monotonic-coarse #-linux clock-monotonic) I know that my math is valid for 64 - bit . (declare (optimize (sb-c::type-check 0))) #+64-bit (let ((delta-sec (the fixnum (- c-sec (the fixnum (slot base 'tv-sec))))) (delta-nsec (the fixnum (- c-nsec (the fixnum (slot base 'tv-nsec)))))) (the sb-kernel:internal-time (+ (the fixnum (* delta-sec internal-time-units-per-second)) (truncate delta-nsec nanoseconds-per-internal-time-unit)))) There are two optimizations here that actually matter on 32 - bit systems : ( 1 ) subtract the epoch from seconds and milliseconds separately , ( 2 ) avoid consing a new bignum if the result is unchanged . Thanks to for the optimization hint . #-64-bit (symbol-macrolet ((observed-sec (sb-thread::thread-observed-internal-real-time-delta-sec thr)) (observed-msec (sb-thread::thread-observed-internal-real-time-delta-millisec thr)) (time (sb-thread::thread-internal-real-time thr))) (let* ((delta-sec (- c-sec (slot base 'tv-sec))) to err on the side of caution rather than cause GC lossage ( which I accidentally did ) . So assert that nanoseconds are < = 10 ^ 9 (delta-nsec (- c-nsec (the (integer 0 #.(expt 10 9)) (slot base 'tv-nsec)))) (delta-millisec (floor delta-nsec 1000000)) (thr sb-thread:*current-thread*)) (if (and (= delta-sec observed-sec) (= delta-millisec observed-msec)) time (let ((current (+ (* delta-sec internal-time-units-per-second) ASSUMPTION : delta - millisec = delta-millisec))) (setf time current observed-msec delta-millisec observed-sec delta-sec) current))))))) (declaim (inline system-internal-run-time)) (defun system-internal-run-time () (multiple-value-bind (sec nsec) (clock-gettime clock-process-cputime-id) (+ (* sec internal-time-units-per-second) (floor (+ nsec (floor nanoseconds-per-internal-time-unit 2)) nanoseconds-per-internal-time-unit))))) FIXME , : GET - TIME - OF - DAY used to be UNIX - GETTIMEOFDAY , and had a information -- though the timezone data was not there on . Now we have GET - TIME - OF - DAY , but it turns out that despite SB - UNIX being of 2009 . (defun unix-gettimeofday () (multiple-value-bind (sec usec) (get-time-of-day) (values t sec usec nil nil))) opendir , , and dirent - name (declaim (inline unix-opendir)) (defun unix-opendir (namestring &optional (errorp t)) (let ((dir (alien-funcall (extern-alien "sb_opendir" (function system-area-pointer c-string)) namestring))) (if (zerop (sap-int dir)) (when errorp (simple-perror (format nil "Error opening directory ~S" namestring))) dir))) (declaim (inline unix-readdir)) (defun unix-readdir (dir &optional (errorp t) namestring) (let ((ent (alien-funcall (extern-alien "sb_readdir" (function system-area-pointer system-area-pointer)) dir)) errno) (if (zerop (sap-int ent)) (when (and errorp (not (zerop (setf errno (get-errno))))) (simple-perror (format nil "Error reading directory entry~@[ from ~S~]" namestring) :errno errno)) ent))) (declaim (inline unix-closedir)) (defun unix-closedir (dir &optional (errorp t) namestring) (let ((r (alien-funcall (extern-alien "sb_closedir" (function int system-area-pointer)) dir))) (if (minusp r) (when errorp (simple-perror (format nil "Error closing directory~@[ ~S~]" namestring))) r))) (declaim (inline unix-dirent-name)) (defun unix-dirent-name (ent) (alien-funcall (extern-alien "sb_dirent_name" (function c-string system-area-pointer)) ent))
86232914be138002a51a940982257980a520458652a4d64ca43f0e36772da05e
liqula/react-hs
LambdaViews.hs
# OPTIONS_GHC -fno - warn - orphans # | The views for the TODO app module LambdaViews where import React.Flux import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.List as List import LambdaAST import LambdaFBAnn import import LambdaStore import LambdaSVG -- | The controller view and also the top level of the LAMBDA app. This controller view registers -- with the store and will be re-rendered whenever the store changes. lambdaApp :: View '[] lambdaApp = mkControllerView @'[StoreArg LambdaState] "lambda app" $ \lambdaState -> div_ $ do lambdaView (lambdaState) lambdaView :: LambdaState -> ReactElementM 'EventHandlerCode () lambdaView ls = section_ ["id" $= "lambda"] $ do h2_ [ "key" &= ("h1" :: String)] "lambda" div_ [ "key" &= ("d1" :: String)] $ textarea_ [ onInput $ \evt -> handleLambda (LambdaSetText $ target evt "value") , onChange $ \evt -> handleLambda (LambdaSetText $ target evt "value") , "value" &= lambdaInputText ls , "className" &= ("lambdatextinput" :: String) ] mempty div_ [ "key" &= ("d2" :: String)] $ do button_ [ "key" &= ("b1" :: String), onClick $ \_ _ -> handleLambda (LambdaLoad "example1.txt") ] $ elemString "load 1" button_ [ "key" &= ("b2" :: String), onClick $ \_ _ -> handleLambda (LambdaLoad "example2.txt") ] $ elemString "load 2" div_ [ "key" &= ("d3" :: String)] $ do button_ [ "key" &= ("b3" :: String), onClick $ \_ _ -> handleLambda (LambdaRunTicks $ not (runTicks ls)), "disabled" @= (maybe True (const False) (lambdaExpr ls)) ] $ elemString (if runTicks ls then "stop" else "run") button_ [ "key" &= ("b4" :: String), onClick $ \_ _ -> handleLambda (LambdaReset), "disabled" @= (maybe True (const False) (lastInput ls)) ] $ elemString "reset" div_ [ "key" &= ("d4" :: String)] $ do button_ [ "key" &= ("b5" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsNormal 1) ] $ elemString "normal reduction" button_ [ "key" &= ("b6" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsNormal 100) ] $ elemString "100 normal reductions" button_ [ "key" &= ("b7" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsNormal 500) ] $ elemString "500 normal reductions" button_ [ "key" &= ("b8" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsRandom 1) ] $ elemString "random reduction" button_ [ "key" &= ("b9" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsRandom 50) ] $ elemString "50 random reductions" button_ [ "key" &= ("b10" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsLeftmost 1) ] $ elemString "leftmost reduction" div_ [ "key" &= ("d5" :: String)] $ elemString (show $ reductionCount ls) div_ [ "key" &= ("d6" :: String)] $ viewExpr (lambdaExpr ls) viewExpr :: Maybe (Expr FBAnn) -> ReactElementM 'EventHandlerCode () viewExpr Nothing = elemString "" viewExpr (Just expr) = do div_ [ "key" &= ("dd1" :: String)] $ renderExpr [] expr div_ [ "key" &= ("dd2" :: String)] $ renderExprSVG expr 0.5 renderExpr :: [Bool] -> Expr FBAnn -> ReactElementM 'EventHandlerCode () renderExpr path expr = case expr of Var _ name -> elemText name Abs ann name body -> do span_ [ "title" &= (List.intercalate " " $ map (T.unpack) $ Set.toList $ freeAnn ann) ] $ elemString ("\\" ++ T.unpack name ++ ". ") renderExpr (True : path) body App ann fun@Abs{} arg -> do span_ [ onClick $ \_ _ -> handleLambda (LambdaStepAt path) , style [("color",if Set.null (conflictAnn ann) then "blue" else "red")] , "title" &= (List.intercalate " " $ map (T.unpack) $ Set.toList $ freeAnn ann) ] "@" renderExprApp path fun arg App ann fun arg -> do span_ [ "title" &= (List.intercalate " " $ map (T.unpack) $ Set.toList $ freeAnn ann) ] "@" renderExprApp path fun arg renderExprApp :: [Bool] -> Expr FBAnn -> Expr FBAnn -> ReactElementM 'EventHandlerCode () renderExprApp path fun arg = do renderExpr (False : path) fun elemString " " renderExpr (True : path) arg
null
https://raw.githubusercontent.com/liqula/react-hs/204c96ee3514b5ddec65378d37872266b05e8954/react-hs-examples/lambda/src/LambdaViews.hs
haskell
| The controller view and also the top level of the LAMBDA app. This controller view registers with the store and will be re-rendered whenever the store changes.
# OPTIONS_GHC -fno - warn - orphans # | The views for the TODO app module LambdaViews where import React.Flux import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.List as List import LambdaAST import LambdaFBAnn import import LambdaStore import LambdaSVG lambdaApp :: View '[] lambdaApp = mkControllerView @'[StoreArg LambdaState] "lambda app" $ \lambdaState -> div_ $ do lambdaView (lambdaState) lambdaView :: LambdaState -> ReactElementM 'EventHandlerCode () lambdaView ls = section_ ["id" $= "lambda"] $ do h2_ [ "key" &= ("h1" :: String)] "lambda" div_ [ "key" &= ("d1" :: String)] $ textarea_ [ onInput $ \evt -> handleLambda (LambdaSetText $ target evt "value") , onChange $ \evt -> handleLambda (LambdaSetText $ target evt "value") , "value" &= lambdaInputText ls , "className" &= ("lambdatextinput" :: String) ] mempty div_ [ "key" &= ("d2" :: String)] $ do button_ [ "key" &= ("b1" :: String), onClick $ \_ _ -> handleLambda (LambdaLoad "example1.txt") ] $ elemString "load 1" button_ [ "key" &= ("b2" :: String), onClick $ \_ _ -> handleLambda (LambdaLoad "example2.txt") ] $ elemString "load 2" div_ [ "key" &= ("d3" :: String)] $ do button_ [ "key" &= ("b3" :: String), onClick $ \_ _ -> handleLambda (LambdaRunTicks $ not (runTicks ls)), "disabled" @= (maybe True (const False) (lambdaExpr ls)) ] $ elemString (if runTicks ls then "stop" else "run") button_ [ "key" &= ("b4" :: String), onClick $ \_ _ -> handleLambda (LambdaReset), "disabled" @= (maybe True (const False) (lastInput ls)) ] $ elemString "reset" div_ [ "key" &= ("d4" :: String)] $ do button_ [ "key" &= ("b5" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsNormal 1) ] $ elemString "normal reduction" button_ [ "key" &= ("b6" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsNormal 100) ] $ elemString "100 normal reductions" button_ [ "key" &= ("b7" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsNormal 500) ] $ elemString "500 normal reductions" button_ [ "key" &= ("b8" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsRandom 1) ] $ elemString "random reduction" button_ [ "key" &= ("b9" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsRandom 50) ] $ elemString "50 random reductions" button_ [ "key" &= ("b10" :: String), onClick $ \_ _ -> handleLambda (LambdaStepsLeftmost 1) ] $ elemString "leftmost reduction" div_ [ "key" &= ("d5" :: String)] $ elemString (show $ reductionCount ls) div_ [ "key" &= ("d6" :: String)] $ viewExpr (lambdaExpr ls) viewExpr :: Maybe (Expr FBAnn) -> ReactElementM 'EventHandlerCode () viewExpr Nothing = elemString "" viewExpr (Just expr) = do div_ [ "key" &= ("dd1" :: String)] $ renderExpr [] expr div_ [ "key" &= ("dd2" :: String)] $ renderExprSVG expr 0.5 renderExpr :: [Bool] -> Expr FBAnn -> ReactElementM 'EventHandlerCode () renderExpr path expr = case expr of Var _ name -> elemText name Abs ann name body -> do span_ [ "title" &= (List.intercalate " " $ map (T.unpack) $ Set.toList $ freeAnn ann) ] $ elemString ("\\" ++ T.unpack name ++ ". ") renderExpr (True : path) body App ann fun@Abs{} arg -> do span_ [ onClick $ \_ _ -> handleLambda (LambdaStepAt path) , style [("color",if Set.null (conflictAnn ann) then "blue" else "red")] , "title" &= (List.intercalate " " $ map (T.unpack) $ Set.toList $ freeAnn ann) ] "@" renderExprApp path fun arg App ann fun arg -> do span_ [ "title" &= (List.intercalate " " $ map (T.unpack) $ Set.toList $ freeAnn ann) ] "@" renderExprApp path fun arg renderExprApp :: [Bool] -> Expr FBAnn -> Expr FBAnn -> ReactElementM 'EventHandlerCode () renderExprApp path fun arg = do renderExpr (False : path) fun elemString " " renderExpr (True : path) arg
4c19ac356a365e89f23244b9791aba994fc907e23a45c6d3c824781d63ebd9b9
Oblosys/proxima
Patterns.hs
UUAGC 0.9.10 ( ) module Patterns where -- Patterns.ag imports import UU.Scanner.Position(Pos) import CommonTypes (ConstructorIdent,Identifier) -- Pattern ----------------------------------------------------- visit 0 : synthesized attribute : copy : SELF alternatives : alternative : child field : { Identifier } child attr : { Identifier } child pat : Pattern child parts : Patterns visit 0 : local copy : _ alternative Constr : child name : { ConstructorIdent } child pats : Patterns visit 0 : local copy : _ alternative Irrefutable : child pat : Pattern visit 0 : local copy : _ alternative Product : child pos : { Pos } child pats : Patterns visit 0 : local copy : _ alternative Underscore : child pos : { Pos } visit 0 : local copy : _ visit 0: synthesized attribute: copy : SELF alternatives: alternative Alias: child field : {Identifier} child attr : {Identifier} child pat : Pattern child parts : Patterns visit 0: local copy : _ alternative Constr: child name : {ConstructorIdent} child pats : Patterns visit 0: local copy : _ alternative Irrefutable: child pat : Pattern visit 0: local copy : _ alternative Product: child pos : {Pos} child pats : Patterns visit 0: local copy : _ alternative Underscore: child pos : {Pos} visit 0: local copy : _ -} data Pattern = Alias (Identifier) (Identifier) (Pattern) (Patterns) | Constr (ConstructorIdent) (Patterns) | Irrefutable (Pattern) | Product (Pos) (Patterns) | Underscore (Pos) deriving ( Show) -- Patterns ---------------------------------------------------- visit 0 : synthesized attribute : copy : SELF alternatives : alternative Cons : child hd : Pattern child tl : Patterns visit 0 : local copy : _ alternative : visit 0 : local copy : _ visit 0: synthesized attribute: copy : SELF alternatives: alternative Cons: child hd : Pattern child tl : Patterns visit 0: local copy : _ alternative Nil: visit 0: local copy : _ -} type Patterns = [(Pattern)]
null
https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/uuagc/src-derived/Patterns.hs
haskell
Patterns.ag imports Pattern ----------------------------------------------------- Patterns ----------------------------------------------------
UUAGC 0.9.10 ( ) module Patterns where import UU.Scanner.Position(Pos) import CommonTypes (ConstructorIdent,Identifier) visit 0 : synthesized attribute : copy : SELF alternatives : alternative : child field : { Identifier } child attr : { Identifier } child pat : Pattern child parts : Patterns visit 0 : local copy : _ alternative Constr : child name : { ConstructorIdent } child pats : Patterns visit 0 : local copy : _ alternative Irrefutable : child pat : Pattern visit 0 : local copy : _ alternative Product : child pos : { Pos } child pats : Patterns visit 0 : local copy : _ alternative Underscore : child pos : { Pos } visit 0 : local copy : _ visit 0: synthesized attribute: copy : SELF alternatives: alternative Alias: child field : {Identifier} child attr : {Identifier} child pat : Pattern child parts : Patterns visit 0: local copy : _ alternative Constr: child name : {ConstructorIdent} child pats : Patterns visit 0: local copy : _ alternative Irrefutable: child pat : Pattern visit 0: local copy : _ alternative Product: child pos : {Pos} child pats : Patterns visit 0: local copy : _ alternative Underscore: child pos : {Pos} visit 0: local copy : _ -} data Pattern = Alias (Identifier) (Identifier) (Pattern) (Patterns) | Constr (ConstructorIdent) (Patterns) | Irrefutable (Pattern) | Product (Pos) (Patterns) | Underscore (Pos) deriving ( Show) visit 0 : synthesized attribute : copy : SELF alternatives : alternative Cons : child hd : Pattern child tl : Patterns visit 0 : local copy : _ alternative : visit 0 : local copy : _ visit 0: synthesized attribute: copy : SELF alternatives: alternative Cons: child hd : Pattern child tl : Patterns visit 0: local copy : _ alternative Nil: visit 0: local copy : _ -} type Patterns = [(Pattern)]
b2296dbc4debe7167613f8200a2632fa29b65e8b73cbf5ed59654daedb0b53a4
jtobin/declarative
Anneal.hs
# OPTIONS_GHC -fno - warn - type - defaults # # LANGUAGE RecordWildCards # -- | -- Module: Numeric.MCMC.Anneal Copyright : ( c ) 2015 License : MIT -- Maintainer : < > -- Stability: unstable Portability : ghc -- -- Transition operators can easily be tweaked to operate over an /annealed/ -- parameter space, which can be useful when sampling from bumpy landscapes -- with isolated modes. -- -- This library exports a single 'anneal' function that allows one to run a -- /declarative/-compatible transition operator over a space that has been -- annealed to a specified temperature. -- > import Numeric . MCMC -- > -- > annealingTransition = do > anneal 0.70 ( metropolis 1 ) > anneal 0.05 ( metropolis 1 ) > anneal 0.05 ( metropolis 1 ) > anneal 0.70 ( metropolis 1 ) > metropolis 1 -- -- These annealed operators can then just be used like any other: -- -- > himmelblau :: Target [Double] -- > himmelblau = Target lHimmelblau Nothing where -- > lHimmelblau :: [Double] -> Double -- > lHimmelblau [x0, x1] = > ( -1 ) * ( ( x0 * ) ^ 2 + ( x1 * x1 - 7 ) ^ 2 ) -- > -- > main :: IO () -- > main = withSystemRandom . asGenIO $ > 10000 [ 0 , 0 ] module Numeric.MCMC.Anneal ( anneal ) where import Control.Monad.Trans.State.Strict (get, modify) import Data.Sampling.Types (Transition, Chain(..), Target(..)) -- | An annealing transformer. -- -- When executed, the supplied transition operator will execute over the -- parameter space annealed to the supplied inverse temperature. -- > let annealedTransition = anneal 0.30 ( slice 0.5 ) anneal :: (Monad m, Functor f) => Double -> Transition m (Chain (f Double) b) -> Transition m (Chain (f Double) b) anneal invTemp baseTransition | invTemp < 0 = error "anneal: invalid temperture" | otherwise = do Chain {..} <- get let annealedTarget = annealer invTemp chainTarget modify $ useTarget annealedTarget baseTransition modify $ useTarget chainTarget annealer :: Functor f => Double -> Target (f Double) -> Target (f Double) annealer invTemp target = Target annealedL annealedG where annealedL xs = invTemp * lTarget target xs annealedG = case glTarget target of Nothing -> Nothing Just g -> Just (fmap (* invTemp) . g) useTarget :: Target a -> Chain a b -> Chain a b useTarget newTarget Chain {..} = Chain newTarget (lTarget newTarget chainPosition) chainPosition chainTunables
null
https://raw.githubusercontent.com/jtobin/declarative/60f4c19cc74dee3fffb284de2daee497b38541fb/lib/Numeric/MCMC/Anneal.hs
haskell
| Module: Numeric.MCMC.Anneal Stability: unstable Transition operators can easily be tweaked to operate over an /annealed/ parameter space, which can be useful when sampling from bumpy landscapes with isolated modes. This library exports a single 'anneal' function that allows one to run a /declarative/-compatible transition operator over a space that has been annealed to a specified temperature. > > annealingTransition = do These annealed operators can then just be used like any other: > himmelblau :: Target [Double] > himmelblau = Target lHimmelblau Nothing where > lHimmelblau :: [Double] -> Double > lHimmelblau [x0, x1] = > > main :: IO () > main = withSystemRandom . asGenIO $ | An annealing transformer. When executed, the supplied transition operator will execute over the parameter space annealed to the supplied inverse temperature.
# OPTIONS_GHC -fno - warn - type - defaults # # LANGUAGE RecordWildCards # Copyright : ( c ) 2015 License : MIT Maintainer : < > Portability : ghc > import Numeric . MCMC > anneal 0.70 ( metropolis 1 ) > anneal 0.05 ( metropolis 1 ) > anneal 0.05 ( metropolis 1 ) > anneal 0.70 ( metropolis 1 ) > metropolis 1 > ( -1 ) * ( ( x0 * ) ^ 2 + ( x1 * x1 - 7 ) ^ 2 ) > 10000 [ 0 , 0 ] module Numeric.MCMC.Anneal ( anneal ) where import Control.Monad.Trans.State.Strict (get, modify) import Data.Sampling.Types (Transition, Chain(..), Target(..)) > let annealedTransition = anneal 0.30 ( slice 0.5 ) anneal :: (Monad m, Functor f) => Double -> Transition m (Chain (f Double) b) -> Transition m (Chain (f Double) b) anneal invTemp baseTransition | invTemp < 0 = error "anneal: invalid temperture" | otherwise = do Chain {..} <- get let annealedTarget = annealer invTemp chainTarget modify $ useTarget annealedTarget baseTransition modify $ useTarget chainTarget annealer :: Functor f => Double -> Target (f Double) -> Target (f Double) annealer invTemp target = Target annealedL annealedG where annealedL xs = invTemp * lTarget target xs annealedG = case glTarget target of Nothing -> Nothing Just g -> Just (fmap (* invTemp) . g) useTarget :: Target a -> Chain a b -> Chain a b useTarget newTarget Chain {..} = Chain newTarget (lTarget newTarget chainPosition) chainPosition chainTunables
cb433a3c700bb37cf374a35a3fa3ff37950c4f9e2f9f2cc7aec59276c46a4d4a
hsyl20/haskus-system
Size.hs
# LANGUAGE LambdaCase # -- | Sizes module Haskus.Arch.X86_64.ISA.Size ( Size(..) , sizeInBits , AddressSize(..) , SizedValue(..) , toSizedValue , fromSizedValue , OperandSize(..) , opSizeInBits , getSize , getSize64 , getOpSize64 ) where import Haskus.Format.Binary.Get import Haskus.Format.Binary.Word -- | Size data Size = Size8 | Size16 | Size32 | Size64 | Size128 | Size256 | Size512 deriving (Show,Eq,Ord) -- | Get a size in bits sizeInBits :: Size -> Word sizeInBits = \case Size8 -> 8 Size16 -> 16 Size32 -> 32 Size64 -> 64 Size128 -> 128 Size256 -> 256 Size512 -> 512 -- | Address size data AddressSize = AddrSize16 | AddrSize32 | AddrSize64 deriving (Show,Eq,Ord) -- | Sized value data SizedValue = SizedValue8 !Word8 | SizedValue16 !Word16 | SizedValue32 !Word32 | SizedValue64 !Word64 deriving (Show,Eq,Ord) | Convert a value into a SizedValue toSizedValue :: Size -> Word64 -> SizedValue toSizedValue s v = case s of Size8 -> SizedValue8 (fromIntegral v) Size16 -> SizedValue16 (fromIntegral v) Size32 -> SizedValue32 (fromIntegral v) Size64 -> SizedValue64 (fromIntegral v) _ -> error ("toSizedValue: invalid size (" ++ show s ++ ")") | Convert a value from a SizedValue fromSizedValue :: SizedValue -> Word64 fromSizedValue = \case SizedValue8 v -> fromIntegral v SizedValue16 v -> fromIntegral v SizedValue32 v -> fromIntegral v SizedValue64 v -> v -- | Operand size data OperandSize = OpSize8 | OpSize16 | OpSize32 | OpSize64 deriving (Show,Eq,Ord) -- | Operand size in bits opSizeInBits :: OperandSize -> Word opSizeInBits = \case OpSize8 -> 8 OpSize16 -> 16 OpSize32 -> 32 OpSize64 -> 64 | Read a SizedValue getSize :: Size -> Get SizedValue getSize Size8 = SizedValue8 <$> getWord8 getSize Size16 = SizedValue16 <$> getWord16le getSize Size32 = SizedValue32 <$> getWord32le getSize Size64 = SizedValue64 <$> getWord64le getSize s = error ("getSize: unsupported size: " ++ show s) -- | Read a value in a Word64 getSize64 :: Size -> Get Word64 getSize64 Size8 = fromIntegral <$> getWord8 getSize64 Size16 = fromIntegral <$> getWord16le getSize64 Size32 = fromIntegral <$> getWord32le getSize64 Size64 = getWord64le getSize64 s = error ("getSize: unsupported size: " ++ show s) -- | Read a value in a Word64 getOpSize64 :: OperandSize -> Get Word64 getOpSize64 OpSize8 = fromIntegral <$> getWord8 getOpSize64 OpSize16 = fromIntegral <$> getWord16le getOpSize64 OpSize32 = fromIntegral <$> getWord32le getOpSize64 OpSize64 = getWord64le
null
https://raw.githubusercontent.com/hsyl20/haskus-system/2f389c6ecae5b0180b464ddef51e36f6e567d690/haskus-system/src/lib/Haskus/Arch/X86_64/ISA/Size.hs
haskell
| Sizes | Size | Get a size in bits | Address size | Sized value | Operand size | Operand size in bits | Read a value in a Word64 | Read a value in a Word64
# LANGUAGE LambdaCase # module Haskus.Arch.X86_64.ISA.Size ( Size(..) , sizeInBits , AddressSize(..) , SizedValue(..) , toSizedValue , fromSizedValue , OperandSize(..) , opSizeInBits , getSize , getSize64 , getOpSize64 ) where import Haskus.Format.Binary.Get import Haskus.Format.Binary.Word data Size = Size8 | Size16 | Size32 | Size64 | Size128 | Size256 | Size512 deriving (Show,Eq,Ord) sizeInBits :: Size -> Word sizeInBits = \case Size8 -> 8 Size16 -> 16 Size32 -> 32 Size64 -> 64 Size128 -> 128 Size256 -> 256 Size512 -> 512 data AddressSize = AddrSize16 | AddrSize32 | AddrSize64 deriving (Show,Eq,Ord) data SizedValue = SizedValue8 !Word8 | SizedValue16 !Word16 | SizedValue32 !Word32 | SizedValue64 !Word64 deriving (Show,Eq,Ord) | Convert a value into a SizedValue toSizedValue :: Size -> Word64 -> SizedValue toSizedValue s v = case s of Size8 -> SizedValue8 (fromIntegral v) Size16 -> SizedValue16 (fromIntegral v) Size32 -> SizedValue32 (fromIntegral v) Size64 -> SizedValue64 (fromIntegral v) _ -> error ("toSizedValue: invalid size (" ++ show s ++ ")") | Convert a value from a SizedValue fromSizedValue :: SizedValue -> Word64 fromSizedValue = \case SizedValue8 v -> fromIntegral v SizedValue16 v -> fromIntegral v SizedValue32 v -> fromIntegral v SizedValue64 v -> v data OperandSize = OpSize8 | OpSize16 | OpSize32 | OpSize64 deriving (Show,Eq,Ord) opSizeInBits :: OperandSize -> Word opSizeInBits = \case OpSize8 -> 8 OpSize16 -> 16 OpSize32 -> 32 OpSize64 -> 64 | Read a SizedValue getSize :: Size -> Get SizedValue getSize Size8 = SizedValue8 <$> getWord8 getSize Size16 = SizedValue16 <$> getWord16le getSize Size32 = SizedValue32 <$> getWord32le getSize Size64 = SizedValue64 <$> getWord64le getSize s = error ("getSize: unsupported size: " ++ show s) getSize64 :: Size -> Get Word64 getSize64 Size8 = fromIntegral <$> getWord8 getSize64 Size16 = fromIntegral <$> getWord16le getSize64 Size32 = fromIntegral <$> getWord32le getSize64 Size64 = getWord64le getSize64 s = error ("getSize: unsupported size: " ++ show s) getOpSize64 :: OperandSize -> Get Word64 getOpSize64 OpSize8 = fromIntegral <$> getWord8 getOpSize64 OpSize16 = fromIntegral <$> getWord16le getOpSize64 OpSize32 = fromIntegral <$> getWord32le getOpSize64 OpSize64 = getWord64le
b019e36a23e9ef204c83851450207b6a50331cc417313b592f20387bf3d30332
Enecuum/Node
Interpreter.hs
module Enecuum.Core.ControlFlow.Interpreter where import Enecuum.Prelude import qualified Enecuum.Core.ControlFlow.Language as L import qualified Enecuum.Runtime as Rt interpretControlFlowF :: Rt.CoreRuntime -> L.ControlFlowF a -> IO a interpretControlFlowF _ (L.Delay i next) = do threadDelay i pure $ next () runControlFlow :: Rt.CoreRuntime -> Free L.ControlFlowF a -> IO a runControlFlow coreRt = foldFree (interpretControlFlowF coreRt)
null
https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/src/Enecuum/Core/ControlFlow/Interpreter.hs
haskell
module Enecuum.Core.ControlFlow.Interpreter where import Enecuum.Prelude import qualified Enecuum.Core.ControlFlow.Language as L import qualified Enecuum.Runtime as Rt interpretControlFlowF :: Rt.CoreRuntime -> L.ControlFlowF a -> IO a interpretControlFlowF _ (L.Delay i next) = do threadDelay i pure $ next () runControlFlow :: Rt.CoreRuntime -> Free L.ControlFlowF a -> IO a runControlFlow coreRt = foldFree (interpretControlFlowF coreRt)
fdd61e1521370f493b1c3cd9aa64861332d5a178e97927f16d7263790b9abf3c
pkel/cpr
bk.ml
open Cpr_lib let incentive_schemes = [ `Block; `Constant ] module type Parameters = sig (** number of votes (= puzzle solutions) per block *) val k : int val incentive_scheme : [ `Block | `Constant ] end module Make (Parameters : Parameters) = struct open Parameters let key = Format.asprintf "bk-%i-%a" k Options.pp incentive_scheme let description = Format.asprintf "Bₖ with k=%i and %a rewards" k Options.pp incentive_scheme ;; let info = let open Info in [ string "family" "bk"; int "k" k; Options.info "incentive_scheme" incentive_scheme ] ;; type block_data = { height : int } type vote_data = { height : int ; id : int } type data = | Vote of vote_data | Block of block_data let height = function | Vote x -> x.height | Block x -> x.height ;; let progress x = match x with | Vote _ -> (height x * k) + 1 |> float_of_int | Block _ -> height x * k |> float_of_int ;; let roots = [ Block { height = 0 } ] module Referee (D : BlockDAG with type data = data) = struct include D let info x = let open Info in match data x with | Vote x -> [ string "kind" "vote"; int "height" x.height; int "id" x.id ] | Block x -> [ string "kind" "block"; int "height" x.height ] ;; let label x = match data x with | Vote _x -> "vote" | Block { height } -> "block " ^ string_of_int height ;; let is_vote x = match data x with | Vote _ -> true | _ -> false ;; let is_block x = match data x with | Block _ -> true | _ -> false ;; let last_block x = match data x with | Block _ -> x | Vote _ -> (match parents x with | [ x ] -> x | _ -> let info _v = [] in raise_invalid_dag info [ x ] "last block hits root") ;; let height x = data x |> height let progress x = data x |> progress let block_height_exn x = match data x with | Block b -> b.height | _ -> let info _v = [] in raise_invalid_dag info [ x ] "block_height_exn: not a block" ;; let confirming_votes x = assert (is_block x); children x |> List.filter is_vote ;; let confirmed_votes x = assert (is_block x); parents x |> List.filter is_vote ;; let validity vertex = let has_pow x = pow x |> Option.is_some and pow_hash x = pow x |> Option.get in match data vertex, parents vertex with | Vote v, [ p ] -> has_pow vertex && is_block p && v.height = height p | Block b, pblock :: vote0 :: votes -> (match data pblock, data vote0 with | Block p, Vote leader -> let ordered_votes, _, nvotes = List.fold_left (fun (ok, h, i) n -> let h' = pow_hash n in is_vote n && compare_pow h' h > 0 && ok, h', i + 1) (true, pow_hash vote0, 1) votes in p.height + 1 = b.height && nvotes = k && ordered_votes && signature vertex = Some leader.id | _ -> false) | _ -> false ;; (** better is bigger *) let compare_blocks = let open Compare in let cmp = by int block_height_exn $ by int (fun x -> List.length (confirming_votes x)) in skip_eq Block.eq cmp ;; let winner = function | [] -> failwith "bk.winner: empty list" | hd :: tl -> List.fold_left (fun acc x -> if compare_blocks x acc > 0 then x else acc) hd tl ;; let precursor this = List.nth_opt (parents this) 0 let constant x = if is_block x then List.filter_map (fun y -> match data y with | Vote v -> Some (v.id, 1.) | Block _ -> None) (parents x) else [] ;; let block x = if is_block x then ( match signature x with | Some i -> [ i, float_of_int k ] | None -> []) else [] ;; let reward = match incentive_scheme with | `Block -> block | `Constant -> constant ;; end let referee (type a) (module D : BlockDAG with type block = a and type data = data) : (a, data) referee = (module Referee (D)) ;; module Honest (V : View with type data = data) = struct include V open Referee (V) type state = block let preferred state = state let init ~roots = match roots with | [ genesis ] -> genesis | _ -> failwith "invalid roots" ;; let appended_by_me x = match visibility x with | `Received -> false | `Withheld | `Released -> true ;; let leader_hash_exn x = if not (is_block x) then raise (Invalid_argument "not a block"); match parents x with | _b :: v0 :: _ -> (match pow v0 with | Some x -> x | None -> raise (Invalid_argument "invalid dag / vote")) | _ -> (* happens for genesis node *) max_pow ;; let compare_blocks ~vote_filter = let open Compare in let cmp = by int block_height_exn $ by int (fun x -> List.length (confirming_votes x |> List.filter vote_filter)) $ by (neg compare_pow) leader_hash_exn TODO . Maybe this should be received_at ? in skip_eq Block.eq cmp ;; let update_head ?(vote_filter = Fun.const true) ~old consider = assert (is_block consider); if compare_blocks ~vote_filter consider old > 0 then consider else old ;; let quorum ~vote_filter b = let pow_hash_exn x = pow x |> Option.get in let my_hash, replace_hash, mine, nmine, theirs, ntheirs = List.fold_left (fun (my_hash, replace_hash, mine, nmine, theirs, ntheirs) x -> match data x with | Vote v -> if v.id = my_id then ( min my_hash (pow_hash_exn x) , replace_hash , x :: mine , nmine + 1 , theirs , ntheirs ) else my_hash, replace_hash, mine, nmine, x :: theirs, ntheirs + 1 | Block _ -> my_hash, min replace_hash (leader_hash_exn x), mine, nmine, theirs, ntheirs) (max_pow, max_pow, [], 0, [], 0) (confirming_votes b |> List.filter vote_filter) in if replace_hash <= my_hash || nmine + ntheirs < k then (* fast path *) None else if nmine >= k then Compare.first Compare.(by compare_pow pow_hash_exn) k mine else ( let theirs, ntheirs = List.fold_left (fun (theirs, ntheirs) vote -> if pow_hash_exn vote > my_hash then vote :: theirs, ntheirs + 1 else theirs, ntheirs) ([], 0) theirs in if ntheirs < k - nmine then (* fast path *) None else ( let theirs = Compare.first Compare.(by float visible_since (* TODO maybe use received_at? *)) (k - nmine) theirs |> Option.get in mine @ theirs |> List.sort Compare.(by compare_pow pow_hash_exn) |> Option.some)) ;; let puzzle_payload preferred = { parents = [ preferred ] ; sign = false ; data = Vote { id = my_id; height = block_height_exn preferred } } ;; let propose ?(vote_filter = Fun.const true) b = quorum ~vote_filter b |> Option.map (fun q -> { parents = b :: q ; data = Block { height = block_height_exn b + 1 } ; sign = true }) ;; let handler preferred = function | Append x | Network x | ProofOfWork x -> let b = last_block x in let append = match propose b with | Some block -> [ block ] | None -> [] and share = match visibility x with | `Withheld -> [ x ] | _ -> [] in update_head ~old:preferred b |> return ~append ~share ;; end let honest (type a) ((module V) : (a, data) view) : (a, data) node = Node (module Honest (V)) ;; end
null
https://raw.githubusercontent.com/pkel/cpr/92bebe4abf723a2ab875f6a1891df1f2fc1ce275/simulator/protocols/bk.ml
ocaml
* number of votes (= puzzle solutions) per block * better is bigger happens for genesis node fast path fast path TODO maybe use received_at?
open Cpr_lib let incentive_schemes = [ `Block; `Constant ] module type Parameters = sig val k : int val incentive_scheme : [ `Block | `Constant ] end module Make (Parameters : Parameters) = struct open Parameters let key = Format.asprintf "bk-%i-%a" k Options.pp incentive_scheme let description = Format.asprintf "Bₖ with k=%i and %a rewards" k Options.pp incentive_scheme ;; let info = let open Info in [ string "family" "bk"; int "k" k; Options.info "incentive_scheme" incentive_scheme ] ;; type block_data = { height : int } type vote_data = { height : int ; id : int } type data = | Vote of vote_data | Block of block_data let height = function | Vote x -> x.height | Block x -> x.height ;; let progress x = match x with | Vote _ -> (height x * k) + 1 |> float_of_int | Block _ -> height x * k |> float_of_int ;; let roots = [ Block { height = 0 } ] module Referee (D : BlockDAG with type data = data) = struct include D let info x = let open Info in match data x with | Vote x -> [ string "kind" "vote"; int "height" x.height; int "id" x.id ] | Block x -> [ string "kind" "block"; int "height" x.height ] ;; let label x = match data x with | Vote _x -> "vote" | Block { height } -> "block " ^ string_of_int height ;; let is_vote x = match data x with | Vote _ -> true | _ -> false ;; let is_block x = match data x with | Block _ -> true | _ -> false ;; let last_block x = match data x with | Block _ -> x | Vote _ -> (match parents x with | [ x ] -> x | _ -> let info _v = [] in raise_invalid_dag info [ x ] "last block hits root") ;; let height x = data x |> height let progress x = data x |> progress let block_height_exn x = match data x with | Block b -> b.height | _ -> let info _v = [] in raise_invalid_dag info [ x ] "block_height_exn: not a block" ;; let confirming_votes x = assert (is_block x); children x |> List.filter is_vote ;; let confirmed_votes x = assert (is_block x); parents x |> List.filter is_vote ;; let validity vertex = let has_pow x = pow x |> Option.is_some and pow_hash x = pow x |> Option.get in match data vertex, parents vertex with | Vote v, [ p ] -> has_pow vertex && is_block p && v.height = height p | Block b, pblock :: vote0 :: votes -> (match data pblock, data vote0 with | Block p, Vote leader -> let ordered_votes, _, nvotes = List.fold_left (fun (ok, h, i) n -> let h' = pow_hash n in is_vote n && compare_pow h' h > 0 && ok, h', i + 1) (true, pow_hash vote0, 1) votes in p.height + 1 = b.height && nvotes = k && ordered_votes && signature vertex = Some leader.id | _ -> false) | _ -> false ;; let compare_blocks = let open Compare in let cmp = by int block_height_exn $ by int (fun x -> List.length (confirming_votes x)) in skip_eq Block.eq cmp ;; let winner = function | [] -> failwith "bk.winner: empty list" | hd :: tl -> List.fold_left (fun acc x -> if compare_blocks x acc > 0 then x else acc) hd tl ;; let precursor this = List.nth_opt (parents this) 0 let constant x = if is_block x then List.filter_map (fun y -> match data y with | Vote v -> Some (v.id, 1.) | Block _ -> None) (parents x) else [] ;; let block x = if is_block x then ( match signature x with | Some i -> [ i, float_of_int k ] | None -> []) else [] ;; let reward = match incentive_scheme with | `Block -> block | `Constant -> constant ;; end let referee (type a) (module D : BlockDAG with type block = a and type data = data) : (a, data) referee = (module Referee (D)) ;; module Honest (V : View with type data = data) = struct include V open Referee (V) type state = block let preferred state = state let init ~roots = match roots with | [ genesis ] -> genesis | _ -> failwith "invalid roots" ;; let appended_by_me x = match visibility x with | `Received -> false | `Withheld | `Released -> true ;; let leader_hash_exn x = if not (is_block x) then raise (Invalid_argument "not a block"); match parents x with | _b :: v0 :: _ -> (match pow v0 with | Some x -> x | None -> raise (Invalid_argument "invalid dag / vote")) | _ -> max_pow ;; let compare_blocks ~vote_filter = let open Compare in let cmp = by int block_height_exn $ by int (fun x -> List.length (confirming_votes x |> List.filter vote_filter)) $ by (neg compare_pow) leader_hash_exn TODO . Maybe this should be received_at ? in skip_eq Block.eq cmp ;; let update_head ?(vote_filter = Fun.const true) ~old consider = assert (is_block consider); if compare_blocks ~vote_filter consider old > 0 then consider else old ;; let quorum ~vote_filter b = let pow_hash_exn x = pow x |> Option.get in let my_hash, replace_hash, mine, nmine, theirs, ntheirs = List.fold_left (fun (my_hash, replace_hash, mine, nmine, theirs, ntheirs) x -> match data x with | Vote v -> if v.id = my_id then ( min my_hash (pow_hash_exn x) , replace_hash , x :: mine , nmine + 1 , theirs , ntheirs ) else my_hash, replace_hash, mine, nmine, x :: theirs, ntheirs + 1 | Block _ -> my_hash, min replace_hash (leader_hash_exn x), mine, nmine, theirs, ntheirs) (max_pow, max_pow, [], 0, [], 0) (confirming_votes b |> List.filter vote_filter) in if replace_hash <= my_hash || nmine + ntheirs < k else if nmine >= k then Compare.first Compare.(by compare_pow pow_hash_exn) k mine else ( let theirs, ntheirs = List.fold_left (fun (theirs, ntheirs) vote -> if pow_hash_exn vote > my_hash then vote :: theirs, ntheirs + 1 else theirs, ntheirs) ([], 0) theirs in if ntheirs < k - nmine else ( let theirs = Compare.first (k - nmine) theirs |> Option.get in mine @ theirs |> List.sort Compare.(by compare_pow pow_hash_exn) |> Option.some)) ;; let puzzle_payload preferred = { parents = [ preferred ] ; sign = false ; data = Vote { id = my_id; height = block_height_exn preferred } } ;; let propose ?(vote_filter = Fun.const true) b = quorum ~vote_filter b |> Option.map (fun q -> { parents = b :: q ; data = Block { height = block_height_exn b + 1 } ; sign = true }) ;; let handler preferred = function | Append x | Network x | ProofOfWork x -> let b = last_block x in let append = match propose b with | Some block -> [ block ] | None -> [] and share = match visibility x with | `Withheld -> [ x ] | _ -> [] in update_head ~old:preferred b |> return ~append ~share ;; end let honest (type a) ((module V) : (a, data) view) : (a, data) node = Node (module Honest (V)) ;; end
e82d445de228cf781574587fc291ee72e27c324875eba63282e38a680a5aaed6
mzp/coq-for-ipad
useunix.mli
(*************************************************************************) (* *) (* Objective Caml LablTk library *) (* *) , Kyoto University RIMS (* *) Copyright 1999 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library (* General Public License, with the special exception on linking *) (* described in file ../../../LICENSE. *) (* *) (*************************************************************************) $ I d : useunix.mli 5094 2002 - 08 - 09 10:34:44Z garrigue $ (* Unix utilities *) val get_files_in_directory : string -> string list val is_directory : string -> bool val concat : string -> string -> string val get_directories_in_files : path:string -> string list -> string list val subshell : cmd:string -> string list
null
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/otherlibs/labltk/browser/useunix.mli
ocaml
*********************************************************************** Objective Caml LablTk library General Public License, with the special exception on linking described in file ../../../LICENSE. *********************************************************************** Unix utilities
, Kyoto University RIMS Copyright 1999 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library $ I d : useunix.mli 5094 2002 - 08 - 09 10:34:44Z garrigue $ val get_files_in_directory : string -> string list val is_directory : string -> bool val concat : string -> string -> string val get_directories_in_files : path:string -> string list -> string list val subshell : cmd:string -> string list
9b566a4ac3c530583b311543c5418d2465fc774dca90519f34c08fd387fc68a9
linoscope/caml8
memory.ml
open Base open Ints type t = bytes let create () = Bytes.create 4096 let of_bytes b = b let size t = Bytes.length t let load t ~src ~dst_pos = Bytes.blito ~src ~dst:t ~dst_pos:(Uint16.to_int dst_pos) () let read_uint16 t ~pos = pos |> Uint16.to_int |> Caml.Bytes.get_int16_be t |> Uint16.of_int let read_uint8 t ~pos = pos |> Uint16.to_int |> Caml.Bytes.get_int8 t |> Uint8.of_int let write_uint16 t ~pos x = Caml.Bytes.set_int16_be t (Uint16.to_int pos) (Uint16.to_int x) let write_uint8 t ~pos x = Caml.Bytes.set_int8 t (Uint16.to_int pos) (Uint8.to_int x) let dump t ~pos ~len = let buf = Buffer.create 100 in for i = 0 to len - 1 do read_uint8 t ~pos:(pos + len + i * 2 |> Uint16.of_int) |> Uint8.to_int |> Printf.sprintf "%x\n" |> Buffer.add_string buf; done; Buffer.contents buf
null
https://raw.githubusercontent.com/linoscope/caml8/03c2f6d788ea430457a0d65872d4d142094147ce/lib/memory.ml
ocaml
open Base open Ints type t = bytes let create () = Bytes.create 4096 let of_bytes b = b let size t = Bytes.length t let load t ~src ~dst_pos = Bytes.blito ~src ~dst:t ~dst_pos:(Uint16.to_int dst_pos) () let read_uint16 t ~pos = pos |> Uint16.to_int |> Caml.Bytes.get_int16_be t |> Uint16.of_int let read_uint8 t ~pos = pos |> Uint16.to_int |> Caml.Bytes.get_int8 t |> Uint8.of_int let write_uint16 t ~pos x = Caml.Bytes.set_int16_be t (Uint16.to_int pos) (Uint16.to_int x) let write_uint8 t ~pos x = Caml.Bytes.set_int8 t (Uint16.to_int pos) (Uint8.to_int x) let dump t ~pos ~len = let buf = Buffer.create 100 in for i = 0 to len - 1 do read_uint8 t ~pos:(pos + len + i * 2 |> Uint16.of_int) |> Uint8.to_int |> Printf.sprintf "%x\n" |> Buffer.add_string buf; done; Buffer.contents buf
a89e910fb2733bffdd59a97605091c6085d42bd8d71c0bc8175b58ce521734a4
kwanghoon/polyrpc
Literal.hs
# LANGUAGE DeriveDataTypeable , DeriveGeneric # module Literal where import Type import Text.JSON.Generic import qualified Data.Aeson as DA import GHC.Generics import Data.Text.Prettyprint.Doc hiding (Pretty) import Data.Text.Prettyprint.Doc.Util data Literal = IntLit Int | StrLit String | BoolLit Bool | UnitLit For -- deriving (Show, Generic) deriving (Eq, Read, Show, Typeable, Data, Generic) instance DA.FromJSON Literal instance DA.ToJSON Literal typeOfLiteral (IntLit _) = int_type typeOfLiteral (StrLit _) = string_type typeOfLiteral (BoolLit _) = bool_type typeOfLiteral (UnitLit) = unit_type trueLit = "True" falseLit = "False" unitLit = "()" --- ppLit (IntLit i) = pretty (show i) ppLit (StrLit s) = dquote <> pretty s <> dquote ppLit (BoolLit b) = pretty (show b) ppLit (UnitLit) = lparen <> rparen
null
https://raw.githubusercontent.com/kwanghoon/polyrpc/49ba773bd3f1b22dce1ad64cda44683553d27c89/app/ast/Literal.hs
haskell
deriving (Show, Generic) -
# LANGUAGE DeriveDataTypeable , DeriveGeneric # module Literal where import Type import Text.JSON.Generic import qualified Data.Aeson as DA import GHC.Generics import Data.Text.Prettyprint.Doc hiding (Pretty) import Data.Text.Prettyprint.Doc.Util data Literal = IntLit Int | StrLit String | BoolLit Bool | UnitLit For deriving (Eq, Read, Show, Typeable, Data, Generic) instance DA.FromJSON Literal instance DA.ToJSON Literal typeOfLiteral (IntLit _) = int_type typeOfLiteral (StrLit _) = string_type typeOfLiteral (BoolLit _) = bool_type typeOfLiteral (UnitLit) = unit_type trueLit = "True" falseLit = "False" unitLit = "()" ppLit (IntLit i) = pretty (show i) ppLit (StrLit s) = dquote <> pretty s <> dquote ppLit (BoolLit b) = pretty (show b) ppLit (UnitLit) = lparen <> rparen
f1038733962ebb143154b532275d501c04e1b7921d764bc1e5e8bca29554e56e
grin-compiler/ghc-wpc-sample-programs
AbsURIs.hs
-- ------------------------------------------------------------ | Module : AbsURIs Copyright : Copyright ( C ) 2005 License : MIT Maintainer : Maintainer : Stability : experimental Portability : portable AbsURIs - Conversion references into absolute URIs in HTML pages The commandline interface Module : AbsURIs Copyright : Copyright (C) 2005 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt Maintainer : Stability : experimental Portability: portable AbsURIs - Conversion references into absolute URIs in HTML pages The commandline interface -} -- ------------------------------------------------------------ module Main where import Text.XML.HXT.Core -- import all stuff for parsing, validating, and transforming XML import the IO and commandline option stuff import System.Environment import System.Console.GetOpt import System.Exit import ProcessDocument -- ------------------------------------------------------------ -- | the main program of the Haskell XML Validating Parser main :: IO () main = do argv <- getArgs -- get the commandline arguments (al, src) <- cmdlineOpts argv -- and evaluate them, return a key-value list [rc] <- runX (parser al src) -- run the parser arrow exitProg (rc >= c_err) -- set return code and terminate -- ------------------------------------------------------------ exitProg :: Bool -> IO a exitProg True = exitWith (ExitFailure 1) exitProg False = exitWith ExitSuccess -- ------------------------------------------------------------ -- | -- the /real/ main program -- -- get wellformed document, validates document, propagates and check namespaces -- and controls output parser :: SysConfigList -> String -> IOSArrow b Int parser config src = configSysVars config -- set all global config options >>> readDocument [withParseHTML yes] src -- use HTML parser >>> traceMsg 1 "start processing" >>> processDocument >>> traceMsg 1 "processing finished" >>> traceSource >>> traceTree >>> ( writeDocument [] $< getSysAttr "output-file" ) >>> getErrStatus -- ------------------------------------------------------------ -- -- the options definition part see doc for System . Console . progName :: String progName = "AbsURIs" options :: [OptDescr SysConfig] options = generalOptions ++ inputOptions ++ [ Option "f" ["output-file"] (ReqArg (withSysAttr "output-file") "FILE") "output file for resulting document (default: stdout)" ] ++ outputOptions ++ showOptions usage :: [String] -> IO a usage errl | null errl = do hPutStrLn stdout use exitProg False | otherwise = do hPutStrLn stderr (concat errl ++ "\n" ++ use) exitProg True where header = progName ++ " - Convert all references in an HTML document into absolute URIs\n\n" ++ "Usage: " ++ progName ++ " [OPTION...] [URI or FILE]" use = usageInfo header options cmdlineOpts :: [String] -> IO (SysConfigList, String) cmdlineOpts argv = case (getOpt Permute options argv) of (scfg,n,[]) -> do sa <- src n help (getConfigAttr a_help scfg) sa return (scfg, sa) (_,_,errs) -> usage errs where src [] = return [] src [uri] = return uri src _ = usage ["only one input uri or file allowed\n"] help "1" _ = usage [] help _ [] = usage ["no input uri or file given\n"] help _ _ = return () -- ------------------------------------------------------------
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/hxt-9.3.1.18/examples/arrows/absurls/AbsURIs.hs
haskell
------------------------------------------------------------ ------------------------------------------------------------ import all stuff for parsing, validating, and transforming XML ------------------------------------------------------------ | get the commandline arguments and evaluate them, return a key-value list run the parser arrow set return code and terminate ------------------------------------------------------------ ------------------------------------------------------------ | the /real/ main program get wellformed document, validates document, propagates and check namespaces and controls output set all global config options use HTML parser ------------------------------------------------------------ the options definition part ------------------------------------------------------------
| Module : AbsURIs Copyright : Copyright ( C ) 2005 License : MIT Maintainer : Maintainer : Stability : experimental Portability : portable AbsURIs - Conversion references into absolute URIs in HTML pages The commandline interface Module : AbsURIs Copyright : Copyright (C) 2005 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt Maintainer : Stability : experimental Portability: portable AbsURIs - Conversion references into absolute URIs in HTML pages The commandline interface -} module Main where import the IO and commandline option stuff import System.Environment import System.Console.GetOpt import System.Exit import ProcessDocument the main program of the Haskell XML Validating Parser main :: IO () main = do exitProg :: Bool -> IO a exitProg True = exitWith (ExitFailure 1) exitProg False = exitWith ExitSuccess parser :: SysConfigList -> String -> IOSArrow b Int parser config src >>> >>> traceMsg 1 "start processing" >>> processDocument >>> traceMsg 1 "processing finished" >>> traceSource >>> traceTree >>> ( writeDocument [] $< getSysAttr "output-file" ) >>> getErrStatus see doc for System . Console . progName :: String progName = "AbsURIs" options :: [OptDescr SysConfig] options = generalOptions ++ inputOptions ++ [ Option "f" ["output-file"] (ReqArg (withSysAttr "output-file") "FILE") "output file for resulting document (default: stdout)" ] ++ outputOptions ++ showOptions usage :: [String] -> IO a usage errl | null errl = do hPutStrLn stdout use exitProg False | otherwise = do hPutStrLn stderr (concat errl ++ "\n" ++ use) exitProg True where header = progName ++ " - Convert all references in an HTML document into absolute URIs\n\n" ++ "Usage: " ++ progName ++ " [OPTION...] [URI or FILE]" use = usageInfo header options cmdlineOpts :: [String] -> IO (SysConfigList, String) cmdlineOpts argv = case (getOpt Permute options argv) of (scfg,n,[]) -> do sa <- src n help (getConfigAttr a_help scfg) sa return (scfg, sa) (_,_,errs) -> usage errs where src [] = return [] src [uri] = return uri src _ = usage ["only one input uri or file allowed\n"] help "1" _ = usage [] help _ [] = usage ["no input uri or file given\n"] help _ _ = return ()
249754e8ccbc53d9237520f4bc2ca99875d3efb7aa435468b1018b717d9c3939
idris-hackers/idris-java
CodegenJava.hs
# LANGUAGE PatternGuards # # LANGUAGE ViewPatterns # module IRTS.CodegenJava (codegenJava) where import Idris.Core.TT hiding (mkApp) import IRTS.CodegenCommon import IRTS.Java.ASTBuilding import IRTS.Java.JTypes import IRTS.Java.Mangling import IRTS.Java.Pom (pomString) import IRTS.Lang import IRTS.Simplified import IRTS.System import Util.System import Control.Applicative hiding (Const) import Control.Arrow import Control.Monad import Control.Monad.Except import qualified Control.Monad.Trans as T import Control.Monad.Trans.State import Data.List (foldl', isSuffixOf) import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Data.Vector.Unboxed as V import Data.Maybe import Language.Java.Parser import Language.Java.Pretty import Language.Java.Syntax hiding (Name) import qualified Language.Java.Syntax as J import System.Directory import System.Exit import System.FilePath import System.IO import System.Process ----------------------------------------------------------------------- -- Main function codegenJava :: CodeGenerator codegenJava cg = codegenJava' [] (simpleDecls cg) (outputFile cg) (includes cg) (compileLibs cg) (outputType cg) codegenJava' :: [(Name, SExp)] -> -- initialization of globals [(Name, SDecl)] -> -- decls FilePath -> -- output file name [String] -> -- headers libs OutputType -> IO () codegenJava' globalInit defs out hdrs libs exec = do withTgtDir exec out (codegenJava' exec) where codegenJava' :: OutputType -> FilePath -> IO () codegenJava' Raw tgtDir = do srcDir <- prepareSrcDir exec tgtDir generateJavaFile globalInit defs hdrs srcDir out codegenJava' MavenProject tgtDir = do codegenJava' Raw tgtDir generatePom tgtDir out libs codegenJava' Object tgtDir = do codegenJava' MavenProject tgtDir invokeMvn tgtDir "compile" copyClassFiles tgtDir out cleanUpTmp tgtDir codegenJava' Executable tgtDir = do codegenJava' MavenProject tgtDir invokeMvn tgtDir "package"; copyJar tgtDir out makeJarExecutable out cleanUpTmp tgtDir ----------------------------------------------------------------------- Compiler IO withTgtDir :: OutputType -> FilePath -> (FilePath -> IO ()) -> IO () withTgtDir Raw out action = action (dropFileName out) withTgtDir MavenProject out action = createDirectoryIfMissing False out >> action out withTgtDir _ out action = withTempdir (takeBaseName out) action prepareSrcDir :: OutputType -> FilePath -> IO FilePath prepareSrcDir Raw tgtDir = return tgtDir prepareSrcDir _ tgtDir = do let srcDir = (tgtDir </> "src" </> "main" </> "java") createDirectoryIfMissing True srcDir return srcDir javaFileName :: FilePath -> FilePath -> FilePath javaFileName srcDir out = either error (\ (Ident clsName) -> srcDir </> clsName <.> "java") (mkClassName out) generateJavaFile :: [(Name, SExp)] -> -- initialization of globals [(Name, SDecl)] -> -- definitions [String] -> -- headers FilePath -> -- Source dir FilePath -> -- output target IO () generateJavaFile globalInit defs hdrs srcDir out = do let code = either error (prettyPrint)-- flatIndent . prettyPrint) (evalStateT (mkCompilationUnit globalInit defs hdrs out) mkCodeGenEnv) writeFile (javaFileName srcDir out) code --writeFile (javaFileName "/Users/br-gaster/dev/" out) code pomFileName :: FilePath -> FilePath pomFileName tgtDir = tgtDir </> "pom.xml" generatePom :: FilePath -> -- tgt dir FilePath -> -- output target libs IO () generatePom tgtDir out libs = do writeFile (pomFileName tgtDir) execPom -- writeFile (pomFileName "/Users/br-gaster/dev/") execPom where (Ident clsName) = either error id (mkClassName out) execPom = pomString clsName (takeBaseName out) libs invokeMvn :: FilePath -> String -> IO () invokeMvn tgtDir command = do mvnCmd <- getMvn let args = ["-f", pomFileName tgtDir] (exit, mvout, err) <- readProcessWithExitCode mvnCmd (args ++ [command]) "" when (exit /= ExitSuccess) $ error ("FAILURE: " ++ mvnCmd ++ " " ++ command ++ "\n" ++ err ++ mvout) classFileDir :: FilePath -> FilePath classFileDir tgtDir = tgtDir </> "target" </> "classes" copyClassFiles :: FilePath -> FilePath -> IO () copyClassFiles tgtDir out = do classFiles <- map (\ clsFile -> classFileDir tgtDir </> clsFile) . filter ((".class" ==) . takeExtension) <$> getDirectoryContents (classFileDir tgtDir) mapM_ (\ clsFile -> copyFile clsFile (takeDirectory out </> takeFileName clsFile)) classFiles jarFileName :: FilePath -> FilePath -> FilePath jarFileName tgtDir out = tgtDir </> "target" </> (takeBaseName out) <.> "jar" copyJar :: FilePath -> FilePath -> IO () copyJar tgtDir out = copyFile (jarFileName tgtDir out) out makeJarExecutable :: FilePath -> IO () makeJarExecutable out = do handle <- openBinaryFile out ReadMode contents <- TIO.hGetContents handle hClose handle handle <- openBinaryFile out WriteMode TIO.hPutStr handle (T.append (T.pack jarHeader) contents) hFlush handle hClose handle perms <- getPermissions out setPermissions out (setOwnerExecutable True perms) removePom :: FilePath -> IO () removePom tgtDir = removeFile (pomFileName tgtDir) cleanUpTmp :: FilePath -> IO () cleanUpTmp tgtDir = do invokeMvn tgtDir "clean" removePom tgtDir ----------------------------------------------------------------------- -- Jar and Pom infrastructure jarHeader :: String jarHeader = "#!/usr/bin/env sh\n" ++ "MYSELF=`which \"$0\" 2>/dev/null`\n" ++ "[ $? -gt 0 -a -f \"$0\" ] && MYSELF=\"./$0\"\n" ++ "java=java\n" ++ "if test -n \"$JAVA_HOME\"; then\n" ++ " java=\"$JAVA_HOME/bin/java\"\n" ++ "fi\n" ++ "exec \"$java\" $java_args -jar $MYSELF \"$@\"\n" ++ "exit 1\n" ----------------------------------------------------------------------- -- Code generation environment data CodeGenerationEnv = CodeGenerationEnv { globalVariables :: [(Name, ArrayIndex)] , localVariables :: [[(Int, Ident)]] , localVarCounter :: Int } type CodeGeneration = StateT (CodeGenerationEnv) (Either String) mkCodeGenEnv :: CodeGenerationEnv mkCodeGenEnv = CodeGenerationEnv [] [] 0 varPos :: LVar -> CodeGeneration (Either ArrayIndex Ident) varPos (Loc i) = do vars <- (concat . localVariables) <$> get case lookup i vars of (Just varName) -> return (Right varName) Nothing -> throwError $ "Invalid local variable id: " ++ show i varPos (Glob name) = do vars <- globalVariables <$> get case lookup name vars of (Just varIdx) -> return (Left varIdx) Nothing -> throwError $ "Invalid global variable id: " ++ show name pushScope :: CodeGeneration () pushScope = modify (\ env -> env { localVariables = []:(localVariables env) }) popScope :: CodeGeneration () popScope = do env <- get let lVars = tail $ localVariables env let vC = if null lVars then 0 else localVarCounter env put $ env { localVariables = tail (localVariables env) , localVarCounter = vC } setVariable :: LVar -> CodeGeneration (Either ArrayIndex Ident) setVariable (Loc i) = do env <- get let lVars = localVariables env let getter = localVar $ localVarCounter env let lVars' = ((i, getter) : head lVars) : tail lVars put $ env { localVariables = lVars' , localVarCounter = 1 + localVarCounter env} return (Right getter) setVariable (Glob n) = do env <- get let gVars = globalVariables env let getter = globalContext @! length gVars let gVars' = (n, getter):gVars put (env { globalVariables = gVars' }) return (Left getter) pushParams :: [Ident] -> CodeGeneration () pushParams paramNames = let varMap = zipWith (flip (,)) paramNames [0..] in modify (\ env -> env { localVariables = varMap:(localVariables env) , localVarCounter = (length varMap) + (localVarCounter env) }) flatIndent :: String -> String flatIndent (' ' : ' ' : xs) = flatIndent xs flatIndent (x:xs) = x:flatIndent xs flatIndent [] = [] ----------------------------------------------------------------------- -- Maintaining control structures over code blocks data BlockPostprocessor = BlockPostprocessor { ppInnerBlock :: [BlockStmt] -> Exp -> CodeGeneration [BlockStmt] , ppOuterBlock :: [BlockStmt] -> CodeGeneration [BlockStmt] } ppExp :: BlockPostprocessor -> Exp -> CodeGeneration [BlockStmt] ppExp pp exp = ((ppInnerBlock pp) [] exp) >>= ppOuterBlock pp addReturn :: BlockPostprocessor addReturn = BlockPostprocessor { ppInnerBlock = (\ block exp -> return $ block ++ [jReturn exp]) , ppOuterBlock = return } ignoreResult :: BlockPostprocessor ignoreResult = BlockPostprocessor { ppInnerBlock = (\ block exp -> return block) , ppOuterBlock = return } ignoreOuter :: BlockPostprocessor -> BlockPostprocessor ignoreOuter pp = pp { ppOuterBlock = return } throwRuntimeException :: BlockPostprocessor -> BlockPostprocessor throwRuntimeException pp = pp { ppInnerBlock = (\ blk exp -> return $ blk ++ [ BlockStmt $ Throw ( InstanceCreation [] (toClassType runtimeExceptionType) [exp] Nothing ) ] ) } rethrowAsRuntimeException :: BlockPostprocessor -> BlockPostprocessor rethrowAsRuntimeException pp = pp { ppOuterBlock = (\ blk -> do ex <- ppInnerBlock (throwRuntimeException pp) [] (ExpName $ J.Name [Ident "ex"]) ppOuterBlock pp $ [ BlockStmt $ Try (Block blk) [Catch (FormalParam [] exceptionType False (VarId (Ident "ex"))) $ Block ex ] Nothing ] ) } ----------------------------------------------------------------------- -- File structure mkCompilationUnit :: [(Name, SExp)] -> [(Name, SDecl)] -> [String] -> FilePath -> CodeGeneration CompilationUnit mkCompilationUnit globalInit defs hdrs out = do clsName <- mkClassName out CompilationUnit Nothing ( [ ImportDecl False idrisRts True , ImportDecl True idrisPrelude True , ImportDecl False bigInteger False , ImportDecl False runtimeException False , ImportDecl False byteBuffer False ] ++ otherHdrs ) <$> mkTypeDecl clsName globalInit defs where idrisRts = J.Name $ map Ident ["org", "idris", "rts"] idrisPrelude = J.Name $ map Ident ["org", "idris", "rts", "Prelude"] bigInteger = J.Name $ map Ident ["java", "math", "BigInteger"] runtimeException = J.Name $ map Ident ["java", "lang", "RuntimeException"] byteBuffer = J.Name $ map Ident ["java", "nio", "ByteBuffer"] otherHdrs = map ( (\ name -> ImportDecl False name False) . J.Name . map (Ident . T.unpack) . T.splitOn (T.pack ".") . T.pack) $ filter (not . isSuffixOf ".h") hdrs ----------------------------------------------------------------------- -- Main class mkTypeDecl :: Ident -> [(Name, SExp)] -> [(Name, SDecl)] -> CodeGeneration [TypeDecl] mkTypeDecl name globalInit defs = (\ body -> [ClassTypeDecl $ ClassDecl [ Public , Annotation $ SingleElementAnnotation (jName "SuppressWarnings") (EVVal . InitExp $ jString "unchecked") ] name [] Nothing [] body]) <$> mkClassBody globalInit (map (second (prefixCallNamespaces name)) defs) mkClassBody :: [(Name, SExp)] -> [(Name, SDecl)] -> CodeGeneration ClassBody mkClassBody globalInit defs = (\ globals defs -> ClassBody . (globals++) . addMainMethod . mergeInnerClasses $ defs) <$> mkGlobalContext globalInit <*> mapM mkDecl defs mkGlobalContext :: [(Name, SExp)] -> CodeGeneration [Decl] mkGlobalContext [] = return [] mkGlobalContext initExps = do pushScope varInit <- mapM (\ (name, exp) -> do pos <- setVariable (Glob name) mkUpdate ignoreResult (Glob name) exp ) initExps popScope return [ MemberDecl $ FieldDecl [Private, Static, Final] (array objectType) [ VarDecl (VarId $ globalContextID). Just . InitExp $ ArrayCreate objectType [jInt $ length initExps] 0 ] , InitDecl True (Block $ concat varInit) ] addMainMethod :: [Decl] -> [Decl] addMainMethod decls | findMainMethod decls = mkMainMethod : decls | otherwise = decls where findMainMethod ((MemberDecl (MethodDecl _ _ _ name [] _ _)):_) | name == mangle' (sMN 0 "runMain") = True findMainMethod (_:decls) = findMainMethod decls findMainMethod [] = False mkMainMethod :: Decl mkMainMethod = simpleMethod [Public, Static] Nothing "main" [FormalParam [] (array stringType) False (VarId $ Ident "args")] $ Block [ BlockStmt . ExpStmt $ call "idris_initArgs" [ jConst "args" ] , BlockStmt . ExpStmt $ call (mangle' (sMN 0 "runMain")) [] ] ----------------------------------------------------------------------- Inner classes ( namespaces ) mergeInnerClasses :: [Decl] -> [Decl] mergeInnerClasses = foldl' mergeInner [] where mergeInner ((decl@(MemberDecl (MemberClassDecl (ClassDecl priv name targs ext imp (ClassBody body))))):decls) decl'@(MemberDecl (MemberClassDecl (ClassDecl _ name' _ ext' imp' (ClassBody body')))) | name == name' = (MemberDecl $ MemberClassDecl $ ClassDecl priv name targs (mplus ext ext') (imp ++ imp') (ClassBody $ mergeInnerClasses (body ++ body'))) : decls | otherwise = decl:(mergeInner decls decl') mergeInner (decl:decls) decl' = decl:(mergeInner decls decl') mergeInner [] decl' = [decl'] mkDecl :: (Name, SDecl) -> CodeGeneration Decl mkDecl ((NS n (ns:nss)), decl) = (\ name body -> MemberDecl $ MemberClassDecl $ ClassDecl [Public, Static] name [] Nothing [] body) <$> mangle (UN ns) <*> mkClassBody [] [(NS n nss, decl)] mkDecl (_, SFun name params stackSize body) = do (Ident methodName) <- mangle name methodParams <- mapM mkFormalParam params paramNames <- mapM mangle params pushParams paramNames methodBody <- mkExp addReturn body popScope return $ simpleMethod [Public, Static] (Just objectType) methodName methodParams (Block methodBody) mkFormalParam :: Name -> CodeGeneration FormalParam mkFormalParam name = (\ name -> FormalParam [Final] objectType False (VarId name)) <$> mangle name ----------------------------------------------------------------------- -- Expressions -- | Compile a simple expression and use the given continuation to postprocess -- the resulting value. mkExp :: BlockPostprocessor -> SExp -> CodeGeneration [BlockStmt] -- Variables mkExp pp (SV var) = (Nothing <>@! var) >>= ppExp pp -- Applications mkExp pp (SApp pushTail name args) = mkApp pushTail name args >>= ppExp pp -- Bindings mkExp pp (SLet var newExp inExp) = mkLet pp var newExp inExp mkExp pp (SUpdate var@(Loc i) newExp) = -- can only update locals mkUpdate pp var newExp mkExp pp (SUpdate var newExp) = mkExp pp newExp -- Objects mkExp pp (SCon _ conId _ args) = mkIdrisObject conId args >>= ppExp pp -- Case expressions mkExp pp (SCase up var alts) = mkCase pp True var alts mkExp pp (SChkCase var alts) = mkCase pp False var alts -- Projections mkExp pp (SProj var i) = mkProjection var i >>= ppExp pp -- Constants mkExp pp (SConst c) = ppExp pp $ mkConstant c -- Foreign function calls mkExp pp f@(SForeign t fname args) = mkForeign pp t fname args -- Primitive functions mkExp pp (SOp LFork [arg]) = (mkThread arg) >>= ppExp pp mkExp pp (SOp LPar [arg]) = (Nothing <>@! arg) >>= ppExp pp mkExp pp (SOp LNoOp args) = (Nothing <>@! (last args)) >>= ppExp pp mkExp pp (SOp op args) = (mkPrimitiveFunction op args) >>= ppExp pp -- Empty expressions mkExp pp (SNothing) = ppExp pp $ Lit Null -- Errors mkExp pp (SError err) = ppExp (throwRuntimeException pp) (jString err) ----------------------------------------------------------------------- -- Variable access (<>@!) :: Maybe J.Type -> LVar -> CodeGeneration Exp (<>@!) Nothing var = either ArrayAccess (\ n -> ExpName $ J.Name [n]) <$> varPos var (<>@!) (Just castTo) var = (castTo <>) <$> (Nothing <>@! var) ----------------------------------------------------------------------- -- Application (wrap method calls in tail call closures) mkApp :: Bool -> Name -> [LVar] -> CodeGeneration Exp mkApp False name args = (\ methodName params -> (idrisClosureType ~> "unwrapTailCall") [call methodName params] ) <$> mangleFull name <*> mapM (Nothing <>@!) args mkApp True name args = mkMethodCallClosure name args mkMethodCallClosure :: Name -> [LVar] -> CodeGeneration Exp mkMethodCallClosure name args = (\ name args -> closure (call name args)) <$> mangleFull name <*> mapM (Nothing <>@!) args ----------------------------------------------------------------------- -- Updates (change context array) and Let bindings (Update, execute) mkUpdate :: BlockPostprocessor -> LVar -> SExp -> CodeGeneration [BlockStmt] mkUpdate pp var exp = mkExp ( pp { ppInnerBlock = (\ blk rhs -> do pos <- setVariable var vExp <- Nothing <>@! var ppInnerBlock pp (blk ++ [pos @:= rhs]) vExp ) } ) exp mkLet :: BlockPostprocessor -> LVar -> SExp -> SExp -> CodeGeneration [BlockStmt] mkLet pp var@(Loc pos) newExp inExp = mkUpdate (pp { ppInnerBlock = (\ blk _ -> do inBlk <- mkExp pp inExp return (blk ++ inBlk) ) } ) var newExp mkLet _ (Glob _) _ _ = T.lift $ Left "Cannot let bind to global variable" ----------------------------------------------------------------------- -- Object creation mkIdrisObject :: Int -> [LVar] -> CodeGeneration Exp mkIdrisObject conId args = (\ args -> InstanceCreation [] (toClassType idrisObjectType) ((jInt conId):args) Nothing ) <$> mapM (Nothing <>@!) args ----------------------------------------------------------------------- -- Case expressions mkCase :: BlockPostprocessor -> Bool -> LVar -> [SAlt] -> CodeGeneration [BlockStmt] mkCase pp checked var cases | isDefaultOnlyCase cases = mkDefaultMatch pp cases | isConstCase cases = do ifte <- mkConstMatch (ignoreOuter pp) (\ pp -> mkDefaultMatch pp cases) var cases ppOuterBlock pp [BlockStmt ifte] | otherwise = do switchExp <- mkGetConstructorId checked var matchBlocks <- mkConsMatch (ignoreOuter pp) (\ pp -> mkDefaultMatch pp cases) var cases ppOuterBlock pp [BlockStmt $ Switch switchExp matchBlocks] isConstCase :: [SAlt] -> Bool isConstCase ((SConstCase _ _):_) = True isConstCase ((SDefaultCase _):cases) = isConstCase cases isConstCase _ = False isDefaultOnlyCase :: [SAlt] -> Bool isDefaultOnlyCase [SDefaultCase _] = True isDefaultOnlyCase [] = True isDefaultOnlyCase _ = False mkDefaultMatch :: BlockPostprocessor -> [SAlt] -> CodeGeneration [BlockStmt] mkDefaultMatch pp (x@(SDefaultCase branchExpression):_) = do pushScope stmt <- mkExp pp branchExpression popScope return stmt mkDefaultMatch pp (x:xs) = mkDefaultMatch pp xs mkDefaultMatch pp [] = ppExp (throwRuntimeException pp) (jString "Non-exhaustive pattern") mkMatchConstExp :: LVar -> Const -> CodeGeneration Exp mkMatchConstExp var c | isPrimitive cty = (\ var -> (primFnType ~> opName (LEq undefined)) [var, jc] ~==~ jInt 1) <$> (Just cty <>@! var) | isArray cty = (\ var -> (arraysType ~> "equals") [var, jc]) <$> (Just cty <>@! var) | isString cty = (\ var -> ((primFnType ~> opName (LStrEq)) [var, jc] ~==~ jInt 1)) <$> (Just cty <>@! var) | otherwise = (\ var -> (var ~> "equals") [jc]) <$> (Just cty <>@! var) where cty = constType c jc = mkConstant c mkConstMatch :: BlockPostprocessor -> (BlockPostprocessor -> CodeGeneration [BlockStmt]) -> LVar -> [SAlt] -> CodeGeneration Stmt mkConstMatch pp getDefaultStmts var ((SConstCase constant branchExpression):cases) = do matchExp <- mkMatchConstExp var constant pushScope branchBlock <- mkExp pp branchExpression popScope otherBranches <- mkConstMatch pp getDefaultStmts var cases return $ IfThenElse matchExp (StmtBlock $ Block branchBlock) otherBranches mkConstMatch pp getDefaultStmts var (c:cases) = mkConstMatch pp getDefaultStmts var cases mkConstMatch pp getDefaultStmts _ [] = do defaultBlock <- getDefaultStmts pp return $ StmtBlock (Block defaultBlock) mkGetConstructorId :: Bool -> LVar -> CodeGeneration Exp mkGetConstructorId True var = (\ var -> ((idrisObjectType <> var) ~> "getConstructorId") []) <$> (Nothing <>@! var) mkGetConstructorId False var = (\ var match -> Cond (InstanceOf var (toRefType idrisObjectType)) match (jInt (-1)) ) <$> (Nothing <>@! var) <*> mkGetConstructorId True var mkConsMatch :: BlockPostprocessor -> (BlockPostprocessor -> CodeGeneration [BlockStmt]) -> LVar -> [SAlt] -> CodeGeneration [SwitchBlock] mkConsMatch pp getDefaultStmts var ((SConCase parentStackPos consIndex _ params branchExpression):cases) = do pushScope caseBranch <- mkCaseBinding pp var parentStackPos params branchExpression popScope otherBranches <- mkConsMatch pp getDefaultStmts var cases return $ (SwitchBlock (SwitchCase $ jInt consIndex) caseBranch):otherBranches mkConsMatch pp getDefaultStmts var (c:cases) = mkConsMatch pp getDefaultStmts var cases mkConsMatch pp getDefaultStmts _ [] = do defaultBlock <- getDefaultStmts pp return $ [SwitchBlock Default defaultBlock] mkCaseBinding :: BlockPostprocessor -> LVar -> Int -> [Name] -> SExp -> CodeGeneration [BlockStmt] mkCaseBinding pp var stackStart params branchExpression = mkExp pp (toLetIn var stackStart params branchExpression) where toLetIn :: LVar -> Int -> [Name] -> SExp -> SExp toLetIn var stackStart members start = foldr (\ pos inExp -> SLet (Loc (stackStart + pos)) (SProj var pos) inExp) start [0.. (length members - 1)] ----------------------------------------------------------------------- -- Projection (retrieve the n-th field of an object) mkProjection :: LVar -> Int -> CodeGeneration Exp mkProjection var memberNr = (\ var -> ArrayAccess $ ((var ~> "getData") []) @! memberNr) <$> (Just idrisObjectType <>@! var) ----------------------------------------------------------------------- -- Constants mkConstantArray :: (V.Unbox a) => J.Type -> (a -> Const) -> V.Vector a -> Exp mkConstantArray cty elemToConst elems = ArrayCreateInit cty 0 (ArrayInit . map (InitExp . mkConstant . elemToConst) $ V.toList elems) mkConstant :: Const -> Exp mkConstant c@(I x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(BI x) = bigInteger (show x) mkConstant c@(Fl x) = constType c <> (Lit . Float $ x) mkConstant c@(Ch x) = constType c <> (Lit . Char $ x) mkConstant c@(Str x) = constType c <> (Lit . String $ x) mkConstant c@(B8 x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(B16 x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(B32 x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(B64 x) = (bigInteger (show c) ~> "longValue") [] mkConstant c@(AType x) = ClassLit (Just $ box (constType c)) mkConstant c@(StrType ) = ClassLit (Just $ stringType) mkConstant c@(VoidType ) = ClassLit (Just $ voidType) mkConstant c@(WorldType ) = ClassLit (Just $ worldType) mkConstant c@(TheWorld ) = worldType <> (Lit . Word $ toInteger 0) mkConstant c@(Forgot ) = ClassLit (Just $ objectType) ----------------------------------------------------------------------- -- Foreign function calls TODO : add support for calling C ( via Java 's JNI ) mkForeign :: BlockPostprocessor -> FDesc -> FDesc -> [(FDesc, LVar)] -> CodeGeneration [BlockStmt] mkForeign pp resTy@(FCon t) fname params | isCType t = error ("Java backend does not (currently) support calling C") | isJavaType t = mkForeignJava pp resTy fname params | otherwise = error (show t ++ " " ++ show fname ++ " " ++ show params) mkForeign pp resTy@(FApp t args) fname params | isCType t = error ("Java backend does not (currently) support calling C") | isJavaType t = mkForeignJava pp resTy fname params | otherwise = error ("mkForeign" ++ show t ++ " " ++ show fname ++ " " ++ show params) mkForeign pp t fname args = error ("mkForeign fall " ++ show t ++ " " ++ show fname ++ " " ++ show args) mkForeignJava :: BlockPostprocessor -> FDesc -> FDesc -> [(FDesc, LVar)] -> CodeGeneration [BlockStmt] mkForeignJava pp resTy (FApp (UN (T.unpack -> "JavaInvoke")) [FStr fname]) params = do method <- liftParsed (parser name fname) args <- foreignVarAccess params wrapReturn pp resTy (call method args) mkForeignJava pp resTy (FCon (UN (T.unpack -> "JavaNew"))) params = do clsTy <- liftParsed (parser classType (nameFromReturnType resTy)) args <- foreignVarAccess params wrapReturn pp resTy (InstanceCreation [] clsTy args Nothing) mkForeignJava pp resTy (FApp (UN (T.unpack -> "JavaInvokeDyn")) [FStr mname]) params = do method <- liftParsed (parser ident mname) (tgt:args) <- foreignVarAccess params wrapReturn pp resTy ((tgt ~> (show $ pretty method)) args) -- The next clause implements the allocation of a class with an -- overridden method, i.e. using anonymous classes. FIXME : ---currently only support a single overloaded -- method, but it should be straightforward to allow the user to pass -- an array of overridden methods. mkForeignJava pp resTy (FApp (UN (T.unpack -> "JavaNewAnonymous")) [FStr mname]) ((f,l):params) = do clsTy <- liftParsed (parser classType (nameFromReturnType resTy)) args <- foreignVarAccess params -- create method for inner class methodResTy <- liftParsed (parser resultType (nameFromReturnType f)) -- can't be an array location! Right var <- varPos l let (names, mparams) = unzip $ foldr mkVars [] $ zip [0..] $ paramTypes f -- the following is slightly complicated by handling the case with arguments and without , as one case (argName, names') = if null names then ("null", []) else (head names, tail names) calls = ((closure (call (mangle' (sMN 0 "APPLY")) [((idrisClosureType ~> "unwrapTailCall") [foldl mkCall (mkCall (ExpName $ J.Name [var]) argName) (tail names)]), Lit Null]) ) ~> "run") [] (methodResTy', returnExp) = mkMethodType methodResTy callEx <- wrapReturn returnExp methodResTy' calls let mbody = simpleMethod [Public] methodResTy mname mparams (Block callEx) wrapReturn pp resTy (InstanceCreation [] clsTy args (Just $ ClassBody [mbody])) where mkMethodType Nothing = (FCon $ sUN "Java_Unit", ignoreResult) mkMethodType _ = (FCon $ sUN "Any", addReturn) mkVars (i,t) params = let n = mname ++ show i in (n, FormalParam [Final] t False (VarId $ Ident n)) : params mkCall e n = call (mangle' (sMN 0 "APPLY")) [ e, jConst n ] mkForeignJava pp resTy fdesc params = error ("mkFJava " ++ show resTy ++ " " ++ show fdesc ++ " " ++ show params) -- Some helpers foreignVarAccess = mapM (\(fty, var) -> (foreignType fty <>@! var)) wrapReturn pp (FCon t) exp | sUN "Java_Unit" == t = ((ppInnerBlock pp') [BlockStmt $ ExpStmt exp] (Lit Null)) >>= ppOuterBlock pp' | otherwise = ((ppInnerBlock pp') [] exp) >>= ppOuterBlock pp' where pp' = rethrowAsRuntimeException pp wrapReturn pp (FApp t args) exp = ((ppInnerBlock pp') [] exp) >>= ppOuterBlock pp' where pp' = rethrowAsRuntimeException pp ----------------------------------------------------------------------- -- Primitive functions mkPrimitiveFunction :: PrimFn -> [LVar] -> CodeGeneration Exp mkPrimitiveFunction op args = (\ args -> (primFnType ~> opName op) (endiannessArguments op ++ args)) <$> sequence (zipWith (\ a t -> (Just t) <>@! a) args (sourceTypes op)) mkThread :: LVar -> CodeGeneration Exp mkThread arg = (\ closure -> (closure ~> "fork") []) <$> mkMethodCallClosure (sMN 0 "EVAL") [arg]
null
https://raw.githubusercontent.com/idris-hackers/idris-java/c1ed11c4c3014ec3e8a4bfdd294826f1b6937d5c/src/IRTS/CodegenJava.hs
haskell
--------------------------------------------------------------------- Main function initialization of globals decls output file name headers --------------------------------------------------------------------- initialization of globals definitions headers Source dir output target flatIndent . prettyPrint) writeFile (javaFileName "/Users/br-gaster/dev/" out) code tgt dir output target writeFile (pomFileName "/Users/br-gaster/dev/") execPom --------------------------------------------------------------------- Jar and Pom infrastructure --------------------------------------------------------------------- Code generation environment --------------------------------------------------------------------- Maintaining control structures over code blocks --------------------------------------------------------------------- File structure --------------------------------------------------------------------- Main class --------------------------------------------------------------------- --------------------------------------------------------------------- Expressions | Compile a simple expression and use the given continuation to postprocess the resulting value. Variables Applications Bindings can only update locals Objects Case expressions Projections Constants Foreign function calls Primitive functions Empty expressions Errors --------------------------------------------------------------------- Variable access --------------------------------------------------------------------- Application (wrap method calls in tail call closures) --------------------------------------------------------------------- Updates (change context array) and Let bindings (Update, execute) --------------------------------------------------------------------- Object creation --------------------------------------------------------------------- Case expressions --------------------------------------------------------------------- Projection (retrieve the n-th field of an object) --------------------------------------------------------------------- Constants --------------------------------------------------------------------- Foreign function calls The next clause implements the allocation of a class with an overridden method, i.e. using anonymous classes. -currently only support a single overloaded method, but it should be straightforward to allow the user to pass an array of overridden methods. create method for inner class can't be an array location! the following is slightly complicated by handling the case with arguments Some helpers --------------------------------------------------------------------- Primitive functions
# LANGUAGE PatternGuards # # LANGUAGE ViewPatterns # module IRTS.CodegenJava (codegenJava) where import Idris.Core.TT hiding (mkApp) import IRTS.CodegenCommon import IRTS.Java.ASTBuilding import IRTS.Java.JTypes import IRTS.Java.Mangling import IRTS.Java.Pom (pomString) import IRTS.Lang import IRTS.Simplified import IRTS.System import Util.System import Control.Applicative hiding (Const) import Control.Arrow import Control.Monad import Control.Monad.Except import qualified Control.Monad.Trans as T import Control.Monad.Trans.State import Data.List (foldl', isSuffixOf) import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Data.Vector.Unboxed as V import Data.Maybe import Language.Java.Parser import Language.Java.Pretty import Language.Java.Syntax hiding (Name) import qualified Language.Java.Syntax as J import System.Directory import System.Exit import System.FilePath import System.IO import System.Process codegenJava :: CodeGenerator codegenJava cg = codegenJava' [] (simpleDecls cg) (outputFile cg) (includes cg) (compileLibs cg) (outputType cg) libs OutputType -> IO () codegenJava' globalInit defs out hdrs libs exec = do withTgtDir exec out (codegenJava' exec) where codegenJava' :: OutputType -> FilePath -> IO () codegenJava' Raw tgtDir = do srcDir <- prepareSrcDir exec tgtDir generateJavaFile globalInit defs hdrs srcDir out codegenJava' MavenProject tgtDir = do codegenJava' Raw tgtDir generatePom tgtDir out libs codegenJava' Object tgtDir = do codegenJava' MavenProject tgtDir invokeMvn tgtDir "compile" copyClassFiles tgtDir out cleanUpTmp tgtDir codegenJava' Executable tgtDir = do codegenJava' MavenProject tgtDir invokeMvn tgtDir "package"; copyJar tgtDir out makeJarExecutable out cleanUpTmp tgtDir Compiler IO withTgtDir :: OutputType -> FilePath -> (FilePath -> IO ()) -> IO () withTgtDir Raw out action = action (dropFileName out) withTgtDir MavenProject out action = createDirectoryIfMissing False out >> action out withTgtDir _ out action = withTempdir (takeBaseName out) action prepareSrcDir :: OutputType -> FilePath -> IO FilePath prepareSrcDir Raw tgtDir = return tgtDir prepareSrcDir _ tgtDir = do let srcDir = (tgtDir </> "src" </> "main" </> "java") createDirectoryIfMissing True srcDir return srcDir javaFileName :: FilePath -> FilePath -> FilePath javaFileName srcDir out = either error (\ (Ident clsName) -> srcDir </> clsName <.> "java") (mkClassName out) IO () generateJavaFile globalInit defs hdrs srcDir out = do let code = either error (evalStateT (mkCompilationUnit globalInit defs hdrs out) mkCodeGenEnv) writeFile (javaFileName srcDir out) code pomFileName :: FilePath -> FilePath pomFileName tgtDir = tgtDir </> "pom.xml" libs IO () generatePom tgtDir out libs = do writeFile (pomFileName tgtDir) execPom where (Ident clsName) = either error id (mkClassName out) execPom = pomString clsName (takeBaseName out) libs invokeMvn :: FilePath -> String -> IO () invokeMvn tgtDir command = do mvnCmd <- getMvn let args = ["-f", pomFileName tgtDir] (exit, mvout, err) <- readProcessWithExitCode mvnCmd (args ++ [command]) "" when (exit /= ExitSuccess) $ error ("FAILURE: " ++ mvnCmd ++ " " ++ command ++ "\n" ++ err ++ mvout) classFileDir :: FilePath -> FilePath classFileDir tgtDir = tgtDir </> "target" </> "classes" copyClassFiles :: FilePath -> FilePath -> IO () copyClassFiles tgtDir out = do classFiles <- map (\ clsFile -> classFileDir tgtDir </> clsFile) . filter ((".class" ==) . takeExtension) <$> getDirectoryContents (classFileDir tgtDir) mapM_ (\ clsFile -> copyFile clsFile (takeDirectory out </> takeFileName clsFile)) classFiles jarFileName :: FilePath -> FilePath -> FilePath jarFileName tgtDir out = tgtDir </> "target" </> (takeBaseName out) <.> "jar" copyJar :: FilePath -> FilePath -> IO () copyJar tgtDir out = copyFile (jarFileName tgtDir out) out makeJarExecutable :: FilePath -> IO () makeJarExecutable out = do handle <- openBinaryFile out ReadMode contents <- TIO.hGetContents handle hClose handle handle <- openBinaryFile out WriteMode TIO.hPutStr handle (T.append (T.pack jarHeader) contents) hFlush handle hClose handle perms <- getPermissions out setPermissions out (setOwnerExecutable True perms) removePom :: FilePath -> IO () removePom tgtDir = removeFile (pomFileName tgtDir) cleanUpTmp :: FilePath -> IO () cleanUpTmp tgtDir = do invokeMvn tgtDir "clean" removePom tgtDir jarHeader :: String jarHeader = "#!/usr/bin/env sh\n" ++ "MYSELF=`which \"$0\" 2>/dev/null`\n" ++ "[ $? -gt 0 -a -f \"$0\" ] && MYSELF=\"./$0\"\n" ++ "java=java\n" ++ "if test -n \"$JAVA_HOME\"; then\n" ++ " java=\"$JAVA_HOME/bin/java\"\n" ++ "fi\n" ++ "exec \"$java\" $java_args -jar $MYSELF \"$@\"\n" ++ "exit 1\n" data CodeGenerationEnv = CodeGenerationEnv { globalVariables :: [(Name, ArrayIndex)] , localVariables :: [[(Int, Ident)]] , localVarCounter :: Int } type CodeGeneration = StateT (CodeGenerationEnv) (Either String) mkCodeGenEnv :: CodeGenerationEnv mkCodeGenEnv = CodeGenerationEnv [] [] 0 varPos :: LVar -> CodeGeneration (Either ArrayIndex Ident) varPos (Loc i) = do vars <- (concat . localVariables) <$> get case lookup i vars of (Just varName) -> return (Right varName) Nothing -> throwError $ "Invalid local variable id: " ++ show i varPos (Glob name) = do vars <- globalVariables <$> get case lookup name vars of (Just varIdx) -> return (Left varIdx) Nothing -> throwError $ "Invalid global variable id: " ++ show name pushScope :: CodeGeneration () pushScope = modify (\ env -> env { localVariables = []:(localVariables env) }) popScope :: CodeGeneration () popScope = do env <- get let lVars = tail $ localVariables env let vC = if null lVars then 0 else localVarCounter env put $ env { localVariables = tail (localVariables env) , localVarCounter = vC } setVariable :: LVar -> CodeGeneration (Either ArrayIndex Ident) setVariable (Loc i) = do env <- get let lVars = localVariables env let getter = localVar $ localVarCounter env let lVars' = ((i, getter) : head lVars) : tail lVars put $ env { localVariables = lVars' , localVarCounter = 1 + localVarCounter env} return (Right getter) setVariable (Glob n) = do env <- get let gVars = globalVariables env let getter = globalContext @! length gVars let gVars' = (n, getter):gVars put (env { globalVariables = gVars' }) return (Left getter) pushParams :: [Ident] -> CodeGeneration () pushParams paramNames = let varMap = zipWith (flip (,)) paramNames [0..] in modify (\ env -> env { localVariables = varMap:(localVariables env) , localVarCounter = (length varMap) + (localVarCounter env) }) flatIndent :: String -> String flatIndent (' ' : ' ' : xs) = flatIndent xs flatIndent (x:xs) = x:flatIndent xs flatIndent [] = [] data BlockPostprocessor = BlockPostprocessor { ppInnerBlock :: [BlockStmt] -> Exp -> CodeGeneration [BlockStmt] , ppOuterBlock :: [BlockStmt] -> CodeGeneration [BlockStmt] } ppExp :: BlockPostprocessor -> Exp -> CodeGeneration [BlockStmt] ppExp pp exp = ((ppInnerBlock pp) [] exp) >>= ppOuterBlock pp addReturn :: BlockPostprocessor addReturn = BlockPostprocessor { ppInnerBlock = (\ block exp -> return $ block ++ [jReturn exp]) , ppOuterBlock = return } ignoreResult :: BlockPostprocessor ignoreResult = BlockPostprocessor { ppInnerBlock = (\ block exp -> return block) , ppOuterBlock = return } ignoreOuter :: BlockPostprocessor -> BlockPostprocessor ignoreOuter pp = pp { ppOuterBlock = return } throwRuntimeException :: BlockPostprocessor -> BlockPostprocessor throwRuntimeException pp = pp { ppInnerBlock = (\ blk exp -> return $ blk ++ [ BlockStmt $ Throw ( InstanceCreation [] (toClassType runtimeExceptionType) [exp] Nothing ) ] ) } rethrowAsRuntimeException :: BlockPostprocessor -> BlockPostprocessor rethrowAsRuntimeException pp = pp { ppOuterBlock = (\ blk -> do ex <- ppInnerBlock (throwRuntimeException pp) [] (ExpName $ J.Name [Ident "ex"]) ppOuterBlock pp $ [ BlockStmt $ Try (Block blk) [Catch (FormalParam [] exceptionType False (VarId (Ident "ex"))) $ Block ex ] Nothing ] ) } mkCompilationUnit :: [(Name, SExp)] -> [(Name, SDecl)] -> [String] -> FilePath -> CodeGeneration CompilationUnit mkCompilationUnit globalInit defs hdrs out = do clsName <- mkClassName out CompilationUnit Nothing ( [ ImportDecl False idrisRts True , ImportDecl True idrisPrelude True , ImportDecl False bigInteger False , ImportDecl False runtimeException False , ImportDecl False byteBuffer False ] ++ otherHdrs ) <$> mkTypeDecl clsName globalInit defs where idrisRts = J.Name $ map Ident ["org", "idris", "rts"] idrisPrelude = J.Name $ map Ident ["org", "idris", "rts", "Prelude"] bigInteger = J.Name $ map Ident ["java", "math", "BigInteger"] runtimeException = J.Name $ map Ident ["java", "lang", "RuntimeException"] byteBuffer = J.Name $ map Ident ["java", "nio", "ByteBuffer"] otherHdrs = map ( (\ name -> ImportDecl False name False) . J.Name . map (Ident . T.unpack) . T.splitOn (T.pack ".") . T.pack) $ filter (not . isSuffixOf ".h") hdrs mkTypeDecl :: Ident -> [(Name, SExp)] -> [(Name, SDecl)] -> CodeGeneration [TypeDecl] mkTypeDecl name globalInit defs = (\ body -> [ClassTypeDecl $ ClassDecl [ Public , Annotation $ SingleElementAnnotation (jName "SuppressWarnings") (EVVal . InitExp $ jString "unchecked") ] name [] Nothing [] body]) <$> mkClassBody globalInit (map (second (prefixCallNamespaces name)) defs) mkClassBody :: [(Name, SExp)] -> [(Name, SDecl)] -> CodeGeneration ClassBody mkClassBody globalInit defs = (\ globals defs -> ClassBody . (globals++) . addMainMethod . mergeInnerClasses $ defs) <$> mkGlobalContext globalInit <*> mapM mkDecl defs mkGlobalContext :: [(Name, SExp)] -> CodeGeneration [Decl] mkGlobalContext [] = return [] mkGlobalContext initExps = do pushScope varInit <- mapM (\ (name, exp) -> do pos <- setVariable (Glob name) mkUpdate ignoreResult (Glob name) exp ) initExps popScope return [ MemberDecl $ FieldDecl [Private, Static, Final] (array objectType) [ VarDecl (VarId $ globalContextID). Just . InitExp $ ArrayCreate objectType [jInt $ length initExps] 0 ] , InitDecl True (Block $ concat varInit) ] addMainMethod :: [Decl] -> [Decl] addMainMethod decls | findMainMethod decls = mkMainMethod : decls | otherwise = decls where findMainMethod ((MemberDecl (MethodDecl _ _ _ name [] _ _)):_) | name == mangle' (sMN 0 "runMain") = True findMainMethod (_:decls) = findMainMethod decls findMainMethod [] = False mkMainMethod :: Decl mkMainMethod = simpleMethod [Public, Static] Nothing "main" [FormalParam [] (array stringType) False (VarId $ Ident "args")] $ Block [ BlockStmt . ExpStmt $ call "idris_initArgs" [ jConst "args" ] , BlockStmt . ExpStmt $ call (mangle' (sMN 0 "runMain")) [] ] Inner classes ( namespaces ) mergeInnerClasses :: [Decl] -> [Decl] mergeInnerClasses = foldl' mergeInner [] where mergeInner ((decl@(MemberDecl (MemberClassDecl (ClassDecl priv name targs ext imp (ClassBody body))))):decls) decl'@(MemberDecl (MemberClassDecl (ClassDecl _ name' _ ext' imp' (ClassBody body')))) | name == name' = (MemberDecl $ MemberClassDecl $ ClassDecl priv name targs (mplus ext ext') (imp ++ imp') (ClassBody $ mergeInnerClasses (body ++ body'))) : decls | otherwise = decl:(mergeInner decls decl') mergeInner (decl:decls) decl' = decl:(mergeInner decls decl') mergeInner [] decl' = [decl'] mkDecl :: (Name, SDecl) -> CodeGeneration Decl mkDecl ((NS n (ns:nss)), decl) = (\ name body -> MemberDecl $ MemberClassDecl $ ClassDecl [Public, Static] name [] Nothing [] body) <$> mangle (UN ns) <*> mkClassBody [] [(NS n nss, decl)] mkDecl (_, SFun name params stackSize body) = do (Ident methodName) <- mangle name methodParams <- mapM mkFormalParam params paramNames <- mapM mangle params pushParams paramNames methodBody <- mkExp addReturn body popScope return $ simpleMethod [Public, Static] (Just objectType) methodName methodParams (Block methodBody) mkFormalParam :: Name -> CodeGeneration FormalParam mkFormalParam name = (\ name -> FormalParam [Final] objectType False (VarId name)) <$> mangle name mkExp :: BlockPostprocessor -> SExp -> CodeGeneration [BlockStmt] mkExp pp (SV var) = (Nothing <>@! var) >>= ppExp pp mkExp pp (SApp pushTail name args) = mkApp pushTail name args >>= ppExp pp mkExp pp (SLet var newExp inExp) = mkLet pp var newExp inExp mkUpdate pp var newExp mkExp pp (SUpdate var newExp) = mkExp pp newExp mkExp pp (SCon _ conId _ args) = mkIdrisObject conId args >>= ppExp pp mkExp pp (SCase up var alts) = mkCase pp True var alts mkExp pp (SChkCase var alts) = mkCase pp False var alts mkExp pp (SProj var i) = mkProjection var i >>= ppExp pp mkExp pp (SConst c) = ppExp pp $ mkConstant c mkExp pp f@(SForeign t fname args) = mkForeign pp t fname args mkExp pp (SOp LFork [arg]) = (mkThread arg) >>= ppExp pp mkExp pp (SOp LPar [arg]) = (Nothing <>@! arg) >>= ppExp pp mkExp pp (SOp LNoOp args) = (Nothing <>@! (last args)) >>= ppExp pp mkExp pp (SOp op args) = (mkPrimitiveFunction op args) >>= ppExp pp mkExp pp (SNothing) = ppExp pp $ Lit Null mkExp pp (SError err) = ppExp (throwRuntimeException pp) (jString err) (<>@!) :: Maybe J.Type -> LVar -> CodeGeneration Exp (<>@!) Nothing var = either ArrayAccess (\ n -> ExpName $ J.Name [n]) <$> varPos var (<>@!) (Just castTo) var = (castTo <>) <$> (Nothing <>@! var) mkApp :: Bool -> Name -> [LVar] -> CodeGeneration Exp mkApp False name args = (\ methodName params -> (idrisClosureType ~> "unwrapTailCall") [call methodName params] ) <$> mangleFull name <*> mapM (Nothing <>@!) args mkApp True name args = mkMethodCallClosure name args mkMethodCallClosure :: Name -> [LVar] -> CodeGeneration Exp mkMethodCallClosure name args = (\ name args -> closure (call name args)) <$> mangleFull name <*> mapM (Nothing <>@!) args mkUpdate :: BlockPostprocessor -> LVar -> SExp -> CodeGeneration [BlockStmt] mkUpdate pp var exp = mkExp ( pp { ppInnerBlock = (\ blk rhs -> do pos <- setVariable var vExp <- Nothing <>@! var ppInnerBlock pp (blk ++ [pos @:= rhs]) vExp ) } ) exp mkLet :: BlockPostprocessor -> LVar -> SExp -> SExp -> CodeGeneration [BlockStmt] mkLet pp var@(Loc pos) newExp inExp = mkUpdate (pp { ppInnerBlock = (\ blk _ -> do inBlk <- mkExp pp inExp return (blk ++ inBlk) ) } ) var newExp mkLet _ (Glob _) _ _ = T.lift $ Left "Cannot let bind to global variable" mkIdrisObject :: Int -> [LVar] -> CodeGeneration Exp mkIdrisObject conId args = (\ args -> InstanceCreation [] (toClassType idrisObjectType) ((jInt conId):args) Nothing ) <$> mapM (Nothing <>@!) args mkCase :: BlockPostprocessor -> Bool -> LVar -> [SAlt] -> CodeGeneration [BlockStmt] mkCase pp checked var cases | isDefaultOnlyCase cases = mkDefaultMatch pp cases | isConstCase cases = do ifte <- mkConstMatch (ignoreOuter pp) (\ pp -> mkDefaultMatch pp cases) var cases ppOuterBlock pp [BlockStmt ifte] | otherwise = do switchExp <- mkGetConstructorId checked var matchBlocks <- mkConsMatch (ignoreOuter pp) (\ pp -> mkDefaultMatch pp cases) var cases ppOuterBlock pp [BlockStmt $ Switch switchExp matchBlocks] isConstCase :: [SAlt] -> Bool isConstCase ((SConstCase _ _):_) = True isConstCase ((SDefaultCase _):cases) = isConstCase cases isConstCase _ = False isDefaultOnlyCase :: [SAlt] -> Bool isDefaultOnlyCase [SDefaultCase _] = True isDefaultOnlyCase [] = True isDefaultOnlyCase _ = False mkDefaultMatch :: BlockPostprocessor -> [SAlt] -> CodeGeneration [BlockStmt] mkDefaultMatch pp (x@(SDefaultCase branchExpression):_) = do pushScope stmt <- mkExp pp branchExpression popScope return stmt mkDefaultMatch pp (x:xs) = mkDefaultMatch pp xs mkDefaultMatch pp [] = ppExp (throwRuntimeException pp) (jString "Non-exhaustive pattern") mkMatchConstExp :: LVar -> Const -> CodeGeneration Exp mkMatchConstExp var c | isPrimitive cty = (\ var -> (primFnType ~> opName (LEq undefined)) [var, jc] ~==~ jInt 1) <$> (Just cty <>@! var) | isArray cty = (\ var -> (arraysType ~> "equals") [var, jc]) <$> (Just cty <>@! var) | isString cty = (\ var -> ((primFnType ~> opName (LStrEq)) [var, jc] ~==~ jInt 1)) <$> (Just cty <>@! var) | otherwise = (\ var -> (var ~> "equals") [jc]) <$> (Just cty <>@! var) where cty = constType c jc = mkConstant c mkConstMatch :: BlockPostprocessor -> (BlockPostprocessor -> CodeGeneration [BlockStmt]) -> LVar -> [SAlt] -> CodeGeneration Stmt mkConstMatch pp getDefaultStmts var ((SConstCase constant branchExpression):cases) = do matchExp <- mkMatchConstExp var constant pushScope branchBlock <- mkExp pp branchExpression popScope otherBranches <- mkConstMatch pp getDefaultStmts var cases return $ IfThenElse matchExp (StmtBlock $ Block branchBlock) otherBranches mkConstMatch pp getDefaultStmts var (c:cases) = mkConstMatch pp getDefaultStmts var cases mkConstMatch pp getDefaultStmts _ [] = do defaultBlock <- getDefaultStmts pp return $ StmtBlock (Block defaultBlock) mkGetConstructorId :: Bool -> LVar -> CodeGeneration Exp mkGetConstructorId True var = (\ var -> ((idrisObjectType <> var) ~> "getConstructorId") []) <$> (Nothing <>@! var) mkGetConstructorId False var = (\ var match -> Cond (InstanceOf var (toRefType idrisObjectType)) match (jInt (-1)) ) <$> (Nothing <>@! var) <*> mkGetConstructorId True var mkConsMatch :: BlockPostprocessor -> (BlockPostprocessor -> CodeGeneration [BlockStmt]) -> LVar -> [SAlt] -> CodeGeneration [SwitchBlock] mkConsMatch pp getDefaultStmts var ((SConCase parentStackPos consIndex _ params branchExpression):cases) = do pushScope caseBranch <- mkCaseBinding pp var parentStackPos params branchExpression popScope otherBranches <- mkConsMatch pp getDefaultStmts var cases return $ (SwitchBlock (SwitchCase $ jInt consIndex) caseBranch):otherBranches mkConsMatch pp getDefaultStmts var (c:cases) = mkConsMatch pp getDefaultStmts var cases mkConsMatch pp getDefaultStmts _ [] = do defaultBlock <- getDefaultStmts pp return $ [SwitchBlock Default defaultBlock] mkCaseBinding :: BlockPostprocessor -> LVar -> Int -> [Name] -> SExp -> CodeGeneration [BlockStmt] mkCaseBinding pp var stackStart params branchExpression = mkExp pp (toLetIn var stackStart params branchExpression) where toLetIn :: LVar -> Int -> [Name] -> SExp -> SExp toLetIn var stackStart members start = foldr (\ pos inExp -> SLet (Loc (stackStart + pos)) (SProj var pos) inExp) start [0.. (length members - 1)] mkProjection :: LVar -> Int -> CodeGeneration Exp mkProjection var memberNr = (\ var -> ArrayAccess $ ((var ~> "getData") []) @! memberNr) <$> (Just idrisObjectType <>@! var) mkConstantArray :: (V.Unbox a) => J.Type -> (a -> Const) -> V.Vector a -> Exp mkConstantArray cty elemToConst elems = ArrayCreateInit cty 0 (ArrayInit . map (InitExp . mkConstant . elemToConst) $ V.toList elems) mkConstant :: Const -> Exp mkConstant c@(I x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(BI x) = bigInteger (show x) mkConstant c@(Fl x) = constType c <> (Lit . Float $ x) mkConstant c@(Ch x) = constType c <> (Lit . Char $ x) mkConstant c@(Str x) = constType c <> (Lit . String $ x) mkConstant c@(B8 x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(B16 x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(B32 x) = constType c <> (Lit . Word $ toInteger x) mkConstant c@(B64 x) = (bigInteger (show c) ~> "longValue") [] mkConstant c@(AType x) = ClassLit (Just $ box (constType c)) mkConstant c@(StrType ) = ClassLit (Just $ stringType) mkConstant c@(VoidType ) = ClassLit (Just $ voidType) mkConstant c@(WorldType ) = ClassLit (Just $ worldType) mkConstant c@(TheWorld ) = worldType <> (Lit . Word $ toInteger 0) mkConstant c@(Forgot ) = ClassLit (Just $ objectType) TODO : add support for calling C ( via Java 's JNI ) mkForeign :: BlockPostprocessor -> FDesc -> FDesc -> [(FDesc, LVar)] -> CodeGeneration [BlockStmt] mkForeign pp resTy@(FCon t) fname params | isCType t = error ("Java backend does not (currently) support calling C") | isJavaType t = mkForeignJava pp resTy fname params | otherwise = error (show t ++ " " ++ show fname ++ " " ++ show params) mkForeign pp resTy@(FApp t args) fname params | isCType t = error ("Java backend does not (currently) support calling C") | isJavaType t = mkForeignJava pp resTy fname params | otherwise = error ("mkForeign" ++ show t ++ " " ++ show fname ++ " " ++ show params) mkForeign pp t fname args = error ("mkForeign fall " ++ show t ++ " " ++ show fname ++ " " ++ show args) mkForeignJava :: BlockPostprocessor -> FDesc -> FDesc -> [(FDesc, LVar)] -> CodeGeneration [BlockStmt] mkForeignJava pp resTy (FApp (UN (T.unpack -> "JavaInvoke")) [FStr fname]) params = do method <- liftParsed (parser name fname) args <- foreignVarAccess params wrapReturn pp resTy (call method args) mkForeignJava pp resTy (FCon (UN (T.unpack -> "JavaNew"))) params = do clsTy <- liftParsed (parser classType (nameFromReturnType resTy)) args <- foreignVarAccess params wrapReturn pp resTy (InstanceCreation [] clsTy args Nothing) mkForeignJava pp resTy (FApp (UN (T.unpack -> "JavaInvokeDyn")) [FStr mname]) params = do method <- liftParsed (parser ident mname) (tgt:args) <- foreignVarAccess params wrapReturn pp resTy ((tgt ~> (show $ pretty method)) args) mkForeignJava pp resTy (FApp (UN (T.unpack -> "JavaNewAnonymous")) [FStr mname]) ((f,l):params) = do clsTy <- liftParsed (parser classType (nameFromReturnType resTy)) args <- foreignVarAccess params methodResTy <- liftParsed (parser resultType (nameFromReturnType f)) Right var <- varPos l let (names, mparams) = unzip $ foldr mkVars [] $ zip [0..] $ paramTypes f and without , as one case (argName, names') = if null names then ("null", []) else (head names, tail names) calls = ((closure (call (mangle' (sMN 0 "APPLY")) [((idrisClosureType ~> "unwrapTailCall") [foldl mkCall (mkCall (ExpName $ J.Name [var]) argName) (tail names)]), Lit Null]) ) ~> "run") [] (methodResTy', returnExp) = mkMethodType methodResTy callEx <- wrapReturn returnExp methodResTy' calls let mbody = simpleMethod [Public] methodResTy mname mparams (Block callEx) wrapReturn pp resTy (InstanceCreation [] clsTy args (Just $ ClassBody [mbody])) where mkMethodType Nothing = (FCon $ sUN "Java_Unit", ignoreResult) mkMethodType _ = (FCon $ sUN "Any", addReturn) mkVars (i,t) params = let n = mname ++ show i in (n, FormalParam [Final] t False (VarId $ Ident n)) : params mkCall e n = call (mangle' (sMN 0 "APPLY")) [ e, jConst n ] mkForeignJava pp resTy fdesc params = error ("mkFJava " ++ show resTy ++ " " ++ show fdesc ++ " " ++ show params) foreignVarAccess = mapM (\(fty, var) -> (foreignType fty <>@! var)) wrapReturn pp (FCon t) exp | sUN "Java_Unit" == t = ((ppInnerBlock pp') [BlockStmt $ ExpStmt exp] (Lit Null)) >>= ppOuterBlock pp' | otherwise = ((ppInnerBlock pp') [] exp) >>= ppOuterBlock pp' where pp' = rethrowAsRuntimeException pp wrapReturn pp (FApp t args) exp = ((ppInnerBlock pp') [] exp) >>= ppOuterBlock pp' where pp' = rethrowAsRuntimeException pp mkPrimitiveFunction :: PrimFn -> [LVar] -> CodeGeneration Exp mkPrimitiveFunction op args = (\ args -> (primFnType ~> opName op) (endiannessArguments op ++ args)) <$> sequence (zipWith (\ a t -> (Just t) <>@! a) args (sourceTypes op)) mkThread :: LVar -> CodeGeneration Exp mkThread arg = (\ closure -> (closure ~> "fork") []) <$> mkMethodCallClosure (sMN 0 "EVAL") [arg]
b17f6a802296fa65f004d8cb92c232134f4929d4bae982bae7650c7d49abc533
avsm/mirage-duniverse
ast_convenience_405.ml
open Ast_405 (* This file is part of the ppx_tools package. It is released *) under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi open Parsetree open Asttypes open Location open Ast_helper module Label = struct type t = Asttypes.arg_label type desc = Asttypes.arg_label = Nolabel | Labelled of string | Optional of string let explode x = x let nolabel = Nolabel let labelled x = Labelled x let optional x = Optional x end module Constant = struct type t = Parsetree.constant = Pconst_integer of string * char option | Pconst_char of char | Pconst_string of string * string option | Pconst_float of string * char option let of_constant x = x let to_constant x = x end let may_tuple ?loc tup = function | [] -> None | [x] -> Some x | l -> Some (tup ?loc ?attrs:None l) let lid ?(loc = !default_loc) s = mkloc (Longident.parse s) loc let constr ?loc ?attrs s args = Exp.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Exp.tuple args) let nil ?loc ?attrs () = constr ?loc ?attrs "[]" [] let unit ?loc ?attrs () = constr ?loc ?attrs "()" [] let tuple ?loc ?attrs = function | [] -> unit ?loc ?attrs () | [x] -> x | xs -> Exp.tuple ?loc ?attrs xs let cons ?loc ?attrs hd tl = constr ?loc ?attrs "::" [hd; tl] let list ?loc ?attrs l = List.fold_right (cons ?loc ?attrs) l (nil ?loc ?attrs ()) let str ?loc ?attrs s = Exp.constant ?loc ?attrs (Pconst_string (s, None)) let int ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (string_of_int x, None)) let int32 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int32.to_string x, Some 'l')) let int64 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int64.to_string x, Some 'L')) let char ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_char x) let float ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_float (string_of_float x, None)) let record ?loc ?attrs ?over l = Exp.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.pexp_loc s, e)) l) over let func ?loc ?attrs l = Exp.function_ ?loc ?attrs (List.map (fun (p, e) -> Exp.case p e) l) let lam ?loc ?attrs ?(label = Label.nolabel) ?default pat exp = Exp.fun_ ?loc ?attrs label default pat exp let app ?loc ?attrs f l = if l = [] then f else Exp.apply ?loc ?attrs f (List.map (fun a -> Label.nolabel, a) l) let evar ?loc ?attrs s = Exp.ident ?loc ?attrs (lid ?loc s) let let_in ?loc ?attrs ?(recursive = false) b body = Exp.let_ ?loc ?attrs (if recursive then Recursive else Nonrecursive) b body let sequence ?loc ?attrs = function | [] -> unit ?loc ?attrs () | hd :: tl -> List.fold_left (fun e1 e2 -> Exp.sequence ?loc ?attrs e1 e2) hd tl let pvar ?(loc = !default_loc) ?attrs s = Pat.var ~loc ?attrs (mkloc s loc) let pconstr ?loc ?attrs s args = Pat.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Pat.tuple args) let precord ?loc ?attrs ?(closed = Open) l = Pat.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.ppat_loc s, e)) l) closed let pnil ?loc ?attrs () = pconstr ?loc ?attrs "[]" [] let pcons ?loc ?attrs hd tl = pconstr ?loc ?attrs "::" [hd; tl] let punit ?loc ?attrs () = pconstr ?loc ?attrs "()" [] let ptuple ?loc ?attrs = function | [] -> punit ?loc ?attrs () | [x] -> x | xs -> Pat.tuple ?loc ?attrs xs let plist ?loc ?attrs l = List.fold_right (pcons ?loc ?attrs) l (pnil ?loc ?attrs ()) let pstr ?loc ?attrs s = Pat.constant ?loc ?attrs (Pconst_string (s, None)) let pint ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_integer (string_of_int x, None)) let pchar ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_char x) let pfloat ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_float (string_of_float x, None)) let tconstr ?loc ?attrs c l = Typ.constr ?loc ?attrs (lid ?loc c) l let get_str = function | {pexp_desc=Pexp_constant (Pconst_string (s, _)); _} -> Some s | _ -> None let get_str_with_quotation_delimiter = function | {pexp_desc=Pexp_constant (Pconst_string (s, d)); _} -> Some (s, d) | _ -> None let get_lid = function | {pexp_desc=Pexp_ident{txt=id;_};_} -> Some (String.concat "." (Longident.flatten id)) | _ -> None let find_attr s attrs = try Some (snd (List.find (fun (x, _) -> x.txt = s) attrs)) with Not_found -> None let expr_of_payload = function | PStr [{pstr_desc=Pstr_eval(e, _); _}] -> Some e | _ -> None let find_attr_expr s attrs = match find_attr s attrs with | Some e -> expr_of_payload e | None -> None let has_attr s attrs = find_attr s attrs <> None
null
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/ppx_tools_versioned/ast_convenience_405.ml
ocaml
This file is part of the ppx_tools package. It is released
open Ast_405 under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi open Parsetree open Asttypes open Location open Ast_helper module Label = struct type t = Asttypes.arg_label type desc = Asttypes.arg_label = Nolabel | Labelled of string | Optional of string let explode x = x let nolabel = Nolabel let labelled x = Labelled x let optional x = Optional x end module Constant = struct type t = Parsetree.constant = Pconst_integer of string * char option | Pconst_char of char | Pconst_string of string * string option | Pconst_float of string * char option let of_constant x = x let to_constant x = x end let may_tuple ?loc tup = function | [] -> None | [x] -> Some x | l -> Some (tup ?loc ?attrs:None l) let lid ?(loc = !default_loc) s = mkloc (Longident.parse s) loc let constr ?loc ?attrs s args = Exp.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Exp.tuple args) let nil ?loc ?attrs () = constr ?loc ?attrs "[]" [] let unit ?loc ?attrs () = constr ?loc ?attrs "()" [] let tuple ?loc ?attrs = function | [] -> unit ?loc ?attrs () | [x] -> x | xs -> Exp.tuple ?loc ?attrs xs let cons ?loc ?attrs hd tl = constr ?loc ?attrs "::" [hd; tl] let list ?loc ?attrs l = List.fold_right (cons ?loc ?attrs) l (nil ?loc ?attrs ()) let str ?loc ?attrs s = Exp.constant ?loc ?attrs (Pconst_string (s, None)) let int ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (string_of_int x, None)) let int32 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int32.to_string x, Some 'l')) let int64 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int64.to_string x, Some 'L')) let char ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_char x) let float ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_float (string_of_float x, None)) let record ?loc ?attrs ?over l = Exp.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.pexp_loc s, e)) l) over let func ?loc ?attrs l = Exp.function_ ?loc ?attrs (List.map (fun (p, e) -> Exp.case p e) l) let lam ?loc ?attrs ?(label = Label.nolabel) ?default pat exp = Exp.fun_ ?loc ?attrs label default pat exp let app ?loc ?attrs f l = if l = [] then f else Exp.apply ?loc ?attrs f (List.map (fun a -> Label.nolabel, a) l) let evar ?loc ?attrs s = Exp.ident ?loc ?attrs (lid ?loc s) let let_in ?loc ?attrs ?(recursive = false) b body = Exp.let_ ?loc ?attrs (if recursive then Recursive else Nonrecursive) b body let sequence ?loc ?attrs = function | [] -> unit ?loc ?attrs () | hd :: tl -> List.fold_left (fun e1 e2 -> Exp.sequence ?loc ?attrs e1 e2) hd tl let pvar ?(loc = !default_loc) ?attrs s = Pat.var ~loc ?attrs (mkloc s loc) let pconstr ?loc ?attrs s args = Pat.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Pat.tuple args) let precord ?loc ?attrs ?(closed = Open) l = Pat.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.ppat_loc s, e)) l) closed let pnil ?loc ?attrs () = pconstr ?loc ?attrs "[]" [] let pcons ?loc ?attrs hd tl = pconstr ?loc ?attrs "::" [hd; tl] let punit ?loc ?attrs () = pconstr ?loc ?attrs "()" [] let ptuple ?loc ?attrs = function | [] -> punit ?loc ?attrs () | [x] -> x | xs -> Pat.tuple ?loc ?attrs xs let plist ?loc ?attrs l = List.fold_right (pcons ?loc ?attrs) l (pnil ?loc ?attrs ()) let pstr ?loc ?attrs s = Pat.constant ?loc ?attrs (Pconst_string (s, None)) let pint ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_integer (string_of_int x, None)) let pchar ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_char x) let pfloat ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_float (string_of_float x, None)) let tconstr ?loc ?attrs c l = Typ.constr ?loc ?attrs (lid ?loc c) l let get_str = function | {pexp_desc=Pexp_constant (Pconst_string (s, _)); _} -> Some s | _ -> None let get_str_with_quotation_delimiter = function | {pexp_desc=Pexp_constant (Pconst_string (s, d)); _} -> Some (s, d) | _ -> None let get_lid = function | {pexp_desc=Pexp_ident{txt=id;_};_} -> Some (String.concat "." (Longident.flatten id)) | _ -> None let find_attr s attrs = try Some (snd (List.find (fun (x, _) -> x.txt = s) attrs)) with Not_found -> None let expr_of_payload = function | PStr [{pstr_desc=Pstr_eval(e, _); _}] -> Some e | _ -> None let find_attr_expr s attrs = match find_attr s attrs with | Some e -> expr_of_payload e | None -> None let has_attr s attrs = find_attr s attrs <> None
c0a7c9b8747c472bb407a8c2ba3a5f54e106acb0117d4a4e9c2fa7b87071b1bc
dalaing/little-languages
Pretty.hs
module Term.Pretty where import Control.Applicative ((<|>)) import Control.Lens (preview) import Data.Foldable (asum) import Data.Maybe (fromMaybe) import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Text.Parser.Expression (Assoc(..)) import Term -- | > > > prettyString text ( TmVar " x " ) -- "x" printVar :: (n -> Doc) -> Term n n -> Maybe Doc printVar pr = fmap pr . preview _TmVar data PrintOperator t = Infix (t -> Maybe (t, t)) (Doc -> Doc -> Doc) Assoc poApply :: PrintOperator t -> (t -> Maybe Doc) -> t -> Maybe Doc poApply (Infix m p _) base t = do (x, y) <- m t x' <- base x y' <- base y return $ p x' y' -- | > > > prettyString text ( TmApp ( TmVar " x " ) ( TmVar " y " ) ) -- "(x) @ (y)" printApp :: Doc -> Doc -> Doc printApp x y = x <+> text "@" <+> y -- | > > > prettyString text ( lam " x " ( TmApp ( TmVar " x " ) ( TmVar " y " ) ) ) -- "\ x -> (x) (y)" printLam :: Eq n => (n -> Doc) -> (Term n n -> Maybe Doc) -> Term n n -> Maybe Doc printLam pv pt = fmap printLam' . preview _lam where printLam' (v,e) = text "\\" <+> pv v <+> text "->" <+> (fromMaybe empty . pt $ e) -- TODO come back here and deal with associativity and precedence properly -- probably worth dealing with prefix and postfix ops at the same time, -- for parity with the expression parser buildExpressionPrinter :: [[PrintOperator (Term n n)]] -> (Term n n -> Maybe Doc) -> Term n n -> Maybe Doc buildExpressionPrinter os base = let baseparens = fmap parens . base ep t = asum . map (\o -> poApply o baseparens t) . concat $ os in ep -- TODO tag App as high or low precedence so we know how to print it -- maybe just start with the high precedence version? printExpr :: Eq n => (n -> Doc) -> Term n n -> Maybe Doc printExpr pr = buildExpressionPrinter table (printTerm pr) where table = [[Infix (preview _TmApp) printApp AssocRight]] TODO return to optionally depth - limited printing later on printTerm :: Eq n => (n -> Doc) -> Term n n -> Maybe Doc printTerm pr t = fmap parens (printExpr pr t) <|> printVar pr t <|> printLam pr (printTerm pr) t docString :: Doc -> String docString d = displayS (renderPretty 0.4 40 (plain d)) "" prettyString :: Term String String -> String prettyString = docString . fromMaybe empty . printTerm text prettyTerm :: Term String String -> Doc prettyTerm = fromMaybe empty . printTerm text
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/unityped/lc/src/Term/Pretty.hs
haskell
| "x" | "(x) @ (y)" | "\ x -> (x) (y)" TODO come back here and deal with associativity and precedence properly probably worth dealing with prefix and postfix ops at the same time, for parity with the expression parser TODO tag App as high or low precedence so we know how to print it maybe just start with the high precedence version?
module Term.Pretty where import Control.Applicative ((<|>)) import Control.Lens (preview) import Data.Foldable (asum) import Data.Maybe (fromMaybe) import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Text.Parser.Expression (Assoc(..)) import Term > > > prettyString text ( TmVar " x " ) printVar :: (n -> Doc) -> Term n n -> Maybe Doc printVar pr = fmap pr . preview _TmVar data PrintOperator t = Infix (t -> Maybe (t, t)) (Doc -> Doc -> Doc) Assoc poApply :: PrintOperator t -> (t -> Maybe Doc) -> t -> Maybe Doc poApply (Infix m p _) base t = do (x, y) <- m t x' <- base x y' <- base y return $ p x' y' > > > prettyString text ( TmApp ( TmVar " x " ) ( TmVar " y " ) ) printApp :: Doc -> Doc -> Doc printApp x y = x <+> text "@" <+> y > > > prettyString text ( lam " x " ( TmApp ( TmVar " x " ) ( TmVar " y " ) ) ) printLam :: Eq n => (n -> Doc) -> (Term n n -> Maybe Doc) -> Term n n -> Maybe Doc printLam pv pt = fmap printLam' . preview _lam where printLam' (v,e) = text "\\" <+> pv v <+> text "->" <+> (fromMaybe empty . pt $ e) buildExpressionPrinter :: [[PrintOperator (Term n n)]] -> (Term n n -> Maybe Doc) -> Term n n -> Maybe Doc buildExpressionPrinter os base = let baseparens = fmap parens . base ep t = asum . map (\o -> poApply o baseparens t) . concat $ os in ep printExpr :: Eq n => (n -> Doc) -> Term n n -> Maybe Doc printExpr pr = buildExpressionPrinter table (printTerm pr) where table = [[Infix (preview _TmApp) printApp AssocRight]] TODO return to optionally depth - limited printing later on printTerm :: Eq n => (n -> Doc) -> Term n n -> Maybe Doc printTerm pr t = fmap parens (printExpr pr t) <|> printVar pr t <|> printLam pr (printTerm pr) t docString :: Doc -> String docString d = displayS (renderPretty 0.4 40 (plain d)) "" prettyString :: Term String String -> String prettyString = docString . fromMaybe empty . printTerm text prettyTerm :: Term String String -> Doc prettyTerm = fromMaybe empty . printTerm text
c750a53bf025a1e2dd6eddc1f1796ca019e0f9e175df9d1735add037809f61a6
taylorwood/advent-of-code
23.clj
(ns advent-of-code.2017.23 (:refer-clojure :exclude [set]) (:require [advent-of-code.2017.18 :refer [parse-instruction inc-ip reg-val]] [clojure.java.io :as io] [clojure.string :as cs])) (def raw-input (slurp (io/resource "data_2017/23.txt"))) (def instructions (->> (cs/split-lines raw-input) (mapv parse-instruction))) (defn set [registers x y] (inc-ip (assoc registers x (reg-val registers y)))) (defn mul [registers x y] (inc-ip (-> registers (update x #(* (or % 0) (reg-val registers y))) (update :muls (fnil inc 0))))) (defn sub [registers x y] (inc-ip (update registers x #(- (or % 0) (reg-val registers y))))) (defn jnz [registers x y] (if-not (zero? (reg-val registers x)) (update registers :ip #(+ % (reg-val registers y))) (inc-ip registers))) solve part one (loop [registers {:ip 0}] (if-let [[f & args :as instr] (nth instructions (:ip registers) nil)] (let [registers (apply (resolve f) registers args)] (recur registers)) registers)) solving part two ;; I did some printf tracing of the program and noticed the loops ;; then went about looking at the instruction branches, then assumed ;; an easy approach would be to reassemble the instructions... b = 93 ; ; c = b b * = 100 ; b + = 100000 ; ; c = b; c + = 17000 ; ; ; while(true): ; ; f = false; for ( d = 2 ; d ! = b ; d++ ) { for ( e = 2 ; e ! = b ; e++ ) { ; if (d * e == b) { // checking for primes ; f = true; ; break; // NOTE this is an optimization/missing instruction ; } ; } ; } ; ; if (f == true) { h++ ; ; ; if (b == c) ; return h; b + = 17 ; (def b (+ 100000 (* 93 100))) (def c (+ b 17000)) (comment "Clojurized version but still slow due to... inefficient prime finding routine!" (loop [b b h 0] (let [h (if (->> (for [x (range 2 (inc b)) y (range 2 (inc b))] (* x y)) (some #(= b %))) (inc h) h)] (if (= b c) h (recur (+ b 17) h))))) (defn is-prime? [x] (and (> x 2) (loop [i 2 max-comp (int (Math/sqrt x))] (or (> i max-comp) (if (= 0 (mod x i)) false (recur (inc i) max-comp)))))) ;; the most ~beautiful~ solution (->> (range b (inc c) 17) (filter (comp not is-prime?)) (count))
null
https://raw.githubusercontent.com/taylorwood/advent-of-code/c6b08f4b618875a45c8083a04ae2c669626c43bf/src/advent_of_code/2017/23.clj
clojure
I did some printf tracing of the program and noticed the loops then went about looking at the instruction branches, then assumed an easy approach would be to reassemble the instructions... c = b c = b; while(true): f = false; d ! = b ; d++ ) { e ! = b ; e++ ) { if (d * e == b) { // checking for primes f = true; break; // NOTE this is an optimization/missing instruction } } } if (f == true) { if (b == c) return h; the most ~beautiful~ solution
(ns advent-of-code.2017.23 (:refer-clojure :exclude [set]) (:require [advent-of-code.2017.18 :refer [parse-instruction inc-ip reg-val]] [clojure.java.io :as io] [clojure.string :as cs])) (def raw-input (slurp (io/resource "data_2017/23.txt"))) (def instructions (->> (cs/split-lines raw-input) (mapv parse-instruction))) (defn set [registers x y] (inc-ip (assoc registers x (reg-val registers y)))) (defn mul [registers x y] (inc-ip (-> registers (update x #(* (or % 0) (reg-val registers y))) (update :muls (fnil inc 0))))) (defn sub [registers x y] (inc-ip (update registers x #(- (or % 0) (reg-val registers y))))) (defn jnz [registers x y] (if-not (zero? (reg-val registers x)) (update registers :ip #(+ % (reg-val registers y))) (inc-ip registers))) solve part one (loop [registers {:ip 0}] (if-let [[f & args :as instr] (nth instructions (:ip registers) nil)] (let [registers (apply (resolve f) registers args)] (recur registers)) registers)) solving part two (def b (+ 100000 (* 93 100))) (def c (+ b 17000)) (comment "Clojurized version but still slow due to... inefficient prime finding routine!" (loop [b b h 0] (let [h (if (->> (for [x (range 2 (inc b)) y (range 2 (inc b))] (* x y)) (some #(= b %))) (inc h) h)] (if (= b c) h (recur (+ b 17) h))))) (defn is-prime? [x] (and (> x 2) (loop [i 2 max-comp (int (Math/sqrt x))] (or (> i max-comp) (if (= 0 (mod x i)) false (recur (inc i) max-comp)))))) (->> (range b (inc c) 17) (filter (comp not is-prime?)) (count))
d3a3a5c061d3c390aea6f6899b7fcf952c1f77b404c321c00bfdb7f00cf857ae
kmonad/kmonad
DeviceSource.hs
{-# LANGUAGE DeriveAnyClass #-} | Module : KMonad . Keyboard . IO.Linux . DeviceSource Description : Load and acquire a linux /dev / input device Copyright : ( c ) , 2019 License : MIT Maintainer : Stability : experimental Portability : portable Module : KMonad.Keyboard.IO.Linux.DeviceSource Description : Load and acquire a linux /dev/input device Copyright : (c) David Janssen, 2019 License : MIT Maintainer : Stability : experimental Portability : portable -} module KMonad.Keyboard.IO.Linux.DeviceSource ( deviceSource , deviceSource64 , KeyEventParser , decode64 ) where import KMonad.Prelude import Foreign.C.Types import System.Posix import KMonad.Keyboard.IO.Linux.Types import KMonad.Util import qualified Data.Serialize as B (decode) import qualified RIO.ByteString as B -------------------------------------------------------------------------------- $ err data DeviceSourceError = IOCtlGrabError FilePath | IOCtlReleaseError FilePath | KeyIODecodeError String deriving Exception instance Show DeviceSourceError where show (IOCtlGrabError pth) = "Could not perform IOCTL grab on: " <> pth show (IOCtlReleaseError pth) = "Could not perform IOCTL release on: " <> pth show (KeyIODecodeError msg) = "KeyEvent decode failed with msg: " <> msg makeClassyPrisms ''DeviceSourceError -------------------------------------------------------------------------------- -- $ffi foreign import ccall "ioctl_keyboard" c_ioctl_keyboard :: CInt -> CInt -> IO CInt | Perform an IOCTL operation on an open keyboard handle ioctl_keyboard :: MonadIO m => Fd -- ^ Descriptor to open keyboard file (like /dev/input/eventXX) -> Bool -- ^ True to grab, False to ungrab -> m Int -- ^ Return the exit code ioctl_keyboard (Fd h) b = fromIntegral <$> liftIO (c_ioctl_keyboard h (if b then 1 else 0)) -------------------------------------------------------------------------------- -- $decoding -- | A 'KeyEventParser' describes how to read and parse 'LinuxKeyEvent's from -- the binary data-stream provided by the device-file. data KeyEventParser = KeyEventParser { _nbytes :: !Int ^ Size of 1 input event in bytes , _prs :: !(B.ByteString -> Either String LinuxKeyEvent) -- ^ Function to convert bytestring to event } makeClassy ''KeyEventParser -- | Default configuration for parsing keyboard events defEventParser :: KeyEventParser defEventParser = KeyEventParser 24 decode64 | The KeyEventParser that works on my 64 - bit Linux environment decode64 :: B.ByteString -> Either String LinuxKeyEvent decode64 bs = linuxKeyEvent . fliptup <$> result where result :: Either String (Int32, Word16, Word16, Word64, Word64) result = B.decode . B.reverse $ bs fliptup (a, b, c, d, e) = (e, d, c, b, a) -------------------------------------------------------------------------------- -- $types -- | Configurable components of a DeviceSource data DeviceSourceCfg = DeviceSourceCfg { _pth :: !FilePath -- ^ Path to the event-file , _parser :: !KeyEventParser -- ^ The method used to decode events } makeClassy ''DeviceSourceCfg -- | Collection of data used to read from linux input.h event stream data DeviceFile = DeviceFile { _cfg :: !DeviceSourceCfg -- ^ Configuration settings ^ filedescriptor to the device file ^ handle to the device file } makeClassy ''DeviceFile instance HasDeviceSourceCfg DeviceFile where deviceSourceCfg = cfg instance HasKeyEventParser DeviceFile where keyEventParser = cfg.parser -- | Open a device file deviceSource :: HasLogFunc e => KeyEventParser -- ^ The method by which to read and decode events -> FilePath -- ^ The filepath to the device file -> RIO e (Acquire KeySource) deviceSource pr pt = mkKeySource (lsOpen pr pt) lsClose lsRead | Open a device file on a standard linux 64 bit architecture deviceSource64 :: HasLogFunc e => FilePath -- ^ The filepath to the device file -> RIO e (Acquire KeySource) deviceSource64 = deviceSource defEventParser -------------------------------------------------------------------------------- -- $io | Open the keyboard , perform an ioctl grab and return a ' DeviceFile ' . This -- can throw an 'IOException' if the file cannot be opened for reading, or an ' IOCtlGrabError ' if an ioctl grab could not be properly performed . lsOpen :: (HasLogFunc e) => KeyEventParser -- ^ The method by which to decode events -> FilePath -- ^ The path to the device file -> RIO e DeviceFile lsOpen pr pt = do h <- liftIO . openFd pt ReadOnly Nothing $ OpenFileFlags False False False False False hd <- liftIO $ fdToHandle h logInfo "Initiating ioctl grab" ioctl_keyboard h True `onErr` IOCtlGrabError pt return $ DeviceFile (DeviceSourceCfg pt pr) h hd | Release the ioctl grab and close the device file . This can throw an -- 'IOException' if the handle to the device cannot be properly closed, or an ' IOCtlReleaseError ' if the ioctl release could not be properly performed . lsClose :: (HasLogFunc e) => DeviceFile -> RIO e () lsClose src = do logInfo "Releasing ioctl grab" ioctl_keyboard (src^.fd) False `onErr` IOCtlReleaseError (src^.pth) liftIO . closeFd $ src^.fd -- | Read a bytestring from an open filehandle and return a parsed event. This can throw a ' KeyIODecodeError ' if reading from the ' DeviceFile ' fails to -- yield a parseable sequence of bytes. lsRead :: (HasLogFunc e) => DeviceFile -> RIO e KeyEvent lsRead src = do bts <- B.hGet (src^.hdl) (src^.nbytes) case src^.prs $ bts of Right p -> case fromLinuxKeyEvent p of Just e -> return e Nothing -> lsRead src Left s -> throwIO $ KeyIODecodeError s
null
https://raw.githubusercontent.com/kmonad/kmonad/3413f1be996142c8ef4f36e246776a6df7175979/src/KMonad/Keyboard/IO/Linux/DeviceSource.hs
haskell
# LANGUAGE DeriveAnyClass # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ $ffi ^ Descriptor to open keyboard file (like /dev/input/eventXX) ^ True to grab, False to ungrab ^ Return the exit code ------------------------------------------------------------------------------ $decoding | A 'KeyEventParser' describes how to read and parse 'LinuxKeyEvent's from the binary data-stream provided by the device-file. ^ Function to convert bytestring to event | Default configuration for parsing keyboard events ------------------------------------------------------------------------------ $types | Configurable components of a DeviceSource ^ Path to the event-file ^ The method used to decode events | Collection of data used to read from linux input.h event stream ^ Configuration settings | Open a device file ^ The method by which to read and decode events ^ The filepath to the device file ^ The filepath to the device file ------------------------------------------------------------------------------ $io can throw an 'IOException' if the file cannot be opened for reading, or an ^ The method by which to decode events ^ The path to the device file 'IOException' if the handle to the device cannot be properly closed, or an | Read a bytestring from an open filehandle and return a parsed event. This yield a parseable sequence of bytes.
| Module : KMonad . Keyboard . IO.Linux . DeviceSource Description : Load and acquire a linux /dev / input device Copyright : ( c ) , 2019 License : MIT Maintainer : Stability : experimental Portability : portable Module : KMonad.Keyboard.IO.Linux.DeviceSource Description : Load and acquire a linux /dev/input device Copyright : (c) David Janssen, 2019 License : MIT Maintainer : Stability : experimental Portability : portable -} module KMonad.Keyboard.IO.Linux.DeviceSource ( deviceSource , deviceSource64 , KeyEventParser , decode64 ) where import KMonad.Prelude import Foreign.C.Types import System.Posix import KMonad.Keyboard.IO.Linux.Types import KMonad.Util import qualified Data.Serialize as B (decode) import qualified RIO.ByteString as B $ err data DeviceSourceError = IOCtlGrabError FilePath | IOCtlReleaseError FilePath | KeyIODecodeError String deriving Exception instance Show DeviceSourceError where show (IOCtlGrabError pth) = "Could not perform IOCTL grab on: " <> pth show (IOCtlReleaseError pth) = "Could not perform IOCTL release on: " <> pth show (KeyIODecodeError msg) = "KeyEvent decode failed with msg: " <> msg makeClassyPrisms ''DeviceSourceError foreign import ccall "ioctl_keyboard" c_ioctl_keyboard :: CInt -> CInt -> IO CInt | Perform an IOCTL operation on an open keyboard handle ioctl_keyboard :: MonadIO m ioctl_keyboard (Fd h) b = fromIntegral <$> liftIO (c_ioctl_keyboard h (if b then 1 else 0)) data KeyEventParser = KeyEventParser { _nbytes :: !Int ^ Size of 1 input event in bytes , _prs :: !(B.ByteString -> Either String LinuxKeyEvent) } makeClassy ''KeyEventParser defEventParser :: KeyEventParser defEventParser = KeyEventParser 24 decode64 | The KeyEventParser that works on my 64 - bit Linux environment decode64 :: B.ByteString -> Either String LinuxKeyEvent decode64 bs = linuxKeyEvent . fliptup <$> result where result :: Either String (Int32, Word16, Word16, Word64, Word64) result = B.decode . B.reverse $ bs fliptup (a, b, c, d, e) = (e, d, c, b, a) data DeviceSourceCfg = DeviceSourceCfg } makeClassy ''DeviceSourceCfg data DeviceFile = DeviceFile ^ filedescriptor to the device file ^ handle to the device file } makeClassy ''DeviceFile instance HasDeviceSourceCfg DeviceFile where deviceSourceCfg = cfg instance HasKeyEventParser DeviceFile where keyEventParser = cfg.parser deviceSource :: HasLogFunc e -> RIO e (Acquire KeySource) deviceSource pr pt = mkKeySource (lsOpen pr pt) lsClose lsRead | Open a device file on a standard linux 64 bit architecture deviceSource64 :: HasLogFunc e -> RIO e (Acquire KeySource) deviceSource64 = deviceSource defEventParser | Open the keyboard , perform an ioctl grab and return a ' DeviceFile ' . This ' IOCtlGrabError ' if an ioctl grab could not be properly performed . lsOpen :: (HasLogFunc e) -> RIO e DeviceFile lsOpen pr pt = do h <- liftIO . openFd pt ReadOnly Nothing $ OpenFileFlags False False False False False hd <- liftIO $ fdToHandle h logInfo "Initiating ioctl grab" ioctl_keyboard h True `onErr` IOCtlGrabError pt return $ DeviceFile (DeviceSourceCfg pt pr) h hd | Release the ioctl grab and close the device file . This can throw an ' IOCtlReleaseError ' if the ioctl release could not be properly performed . lsClose :: (HasLogFunc e) => DeviceFile -> RIO e () lsClose src = do logInfo "Releasing ioctl grab" ioctl_keyboard (src^.fd) False `onErr` IOCtlReleaseError (src^.pth) liftIO . closeFd $ src^.fd can throw a ' KeyIODecodeError ' if reading from the ' DeviceFile ' fails to lsRead :: (HasLogFunc e) => DeviceFile -> RIO e KeyEvent lsRead src = do bts <- B.hGet (src^.hdl) (src^.nbytes) case src^.prs $ bts of Right p -> case fromLinuxKeyEvent p of Just e -> return e Nothing -> lsRead src Left s -> throwIO $ KeyIODecodeError s
654a8615e19209551bd3d8c4776c62b57eca4dcb6796f75405a02f77fd339683
bobzhang/fan
gtools.ml
let empty_entry ename _ = raise (Streamf.Error ("entry [" ^ ename ^ "] is empty")) (* let is_level_labelled n l = *) (* match (l:Gdefs.level) with *) (* | {lname=Some n1 ; _ } -> n = n1 *) (* | _ -> false *) try to decouple the node [ x ] into ( terminals , node , son ) triple , the length of terminals should have at least length [ 2 ] , otherwise , it does not make sense { [ ] } try to decouple the node [x] into (terminals,node,son) triple, the length of terminals should have at least length [2], otherwise, it does not make sense {[ ]} *) let get_terminals x = let rec aux tokl last_tok x = match (x:Gdefs.tree) with | Node {node = Token tok (* (#Tokenf.terminal as tok) *); son; brother = DeadEnd} -> aux (last_tok :: tokl) tok son | tree -> if tokl = [] then None (* FIXME?*) else Some (List.rev (last_tok :: tokl), last_tok, tree) in match (x:Gdefs.node) with | {node=Token tok;son;_} -> first case we do n't require anything on [ brother ] (aux [] tok son) | _ -> None (** used in [Delete], the delete API may be deprecated in the future *) let logically_eq_symbols (entry:Gdefs.entry) = let rec eq_symbol (s1:Gdefs.symbol) (s2:Gdefs.symbol) = match (s1, s2) with | (Nterm e1, Nterm e2) -> e1.name = e2.name | (Nterm e1, Self) -> e1.name = entry.name | (Self, Nterm e2) -> entry.name = e2.name (* | (Self, Self) -> true *) | (Snterml (e1, l1), Snterml (e2, l2)) -> e1.name = e2.name && l1 = l2 | (List0 s1, List0 s2) | (List1 s1, List1 s2) | (Peek s1, Peek s2) | (Try s1, Try s2) -> eq_symbol s1 s2 | (List0sep (s1, sep1), List0sep (s2, sep2)) | (List1sep (s1, sep1), List1sep (s2, sep2)) -> eq_symbol s1 s2 && eq_symbol sep1 sep2 | Token x , Token y -> Tokenf.eq_pattern x y | _ -> s1 = s2 in eq_symbol (* used in [Insert] *) let rec eq_symbol (s1:Gdefs.symbol) (s2:Gdefs.symbol) = match (s1, s2) with | (Nterm e1, Nterm e2) -> e1 == e2 | (Snterml (e1, l1), Snterml (e2, l2)) -> e1 == e2 && l1 = l2 | (Self, Self) -> true | (List0 s1, List0 s2) | (List1 s1, List1 s2) | (Peek s1, Peek s2) | (Try s1, Try s2) -> eq_symbol s1 s2 | (List0sep (s1, sep1), List0sep (s2, sep2)) | (List1sep (s1, sep1), List1sep (s2, sep2)) -> eq_symbol s1 s2 && eq_symbol sep1 sep2 | Token x, Token y -> Tokenf.eq_pattern x y | _ -> s1 = s2 let rec entry_first (v:Gdefs.entry) : string list = Listf.concat_map level_first v.levels and level_first (x:Gdefs.level) : string list = tree_first x.lprefix and tree_first (x:Gdefs.tree) : string list = match x with | Node {node;brother;_} -> symbol_first node @ tree_first brother | LocAct _ | DeadEnd -> [] and symbol_first (x:Gdefs.symbol) : string list = match x with | Nterm e -> entry_first e | Snterml (e,_) -> entry_first e | List0 s | List1 s | List0sep (s,_) | List1sep (s,_) -> symbol_first s | Self -> assert false | Try s | Peek s ->symbol_first s (* | `Keyword s -> [s ] (\* FIXME *\) *) | Token _ -> [] let mk_action=Gaction.mk (* tree processing *) let rec flatten_tree (x: Gdefs.tree ) = match x with | DeadEnd -> [] | LocAct _ -> [[]] | Node {node = n; brother = b; son = s} -> List.map (fun l -> n::l) (flatten_tree s) @ flatten_tree b type brothers = | Bro of Gdefs.symbol * brothers list | End let get_brothers x = let rec aux acc (x:Gdefs.tree) = match x with | DeadEnd -> List.rev acc | LocAct _ -> List.rev (End:: acc) | Node {node = n; brother = b; son = s} -> aux (Bro (n, aux [] s) :: acc) b in aux [] x let get_children x = let rec aux acc = function | [] -> List.rev acc | [Bro (n, x)] -> aux (n::acc) x | _ -> raise Exit in aux [] x (* level -> lprefix -> *) let get_first = let rec aux acc (x:Gdefs.tree) = match x with |Node {node;brother;_} -> aux (node::acc) brother |LocAct _ | DeadEnd -> acc in aux [] let get_first_from levels set = levels |> List.iter (fun (level:Gdefs.level) -> level.lprefix |> get_first |> Hashset.add_list set) (* let rec get_first = fun *) (* [ Node {node;brother} -> [node::get_first brother] *) (* | _ -> [] ]; *) let ( a : tree ) ( b : tree ) = match a with [ Node { node;son;brother = } - > ( * merge_tree let rec append_tree (a:tree) (b:tree) = match a with [Node {node;son;brother=DeadEnd} -> (* merge_tree *) Node {node; son = append_tree son b; brother = DeadEnd } (* (append_tree brother b) *) |Node {node;son;brother} -> merge_tree (Node {node;son=append_tree son b; brother=DeadEnd}) (append_tree brother b) | LocAct (anno_action,ls) -> LocActAppend(anno_action,ls,b) | DeadEnd -> assert false | LocActAppend (anno_action,ls,la) -> LocActAppend (anno_action,ls, append_tree la b) ] and merge_tree (a:tree) (b:tree) : tree = match (a,b) with [ (DeadEnd,_) -> b | (_,DeadEnd) -> a | (Node {node=n1;son=s1;brother=b1}, Node{node=n2;son=s2;brother=b2}) -> if eq_symbol n1 n2 then merge_tree (Node {node=n1; son = merge_tree s1 s2;brother=DeadEnd }) (merge_tree b1 b2) else Node {node=n1;son=s1;brother = merge_tree b1 b} | (Node {node;son;brother=b1},(LocAct _ as b2) ) -> Node {node;son;brother = merge_tree b1 b2} | (Node {node;son;brother=b1}, (LocActAppend (act,ls,n2))) -> | (LocAct (act,ls), LocActAppend (act2,ls2,n2)) -> LocActAppend (act2,ls2,) ] ; *) (* local variables: *) compile - command : " cd .. & & pmake treeparser / gtools.cmo " (* end: *)
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/treeparser/gtools.ml
ocaml
let is_level_labelled n l = match (l:Gdefs.level) with | {lname=Some n1 ; _ } -> n = n1 | _ -> false (#Tokenf.terminal as tok) FIXME? * used in [Delete], the delete API may be deprecated in the future | (Self, Self) -> true used in [Insert] | `Keyword s -> [s ] (\* FIXME *\) tree processing level -> lprefix -> let rec get_first = fun [ Node {node;brother} -> [node::get_first brother] | _ -> [] ]; merge_tree (append_tree brother b) local variables: end:
let empty_entry ename _ = raise (Streamf.Error ("entry [" ^ ename ^ "] is empty")) try to decouple the node [ x ] into ( terminals , node , son ) triple , the length of terminals should have at least length [ 2 ] , otherwise , it does not make sense { [ ] } try to decouple the node [x] into (terminals,node,son) triple, the length of terminals should have at least length [2], otherwise, it does not make sense {[ ]} *) let get_terminals x = let rec aux tokl last_tok x = match (x:Gdefs.tree) with -> aux (last_tok :: tokl) tok son | tree -> else Some (List.rev (last_tok :: tokl), last_tok, tree) in match (x:Gdefs.node) with | {node=Token tok;son;_} -> first case we do n't require anything on [ brother ] (aux [] tok son) | _ -> None let logically_eq_symbols (entry:Gdefs.entry) = let rec eq_symbol (s1:Gdefs.symbol) (s2:Gdefs.symbol) = match (s1, s2) with | (Nterm e1, Nterm e2) -> e1.name = e2.name | (Nterm e1, Self) -> e1.name = entry.name | (Self, Nterm e2) -> entry.name = e2.name | (Snterml (e1, l1), Snterml (e2, l2)) -> e1.name = e2.name && l1 = l2 | (List0 s1, List0 s2) | (List1 s1, List1 s2) | (Peek s1, Peek s2) | (Try s1, Try s2) -> eq_symbol s1 s2 | (List0sep (s1, sep1), List0sep (s2, sep2)) | (List1sep (s1, sep1), List1sep (s2, sep2)) -> eq_symbol s1 s2 && eq_symbol sep1 sep2 | Token x , Token y -> Tokenf.eq_pattern x y | _ -> s1 = s2 in eq_symbol let rec eq_symbol (s1:Gdefs.symbol) (s2:Gdefs.symbol) = match (s1, s2) with | (Nterm e1, Nterm e2) -> e1 == e2 | (Snterml (e1, l1), Snterml (e2, l2)) -> e1 == e2 && l1 = l2 | (Self, Self) -> true | (List0 s1, List0 s2) | (List1 s1, List1 s2) | (Peek s1, Peek s2) | (Try s1, Try s2) -> eq_symbol s1 s2 | (List0sep (s1, sep1), List0sep (s2, sep2)) | (List1sep (s1, sep1), List1sep (s2, sep2)) -> eq_symbol s1 s2 && eq_symbol sep1 sep2 | Token x, Token y -> Tokenf.eq_pattern x y | _ -> s1 = s2 let rec entry_first (v:Gdefs.entry) : string list = Listf.concat_map level_first v.levels and level_first (x:Gdefs.level) : string list = tree_first x.lprefix and tree_first (x:Gdefs.tree) : string list = match x with | Node {node;brother;_} -> symbol_first node @ tree_first brother | LocAct _ | DeadEnd -> [] and symbol_first (x:Gdefs.symbol) : string list = match x with | Nterm e -> entry_first e | Snterml (e,_) -> entry_first e | List0 s | List1 s | List0sep (s,_) | List1sep (s,_) -> symbol_first s | Self -> assert false | Try s | Peek s ->symbol_first s | Token _ -> [] let mk_action=Gaction.mk let rec flatten_tree (x: Gdefs.tree ) = match x with | DeadEnd -> [] | LocAct _ -> [[]] | Node {node = n; brother = b; son = s} -> List.map (fun l -> n::l) (flatten_tree s) @ flatten_tree b type brothers = | Bro of Gdefs.symbol * brothers list | End let get_brothers x = let rec aux acc (x:Gdefs.tree) = match x with | DeadEnd -> List.rev acc | LocAct _ -> List.rev (End:: acc) | Node {node = n; brother = b; son = s} -> aux (Bro (n, aux [] s) :: acc) b in aux [] x let get_children x = let rec aux acc = function | [] -> List.rev acc | [Bro (n, x)] -> aux (n::acc) x | _ -> raise Exit in aux [] x let get_first = let rec aux acc (x:Gdefs.tree) = match x with |Node {node;brother;_} -> aux (node::acc) brother |LocAct _ | DeadEnd -> acc in aux [] let get_first_from levels set = levels |> List.iter (fun (level:Gdefs.level) -> level.lprefix |> get_first |> Hashset.add_list set) let ( a : tree ) ( b : tree ) = match a with [ Node { node;son;brother = } - > ( * merge_tree let rec append_tree (a:tree) (b:tree) = match a with [Node {node;son;brother=DeadEnd} -> Node {node; son = append_tree son b; brother = DeadEnd } |Node {node;son;brother} -> merge_tree (Node {node;son=append_tree son b; brother=DeadEnd}) (append_tree brother b) | LocAct (anno_action,ls) -> LocActAppend(anno_action,ls,b) | DeadEnd -> assert false | LocActAppend (anno_action,ls,la) -> LocActAppend (anno_action,ls, append_tree la b) ] and merge_tree (a:tree) (b:tree) : tree = match (a,b) with [ (DeadEnd,_) -> b | (_,DeadEnd) -> a | (Node {node=n1;son=s1;brother=b1}, Node{node=n2;son=s2;brother=b2}) -> if eq_symbol n1 n2 then merge_tree (Node {node=n1; son = merge_tree s1 s2;brother=DeadEnd }) (merge_tree b1 b2) else Node {node=n1;son=s1;brother = merge_tree b1 b} | (Node {node;son;brother=b1},(LocAct _ as b2) ) -> Node {node;son;brother = merge_tree b1 b2} | (Node {node;son;brother=b1}, (LocActAppend (act,ls,n2))) -> | (LocAct (act,ls), LocActAppend (act2,ls2,n2)) -> LocActAppend (act2,ls2,) ] ; *) compile - command : " cd .. & & pmake treeparser / gtools.cmo "
58ddb0b2609bce417ca7b68ca44bd03e466537b14e8a9ed451550d245e15b4f2
joelmccracken/reddup
Git.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveAnyClass #-} module Git where import Data.Text (concat) import Turtle import Prelude hiding (FilePath, concat) import qualified Control.Foldl as Fold import GitParse gitStatus :: Shell GitStatus gitStatus = do let statusStream = inshell "git status --porcelain" Turtle.empty fmap parseGitStatusLine statusStream gitBranches :: Shell GitBranch gitBranches = do let branchStream = inshell "git branch" Turtle.empty fmap parseGitBranchLine branchStream lengthOfOutput :: Shell Turtle.Line -> Shell Int lengthOfOutput cmd = Turtle.fold cmd Fold.length remoteBranchContainsBranch :: GitBranch -> Shell Bool remoteBranchContainsBranch (GitBranch name) = do let command = inshell (concat ["git branch -r --contains ", name]) Turtle.empty len <- lengthOfOutput command return $ len > 0 withoutRemote :: Shell GitBranch -> GitBranch -> Shell GitBranch withoutRemote accum next = do remoteFound <- remoteBranchContainsBranch next if remoteFound then accum else accum <|> return next unpushedGitBranches :: Shell GitBranch unpushedGitBranches = join $ fold gitBranches $ Fold withoutRemote mzero id
null
https://raw.githubusercontent.com/joelmccracken/reddup/1bce9371d79c410b30b91c10bf040777260777ad/src/Git.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE DeriveAnyClass #
module Git where import Data.Text (concat) import Turtle import Prelude hiding (FilePath, concat) import qualified Control.Foldl as Fold import GitParse gitStatus :: Shell GitStatus gitStatus = do let statusStream = inshell "git status --porcelain" Turtle.empty fmap parseGitStatusLine statusStream gitBranches :: Shell GitBranch gitBranches = do let branchStream = inshell "git branch" Turtle.empty fmap parseGitBranchLine branchStream lengthOfOutput :: Shell Turtle.Line -> Shell Int lengthOfOutput cmd = Turtle.fold cmd Fold.length remoteBranchContainsBranch :: GitBranch -> Shell Bool remoteBranchContainsBranch (GitBranch name) = do let command = inshell (concat ["git branch -r --contains ", name]) Turtle.empty len <- lengthOfOutput command return $ len > 0 withoutRemote :: Shell GitBranch -> GitBranch -> Shell GitBranch withoutRemote accum next = do remoteFound <- remoteBranchContainsBranch next if remoteFound then accum else accum <|> return next unpushedGitBranches :: Shell GitBranch unpushedGitBranches = join $ fold gitBranches $ Fold withoutRemote mzero id
9949163db417d298f94866e319df15d3fb6115fe6e3a24e7545f3d2a9df80776
kapok-lang/kapok
kapok_trans_special_form.erl
%% special form -module(kapok_trans_special_form). -export([translate_attribute/4, translate_let/4, translate_dot_let/4, translate_let_args/2, translate_do/3, translate_case/5, translate_fn/3, translate_fn/4, translate_fn/5, translate_fn/6, translate_send/4, translate_receive/3, translate_try/3, format_error/1 ]). -import(kapok_scanner, [token_meta/1, token_symbol/1]). -import(kapok_trans, [translate/2, translate_def_arg/2, translate_def_args/2, translate_guard/2, translate_body/3]). -include("kapok.hrl"). %% attribute translate_attribute(Meta, A, T, Ctx) -> {{attribute,?line(Meta), A, T}, Ctx}. %% let translate_let(Meta, Args, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TArgs, TCtx1} = translate_let_args(Args, Ctx1), {TBody, TCtx2} = translate_body(Meta, Body, TCtx1), BodyBlock = build_block(Meta, TBody), TCtx3 = kapok_ctx:pop_scope(TCtx2), {build_block(Meta, TArgs ++ [BodyBlock]), TCtx3}. %% dot let translate_dot_let(Meta, Args, Tail, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TArgs, TCtx1, [Module, Fun]} = translate_dot_let_args(Args, Ctx1), Dot = {dot, Meta, {Module, Fun}}, Body = [{list, Meta, [Dot | Tail]}], {TBody, TCtx2} = translate_body(Meta, Body, TCtx1), TCtx3 = kapok_ctx:pop_scope(TCtx2), {build_block(Meta, TArgs ++ TBody), TCtx3}. translate_let_pattern(Arg, #{context := Context} = Ctx) -> {TArg, TCtx} = translate(Arg, Ctx#{context => let_pattern}), {TArg, TCtx#{context => Context}}. translate_dot_let_pattern(Arg, #{context := Context} = Ctx) -> {TArg, TCtx} = translate(Arg, Ctx#{context => dot_let_pattern}), {TArg, TCtx#{context => Context}, token_symbol(TArg)}. translate_let_args(Args, Ctx) -> translate_let_args(Args, [], Ctx). translate_let_args([], Acc, Ctx) -> {lists:reverse(Acc), Ctx#{context => nil}}; translate_let_args([H], _Acc, Ctx) -> Error = {let_odd_forms, {H}}, kapok_error:form_error(token_meta(H), ?m(Ctx, file), ?MODULE, Error); translate_let_args([Pattern, Value | T], Acc, Ctx) -> Translate the value part first , and then the pattern part . %% Otherwise if there is a call of the pattern in the value part, it will cause a weird compile error saying " VAR_xxx is unbound " , where ` VAR_xxx ` %% is the variable name of the translated pattern. {TValue, TCtx} = translate(Value, Ctx), {TPattern, TCtx1} = translate_let_pattern(Pattern, TCtx), translate_let_args(T, [{match, ?line(token_meta(Pattern)), TPattern, TValue} | Acc], TCtx1). translate_dot_let_arg({C, Meta, Name}, Ctx) when ?is_id(C) -> case kapok_ctx:get_var(Meta, Ctx, Name) of {ok, _} -> {[], Ctx, {identifier, Meta, Name}}; _ -> {[], Ctx, {atom, Meta, Name}} end; translate_dot_let_arg({C, Meta, Name}, Ctx) when ?is_keyword_or_atom(C) -> {[], Ctx, {atom, Meta, Name}}; translate_dot_let_arg({_, Meta, _} = Dot, Ctx) -> {TDot, TCtx} = translate(Dot, Ctx), {TName, TCtx1, Name} = translate_dot_let_pattern({identifier, Meta, 'DOT'}, TCtx), Ast = {match, ?line(Meta), TName, TDot}, Id = {identifier, Meta, Name}, {[Ast], TCtx1, Id}. translate_dot_let_args(Args, Ctx) -> {AstList, Ctx1, IdList} = lists:foldl(fun (Ast, {AstAcc, C, IdAcc}) -> {Ast1, C1, Id1} = translate_dot_let_arg(Ast, C), {Ast1 ++ AstAcc, C1, [Id1 | IdAcc]} end, {[], Ctx, []}, Args), {lists:reverse(AstList), Ctx1, lists:reverse(IdList)}. %% do translate_do(Meta, Exprs, Ctx) -> {TExprs, TCtx} = translate(Exprs, Ctx), {build_block(Meta, TExprs), TCtx}. build_block(Meta, Exprs) when is_list(Meta) -> build_block(?line(Meta), Exprs); build_block(Line, Exprs) when is_integer(Line) -> {block, Line, Exprs}. %% case translate_case(Meta, Expr, Clause, Left, Ctx) -> {TExpr, TCtx} = translate(Expr, Ctx), {TClause, TCtx1} = translate_case_clause(Clause, TCtx), {TLeft, TCtx2} = lists:mapfoldl(fun translate_case_clause/2, TCtx1, Left), {{'case', ?line(Meta), TExpr, [TClause | TLeft]}, TCtx2}. translate_case_clause({list, Meta, []}, Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_case_clause}); translate_case_clause({list, Meta, [_P]}, Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {missing_case_clause_body}); translate_case_clause({list, Meta, [P, {list, _, [{keyword_when, _, _} | _]} = Guard | Body]}, Ctx) -> translate_case_clause(Meta, P, Guard, Body, Ctx); translate_case_clause({list, Meta, [P | B]}, Ctx) -> translate_case_clause(Meta, P, [], B, Ctx); translate_case_clause({C, Meta, _} = Ast, Ctx) when C /= list -> Error = {invalid_case_clause, {Ast}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error). translate_case_clause(Meta, Pattern, Guard, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TPattern, TCtx1} = translate_case_pattern(Pattern, Ctx1), {TGuard, TCtx2} = translate_guard(Guard, TCtx1), {TBody, TCtx3} = translate_body(Meta, Body, TCtx2), TCtx4 = kapok_ctx:pop_scope(TCtx3), {{clause, ?line(Meta), [TPattern], TGuard, TBody}, TCtx4}. translate_case_pattern(Arg, #{context := Context} = Ctx) -> {TArg, TCtx} = translate(Arg, Ctx#{context => case_pattern}), {TArg, TCtx#{context => Context}}. %% fn translate_fn(Meta, Exprs, Ctx) when is_list(Exprs) -> {Clauses, TCtx} = translate_fn_exprs(Exprs, Ctx), {{'fun', ?line(Meta), {clauses, Clauses}}, TCtx}. translate_fn(Meta, Name, Arity, Ctx) when is_atom(Name), is_number(Arity) -> {{'fun', ?line(Meta), {function, Name, Arity}}, Ctx}; translate_fn(Meta, {identifier, _, Name} = Id, Exprs, Ctx) when is_list(Exprs) -> Ctx1 = kapok_ctx:push_scope(Ctx), {_, TCtx1} = translate_def_arg(Id, Ctx1), {Clauses, TCtx2} = translate_fn_exprs(Exprs, TCtx1), TCtx3 = kapok_ctx:pop_scope(TCtx2), {{'named_fun', ?line(Meta), Name, Clauses}, TCtx3}. translate_fn(Meta, {C1, _, _} = Module, {C2, _, _} = Name, {C3, _, _} = Arity, Ctx) when ?is_local_id(C1), ?is_local_id(C2), ?is_number(C3) -> {TModule, TCtx} = translate(Module, Ctx), {TName, TCtx1} = translate(Name, TCtx), {TArity, TCtx2} = translate(Arity, TCtx1), {{'fun', ?line(Meta), {function, TModule, TName, TArity}}, TCtx2}; translate_fn(Meta, Args, Guard, Body, Ctx) when is_tuple(Args), (is_list(Guard) orelse is_tuple(Guard)), is_list(Body) -> {Clause, TCtx} = translate_fn_clause(Meta, Args, Guard, Body, Ctx), {{'fun', ?line(Meta), {clauses, [Clause]}}, TCtx}. translate_fn(Meta, {identifier, _, Name} = Id, Args, Guard, Body, Ctx) when is_tuple(Args), (is_list(Guard) orelse is_tuple(Guard)), is_list(Body) -> Ctx1 = kapok_ctx:push_scope(Ctx), {_, TCtx1} = translate_def_arg(Id, Ctx1), {Clause, TCtx2} = translate_fn_clause(Meta, Args, Guard, Body, TCtx1), TCtx3 = kapok_ctx:pop_scope(TCtx2), {{'named_fun', ?line(Meta), Name, [Clause]}, TCtx3}. translate_fn_exprs(Exprs, Ctx) when is_list(Exprs) -> check_fn_exprs(Exprs, Ctx), lists:mapfoldl(fun translate_fn_expr/2, Ctx, Exprs). translate_fn_expr({list, Meta, [{literal_list, _, _} = Args, {list, _, [{keyword_when, _, _} | _]} = Guard | Body]}, Ctx) -> translate_fn_clause(Meta, Args, Guard, Body, Ctx); translate_fn_expr({list, Meta, [{literal_list, _, _} = Args | Body]}, Ctx) -> translate_fn_clause(Meta, Args, [], Body, Ctx); translate_fn_expr(Ast, Ctx) -> Error = {invalid_fn_expression, {Ast}}, kapok_error:form_error(token_meta(Ast), ?m(Ctx, file), ?MODULE, Error). translate_fn_clause(Meta, Args, Guard, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TArgs, TCtx1} = translate_def_args(Args, Ctx1), {TGuard, TCtx2} = translate_guard(Guard, TCtx1), {TBody, TCtx3} = translate_body(Meta, Body, TCtx2), Clause = {clause, ?line(Meta), TArgs, TGuard, TBody}, TCtx4 = kapok_ctx:pop_scope(TCtx3), {Clause, TCtx4}. check_fn_exprs(Exprs, Ctx) when is_list(Exprs) -> lists:foldl(fun check_fn_expr_arity/2, {0, Ctx}, Exprs). check_fn_expr_arity({list, Meta, [{literal_list, _, List} | _]}, {Last, Ctx}) -> Arity = length(List), case Last of 0 -> {Arity, Ctx}; Arity -> {Arity, Ctx}; _ -> Error = {fn_clause_arity_mismatch, {Arity, Last}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error) end. %% send translate_send(Meta, Pid, Message, Ctx) -> {TPid, TCtx} = translate(Pid, Ctx), {TMessage, TCtx1} = translate(Message, TCtx), {{op, ?line(Meta), '!', TPid, TMessage}, TCtx1}. %% receive %% translate receive translate_receive(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_receive_expr}); translate_receive(Meta, Clauses, Ctx) -> {Result, TCtx} = translate_receive(Meta, Clauses, [], Ctx), case Result of {TClauses, TExpr, TBody} when is_list(TClauses) -> {{'receive', ?line(Meta), TClauses, TExpr, TBody}, TCtx}; TClauses when is_list(TClauses) -> {{'receive', ?line(Meta), TClauses}, TCtx} end. translate_receive(_Meta, [], Acc, Ctx) -> {lists:reverse(Acc), Ctx}; translate_receive(Meta, [H], Acc, Ctx) -> case H of {list, Meta1, [{identifier, _, 'after'}, Expr | Body]} -> {TExpr, TCtx} = translate(Expr, Ctx), {TBody, TCtx1} = translate_body(Meta1, Body, TCtx), {{lists:reverse(Acc), TExpr, TBody}, TCtx1}; _ -> {TClause, TCtx} = translate_case_clause(H, Ctx), translate_receive(Meta, [], [TClause | Acc], TCtx) end; translate_receive(Meta, [H|T], Acc, Ctx) -> case H of {list, Meta1, [{identifier, _, 'after'}, _Expr | _Body]} -> kapok_error:form_error(Meta1, ?m(Ctx, file), ?MODULE, {after_clause_not_the_last}); _ -> {TClause, TCtx} = translate_case_clause(H, Ctx), translate_receive(Meta, T, [TClause | Acc], TCtx) end. %% try catch after block translate_try(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_try_expr}); translate_try(Meta, [Expr|Left], Ctx) -> {TExpr, TCtx} = translate(Expr, Ctx), {CaseClauses, CatchClauses, AfterBody, TCtx1} = translate_try_body(Meta, Left, TCtx), %% notice that case clauses are always empty {{'try', ?line(Meta), [TExpr], CaseClauses, CatchClauses, AfterBody}, TCtx1}. translate_try_body(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {try_without_body}); translate_try_body(Meta, [{list, _, [{list, _, _} | _] = Clauses} | Left], Ctx) -> {TClauses, TCtx} = lists:mapfoldl(fun translate_case_clause/2, Ctx, Clauses), {TCatchClauses, AfterBody, TCtx1} = translate_try_catch_after(Meta, Left, TCtx), {TClauses, TCatchClauses, AfterBody, TCtx1}; translate_try_body(Meta, Left, Ctx) -> {TCatchClauses, AfterBody, TCtx1} = translate_try_catch_after(Meta, Left, Ctx), {[], TCatchClauses, AfterBody, TCtx1}. translate_try_catch_after(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {try_without_catch_or_after}); translate_try_catch_after(_Meta, [{list, Meta1, [{identifier, _, 'catch'} | CatchClauses]}], Ctx) -> {TCatchClauses, TCtx} = translate_catch_clauses(Meta1, CatchClauses, Ctx), {TCatchClauses, [], TCtx}; translate_try_catch_after(_Meta, [{list, Meta1, [{identifier, _, 'after'} | Body]}], Ctx) -> {TBody, TCtx} = translate_body(Meta1, Body, Ctx), {[], TBody, TCtx}; translate_try_catch_after(_Meta, [{list, Meta1, [{identifier, _, 'catch'} | CatchClauses]}, {list, Meta2, [{identifier, _, 'after'} | Body]}], Ctx) -> {TCatchClauses, TCtx} = translate_catch_clauses(Meta1, CatchClauses, Ctx), {TBody, TCtx1} = translate_body(Meta2, Body, TCtx), {TCatchClauses, TBody, TCtx1}; translate_try_catch_after(Meta, Exprs, Ctx) -> Error = {invalid_catch_after_clause, {Exprs}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error). translate_catch_clauses(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {no_catch_clause}); translate_catch_clauses(_Meta, Clauses, Ctx) -> lists:mapfoldl(fun translate_catch_clause/2, Ctx, Clauses). translate_catch_clause({list, Meta, []}, Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_catch_clause}); translate_catch_clause({list, Meta, [E]}, Ctx) -> Error = {missing_catch_clause_body, {E}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error); translate_catch_clause({list, Meta, [E, {list, _, [{keyword_when, _, _} | _]} = Guard | Body]}, Ctx) -> translate_catch_clause(Meta, E, Guard, Body, Ctx); translate_catch_clause({list, Meta, [E | B]}, Ctx) -> translate_catch_clause(Meta, E, [], B, Ctx); translate_catch_clause({C, Meta, _} = Ast, Ctx) when C /= list -> Error = {invalid_catch_clause, {Ast}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error). translate_catch_clause(Meta, Exception, Guard, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TException, TCtx1} = translate_exception(Exception, Ctx1), {TGuard, TCtx2} = translate_guard(Guard, TCtx1), {TBody, TCtx3} = translate_body(Meta, Body, TCtx2), TCtx4 = kapok_ctx:pop_scope(TCtx3), {{clause, ?line(Meta), [TException], TGuard, TBody}, TCtx4}. translate_exception({list, Meta, [{Category, _, Atom} = Kind, Pattern]}, Ctx) when Category == keyword; Category == atom -> case lists:any(fun(X) -> Atom == X end, ['throw', 'exit', 'error']) of false -> Error = {invalid_exception_type, {Atom}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error); true -> ok end, {TKind, TCtx} = translate(Kind, Ctx), {TPattern, TCtx1} = translate_case_pattern(Pattern, TCtx), Line = ?line(Meta), {{tuple, Line, [TKind, TPattern, {var, Line, '_'}]}, TCtx1}; translate_exception({list, Meta, [Kind, Pattern]}, Ctx) -> {TKind, TCtx} = translate_case_pattern(Kind, Ctx), {TPattern, TCtx1} = translate_case_pattern(Pattern, TCtx), Line = ?line(Meta), {{tuple, Line, [TKind, TPattern, {var, Line, '_'}]}, TCtx1}; translate_exception(Pattern, Ctx) -> {TPattern, TCtx} = translate_case_pattern(Pattern, Ctx), Line = ?line(token_meta(Pattern)), {{tuple, Line, [{atom, Line, 'throw'}, TPattern, {var, Line, '_'}]}, TCtx}. %% Error format_error({let_odd_forms, {Form}}) -> io_lib:format("let requires an even number of forms in binding, unpaired form: ~p~n", [Form]); format_error({empty_case_clause}) -> io_lib:format("case clause is empty"); format_error({missing_case_clause_body}) -> io_lib:format("case clause body is missing"); format_error({invalid_case_clause, {Ast}}) -> io_lib:format("invalid case clause ~w", [Ast]); format_error({invalid_fn_expression, {Expr}}) -> io_lib:format("invalid fn expression ~w", [Expr]); format_error({fn_clause_arity_mismatch, {Arity, Last}}) -> io_lib:format("fn clause arity ~B mismatch with last clause arity ~B~n", [Arity, Last]); format_error({empty_receive_expr}) -> io_lib:format("empty receive expression", []); format_error({after_clause_not_the_last}) -> io_lib:format("after clause should be the last expression of receive or try catch", []); format_error({empty_try_expr}) -> io_lib:format("empty try expression", []); format_error({try_without_body}) -> io_lib:format("try expression without body", []); format_error({try_without_catch_or_after}) -> io_lib:format("try expression without catch or after clause", []); format_error({invalid_catch_after_clause, {Exprs}}) -> io_lib:format("invalid catch and after clause in try: ~w", [Exprs]); format_error({empty_catch_clause}) -> io_lib:format("catch clause is empty", []); format_error({missing_catch_clause_body}) -> io_lib:format("catch clause body is missing", []); format_error({invalid_catch_clause, {Ast}}) -> io_lib:format("invalid catch clause: ~w", [Ast]); format_error({invalid_exception_type, {Type}}) -> io_lib:format("invalid exception type: ~p", [Type]).
null
https://raw.githubusercontent.com/kapok-lang/kapok/4272f990fe495e595d2afe38605dbca560bbe072/lib/kapok/src/kapok_trans_special_form.erl
erlang
special form attribute let dot let Otherwise if there is a call of the pattern in the value part, it will is the variable name of the translated pattern. do case fn send receive translate receive try catch after block notice that case clauses are always empty Error
-module(kapok_trans_special_form). -export([translate_attribute/4, translate_let/4, translate_dot_let/4, translate_let_args/2, translate_do/3, translate_case/5, translate_fn/3, translate_fn/4, translate_fn/5, translate_fn/6, translate_send/4, translate_receive/3, translate_try/3, format_error/1 ]). -import(kapok_scanner, [token_meta/1, token_symbol/1]). -import(kapok_trans, [translate/2, translate_def_arg/2, translate_def_args/2, translate_guard/2, translate_body/3]). -include("kapok.hrl"). translate_attribute(Meta, A, T, Ctx) -> {{attribute,?line(Meta), A, T}, Ctx}. translate_let(Meta, Args, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TArgs, TCtx1} = translate_let_args(Args, Ctx1), {TBody, TCtx2} = translate_body(Meta, Body, TCtx1), BodyBlock = build_block(Meta, TBody), TCtx3 = kapok_ctx:pop_scope(TCtx2), {build_block(Meta, TArgs ++ [BodyBlock]), TCtx3}. translate_dot_let(Meta, Args, Tail, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TArgs, TCtx1, [Module, Fun]} = translate_dot_let_args(Args, Ctx1), Dot = {dot, Meta, {Module, Fun}}, Body = [{list, Meta, [Dot | Tail]}], {TBody, TCtx2} = translate_body(Meta, Body, TCtx1), TCtx3 = kapok_ctx:pop_scope(TCtx2), {build_block(Meta, TArgs ++ TBody), TCtx3}. translate_let_pattern(Arg, #{context := Context} = Ctx) -> {TArg, TCtx} = translate(Arg, Ctx#{context => let_pattern}), {TArg, TCtx#{context => Context}}. translate_dot_let_pattern(Arg, #{context := Context} = Ctx) -> {TArg, TCtx} = translate(Arg, Ctx#{context => dot_let_pattern}), {TArg, TCtx#{context => Context}, token_symbol(TArg)}. translate_let_args(Args, Ctx) -> translate_let_args(Args, [], Ctx). translate_let_args([], Acc, Ctx) -> {lists:reverse(Acc), Ctx#{context => nil}}; translate_let_args([H], _Acc, Ctx) -> Error = {let_odd_forms, {H}}, kapok_error:form_error(token_meta(H), ?m(Ctx, file), ?MODULE, Error); translate_let_args([Pattern, Value | T], Acc, Ctx) -> Translate the value part first , and then the pattern part . cause a weird compile error saying " VAR_xxx is unbound " , where ` VAR_xxx ` {TValue, TCtx} = translate(Value, Ctx), {TPattern, TCtx1} = translate_let_pattern(Pattern, TCtx), translate_let_args(T, [{match, ?line(token_meta(Pattern)), TPattern, TValue} | Acc], TCtx1). translate_dot_let_arg({C, Meta, Name}, Ctx) when ?is_id(C) -> case kapok_ctx:get_var(Meta, Ctx, Name) of {ok, _} -> {[], Ctx, {identifier, Meta, Name}}; _ -> {[], Ctx, {atom, Meta, Name}} end; translate_dot_let_arg({C, Meta, Name}, Ctx) when ?is_keyword_or_atom(C) -> {[], Ctx, {atom, Meta, Name}}; translate_dot_let_arg({_, Meta, _} = Dot, Ctx) -> {TDot, TCtx} = translate(Dot, Ctx), {TName, TCtx1, Name} = translate_dot_let_pattern({identifier, Meta, 'DOT'}, TCtx), Ast = {match, ?line(Meta), TName, TDot}, Id = {identifier, Meta, Name}, {[Ast], TCtx1, Id}. translate_dot_let_args(Args, Ctx) -> {AstList, Ctx1, IdList} = lists:foldl(fun (Ast, {AstAcc, C, IdAcc}) -> {Ast1, C1, Id1} = translate_dot_let_arg(Ast, C), {Ast1 ++ AstAcc, C1, [Id1 | IdAcc]} end, {[], Ctx, []}, Args), {lists:reverse(AstList), Ctx1, lists:reverse(IdList)}. translate_do(Meta, Exprs, Ctx) -> {TExprs, TCtx} = translate(Exprs, Ctx), {build_block(Meta, TExprs), TCtx}. build_block(Meta, Exprs) when is_list(Meta) -> build_block(?line(Meta), Exprs); build_block(Line, Exprs) when is_integer(Line) -> {block, Line, Exprs}. translate_case(Meta, Expr, Clause, Left, Ctx) -> {TExpr, TCtx} = translate(Expr, Ctx), {TClause, TCtx1} = translate_case_clause(Clause, TCtx), {TLeft, TCtx2} = lists:mapfoldl(fun translate_case_clause/2, TCtx1, Left), {{'case', ?line(Meta), TExpr, [TClause | TLeft]}, TCtx2}. translate_case_clause({list, Meta, []}, Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_case_clause}); translate_case_clause({list, Meta, [_P]}, Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {missing_case_clause_body}); translate_case_clause({list, Meta, [P, {list, _, [{keyword_when, _, _} | _]} = Guard | Body]}, Ctx) -> translate_case_clause(Meta, P, Guard, Body, Ctx); translate_case_clause({list, Meta, [P | B]}, Ctx) -> translate_case_clause(Meta, P, [], B, Ctx); translate_case_clause({C, Meta, _} = Ast, Ctx) when C /= list -> Error = {invalid_case_clause, {Ast}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error). translate_case_clause(Meta, Pattern, Guard, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TPattern, TCtx1} = translate_case_pattern(Pattern, Ctx1), {TGuard, TCtx2} = translate_guard(Guard, TCtx1), {TBody, TCtx3} = translate_body(Meta, Body, TCtx2), TCtx4 = kapok_ctx:pop_scope(TCtx3), {{clause, ?line(Meta), [TPattern], TGuard, TBody}, TCtx4}. translate_case_pattern(Arg, #{context := Context} = Ctx) -> {TArg, TCtx} = translate(Arg, Ctx#{context => case_pattern}), {TArg, TCtx#{context => Context}}. translate_fn(Meta, Exprs, Ctx) when is_list(Exprs) -> {Clauses, TCtx} = translate_fn_exprs(Exprs, Ctx), {{'fun', ?line(Meta), {clauses, Clauses}}, TCtx}. translate_fn(Meta, Name, Arity, Ctx) when is_atom(Name), is_number(Arity) -> {{'fun', ?line(Meta), {function, Name, Arity}}, Ctx}; translate_fn(Meta, {identifier, _, Name} = Id, Exprs, Ctx) when is_list(Exprs) -> Ctx1 = kapok_ctx:push_scope(Ctx), {_, TCtx1} = translate_def_arg(Id, Ctx1), {Clauses, TCtx2} = translate_fn_exprs(Exprs, TCtx1), TCtx3 = kapok_ctx:pop_scope(TCtx2), {{'named_fun', ?line(Meta), Name, Clauses}, TCtx3}. translate_fn(Meta, {C1, _, _} = Module, {C2, _, _} = Name, {C3, _, _} = Arity, Ctx) when ?is_local_id(C1), ?is_local_id(C2), ?is_number(C3) -> {TModule, TCtx} = translate(Module, Ctx), {TName, TCtx1} = translate(Name, TCtx), {TArity, TCtx2} = translate(Arity, TCtx1), {{'fun', ?line(Meta), {function, TModule, TName, TArity}}, TCtx2}; translate_fn(Meta, Args, Guard, Body, Ctx) when is_tuple(Args), (is_list(Guard) orelse is_tuple(Guard)), is_list(Body) -> {Clause, TCtx} = translate_fn_clause(Meta, Args, Guard, Body, Ctx), {{'fun', ?line(Meta), {clauses, [Clause]}}, TCtx}. translate_fn(Meta, {identifier, _, Name} = Id, Args, Guard, Body, Ctx) when is_tuple(Args), (is_list(Guard) orelse is_tuple(Guard)), is_list(Body) -> Ctx1 = kapok_ctx:push_scope(Ctx), {_, TCtx1} = translate_def_arg(Id, Ctx1), {Clause, TCtx2} = translate_fn_clause(Meta, Args, Guard, Body, TCtx1), TCtx3 = kapok_ctx:pop_scope(TCtx2), {{'named_fun', ?line(Meta), Name, [Clause]}, TCtx3}. translate_fn_exprs(Exprs, Ctx) when is_list(Exprs) -> check_fn_exprs(Exprs, Ctx), lists:mapfoldl(fun translate_fn_expr/2, Ctx, Exprs). translate_fn_expr({list, Meta, [{literal_list, _, _} = Args, {list, _, [{keyword_when, _, _} | _]} = Guard | Body]}, Ctx) -> translate_fn_clause(Meta, Args, Guard, Body, Ctx); translate_fn_expr({list, Meta, [{literal_list, _, _} = Args | Body]}, Ctx) -> translate_fn_clause(Meta, Args, [], Body, Ctx); translate_fn_expr(Ast, Ctx) -> Error = {invalid_fn_expression, {Ast}}, kapok_error:form_error(token_meta(Ast), ?m(Ctx, file), ?MODULE, Error). translate_fn_clause(Meta, Args, Guard, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TArgs, TCtx1} = translate_def_args(Args, Ctx1), {TGuard, TCtx2} = translate_guard(Guard, TCtx1), {TBody, TCtx3} = translate_body(Meta, Body, TCtx2), Clause = {clause, ?line(Meta), TArgs, TGuard, TBody}, TCtx4 = kapok_ctx:pop_scope(TCtx3), {Clause, TCtx4}. check_fn_exprs(Exprs, Ctx) when is_list(Exprs) -> lists:foldl(fun check_fn_expr_arity/2, {0, Ctx}, Exprs). check_fn_expr_arity({list, Meta, [{literal_list, _, List} | _]}, {Last, Ctx}) -> Arity = length(List), case Last of 0 -> {Arity, Ctx}; Arity -> {Arity, Ctx}; _ -> Error = {fn_clause_arity_mismatch, {Arity, Last}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error) end. translate_send(Meta, Pid, Message, Ctx) -> {TPid, TCtx} = translate(Pid, Ctx), {TMessage, TCtx1} = translate(Message, TCtx), {{op, ?line(Meta), '!', TPid, TMessage}, TCtx1}. translate_receive(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_receive_expr}); translate_receive(Meta, Clauses, Ctx) -> {Result, TCtx} = translate_receive(Meta, Clauses, [], Ctx), case Result of {TClauses, TExpr, TBody} when is_list(TClauses) -> {{'receive', ?line(Meta), TClauses, TExpr, TBody}, TCtx}; TClauses when is_list(TClauses) -> {{'receive', ?line(Meta), TClauses}, TCtx} end. translate_receive(_Meta, [], Acc, Ctx) -> {lists:reverse(Acc), Ctx}; translate_receive(Meta, [H], Acc, Ctx) -> case H of {list, Meta1, [{identifier, _, 'after'}, Expr | Body]} -> {TExpr, TCtx} = translate(Expr, Ctx), {TBody, TCtx1} = translate_body(Meta1, Body, TCtx), {{lists:reverse(Acc), TExpr, TBody}, TCtx1}; _ -> {TClause, TCtx} = translate_case_clause(H, Ctx), translate_receive(Meta, [], [TClause | Acc], TCtx) end; translate_receive(Meta, [H|T], Acc, Ctx) -> case H of {list, Meta1, [{identifier, _, 'after'}, _Expr | _Body]} -> kapok_error:form_error(Meta1, ?m(Ctx, file), ?MODULE, {after_clause_not_the_last}); _ -> {TClause, TCtx} = translate_case_clause(H, Ctx), translate_receive(Meta, T, [TClause | Acc], TCtx) end. translate_try(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_try_expr}); translate_try(Meta, [Expr|Left], Ctx) -> {TExpr, TCtx} = translate(Expr, Ctx), {CaseClauses, CatchClauses, AfterBody, TCtx1} = translate_try_body(Meta, Left, TCtx), {{'try', ?line(Meta), [TExpr], CaseClauses, CatchClauses, AfterBody}, TCtx1}. translate_try_body(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {try_without_body}); translate_try_body(Meta, [{list, _, [{list, _, _} | _] = Clauses} | Left], Ctx) -> {TClauses, TCtx} = lists:mapfoldl(fun translate_case_clause/2, Ctx, Clauses), {TCatchClauses, AfterBody, TCtx1} = translate_try_catch_after(Meta, Left, TCtx), {TClauses, TCatchClauses, AfterBody, TCtx1}; translate_try_body(Meta, Left, Ctx) -> {TCatchClauses, AfterBody, TCtx1} = translate_try_catch_after(Meta, Left, Ctx), {[], TCatchClauses, AfterBody, TCtx1}. translate_try_catch_after(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {try_without_catch_or_after}); translate_try_catch_after(_Meta, [{list, Meta1, [{identifier, _, 'catch'} | CatchClauses]}], Ctx) -> {TCatchClauses, TCtx} = translate_catch_clauses(Meta1, CatchClauses, Ctx), {TCatchClauses, [], TCtx}; translate_try_catch_after(_Meta, [{list, Meta1, [{identifier, _, 'after'} | Body]}], Ctx) -> {TBody, TCtx} = translate_body(Meta1, Body, Ctx), {[], TBody, TCtx}; translate_try_catch_after(_Meta, [{list, Meta1, [{identifier, _, 'catch'} | CatchClauses]}, {list, Meta2, [{identifier, _, 'after'} | Body]}], Ctx) -> {TCatchClauses, TCtx} = translate_catch_clauses(Meta1, CatchClauses, Ctx), {TBody, TCtx1} = translate_body(Meta2, Body, TCtx), {TCatchClauses, TBody, TCtx1}; translate_try_catch_after(Meta, Exprs, Ctx) -> Error = {invalid_catch_after_clause, {Exprs}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error). translate_catch_clauses(Meta, [], Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {no_catch_clause}); translate_catch_clauses(_Meta, Clauses, Ctx) -> lists:mapfoldl(fun translate_catch_clause/2, Ctx, Clauses). translate_catch_clause({list, Meta, []}, Ctx) -> kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, {empty_catch_clause}); translate_catch_clause({list, Meta, [E]}, Ctx) -> Error = {missing_catch_clause_body, {E}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error); translate_catch_clause({list, Meta, [E, {list, _, [{keyword_when, _, _} | _]} = Guard | Body]}, Ctx) -> translate_catch_clause(Meta, E, Guard, Body, Ctx); translate_catch_clause({list, Meta, [E | B]}, Ctx) -> translate_catch_clause(Meta, E, [], B, Ctx); translate_catch_clause({C, Meta, _} = Ast, Ctx) when C /= list -> Error = {invalid_catch_clause, {Ast}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error). translate_catch_clause(Meta, Exception, Guard, Body, Ctx) -> Ctx1 = kapok_ctx:push_scope(Ctx), {TException, TCtx1} = translate_exception(Exception, Ctx1), {TGuard, TCtx2} = translate_guard(Guard, TCtx1), {TBody, TCtx3} = translate_body(Meta, Body, TCtx2), TCtx4 = kapok_ctx:pop_scope(TCtx3), {{clause, ?line(Meta), [TException], TGuard, TBody}, TCtx4}. translate_exception({list, Meta, [{Category, _, Atom} = Kind, Pattern]}, Ctx) when Category == keyword; Category == atom -> case lists:any(fun(X) -> Atom == X end, ['throw', 'exit', 'error']) of false -> Error = {invalid_exception_type, {Atom}}, kapok_error:form_error(Meta, ?m(Ctx, file), ?MODULE, Error); true -> ok end, {TKind, TCtx} = translate(Kind, Ctx), {TPattern, TCtx1} = translate_case_pattern(Pattern, TCtx), Line = ?line(Meta), {{tuple, Line, [TKind, TPattern, {var, Line, '_'}]}, TCtx1}; translate_exception({list, Meta, [Kind, Pattern]}, Ctx) -> {TKind, TCtx} = translate_case_pattern(Kind, Ctx), {TPattern, TCtx1} = translate_case_pattern(Pattern, TCtx), Line = ?line(Meta), {{tuple, Line, [TKind, TPattern, {var, Line, '_'}]}, TCtx1}; translate_exception(Pattern, Ctx) -> {TPattern, TCtx} = translate_case_pattern(Pattern, Ctx), Line = ?line(token_meta(Pattern)), {{tuple, Line, [{atom, Line, 'throw'}, TPattern, {var, Line, '_'}]}, TCtx}. format_error({let_odd_forms, {Form}}) -> io_lib:format("let requires an even number of forms in binding, unpaired form: ~p~n", [Form]); format_error({empty_case_clause}) -> io_lib:format("case clause is empty"); format_error({missing_case_clause_body}) -> io_lib:format("case clause body is missing"); format_error({invalid_case_clause, {Ast}}) -> io_lib:format("invalid case clause ~w", [Ast]); format_error({invalid_fn_expression, {Expr}}) -> io_lib:format("invalid fn expression ~w", [Expr]); format_error({fn_clause_arity_mismatch, {Arity, Last}}) -> io_lib:format("fn clause arity ~B mismatch with last clause arity ~B~n", [Arity, Last]); format_error({empty_receive_expr}) -> io_lib:format("empty receive expression", []); format_error({after_clause_not_the_last}) -> io_lib:format("after clause should be the last expression of receive or try catch", []); format_error({empty_try_expr}) -> io_lib:format("empty try expression", []); format_error({try_without_body}) -> io_lib:format("try expression without body", []); format_error({try_without_catch_or_after}) -> io_lib:format("try expression without catch or after clause", []); format_error({invalid_catch_after_clause, {Exprs}}) -> io_lib:format("invalid catch and after clause in try: ~w", [Exprs]); format_error({empty_catch_clause}) -> io_lib:format("catch clause is empty", []); format_error({missing_catch_clause_body}) -> io_lib:format("catch clause body is missing", []); format_error({invalid_catch_clause, {Ast}}) -> io_lib:format("invalid catch clause: ~w", [Ast]); format_error({invalid_exception_type, {Type}}) -> io_lib:format("invalid exception type: ~p", [Type]).
1ca3d0b56b3b2a3fa507c382242d4c45a34baa3310add3e7b95cac414fe14512
metabase/metabase
last_edit.clj
(ns metabase.models.revision.last-edit "A namespace to handle getting the last edited information about items that satisfy the revision system. The revision system is a 'reversion' system, built to easily revert to previous states and can compute on demand a changelog. The revision system works through events and so when editing something, you should construct the last-edit-info yourself (using `edit-information-for-user`) rather looking at the revision table which might not be updated yet. This constructs `:last-edit-info`, a map with keys `:timestamp`, `:id`, `:first_name`, `:last_name`, and `:email`. It is not a full User object (missing some superuser metadata, last login time, and a common name). This was done to prevent another db call and hooking up timestamps to users but this can be added if preferred." (:require [clj-time.core :as time] [clojure.set :as set] [medley.core :as m] [metabase.db.query :as mdb.query] [metabase.util.schema :as su] [schema.core :as s])) (def ^:private model->db-model {:card "Card" :dashboard "Dashboard"}) ;; these are all maybes as sometimes revisions don't exist, or users might be missing the names, etc (def LastEditInfo "Schema of the `:last-edit-info` map. A subset of a user with a timestamp indicating when the last edit was." {:timestamp (s/maybe s/Any) :id (s/maybe su/IntGreaterThanZero) :first_name (s/maybe s/Str) :last_name (s/maybe s/Str) :email (s/maybe s/Str)}) (def MaybeAnnotated "Spec for an item annotated with last-edit-info. Items are cards or dashboards. Optional because we may not always have revision history for all cards/dashboards." {(s/optional-key :last-edit-info) LastEditInfo s/Any s/Any}) (s/defn with-last-edit-info :- MaybeAnnotated "Add the last edited information to a card. Will add a key `:last-edit-info`. Model should be one of `:dashboard` or `:card`. Gets the last edited information from the revisions table. If you need this information from a put route, use `@api/*current-user*` and a current timestamp since revisions are events and asynchronous." [{:keys [id] :as item} model :- (s/enum :dashboard :card)] (if-let [[updated-info] (seq (mdb.query/query {:select [:u.id :u.email :u.first_name :u.last_name :r.timestamp] :from [[:revision :r]] :left-join [[:core_user :u] [:= :u.id :r.user_id]] :where [:and [:= :r.model (model->db-model model)] [:= :r.model_id id]] :order-by [[:r.id :desc]] :limit 1}))] (assoc item :last-edit-info updated-info) item)) (s/defn edit-information-for-user :- LastEditInfo "Construct the `:last-edit-info` map given a user. Useful for editing routes. Most edit info information comes from the revisions table. But this table is populated from events asynchronously so when editing and wanting last-edit-info, you must construct it from `@api/*current-user*` and the current timestamp rather than checking the revisions table as those revisions may not be present yet." [user] (merge {:timestamp (time/now)} (select-keys user [:id :first_name :last_name :email]))) (def CollectionLastEditInfo "Schema for the map of bulk last-item-info. A map of two keys, `:card` and `:dashboard`, each of which is a map from id to a LastEditInfo." {(s/optional-key :card) {s/Int LastEditInfo} (s/optional-key :dashboard) {s/Int LastEditInfo}}) (s/defn fetch-last-edited-info :- (s/maybe CollectionLastEditInfo) "Fetch edited info from the revisions table. Revision information is timestamp, user id, email, first and last name. Takes card-ids and dashboard-ids and returns a map structured like {:card {model_id {:id :email :first_name :last_name :timestamp}} :dashboard {model_id {:id :email :first_name :last_name :timestamp}}}" [{:keys [card-ids dashboard-ids]}] (when (seq (concat card-ids dashboard-ids)) [: in : [ ] ] generates bad sql so need to conditionally add it (let [where-clause (into [:or] (keep (fn [[model-name ids]] (when (seq ids) [:and [:= :model model-name] [:in :model_id ids]]))) [["Card" card-ids] ["Dashboard" dashboard-ids]]) latest-changes (mdb.query/query {:select [:u.id :u.email :u.first_name :u.last_name :r.model :r.model_id :r.timestamp] :from [[:revision :r]] :left-join [[:core_user :u] [:= :u.id :r.user_id]] :where [:in :r.id subselect for the revision i d for each item {:select [[:%max.id :latest-revision-id]] :from [:revision] :where where-clause :group-by [:model :model_id]}]})] (->> latest-changes (group-by :model) (m/map-vals (fn [model-changes] (into {} (map (juxt :model_id #(dissoc % :model :model_id))) model-changes))) ;; keys are "Card" and "Dashboard" (model in revision table) back to keywords (m/map-keys (set/map-invert model->db-model))))))
null
https://raw.githubusercontent.com/metabase/metabase/2cd0bb399bb9c4d1ed2b8de0c5fd05cb499aa02b/src/metabase/models/revision/last_edit.clj
clojure
these are all maybes as sometimes revisions don't exist, or users might be missing the names, etc keys are "Card" and "Dashboard" (model in revision table) back to keywords
(ns metabase.models.revision.last-edit "A namespace to handle getting the last edited information about items that satisfy the revision system. The revision system is a 'reversion' system, built to easily revert to previous states and can compute on demand a changelog. The revision system works through events and so when editing something, you should construct the last-edit-info yourself (using `edit-information-for-user`) rather looking at the revision table which might not be updated yet. This constructs `:last-edit-info`, a map with keys `:timestamp`, `:id`, `:first_name`, `:last_name`, and `:email`. It is not a full User object (missing some superuser metadata, last login time, and a common name). This was done to prevent another db call and hooking up timestamps to users but this can be added if preferred." (:require [clj-time.core :as time] [clojure.set :as set] [medley.core :as m] [metabase.db.query :as mdb.query] [metabase.util.schema :as su] [schema.core :as s])) (def ^:private model->db-model {:card "Card" :dashboard "Dashboard"}) (def LastEditInfo "Schema of the `:last-edit-info` map. A subset of a user with a timestamp indicating when the last edit was." {:timestamp (s/maybe s/Any) :id (s/maybe su/IntGreaterThanZero) :first_name (s/maybe s/Str) :last_name (s/maybe s/Str) :email (s/maybe s/Str)}) (def MaybeAnnotated "Spec for an item annotated with last-edit-info. Items are cards or dashboards. Optional because we may not always have revision history for all cards/dashboards." {(s/optional-key :last-edit-info) LastEditInfo s/Any s/Any}) (s/defn with-last-edit-info :- MaybeAnnotated "Add the last edited information to a card. Will add a key `:last-edit-info`. Model should be one of `:dashboard` or `:card`. Gets the last edited information from the revisions table. If you need this information from a put route, use `@api/*current-user*` and a current timestamp since revisions are events and asynchronous." [{:keys [id] :as item} model :- (s/enum :dashboard :card)] (if-let [[updated-info] (seq (mdb.query/query {:select [:u.id :u.email :u.first_name :u.last_name :r.timestamp] :from [[:revision :r]] :left-join [[:core_user :u] [:= :u.id :r.user_id]] :where [:and [:= :r.model (model->db-model model)] [:= :r.model_id id]] :order-by [[:r.id :desc]] :limit 1}))] (assoc item :last-edit-info updated-info) item)) (s/defn edit-information-for-user :- LastEditInfo "Construct the `:last-edit-info` map given a user. Useful for editing routes. Most edit info information comes from the revisions table. But this table is populated from events asynchronously so when editing and wanting last-edit-info, you must construct it from `@api/*current-user*` and the current timestamp rather than checking the revisions table as those revisions may not be present yet." [user] (merge {:timestamp (time/now)} (select-keys user [:id :first_name :last_name :email]))) (def CollectionLastEditInfo "Schema for the map of bulk last-item-info. A map of two keys, `:card` and `:dashboard`, each of which is a map from id to a LastEditInfo." {(s/optional-key :card) {s/Int LastEditInfo} (s/optional-key :dashboard) {s/Int LastEditInfo}}) (s/defn fetch-last-edited-info :- (s/maybe CollectionLastEditInfo) "Fetch edited info from the revisions table. Revision information is timestamp, user id, email, first and last name. Takes card-ids and dashboard-ids and returns a map structured like {:card {model_id {:id :email :first_name :last_name :timestamp}} :dashboard {model_id {:id :email :first_name :last_name :timestamp}}}" [{:keys [card-ids dashboard-ids]}] (when (seq (concat card-ids dashboard-ids)) [: in : [ ] ] generates bad sql so need to conditionally add it (let [where-clause (into [:or] (keep (fn [[model-name ids]] (when (seq ids) [:and [:= :model model-name] [:in :model_id ids]]))) [["Card" card-ids] ["Dashboard" dashboard-ids]]) latest-changes (mdb.query/query {:select [:u.id :u.email :u.first_name :u.last_name :r.model :r.model_id :r.timestamp] :from [[:revision :r]] :left-join [[:core_user :u] [:= :u.id :r.user_id]] :where [:in :r.id subselect for the revision i d for each item {:select [[:%max.id :latest-revision-id]] :from [:revision] :where where-clause :group-by [:model :model_id]}]})] (->> latest-changes (group-by :model) (m/map-vals (fn [model-changes] (into {} (map (juxt :model_id #(dissoc % :model :model_id))) model-changes))) (m/map-keys (set/map-invert model->db-model))))))
3f0698848e5639a1d0f9bf6a801241a343ea27067b285935d8a84aebebb57e69
tsikov/clerk
clerk.lisp
(in-package #:cl-user) (defpackage #:clerk (:use #:cl) (:export #:*jobs* #:empty-jobs-queue #:job #:job-fn #:start #:stop #:calendar)) (in-package #:clerk) (defparameter *jobs* nil "All scheduled jobs") (defparameter *main-thread* nil) (defclass job () ((name :initarg :name :reader name) (interval :initarg :interval :reader interval) (fire-time :initarg :fire-time :accessor fire-time) (body :initarg :body :reader body))) (defclass continuous-job (job) ()) (defclass one-time-job (job) ()) (defmethod initialize-instance :after ((job job) &key) (let ((fire-time (clerk.time:timejump (get-universal-time) (interval job)))) (setf (fire-time job) fire-time))) (defun continuous-p (type) "Only interval declared with `every` are considered continuous" string= will do package agnostic symbol comparison (string= type 'every)) (defun make-job (name type interval body) (let ((job-class (if (continuous-p type) 'continuous-job 'one-time-job))) (make-instance job-class :name name :interval interval :body body))) (defmacro job (name type interval body) `(add-to-jobs-queue ,name ',type ',interval (lambda () ,body))) (defun job-fn (name type interval fn) (add-to-jobs-queue name type interval fn)) (defun add-to-jobs-queue (name type interval fn) (let ((job (make-job name type interval fn))) (push job *jobs*) (sort *jobs* #'< :key #'fire-time) job)) (defun empty-jobs-queue () (setf *jobs* nil)) (defun fire-job-p (job) "Check if it is time to fire a job" (<= (fire-time job) (get-universal-time))) (defmethod fire-job ((job job)) (bt:make-thread (body job) :name (name job))) (defmethod fire-job :before ((job continuous-job)) "Create the next job in the job queue when firing continuous jobs." (with-slots (name interval body) job (add-to-jobs-queue name 'every interval body))) (defun fire-job-if-needed () (if (fire-job-p (car *jobs*)) (progn (fire-job (pop *jobs*)) just in case the second job in queue is the same second as the first one . Or there might be a lot of ;; jobs in the queue. (fire-job-if-needed)))) (defun start () "Start the thread that waits for a jobs to fire." (setf *main-thread* (bt:make-thread #'(lambda () (loop (fire-job-if-needed) (sleep 1))) :name "Main scheduler thread."))) (defun stop () "Stop scheduler" (bt:destroy-thread *main-thread*) (setf *main-thread* nil)) (defun calendar (&optional (stream *standard-output*)) "Print the scheduled jobs" (format stream "JOBS:~%") (loop for job in *jobs* do (with-slots (name interval fire-time) job (format stream "~A - ~A - ~A~%" name interval fire-time))))
null
https://raw.githubusercontent.com/tsikov/clerk/96eef1ec4ea6ae7144a4e13be8d5fdbc00ced29d/src/clerk.lisp
lisp
jobs in the queue.
(in-package #:cl-user) (defpackage #:clerk (:use #:cl) (:export #:*jobs* #:empty-jobs-queue #:job #:job-fn #:start #:stop #:calendar)) (in-package #:clerk) (defparameter *jobs* nil "All scheduled jobs") (defparameter *main-thread* nil) (defclass job () ((name :initarg :name :reader name) (interval :initarg :interval :reader interval) (fire-time :initarg :fire-time :accessor fire-time) (body :initarg :body :reader body))) (defclass continuous-job (job) ()) (defclass one-time-job (job) ()) (defmethod initialize-instance :after ((job job) &key) (let ((fire-time (clerk.time:timejump (get-universal-time) (interval job)))) (setf (fire-time job) fire-time))) (defun continuous-p (type) "Only interval declared with `every` are considered continuous" string= will do package agnostic symbol comparison (string= type 'every)) (defun make-job (name type interval body) (let ((job-class (if (continuous-p type) 'continuous-job 'one-time-job))) (make-instance job-class :name name :interval interval :body body))) (defmacro job (name type interval body) `(add-to-jobs-queue ,name ',type ',interval (lambda () ,body))) (defun job-fn (name type interval fn) (add-to-jobs-queue name type interval fn)) (defun add-to-jobs-queue (name type interval fn) (let ((job (make-job name type interval fn))) (push job *jobs*) (sort *jobs* #'< :key #'fire-time) job)) (defun empty-jobs-queue () (setf *jobs* nil)) (defun fire-job-p (job) "Check if it is time to fire a job" (<= (fire-time job) (get-universal-time))) (defmethod fire-job ((job job)) (bt:make-thread (body job) :name (name job))) (defmethod fire-job :before ((job continuous-job)) "Create the next job in the job queue when firing continuous jobs." (with-slots (name interval body) job (add-to-jobs-queue name 'every interval body))) (defun fire-job-if-needed () (if (fire-job-p (car *jobs*)) (progn (fire-job (pop *jobs*)) just in case the second job in queue is the same second as the first one . Or there might be a lot of (fire-job-if-needed)))) (defun start () "Start the thread that waits for a jobs to fire." (setf *main-thread* (bt:make-thread #'(lambda () (loop (fire-job-if-needed) (sleep 1))) :name "Main scheduler thread."))) (defun stop () "Stop scheduler" (bt:destroy-thread *main-thread*) (setf *main-thread* nil)) (defun calendar (&optional (stream *standard-output*)) "Print the scheduled jobs" (format stream "JOBS:~%") (loop for job in *jobs* do (with-slots (name interval fire-time) job (format stream "~A - ~A - ~A~%" name interval fire-time))))
8a821855bdd276e93b7e7d8657d75a74d7a2aa0f431181f82d2a1b291f2165c7
RBornat/jape
alert.mli
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jape 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 jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) type alertspec = Alert of (string * (string * alertspec option) list * int) | HowToFormulaSelect | HowToTextSelect | HowToDragFormulae | HowToDragDisproofStuff type alertseverity = Info | Warning | Error | Question val ask : alertseverity -> string -> (string * 'a) list -> int -> 'a message buttons actions defaultindex result val askCancel : alertseverity -> string -> (string * 'a) list -> 'a -> int -> 'a message buttons actions cancelaction defaultindex result * ( set defaultindex = buttons to choose Cancel ) * (set defaultindex = List.length buttons to choose Cancel) *) val askDangerously : string -> string * 'a -> string * 'a -> 'a -> 'a message Do Do n't Cancel Result * * special version of askCancel , with Do as default , and * the buttons in " Do / Don't " positions -- like this * * ICON * ICON message * ICON * * Do n't Cancel Do * * special version of askCancel, with Do as default, and * the buttons in "Do/Don't" positions -- like this * * ICON * ICON message * ICON * * Don't Cancel Do *) val askChoice : string * string list list -> int option val defaultseverity : 'a list -> alertseverity val defaultseverity_alert : alertseverity val patchalert : string * alertspec -> unit val patchalertdebug : bool ref val resetalertpatches : unit -> unit val setComment : string -> unit (* this demoted to a thing which sets a comment line *) val showAlert : alertseverity -> string -> unit (* this just pops up a window *) val showHowTo : string -> unit
null
https://raw.githubusercontent.com/RBornat/jape/afe9f207e89e965636b43ef8fad38fd1f69737ae/distrib/camlengine/alert.mli
ocaml
this demoted to a thing which sets a comment line this just pops up a window
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jape 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 jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) type alertspec = Alert of (string * (string * alertspec option) list * int) | HowToFormulaSelect | HowToTextSelect | HowToDragFormulae | HowToDragDisproofStuff type alertseverity = Info | Warning | Error | Question val ask : alertseverity -> string -> (string * 'a) list -> int -> 'a message buttons actions defaultindex result val askCancel : alertseverity -> string -> (string * 'a) list -> 'a -> int -> 'a message buttons actions cancelaction defaultindex result * ( set defaultindex = buttons to choose Cancel ) * (set defaultindex = List.length buttons to choose Cancel) *) val askDangerously : string -> string * 'a -> string * 'a -> 'a -> 'a message Do Do n't Cancel Result * * special version of askCancel , with Do as default , and * the buttons in " Do / Don't " positions -- like this * * ICON * ICON message * ICON * * Do n't Cancel Do * * special version of askCancel, with Do as default, and * the buttons in "Do/Don't" positions -- like this * * ICON * ICON message * ICON * * Don't Cancel Do *) val askChoice : string * string list list -> int option val defaultseverity : 'a list -> alertseverity val defaultseverity_alert : alertseverity val patchalert : string * alertspec -> unit val patchalertdebug : bool ref val resetalertpatches : unit -> unit val showHowTo : string -> unit
fb353bc7d64029a4c1f70f895dd42f789851a05ea92b95e9659b645fb613b4b5
facebookarchive/pfff
token_helpers_css.ml
* * Copyright ( C ) 2011 Facebook * * This library is free software ; 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 , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2011 Facebook * * This library is free software; 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, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common open Parser_css module Ast = Ast_css module PI = Parse_info (*****************************************************************************) (* Token Helpers *) (*****************************************************************************) (*****************************************************************************) (* Visitors *) (*****************************************************************************) let visitor_info_of_tok f = function | TComment (ii) -> TComment (f ii) | S (ii) -> S (f ii) | CHARSET (ii) -> CHARSET (f ii) | IMPORT (ii) -> IMPORT (f ii) | MEDIA (ii) -> MEDIA (f ii) | PAGE (ii) -> PAGE (f ii) | FONTFACE (ii) -> FONTFACE (f ii) | OPEN_CURLY (ii) -> OPEN_CURLY (f ii) | CLOSE_CURLY (ii) -> CLOSE_CURLY (f ii) | OPEN_ROUND (ii) -> OPEN_ROUND (f ii) | CLOSE_ROUND (ii) -> CLOSE_ROUND (f ii) | OPEN_SQUARE (ii) -> OPEN_SQUARE (f ii) | CLOSE_SQUARE (ii) -> CLOSE_SQUARE (f ii) | SEMICOLON (ii) -> SEMICOLON (f ii) | COLON (ii) -> COLON (f ii) | DOUBLE_COLON (ii) -> DOUBLE_COLON (f ii) | COMMA (ii) -> COMMA (f ii) | PERIOD (ii) -> PERIOD (f ii) | SLASH (ii) -> SLASH (f ii) | ASTERISK (ii) -> ASTERISK (f ii) | QUOTIENT (ii) -> QUOTIENT (f ii) | PLUS (ii) -> PLUS (f ii) | MINUS (ii) -> MINUS (f ii) | TILDE (ii) -> TILDE (f ii) | GT (ii) -> GT (f ii) | IMPORTANT (ii) -> IMPORTANT (f ii) | ATTR_EQUALS (ii) -> ATTR_EQUALS (f ii) | ATTR_INCLUDES (ii) -> ATTR_INCLUDES (f ii) | ATTR_DASHMATCH (ii) -> ATTR_DASHMATCH (f ii) | ATTR_PREFIX (ii) -> ATTR_PREFIX (f ii) | ATTR_SUFFIX (ii) -> ATTR_SUFFIX (f ii) | ATTR_SUBSTRING (ii) -> ATTR_SUBSTRING (f ii) | URI (ii) -> URI (f ii) | TString (s, ii) -> TString (s, f ii) | IDENT (s, ii) -> IDENT (s, f ii) | NTH (s, ii) -> NTH (s, f ii) | HASH (s, ii) -> HASH (s, f ii) | VAR (s, ii) -> VAR (s, f ii) | SEL_FUNC (s, ii) -> SEL_FUNC (s, f ii) | TERM_FUNC (s, ii) -> TERM_FUNC (s, f ii) | QUANTITY (s, ii) -> QUANTITY (s, f ii) | TUnknown (ii) -> TUnknown (f ii) | EOF(ii) -> EOF(f ii) let info_of_tok tok = let res = ref None in visitor_info_of_tok (fun ii -> res := Some ii; ii) tok +> ignore; Common2.some !res (*****************************************************************************) Accessors (*****************************************************************************) let linecol_of_tok tok = let info = info_of_tok tok in PI.line_of_info info, PI.col_of_info info let line_of_tok x = fst (linecol_of_tok x) let str_of_tok x = PI.str_of_info (info_of_tok x) let file_of_tok x = PI.file_of_info (info_of_tok x) let pos_of_tok x = PI.pos_of_info (info_of_tok x)
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/lang_css/parsing/token_helpers_css.ml
ocaml
*************************************************************************** Token Helpers *************************************************************************** *************************************************************************** Visitors *************************************************************************** *************************************************************************** ***************************************************************************
* * Copyright ( C ) 2011 Facebook * * This library is free software ; 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 , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2011 Facebook * * This library is free software; 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, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common open Parser_css module Ast = Ast_css module PI = Parse_info let visitor_info_of_tok f = function | TComment (ii) -> TComment (f ii) | S (ii) -> S (f ii) | CHARSET (ii) -> CHARSET (f ii) | IMPORT (ii) -> IMPORT (f ii) | MEDIA (ii) -> MEDIA (f ii) | PAGE (ii) -> PAGE (f ii) | FONTFACE (ii) -> FONTFACE (f ii) | OPEN_CURLY (ii) -> OPEN_CURLY (f ii) | CLOSE_CURLY (ii) -> CLOSE_CURLY (f ii) | OPEN_ROUND (ii) -> OPEN_ROUND (f ii) | CLOSE_ROUND (ii) -> CLOSE_ROUND (f ii) | OPEN_SQUARE (ii) -> OPEN_SQUARE (f ii) | CLOSE_SQUARE (ii) -> CLOSE_SQUARE (f ii) | SEMICOLON (ii) -> SEMICOLON (f ii) | COLON (ii) -> COLON (f ii) | DOUBLE_COLON (ii) -> DOUBLE_COLON (f ii) | COMMA (ii) -> COMMA (f ii) | PERIOD (ii) -> PERIOD (f ii) | SLASH (ii) -> SLASH (f ii) | ASTERISK (ii) -> ASTERISK (f ii) | QUOTIENT (ii) -> QUOTIENT (f ii) | PLUS (ii) -> PLUS (f ii) | MINUS (ii) -> MINUS (f ii) | TILDE (ii) -> TILDE (f ii) | GT (ii) -> GT (f ii) | IMPORTANT (ii) -> IMPORTANT (f ii) | ATTR_EQUALS (ii) -> ATTR_EQUALS (f ii) | ATTR_INCLUDES (ii) -> ATTR_INCLUDES (f ii) | ATTR_DASHMATCH (ii) -> ATTR_DASHMATCH (f ii) | ATTR_PREFIX (ii) -> ATTR_PREFIX (f ii) | ATTR_SUFFIX (ii) -> ATTR_SUFFIX (f ii) | ATTR_SUBSTRING (ii) -> ATTR_SUBSTRING (f ii) | URI (ii) -> URI (f ii) | TString (s, ii) -> TString (s, f ii) | IDENT (s, ii) -> IDENT (s, f ii) | NTH (s, ii) -> NTH (s, f ii) | HASH (s, ii) -> HASH (s, f ii) | VAR (s, ii) -> VAR (s, f ii) | SEL_FUNC (s, ii) -> SEL_FUNC (s, f ii) | TERM_FUNC (s, ii) -> TERM_FUNC (s, f ii) | QUANTITY (s, ii) -> QUANTITY (s, f ii) | TUnknown (ii) -> TUnknown (f ii) | EOF(ii) -> EOF(f ii) let info_of_tok tok = let res = ref None in visitor_info_of_tok (fun ii -> res := Some ii; ii) tok +> ignore; Common2.some !res Accessors let linecol_of_tok tok = let info = info_of_tok tok in PI.line_of_info info, PI.col_of_info info let line_of_tok x = fst (linecol_of_tok x) let str_of_tok x = PI.str_of_info (info_of_tok x) let file_of_tok x = PI.file_of_info (info_of_tok x) let pos_of_tok x = PI.pos_of_info (info_of_tok x)
87c3106d7fb8b36f1611c8146fdcf91f7eac796b80e729d34b214a2591d783ac
khasm-lang/khasmc
process.ml
open Args let rec normalise files = match files with | [] -> [] | x :: xs -> ( try (Filename.basename x |> Filename.chop_extension |> Batteries.String.capitalize) :: normalise xs with _ -> Batteries.String.capitalize x :: normalise xs) let compile names asts args = print_endline ""; if args.dump_ast1 then asts |> List.iter (fun x -> print_endline (Ast.show_program x)) else (); let asts' = asts |> List.map Complexity.init_program |> List.map2 Modules.wrap_in names |> List.rev |> Elim_modules.elim in if args.dump_ast2 then asts' |> List.iter (fun x -> print_endline (Ast.show_program x)) else (); (*typcheck stage*) asts' |> List.map Typelam_init.init_program |> Typecheck.typecheck_program_list; codegen stage let kir = asts' |> Translateftm.front_to_middle in if args.dump_ast3 then print_endline (Kir.show_kirprog kir) else (); let kir' = kir |> Lamlift.lambda_lift in if args.dump_ast3 then print_endline (Kir.show_kirprog kir') else (); "done"
null
https://raw.githubusercontent.com/khasm-lang/khasmc/e190cad60ba66e701ad0ae9d288ddb9a55e63a12/lib/process.ml
ocaml
typcheck stage
open Args let rec normalise files = match files with | [] -> [] | x :: xs -> ( try (Filename.basename x |> Filename.chop_extension |> Batteries.String.capitalize) :: normalise xs with _ -> Batteries.String.capitalize x :: normalise xs) let compile names asts args = print_endline ""; if args.dump_ast1 then asts |> List.iter (fun x -> print_endline (Ast.show_program x)) else (); let asts' = asts |> List.map Complexity.init_program |> List.map2 Modules.wrap_in names |> List.rev |> Elim_modules.elim in if args.dump_ast2 then asts' |> List.iter (fun x -> print_endline (Ast.show_program x)) else (); asts' |> List.map Typelam_init.init_program |> Typecheck.typecheck_program_list; codegen stage let kir = asts' |> Translateftm.front_to_middle in if args.dump_ast3 then print_endline (Kir.show_kirprog kir) else (); let kir' = kir |> Lamlift.lambda_lift in if args.dump_ast3 then print_endline (Kir.show_kirprog kir') else (); "done"
50b8e03ea2e5747860f1b5d61627b6c7555adfea8af2d9019f1c2a24bdf39770
xvw/muhokama
category_services.ml
open Lib_common open Lib_service open Util open Middlewares let topics_count_by_categories = Service.failable_with ~:Endpoints.Category.list [ user_authenticated ] ~attached:user_required (fun user request -> let open Lwt_util in let+? count_topics_by_categories = Dream.sql request @@ Models.Topic.count_by_categories in user, count_topics_by_categories) ~succeed:(fun (user, count_topics_by_categories) request -> let flash_info = Util.Flash_info.fetch request in let view = Views.Category.by_topics_count ?flash_info ~user count_topics_by_categories in Dream.html @@ from_tyxml view) ~failure:(fun err request -> Flash_info.error_tree request err; redirect_to ~:Endpoints.Global.root request) ;;
null
https://raw.githubusercontent.com/xvw/muhokama/dcfa488169677ff7f1a3ed71182524aeb0b13c53/app/services/category_services.ml
ocaml
open Lib_common open Lib_service open Util open Middlewares let topics_count_by_categories = Service.failable_with ~:Endpoints.Category.list [ user_authenticated ] ~attached:user_required (fun user request -> let open Lwt_util in let+? count_topics_by_categories = Dream.sql request @@ Models.Topic.count_by_categories in user, count_topics_by_categories) ~succeed:(fun (user, count_topics_by_categories) request -> let flash_info = Util.Flash_info.fetch request in let view = Views.Category.by_topics_count ?flash_info ~user count_topics_by_categories in Dream.html @@ from_tyxml view) ~failure:(fun err request -> Flash_info.error_tree request err; redirect_to ~:Endpoints.Global.root request) ;;
ec7b8ffc6d572b1244b8696c394678599c8f8139809d1ef8c431aeafec138a38
clojure-interop/google-cloud-clients
RpcBatch$Callback.clj
(ns com.google.cloud.storage.spi.v1.RpcBatch$Callback "An interface for batch callbacks." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.storage.spi.v1 RpcBatch$Callback])) (defn on-success "This method will be called upon success of the batch operation. response - `T`" ([^RpcBatch$Callback this response] (-> this (.onSuccess response)))) (defn on-failure "This method will be called upon failure of the batch operation. google-json-error - `com.google.api.client.googleapis.json.GoogleJsonError`" ([^RpcBatch$Callback this ^com.google.api.client.googleapis.json.GoogleJsonError google-json-error] (-> this (.onFailure google-json-error))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.storage/src/com/google/cloud/storage/spi/v1/RpcBatch%24Callback.clj
clojure
(ns com.google.cloud.storage.spi.v1.RpcBatch$Callback "An interface for batch callbacks." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.storage.spi.v1 RpcBatch$Callback])) (defn on-success "This method will be called upon success of the batch operation. response - `T`" ([^RpcBatch$Callback this response] (-> this (.onSuccess response)))) (defn on-failure "This method will be called upon failure of the batch operation. google-json-error - `com.google.api.client.googleapis.json.GoogleJsonError`" ([^RpcBatch$Callback this ^com.google.api.client.googleapis.json.GoogleJsonError google-json-error] (-> this (.onFailure google-json-error))))
b2d3814882fedadcef452a7480acb6b5920d52436e1d6755e6f6d770302557c6
ocaml-community/ISO8601.ml
ISO8601.mli
* { 2 ISO 8601 and RFC 3339 parsing and printing } * Version 0.2.5 module Permissive : sig (** {2 Date parsing} [date], [time] and [datetime] parse a [string] and return the corresponding timestamp (as [float]). Times are {b always} converted to UTC representation. For each of these functions, a [_lex] suffixed function read from a [Lexing.lexbuf] instead of a [string]. [datetime] functions also take an optional boolean [reqtime] indicating if parsing must fail if a date is given and not a complete datetime. (Default is true). Functions with [_tz] in their name return a [float * float option] representing [timestamp * offset option (timezone)]. [timestamp] will be the UTC time, and [offset option] is just an information about the original timezone. *) val date_lex : Lexing.lexbuf -> float val date : string -> float val time_tz_lex : Lexing.lexbuf -> (float * float option) val time_lex : Lexing.lexbuf -> float val time_tz : string -> (float * float option) val time : string -> float val datetime_tz_lex : ?reqtime:bool -> Lexing.lexbuf -> (float * float option) val datetime_lex : ?reqtime:bool -> Lexing.lexbuf -> float val datetime_tz : ?reqtime:bool -> string -> (float * float option) val datetime : ?reqtime:bool -> string -> float * { 2 Printing functions } { b NB : fractionnal part of timestamps will be lost when printing with current implementation . } {b NB: fractionnal part of timestamps will be lost when printing with current implementation.} *) * [ pp_format fmt format x tz ] [ x ] is the timestamp , and [ tz ] the time zone offset . The [ format ] string is a character string which contains two types of objects : plain characters , which are simply copied to [ fmt ] , and conversion specifications , each of which causes conversion and printing of ( a part of ) [ x ] or [ tz ] . { b If you do not want to use a timezone , set it to 0 . } Conversion specifications have the form [ % X ] , where X can be : - [ Y ] : Year - [ M ] : Month - [ D ] : Day - [ h ] : Hours - [ m ] : Minutes - [ s ] : Seconds - [ Z ] : Hours of [ tz ] offset ( with its sign ) - [ z ] : Minutes of [ tz ] offset ( without sign ) - [ % ] : The ' % ' character [x] is the timestamp, and [tz] the time zone offset. The [format] string is a character string which contains two types of objects: plain characters, which are simply copied to [fmt], and conversion specifications, each of which causes conversion and printing of (a part of) [x] or [tz]. {b If you do not want to use a timezone, set it to 0.} Conversion specifications have the form [%X], where X can be: - [Y]: Year - [M]: Month - [D]: Day - [h]: Hours - [m]: Minutes - [s]: Seconds - [Z]: Hours of [tz] offset (with its sign) - [z]: Minutes of [tz] offset (without sign) - [%]: The '%' character *) val pp_format : Format.formatter -> string -> float -> float -> unit (** "%Y-%M-%D" format. *) val pp_date : Format.formatter -> float -> unit val string_of_date : float -> string (** "%Y%M%D" format. *) val pp_date_basic : Format.formatter -> float -> unit val string_of_date_basic : float -> string (** "%h:%m:%s" format. *) val pp_time : Format.formatter -> float -> unit val string_of_time : float -> string (** "%h%m%s" format. *) val pp_time_basic : Format.formatter -> float -> unit val string_of_time_basic : float -> string (** "%Y-%M-%DT%h:%m:%s" format. *) val pp_datetime : Format.formatter -> float -> unit val string_of_datetime : float -> string * " % Y%M%DT%h%m%s " format . val pp_datetime_basic : Format.formatter -> float -> unit val string_of_datetime_basic : float -> string (** "%Y-%M-%DT%h:%m:%s%Z:%z" format. *) val pp_datetimezone : Format.formatter -> (float * float) -> unit val string_of_datetimezone : (float * float) -> string (** "%Y%M%DT%h%m%s%Z%z" format. *) val pp_datetimezone_basic : Format.formatter -> (float * float) -> unit val string_of_datetimezone_basic : (float * float) -> string end
null
https://raw.githubusercontent.com/ocaml-community/ISO8601.ml/4c6820de3098a5e0b00503b899456297706dc0a5/src/ISO8601.mli
ocaml
* {2 Date parsing} [date], [time] and [datetime] parse a [string] and return the corresponding timestamp (as [float]). Times are {b always} converted to UTC representation. For each of these functions, a [_lex] suffixed function read from a [Lexing.lexbuf] instead of a [string]. [datetime] functions also take an optional boolean [reqtime] indicating if parsing must fail if a date is given and not a complete datetime. (Default is true). Functions with [_tz] in their name return a [float * float option] representing [timestamp * offset option (timezone)]. [timestamp] will be the UTC time, and [offset option] is just an information about the original timezone. * "%Y-%M-%D" format. * "%Y%M%D" format. * "%h:%m:%s" format. * "%h%m%s" format. * "%Y-%M-%DT%h:%m:%s" format. * "%Y-%M-%DT%h:%m:%s%Z:%z" format. * "%Y%M%DT%h%m%s%Z%z" format.
* { 2 ISO 8601 and RFC 3339 parsing and printing } * Version 0.2.5 module Permissive : sig val date_lex : Lexing.lexbuf -> float val date : string -> float val time_tz_lex : Lexing.lexbuf -> (float * float option) val time_lex : Lexing.lexbuf -> float val time_tz : string -> (float * float option) val time : string -> float val datetime_tz_lex : ?reqtime:bool -> Lexing.lexbuf -> (float * float option) val datetime_lex : ?reqtime:bool -> Lexing.lexbuf -> float val datetime_tz : ?reqtime:bool -> string -> (float * float option) val datetime : ?reqtime:bool -> string -> float * { 2 Printing functions } { b NB : fractionnal part of timestamps will be lost when printing with current implementation . } {b NB: fractionnal part of timestamps will be lost when printing with current implementation.} *) * [ pp_format fmt format x tz ] [ x ] is the timestamp , and [ tz ] the time zone offset . The [ format ] string is a character string which contains two types of objects : plain characters , which are simply copied to [ fmt ] , and conversion specifications , each of which causes conversion and printing of ( a part of ) [ x ] or [ tz ] . { b If you do not want to use a timezone , set it to 0 . } Conversion specifications have the form [ % X ] , where X can be : - [ Y ] : Year - [ M ] : Month - [ D ] : Day - [ h ] : Hours - [ m ] : Minutes - [ s ] : Seconds - [ Z ] : Hours of [ tz ] offset ( with its sign ) - [ z ] : Minutes of [ tz ] offset ( without sign ) - [ % ] : The ' % ' character [x] is the timestamp, and [tz] the time zone offset. The [format] string is a character string which contains two types of objects: plain characters, which are simply copied to [fmt], and conversion specifications, each of which causes conversion and printing of (a part of) [x] or [tz]. {b If you do not want to use a timezone, set it to 0.} Conversion specifications have the form [%X], where X can be: - [Y]: Year - [M]: Month - [D]: Day - [h]: Hours - [m]: Minutes - [s]: Seconds - [Z]: Hours of [tz] offset (with its sign) - [z]: Minutes of [tz] offset (without sign) - [%]: The '%' character *) val pp_format : Format.formatter -> string -> float -> float -> unit val pp_date : Format.formatter -> float -> unit val string_of_date : float -> string val pp_date_basic : Format.formatter -> float -> unit val string_of_date_basic : float -> string val pp_time : Format.formatter -> float -> unit val string_of_time : float -> string val pp_time_basic : Format.formatter -> float -> unit val string_of_time_basic : float -> string val pp_datetime : Format.formatter -> float -> unit val string_of_datetime : float -> string * " % Y%M%DT%h%m%s " format . val pp_datetime_basic : Format.formatter -> float -> unit val string_of_datetime_basic : float -> string val pp_datetimezone : Format.formatter -> (float * float) -> unit val string_of_datetimezone : (float * float) -> string val pp_datetimezone_basic : Format.formatter -> (float * float) -> unit val string_of_datetimezone_basic : (float * float) -> string end
3860dd648bc89d4a79a5f306cd38344cc1ca7a92fb286719469ce58fcc591d71
CryptoKami/cryptokami-core
CLI.hs
# LANGUAGE ApplicativeDo # {-# LANGUAGE CPP #-} # LANGUAGE NamedFieldPuns # -- following Pos.Util.UserSecret #if !defined(mingw32_HOST_OS) #define POSIX #endif -- | Command line interface for specifying the network config module Pos.Network.CLI ( NetworkConfigOpts(..) , NetworkConfigException(..) , networkConfigOption , externalNetworkAddressOption , listenNetworkAddressOption , ipv4ToNetworkAddress , intNetworkConfigOpts -- * Exported primilary for testing , readTopology , readPolicies , fromPovOf ) where import Universum import Control.Concurrent import Control.Exception.Safe (try) import qualified Data.ByteString.Char8 as BS.C8 import Data.IP (IPv4) import qualified Data.Map.Strict as M import Data.Maybe (fromJust, mapMaybe) import qualified Data.Yaml as Yaml import Formatting (build, sformat, shown, (%)) import Mockable (Mockable, fork) import Mockable.Concurrent import Network.Broadcast.OutboundQueue (Alts, Peers, peersFromList) import qualified Network.DNS as DNS import qualified Network.Transport.TCP as TCP import qualified Options.Applicative as Opt import Serokell.Util.OptParse (fromParsec) import System.Wlog.CanLog (WithLogger, logError, logNotice) import qualified Pos.DHT.Real.Param as DHT (KademliaParams (..), MalformedDHTKey (..), fromYamlConfig) import Pos.Network.DnsDomains (DnsDomains (..), NodeAddr (..)) import Pos.Network.Types (NodeId, NodeName (..)) import qualified Pos.Network.Types as T import Pos.Network.Yaml (NodeMetadata (..)) import qualified Pos.Network.Yaml as Y import Pos.Util.TimeWarp (NetworkAddress, addrParser, addrParserNoWildcard, addressToNodeId) #ifdef POSIX import Pos.Util.SigHandler (Signal (..), installHandler) #endif ---------------------------------------------------------------------------- -- Command line arguments ---------------------------------------------------------------------------- data NetworkConfigOpts = NetworkConfigOpts { ncoTopology :: !(Maybe FilePath) ^ to .yaml file with the network topology , ncoKademlia :: !(Maybe FilePath) ^ Filepath to .yaml config of kademlia , ncoSelf :: !(Maybe NodeName) -- ^ Name of the current node , ncoPort :: !Word16 ^ Port number to use when translating IP addresses to NodeIds , ncoPolicies :: !(Maybe FilePath) -- DOCUMENT THIS FIELD , ncoBindAddress :: !(Maybe NetworkAddress) -- ^ A node may have a bind address which differs from its external -- address. , ncoExternalAddress :: !(Maybe NetworkAddress) -- ^ A node must be addressable on the network. } deriving (Show) ---------------------------------------------------------------------------- Parser ---------------------------------------------------------------------------- networkConfigOption :: Opt.Parser NetworkConfigOpts networkConfigOption = do ncoTopology <- optional $ Opt.strOption $ mconcat [ Opt.long "topology" , Opt.metavar "FILEPATH" , Opt.help "Path to a YAML file containing the network topology" ] ncoKademlia <- optional $ Opt.strOption $ mconcat [ Opt.long "kademlia" , Opt.metavar "FILEPATH" , Opt.help "Path to a YAML file containing the kademlia configuration" ] ncoSelf <- optional $ Opt.option (fromString <$> Opt.str) $ mconcat [ Opt.long "node-id" , Opt.metavar "NODE_ID" , Opt.help "Identifier for this node within the network" ] ncoPort <- Opt.option Opt.auto $ mconcat [ Opt.long "default-port" , Opt.metavar "PORT" , Opt.help "Port number for IP address to node ID translation" , Opt.value 3000 ] ncoPolicies <- Opt.optional $ Opt.strOption $ mconcat [ Opt.long "policies" , Opt.metavar "FILEPATH" , Opt.help "Path to a YAML file containing the network policies" ] ncoExternalAddress <- optional $ externalNetworkAddressOption Nothing ncoBindAddress <- optional $ listenNetworkAddressOption Nothing pure $ NetworkConfigOpts {..} externalNetworkAddressOption :: Maybe NetworkAddress -> Opt.Parser NetworkAddress externalNetworkAddressOption na = Opt.option (fromParsec addrParserNoWildcard) $ Opt.long "address" <> Opt.metavar "IP:PORT" <> Opt.help helpMsg <> Opt.showDefault <> maybe mempty Opt.value na where helpMsg = "IP and port of external address. " <> "Please make sure these IP and port (on which node is running) are accessible " <> "otherwise proper work of CSL isn't guaranteed. " <> "0.0.0.0 is not accepted as a valid host." listenNetworkAddressOption :: Maybe NetworkAddress -> Opt.Parser NetworkAddress listenNetworkAddressOption na = Opt.option (fromParsec addrParser) $ Opt.long "listen" <> Opt.metavar "IP:PORT" <> Opt.help helpMsg <> Opt.showDefault <> maybe mempty Opt.value na where helpMsg = "IP and port on which to bind and listen. Please make sure these IP " <> "and port are accessible, otherwise proper work of CSL isn't guaranteed." ---------------------------------------------------------------------------- -- Defaults ---------------------------------------------------------------------------- -- | The topology we assume when no topology file is specified defaultTopology :: Y.Topology defaultTopology = Y.TopologyBehindNAT { topologyValency = 1 , topologyFallbacks = 1 , topologyDnsDomains = defaultDnsDomains } | The default DNS domains used for relay discovery -- -- TODO: Give this a proper value defaultDnsDomains :: DnsDomains DNS.Domain defaultDnsDomains = DnsDomains [ [NodeAddrDNS "todo.defaultDnsDomain.com" Nothing] ] ---------------------------------------------------------------------------- -- Monitor for static peers ---------------------------------------------------------------------------- data MonitorEvent m = MonitorRegister (Peers NodeId -> m ()) | MonitorSIGHUP -- | Monitor for changes to the static config monitorStaticConfig :: forall m. ( WithLogger m , MonadIO m , Mockable Fork m , MonadCatch m ) => NetworkConfigOpts -> NodeMetadata -- ^ Original metadata (at startup) -> Peers NodeId -- ^ Initial value -> m T.StaticPeers monitorStaticConfig cfg@NetworkConfigOpts{..} origMetadata initPeers = do events :: Chan (MonitorEvent m) <- liftIO newChan #ifdef POSIX liftIO $ installHandler SigHUP $ writeChan events MonitorSIGHUP #endif _tid <- fork $ loop events initPeers [] return T.StaticPeers { T.staticPeersOnChange = writeChan events . MonitorRegister } where loop :: Chan (MonitorEvent m) -> Peers NodeId -> [Peers NodeId -> m ()] -> m () loop events peers handlers = liftIO (readChan events) >>= \case MonitorRegister handler -> do runHandler peers handler -- Call new handler with current value loop events peers (handler:handlers) MonitorSIGHUP -> do let fp = fromJust ncoTopology mParsedTopology <- try $ liftIO $ readTopology fp case mParsedTopology of Right (Y.TopologyStatic allPeers) -> do (newMetadata, newPeers, _) <- liftIO $ fromPovOf cfg allPeers unless (nmType newMetadata == nmType origMetadata) $ logError $ changedType fp unless (nmKademlia newMetadata == nmKademlia origMetadata) $ logError $ changedKademlia fp unless (nmMaxSubscrs newMetadata == nmMaxSubscrs origMetadata) $ logError $ changedMaxSubscrs fp mapM_ (runHandler newPeers) handlers logNotice $ sformat "SIGHUP: Re-read topology" loop events newPeers handlers Right _otherTopology -> do logError $ changedFormat fp loop events peers handlers Left ex -> do logError $ readFailed fp ex loop events peers handlers runHandler :: forall t . t -> (t -> m ()) -> m () runHandler it handler = do mu <- try (handler it) case mu of Left ex -> logError $ handlerError ex Right () -> return () changedFormat, changedType, changedKademlia :: FilePath -> Text changedFormat = sformat $ "SIGHUP ("%shown%"): Cannot dynamically change topology." changedType = sformat $ "SIGHUP ("%shown%"): Cannot dynamically change own node type." changedKademlia = sformat $ "SIGHUP ("%shown%"): Cannot dynamically start/stop Kademlia." changedMaxSubscrs = sformat $ "SIGHUP ("%shown%"): Cannot dynamically change maximum number of subscribers." readFailed :: FilePath -> SomeException -> Text readFailed = sformat $ "SIGHUP: Failed to read " % shown % ": " % shown % ". Ignored." handlerError :: SomeException -> Text handlerError = sformat $ "Exception thrown by staticPeersOnChange handler: " % shown % ". Ignored." ---------------------------------------------------------------------------- -- Interpreter ---------------------------------------------------------------------------- -- | Interpreter for the network config opts intNetworkConfigOpts :: forall m. ( WithLogger m , MonadIO m , Mockable Fork m , MonadCatch m ) => NetworkConfigOpts -> m (T.NetworkConfig DHT.KademliaParams) intNetworkConfigOpts cfg@NetworkConfigOpts{..} = do parsedTopology <- case ncoTopology of Nothing -> pure defaultTopology Just fp -> liftIO $ readTopology fp (ourTopology, tcpAddr) <- case parsedTopology of Y.TopologyStatic{..} -> do (md@NodeMetadata{..}, initPeers, kademliaPeers) <- liftIO $ fromPovOf cfg topologyAllPeers topologyStaticPeers <- monitorStaticConfig cfg md initPeers -- If kademlia is enabled here then we'll try to read the configuration -- file. However it's not necessary that the file exists. If it doesn't, -- we can fill in some sensible defaults using the static routing and -- kademlia flags for other nodes. topologyOptKademlia <- if nmKademlia then liftIO getKademliaParamsFromFile >>= \case Right kparams -> return $ Just kparams Left MissingKademliaConfig -> let ekparams' = getKademliaParamsFromStatic kademliaPeers in either (throwM . CannotParseKademliaConfig . Left) (return . Just) ekparams' Left err -> throwM err else do when (isJust ncoKademlia) $ throwM $ RedundantCliParameter $ "TopologyStatic doesn't require kademlia, but it was passed" pure Nothing topology <- case nmType of T.NodeCore -> return T.TopologyCore{..} T.NodeRelay -> return T.TopologyRelay { topologyStaticPeers, topologyDnsDomains = nmSubscribe, topologyValency = nmValency, topologyFallbacks = nmFallbacks, topologyOptKademlia, topologyMaxSubscrs = nmMaxSubscrs } T.NodeEdge -> throwM NetworkConfigSelfEdge tcpAddr <- createTcpAddr topologyOptKademlia pure (topology, tcpAddr) Y.TopologyBehindNAT{..} -> do -- Behind-NAT topology claims no address for the transport, and also -- throws an exception if the --listen parameter is given, to avoid -- confusion: if a user gives a --listen parameter then they probably -- think the program will bind a socket. whenJust ncoKademlia $ const $ throwM $ RedundantCliParameter "BehindNAT topology is used, so no kademlia config is expected" when (isJust ncoBindAddress) $ throwM $ RedundantCliParameter $ "BehindNAT topology is used, no bind address is expected" when (isJust ncoExternalAddress) $ throwM $ RedundantCliParameter $ "BehindNAT topology is used, no external address is expected" pure (T.TopologyBehindNAT{..}, TCP.Unaddressable) Y.TopologyP2P{..} -> do kparams <- either throwM return =<< liftIO getKademliaParamsFromFile tcpAddr <- createTcpAddr (Just kparams) pure ( T.TopologyP2P{topologyKademlia = kparams, ..} , tcpAddr ) Y.TopologyTraditional{..} -> do kparams <- either throwM return =<< liftIO getKademliaParamsFromFile tcpAddr <- createTcpAddr (Just kparams) pure ( T.TopologyTraditional{topologyKademlia = kparams, ..} , tcpAddr ) (enqueuePolicy, dequeuePolicy, failurePolicy) <- case ncoPolicies of -- If no policy file is given we just use the default derived from the -- topology. Nothing -> return ( T.topologyEnqueuePolicy ourTopology , T.topologyDequeuePolicy ourTopology , T.topologyFailurePolicy ourTopology ) -- A policy file is given: the topology-derived defaults are ignored -- and we take the complete policy description from the file. Just fp -> liftIO $ Y.fromStaticPolicies <$> readPolicies fp let networkConfig = T.NetworkConfig { ncTopology = ourTopology , ncDefaultPort = ncoPort , ncSelfName = ncoSelf , ncEnqueuePolicy = enqueuePolicy , ncDequeuePolicy = dequeuePolicy , ncFailurePolicy = failurePolicy , ncTcpAddr = tcpAddr } pure networkConfig where -- Creates transport params out of config. If kademlia config is specified , kademlia external address should match external -- address of transport (which will be checked in this function). createTcpAddr :: Maybe DHT.KademliaParams -> m TCP.TCPAddr createTcpAddr kademliaBind = do let kademliaExternal :: Maybe NetworkAddress kademliaExternal = join $ DHT.kpExternalAddress <$> kademliaBind bindAddr@(bindHost, bindPort) <- maybe (throwM MissingBindAddress) pure ncoBindAddress whenJust ((,) <$> kademliaExternal <*> ncoExternalAddress) $ \(kademliaEx::NetworkAddress,paramEx::NetworkAddress) -> when (kademliaEx /= paramEx) $ throwM $ InconsistentParameters $ sformat ("Kademlia network address is "%build% " but external address passed in cli is "%build% ". They must be the same") kademliaEx paramEx let (externalHost, externalPort) = fromMaybe bindAddr ncoExternalAddress let tcpHost = BS.C8.unpack bindHost tcpPort = show bindPort tcpMkExternal = const (BS.C8.unpack externalHost, show externalPort) pure $ TCP.Addressable $ TCP.TCPAddrInfo tcpHost tcpPort tcpMkExternal -- Come up with kademlia parameters, possibly giving 'Left' in case -- there's no configuration file path given, or if it couldn't be parsed. getKademliaParamsFromFile :: IO (Either NetworkConfigException DHT.KademliaParams) getKademliaParamsFromFile = case ncoKademlia of Nothing -> pure $ Left MissingKademliaConfig Just fp -> do kconf <- parseKademlia fp pure $ first (CannotParseKademliaConfig . Left . DHT.MalformedDHTKey) (DHT.fromYamlConfig kconf) -- Derive kademlia parameters from the set of kademlia-enabled peers. They -- are used as the initial peers, and everything else is unspecified, and will -- be defaulted. getKademliaParamsFromStatic :: [Y.KademliaAddress] -> Either DHT.MalformedDHTKey DHT.KademliaParams -- Since 'Nothing' is given for the kpId, it's impossible to get a 'Left' getKademliaParamsFromStatic kpeers = first DHT.MalformedDHTKey $ DHT.fromYamlConfig $ Y.KademliaParams { Y.kpId = Nothing , Y.kpPeers = kpeers , Y.kpAddress = Nothing , Y.kpBind = Nothing , Y.kpExplicitInitial = Nothing , Y.kpDumpFile = Nothing } -- | Perspective on 'AllStaticallyKnownPeers' from the point of view of -- a single node. -- First component is this node 's metadata . Second component is the set of all known peers ( routes included ) . Third component is the set of addresses of peers running kademlia . If this node runs kademlia , its address will appear as the last entry in -- the list. fromPovOf :: NetworkConfigOpts -> Y.AllStaticallyKnownPeers -> IO (NodeMetadata, Peers NodeId, [Y.KademliaAddress]) fromPovOf cfg@NetworkConfigOpts{..} allPeers = case ncoSelf of Nothing -> throwM NetworkConfigSelfUnknown Just self -> T.initDnsOnUse $ \resolve -> do selfMetadata <- metadataFor allPeers self resolved <- resolvePeers resolve (Y.allStaticallyKnownPeers allPeers) routes <- mkRoutes (second addressToNodeId <$> resolved) (Y.nmRoutes selfMetadata) let directory = M.fromList (map (\(a, b) -> (addressToNodeId b, a)) (M.elems resolved)) hasKademlia = M.filter nmKademlia (Y.allStaticallyKnownPeers allPeers) selfKademlia = M.member self hasKademlia otherKademlia = M.delete self hasKademlia -- Linter claims that -- [self | selfKademlia] -- is more readable than -- if selfKademlia then [self] else [] allKademlia = M.keys otherKademlia ++ [self | selfKademlia] kademliaPeers = mkKademliaAddress . snd <$> mapMaybe (\name -> M.lookup name resolved) allKademlia pure (selfMetadata, peersFromList directory routes, kademliaPeers) where mkKademliaAddress :: NetworkAddress -> Y.KademliaAddress mkKademliaAddress (addr, port) = Y.KademliaAddress { Y.kaHost = BS.C8.unpack addr , Y.kaPort = port } -- Use the name/metadata association to come up with types and -- addresses for each name. resolvePeers :: T.Resolver -> Map NodeName Y.NodeMetadata -> IO (Map NodeName (T.NodeType, NetworkAddress)) resolvePeers resolve = M.traverseWithKey (resolvePeer resolve) resolvePeer :: T.Resolver -> NodeName -> Y.NodeMetadata -> IO (T.NodeType, NetworkAddress) resolvePeer resolve name metadata = (typ,) <$> resolveNodeAddr cfg resolve (name, addr) where typ = nmType metadata addr = nmAddress metadata Given a NodeName directory ( see ' resolvePeers ' ) , fill in the NodeRoutes -- by looking up the relevant names. -- It's assumed that each name in a list of alternatives has the same -- type. mkRoutes :: Map NodeName (T.NodeType, NodeId) -> Y.NodeRoutes -> IO [(T.NodeType, Alts NodeId)] mkRoutes directory (Y.NodeRoutes routes) = mapM (mkAlts directory) routes mkAlts :: Map NodeName (T.NodeType, NodeId) -> Alts NodeName -> IO (T.NodeType, Alts NodeId) mkAlts _ [] = throwM $ EmptyListOfAltsFor (fromJust ncoSelf) mkAlts directory names@(name:_) = do Use the type associated to the first name , and assume all alts have -- same type. -- TODO we could easily check that using -- mapM ( resolveName directory ) names : : IO ( NodeType , NodeId ) -- -- and throw an exception if there's a mismatch. typ <- fmap fst . resolveName directory $ name nids <- mapM (fmap snd . resolveName directory) names return (typ, nids) resolveName :: Map NodeName t -> NodeName -> IO t resolveName directory name = case M.lookup name directory of Nothing -> throwM $ UndefinedNodeName name Just t -> return t -- | Resolve node name to IP address -- -- We do this when reading the topology file so that we detect DNS problems -- early, and so that we are using canonical addresses (IP addresses) for -- node IDs. -- -- NOTE: This is /only/ used for core or edge nodes (nodes with a statically -- configured set of peers). For such nodes it makes sense to detect DNS problems at startup . For behind NAT nodes we do not do any resolution at -- this point; instead, it happens dynamically in the subscription worker. -- This is important; in user applications we certainly don't want to prevent the application from starting up because of DNS problems at startup . -- TODO : Support re - reading this file after SIGHUP . resolveNodeAddr :: NetworkConfigOpts -> T.Resolver -> (NodeName, NodeAddr (Maybe DNS.Domain)) -> IO NetworkAddress resolveNodeAddr cfg _ (_, NodeAddrExact addr mPort) = do let port = fromMaybe (ncoPort cfg) mPort return (encodeUtf8 @String . show $ addr, port) resolveNodeAddr cfg resolve (name, NodeAddrDNS mHost mPort) = do let host = fromMaybe (nameToDomain name) mHost port = fromMaybe (ncoPort cfg) mPort mAddrs <- resolve host case mAddrs of Left err -> throwM $ NetworkConfigDnsError host err Right [] -> throwM $ CannotResolve name Right addrs@(_:_:_) -> throwM $ NoUniqueResolution name addrs Right [addr] -> return $ ipv4ToNetworkAddress addr port where nameToDomain :: NodeName -> DNS.Domain nameToDomain (NodeName n) = BS.C8.pack (toString n) ipv4ToNetworkAddress :: IPv4 -> Word16 -> NetworkAddress ipv4ToNetworkAddress addr port = (BS.C8.pack (show addr), port) metadataFor :: Y.AllStaticallyKnownPeers -> NodeName -> IO Y.NodeMetadata metadataFor (Y.AllStaticallyKnownPeers allPeers) node = case M.lookup node allPeers of Nothing -> throwM $ UndefinedNodeName node Just metadata -> return metadata readTopology :: FilePath -> IO Y.Topology readTopology fp = Yaml.decodeFileEither fp >>= \case Left err -> throwM $ CannotParseNetworkConfig err Right topology -> return topology readPolicies :: FilePath -> IO Y.StaticPolicies readPolicies fp = Yaml.decodeFileEither fp >>= \case Left err -> throwM $ CannotParsePolicies err Right staticPolicies -> return staticPolicies parseKademlia :: FilePath -> IO Y.KademliaParams parseKademlia fp = Yaml.decodeFileEither fp >>= \case Left err -> throwM $ CannotParseKademliaConfig (Right err) Right kademlia -> return kademlia ---------------------------------------------------------------------------- -- Errors ---------------------------------------------------------------------------- -- | Something is wrong with the network configuration -- -- NOTE: Behind NAT nodes are not given an explicit network configuration file, -- but instead rely on the default topology. These exceptions should never be thrown for behind NAT nodes , as we do n't want to prevent the user application -- from starting up. data NetworkConfigException = -- | We cannot parse the topology .yaml file CannotParseNetworkConfig Yaml.ParseException -- | A Kademlia configuration file is expected but was not specified. | MissingKademliaConfig -- | Address to bind on is missing in CLI. | MissingBindAddress -- | Some passed parameters can't be used together. | InconsistentParameters Text -- | Some CLI parameter is redundant. | RedundantCliParameter Text -- | We cannot parse the kademlia .yaml file | CannotParseKademliaConfig (Either DHT.MalformedDHTKey Yaml.ParseException) -- | A policy description .yaml was specified but couldn't be parsed. | CannotParsePolicies Yaml.ParseException -- | We use a set of statically known peers but we weren't given the -- name of the current node | NetworkConfigSelfUnknown -- | We resolved our name under static configuration to be an edge node. -- This indicates a programmer error. | NetworkConfigSelfEdge -- | The .yaml file contains a node name which is undefined | UndefinedNodeName NodeName -- | The static routes for a node contains an empty list of alternatives | EmptyListOfAltsFor NodeName -- | Something went wrong during node name resolution | NetworkConfigDnsError DNS.Domain DNS.DNSError -- | Could not resolve a node name to an IP address | CannotResolve NodeName -- | DNS returned multiple IP addresses for the give node name -- -- This is no good because we need canonical node IDs. | NoUniqueResolution NodeName [IPv4] deriving (Show) instance Exception NetworkConfigException
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/infra/Pos/Network/CLI.hs
haskell
# LANGUAGE CPP # following Pos.Util.UserSecret | Command line interface for specifying the network config * Exported primilary for testing -------------------------------------------------------------------------- Command line arguments -------------------------------------------------------------------------- ^ Name of the current node DOCUMENT THIS FIELD ^ A node may have a bind address which differs from its external address. ^ A node must be addressable on the network. -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- Defaults -------------------------------------------------------------------------- | The topology we assume when no topology file is specified TODO: Give this a proper value -------------------------------------------------------------------------- Monitor for static peers -------------------------------------------------------------------------- | Monitor for changes to the static config ^ Original metadata (at startup) ^ Initial value Call new handler with current value -------------------------------------------------------------------------- Interpreter -------------------------------------------------------------------------- | Interpreter for the network config opts If kademlia is enabled here then we'll try to read the configuration file. However it's not necessary that the file exists. If it doesn't, we can fill in some sensible defaults using the static routing and kademlia flags for other nodes. Behind-NAT topology claims no address for the transport, and also throws an exception if the --listen parameter is given, to avoid confusion: if a user gives a --listen parameter then they probably think the program will bind a socket. If no policy file is given we just use the default derived from the topology. A policy file is given: the topology-derived defaults are ignored and we take the complete policy description from the file. Creates transport params out of config. If kademlia config is address of transport (which will be checked in this function). Come up with kademlia parameters, possibly giving 'Left' in case there's no configuration file path given, or if it couldn't be parsed. Derive kademlia parameters from the set of kademlia-enabled peers. They are used as the initial peers, and everything else is unspecified, and will be defaulted. Since 'Nothing' is given for the kpId, it's impossible to get a 'Left' | Perspective on 'AllStaticallyKnownPeers' from the point of view of a single node. the list. Linter claims that [self | selfKademlia] is more readable than if selfKademlia then [self] else [] Use the name/metadata association to come up with types and addresses for each name. by looking up the relevant names. It's assumed that each name in a list of alternatives has the same type. same type. TODO we could easily check that using and throw an exception if there's a mismatch. | Resolve node name to IP address We do this when reading the topology file so that we detect DNS problems early, and so that we are using canonical addresses (IP addresses) for node IDs. NOTE: This is /only/ used for core or edge nodes (nodes with a statically configured set of peers). For such nodes it makes sense to detect DNS this point; instead, it happens dynamically in the subscription worker. This is important; in user applications we certainly don't want to prevent -------------------------------------------------------------------------- Errors -------------------------------------------------------------------------- | Something is wrong with the network configuration NOTE: Behind NAT nodes are not given an explicit network configuration file, but instead rely on the default topology. These exceptions should never be from starting up. | We cannot parse the topology .yaml file | A Kademlia configuration file is expected but was not specified. | Address to bind on is missing in CLI. | Some passed parameters can't be used together. | Some CLI parameter is redundant. | We cannot parse the kademlia .yaml file | A policy description .yaml was specified but couldn't be parsed. | We use a set of statically known peers but we weren't given the name of the current node | We resolved our name under static configuration to be an edge node. This indicates a programmer error. | The .yaml file contains a node name which is undefined | The static routes for a node contains an empty list of alternatives | Something went wrong during node name resolution | Could not resolve a node name to an IP address | DNS returned multiple IP addresses for the give node name This is no good because we need canonical node IDs.
# LANGUAGE ApplicativeDo # # LANGUAGE NamedFieldPuns # #if !defined(mingw32_HOST_OS) #define POSIX #endif module Pos.Network.CLI ( NetworkConfigOpts(..) , NetworkConfigException(..) , networkConfigOption , externalNetworkAddressOption , listenNetworkAddressOption , ipv4ToNetworkAddress , intNetworkConfigOpts , readTopology , readPolicies , fromPovOf ) where import Universum import Control.Concurrent import Control.Exception.Safe (try) import qualified Data.ByteString.Char8 as BS.C8 import Data.IP (IPv4) import qualified Data.Map.Strict as M import Data.Maybe (fromJust, mapMaybe) import qualified Data.Yaml as Yaml import Formatting (build, sformat, shown, (%)) import Mockable (Mockable, fork) import Mockable.Concurrent import Network.Broadcast.OutboundQueue (Alts, Peers, peersFromList) import qualified Network.DNS as DNS import qualified Network.Transport.TCP as TCP import qualified Options.Applicative as Opt import Serokell.Util.OptParse (fromParsec) import System.Wlog.CanLog (WithLogger, logError, logNotice) import qualified Pos.DHT.Real.Param as DHT (KademliaParams (..), MalformedDHTKey (..), fromYamlConfig) import Pos.Network.DnsDomains (DnsDomains (..), NodeAddr (..)) import Pos.Network.Types (NodeId, NodeName (..)) import qualified Pos.Network.Types as T import Pos.Network.Yaml (NodeMetadata (..)) import qualified Pos.Network.Yaml as Y import Pos.Util.TimeWarp (NetworkAddress, addrParser, addrParserNoWildcard, addressToNodeId) #ifdef POSIX import Pos.Util.SigHandler (Signal (..), installHandler) #endif data NetworkConfigOpts = NetworkConfigOpts { ncoTopology :: !(Maybe FilePath) ^ to .yaml file with the network topology , ncoKademlia :: !(Maybe FilePath) ^ Filepath to .yaml config of kademlia , ncoSelf :: !(Maybe NodeName) , ncoPort :: !Word16 ^ Port number to use when translating IP addresses to NodeIds , ncoPolicies :: !(Maybe FilePath) , ncoBindAddress :: !(Maybe NetworkAddress) , ncoExternalAddress :: !(Maybe NetworkAddress) } deriving (Show) Parser networkConfigOption :: Opt.Parser NetworkConfigOpts networkConfigOption = do ncoTopology <- optional $ Opt.strOption $ mconcat [ Opt.long "topology" , Opt.metavar "FILEPATH" , Opt.help "Path to a YAML file containing the network topology" ] ncoKademlia <- optional $ Opt.strOption $ mconcat [ Opt.long "kademlia" , Opt.metavar "FILEPATH" , Opt.help "Path to a YAML file containing the kademlia configuration" ] ncoSelf <- optional $ Opt.option (fromString <$> Opt.str) $ mconcat [ Opt.long "node-id" , Opt.metavar "NODE_ID" , Opt.help "Identifier for this node within the network" ] ncoPort <- Opt.option Opt.auto $ mconcat [ Opt.long "default-port" , Opt.metavar "PORT" , Opt.help "Port number for IP address to node ID translation" , Opt.value 3000 ] ncoPolicies <- Opt.optional $ Opt.strOption $ mconcat [ Opt.long "policies" , Opt.metavar "FILEPATH" , Opt.help "Path to a YAML file containing the network policies" ] ncoExternalAddress <- optional $ externalNetworkAddressOption Nothing ncoBindAddress <- optional $ listenNetworkAddressOption Nothing pure $ NetworkConfigOpts {..} externalNetworkAddressOption :: Maybe NetworkAddress -> Opt.Parser NetworkAddress externalNetworkAddressOption na = Opt.option (fromParsec addrParserNoWildcard) $ Opt.long "address" <> Opt.metavar "IP:PORT" <> Opt.help helpMsg <> Opt.showDefault <> maybe mempty Opt.value na where helpMsg = "IP and port of external address. " <> "Please make sure these IP and port (on which node is running) are accessible " <> "otherwise proper work of CSL isn't guaranteed. " <> "0.0.0.0 is not accepted as a valid host." listenNetworkAddressOption :: Maybe NetworkAddress -> Opt.Parser NetworkAddress listenNetworkAddressOption na = Opt.option (fromParsec addrParser) $ Opt.long "listen" <> Opt.metavar "IP:PORT" <> Opt.help helpMsg <> Opt.showDefault <> maybe mempty Opt.value na where helpMsg = "IP and port on which to bind and listen. Please make sure these IP " <> "and port are accessible, otherwise proper work of CSL isn't guaranteed." defaultTopology :: Y.Topology defaultTopology = Y.TopologyBehindNAT { topologyValency = 1 , topologyFallbacks = 1 , topologyDnsDomains = defaultDnsDomains } | The default DNS domains used for relay discovery defaultDnsDomains :: DnsDomains DNS.Domain defaultDnsDomains = DnsDomains [ [NodeAddrDNS "todo.defaultDnsDomain.com" Nothing] ] data MonitorEvent m = MonitorRegister (Peers NodeId -> m ()) | MonitorSIGHUP monitorStaticConfig :: forall m. ( WithLogger m , MonadIO m , Mockable Fork m , MonadCatch m ) => NetworkConfigOpts -> m T.StaticPeers monitorStaticConfig cfg@NetworkConfigOpts{..} origMetadata initPeers = do events :: Chan (MonitorEvent m) <- liftIO newChan #ifdef POSIX liftIO $ installHandler SigHUP $ writeChan events MonitorSIGHUP #endif _tid <- fork $ loop events initPeers [] return T.StaticPeers { T.staticPeersOnChange = writeChan events . MonitorRegister } where loop :: Chan (MonitorEvent m) -> Peers NodeId -> [Peers NodeId -> m ()] -> m () loop events peers handlers = liftIO (readChan events) >>= \case MonitorRegister handler -> do loop events peers (handler:handlers) MonitorSIGHUP -> do let fp = fromJust ncoTopology mParsedTopology <- try $ liftIO $ readTopology fp case mParsedTopology of Right (Y.TopologyStatic allPeers) -> do (newMetadata, newPeers, _) <- liftIO $ fromPovOf cfg allPeers unless (nmType newMetadata == nmType origMetadata) $ logError $ changedType fp unless (nmKademlia newMetadata == nmKademlia origMetadata) $ logError $ changedKademlia fp unless (nmMaxSubscrs newMetadata == nmMaxSubscrs origMetadata) $ logError $ changedMaxSubscrs fp mapM_ (runHandler newPeers) handlers logNotice $ sformat "SIGHUP: Re-read topology" loop events newPeers handlers Right _otherTopology -> do logError $ changedFormat fp loop events peers handlers Left ex -> do logError $ readFailed fp ex loop events peers handlers runHandler :: forall t . t -> (t -> m ()) -> m () runHandler it handler = do mu <- try (handler it) case mu of Left ex -> logError $ handlerError ex Right () -> return () changedFormat, changedType, changedKademlia :: FilePath -> Text changedFormat = sformat $ "SIGHUP ("%shown%"): Cannot dynamically change topology." changedType = sformat $ "SIGHUP ("%shown%"): Cannot dynamically change own node type." changedKademlia = sformat $ "SIGHUP ("%shown%"): Cannot dynamically start/stop Kademlia." changedMaxSubscrs = sformat $ "SIGHUP ("%shown%"): Cannot dynamically change maximum number of subscribers." readFailed :: FilePath -> SomeException -> Text readFailed = sformat $ "SIGHUP: Failed to read " % shown % ": " % shown % ". Ignored." handlerError :: SomeException -> Text handlerError = sformat $ "Exception thrown by staticPeersOnChange handler: " % shown % ". Ignored." intNetworkConfigOpts :: forall m. ( WithLogger m , MonadIO m , Mockable Fork m , MonadCatch m ) => NetworkConfigOpts -> m (T.NetworkConfig DHT.KademliaParams) intNetworkConfigOpts cfg@NetworkConfigOpts{..} = do parsedTopology <- case ncoTopology of Nothing -> pure defaultTopology Just fp -> liftIO $ readTopology fp (ourTopology, tcpAddr) <- case parsedTopology of Y.TopologyStatic{..} -> do (md@NodeMetadata{..}, initPeers, kademliaPeers) <- liftIO $ fromPovOf cfg topologyAllPeers topologyStaticPeers <- monitorStaticConfig cfg md initPeers topologyOptKademlia <- if nmKademlia then liftIO getKademliaParamsFromFile >>= \case Right kparams -> return $ Just kparams Left MissingKademliaConfig -> let ekparams' = getKademliaParamsFromStatic kademliaPeers in either (throwM . CannotParseKademliaConfig . Left) (return . Just) ekparams' Left err -> throwM err else do when (isJust ncoKademlia) $ throwM $ RedundantCliParameter $ "TopologyStatic doesn't require kademlia, but it was passed" pure Nothing topology <- case nmType of T.NodeCore -> return T.TopologyCore{..} T.NodeRelay -> return T.TopologyRelay { topologyStaticPeers, topologyDnsDomains = nmSubscribe, topologyValency = nmValency, topologyFallbacks = nmFallbacks, topologyOptKademlia, topologyMaxSubscrs = nmMaxSubscrs } T.NodeEdge -> throwM NetworkConfigSelfEdge tcpAddr <- createTcpAddr topologyOptKademlia pure (topology, tcpAddr) Y.TopologyBehindNAT{..} -> do whenJust ncoKademlia $ const $ throwM $ RedundantCliParameter "BehindNAT topology is used, so no kademlia config is expected" when (isJust ncoBindAddress) $ throwM $ RedundantCliParameter $ "BehindNAT topology is used, no bind address is expected" when (isJust ncoExternalAddress) $ throwM $ RedundantCliParameter $ "BehindNAT topology is used, no external address is expected" pure (T.TopologyBehindNAT{..}, TCP.Unaddressable) Y.TopologyP2P{..} -> do kparams <- either throwM return =<< liftIO getKademliaParamsFromFile tcpAddr <- createTcpAddr (Just kparams) pure ( T.TopologyP2P{topologyKademlia = kparams, ..} , tcpAddr ) Y.TopologyTraditional{..} -> do kparams <- either throwM return =<< liftIO getKademliaParamsFromFile tcpAddr <- createTcpAddr (Just kparams) pure ( T.TopologyTraditional{topologyKademlia = kparams, ..} , tcpAddr ) (enqueuePolicy, dequeuePolicy, failurePolicy) <- case ncoPolicies of Nothing -> return ( T.topologyEnqueuePolicy ourTopology , T.topologyDequeuePolicy ourTopology , T.topologyFailurePolicy ourTopology ) Just fp -> liftIO $ Y.fromStaticPolicies <$> readPolicies fp let networkConfig = T.NetworkConfig { ncTopology = ourTopology , ncDefaultPort = ncoPort , ncSelfName = ncoSelf , ncEnqueuePolicy = enqueuePolicy , ncDequeuePolicy = dequeuePolicy , ncFailurePolicy = failurePolicy , ncTcpAddr = tcpAddr } pure networkConfig where specified , kademlia external address should match external createTcpAddr :: Maybe DHT.KademliaParams -> m TCP.TCPAddr createTcpAddr kademliaBind = do let kademliaExternal :: Maybe NetworkAddress kademliaExternal = join $ DHT.kpExternalAddress <$> kademliaBind bindAddr@(bindHost, bindPort) <- maybe (throwM MissingBindAddress) pure ncoBindAddress whenJust ((,) <$> kademliaExternal <*> ncoExternalAddress) $ \(kademliaEx::NetworkAddress,paramEx::NetworkAddress) -> when (kademliaEx /= paramEx) $ throwM $ InconsistentParameters $ sformat ("Kademlia network address is "%build% " but external address passed in cli is "%build% ". They must be the same") kademliaEx paramEx let (externalHost, externalPort) = fromMaybe bindAddr ncoExternalAddress let tcpHost = BS.C8.unpack bindHost tcpPort = show bindPort tcpMkExternal = const (BS.C8.unpack externalHost, show externalPort) pure $ TCP.Addressable $ TCP.TCPAddrInfo tcpHost tcpPort tcpMkExternal getKademliaParamsFromFile :: IO (Either NetworkConfigException DHT.KademliaParams) getKademliaParamsFromFile = case ncoKademlia of Nothing -> pure $ Left MissingKademliaConfig Just fp -> do kconf <- parseKademlia fp pure $ first (CannotParseKademliaConfig . Left . DHT.MalformedDHTKey) (DHT.fromYamlConfig kconf) getKademliaParamsFromStatic :: [Y.KademliaAddress] -> Either DHT.MalformedDHTKey DHT.KademliaParams getKademliaParamsFromStatic kpeers = first DHT.MalformedDHTKey $ DHT.fromYamlConfig $ Y.KademliaParams { Y.kpId = Nothing , Y.kpPeers = kpeers , Y.kpAddress = Nothing , Y.kpBind = Nothing , Y.kpExplicitInitial = Nothing , Y.kpDumpFile = Nothing } First component is this node 's metadata . Second component is the set of all known peers ( routes included ) . Third component is the set of addresses of peers running kademlia . If this node runs kademlia , its address will appear as the last entry in fromPovOf :: NetworkConfigOpts -> Y.AllStaticallyKnownPeers -> IO (NodeMetadata, Peers NodeId, [Y.KademliaAddress]) fromPovOf cfg@NetworkConfigOpts{..} allPeers = case ncoSelf of Nothing -> throwM NetworkConfigSelfUnknown Just self -> T.initDnsOnUse $ \resolve -> do selfMetadata <- metadataFor allPeers self resolved <- resolvePeers resolve (Y.allStaticallyKnownPeers allPeers) routes <- mkRoutes (second addressToNodeId <$> resolved) (Y.nmRoutes selfMetadata) let directory = M.fromList (map (\(a, b) -> (addressToNodeId b, a)) (M.elems resolved)) hasKademlia = M.filter nmKademlia (Y.allStaticallyKnownPeers allPeers) selfKademlia = M.member self hasKademlia otherKademlia = M.delete self hasKademlia allKademlia = M.keys otherKademlia ++ [self | selfKademlia] kademliaPeers = mkKademliaAddress . snd <$> mapMaybe (\name -> M.lookup name resolved) allKademlia pure (selfMetadata, peersFromList directory routes, kademliaPeers) where mkKademliaAddress :: NetworkAddress -> Y.KademliaAddress mkKademliaAddress (addr, port) = Y.KademliaAddress { Y.kaHost = BS.C8.unpack addr , Y.kaPort = port } resolvePeers :: T.Resolver -> Map NodeName Y.NodeMetadata -> IO (Map NodeName (T.NodeType, NetworkAddress)) resolvePeers resolve = M.traverseWithKey (resolvePeer resolve) resolvePeer :: T.Resolver -> NodeName -> Y.NodeMetadata -> IO (T.NodeType, NetworkAddress) resolvePeer resolve name metadata = (typ,) <$> resolveNodeAddr cfg resolve (name, addr) where typ = nmType metadata addr = nmAddress metadata Given a NodeName directory ( see ' resolvePeers ' ) , fill in the NodeRoutes mkRoutes :: Map NodeName (T.NodeType, NodeId) -> Y.NodeRoutes -> IO [(T.NodeType, Alts NodeId)] mkRoutes directory (Y.NodeRoutes routes) = mapM (mkAlts directory) routes mkAlts :: Map NodeName (T.NodeType, NodeId) -> Alts NodeName -> IO (T.NodeType, Alts NodeId) mkAlts _ [] = throwM $ EmptyListOfAltsFor (fromJust ncoSelf) mkAlts directory names@(name:_) = do Use the type associated to the first name , and assume all alts have mapM ( resolveName directory ) names : : IO ( NodeType , NodeId ) typ <- fmap fst . resolveName directory $ name nids <- mapM (fmap snd . resolveName directory) names return (typ, nids) resolveName :: Map NodeName t -> NodeName -> IO t resolveName directory name = case M.lookup name directory of Nothing -> throwM $ UndefinedNodeName name Just t -> return t problems at startup . For behind NAT nodes we do not do any resolution at the application from starting up because of DNS problems at startup . TODO : Support re - reading this file after SIGHUP . resolveNodeAddr :: NetworkConfigOpts -> T.Resolver -> (NodeName, NodeAddr (Maybe DNS.Domain)) -> IO NetworkAddress resolveNodeAddr cfg _ (_, NodeAddrExact addr mPort) = do let port = fromMaybe (ncoPort cfg) mPort return (encodeUtf8 @String . show $ addr, port) resolveNodeAddr cfg resolve (name, NodeAddrDNS mHost mPort) = do let host = fromMaybe (nameToDomain name) mHost port = fromMaybe (ncoPort cfg) mPort mAddrs <- resolve host case mAddrs of Left err -> throwM $ NetworkConfigDnsError host err Right [] -> throwM $ CannotResolve name Right addrs@(_:_:_) -> throwM $ NoUniqueResolution name addrs Right [addr] -> return $ ipv4ToNetworkAddress addr port where nameToDomain :: NodeName -> DNS.Domain nameToDomain (NodeName n) = BS.C8.pack (toString n) ipv4ToNetworkAddress :: IPv4 -> Word16 -> NetworkAddress ipv4ToNetworkAddress addr port = (BS.C8.pack (show addr), port) metadataFor :: Y.AllStaticallyKnownPeers -> NodeName -> IO Y.NodeMetadata metadataFor (Y.AllStaticallyKnownPeers allPeers) node = case M.lookup node allPeers of Nothing -> throwM $ UndefinedNodeName node Just metadata -> return metadata readTopology :: FilePath -> IO Y.Topology readTopology fp = Yaml.decodeFileEither fp >>= \case Left err -> throwM $ CannotParseNetworkConfig err Right topology -> return topology readPolicies :: FilePath -> IO Y.StaticPolicies readPolicies fp = Yaml.decodeFileEither fp >>= \case Left err -> throwM $ CannotParsePolicies err Right staticPolicies -> return staticPolicies parseKademlia :: FilePath -> IO Y.KademliaParams parseKademlia fp = Yaml.decodeFileEither fp >>= \case Left err -> throwM $ CannotParseKademliaConfig (Right err) Right kademlia -> return kademlia thrown for behind NAT nodes , as we do n't want to prevent the user application data NetworkConfigException = CannotParseNetworkConfig Yaml.ParseException | MissingKademliaConfig | MissingBindAddress | InconsistentParameters Text | RedundantCliParameter Text | CannotParseKademliaConfig (Either DHT.MalformedDHTKey Yaml.ParseException) | CannotParsePolicies Yaml.ParseException | NetworkConfigSelfUnknown | NetworkConfigSelfEdge | UndefinedNodeName NodeName | EmptyListOfAltsFor NodeName | NetworkConfigDnsError DNS.Domain DNS.DNSError | CannotResolve NodeName | NoUniqueResolution NodeName [IPv4] deriving (Show) instance Exception NetworkConfigException
2a22240f2f25d544374da88ae421316c28f2d8b3fc7460e30774b7c55ce29cc6
waymonad/waymonad
Output.hs
waymonad A wayland compositor in the spirit of xmonad Copyright ( C ) 2017 This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA Reach us at waymonad A wayland compositor in the spirit of xmonad Copyright (C) 2017 Markus Ongyerth This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Reach us at -} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # | Module : Output Description : The output type for Waymonad Maintainer : ongy Stability : testing Portability : Linux This is the core for outputs . Most modules will probably not use this , unless they want to do something with the lifecycle of an output , rather than workspace or layout management . With that said , the intended lifecycle of an output : 1 . An output is plugged in / created 2 . The output is configured 3 . The output is added to the layout / workarea 4 . The output can be configured over IPC 5 . The output is removed from the layout / workarea 6 . The output disappears The 5th step here may actually be caused by the 6th step . Unplugging or destroying the output will trigger the transition from 4 over 5 to 6 . Steps 1 and 2 should be handled immediatly . Adding the output to the ( ) globals , to expose it over IPC , happens automatically . Configuration of the output should be handled by the user . The hook in the main entry is @wayUserConfOutputAdd@ in ' Waymonad . Main . WayUserConf ' . This now set up ' Output ' should then be added to the workarea . This will then emit the core hook @wayHooksSeatNewOutput@ in ' Waymonad . Types . WayHooks ' which is responsible for setting up workspace mappings or similar shenanigans . At this point the output is set up and usable by the user and applications . It can still be configured over IPC , though currently no events for this exist . When it 's unplugged the core will clean up any traces of it . There is currently no core event for it , though that may change . Module : Output Description : The output type for Waymonad Maintainer : ongy Stability : testing Portability : Linux This is the core for outputs. Most modules will probably not use this, unless they want to do something with the lifecycle of an output, rather than workspace or layout management. With that said, the intended lifecycle of an output: 1. An output is plugged in/created 2. The output is configured 3. The output is added to the layout/workarea 4. The output can be configured over IPC 5. The output is removed from the layout/workarea 6. The output disappears The 5th step here may actually be caused by the 6th step. Unplugging or destroying the output will trigger the transition from 4 over 5 to 6. Steps 1 and 2 should be handled immediatly. Adding the output to the (Waymoand) globals, to expose it over IPC, happens automatically. Configuration of the output should be handled by the user. The hook in the main entry is @wayUserConfOutputAdd@ in 'Waymonad.Main.WayUserConf'. This now set up 'Output' should then be added to the workarea. This will then emit the core hook @wayHooksSeatNewOutput@ in 'Waymonad.Types.WayHooks' which is responsible for setting up workspace mappings or similar shenanigans. At this point the output is set up and usable by the user and applications. It can still be configured over IPC, though currently no events for this exist. When it's unplugged the core will clean up any traces of it. There is currently no core event for it, though that may change. -} module Waymonad.Output ( handleOutputAdd , handleOutputAdd' , handleOutputRemove , Output (..) , getOutputId , outputFromWlr , findMode , setOutputDirty , forOutput , readTransform , setPreferdMode , addOutputToWork , removeOutputFromWork , getOutputBox , intersectsOutput , outApplyDamage , setOutMode ) where import Control.Exception (try) import System.IO.Error (IOError) import Control.Monad (forM_, forM) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Foldable (maximumBy, minimumBy) import Data.Function (on) import Data.IORef (writeIORef, newIORef, readIORef, modifyIORef) import Data.List ((\\), find) import Data.Text (Text) import Data.Word (Word32) import Foreign.Ptr (Ptr) import Foreign.Storable (Storable(peek)) import Graphics.Pixman import Graphics.Wayland.Signal (removeListener) import Graphics.Wayland.Server ( OutputTransform , outputTransformNormal , outputTransform180 , outputTransform90 , outputTransform270 , outputTransformFlipped , outputTransformFlipped_180 , outputTransformFlipped_90 , outputTransformFlipped_270 ) import Graphics.Wayland.WlRoots.Box (WlrBox(..), Point (..)) import Graphics.Wayland.WlRoots.Output ( WlrOutput , OutputMode (..) , getModes , getOutputName , getOutputScale , setOutputMode , outputEnable , outputDisable , getWidth , getHeight , OutputSignals (..) , getOutputSignals , scheduleOutputFrame ) import Graphics.Wayland.WlRoots.OutputLayout ( outputIntersects -- TODO: I think wlroots made this simpler , layoutOuputGetPosition , layoutGetOutput , addOutput , addOutputAuto , removeOutput ) import Waymonad (makeCallback2) import Waymonad.Types (Compositor (..), WayHooks (..), OutputEvent (..), Output (..), OutputEffective (..)) import Waymonad.Utility.Signal import Waymonad.Utility.Mapping (getOutputKeyboards, unsetSeatKeyboardOut) import Waymonad.Input.Seat (Seat(seatLoadScale)) import Waymonad.Start (attachFrame) import Waymonad.Utility.Base (doJust) import Waymonad.Output.Render (frameHandler) import Waymonad.ViewSet (WSTag (..), FocusCore) import Waymonad ( Way , WayBindingState (..) , getState , getSeats ) import Waymonad.Output.Core import qualified Data.Map.Strict as M findMode :: MonadIO m => Ptr WlrOutput -> Word32 -> Word32 -> Maybe Word32 -> m (Maybe (Ptr OutputMode)) findMode output width height refresh = liftIO $ do modes <- getModes output paired <- forM modes $ \x -> do marshalled <- peek x pure (marshalled, x) let candidates = filter (\(mode, _) -> modeWidth mode == width && modeHeight mode == height) paired let fun = case refresh of Nothing -> maximumBy (compare `on` (modeRefresh . fst)) Just val -> minimumBy (compare `on` (abs . (-) (fromIntegral val :: Int) . fromIntegral . modeRefresh . fst)) pure $ case candidates of [] -> Nothing xs -> Just . snd . fun $ xs outputEffectiveChanged :: Output -> Way vs ws () outputEffectiveChanged out = do WayHooks {wayHooksOutputEffective = hook} <- wayCoreHooks <$> getState hook $ OutputEffective out handleOutputAdd' :: (WSTag ws, FocusCore vs ws) => (Double -> Output -> Way vs ws ()) -> (Output -> Way vs ws ()) -> Ptr WlrOutput -> Way vs ws () handleOutputAdd' handler hook output = do name <- liftIO $ getOutputName output current <- wayBindingOutputs <$> getState active <- liftIO $ newIORef False let layerNames = ["overlay", "top", "override", "floating", "main", "bottom", "background"] layerPairs <- liftIO $ mapM (\x -> (x,) <$> newIORef []) layerNames let layers = map snd layerPairs layerMap = M.fromList layerPairs outputDamageR <- liftIO allocateRegion outputBuf1 <- liftIO allocateRegion outputBuf2 <- liftIO allocateRegion let out = Output output name active layers layerMap outputDamageR (outputBuf1, outputBuf2) liftIO $ modifyIORef current (out :) let signals = getOutputSignals output modeH <- setSignalHandler (outSignalMode signals) (const $ outputEffectiveChanged out) scaleH <- setSignalHandler (outSignalScale signals) (const $ outputEffectiveChanged out) transformH <- setSignalHandler (outSignalTransform signals) (const $ outputEffectiveChanged out) needsSwapH <- setSignalHandler (outSignalNeedsSwap signals) (const . liftIO $ scheduleOutputFrame (outputRoots out)) hook out frameCB <- makeCallback2 (\t _ -> handler t out) frameH <- liftIO $ attachFrame frameCB output setDestroyHandler (outSignalDestroy signals) (\dout -> do liftIO $ mapM_ removeListener [modeH, scaleH, transformH, needsSwapH, frameH] handleOutputRemove dout ) handleOutputAdd :: (WSTag ws, FocusCore vs ws) => (Output -> Way vs ws ()) -> Ptr WlrOutput -> Way vs ws () handleOutputAdd = handleOutputAdd' frameHandler handleOutputRemove :: WSTag ws => Ptr WlrOutput -> Way vs ws () handleOutputRemove output = doJust (outputFromWlr output) $ \out -> do state <- getState removeOutputFromWork out liftIO $ modifyIORef (wayBindingOutputs state) $ \xs -> xs \\ [out] removeOutputFromWork :: WSTag ws => Output -> Way vs ws () removeOutputFromWork output = do state <- getState let Compositor {compLayout = layout} = wayCompositor state liftIO $ removeOutput layout $ outputRoots output liftIO $ outputDisable (outputRoots output) liftIO $ modifyIORef (wayBindingMapping state) $ filter ((/=) output . snd) liftIO $ writeIORef (outputActive output) False keyboards <- getOutputKeyboards output mapM_ unsetSeatKeyboardOut keyboards outputFromWlr :: Ptr WlrOutput -> Way vs a (Maybe Output) outputFromWlr ptr = do outs <- liftIO . readIORef . wayBindingOutputs =<< getState pure . find ((==) ptr . outputRoots) $ outs forOutput :: (Output -> Way vs ws a) -> Way vs ws [a] forOutput fun = do current <- wayBindingOutputs <$> getState outs <- liftIO $ readIORef current mapM fun outs readTransform :: Text -> Maybe OutputTransform readTransform "Normal" = Just outputTransformNormal readTransform "90" = Just outputTransform90 readTransform "180" = Just outputTransform180 readTransform "270" = Just outputTransform270 readTransform "Flipped" = Just outputTransformFlipped readTransform "Flipped90" = Just outputTransformFlipped_90 readTransform "Flipped180" = Just outputTransformFlipped_180 readTransform "Flipped270" = Just outputTransformFlipped_270 readTransform _ = Nothing setOutMode :: MonadIO m => Ptr WlrOutput -> Ptr OutputMode -> m () -> m () setOutMode output mode cont = do ret :: Either IOError () <- liftIO $ try $ setOutputMode mode output case ret of Left _ -> pure () Right _ -> cont setPreferdMode :: MonadIO m => Ptr WlrOutput -> m () -> m () setPreferdMode output cont = do modes <- liftIO $ getModes output case modes of [] -> cont _ -> setOutMode output (last modes) cont addOutputToWork :: Output -> Maybe Point -> Way vs ws () addOutputToWork output position = do Compositor {compLayout = layout} <- wayCompositor <$> getState liftIO $ case position of Nothing -> addOutputAuto layout $ outputRoots output Just (Point x y) -> addOutput layout (outputRoots output) x y WayHooks {wayHooksNewOutput = hook} <- wayCoreHooks <$> getState scale <- liftIO $ getOutputScale (outputRoots output) seats <- getSeats liftIO $ forM_ seats $ \seat -> seatLoadScale seat scale liftIO $ writeIORef (outputActive output) True liftIO $ outputEnable (outputRoots output) hook (OutputEvent output) getOutputBox :: Output -> Way vs ws (Maybe WlrBox) getOutputBox Output { outputRoots = output } = do Compositor {compLayout = layout} <- wayCompositor <$> getState (Point ox oy) <- liftIO (layoutOuputGetPosition =<< layoutGetOutput layout output) width <- liftIO $ getWidth output height <- liftIO $ getHeight output pure $ Just $ WlrBox ox oy (fromIntegral width) (fromIntegral height) intersectsOutput :: Output -> WlrBox -> Way vs ws Bool intersectsOutput Output {outputRoots = out} box = do Compositor {compLayout = layout} <- wayCompositor <$> getState liftIO $ outputIntersects layout out box
null
https://raw.githubusercontent.com/waymonad/waymonad/18ab493710dd54c330fb4d122ed35bc3a59585df/src/Waymonad/Output.hs
haskell
# LANGUAGE OverloadedStrings # TODO: I think wlroots made this simpler
waymonad A wayland compositor in the spirit of xmonad Copyright ( C ) 2017 This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA Reach us at waymonad A wayland compositor in the spirit of xmonad Copyright (C) 2017 Markus Ongyerth This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Reach us at -} # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # | Module : Output Description : The output type for Waymonad Maintainer : ongy Stability : testing Portability : Linux This is the core for outputs . Most modules will probably not use this , unless they want to do something with the lifecycle of an output , rather than workspace or layout management . With that said , the intended lifecycle of an output : 1 . An output is plugged in / created 2 . The output is configured 3 . The output is added to the layout / workarea 4 . The output can be configured over IPC 5 . The output is removed from the layout / workarea 6 . The output disappears The 5th step here may actually be caused by the 6th step . Unplugging or destroying the output will trigger the transition from 4 over 5 to 6 . Steps 1 and 2 should be handled immediatly . Adding the output to the ( ) globals , to expose it over IPC , happens automatically . Configuration of the output should be handled by the user . The hook in the main entry is @wayUserConfOutputAdd@ in ' Waymonad . Main . WayUserConf ' . This now set up ' Output ' should then be added to the workarea . This will then emit the core hook @wayHooksSeatNewOutput@ in ' Waymonad . Types . WayHooks ' which is responsible for setting up workspace mappings or similar shenanigans . At this point the output is set up and usable by the user and applications . It can still be configured over IPC , though currently no events for this exist . When it 's unplugged the core will clean up any traces of it . There is currently no core event for it , though that may change . Module : Output Description : The output type for Waymonad Maintainer : ongy Stability : testing Portability : Linux This is the core for outputs. Most modules will probably not use this, unless they want to do something with the lifecycle of an output, rather than workspace or layout management. With that said, the intended lifecycle of an output: 1. An output is plugged in/created 2. The output is configured 3. The output is added to the layout/workarea 4. The output can be configured over IPC 5. The output is removed from the layout/workarea 6. The output disappears The 5th step here may actually be caused by the 6th step. Unplugging or destroying the output will trigger the transition from 4 over 5 to 6. Steps 1 and 2 should be handled immediatly. Adding the output to the (Waymoand) globals, to expose it over IPC, happens automatically. Configuration of the output should be handled by the user. The hook in the main entry is @wayUserConfOutputAdd@ in 'Waymonad.Main.WayUserConf'. This now set up 'Output' should then be added to the workarea. This will then emit the core hook @wayHooksSeatNewOutput@ in 'Waymonad.Types.WayHooks' which is responsible for setting up workspace mappings or similar shenanigans. At this point the output is set up and usable by the user and applications. It can still be configured over IPC, though currently no events for this exist. When it's unplugged the core will clean up any traces of it. There is currently no core event for it, though that may change. -} module Waymonad.Output ( handleOutputAdd , handleOutputAdd' , handleOutputRemove , Output (..) , getOutputId , outputFromWlr , findMode , setOutputDirty , forOutput , readTransform , setPreferdMode , addOutputToWork , removeOutputFromWork , getOutputBox , intersectsOutput , outApplyDamage , setOutMode ) where import Control.Exception (try) import System.IO.Error (IOError) import Control.Monad (forM_, forM) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Foldable (maximumBy, minimumBy) import Data.Function (on) import Data.IORef (writeIORef, newIORef, readIORef, modifyIORef) import Data.List ((\\), find) import Data.Text (Text) import Data.Word (Word32) import Foreign.Ptr (Ptr) import Foreign.Storable (Storable(peek)) import Graphics.Pixman import Graphics.Wayland.Signal (removeListener) import Graphics.Wayland.Server ( OutputTransform , outputTransformNormal , outputTransform180 , outputTransform90 , outputTransform270 , outputTransformFlipped , outputTransformFlipped_180 , outputTransformFlipped_90 , outputTransformFlipped_270 ) import Graphics.Wayland.WlRoots.Box (WlrBox(..), Point (..)) import Graphics.Wayland.WlRoots.Output ( WlrOutput , OutputMode (..) , getModes , getOutputName , getOutputScale , setOutputMode , outputEnable , outputDisable , getWidth , getHeight , OutputSignals (..) , getOutputSignals , scheduleOutputFrame ) import Graphics.Wayland.WlRoots.OutputLayout ( outputIntersects , layoutOuputGetPosition , layoutGetOutput , addOutput , addOutputAuto , removeOutput ) import Waymonad (makeCallback2) import Waymonad.Types (Compositor (..), WayHooks (..), OutputEvent (..), Output (..), OutputEffective (..)) import Waymonad.Utility.Signal import Waymonad.Utility.Mapping (getOutputKeyboards, unsetSeatKeyboardOut) import Waymonad.Input.Seat (Seat(seatLoadScale)) import Waymonad.Start (attachFrame) import Waymonad.Utility.Base (doJust) import Waymonad.Output.Render (frameHandler) import Waymonad.ViewSet (WSTag (..), FocusCore) import Waymonad ( Way , WayBindingState (..) , getState , getSeats ) import Waymonad.Output.Core import qualified Data.Map.Strict as M findMode :: MonadIO m => Ptr WlrOutput -> Word32 -> Word32 -> Maybe Word32 -> m (Maybe (Ptr OutputMode)) findMode output width height refresh = liftIO $ do modes <- getModes output paired <- forM modes $ \x -> do marshalled <- peek x pure (marshalled, x) let candidates = filter (\(mode, _) -> modeWidth mode == width && modeHeight mode == height) paired let fun = case refresh of Nothing -> maximumBy (compare `on` (modeRefresh . fst)) Just val -> minimumBy (compare `on` (abs . (-) (fromIntegral val :: Int) . fromIntegral . modeRefresh . fst)) pure $ case candidates of [] -> Nothing xs -> Just . snd . fun $ xs outputEffectiveChanged :: Output -> Way vs ws () outputEffectiveChanged out = do WayHooks {wayHooksOutputEffective = hook} <- wayCoreHooks <$> getState hook $ OutputEffective out handleOutputAdd' :: (WSTag ws, FocusCore vs ws) => (Double -> Output -> Way vs ws ()) -> (Output -> Way vs ws ()) -> Ptr WlrOutput -> Way vs ws () handleOutputAdd' handler hook output = do name <- liftIO $ getOutputName output current <- wayBindingOutputs <$> getState active <- liftIO $ newIORef False let layerNames = ["overlay", "top", "override", "floating", "main", "bottom", "background"] layerPairs <- liftIO $ mapM (\x -> (x,) <$> newIORef []) layerNames let layers = map snd layerPairs layerMap = M.fromList layerPairs outputDamageR <- liftIO allocateRegion outputBuf1 <- liftIO allocateRegion outputBuf2 <- liftIO allocateRegion let out = Output output name active layers layerMap outputDamageR (outputBuf1, outputBuf2) liftIO $ modifyIORef current (out :) let signals = getOutputSignals output modeH <- setSignalHandler (outSignalMode signals) (const $ outputEffectiveChanged out) scaleH <- setSignalHandler (outSignalScale signals) (const $ outputEffectiveChanged out) transformH <- setSignalHandler (outSignalTransform signals) (const $ outputEffectiveChanged out) needsSwapH <- setSignalHandler (outSignalNeedsSwap signals) (const . liftIO $ scheduleOutputFrame (outputRoots out)) hook out frameCB <- makeCallback2 (\t _ -> handler t out) frameH <- liftIO $ attachFrame frameCB output setDestroyHandler (outSignalDestroy signals) (\dout -> do liftIO $ mapM_ removeListener [modeH, scaleH, transformH, needsSwapH, frameH] handleOutputRemove dout ) handleOutputAdd :: (WSTag ws, FocusCore vs ws) => (Output -> Way vs ws ()) -> Ptr WlrOutput -> Way vs ws () handleOutputAdd = handleOutputAdd' frameHandler handleOutputRemove :: WSTag ws => Ptr WlrOutput -> Way vs ws () handleOutputRemove output = doJust (outputFromWlr output) $ \out -> do state <- getState removeOutputFromWork out liftIO $ modifyIORef (wayBindingOutputs state) $ \xs -> xs \\ [out] removeOutputFromWork :: WSTag ws => Output -> Way vs ws () removeOutputFromWork output = do state <- getState let Compositor {compLayout = layout} = wayCompositor state liftIO $ removeOutput layout $ outputRoots output liftIO $ outputDisable (outputRoots output) liftIO $ modifyIORef (wayBindingMapping state) $ filter ((/=) output . snd) liftIO $ writeIORef (outputActive output) False keyboards <- getOutputKeyboards output mapM_ unsetSeatKeyboardOut keyboards outputFromWlr :: Ptr WlrOutput -> Way vs a (Maybe Output) outputFromWlr ptr = do outs <- liftIO . readIORef . wayBindingOutputs =<< getState pure . find ((==) ptr . outputRoots) $ outs forOutput :: (Output -> Way vs ws a) -> Way vs ws [a] forOutput fun = do current <- wayBindingOutputs <$> getState outs <- liftIO $ readIORef current mapM fun outs readTransform :: Text -> Maybe OutputTransform readTransform "Normal" = Just outputTransformNormal readTransform "90" = Just outputTransform90 readTransform "180" = Just outputTransform180 readTransform "270" = Just outputTransform270 readTransform "Flipped" = Just outputTransformFlipped readTransform "Flipped90" = Just outputTransformFlipped_90 readTransform "Flipped180" = Just outputTransformFlipped_180 readTransform "Flipped270" = Just outputTransformFlipped_270 readTransform _ = Nothing setOutMode :: MonadIO m => Ptr WlrOutput -> Ptr OutputMode -> m () -> m () setOutMode output mode cont = do ret :: Either IOError () <- liftIO $ try $ setOutputMode mode output case ret of Left _ -> pure () Right _ -> cont setPreferdMode :: MonadIO m => Ptr WlrOutput -> m () -> m () setPreferdMode output cont = do modes <- liftIO $ getModes output case modes of [] -> cont _ -> setOutMode output (last modes) cont addOutputToWork :: Output -> Maybe Point -> Way vs ws () addOutputToWork output position = do Compositor {compLayout = layout} <- wayCompositor <$> getState liftIO $ case position of Nothing -> addOutputAuto layout $ outputRoots output Just (Point x y) -> addOutput layout (outputRoots output) x y WayHooks {wayHooksNewOutput = hook} <- wayCoreHooks <$> getState scale <- liftIO $ getOutputScale (outputRoots output) seats <- getSeats liftIO $ forM_ seats $ \seat -> seatLoadScale seat scale liftIO $ writeIORef (outputActive output) True liftIO $ outputEnable (outputRoots output) hook (OutputEvent output) getOutputBox :: Output -> Way vs ws (Maybe WlrBox) getOutputBox Output { outputRoots = output } = do Compositor {compLayout = layout} <- wayCompositor <$> getState (Point ox oy) <- liftIO (layoutOuputGetPosition =<< layoutGetOutput layout output) width <- liftIO $ getWidth output height <- liftIO $ getHeight output pure $ Just $ WlrBox ox oy (fromIntegral width) (fromIntegral height) intersectsOutput :: Output -> WlrBox -> Way vs ws Bool intersectsOutput Output {outputRoots = out} box = do Compositor {compLayout = layout} <- wayCompositor <$> getState liftIO $ outputIntersects layout out box
60a5b05b78f201ee3ee1b6d0d0e1e2cd1fbf79f1d9241a862f590973422ae6e7
termite-analyser/termite
algo1.mli
* First ( non - terminating ) algorithm First (non-terminating) algorithm *) open Smt.ZZ (** Exception raised when the algorithm makes too much iterations *) exception Timeout * [ algo1 block_dict invariant tau timeout verbose ] returns the linear component [ l ] of a weak ranking function , such that [ pi(l ) ] is maximal . - [ block_dict ] and [ var_dict ] are dictionaries respectively from basic blocks and variables to smt variables . positive integer ( see { ! } ) - [ invariant ] is the the invariant ( see { ! Invariants.invariants } ) - [ tau ] is the formula representing the transition relation - If [ timeout ] is a positive integer , the algorithm will raise the [ Timeout ] exception at the [ timeout]-th iteration . Default is [ 10 ] . - If [ verbose ] is true , prints the values of [ l ] , [ x ] , [ y ] , [ x - y ] , [ cost ] , [ lambda ] and [ delta ] at each iteration . Default is [ false ] { b WARNING } : This algorithm does not always terminate . See { ! Monodimensional.monodimensional } for a terminating algorithm . [algo1 block_dict var_dict invariant tau timeout verbose] returns the linear component [l] of a weak ranking function, such that [pi(l)] is maximal. - [block_dict] and [var_dict] are dictionaries respectively from basic blocks and llvm variables to smt variables. positive integer (see {!Automaton.indexed_strings}) - [invariant] is the the invariant (see {!Invariants.invariants}) - [tau] is the formula representing the transition relation - If [timeout] is a positive integer, the algorithm will raise the [Timeout] exception at the [timeout]-th iteration. Default is [10]. - If [verbose] is true, prints the values of [l], [x], [y], [x-y], [cost], [lambda] and [delta] at each iteration. Default is [false] {b WARNING} : This algorithm does not always terminate. See {!Monodimensional.monodimensional} for a terminating algorithm. *) val algo1 : ?verbose:bool -> ?timeout:int -> (bool -> Llvm.llbasicblock -> zbool term) -> (bool -> Llvm.llvalue -> [< znum ] term) -> Invariants.invariant -> zbool term -> (Q.t array * Q.t) Debug.result
null
https://raw.githubusercontent.com/termite-analyser/termite/285d92215a28fcce55614f6d04b44886f253a894/src/algo1.mli
ocaml
* Exception raised when the algorithm makes too much iterations
* First ( non - terminating ) algorithm First (non-terminating) algorithm *) open Smt.ZZ exception Timeout * [ algo1 block_dict invariant tau timeout verbose ] returns the linear component [ l ] of a weak ranking function , such that [ pi(l ) ] is maximal . - [ block_dict ] and [ var_dict ] are dictionaries respectively from basic blocks and variables to smt variables . positive integer ( see { ! } ) - [ invariant ] is the the invariant ( see { ! Invariants.invariants } ) - [ tau ] is the formula representing the transition relation - If [ timeout ] is a positive integer , the algorithm will raise the [ Timeout ] exception at the [ timeout]-th iteration . Default is [ 10 ] . - If [ verbose ] is true , prints the values of [ l ] , [ x ] , [ y ] , [ x - y ] , [ cost ] , [ lambda ] and [ delta ] at each iteration . Default is [ false ] { b WARNING } : This algorithm does not always terminate . See { ! Monodimensional.monodimensional } for a terminating algorithm . [algo1 block_dict var_dict invariant tau timeout verbose] returns the linear component [l] of a weak ranking function, such that [pi(l)] is maximal. - [block_dict] and [var_dict] are dictionaries respectively from basic blocks and llvm variables to smt variables. positive integer (see {!Automaton.indexed_strings}) - [invariant] is the the invariant (see {!Invariants.invariants}) - [tau] is the formula representing the transition relation - If [timeout] is a positive integer, the algorithm will raise the [Timeout] exception at the [timeout]-th iteration. Default is [10]. - If [verbose] is true, prints the values of [l], [x], [y], [x-y], [cost], [lambda] and [delta] at each iteration. Default is [false] {b WARNING} : This algorithm does not always terminate. See {!Monodimensional.monodimensional} for a terminating algorithm. *) val algo1 : ?verbose:bool -> ?timeout:int -> (bool -> Llvm.llbasicblock -> zbool term) -> (bool -> Llvm.llvalue -> [< znum ] term) -> Invariants.invariant -> zbool term -> (Q.t array * Q.t) Debug.result
16f12df30a24b9da9f824fff9b2ca7d45197a27a33ec776591166928c665ddd6
digitallyinduced/ihp
ViewErrorMessages.hs
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module IHP.ViewErrorMessages where instance TypeError ( Text " Can not ' Show ' functions . " : $ $ : Text " Perhaps there is a missing argument ? " ) = > Show ( a - > b ) where -- showsPrec = error "unreachable"
null
https://raw.githubusercontent.com/digitallyinduced/ihp/62ca014a3d986e35da0fb05a4b1e84e5831e87cf/IHP/ViewErrorMessages.hs
haskell
showsPrec = error "unreachable"
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module IHP.ViewErrorMessages where instance TypeError ( Text " Can not ' Show ' functions . " : $ $ : Text " Perhaps there is a missing argument ? " ) = > Show ( a - > b ) where
0099162dce1c5e103221b605f728e2ac0f0c8c4986c4f367cb32526001a2d477
objectionary/try-phi
Setup.hs
# LANGUAGE CPP # # OPTIONS_GHC -Wall # module Main (main) where #ifndef MIN_VERSION_cabal_doctest #define MIN_VERSION_cabal_doctest(x,y,z) 0 #endif #if MIN_VERSION_cabal_doctest(1,0,0) import Distribution.Extra.Doctest ( defaultMainWithDoctests ) main :: IO () main = defaultMainWithDoctests "doctests" #else #ifdef MIN_VERSION_Cabal -- If the macro is defined, we have new cabal-install, -- but for some reason we don't have cabal-doctest in package-db -- -- Probably we are running cabal sdist, when otherwise using new-build -- workflow #warning You are configuring this package without cabal-doctest installed. \ The doctests test-suite will not work as a result. \ To fix this, install cabal-doctest before configuring. #endif import Distribution.Simple main :: IO () main = defaultMain #endif
null
https://raw.githubusercontent.com/objectionary/try-phi/9eb9879c46decc4eb1e6f34beaa6a2736224b649/back/language-utils/Setup.hs
haskell
If the macro is defined, we have new cabal-install, but for some reason we don't have cabal-doctest in package-db Probably we are running cabal sdist, when otherwise using new-build workflow
# LANGUAGE CPP # # OPTIONS_GHC -Wall # module Main (main) where #ifndef MIN_VERSION_cabal_doctest #define MIN_VERSION_cabal_doctest(x,y,z) 0 #endif #if MIN_VERSION_cabal_doctest(1,0,0) import Distribution.Extra.Doctest ( defaultMainWithDoctests ) main :: IO () main = defaultMainWithDoctests "doctests" #else #ifdef MIN_VERSION_Cabal #warning You are configuring this package without cabal-doctest installed. \ The doctests test-suite will not work as a result. \ To fix this, install cabal-doctest before configuring. #endif import Distribution.Simple main :: IO () main = defaultMain #endif
ea4bc5650b4345da585f5f8bbc447787783f4249dd9e218977257751549d9196
softwarelanguageslab/maf
R5RS_WeiChenRompf2019_the-little-schemer_ch2-1.scm
; Changes: * removed : 2 * added : 0 * swaps : 0 ; * negated predicates: 0 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((atom? (lambda (x) (if (not (pair? x)) (not (null? x)) #f))) (lat? (lambda (l) (if (null? l) #t (if (atom? (car l)) (lat? (cdr l)) #f))))) (lat? (__toplevel_cons 'Jack (__toplevel_cons 'Sprat (__toplevel_cons 'could (__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))) (<change> (lat? (__toplevel_cons (__toplevel_cons 'Jack ()) (__toplevel_cons 'Sprat (__toplevel_cons 'could (__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))) ()) (<change> (lat? (__toplevel_cons 'Jack (__toplevel_cons (__toplevel_cons 'Sprat (__toplevel_cons 'could ())) (__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ()))))))) ()) (lat? ()))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_WeiChenRompf2019_the-little-schemer_ch2-1.scm
scheme
Changes: * negated predicates: 0 * swapped branches: 0 * calls to id fun: 0
* removed : 2 * added : 0 * swaps : 0 (letrec ((atom? (lambda (x) (if (not (pair? x)) (not (null? x)) #f))) (lat? (lambda (l) (if (null? l) #t (if (atom? (car l)) (lat? (cdr l)) #f))))) (lat? (__toplevel_cons 'Jack (__toplevel_cons 'Sprat (__toplevel_cons 'could (__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))) (<change> (lat? (__toplevel_cons (__toplevel_cons 'Jack ()) (__toplevel_cons 'Sprat (__toplevel_cons 'could (__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))) ()) (<change> (lat? (__toplevel_cons 'Jack (__toplevel_cons (__toplevel_cons 'Sprat (__toplevel_cons 'could ())) (__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ()))))))) ()) (lat? ()))
3a7283b6134fef65f7e4bd3342c2f62992d3198fbd22595efc7651231ef0b135
threatgrid/ctim
target_records.cljc
(ns ctim.examples.target-records (:require [ctim.schemas.common :as c])) (def target-record-maximal {:id "-record/target-record-7d3e0f0c-6ee7-4578-8e1a-f45a750bb37b" :type "target-record" :schema_version c/ctim-schema-version :revision 1 :external_ids ["-record/target-record-7d3e0f0c-6ee7-4578-8e1a-f45a750bb37b"] :source "cisco:ise:dhcp-server" :source_uri "-record" :external_references [{:source_name "source" :external_id "TR042" :url "" :hashes ["#section1"] :description "Description text"}] :title "TR-8BA72C1B" :description "description" :short_description "short description" :timestamp #inst "2016-02-11T00:40:48.212-00:00" :language "language" :tlp "green" :targets [{:type "endpoint" :os "centos linux release 7.5" :observed_time {:start_time #inst "2020-01-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"} :observables [{:value "atl.ciscothreatresponse.local" :type "hostname"} {:value "192.168.1.204" :type "ip"} {:value "00:50:56:b8:0c:c8" :type "mac_address"}] :internal true :source_uri "-a3f1-4a05-b961-65c8b9a28e96/trajectory?q=192.168.243.112" :sensor "process.dhcp-server"}]}) (def target-record-minimal {:id "-record/target-record-7d3e0f0c-6ee7-4578-8e1a-f45a750bb37b" :type "target-record" :schema_version c/ctim-schema-version :source "cisco:ise:dhcp-server" :targets [{:type "endpoint" :observables [{:value "atl.ciscothreatresponse.local" :type "hostname"}] :os "centos linux release 7.5" :internal true :source_uri "-a3f1-4a05-b961-65c8b9a28e96/trajectory?q=192.168.243.112" :observed_time {:start_time #inst "2020-01-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"} :sensor "process.dhcp-server"}]}) (def new-target-record-maximal target-record-maximal) (def new-target-record-minimal target-record-minimal)
null
https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/src/ctim/examples/target_records.cljc
clojure
(ns ctim.examples.target-records (:require [ctim.schemas.common :as c])) (def target-record-maximal {:id "-record/target-record-7d3e0f0c-6ee7-4578-8e1a-f45a750bb37b" :type "target-record" :schema_version c/ctim-schema-version :revision 1 :external_ids ["-record/target-record-7d3e0f0c-6ee7-4578-8e1a-f45a750bb37b"] :source "cisco:ise:dhcp-server" :source_uri "-record" :external_references [{:source_name "source" :external_id "TR042" :url "" :hashes ["#section1"] :description "Description text"}] :title "TR-8BA72C1B" :description "description" :short_description "short description" :timestamp #inst "2016-02-11T00:40:48.212-00:00" :language "language" :tlp "green" :targets [{:type "endpoint" :os "centos linux release 7.5" :observed_time {:start_time #inst "2020-01-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"} :observables [{:value "atl.ciscothreatresponse.local" :type "hostname"} {:value "192.168.1.204" :type "ip"} {:value "00:50:56:b8:0c:c8" :type "mac_address"}] :internal true :source_uri "-a3f1-4a05-b961-65c8b9a28e96/trajectory?q=192.168.243.112" :sensor "process.dhcp-server"}]}) (def target-record-minimal {:id "-record/target-record-7d3e0f0c-6ee7-4578-8e1a-f45a750bb37b" :type "target-record" :schema_version c/ctim-schema-version :source "cisco:ise:dhcp-server" :targets [{:type "endpoint" :observables [{:value "atl.ciscothreatresponse.local" :type "hostname"}] :os "centos linux release 7.5" :internal true :source_uri "-a3f1-4a05-b961-65c8b9a28e96/trajectory?q=192.168.243.112" :observed_time {:start_time #inst "2020-01-11T00:40:48.212-00:00" :end_time #inst "2525-01-01T00:00:00.000-00:00"} :sensor "process.dhcp-server"}]}) (def new-target-record-maximal target-record-maximal) (def new-target-record-minimal target-record-minimal)
040b7fcec075b32f28725f7451c1f8a08f9a665068e8ed81a51ed080c2ca0fd9
tekul/jose-jwt
JwkSpec.hs
# LANGUAGE OverloadedStrings , CPP # module Tests.JwkSpec where import Test.Hspec import Test.HUnit hiding (Test) import Data.Aeson #if MIN_VERSION_aeson(2,0,0) import qualified Data.Aeson.KeyMap as KM #else import qualified Data.HashMap.Strict as H #endif import qualified Data.ByteString.Char8 as B import Data.Word (Word64) import qualified Data.Vector as V import Crypto.PubKey.ECC.ECDSA import Crypto.PubKey.ECC.Types import Crypto.Random (drgNewTest, withDRG) import Jose.Jwt (defJwsHdr, JwsHeader(..), KeyId(..)) import Jose.Jwk import Jose.Jwa spec :: Spec spec = do jwkFile <- runIO (B.readFile "tests/jwks.json") let Just (Object keySet) = decodeStrict jwkFile Success s = fromJSON (Object keySet) :: Result JwkSet Just s' = decode (encode s) Just s'' = decode' (encode s') kss = keys s' k0 = head kss k1 = kss !! 1 k3 = kss !! 3 k4 = kss !! 4 describe "JWK encoding and decoding" $ do it "decodes and encodes an entire key set successfully" $ do let RsaPublicJwk _ key0Id key0Use a0 = k0 RsaPublicJwk _ key1Id key1Use _ = k1 EcPublicJwk k key2Id key2Use _ _ = kss !! 2 EcPublicJwk _ key3Id key3Use _ _ = k3 SymmetricJwk _ key4Id Nothing _ = k4 EcPublicJwk _ key5Id (Just Enc) _ _ = kss !! 5 RsaPublicJwk _ key6Id Nothing a6 = kss !! 6 EcPrivateJwk _ key7Id (Just Enc) _ _ = kss !! 7 RsaPrivateJwk _ _ Nothing a8 = kss !! 8 Ed25519PrivateJwk _ _ key9Id = kss !! 9 Ed25519PublicJwk _ key10Id = kss !! 10 Success utcKeyId = fromJSON (String "2015-05-16T18:00:14.259Z") length kss @?= 14 a0 @?= Nothing key0Id @?= Just (KeyId "a0") key1Id @?= Just (KeyId "a1") key2Id @?= Just (KeyId "a2") public_curve k @?= getCurveByName SEC_p256r1 key3Id @?= Just (KeyId "a3") key4Id @?= Just (KeyId "HMAC key used in JWS A.1 example") key5Id @?= Just (KeyId "1") key6Id @?= Just (UTCKeyId utcKeyId) key7Id @?= Just (KeyId "1") key9Id @?= Just (KeyId "rfc8037SecretKey") key10Id @?= Just (KeyId "rfc8037PublicKey") key0Use @?= Just Enc key1Use @?= Just Sig key2Use @?= Just Sig key3Use @?= Just Enc a6 @?= Just (Signed RS256) a8 @?= Just (Signed RS256) isPublic k3 @?= True isPublic k4 @?= False isPrivate k4 @?= False it "shameless Show and Eq coverage boosting" $ do s' @?= s'' assertBool "Different sets aren't equal" (s' /= JwkSet { keys = take 8 kss ++ [k0]}) assertBool "Show stuff" $ showCov s' && showCov k0 && showCov k3 && showCov Sig assertBool "Different keys should be unequal" (k0 /= k1) describe "Errors in JWK data" $ do #if MIN_VERSION_aeson(2,0,0) let Just (Array ks) = KM.lookup "keys" keySet #else let Just (Array ks) = H.lookup "keys" keySet #endif Object k0obj = V.head ks it "invalid Base64 returns an error" $ do #if MIN_VERSION_aeson(2,0,0) let result = fromJSON (Object $ KM.insert "n" (String "NotBase64**") k0obj) :: Result Jwk #else let result = fromJSON (Object $ H.insert "n" (String "NotBase64**") k0obj) :: Result Jwk #endif case result of Error _ -> assertBool "" True _ -> assertFailure "Expected an error for invalid base 64" describe "JWK Algorithm matching" $ do let jwks = keys s it "finds one key for RS256 encoding" $ do -- Only the RSA Private key let jwks' = filter (canEncodeJws RS256) jwks length jwks' @?= 1 it "finds 3 keys for RS256 decoding with no kid" $ do All RSA keys are valid except for the " enc " one let jwks' = filter (canDecodeJws (defJwsHdr {jwsAlg = RS256})) jwks length jwks' @?= 3 it "finds one key for RS256 decoding with kid specified" $ do let jwks' = filter (canDecodeJws (defJwsHdr {jwsAlg = RS256, jwsKid = Just (KeyId "a1")})) jwks length jwks' @?= 1 it "finds an RS1_5 key for encoding" $ do Only key a0 matches . The other 3 RSA keys are signing keys let jwks' = filter (canEncodeJwe RSA1_5) jwks length jwks' @?= 1 describe "RSA Key generation" $ do let rng = drgNewTest (w, w, w, w, w) where w = 1 :: Word64 kid = KeyId "mykey" ((kPub, kPr), _) = withDRG rng (generateRsaKeyPair 512 kid Sig Nothing) it "keys generated with same RNG are equal" $ do let ((kPub', kPr'), _) = withDRG rng (generateRsaKeyPair 512 kid Sig Nothing) kPub' @?= kPub kPr' @?= kPr it "isPublic and isPrivate are correct for RSA keys" $ do isPublic kPub @?= True isPublic kPr @?= False isPrivate kPr @?= True it "keys have supplied ID" $ do jwkId kPr @?= Just kid jwkId kPub @?= Just kid it "keys have supplied use" $ do jwkUse kPr @?= Just Sig jwkUse kPub @?= Just Sig where showCov x = showList [x] `seq` showsPrec 1 x `seq` show x `seq` True
null
https://raw.githubusercontent.com/tekul/jose-jwt/342cc23c75ae429049821c7198d92aa8c4364d96/tests/Tests/JwkSpec.hs
haskell
Only the RSA Private key
# LANGUAGE OverloadedStrings , CPP # module Tests.JwkSpec where import Test.Hspec import Test.HUnit hiding (Test) import Data.Aeson #if MIN_VERSION_aeson(2,0,0) import qualified Data.Aeson.KeyMap as KM #else import qualified Data.HashMap.Strict as H #endif import qualified Data.ByteString.Char8 as B import Data.Word (Word64) import qualified Data.Vector as V import Crypto.PubKey.ECC.ECDSA import Crypto.PubKey.ECC.Types import Crypto.Random (drgNewTest, withDRG) import Jose.Jwt (defJwsHdr, JwsHeader(..), KeyId(..)) import Jose.Jwk import Jose.Jwa spec :: Spec spec = do jwkFile <- runIO (B.readFile "tests/jwks.json") let Just (Object keySet) = decodeStrict jwkFile Success s = fromJSON (Object keySet) :: Result JwkSet Just s' = decode (encode s) Just s'' = decode' (encode s') kss = keys s' k0 = head kss k1 = kss !! 1 k3 = kss !! 3 k4 = kss !! 4 describe "JWK encoding and decoding" $ do it "decodes and encodes an entire key set successfully" $ do let RsaPublicJwk _ key0Id key0Use a0 = k0 RsaPublicJwk _ key1Id key1Use _ = k1 EcPublicJwk k key2Id key2Use _ _ = kss !! 2 EcPublicJwk _ key3Id key3Use _ _ = k3 SymmetricJwk _ key4Id Nothing _ = k4 EcPublicJwk _ key5Id (Just Enc) _ _ = kss !! 5 RsaPublicJwk _ key6Id Nothing a6 = kss !! 6 EcPrivateJwk _ key7Id (Just Enc) _ _ = kss !! 7 RsaPrivateJwk _ _ Nothing a8 = kss !! 8 Ed25519PrivateJwk _ _ key9Id = kss !! 9 Ed25519PublicJwk _ key10Id = kss !! 10 Success utcKeyId = fromJSON (String "2015-05-16T18:00:14.259Z") length kss @?= 14 a0 @?= Nothing key0Id @?= Just (KeyId "a0") key1Id @?= Just (KeyId "a1") key2Id @?= Just (KeyId "a2") public_curve k @?= getCurveByName SEC_p256r1 key3Id @?= Just (KeyId "a3") key4Id @?= Just (KeyId "HMAC key used in JWS A.1 example") key5Id @?= Just (KeyId "1") key6Id @?= Just (UTCKeyId utcKeyId) key7Id @?= Just (KeyId "1") key9Id @?= Just (KeyId "rfc8037SecretKey") key10Id @?= Just (KeyId "rfc8037PublicKey") key0Use @?= Just Enc key1Use @?= Just Sig key2Use @?= Just Sig key3Use @?= Just Enc a6 @?= Just (Signed RS256) a8 @?= Just (Signed RS256) isPublic k3 @?= True isPublic k4 @?= False isPrivate k4 @?= False it "shameless Show and Eq coverage boosting" $ do s' @?= s'' assertBool "Different sets aren't equal" (s' /= JwkSet { keys = take 8 kss ++ [k0]}) assertBool "Show stuff" $ showCov s' && showCov k0 && showCov k3 && showCov Sig assertBool "Different keys should be unequal" (k0 /= k1) describe "Errors in JWK data" $ do #if MIN_VERSION_aeson(2,0,0) let Just (Array ks) = KM.lookup "keys" keySet #else let Just (Array ks) = H.lookup "keys" keySet #endif Object k0obj = V.head ks it "invalid Base64 returns an error" $ do #if MIN_VERSION_aeson(2,0,0) let result = fromJSON (Object $ KM.insert "n" (String "NotBase64**") k0obj) :: Result Jwk #else let result = fromJSON (Object $ H.insert "n" (String "NotBase64**") k0obj) :: Result Jwk #endif case result of Error _ -> assertBool "" True _ -> assertFailure "Expected an error for invalid base 64" describe "JWK Algorithm matching" $ do let jwks = keys s it "finds one key for RS256 encoding" $ do let jwks' = filter (canEncodeJws RS256) jwks length jwks' @?= 1 it "finds 3 keys for RS256 decoding with no kid" $ do All RSA keys are valid except for the " enc " one let jwks' = filter (canDecodeJws (defJwsHdr {jwsAlg = RS256})) jwks length jwks' @?= 3 it "finds one key for RS256 decoding with kid specified" $ do let jwks' = filter (canDecodeJws (defJwsHdr {jwsAlg = RS256, jwsKid = Just (KeyId "a1")})) jwks length jwks' @?= 1 it "finds an RS1_5 key for encoding" $ do Only key a0 matches . The other 3 RSA keys are signing keys let jwks' = filter (canEncodeJwe RSA1_5) jwks length jwks' @?= 1 describe "RSA Key generation" $ do let rng = drgNewTest (w, w, w, w, w) where w = 1 :: Word64 kid = KeyId "mykey" ((kPub, kPr), _) = withDRG rng (generateRsaKeyPair 512 kid Sig Nothing) it "keys generated with same RNG are equal" $ do let ((kPub', kPr'), _) = withDRG rng (generateRsaKeyPair 512 kid Sig Nothing) kPub' @?= kPub kPr' @?= kPr it "isPublic and isPrivate are correct for RSA keys" $ do isPublic kPub @?= True isPublic kPr @?= False isPrivate kPr @?= True it "keys have supplied ID" $ do jwkId kPr @?= Just kid jwkId kPub @?= Just kid it "keys have supplied use" $ do jwkUse kPr @?= Just Sig jwkUse kPub @?= Just Sig where showCov x = showList [x] `seq` showsPrec 1 x `seq` show x `seq` True
fbbc495d200e2f9ee26b76a2ba3ac419f2652014996374f4515399449020e6a5
ruanpienaar/goanna
goanna_node_tests.erl
-module(goanna_node_tests). -include_lib("eunit/include/eunit.hrl"). -behaviour(goanna_forward_callback_mod). -export([ forward_init/1, forward/2 ]). -include_lib("goanna.hrl"). -spec forward_init(atom()) -> {ok, pid() | atom()} | {error, term()}. forward_init(_ChildId) -> {ok, self()}. -spec forward(_Process :: pid() | atom(), goanna_forward_callback_mod:goanna_trace_tuple()) -> ok. forward(_Process, {_Ts, _Node, _TraceItem}) -> ok. goanna_node_unit_test_() -> unit_testing:foreach( % Setup fun() -> % ?debugFmt("----------> SELF SETUP 1 <----------- ~p\n", [self()]), ok = application:load(goanna) end, % Cleanup fun(_) -> NodeRegName = goanna_node_sup:id('nonode@nohost', cookie), case unit_testing:wait_for_match(10, fun() -> is_pid(whereis(NodeRegName)) end, true) of ok -> Pid = whereis(NodeRegName), true = erlang:unregister(NodeRegName), true = erlang:unlink(Pid), true = erlang:exit(Pid, kill); {error, no_answer} -> ok end, ok = application:unload(goanna) end, % Tests [ {"goanna_node:start_link/0 remote_node_went_down", ?_assert(unit_testing:try_test_fun(fun start_link_node_went_down/0)) }, {"goanna_node:start_link/0 No existing traces - Pull", ?_assert(unit_testing:try_test_fun(fun start_link_no_traces_pull/0)) }, {"goanna_node:start_link/0 No existing traces - Push", ?_assert(unit_testing:try_test_fun(fun start_link_no_traces_push/0))}, {"goanna_node:start_link/0 existing traces - Pull", ?_assert(unit_testing:try_test_fun(fun start_link_traces_pull/0)) }, {"goanna_node:start_link/0 existing traces - Push", ?_assert(unit_testing:try_test_fun(fun start_link_traces_push/0))}, {"goanna_node:start_link/0 forward_mod has only forward - Push", ?_assert(unit_testing:try_test_fun(fun start_link_fmhof/0)) }, {"goanna_node:stop_all_traces_return_state/1", ?_assert(unit_testing:try_test_fun(fun stop_all_traces_return_state/0)) } ], % Mocks [ % Mocks done in tests {goanna_node_mon, [], [ {monitor, fun('nonode@nohost' = Node, SelfPid) -> {monitor, Node, SelfPid}; ('fake@fake' = Node, SelfPid) -> {monitor, Node, SelfPid} end } ]}, {goanna_db, [], [ {init_node, fun(['nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie']) -> {ok, node_obj}; (['fake@fake', cookie, tcpip_port, 'fake@fake©cookie']) -> {ok, node_obj} end }, {lookup, fun([tracelist, _ChildId]) -> [] end } ]} ], true ). start_link_node_went_down() -> ok = application:set_env(goanna, data_retrival_method, pull), {ok, Pid} = goanna_node:start_link('fake@fake', cookie, tcpip_port, 'fake@fake©cookie'), timer:sleep(100), ?assertEqual( {current_function,{goanna_node,terminate,0}}, erlang:process_info(Pid, current_function) ), ?assertEqual( {registered_name,'fake@fake©cookie'}, erlang:process_info(Pid, registered_name) ), Pid ! should_have_been_in_terminate_recv_loop, timer:sleep(100), ?assertEqual( undefined, erlang:process_info(Pid) ). start_link_no_traces_pull() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [] end), ok = application:set_env(goanna, data_retrival_method, pull), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_no_traces_push() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [] end), %% Scenario 1 - Forward module is not compatible ok = application:set_env(goanna, data_retrival_method, {push, 60000, some_non_existant_module, 10}), ?assertException( throw, {some_non_existant_module, does_not_exist}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), %% Scenario 2 - Forward module forward_init crashed ok = application:set_env(goanna, data_retrival_method, {push, 60000, goanna_forward_crash_mod, 10}), ?assertException( throw, {forward_module, goanna_forward_crash_mod, forward_init_crashed, throw, {crash, on, purpose}}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), Scenario 3 - forward module exists , forward_init returns { ok , _ } . ok = application:set_env(goanna, data_retrival_method, {push, 60000, ?MODULE, 10}), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_traces_pull() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [{ets}] end), ok = application:set_env(goanna, data_retrival_method, pull), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_traces_push() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [{ets}] end), %% Scenario 1 - Forward module is not compatible ok = application:set_env(goanna, data_retrival_method, {push, 60000, some_non_existant_module, 10}), ?assertException( throw, {some_non_existant_module, does_not_exist}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), %% Scenario 2 - Forward module forward_init crashed ok = application:set_env(goanna, data_retrival_method, {push, 60000, goanna_forward_crash_mod, 10}), ?assertException( throw, {forward_module, goanna_forward_crash_mod, forward_init_crashed, throw, {crash, on, purpose}}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), Scenario 3 - forward module exists , forward_init returns { ok , _ } . ok = application:set_env(goanna, data_retrival_method, {push, 60000, ?MODULE, 10}), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_fmhof() -> ok = application:set_env(goanna, data_retrival_method, {push, 60000, goanna_forward_only, 10}), ?assertException( throw, {goanna_forward_only,not_goanna_forward_module_compatible}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). stop_all_traces_return_state() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([nodelist, 'nonode@nohost']) -> [{'nonode@nohost', cookie, tcpip_port}] end), ok = unit_testing:mock_expect(goanna_db, truncate_tracelist, fun([]) -> true end), ?assertEqual( #{cookie => cookie, node => nonode@nohost, trace_msg_count => 0, trace_timer_tref => undefined, tracing => false, type => tcpip_port}, goanna_node:stop_all_traces_return_state( #{node => 'nonode@nohost', cookie => cookie, type => tcpip_port, trace_timer_tref => undefined} ) ). initial_state_test() -> ?assertEqual( #{ node => 'nonode@nohost', cookie => cookie, type => tcpip_port, child_id => 'nonode@nohost©cookie', trace_msg_count => 0, trace_timer_tref => undefined, trace_client_pid => undefined, tracing => false, push_timer_tref => undefined, previous_trace_client_pid => undefined }, goanna_node:initial_state('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ).
null
https://raw.githubusercontent.com/ruanpienaar/goanna/52d75566fd6f9760fbdebe53b2ca3c82fdb44e01/test/goanna_node_tests.erl
erlang
Setup ?debugFmt("----------> SELF SETUP 1 <----------- ~p\n", [self()]), Cleanup Tests Mocks Mocks done in tests Scenario 1 - Forward module is not compatible Scenario 2 - Forward module forward_init crashed Scenario 1 - Forward module is not compatible Scenario 2 - Forward module forward_init crashed
-module(goanna_node_tests). -include_lib("eunit/include/eunit.hrl"). -behaviour(goanna_forward_callback_mod). -export([ forward_init/1, forward/2 ]). -include_lib("goanna.hrl"). -spec forward_init(atom()) -> {ok, pid() | atom()} | {error, term()}. forward_init(_ChildId) -> {ok, self()}. -spec forward(_Process :: pid() | atom(), goanna_forward_callback_mod:goanna_trace_tuple()) -> ok. forward(_Process, {_Ts, _Node, _TraceItem}) -> ok. goanna_node_unit_test_() -> unit_testing:foreach( fun() -> ok = application:load(goanna) end, fun(_) -> NodeRegName = goanna_node_sup:id('nonode@nohost', cookie), case unit_testing:wait_for_match(10, fun() -> is_pid(whereis(NodeRegName)) end, true) of ok -> Pid = whereis(NodeRegName), true = erlang:unregister(NodeRegName), true = erlang:unlink(Pid), true = erlang:exit(Pid, kill); {error, no_answer} -> ok end, ok = application:unload(goanna) end, [ {"goanna_node:start_link/0 remote_node_went_down", ?_assert(unit_testing:try_test_fun(fun start_link_node_went_down/0)) }, {"goanna_node:start_link/0 No existing traces - Pull", ?_assert(unit_testing:try_test_fun(fun start_link_no_traces_pull/0)) }, {"goanna_node:start_link/0 No existing traces - Push", ?_assert(unit_testing:try_test_fun(fun start_link_no_traces_push/0))}, {"goanna_node:start_link/0 existing traces - Pull", ?_assert(unit_testing:try_test_fun(fun start_link_traces_pull/0)) }, {"goanna_node:start_link/0 existing traces - Push", ?_assert(unit_testing:try_test_fun(fun start_link_traces_push/0))}, {"goanna_node:start_link/0 forward_mod has only forward - Push", ?_assert(unit_testing:try_test_fun(fun start_link_fmhof/0)) }, {"goanna_node:stop_all_traces_return_state/1", ?_assert(unit_testing:try_test_fun(fun stop_all_traces_return_state/0)) } ], {goanna_node_mon, [], [ {monitor, fun('nonode@nohost' = Node, SelfPid) -> {monitor, Node, SelfPid}; ('fake@fake' = Node, SelfPid) -> {monitor, Node, SelfPid} end } ]}, {goanna_db, [], [ {init_node, fun(['nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie']) -> {ok, node_obj}; (['fake@fake', cookie, tcpip_port, 'fake@fake©cookie']) -> {ok, node_obj} end }, {lookup, fun([tracelist, _ChildId]) -> [] end } ]} ], true ). start_link_node_went_down() -> ok = application:set_env(goanna, data_retrival_method, pull), {ok, Pid} = goanna_node:start_link('fake@fake', cookie, tcpip_port, 'fake@fake©cookie'), timer:sleep(100), ?assertEqual( {current_function,{goanna_node,terminate,0}}, erlang:process_info(Pid, current_function) ), ?assertEqual( {registered_name,'fake@fake©cookie'}, erlang:process_info(Pid, registered_name) ), Pid ! should_have_been_in_terminate_recv_loop, timer:sleep(100), ?assertEqual( undefined, erlang:process_info(Pid) ). start_link_no_traces_pull() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [] end), ok = application:set_env(goanna, data_retrival_method, pull), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_no_traces_push() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [] end), ok = application:set_env(goanna, data_retrival_method, {push, 60000, some_non_existant_module, 10}), ?assertException( throw, {some_non_existant_module, does_not_exist}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), ok = application:set_env(goanna, data_retrival_method, {push, 60000, goanna_forward_crash_mod, 10}), ?assertException( throw, {forward_module, goanna_forward_crash_mod, forward_init_crashed, throw, {crash, on, purpose}}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), Scenario 3 - forward module exists , forward_init returns { ok , _ } . ok = application:set_env(goanna, data_retrival_method, {push, 60000, ?MODULE, 10}), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_traces_pull() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [{ets}] end), ok = application:set_env(goanna, data_retrival_method, pull), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_traces_push() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([tracelist, 'nonode@nohost©cookie']) -> [{ets}] end), ok = application:set_env(goanna, data_retrival_method, {push, 60000, some_non_existant_module, 10}), ?assertException( throw, {some_non_existant_module, does_not_exist}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), ok = application:set_env(goanna, data_retrival_method, {push, 60000, goanna_forward_crash_mod, 10}), ?assertException( throw, {forward_module, goanna_forward_crash_mod, forward_init_crashed, throw, {crash, on, purpose}}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ), Scenario 3 - forward module exists , forward_init returns { ok , _ } . ok = application:set_env(goanna, data_retrival_method, {push, 60000, ?MODULE, 10}), ?assertMatch( {ok, _}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). start_link_fmhof() -> ok = application:set_env(goanna, data_retrival_method, {push, 60000, goanna_forward_only, 10}), ?assertException( throw, {goanna_forward_only,not_goanna_forward_module_compatible}, goanna_node:start_link('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ). stop_all_traces_return_state() -> ok = unit_testing:mock_expect(goanna_db, lookup, fun([nodelist, 'nonode@nohost']) -> [{'nonode@nohost', cookie, tcpip_port}] end), ok = unit_testing:mock_expect(goanna_db, truncate_tracelist, fun([]) -> true end), ?assertEqual( #{cookie => cookie, node => nonode@nohost, trace_msg_count => 0, trace_timer_tref => undefined, tracing => false, type => tcpip_port}, goanna_node:stop_all_traces_return_state( #{node => 'nonode@nohost', cookie => cookie, type => tcpip_port, trace_timer_tref => undefined} ) ). initial_state_test() -> ?assertEqual( #{ node => 'nonode@nohost', cookie => cookie, type => tcpip_port, child_id => 'nonode@nohost©cookie', trace_msg_count => 0, trace_timer_tref => undefined, trace_client_pid => undefined, tracing => false, push_timer_tref => undefined, previous_trace_client_pid => undefined }, goanna_node:initial_state('nonode@nohost', cookie, tcpip_port, 'nonode@nohost©cookie') ).
25d65a6941e64a50a7d95369825e1bb924a41441f8ce727485992758448e6a9b
dergraf/epmdpxy
epmdpxy_session_sup.erl
-module(epmdpxy_session_sup). -behaviour(supervisor). %% API -export([start_link/0, start_session/2, connection_created/3, connection_deleted/3, status/0]). %% Supervisor callbacks -export([init/1]). -define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args}, temporary, 5000, Type, [Mod]}). %%%=================================================================== %%% API functions %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the supervisor %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). start_session(UpstreamNode, Port) -> {ok, Pid} = supervisor:start_child(?MODULE, [UpstreamNode, Port]), ProxyPort = epmdpxy_session:accept(Pid), ProxyPort. connection_created(SessionPid, DownstreamNode, UpstreamNode) -> epmdpxy_splitter:add_cable(DownstreamNode, UpstreamNode, SessionPid). connection_deleted(SessionPid, DownstreamNode, UpstreamNode) -> epmdpxy_splitter:delete_cable(DownstreamNode, UpstreamNode, SessionPid). status() -> [epmdpxy_session:status(Pid) || {_, Pid, _, _} <- supervisor:which_children(?MODULE), is_pid(Pid)]. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Whenever a supervisor is started using supervisor:start_link/[2,3], %% this function is called by the new process to find out about %% restart strategy, maximum restart frequency and child %% specifications. %% ) - > { ok , { SupFlags , [ ChildSpec ] } } | %% ignore | %% {error, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> {ok, {{simple_one_for_one, 0, 5}, [?CHILD(epmdpxy_session, epmdpxy_session, worker, [])]}}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/dergraf/epmdpxy/646506ba2117cb5ac81b9d37c2fe5cb7f042b043/src/epmdpxy_session_sup.erl
erlang
API Supervisor callbacks =================================================================== API functions =================================================================== -------------------------------------------------------------------- @doc Starts the supervisor @end -------------------------------------------------------------------- =================================================================== Supervisor callbacks =================================================================== -------------------------------------------------------------------- @doc Whenever a supervisor is started using supervisor:start_link/[2,3], this function is called by the new process to find out about restart strategy, maximum restart frequency and child specifications. ignore | {error, Reason} @end -------------------------------------------------------------------- =================================================================== ===================================================================
-module(epmdpxy_session_sup). -behaviour(supervisor). -export([start_link/0, start_session/2, connection_created/3, connection_deleted/3, status/0]). -export([init/1]). -define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args}, temporary, 5000, Type, [Mod]}). ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). start_session(UpstreamNode, Port) -> {ok, Pid} = supervisor:start_child(?MODULE, [UpstreamNode, Port]), ProxyPort = epmdpxy_session:accept(Pid), ProxyPort. connection_created(SessionPid, DownstreamNode, UpstreamNode) -> epmdpxy_splitter:add_cable(DownstreamNode, UpstreamNode, SessionPid). connection_deleted(SessionPid, DownstreamNode, UpstreamNode) -> epmdpxy_splitter:delete_cable(DownstreamNode, UpstreamNode, SessionPid). status() -> [epmdpxy_session:status(Pid) || {_, Pid, _, _} <- supervisor:which_children(?MODULE), is_pid(Pid)]. @private ) - > { ok , { SupFlags , [ ChildSpec ] } } | init([]) -> {ok, {{simple_one_for_one, 0, 5}, [?CHILD(epmdpxy_session, epmdpxy_session, worker, [])]}}. Internal functions
e627ffe44526548d8844f7b53d6cd4581f559e04e89162946efeb1b37b757b33
ocaml-multicore/tezos
test_baking.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) (** Testing ------- Component: Protocol (baking) Invocation: dune exec src/proto_alpha/lib_protocol/test/main.exe -- test "^baking$" Subject: Rewards and bakers. Tests based on RPCs. *) open Protocol open Alpha_context * Verify the level is correctly computed when the first cycle is passed and after baking a certain fixed number of blocks ( 10 for the moment ) . The result should be [ blocks_per_cycle + 10 ] where [ blocks_per_cycle ] comes from the constants of the selected protocol . IMPROVEMENTS : - Randomize the number of cycle . - Randomize the number of accounts created at the beginning - Randomize the blocks per cycle . - Randomize the number of blocks baked after the n cycles baked previously . passed and after baking a certain fixed number of blocks (10 for the moment). The result should be [blocks_per_cycle + 10] where [blocks_per_cycle] comes from the constants of the selected protocol. IMPROVEMENTS: - Randomize the number of cycle. - Randomize the number of accounts created at the beginning - Randomize the blocks per cycle. - Randomize the number of blocks baked after the n cycles baked previously. *) let test_cycle () = Context.init ~consensus_threshold:0 5 >>=? fun (b, _) -> Context.get_constants (B b) >>=? fun csts -> let blocks_per_cycle = csts.parametric.blocks_per_cycle in let pp fmt x = Format.fprintf fmt "%ld" x in Block.bake b >>=? fun b -> Block.bake_until_cycle_end b >>=? fun b -> Context.get_level (B b) >>?= fun curr_level -> Assert.equal ~loc:__LOC__ Int32.equal "not the right level" pp (Alpha_context.Raw_level.to_int32 curr_level) blocks_per_cycle >>=? fun () -> Context.get_level (B b) >>?= fun l -> Block.bake_n 10 b >>=? fun b -> Context.get_level (B b) >>?= fun curr_level -> Assert.equal ~loc:__LOC__ Int32.equal "not the right level" pp (Alpha_context.Raw_level.to_int32 curr_level) (Int32.add (Alpha_context.Raw_level.to_int32 l) 10l) let wrap et = et >>= fun e -> Lwt.return (Environment.wrap_tzresult e) (** Test baking [n] cycles in a raw works smoothly. *) let test_bake_n_cycles n () = let open Block in let policy = By_round 0 in Context.init ~consensus_threshold:0 1 >>=? fun (block, _contracts) -> Block.bake_until_n_cycle_end ~policy n block >>=? fun _block -> return () * Check that , after one or two voting periods , the voting power of a baker is updated according to the rewards it receives for baking the blocks in the voting periods . Note we consider only one baker . updated according to the rewards it receives for baking the blocks in the voting periods. Note we consider only one baker. *) let test_voting_power_cache () = let open Block in let policy = By_round 0 in Context.init ~consensus_threshold:0 1 >>=? fun (genesis, _contracts) -> Context.get_constants (B genesis) >>=? fun csts -> let blocks_per_voting_period = csts.parametric.blocks_per_voting_period in let blocks_per_voting_periods n = Int64.of_int (n * Int32.to_int blocks_per_voting_period) in Context.get_baking_reward_fixed_portion (B genesis) >>=? fun baking_reward -> let tokens_per_roll = csts.parametric.tokens_per_roll in let rolls_from_tez amount = Test_tez.(amount /! Tez.to_mutez tokens_per_roll) |> Tez.to_mutez |> Int64.to_int in Context.get_bakers (B genesis) >>=? fun bakers -> let baker = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd bakers in Context.Delegate.full_balance (B genesis) baker >>=? fun full_balance -> let assert_voting_power n block = Context.get_voting_power (B block) baker >>=? fun voting_power -> Assert.equal_int ~loc:__LOC__ n (Int32.to_int voting_power) in (* the voting power is the number of rolls *) let initial_voting_power_at_genesis = rolls_from_tez full_balance in assert_voting_power initial_voting_power_at_genesis genesis >>=? fun () -> let rewards_after_one_voting_period = Test_tez.(baking_reward *! blocks_per_voting_periods 1) in let expected_delta_voting_power_after_one_voting_period = rolls_from_tez rewards_after_one_voting_period in Block.bake_n ~policy (Int32.to_int blocks_per_voting_period) genesis >>=? fun block -> let expected_voting_power_after_one_voting_period = initial_voting_power_at_genesis + expected_delta_voting_power_after_one_voting_period in assert_voting_power expected_voting_power_after_one_voting_period block >>=? fun () -> let rewards_after_two_voting_periods = Test_tez.(baking_reward *! blocks_per_voting_periods 2) in let expected_delta_voting_power_after_two_voting_periods = rolls_from_tez rewards_after_two_voting_periods in Block.bake_n ~policy (Int32.to_int blocks_per_voting_period) block >>=? fun block -> let expected_voting_power_after_two_voting_periods = initial_voting_power_at_genesis + expected_delta_voting_power_after_two_voting_periods in assert_voting_power expected_voting_power_after_two_voting_periods block (** test that after baking, one gets the baking reward fixed portion. *) let test_basic_baking_reward () = Context.init ~consensus_threshold:0 1 >>=? fun (genesis, contracts) -> Block.bake genesis >>=? fun b -> let baker = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in Context.Contract.pkh baker >>=? fun baker_pkh -> Context.Contract.balance (B b) baker >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b) baker_pkh >>=? fun frozen_deposit -> Context.get_baking_reward_fixed_portion (B b) >>=? fun br -> let open Test_tez in let expected_initial_balance = bal +! frozen_deposit -! br in Assert.equal_tez ~loc:__LOC__ expected_initial_balance Account.default_initial_balance let get_contract_for_pkh contracts pkh = let rec find_contract = function | [] -> assert false | c :: t -> Context.Contract.pkh c >>=? fun c_pkh -> if Signature.Public_key_hash.equal c_pkh pkh then return c else find_contract t in find_contract contracts let get_baker_different_from_baker ctxt baker = Context.get_bakers ~filter:(fun x -> not (Signature.Public_key_hash.equal x.delegate baker)) ctxt >>=? fun bakers -> return (WithExceptions.Option.get ~loc:__LOC__ @@ List.hd bakers) * Test that - the block producer gets the bonus for including the endorsements ; - the payload producer gets the baking reward . The test checks this in two scenarios , in the first one the payload producer and the block producer are the same delegate , in the second one they are different . The first scenario is checked by first baking block [ b1 ] and then block [ b2 ] at round 0 containing a number of endorsements for [ b1 ] and the checking the balance of [ b2 ] 's baker . For the second scenario another block [ b2 ' ] is build on top of [ b1 ] by a different baker , using the same payload as [ b2 ] . - the block producer gets the bonus for including the endorsements; - the payload producer gets the baking reward. The test checks this in two scenarios, in the first one the payload producer and the block producer are the same delegate, in the second one they are different. The first scenario is checked by first baking block [b1] and then block [b2] at round 0 containing a number of endorsements for [b1] and the checking the balance of [b2]'s baker. For the second scenario another block [b2'] is build on top of [b1] by a different baker, using the same payload as [b2]. *) let test_rewards_block_and_payload_producer () = Context.init ~consensus_threshold:1 10 >>=? fun (genesis, contracts) -> Context.get_baker (B genesis) ~round:0 >>=? fun baker_b1 -> get_contract_for_pkh contracts baker_b1 >>=? fun baker_b1_contract -> Block.bake ~policy:(By_round 0) genesis >>=? fun b1 -> Context.get_endorsers (B b1) >>=? fun endorsers -> List.map_es (function | {Plugin.RPC.Validators.delegate; slots; _} -> return (delegate, slots)) endorsers >>=? fun endorsers -> We let just a part of the endorsers vote ; we assume here that 5 of 10 endorsers will have together at least one slot ( to pass the threshold ) , but not all slots ( to make the test more interesting , otherwise we know the total endorsing power ) . endorsers will have together at least one slot (to pass the threshold), but not all slots (to make the test more interesting, otherwise we know the total endorsing power). *) let endorsers = List.take_n 5 endorsers in List.map_ep (fun endorser -> Op.endorsement ~delegate:endorser ~endorsed_block:b1 (B genesis) () >|=? Operation.pack) endorsers >>=? fun endos -> let endorsing_power = List.fold_left (fun acc (_pkh, slots) -> acc + List.length slots) 0 endorsers in let fee = Tez.one in Op.transaction (B b1) ~fee baker_b1_contract baker_b1_contract Tez.zero >>=? fun tx -> Block.bake ~policy:(By_round 0) ~operations:(tx :: endos) b1 >>=? fun b2 -> Context.get_baker (B b1) ~round:0 >>=? fun baker_b2 -> get_contract_for_pkh contracts baker_b2 >>=? fun baker_b2_contract -> Context.Contract.balance (B b2) baker_b2_contract >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b2) baker_b2 >>=? fun frozen_deposit -> Context.get_baking_reward_fixed_portion (B b2) >>=? fun baking_reward -> Context.get_bonus_reward (B b2) ~endorsing_power >>=? fun bonus_reward -> (if Signature.Public_key_hash.equal baker_b2 baker_b1 then Context.get_baking_reward_fixed_portion (B b1) else return Tez.zero) >>=? fun reward_for_b1 -> we are in the first scenario where the payload producer is the same as the block producer , in our case , [ baker_b2 ] . [ baker_b2 ] gets the baking reward plus the fee for the transaction [ tx ] . block producer, in our case, [baker_b2]. [baker_b2] gets the baking reward plus the fee for the transaction [tx]. *) let expected_balance = let open Test_tez in Account.default_initial_balance -! frozen_deposit +! baking_reward +! bonus_reward +! reward_for_b1 +! fee in Assert.equal_tez ~loc:__LOC__ bal expected_balance >>=? fun () -> Some new baker [ baker_b2 ' ] bakes b2 ' at the first round which does not correspond to a slot of [ baker_b2 ] and it includes the PQC for [ b2 ] . We check that the fixed baking reward goes to the payload producer [ baker_b2 ] , while the bonus goes to the the block producer ( aka baker ) [ baker_b2 ' ] . correspond to a slot of [baker_b2] and it includes the PQC for [b2]. We check that the fixed baking reward goes to the payload producer [baker_b2], while the bonus goes to the the block producer (aka baker) [baker_b2']. *) Context.get_endorsers (B b2) >>=? fun endorsers -> List.map_es (function | {Plugin.RPC.Validators.delegate; slots; _} -> return (delegate, slots)) endorsers >>=? fun preendorsers -> List.map_ep (fun endorser -> Op.preendorsement ~delegate:endorser ~endorsed_block:b2 (B b1) () >|=? Operation.pack) preendorsers >>=? fun preendos -> Context.get_baker (B b1) ~round:0 >>=? fun baker_b2 -> get_baker_different_from_baker (B b1) baker_b2 >>=? fun baker_b2' -> Block.bake ~payload_round:(Some Round.zero) ~locked_round:(Some Round.zero) ~policy:(By_account baker_b2') ~operations:(tx :: preendos @ endos) b1 >>=? fun b2' -> (* [baker_b2], as payload producer, gets the block reward and the fees *) Context.Contract.balance (B b2') baker_b2_contract >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b2') baker_b2 >>=? fun frozen_deposit -> let reward_for_b1 = if Signature.Public_key_hash.equal baker_b2 baker_b1 then baking_reward else Tez.zero in let expected_balance = let open Test_tez in Account.default_initial_balance +! baking_reward -! frozen_deposit +! reward_for_b1 +! fee in Assert.equal_tez ~loc:__LOC__ bal expected_balance >>=? fun () -> (* [baker_b2'] gets the bonus because he is the one who included the endorsements *) get_contract_for_pkh contracts baker_b2' >>=? fun baker_b2'_contract -> Context.Contract.balance (B b2') baker_b2'_contract >>=? fun bal' -> Context.Delegate.current_frozen_deposits (B b2') baker_b2' >>=? fun frozen_deposits' -> Context.get_baker (B genesis) ~round:0 >>=? fun baker_b1 -> let reward_for_b1' = if Signature.Public_key_hash.equal baker_b2' baker_b1 then baking_reward else Tez.zero in let expected_balance' = let open Test_tez in Account.default_initial_balance +! bonus_reward +! reward_for_b1' -! frozen_deposits' in Assert.equal_tez ~loc:__LOC__ bal' expected_balance' (** We test that: - a delegate that has active stake can bake; - a delegate that has no active stake cannot bake. *) let test_enough_active_stake_to_bake ~has_active_stake () = Context.init 1 >>=? fun (b_for_constants, _) -> Context.get_constants (B b_for_constants) >>=? fun Constants.{parametric = {tokens_per_roll; _}; _} -> let tpr = Tez.to_mutez tokens_per_roll in (* N.B. setting the balance has an impact on the active stake; without delegation, the full balance is the same as the staking balance and the active balance is less or equal the staking balance (see [Delegate_storage.select_distribution_for_cycle]). *) let initial_bal1 = if has_active_stake then tpr else Int64.sub tpr 1L in Context.init ~initial_balances:[initial_bal1; tpr] ~consensus_threshold:0 2 >>=? fun (b0, accounts) -> let (account1, _account2) = match accounts with a1 :: a2 :: _ -> (a1, a2) | _ -> assert false in Context.Contract.pkh account1 >>=? fun pkh1 -> Context.get_constants (B b0) >>=? fun Constants.{parametric = {baking_reward_fixed_portion; _}; _} -> Block.bake ~policy:(By_account pkh1) b0 >>= fun b1 -> if has_active_stake then b1 >>?= fun b1 -> Context.Contract.balance (B b1) account1 >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b1) pkh1 >>=? fun frozen_deposit -> let expected_bal = Test_tez.( Tez.of_mutez_exn initial_bal1 -! frozen_deposit +! baking_reward_fixed_portion) in Assert.equal_tez ~loc:__LOC__ bal expected_bal else (* pkh1 has less than tokens_per_roll so it will have no slots, thus it cannot be a proposer, thus it cannot bake. Precisely, bake fails because get_next_baker_by_account fails with "No slots found for pkh1" *) Assert.error ~loc:__LOC__ b1 (fun _ -> true) let test_committee_sampling () = let test_distribution max_round distribution = let (initial_balances, bounds) = List.split distribution in let accounts = Account.generate_accounts ~initial_balances (List.length initial_balances) in let bootstrap_accounts = List.map (fun (acc, tez) -> Default_parameters.make_bootstrap_account (acc.Account.pkh, acc.Account.pk, tez)) accounts in let constants = { Default_parameters.constants_test with consensus_committee_size = max_round; consensus_threshold = 0; } in let parameters = Default_parameters.parameters_of_constants ~bootstrap_accounts constants in Block.genesis_with_parameters parameters >>=? fun genesis -> Plugin.RPC.Baking_rights.get Block.rpc_ctxt ~all:true ~max_round genesis >|=? fun bakers -> let stats = Stdlib.Hashtbl.create 10 in Stdlib.List.iter2 (fun (acc, _) bounds -> Stdlib.Hashtbl.add stats acc.Account.pkh (bounds, 0)) accounts bounds ; List.iter (fun {Plugin.RPC.Baking_rights.delegate = pkh; _} -> let (bounds, n) = Stdlib.Hashtbl.find stats pkh in Stdlib.Hashtbl.replace stats pkh (bounds, n + 1)) bakers ; let one_failed = ref false in Format.eprintf "Testing with baker distribution [%a], committee size %d.@\n" (Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ",") (fun ppf (tez, _) -> Format.fprintf ppf "%Ld" tez)) distribution max_round ; Stdlib.Hashtbl.iter (fun pkh ((min_p, max_p), n) -> let failed = not (n >= min_p && n <= max_p) in Format.eprintf " - %s%a %d%s@." (if failed then "\027[1m" else "") Signature.Public_key_hash.pp pkh n (if failed then Format.asprintf " [FAIL]\027[0m should be \\in [%d,%d]" min_p max_p else "") ; if failed then one_failed := true) stats ; if !one_failed then Stdlib.failwith "The proportion of bakers marked as [FAILED] in the log output appear \ in the wrong proportion in the committee." else Format.eprintf "Test succesful.@\n" in (* The tests below are not deterministic, but the probability that they fail is infinitesimal. *) test_distribution 100_000 [ (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); ] >>=? fun () -> test_distribution 10_000 [ (16_000_000_000L, (4_600, 5_400)); (8_000_000_000L, (2_200, 2_800)); (8_000_000_000L, (2_200, 2_800)); ] >>=? fun () -> test_distribution 10_000 [(792_000_000_000L, (9_830, 9_970)); (8_000_000_000L, (40, 160))] let tests = [ Tztest.tztest "cycle" `Quick test_cycle; Tztest.tztest "test_bake_n_cycles for 12 cycles" `Quick (test_bake_n_cycles 12); Tztest.tztest "voting_power" `Quick test_voting_power_cache; Tztest.tztest "the fixed baking reward is given after a bake" `Quick test_basic_baking_reward; Tztest.tztest "test that the block producer gets the bonus while the payload producer \ gets the baking reward " `Quick test_rewards_block_and_payload_producer; Tztest.tztest "test that a delegate with 8000 tez can bake" `Quick (test_enough_active_stake_to_bake ~has_active_stake:true); Tztest.tztest "test that a delegate with 7999 tez cannot bake" `Quick (test_enough_active_stake_to_bake ~has_active_stake:false); Tztest.tztest "test committee sampling" `Quick test_committee_sampling; ]
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/test/test_baking.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Testing ------- Component: Protocol (baking) Invocation: dune exec src/proto_alpha/lib_protocol/test/main.exe -- test "^baking$" Subject: Rewards and bakers. Tests based on RPCs. * Test baking [n] cycles in a raw works smoothly. the voting power is the number of rolls * test that after baking, one gets the baking reward fixed portion. [baker_b2], as payload producer, gets the block reward and the fees [baker_b2'] gets the bonus because he is the one who included the endorsements * We test that: - a delegate that has active stake can bake; - a delegate that has no active stake cannot bake. N.B. setting the balance has an impact on the active stake; without delegation, the full balance is the same as the staking balance and the active balance is less or equal the staking balance (see [Delegate_storage.select_distribution_for_cycle]). pkh1 has less than tokens_per_roll so it will have no slots, thus it cannot be a proposer, thus it cannot bake. Precisely, bake fails because get_next_baker_by_account fails with "No slots found for pkh1" The tests below are not deterministic, but the probability that they fail is infinitesimal.
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol open Alpha_context * Verify the level is correctly computed when the first cycle is passed and after baking a certain fixed number of blocks ( 10 for the moment ) . The result should be [ blocks_per_cycle + 10 ] where [ blocks_per_cycle ] comes from the constants of the selected protocol . IMPROVEMENTS : - Randomize the number of cycle . - Randomize the number of accounts created at the beginning - Randomize the blocks per cycle . - Randomize the number of blocks baked after the n cycles baked previously . passed and after baking a certain fixed number of blocks (10 for the moment). The result should be [blocks_per_cycle + 10] where [blocks_per_cycle] comes from the constants of the selected protocol. IMPROVEMENTS: - Randomize the number of cycle. - Randomize the number of accounts created at the beginning - Randomize the blocks per cycle. - Randomize the number of blocks baked after the n cycles baked previously. *) let test_cycle () = Context.init ~consensus_threshold:0 5 >>=? fun (b, _) -> Context.get_constants (B b) >>=? fun csts -> let blocks_per_cycle = csts.parametric.blocks_per_cycle in let pp fmt x = Format.fprintf fmt "%ld" x in Block.bake b >>=? fun b -> Block.bake_until_cycle_end b >>=? fun b -> Context.get_level (B b) >>?= fun curr_level -> Assert.equal ~loc:__LOC__ Int32.equal "not the right level" pp (Alpha_context.Raw_level.to_int32 curr_level) blocks_per_cycle >>=? fun () -> Context.get_level (B b) >>?= fun l -> Block.bake_n 10 b >>=? fun b -> Context.get_level (B b) >>?= fun curr_level -> Assert.equal ~loc:__LOC__ Int32.equal "not the right level" pp (Alpha_context.Raw_level.to_int32 curr_level) (Int32.add (Alpha_context.Raw_level.to_int32 l) 10l) let wrap et = et >>= fun e -> Lwt.return (Environment.wrap_tzresult e) let test_bake_n_cycles n () = let open Block in let policy = By_round 0 in Context.init ~consensus_threshold:0 1 >>=? fun (block, _contracts) -> Block.bake_until_n_cycle_end ~policy n block >>=? fun _block -> return () * Check that , after one or two voting periods , the voting power of a baker is updated according to the rewards it receives for baking the blocks in the voting periods . Note we consider only one baker . updated according to the rewards it receives for baking the blocks in the voting periods. Note we consider only one baker. *) let test_voting_power_cache () = let open Block in let policy = By_round 0 in Context.init ~consensus_threshold:0 1 >>=? fun (genesis, _contracts) -> Context.get_constants (B genesis) >>=? fun csts -> let blocks_per_voting_period = csts.parametric.blocks_per_voting_period in let blocks_per_voting_periods n = Int64.of_int (n * Int32.to_int blocks_per_voting_period) in Context.get_baking_reward_fixed_portion (B genesis) >>=? fun baking_reward -> let tokens_per_roll = csts.parametric.tokens_per_roll in let rolls_from_tez amount = Test_tez.(amount /! Tez.to_mutez tokens_per_roll) |> Tez.to_mutez |> Int64.to_int in Context.get_bakers (B genesis) >>=? fun bakers -> let baker = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd bakers in Context.Delegate.full_balance (B genesis) baker >>=? fun full_balance -> let assert_voting_power n block = Context.get_voting_power (B block) baker >>=? fun voting_power -> Assert.equal_int ~loc:__LOC__ n (Int32.to_int voting_power) in let initial_voting_power_at_genesis = rolls_from_tez full_balance in assert_voting_power initial_voting_power_at_genesis genesis >>=? fun () -> let rewards_after_one_voting_period = Test_tez.(baking_reward *! blocks_per_voting_periods 1) in let expected_delta_voting_power_after_one_voting_period = rolls_from_tez rewards_after_one_voting_period in Block.bake_n ~policy (Int32.to_int blocks_per_voting_period) genesis >>=? fun block -> let expected_voting_power_after_one_voting_period = initial_voting_power_at_genesis + expected_delta_voting_power_after_one_voting_period in assert_voting_power expected_voting_power_after_one_voting_period block >>=? fun () -> let rewards_after_two_voting_periods = Test_tez.(baking_reward *! blocks_per_voting_periods 2) in let expected_delta_voting_power_after_two_voting_periods = rolls_from_tez rewards_after_two_voting_periods in Block.bake_n ~policy (Int32.to_int blocks_per_voting_period) block >>=? fun block -> let expected_voting_power_after_two_voting_periods = initial_voting_power_at_genesis + expected_delta_voting_power_after_two_voting_periods in assert_voting_power expected_voting_power_after_two_voting_periods block let test_basic_baking_reward () = Context.init ~consensus_threshold:0 1 >>=? fun (genesis, contracts) -> Block.bake genesis >>=? fun b -> let baker = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in Context.Contract.pkh baker >>=? fun baker_pkh -> Context.Contract.balance (B b) baker >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b) baker_pkh >>=? fun frozen_deposit -> Context.get_baking_reward_fixed_portion (B b) >>=? fun br -> let open Test_tez in let expected_initial_balance = bal +! frozen_deposit -! br in Assert.equal_tez ~loc:__LOC__ expected_initial_balance Account.default_initial_balance let get_contract_for_pkh contracts pkh = let rec find_contract = function | [] -> assert false | c :: t -> Context.Contract.pkh c >>=? fun c_pkh -> if Signature.Public_key_hash.equal c_pkh pkh then return c else find_contract t in find_contract contracts let get_baker_different_from_baker ctxt baker = Context.get_bakers ~filter:(fun x -> not (Signature.Public_key_hash.equal x.delegate baker)) ctxt >>=? fun bakers -> return (WithExceptions.Option.get ~loc:__LOC__ @@ List.hd bakers) * Test that - the block producer gets the bonus for including the endorsements ; - the payload producer gets the baking reward . The test checks this in two scenarios , in the first one the payload producer and the block producer are the same delegate , in the second one they are different . The first scenario is checked by first baking block [ b1 ] and then block [ b2 ] at round 0 containing a number of endorsements for [ b1 ] and the checking the balance of [ b2 ] 's baker . For the second scenario another block [ b2 ' ] is build on top of [ b1 ] by a different baker , using the same payload as [ b2 ] . - the block producer gets the bonus for including the endorsements; - the payload producer gets the baking reward. The test checks this in two scenarios, in the first one the payload producer and the block producer are the same delegate, in the second one they are different. The first scenario is checked by first baking block [b1] and then block [b2] at round 0 containing a number of endorsements for [b1] and the checking the balance of [b2]'s baker. For the second scenario another block [b2'] is build on top of [b1] by a different baker, using the same payload as [b2]. *) let test_rewards_block_and_payload_producer () = Context.init ~consensus_threshold:1 10 >>=? fun (genesis, contracts) -> Context.get_baker (B genesis) ~round:0 >>=? fun baker_b1 -> get_contract_for_pkh contracts baker_b1 >>=? fun baker_b1_contract -> Block.bake ~policy:(By_round 0) genesis >>=? fun b1 -> Context.get_endorsers (B b1) >>=? fun endorsers -> List.map_es (function | {Plugin.RPC.Validators.delegate; slots; _} -> return (delegate, slots)) endorsers >>=? fun endorsers -> We let just a part of the endorsers vote ; we assume here that 5 of 10 endorsers will have together at least one slot ( to pass the threshold ) , but not all slots ( to make the test more interesting , otherwise we know the total endorsing power ) . endorsers will have together at least one slot (to pass the threshold), but not all slots (to make the test more interesting, otherwise we know the total endorsing power). *) let endorsers = List.take_n 5 endorsers in List.map_ep (fun endorser -> Op.endorsement ~delegate:endorser ~endorsed_block:b1 (B genesis) () >|=? Operation.pack) endorsers >>=? fun endos -> let endorsing_power = List.fold_left (fun acc (_pkh, slots) -> acc + List.length slots) 0 endorsers in let fee = Tez.one in Op.transaction (B b1) ~fee baker_b1_contract baker_b1_contract Tez.zero >>=? fun tx -> Block.bake ~policy:(By_round 0) ~operations:(tx :: endos) b1 >>=? fun b2 -> Context.get_baker (B b1) ~round:0 >>=? fun baker_b2 -> get_contract_for_pkh contracts baker_b2 >>=? fun baker_b2_contract -> Context.Contract.balance (B b2) baker_b2_contract >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b2) baker_b2 >>=? fun frozen_deposit -> Context.get_baking_reward_fixed_portion (B b2) >>=? fun baking_reward -> Context.get_bonus_reward (B b2) ~endorsing_power >>=? fun bonus_reward -> (if Signature.Public_key_hash.equal baker_b2 baker_b1 then Context.get_baking_reward_fixed_portion (B b1) else return Tez.zero) >>=? fun reward_for_b1 -> we are in the first scenario where the payload producer is the same as the block producer , in our case , [ baker_b2 ] . [ baker_b2 ] gets the baking reward plus the fee for the transaction [ tx ] . block producer, in our case, [baker_b2]. [baker_b2] gets the baking reward plus the fee for the transaction [tx]. *) let expected_balance = let open Test_tez in Account.default_initial_balance -! frozen_deposit +! baking_reward +! bonus_reward +! reward_for_b1 +! fee in Assert.equal_tez ~loc:__LOC__ bal expected_balance >>=? fun () -> Some new baker [ baker_b2 ' ] bakes b2 ' at the first round which does not correspond to a slot of [ baker_b2 ] and it includes the PQC for [ b2 ] . We check that the fixed baking reward goes to the payload producer [ baker_b2 ] , while the bonus goes to the the block producer ( aka baker ) [ baker_b2 ' ] . correspond to a slot of [baker_b2] and it includes the PQC for [b2]. We check that the fixed baking reward goes to the payload producer [baker_b2], while the bonus goes to the the block producer (aka baker) [baker_b2']. *) Context.get_endorsers (B b2) >>=? fun endorsers -> List.map_es (function | {Plugin.RPC.Validators.delegate; slots; _} -> return (delegate, slots)) endorsers >>=? fun preendorsers -> List.map_ep (fun endorser -> Op.preendorsement ~delegate:endorser ~endorsed_block:b2 (B b1) () >|=? Operation.pack) preendorsers >>=? fun preendos -> Context.get_baker (B b1) ~round:0 >>=? fun baker_b2 -> get_baker_different_from_baker (B b1) baker_b2 >>=? fun baker_b2' -> Block.bake ~payload_round:(Some Round.zero) ~locked_round:(Some Round.zero) ~policy:(By_account baker_b2') ~operations:(tx :: preendos @ endos) b1 >>=? fun b2' -> Context.Contract.balance (B b2') baker_b2_contract >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b2') baker_b2 >>=? fun frozen_deposit -> let reward_for_b1 = if Signature.Public_key_hash.equal baker_b2 baker_b1 then baking_reward else Tez.zero in let expected_balance = let open Test_tez in Account.default_initial_balance +! baking_reward -! frozen_deposit +! reward_for_b1 +! fee in Assert.equal_tez ~loc:__LOC__ bal expected_balance >>=? fun () -> get_contract_for_pkh contracts baker_b2' >>=? fun baker_b2'_contract -> Context.Contract.balance (B b2') baker_b2'_contract >>=? fun bal' -> Context.Delegate.current_frozen_deposits (B b2') baker_b2' >>=? fun frozen_deposits' -> Context.get_baker (B genesis) ~round:0 >>=? fun baker_b1 -> let reward_for_b1' = if Signature.Public_key_hash.equal baker_b2' baker_b1 then baking_reward else Tez.zero in let expected_balance' = let open Test_tez in Account.default_initial_balance +! bonus_reward +! reward_for_b1' -! frozen_deposits' in Assert.equal_tez ~loc:__LOC__ bal' expected_balance' let test_enough_active_stake_to_bake ~has_active_stake () = Context.init 1 >>=? fun (b_for_constants, _) -> Context.get_constants (B b_for_constants) >>=? fun Constants.{parametric = {tokens_per_roll; _}; _} -> let tpr = Tez.to_mutez tokens_per_roll in let initial_bal1 = if has_active_stake then tpr else Int64.sub tpr 1L in Context.init ~initial_balances:[initial_bal1; tpr] ~consensus_threshold:0 2 >>=? fun (b0, accounts) -> let (account1, _account2) = match accounts with a1 :: a2 :: _ -> (a1, a2) | _ -> assert false in Context.Contract.pkh account1 >>=? fun pkh1 -> Context.get_constants (B b0) >>=? fun Constants.{parametric = {baking_reward_fixed_portion; _}; _} -> Block.bake ~policy:(By_account pkh1) b0 >>= fun b1 -> if has_active_stake then b1 >>?= fun b1 -> Context.Contract.balance (B b1) account1 >>=? fun bal -> Context.Delegate.current_frozen_deposits (B b1) pkh1 >>=? fun frozen_deposit -> let expected_bal = Test_tez.( Tez.of_mutez_exn initial_bal1 -! frozen_deposit +! baking_reward_fixed_portion) in Assert.equal_tez ~loc:__LOC__ bal expected_bal else Assert.error ~loc:__LOC__ b1 (fun _ -> true) let test_committee_sampling () = let test_distribution max_round distribution = let (initial_balances, bounds) = List.split distribution in let accounts = Account.generate_accounts ~initial_balances (List.length initial_balances) in let bootstrap_accounts = List.map (fun (acc, tez) -> Default_parameters.make_bootstrap_account (acc.Account.pkh, acc.Account.pk, tez)) accounts in let constants = { Default_parameters.constants_test with consensus_committee_size = max_round; consensus_threshold = 0; } in let parameters = Default_parameters.parameters_of_constants ~bootstrap_accounts constants in Block.genesis_with_parameters parameters >>=? fun genesis -> Plugin.RPC.Baking_rights.get Block.rpc_ctxt ~all:true ~max_round genesis >|=? fun bakers -> let stats = Stdlib.Hashtbl.create 10 in Stdlib.List.iter2 (fun (acc, _) bounds -> Stdlib.Hashtbl.add stats acc.Account.pkh (bounds, 0)) accounts bounds ; List.iter (fun {Plugin.RPC.Baking_rights.delegate = pkh; _} -> let (bounds, n) = Stdlib.Hashtbl.find stats pkh in Stdlib.Hashtbl.replace stats pkh (bounds, n + 1)) bakers ; let one_failed = ref false in Format.eprintf "Testing with baker distribution [%a], committee size %d.@\n" (Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ",") (fun ppf (tez, _) -> Format.fprintf ppf "%Ld" tez)) distribution max_round ; Stdlib.Hashtbl.iter (fun pkh ((min_p, max_p), n) -> let failed = not (n >= min_p && n <= max_p) in Format.eprintf " - %s%a %d%s@." (if failed then "\027[1m" else "") Signature.Public_key_hash.pp pkh n (if failed then Format.asprintf " [FAIL]\027[0m should be \\in [%d,%d]" min_p max_p else "") ; if failed then one_failed := true) stats ; if !one_failed then Stdlib.failwith "The proportion of bakers marked as [FAILED] in the log output appear \ in the wrong proportion in the committee." else Format.eprintf "Test succesful.@\n" in test_distribution 100_000 [ (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); (8_000_000_000L, (9_400, 10_600)); ] >>=? fun () -> test_distribution 10_000 [ (16_000_000_000L, (4_600, 5_400)); (8_000_000_000L, (2_200, 2_800)); (8_000_000_000L, (2_200, 2_800)); ] >>=? fun () -> test_distribution 10_000 [(792_000_000_000L, (9_830, 9_970)); (8_000_000_000L, (40, 160))] let tests = [ Tztest.tztest "cycle" `Quick test_cycle; Tztest.tztest "test_bake_n_cycles for 12 cycles" `Quick (test_bake_n_cycles 12); Tztest.tztest "voting_power" `Quick test_voting_power_cache; Tztest.tztest "the fixed baking reward is given after a bake" `Quick test_basic_baking_reward; Tztest.tztest "test that the block producer gets the bonus while the payload producer \ gets the baking reward " `Quick test_rewards_block_and_payload_producer; Tztest.tztest "test that a delegate with 8000 tez can bake" `Quick (test_enough_active_stake_to_bake ~has_active_stake:true); Tztest.tztest "test that a delegate with 7999 tez cannot bake" `Quick (test_enough_active_stake_to_bake ~has_active_stake:false); Tztest.tztest "test committee sampling" `Quick test_committee_sampling; ]